Skip to content

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

Python

Release v0.5.9: Collaboration, voice profiles, and major architectural improvements

Murtaza Nasira4165584bb16
diff --git a/README.md b/README.md
index 5a91f1ca..dfaf840d 100644
--- a/README.md
+++ b/README.md
@@ -9,6 +9,7 @@
<a href="https://www.gnu.org/licenses/agpl-3.0"><img alt="AGPL v3" src="https://img.shields.io/badge/License-AGPL_v3-blue.svg"></a>
<a href="https://github.com/murtaza-nasir/speakr/actions/workflows/docker-publish.yml"><img alt="Docker Build" src="https://github.com/murtaza-nasir/speakr/actions/workflows/docker-publish.yml/badge.svg"></a>
<a href="https://hub.docker.com/r/learnedmachine/speakr"><img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/learnedmachine/speakr"></a>
+ <a href="https://github.com/murtaza-nasir/speakr/releases/latest"><img alt="Latest Version" src="https://img.shields.io/badge/version-0.5.9-brightgreen.svg"></a>
</p>
<p align="center">
@@ -23,23 +24,78 @@
## Overview
-Speakr transforms your audio recordings into organized, searchable, and intelligent notes. Built for privacy-conscious teams and individuals, it runs entirely on your own infrastructure, ensuring your sensitive conversations remain completely private.
+Speakr transforms your audio recordings into organized, searchable, and intelligent notes. Built for privacy-conscious groups and individuals, it runs entirely on your own infrastructure, ensuring your sensitive conversations remain completely private.
<div align="center">
- <img src="docs/assets/images/screenshots/Filters.png" alt="Speakr Main Interface" width="750"/>
+ <img src="docs/assets/images/screenshots/Main view.png" alt="Speakr Main Interface" width="750"/>
</div>
## Key Features
+### Core Functionality
- **Smart Recording & Upload** - Record directly in browser or upload existing audio files
- **AI Transcription** - High-accuracy transcription with speaker identification
+- **Voice Profiles** - AI-powered speaker recognition with voice embeddings (requires WhisperX ASR service)
+- **Audio-Transcript Sync** - Click transcript to jump to audio, auto-highlight current text, follow mode for hands-free playback
- **Interactive Chat** - Ask questions about your recordings and get AI-powered answers
- **Inquire Mode** - Semantic search across all recordings using natural language
- **Internationalization** - Full support for English, Spanish, French, German, and Chinese
-- **Smart Tagging** - Organize with tags that include custom AI prompts
-- **Secure Sharing** - Generate secure links to share recordings
- **Beautiful Themes** - Light and dark modes with customizable color schemes
+### Collaboration & Sharing
+- **Internal Sharing** - Share recordings with specific users with granular permissions (view/edit/reshare)
+- **Group Management** - Create groups with automatic sharing via group-scoped tags
+- **Public Sharing** - Generate secure links to share recordings externally (admin-controlled)
+- **Group Tags** - Tags that automatically share recordings with all group members
+
+### Organization & Management
+- **Smart Tagging** - Organize with tags that include custom AI prompts and ASR settings
+- **Tag Prompt Stacking** - Combine multiple tags to layer AI instructions for powerful transformations
+- **Tag Protection** - Prevent specific recordings from being auto-deleted
+- **Group Retention Policies** - Set custom retention periods per group tag
+- **Auto-Deletion** - Automatic cleanup of old recordings with flexible retention policies
+
+## Real-World Use Cases
+
+Different people use Speakr's collaboration and retention features in different ways:
+
+| Use Case | Setup | What It Does |
+|----------|-------|-------------|
+| **Family memories** | Create "Family" group with protected tag | Everyone gets access to trips and events automatically, recordings preserved forever |
+| **Book club discussions** | "Book Club" group, tag monthly meetings | All members auto-share discussions, can add personal notes about what resonated |
+| **Work project group** | Share individually with 3 teammates | Temporary collaboration, easy to revoke when project ends |
+| **Daily group standups** | Group tag with 14-day retention | Auto-share with group, auto-cleanup of routine meetings |
+| **Architecture decisions** | Engineering group tag, protected from deletion | Technical discussions automatically shared, preserved permanently as reference |
+| **Client consultations** | Individual share with view-only permission | Controlled external access, clients can't accidentally edit |
+| **Research interviews** | Protected tag + Obsidian export | Preserve recordings indefinitely, transcripts auto-import to note-taking system |
+| **Legal consultations** | Group tag with 7-year retention | Automatic sharing with legal group, compliance-based retention |
+| **Sales calls** | Group tag with 1-year retention | Whole sales group learns from each call, cleanup after sales cycle |
+
+### Creative Tag Prompt Examples
+
+Tags with custom prompts transform raw recordings into exactly what you need:
+
+- **Recipe recordings**: Record yourself cooking while narrating - tag with "Recipe" to convert messy speech into formatted recipes with ingredient lists and numbered steps
+- **Lecture notes**: Students tag lectures with "Study Notes" to get organized outlines with concepts, examples, and definitions instead of raw transcripts
+- **Code reviews**: "Code Review" tag extracts issues, suggested changes, and action items in technical language developers can use directly
+- **Meeting summaries**: "Action Items" tag ignores discussion and returns just decisions, tasks, and deadlines
+
+### Tag Stacking for Combined Effects
+
+Stack multiple tags to layer instructions:
+- "Recipe" + "Gluten Free" = Formatted recipe with gluten substitution suggestions
+- "Lecture" + "Biology 301" = Study notes format focused on biological terminology
+- "Client Meeting" + "Legal Review" = Client requirements plus legal implications highlighted
+
+The order can matter - start with format tags, then add focus tags for best results.
+
+### Integration Examples
+
+- **Obsidian/Logseq**: Enable auto-export to write completed transcripts directly to your vault using your custom template - no manual export needed
+- **Documentation wikis**: Map auto-export to your wiki's import folder for seamless transcript publishing
+- **Content creation**: Create SRT subtitle templates from your audio recordings for podcasts or video content
+- **Project management**: Extract action items with custom tag prompts, then auto-export for automated task creation
+
## Quick Start
### Using Docker (Recommended)
@@ -48,13 +104,18 @@ Speakr transforms your audio recordings into organized, searchable, and intellig
# Create project directory
mkdir speakr && cd speakr
-# Download configuration (choose one):
+# Download docker-compose configuration:
wget https://raw.githubusercontent.com/murtaza-nasir/speakr/master/config/docker-compose.example.yml -O docker-compose.yml
-# For OpenAI or similar Whisper API:
+# Choose your transcription method and download the corresponding .env file:
+
+# Option 1: Standard Whisper API (no speaker diarization):
wget https://raw.githubusercontent.com/murtaza-nasir/speakr/master/config/env.whisper.example -O .env
-# OR for ASR with speaker diarization (requires additional container):
+# Option 2: WhisperX ASR with voice profiles (recommended for speaker features):
+wget https://raw.githubusercontent.com/murtaza-nasir/speakr/master/config/env.whisperx.example -O .env
+
+# Option 3: Basic ASR with diarization (no voice profiles):
wget https://raw.githubusercontent.com/murtaza-nasir/speakr/master/config/env.asr.example -O .env
# Configure your service endpoints and API keys
@@ -66,7 +127,11 @@ docker compose up -d
# Access at http://localhost:8899
```
-**Note:** ASR option requires running `onerahmet/openai-whisper-asr-webservice` container alongside Speakr. See [installation guide](https://murtaza-nasir.github.io/speakr/getting-started/installation#running-asr-service-for-speaker-diarization) for complete setup.
+**Note:** ASR option requires running an additional ASR service container alongside Speakr:
+- **For voice profiles & speaker embeddings:** Use [WhisperX ASR Service](https://github.com/murtaza-nasir/whisperx-asr-service) (recommended)
+- **For basic speaker diarization:** Use [OpenAI Whisper ASR Webservice](https://github.com/ahmetoner/whisper-asr-webservice)
+
+See [installation guide](https://murtaza-nasir.github.io/speakr/getting-started/installation#running-asr-service-for-speaker-diarization) for complete setup instructions.
**[View Full Installation Guide →](https://murtaza-nasir.github.io/speakr/getting-started)**
@@ -80,38 +145,64 @@ Complete documentation is available at **[murtaza-nasir.github.io/speakr](https:
- [Troubleshooting](https://murtaza-nasir.github.io/speakr/troubleshooting) - Common issues and solutions
- [FAQ](https://murtaza-nasir.github.io/speakr/faq) - Frequently asked questions
-## Latest Release (v0.5.8)
+## Latest Release (v0.5.9)
+
+> **⚠️ IMPORTANT - Major Release Warning:**
+>
+> This is a **major release** with significant architectural changes and new features. Before upgrading:
+>
+> - **BACKUP YOUR DATA** - Database schema changes require migration
+> - **Review new environment variables** - Many features require `.env` configuration
+> - **Test in development first** - Major refactoring may affect existing workflows
+>
+> **Required Environment Variables for New Features:**
+> - `ENABLE_INTERNAL_SHARING` - User-to-user sharing (default: false)
+> - `SHOW_USERNAMES_IN_UI` - Username visibility control (default: false)
+> - `USERS_CAN_DELETE` - Deletion permissions (default: true)
+> - `ENABLE_AUTO_DELETION` - Retention system (default: false)
+> - `GLOBAL_RETENTION_DAYS` - Retention period (default: 0)
+> - `ENABLE_AUTO_EXPORT` - Automated markdown export (default: false)
+> - `ENABLE_PUBLIC_SHARING` - Public share links (default: true)
+>
+> See [configuration guide](https://murtaza-nasir.github.io/speakr/getting-started/installation#configuration-updates) for complete setup instructions.
### Highlights
+- **Complete Internal Sharing System** - Share recordings with users with granular permissions (view/edit/reshare)
+- **Group Management & Collaboration** - Create groups with auto-sharing via group tags and custom retention policies
+- **Speaker Voice Profiles** - AI-powered speaker identification with 256-dimensional voice embeddings
+- **Audio-Transcript Synchronization** - Click-to-jump, auto-highlight, and follow mode for interactive navigation
+- **Auto-Deletion & Retention System** - Flexible retention policies with global and group-level controls
+- **Automated Export** - Auto-export transcriptions to markdown for Obsidian, Logseq, and other note-taking apps
+- **Permission System** - Fine-grained access control throughout the application
+- **Modular Architecture** - Backend refactored into blueprints, frontend composables for maintainability
+- **UI/UX Enhancements** - Compact controls, inline editing, unified toast notifications, improved badges
+- **Enhanced Internationalization** - 29 new tooltip translations across all supported languages
+
+### Previous Release (v0.5.8)
- **Inline Transcript Editing** - Edit speaker assignments and text directly within the speaker identification modal
- **Add Speaker Functionality** - Dynamically add new speakers during transcript review
- **Enhanced Speaker Modal** - Improved UX with hover-based edit controls and real-time updates
-### Previous Release (v0.5.7)
-- GPT-5 Model Support with automatic detection
-- Custom Prompt Selection for summary reprocessing
-- PWA Enhancements and mobile recording improvements
-
## Screenshots
<table align="center" border="0">
<tr>
<td align="center">
- <img src="docs/assets/images/screenshots/Filters.png" alt="Main Dashboard" width="400"/>
- <br><em>Advanced Filtering Dashboard</em>
+ <img src="docs/assets/images/screenshots/Main view.png" alt="Main Dashboard" width="400"/>
+ <br><em>Main Dashboard with Chat</em>
</td>
<td align="center">
- <img src="docs/assets/images/screenshots/inquire mode.png" alt="Inquire Mode" width="400"/>
+ <img src="docs/assets/images/screenshots/Inquire mode.png" alt="Inquire Mode" width="400"/>
<br><em>AI-Powered Semantic Search</em>
</td>
</tr>
<tr>
<td align="center">
- <img src="docs/assets/images/screenshots/recording view with simple transcription view and chat visible.png" alt="Transcription with Chat" width="400"/>
+ <img src="docs/assets/images/screenshots/chat-interface.png" alt="Transcription with Chat" width="400"/>
<br><em>Interactive Transcription & Chat</em>
</td>
<td align="center">
- <img src="docs/assets/images/screenshots/Multilingual.png" alt="Multi-language Support" width="400"/>
+ <img src="docs/assets/images/screenshots/multilingual-chinese.png" alt="Multi-language Support" width="400"/>
<br><em>Full Internationalization</em>
</td>
</tr>
@@ -136,7 +227,7 @@ Complete documentation is available at **[murtaza-nasir.github.io/speakr](https:
### Mid-term
- Plugin system for custom integrations
-- Team workspaces with shared recordings
+- Group workspaces with shared recordings
- Automated workflow triggers
### Long-term
diff --git a/VERSION b/VERSION
index 1b0ae03b..5734d3a4 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-v0.5.8
+v0.5.9
diff --git a/config/docker-compose.example.yml b/config/docker-compose.example.yml
index 1533f0aa..d2ac8b03 100644
--- a/config/docker-compose.example.yml
+++ b/config/docker-compose.example.yml
@@ -5,21 +5,29 @@ services:
restart: unless-stopped
ports:
- "8899:8899"
-
+
# --- Configuration ---
# Environment variables are loaded from the .env file.
#
# To get started:
- # 1. Choose your desired transcription method.
- # 2. Copy the corresponding example file to .env:
+ # 1. Copy this file to your project root:
+ # cp config/docker-compose.example.yml docker-compose.yml
+ #
+ # 2. Choose your transcription method and copy the corresponding .env file:
#
- # For standard Whisper API:
+ # For standard Whisper API (no speaker diarization):
# cp config/env.whisper.example .env
#
- # For a custom ASR endpoint:
+ # For WhisperX ASR with voice profiles (recommended for speaker features):
+ # cp config/env.whisperx.example .env
+ #
+ # For basic ASR with diarization (no voice profiles):
# cp config/env.asr.example .env
#
# 3. Edit the .env file to add your API keys and settings.
+ #
+ # 4. Start Speakr:
+ # docker compose up -d
env_file:
- .env
@@ -36,8 +44,16 @@ services:
volumes:
- ./uploads:/data/uploads
- ./instance:/data/instance
+ # Optional: Uncomment if using auto-export feature (ENABLE_AUTO_EXPORT=true)
+ # - ./exports:/data/exports
+ # Optional: Uncomment if using auto-processing feature (ENABLE_AUTO_PROCESSING=true)
+ # - ./auto-process:/data/auto-process
# Option 2: Docker-managed volumes.
# volumes:
# - speakr-uploads:/data/uploads
# - speakr-instance:/data/instance
+ # # Optional: Uncomment if using auto-export feature
+ # # - speakr-exports:/data/exports
+ # # Optional: Uncomment if using auto-processing feature
+ # # - speakr-auto-process:/data/auto-process
diff --git a/config/env.asr.example b/config/env.asr.example
index 8edfffe6..2f47b551 100644
--- a/config/env.asr.example
+++ b/config/env.asr.example
@@ -78,6 +78,17 @@ ENABLE_INQUIRE_MODE=false
# Set to "true" to enable automated file processing
ENABLE_AUTO_PROCESSING=false
+# --- Automated Export Settings ---
+# Automatically export transcriptions and summaries to markdown files
+ENABLE_AUTO_EXPORT=false
+
+# Directory where exports will be saved (per-user subdirectories created automatically)
+AUTO_EXPORT_DIR=/data/exports
+
+# What to include in exports
+AUTO_EXPORT_TRANSCRIPTION=true
+AUTO_EXPORT_SUMMARY=true
+
# Processing mode: admin_only, user_directories, or single_user
AUTO_PROCESS_MODE=admin_only
@@ -90,6 +101,43 @@ AUTO_PROCESS_CHECK_INTERVAL=30
# Default username for single_user mode (only used if AUTO_PROCESS_MODE=single_user)
# AUTO_PROCESS_DEFAULT_USERNAME=admin
+# --- Auto-Deletion & Retention Settings ---
+# Enable automated deletion of old recordings
+ENABLE_AUTO_DELETION=false
+
+# Number of days to retain recordings (0 = disabled)
+# Example: 90 means recordings older than 90 days will be processed
+GLOBAL_RETENTION_DAYS=90
+
+# Deletion mode: 'audio_only' keeps transcription, 'full_recording' deletes everything
+# audio_only: Deletes audio file but keeps transcription/summary/notes (recommended)
+# full_recording: Permanently deletes the entire recording from database
+DELETION_MODE=audio_only
+
+# --- Permission-Based Deletion Controls ---
+# Allow all users to delete their recordings, or restrict to admins only
+# true: All users can delete their own recordings (default)
+# false: Only admins can delete recordings
+USERS_CAN_DELETE=true
+
+# --- Internal Sharing Settings ---
+# Enable user-to-user sharing of recordings (works independently of groups)
+ENABLE_INTERNAL_SHARING=false
+
+# Show usernames in the UI (when sharing/viewing shared recordings)
+# true: Display usernames throughout the interface
+# false: Hide usernames (users must know each other's usernames to share)
+SHOW_USERNAMES_IN_UI=false
+
+# --- Public Sharing Settings ---
+# Enable creation of public share links (anonymous access)
+# true: Users can create public links to share recordings externally (default)
+# false: Public sharing is disabled globally
+ENABLE_PUBLIC_SHARING=true
+
+# Note: Admins can control public sharing permissions per-user in the admin dashboard
+# even when ENABLE_PUBLIC_SHARING is true
+
# --- Docker Settings (rarely need to be changed) ---
SQLALCHEMY_DATABASE_URI=sqlite:////data/instance/transcriptions.db
UPLOAD_FOLDER=/data/uploads
diff --git a/config/env.whisper.example b/config/env.whisper.example
index 5fadf7b9..18ad9047 100644
--- a/config/env.whisper.example
+++ b/config/env.whisper.example
@@ -81,6 +81,17 @@ ENABLE_INQUIRE_MODE=false
# Set to "true" to enable automated file processing
ENABLE_AUTO_PROCESSING=false
+# --- Automated Export Settings ---
+# Automatically export transcriptions and summaries to markdown files
+ENABLE_AUTO_EXPORT=false
+
+# Directory where exports will be saved (per-user subdirectories created automatically)
+AUTO_EXPORT_DIR=/data/exports
+
+# What to include in exports
+AUTO_EXPORT_TRANSCRIPTION=true
+AUTO_EXPORT_SUMMARY=true
+
# Processing mode: admin_only, user_directories, or single_user
AUTO_PROCESS_MODE=admin_only
@@ -93,6 +104,43 @@ AUTO_PROCESS_CHECK_INTERVAL=30
# Default username for single_user mode (only used if AUTO_PROCESS_MODE=single_user)
# AUTO_PROCESS_DEFAULT_USERNAME=admin
+# --- Auto-Deletion & Retention Settings ---
+# Enable automated deletion of old recordings
+ENABLE_AUTO_DELETION=false
+
+# Number of days to retain recordings (0 = disabled)
+# Example: 90 means recordings older than 90 days will be processed
+GLOBAL_RETENTION_DAYS=90
+
+# Deletion mode: 'audio_only' keeps transcription, 'full_recording' deletes everything
+# audio_only: Deletes audio file but keeps transcription/summary/notes (recommended)
+# full_recording: Permanently deletes the entire recording from database
+DELETION_MODE=audio_only
+
+# --- Permission-Based Deletion Controls ---
+# Allow all users to delete their recordings, or restrict to admins only
+# true: All users can delete their own recordings (default)
+# false: Only admins can delete recordings
+USERS_CAN_DELETE=true
+
+# --- Internal Sharing Settings ---
+# Enable user-to-user sharing of recordings (works independently of groups)
+ENABLE_INTERNAL_SHARING=false
+
+# Show usernames in the UI (when sharing/viewing shared recordings)
+# true: Display usernames throughout the interface
+# false: Hide usernames (users must know each other's usernames to share)
+SHOW_USERNAMES_IN_UI=false
+
+# --- Public Sharing Settings ---
+# Enable creation of public share links (anonymous access)
+# true: Users can create public links to share recordings externally (default)
+# false: Public sharing is disabled globally
+ENABLE_PUBLIC_SHARING=true
+
+# Note: Admins can control public sharing permissions per-user in the admin dashboard
+# even when ENABLE_PUBLIC_SHARING is true
+
# --- Docker Settings (rarely need to be changed) ---
SQLALCHEMY_DATABASE_URI=sqlite:////data/instance/transcriptions.db
UPLOAD_FOLDER=/data/uploads
diff --git a/config/env.whisperx.example b/config/env.whisperx.example
new file mode 100644
index 00000000..ddf0f5e4
--- /dev/null
+++ b/config/env.whisperx.example
@@ -0,0 +1,153 @@
+# -----------------------------------------------------------------------------
+# Speakr Configuration: WhisperX ASR Endpoint (with Voice Profiles)
+#
+# This configuration is for use with the WhisperX ASR Service:
+# https://github.com/murtaza-nasir/whisperx-asr-service
+#
+# Features supported:
+# - Speaker diarization with pyannote/speaker-diarization-community-1
+# - Voice profile embeddings (256-dimensional) for speaker recognition
+# - Automatic speaker matching across recordings
+# - Better timestamp alignment between speakers and words
+#
+# Instructions:
+# 1. Copy this file to a new file named .env
+# cp config/env.whisperx.example .env
+# 2. Fill in the required URLs, API keys, and settings below.
+# 3. Set up WhisperX ASR Service (see installation guide)
+# -----------------------------------------------------------------------------
+
+# --- Text Generation Model (for summaries, titles, etc.) ---
+TEXT_MODEL_BASE_URL=https://openrouter.ai/api/v1
+TEXT_MODEL_API_KEY=your_openrouter_api_key
+TEXT_MODEL_NAME=openai/gpt-4o-mini
+
+# --- GPT-5 Specific Settings (only used with OpenAI API and GPT-5 models) ---
+# If using GPT-5 models (gpt-5, gpt-5-mini, gpt-5-nano, gpt-5-chat-latest) with OpenAI API,
+# these parameters will be used instead of temperature.
+#
+# Example GPT-5 configuration:
+# TEXT_MODEL_BASE_URL=https://api.openai.com/v1
+# TEXT_MODEL_NAME=gpt-5-mini
+#
+# Reasoning effort: minimal, low, medium, high (default: medium)
+# - minimal: Fastest responses, minimal reasoning tokens
+# - low: Fast responses with basic reasoning
+# - medium: Balanced reasoning and speed (recommended)
+# - high: Maximum reasoning for complex tasks
+GPT5_REASONING_EFFORT=medium
+#
+# Verbosity: low, medium, high (default: medium)
+# - low: Concise responses
+# - medium: Balanced detail
+# - high: Detailed explanations
+GPT5_VERBOSITY=medium
+
+# --- Transcription Service (WhisperX ASR Endpoint) ---
+# Setting this to true enables all ASR features including speaker diarization and voice profiles
+# Note: File chunking is NOT supported with ASR endpoints
+USE_ASR_ENDPOINT=true
+
+# WhisperX ASR Endpoint URL
+# For containers in same docker-compose: Use container name and internal port
+# Example: http://whisperx-asr:9000 (NOT the host port or external IP)
+# For external ASR: Use http://192.168.1.100:9000 or http://asr.example.com:9000
+ASR_BASE_URL=http://whisperx-asr:9000
+
+# Optional: Override default speaker settings (defaults shown)
+# These are automatically set when USE_ASR_ENDPOINT=true
+# ASR_DIARIZE=true # Auto-enabled with ASR (set to false to disable)
+# ASR_MIN_SPEAKERS=1 # Default minimum speakers
+# ASR_MAX_SPEAKERS=5 # Default maximum speakers
+
+# --- Application Settings ---
+# Set to "true" to allow user registration, "false" to disable
+ALLOW_REGISTRATION=false
+SUMMARY_MAX_TOKENS=8000
+CHAT_MAX_TOKENS=5000
+
+# Timezone for displaying dates and times in the UI
+# Use a valid TZ database name (e.g., "America/New_York", "Europe/London", "UTC")
+TIMEZONE="UTC"
+
+# Set the logging level for the application.
+# Options: DEBUG, INFO, WARNING, ERROR
+LOG_LEVEL="INFO"
+
+# --- Admin User (created on first run) ---
+ADMIN_USERNAME=admin
+ADMIN_PASSWORD=changeme
+
+# --- Inquire Mode (AI search across all recordings) ---
+# Set to "true" to enable semantic search and chat across all recordings
+# Requires additional dependencies (already included in Docker image)
+ENABLE_INQUIRE_MODE=false
+
+# --- Automated File Processing (Black Hole Directory) ---
+# Set to "true" to enable automated file processing
+ENABLE_AUTO_PROCESSING=false
+
+# --- Automated Export Settings ---
+# Automatically export transcriptions and summaries to markdown files
+ENABLE_AUTO_EXPORT=false
+
+# Directory where exports will be saved (per-user subdirectories created automatically)
+AUTO_EXPORT_DIR=/data/exports
+
+# What to include in exports
+AUTO_EXPORT_TRANSCRIPTION=true
+AUTO_EXPORT_SUMMARY=true
+
+# Processing mode: admin_only, user_directories, or single_user
+AUTO_PROCESS_MODE=admin_only
+
+# Directory to watch for new audio files
+AUTO_PROCESS_WATCH_DIR=/data/auto-process
+
+# How often to check for new files (seconds)
+AUTO_PROCESS_CHECK_INTERVAL=30
+
+# Default username for single_user mode (only used if AUTO_PROCESS_MODE=single_user)
+# AUTO_PROCESS_DEFAULT_USERNAME=admin
+
+# --- Auto-Deletion & Retention Settings ---
+# Enable automated deletion of old recordings
+ENABLE_AUTO_DELETION=false
+
+# Number of days to retain recordings (0 = disabled)
+# Example: 90 means recordings older than 90 days will be processed
+GLOBAL_RETENTION_DAYS=90
+
+# Deletion mode: 'audio_only' keeps transcription, 'full_recording' deletes everything
+# audio_only: Deletes audio file but keeps transcription/summary/notes (recommended)
+# full_recording: Permanently deletes the entire recording from database
+DELETION_MODE=audio_only
+
+# --- Permission-Based Deletion Controls ---
+# Allow all users to delete their recordings, or restrict to admins only
+# true: All users can delete their own recordings (default)
+# false: Only admins can delete recordings
+USERS_CAN_DELETE=true
+
+# --- Internal Sharing Settings ---
+# Enable user-to-user sharing of recordings (works independently of groups)
+ENABLE_INTERNAL_SHARING=false
+
+# Show usernames in the UI (when sharing/viewing shared recordings)
+# true: Display usernames throughout the interface
+# false: Hide usernames (users must know each other's usernames to share)
+SHOW_USERNAMES_IN_UI=false
+
+# --- Public Sharing Settings ---
+# Enable creation of public share links (anonymous access)
+# true: Users can create public links to share recordings externally (default)
+# false: Public sharing is disabled globally
+ENABLE_PUBLIC_SHARING=true
+
+# Note: Admins can control public sharing permissions per-user in the admin dashboard
+# even when ENABLE_PUBLIC_SHARING is true
+
+# --- Docker Settings (rarely need to be changed) ---
+SQLALCHEMY_DATABASE_URI=sqlite:////data/instance/transcriptions.db
+UPLOAD_FOLDER=/data/uploads
diff --git a/docs/admin-guide/group-management.md b/docs/admin-guide/group-management.md
new file mode 100644
index 00000000..635f975a
--- /dev/null
+++ b/docs/admin-guide/group-management.md
@@ -0,0 +1,405 @@
+---
+layout: default
+title: Group Management
+parent: Admin Guide
+nav_order: 6
+---
+
+# Group Management
+
+Groups enable organized collaboration in multi-user Speakr instances by grouping users and automating recording access through group-specific tags. This powerful feature reduces administrative overhead while maintaining security and control over content access.
+
+## Prerequisites
+
+Before enabling groups, ensure internal sharing is configured. Groups build on Speakr's internal sharing infrastructure to automatically grant access when users apply group tags.
+
+### Required Configuration
+
+Add these settings to your `.env` file:
+
+```bash
+# Enable internal sharing (required for groups)
+ENABLE_INTERNAL_SHARING=true
+
+# Control username visibility
+SHOW_USERNAMES_IN_UI=true # Show usernames in UI
+# OR
+SHOW_USERNAMES_IN_UI=false # Hide usernames (users type usernames manually to share)
+```
+
+After modifying `.env`, restart your Speakr instance for changes to take effect. The Groups tab will appear in the admin dashboard once internal sharing is enabled.
+
+### Privacy Considerations
+
+The `SHOW_USERNAMES_IN_UI` setting affects the entire instance. When enabled (`true`), users see actual usernames when searching for colleagues and viewing shared content. This improves usability in small, trusted groups where everyone knows each other.
+
+When disabled (`false`), usernames are hidden from the interface. Users must know each other's usernames to share recordings - they type the username manually when creating shares. This privacy-focused approach suits organizations where username visibility should be restricted. Group functionality works identically in both modes - only the display changes.
+
+## Creating and Managing Groups
+
+Groups are created and managed exclusively through the admin dashboard. Regular users cannot create groups, ensuring centralized control over organizational structure.
+
+### Creating a Group
+
+Navigate to the Admin Dashboard and select the Groups tab. Click "Create Group" to open the creation modal. Provide a group name that clearly identifies the group's purpose - "Engineering", "Sales EMEA", "Project Phoenix", etc. Descriptive names help users understand each group's scope and purpose.
+
+The description field is optional but recommended. Use it to explain the group's purpose, which projects or departments it serves, or who should be members. Good descriptions help future administrators understand group organization and make membership decisions.
+
+Click "Create Group" to finalize creation. The group appears in your groups list immediately, though it starts with no members. The creating user (you) doesn't automatically join - membership must be explicitly granted even for group creators.
+
+### Managing Group Membership
+
+Click the users-cog icon next to any group to open the group management modal. This interface shows current members, their roles, and provides tools for adding or removing members.
+
+To add a member, select a user from the dropdown and choose their role:
+
+- **Member**: Can use group tags and access group-tagged recordings. Suitable for most group participants who need to collaborate on content.
+- **Admin**: All member capabilities plus the ability to manage group membership, create and delete group tags, and access group management features. Useful for group leads or managers who need administrative control.
+
+Click "Add Member" to grant access. The user immediately gains visibility to group tags and will receive future group-tagged recordings. They don't automatically gain access to existing group-tagged recordings - only new ones tagged after they join.
+
+### Changing Member Roles
+
+Group roles can change as responsibilities evolve. Click the role dropdown next to any member to toggle them between Member and Admin. Role changes take effect immediately.
+
+Promoting members to admin grants them access to group management capabilities. They'll see a "Group Management" link in their interface and can add/remove members, create tags, and manage the group independently. This distributes administrative workload and empowers group leads.
+
+Demoting admins to members removes their management capabilities but preserves their group membership. They retain access to group tags and recordings but can no longer manage group membership or tags.
+
+### Removing Group Members
+
+Click the red user-times icon next to any member to remove them from the group. Removal is immediate and has several effects:
+
+- The user loses access to group tags
+- They won't receive new group-tagged recordings
+- Their access to previously-shared group recordings persists
+- Their personal notes on group recordings are preserved
+
+If you need to fully revoke access to existing group recordings, you must manually revoke those internal shares through the recording's share management interface. Group removal only prevents future automatic sharing.
+
+### Deleting Groups
+
+Click the red trash icon next to a group to delete it entirely. A confirmation dialog prevents accidental deletion. Deleting a group:
+
+- Removes all group memberships
+- Deletes all group tags (via database cascade)
+- Preserves all recordings (including previously group-tagged ones)
+- Preserves all internal shares created by group tags
+
+Group deletion is irreversible. Once deleted, the group structure is gone, though recordings and access permissions created by the group persist. If you need to temporarily disable a group, consider removing all members instead of deleting the group itself.
+
+## Group Tags
+
+Group tags power automatic sharing within groups. Unlike personal tags that organize individual content, group tags trigger access grants across all group members whenever applied.
+
+### Creating Group Tags
+
+From the Groups tab, click the purple tags icon next to the relevant group. This opens the group tags modal showing existing tags and a creation form.
+
+Provide a tag name that describes the content type or purpose. Good names are specific and clear: "Sprint Reviews", "Customer Calls", "Legal Contracts". Avoid generic names like "Important" or "Group" that don't convey useful information.
+
+Select a color to visually distinguish the tag. Colors help users quickly identify content categories in the interface. Consider establishing color conventions - blue for technical content, green for sales, red for legal, etc.
+
+### Tag Retention Policies
+
+Group tags can override global retention settings with tag-specific retention periods. This powerful feature lets different content types have different lifecycles within the same instance.
+
+Leave the retention field empty to use global retention settings. The tag won't affect how long recordings are kept - they'll follow the instance-wide `GLOBAL_RETENTION_DAYS` setting.
+
+Enter a number of days to set custom retention for this tag. Recordings with this tag will be auto-deleted after the specified period, regardless of global settings. For example:
+
+- Legal group: 2555 days (7 years) for contracts and compliance recordings
+- Operations group: 14 days for daily stand-ups
+- Marketing group: 180 days for campaign planning sessions
+
+When a recording has multiple tags with different retention periods, the shortest period applies. This ensures content is never kept longer than its most restrictive tag allows.
+
+### Protection from Deletion
+
+Enable "Protect from deletion" to make recordings with this tag immune to automatic deletion. Protected recordings are never auto-deleted regardless of age, global retention settings, or other tag retention periods.
+
+Use protection for recordings that must be permanently preserved:
+
+- Legal and compliance records
+- Critical business decisions
+- Training and onboarding materials
+- Reference documentation
+- Historical archives
+
+Protection can be removed by editing the tag later if preservation requirements change. Removing protection doesn't immediately delete recordings - they'll be evaluated for deletion on the next retention check based on their age and other applicable retention policies.
+
+### Auto-Share Settings
+
+Group tags support two levels of automatic sharing that trigger when any group member applies the tag to a recording:
+
+**Share with All Group Members** is the default and recommended approach. When enabled, applying this tag shares the recording with every group member (excluding the owner). All members receive view and edit permissions, enabling full collaboration.
+
+**Share with Group Leads Only** restricts automatic sharing to group admins. When enabled, only users with the admin role in this group receive automatic access. Regular members don't get automatic access, though group admins can manually share with them if needed. This option suits sensitive content that requires administrative oversight before wider distribution.
+
+Both options can be enabled simultaneously, though this is redundant - sharing with all members already includes group leads. Use one or the other based on your content sensitivity and group structure.
+
+### Managing Group Tags
+
+Existing group tags appear in the group tags modal with their current settings. Click the edit icon to modify a tag's name, color, retention, protection, or sharing settings. Changes affect the tag going forward but don't retroactively change already-applied tags or shares.
+
+Delete group tags by clicking the trash icon. Deleted tags:
+
+- Are removed from all recordings they were applied to
+- Disappear from tag selectors for all group members
+- Don't delete the recordings themselves
+- Don't revoke access already granted through the tag
+
+If a tag was widely used, consider the impact before deletion. Users may have organized content around that tag, and deletion removes that organizational structure. In most cases, retaining unused tags causes no harm.
+
+### Syncing Group Shares
+
+If your instance enabled group features after recordings were already tagged, or if group membership changed significantly, you might have group-tagged recordings that weren't automatically shared with current group members. The "Sync Group Shares" feature addresses this.
+
+Click "Sync Group Shares" in the group management modal to open the sync dialog. Review the information about what the sync will do - it applies automatic sharing retroactively to all existing recordings with this group's tags.
+
+The sync operation:
+
+- Identifies all recordings tagged with any of this group's tags
+- Checks each recording for existing shares with current group members
+- Creates missing shares for group members who should have access but don't
+- Respects the tag's sharing settings (all members vs. group leads only)
+- Skips recordings where members already have access
+
+Confirm the sync to execute. Depending on the number of tagged recordings and group size, this might take a few seconds to several minutes. A result modal shows how many shares were created and how many recordings were processed.
+
+Sync is safe to run multiple times - it won't create duplicate shares. Use it after adding many new members, after fixing misconfigured tags, or when migrating from older Speakr versions that didn't have full group support.
+
+## Group Admin Role
+
+Group admins are group members with elevated permissions within their group's scope. Unlike full instance administrators who can manage all groups and system settings, group admins can only manage groups where they have the admin role.
+
+### Granting Group Admin Access
+
+When adding a member to a group, select "Admin" from the role dropdown. The user immediately gains group admin capabilities for that group only. They cannot manage other groups or access system-wide administrative features.
+
+Group admins see a "Group Management" link in their user menu instead of the full admin link. Clicking this takes them to a focused admin interface showing only groups they administer. The interface is identical to the Groups tab regular admins see, but scoped to their groups.
+
+### Group Admin Capabilities
+
+Group admins can perform these actions within their groups:
+
+- Add new members from the instance's user base
+- Remove existing members (excluding themselves)
+- Change member roles between admin and member
+- Create new group tags with full configuration options
+- Edit existing group tags including retention and sharing settings
+- Delete group tags
+- Sync group shares for their groups
+
+Group admins cannot:
+
+- Create new groups
+- Delete groups
+- Manage groups they're not admins of
+- Access system-wide admin features (users, settings, statistics)
+- Grant themselves admin access to other groups
+
+This scoped access lets you distribute group management responsibility to group leads without granting full administrative access. Group leads can manage their groups independently while you maintain control over instance-wide settings and group creation.
+
+### Security Boundaries
+
+Group admins have powerful capabilities within their groups but cannot escalate their privileges. They cannot:
+
+- Make themselves full instance administrators
+- Grant themselves admin roles in other groups
+- Access or modify system settings
+- View statistics for other groups or the entire instance
+- Delete recordings owned by other users (even within their group)
+
+The database enforces these boundaries at the API level. Even if a group admin could somehow call instance-wide admin APIs, the backend verifies permissions and rejects unauthorized requests. The UI simply hides controls group admins can't use, but security doesn't rely on UI hiding.
+
+## Configuration Reference
+
+### Environment Variables
+
+```bash
+# Internal Sharing (Required)
+ENABLE_INTERNAL_SHARING=true|false
+
+# Username Display
+SHOW_USERNAMES_IN_UI=true|false
+
+# Public Sharing Control (Affects group members' public sharing)
+ENABLE_PUBLIC_SHARING=true|false
+
+# Retention Settings (Groups can override)
+ENABLE_AUTO_DELETION=true|false
+GLOBAL_RETENTION_DAYS=90
+DELETION_MODE=audio_only|full_recording
+```
+
+### Database Schema
+
+Groups use several database tables that work together:
+
+**Group Table**:
+- `id`: Primary key
+- `name`: Group name (max 100 chars)
+- `description`: Optional group description
+- `created_by`: User ID of creator (full admin)
+- `created_at`: Creation timestamp
+
+**TeamMembership Table**:
+- `id`: Primary key
+- `team_id`: References Group
+- `user_id`: References User
+- `role`: "admin" or "member"
+- `joined_at`: Membership timestamp
+
+**Tag Table** (Extended):
+- `team_id`: References Group (null for personal tags)
+- `retention_days`: Custom retention override (null uses global)
+- `protect_from_deletion`: Boolean protection flag
+- `auto_share_on_apply`: Boolean (share with all members)
+- `share_with_team_lead`: Boolean (share with group admins only)
+
+Cascade deletion is configured so deleting a group deletes its tags and memberships, but preserves recordings and shares.
+
+## Troubleshooting
+
+### Groups Tab Not Visible
+
+**Cause**: Internal sharing not enabled or not configured correctly.
+
+**Solution**:
+1. Check `.env` contains `ENABLE_INTERNAL_SHARING=true`
+2. Restart Speakr after `.env` changes
+3. Clear browser cache and reload
+4. Check application logs for startup errors
+
+### Users Can't See Group Tags
+
+**Cause**: User not added to group, or internal sharing disabled.
+
+**Solution**:
+1. Verify user is listed in group membership
+2. Confirm `ENABLE_INTERNAL_SHARING=true` in `.env`
+3. Check user is logged in (group tags hidden for anonymous users)
+4. Refresh the page to load updated tag lists
+
+### Auto-Sharing Not Working
+
+**Cause**: Group tag misconfigured or internal sharing disabled.
+
+**Solution**:
+1. Edit the group tag and verify "Share with all group members" or "Share with group leads" is enabled
+2. Confirm `ENABLE_INTERNAL_SHARING=true` in `.env`
+3. Check application logs when applying tags for sharing errors
+4. Try manually sharing the recording to verify sharing infrastructure works
+
+### Group Admin Can't Access Admin Interface
+
+**Cause**: User doesn't have admin role in any group, or routing issue.
+
+**Solution**:
+1. Verify user role is "admin" not "member" in group membership
+2. Have user log out and back in to refresh session
+3. Check "Group Management" link appears in user menu (not "Admin")
+4. Review application logs for permission errors
+
+### Recordings Not Deleted Per Retention Policy
+
+**Cause**: Protected tags, misconfigured retention, or auto-deletion disabled.
+
+**Solution**:
+1. Check if recording has protected group tags
+2. Verify `ENABLE_AUTO_DELETION=true` in `.env`
+3. Confirm `GLOBAL_RETENTION_DAYS` is set if no tag retention applies
+4. Review cron scheduler logs for deletion errors
+5. Check tag retention_days is set correctly (null = use global)
+
+### Sync Group Shares Shows Zero Shares Created
+
+**Cause**: All applicable shares already exist, or no recordings have group tags.
+
+**Solution**:
+1. Verify recordings actually have tags from this group
+2. Check if group members already have access via other shares
+3. Review whether recordings are owned by current group members (no self-sharing)
+4. Confirm group has members beyond the recording owners
+
+## Best Practices
+
+### Group Structure
+
+**Small Organizations (<10 users)**:
+Create groups per department (Engineering, Sales, HR). Use group tags for project names or content types. Liberal use of groups promotes collaboration since everyone knows everyone.
+
+**Large Organizations (>10 users)**:
+Create groups per product, division, or major project. Use nested organizational patterns if needed (separate groups for Product A Engineering and Product A Sales). More selective group membership prevents information overload.
+
+### Tag Naming Conventions
+
+Establish conventions early and document them for consistency:
+
+```
+Project-Based: "Project-Phoenix", "Initiative-Q3-2024"
+Content-Type: "Sprint-Reviews", "Customer-Calls", "Legal-Contracts"
+Department: "Eng-Architecture", "Sales-Training", "HR-Interviews"
+```
+
+Avoid generic names that don't communicate purpose:
+❌ "Important", "Misc", "Other", "Temp", "Group"
+✓ "Executive-Briefings", "Tech-Specs", "Client-Demos"
+
+### Retention Strategy
+
+Set thoughtful defaults that balance storage costs with compliance needs:
+
+```
+Global Default: 90 days (captures most content)
+Legal Group Tags: 2555 days (7 years for legal records)
+Compliance Tags: Protected (permanent retention)
+Meeting Tags: 180 days (reasonable collaboration window)
+Stand-up Tags: 14 days (ephemeral daily content)
+```
+
+Review retention policies quarterly to ensure they remain appropriate as business needs change.
+
+### Group Admin Distribution
+
+Grant group admin roles to natural group leaders - project managers, department heads, tech leads. This distributes administrative workload and empowers groups to self-manage.
+
+Avoid granting group admin too liberally. While it's scoped to individual groups, group admins can add members and create tags that affect access. Limit the role to trusted individuals who understand security implications.
+
+Document each group's admins in the group description or external documentation. Future administrators will appreciate knowing who to contact about group-specific questions.
+
+## Integration with Other Features
+
+### Inquire Mode
+
+Group tags automatically appear in Inquire Mode's available filters, enabling group-scoped semantic search. Users can search for "budget discussions" and filter to just their project group, finding relevant conversations without noise from other groups.
+
+Recordings shared via group tags are included in semantic search results. The vector store indexes all accessible recordings, meaning group content becomes part of users' searchable knowledge base automatically.
+
+### Retention and Auto-Deletion
+
+Tag-level retention policies integrate with Speakr's auto-deletion system. The nightly retention check evaluates each recording's tags to determine applicable retention periods:
+
+1. If recording has protected tags → Never deleted
+2. If recording has tags with `retention_days` → Use shortest tag retention
+3. Otherwise → Use global `GLOBAL_RETENTION_DAYS`
+
+This cascading system lets groups set specific policies while maintaining instance-wide defaults for untagged content.
+
+### Public Sharing
+
+Group membership doesn't affect public sharing capabilities. Users' ability to create public share links is controlled by:
+
+1. Global `ENABLE_PUBLIC_SHARING` setting
+2. Per-user `can_share_publicly` permission (if global is enabled)
+
+Group members can create public links for group recordings if they have appropriate permissions, enabling external stakeholder communication while maintaining group-internal collaboration.
+
+---
+
+Groups transform multi-user Speakr instances into collaborative platforms where information flows automatically to relevant people. Proper configuration and management ensure security while enabling seamless knowledge sharing.
+
+For user-focused group documentation, see the [Group Collaboration](../user-guide/groups.md) guide.
+
+Return to [Admin Guide](index.md) →
diff --git a/docs/admin-guide/index.md b/docs/admin-guide/index.md
index 0f0ca4b4..40aec35f 100644
--- a/docs/admin-guide/index.md
+++ b/docs/admin-guide/index.md
@@ -11,7 +11,14 @@ Welcome to the Speakr Admin Guide! As an administrator, you control the heart of
<p>Create accounts, manage permissions, monitor usage, and control access to your Speakr instance.</p>
<a href="user-management" class="card-link">Manage Users →</a>
</div>
-
+
+ <div class="guide-card">
+ <div class="card-icon">🤝</div>
+ <h3>Group Management</h3>
+ <p>Create groups, assign roles, configure auto-sharing tags, and enable organized collaboration.</p>
+ <a href="group-management" class="card-link">Manage Groups →</a>
+ </div>
+
<div class="guide-card">
<div class="card-icon">📊</div>
<h3>System Statistics</h3>
@@ -46,6 +53,13 @@ Welcome to the Speakr Admin Guide! As an administrator, you control the heart of
<p>Manage semantic search capabilities, monitor embedding status, and control Inquire Mode.</p>
<a href="vector-store" class="card-link">Manage Search →</a>
</div>
+
+ <div class="guide-card">
+ <div class="card-icon">🗑️</div>
+ <h3>Retention & Auto-Deletion</h3>
+ <p>Configure automated data lifecycle management with flexible retention policies and smart deletion rules.</p>
+ <a href="retention" class="card-link">Manage Retention →</a>
+ </div>
</div>
## Quick Actions
@@ -58,7 +72,15 @@ Welcome to the Speakr Admin Guide! As an administrator, you control the heart of
<p>User Management → Add User Button → Enter details → Set permissions</p>
</div>
</div>
-
+
+ <div class="action-card">
+ <span class="action-icon">🤝</span>
+ <div>
+ <strong>Create a Group</strong>
+ <p>Group Management → Create Group → Add members → Configure group tags</p>
+ </div>
+ </div>
+
<div class="action-card">
<span class="action-icon">📈</span>
<div>
@@ -93,7 +115,7 @@ Welcome to the Speakr Admin Guide! As an administrator, you control the heart of
</div>
<div class="help-item">
<span class="help-icon">🐛</span>
- <span>Check Docker logs: <code>docker-compose logs -f app</code></span>
+ <span>Check Docker logs: <code>docker compose logs -f app</code></span>
</div>
<div class="help-item">
<span class="help-icon">💾</span>
diff --git a/docs/admin-guide/prompts.md b/docs/admin-guide/prompts.md
index 18872246..a8fde0e6 100644
--- a/docs/admin-guide/prompts.md
+++ b/docs/admin-guide/prompts.md
@@ -62,6 +62,78 @@ Consider the AI model's strengths and limitations. Current models excel at ident
Balance detail with readability. Extremely detailed prompts might produce comprehensive summaries that users don't read. Sometimes a concise, focused summary serves users better than exhaustive documentation.
+## Creative Tag Prompt Use Cases
+
+Tags with custom prompts unlock powerful transformation capabilities. Here are creative ways people use this feature:
+
+### Recipe Recordings
+
+Create a "Recipe" tag with a prompt like: "Convert this free-form cooking narration into a properly formatted recipe with ingredients list, step-by-step instructions, cooking times, and servings. Organize ingredients by quantity and item. Number the steps clearly."
+
+When you record yourself cooking while talking through what you're doing - "okay I'm adding maybe two cups of flour, bit more actually, and then half a cup of sugar, no wait three quarters" - the AI transforms that messy stream-of-consciousness into a clean, usable recipe format with organized ingredients and numbered steps.
+
+### Lecture Notes
+
+A "Lecture" tag could use: "Extract the main concepts, supporting examples, key terminology with definitions, and any practical applications mentioned. Organize in an outline format suitable for study notes."
+
+Students record lectures as they happen. The messy 90-minute recording becomes organized study notes with concepts clearly labeled, examples pulled out, and terminology defined. Much more useful than trying to review the raw transcript.
+
+### Meeting Action Items
+
+Create a "Project Meeting" tag with: "Focus exclusively on action items, decisions made, and next steps. For each action item, identify who is responsible and any mentioned deadlines. Ignore general discussion."
+
+The group spends an hour talking about a project. The summary ignores all the background discussion and debate, giving you just the concrete outcomes - who's doing what and when.
+
+### Brainstorming Sessions
+
+A "Ideas" tag with: "List every distinct idea mentioned, no matter how brief the discussion. For each idea, note any immediate reactions or concerns raised. Don't evaluate or synthesize - just capture everything."
+
+Free-flowing creative sessions produce transcripts full of half-formed thoughts and tangents. This prompt pulls out every idea fragment so nothing gets lost in the noise.
+
+### Code Review Sessions
+
+"Code Review" tag: "For each piece of code or system discussed, list: 1) What was reviewed, 2) Issues identified, 3) Suggested changes, 4) Who will implement fixes. Use technical language, don't simplify."
+
+Technical discussions stay technical. The summary uses proper terminology and maintains the level of detail needed for developers to act on the feedback.
+
+## Tag Stacking and Order
+
+When a recording has multiple tags with prompts, they concatenate in the order tags were applied. This creates powerful combinations:
+
+### Example: Personal Lecture + Specific Course
+
+You have a personal "My Lectures" tag with: "Organize as study notes with clear headers."
+
+You also tag with "Biology 301" which adds: "Pay special attention to biological processes, terminology, and diagrams mentioned."
+
+The result combines both: study notes format focused on biological content. The order doesn't matter much here since they're complementary.
+
+### Example: Client Meeting + Legal Review
+
+"Client Meeting" tag: "Extract client requirements, concerns, and preferences."
+
+"Legal Review" tag: "Identify any legal considerations, compliance requirements, or risk factors mentioned."
+
+Together, you get client needs plus legal implications in one summary - useful when client calls touch on contractual matters. If you tagged "Legal Review" first and "Client Meeting" second, the legal aspects would be emphasized first, then client concerns.
+
+### Example: Recipe + Dietary Restriction
+
+"Recipe" tag: "Convert to formatted recipe."
+
+"Gluten Free" tag: "Note which ingredients contain gluten and suggest substitutions."
+
+The recipe gets formatted properly, plus you get automatic gluten-free adaptation notes. Perfect when you're adapting traditional recipes for dietary needs.
+
+### When Order Matters
+
+More specific prompts should generally come last, as they refine the output from general prompts. Start broad (format type) then add specifics (focus areas).
+
+If you tag "Technical Details" + "Executive Summary", you're asking for detailed technical content presented as an executive summary - probably condensed but still technical.
+
+Reverse it to "Executive Summary" + "Technical Details" and you're requesting executive-level content with technical depth where applicable - probably less detailed overall.
+
+Test your tag combinations with sample recordings to see which order produces the results you want.
+
## Coordinating with User Prompts
Your default prompt should complement, not compete with, user customization. Design it as a solid foundation that works for most cases while encouraging power users to customize for their specific needs.
diff --git a/docs/admin-guide/retention.md b/docs/admin-guide/retention.md
new file mode 100644
index 00000000..8080c698
--- /dev/null
+++ b/docs/admin-guide/retention.md
@@ -0,0 +1,453 @@
+---
+layout: default
+title: Retention & Auto-Deletion
+parent: Admin Guide
+nav_order: 7
+---
+
+# Auto-Deletion and Retention Policies
+
+This document describes the automated retention and deletion system for Speakr recordings.
+
+## Overview
+
+The auto-deletion system provides automated lifecycle management for your recordings, helping you:
+- **Comply with data retention policies** - Automatically remove recordings after a specified retention period
+- **Manage storage** - Prevent unlimited growth of audio files
+- **Maintain critical data** - Keep transcriptions and metadata even after audio deletion
+- **Protect important recordings** - Exempt specific recordings from automatic deletion
+
+## Configuration
+
+### Environment Variables
+
+Add these to your `.env` file to configure auto-deletion:
+
+```bash
+# Enable or disable the auto-deletion feature
+ENABLE_AUTO_DELETION=false # Set to 'true' to enable
+
+# Global retention period in days (0 = disabled)
+GLOBAL_RETENTION_DAYS=90 # Recordings older than this will be processed
+
+# Deletion mode: what to delete
+DELETION_MODE=full_recording # Options: 'audio_only' or 'full_recording'
+```
+
+### Deletion Modes
+
+#### Audio-Only Mode (`DELETION_MODE=audio_only`)
+- **Deletes**: Audio file only
+- **Keeps**: Transcription, summary, notes, metadata
+- **Use case**: Long-term record keeping with storage optimization
+- **Result**: Recordings appear in "Archived" view, transcription remains searchable
+
+#### Full Recording Mode (`DELETION_MODE=full_recording`)
+- **Deletes**: Complete recording including audio, transcription, summary, notes
+- **Keeps**: Nothing - recording is permanently removed
+- **Use case**: Complete data removal for compliance
+- **Result**: Recording is completely removed from the system
+
+## Multi-Tier Retention System
+
+Speakr uses a hierarchical retention policy system:
+
+### 1. Global Retention (System-Wide)
+Set via `GLOBAL_RETENTION_DAYS` environment variable. Applies to all recordings unless overridden.
+
+```bash
+GLOBAL_RETENTION_DAYS=90 # All recordings older than 90 days
+```
+
+### 2. Tag-Based Retention
+Tags can override the global retention period with custom retention periods. This is especially powerful with group tags, where group admins can set retention policies for their group's content.
+
+```
+Global: 90 days
+Tag "Legal Records": 2555 days (7 years) # Longer retention
+Tag "Daily Standups": 14 days # Shorter retention
+Untagged recordings: Uses global (90 days)
+```
+
+When a recording has multiple tags with different retention periods, the **shortest** period applies.
+
+### 3. Tag-Based Protection
+Individual tags can protect recordings from auto-deletion entirely.
+
+**Example Hierarchy:**
+- Global retention: 90 days
+- Tag "Sprint Reviews": 180 days (longer than global)
+- Tag "Daily Standups": 14 days (shorter than global)
+- Tag "Legal" with protection enabled: Never deleted (permanent)
+
+## Protecting Recordings from Deletion
+
+1. Go to **Account Settings** → **Tags** tab
+2. Click **Create Tag** or **Edit** an existing tag
+3. Enable **"Protect from Auto-Deletion"** checkbox
+4. Apply this tag to recordings you want to protect
+
+**When protected:**
+- ✅ Recordings with protected tags are exempt from auto-deletion
+- ✅ Works regardless of age or retention period
+- ✅ Applies to all recordings with that tag
+
+## Archived Recordings
+
+When `DELETION_MODE=audio_only`, recordings become "archived" after audio deletion.
+
+### Accessing Archived Recordings
+
+1. Open the **Recordings** sidebar
+2. Click **Advanced Filters**
+3. Toggle **"Archived Recordings"** ON
+
+### What You Can Do with Archived Recordings
+
+| Feature | Available | Notes |
+|---------|-----------|-------|
+| View transcription | ✅ | Full transcript accessible |
+| Search content | ✅ | Text search still works |
+| Read summary | ✅ | AI summary preserved |
+| View/edit notes | ✅ | All metadata accessible |
+| Play audio | ❌ | Audio file deleted |
+| Re-process | ❌ | Source audio unavailable |
+| Share | ✅ | Can share transcription |
+| Export | ✅ | Download transcript, summary, notes |
+
+### Archived Recording Indicators
+
+- **Sidebar**: Gray "Archived" badge next to recording title
+- **Player**: Info banner: "Audio file has been deleted, but the transcription remains available"
+- **Filter**: Separate "Archived" view toggle in advanced filters
+
+## Admin Controls
+
+### Running Auto-Deletion
+
+Auto-deletion runs automatically based on configured schedule. Admins can also trigger manually:
+
+**API Endpoint:**
+```bash
+POST /admin/auto-deletion/run
+```
+
+**Response:**
+```json
+{
+ "checked": 150,
+ "deleted_audio_only": 45,
+ "deleted_full": 0,
+ "exempted": 12,
+ "errors": 0
+}
+```
+
+### Checking Auto-Deletion Stats
+
+**API Endpoint:**
+```bash
+GET /admin/auto-deletion/stats
+```
+
+**Response:**
+```json
+{
+ "enabled": true,
+ "global_retention_days": 90,
+ "deletion_mode": "audio_only",
+ "eligible_count": 45,
+ "exempted_count": 12,
+ "archived_count": 128
+}
+```
+
+## Speaker Data Cleanup
+
+When recordings are automatically deleted, Speakr manages associated speaker voice profile data to maintain privacy and GDPR compliance.
+
+### What Gets Cleaned Up
+
+When the auto-deletion job runs, the system automatically:
+
+1. **Removes orphaned speaker profiles**: Speakers with no remaining recordings are deleted entirely
+2. **Cleans embedding references**: Recording IDs are removed from speaker voice profile metadata
+3. **Applies to both deletion modes**: Works with both `audio_only` and `full_recording` deletion modes
+
+### Cleanup Schedule
+
+Speaker cleanup runs on the same schedule as auto-deletion:
+
+- **Frequency**: Daily at 2:00 AM (server time)
+- **Trigger**: Automatically when `ENABLE_AUTO_DELETION=true`
+- **No additional configuration**: Uses existing auto-deletion settings
+
+### When Speakers Are Deleted
+
+A speaker is considered "orphaned" and deleted when:
+
+- No `SpeakerSnippet` records exist for the speaker (no voice samples in any recordings)
+- No valid recording references remain in the speaker's voice profile metadata
+- This occurs after all recordings containing that speaker have been deleted
+
+**Note**: Speakers are preserved as long as they have at least one active recording with speaker identifications.
+
+### Privacy & GDPR Compliance
+
+This automatic cleanup ensures:
+
+- **Data Minimization**: Removes biometric voice data (embeddings) when no longer needed for system function
+- **Right to Erasure**: Deletes personal data (voice profiles) when recordings are removed
+- **Transparency**: Cleanup activity is logged for audit purposes
+- **No Manual Action Required**: Cleanup happens automatically with retention policies
+
+The system treats voice embeddings as biometric data under GDPR. When recordings are deleted (either through auto-deletion or manual deletion), the associated voice profile data is evaluated for removal. This ensures compliance with data protection regulations without requiring manual intervention.
+
+### Monitoring Cleanup Activity
+
+View cleanup statistics in:
+
+- **System logs**: Check application logs for cleanup counts and activity
+- **Auto-deletion response**: Speaker cleanup counts included in scheduled job output
+
+Example log entry:
+```
+INFO - Speaker cleanup completed: 5 speakers deleted, 12 embedding references removed
+```
+
+The cleanup process includes these statistics in the auto-deletion job response:
+
+```json
+{
+ "checked": 123,
+ "deleted_audio_only": 45,
+ "deleted_full": 0,
+ "exempted": 12,
+ "speakers_deleted": 5,
+ "embeddings_cleaned": 12,
+ "speakers_evaluated": 94
+}
+```
+
+### What Data Is Retained
+
+The system preserves:
+
+- **Active speakers**: Speakers with at least one recording containing their voice
+- **Speaker names**: Names are retained as long as associated recordings exist
+- **Voice profiles**: Embedding data is kept when recordings reference the speaker
+
+### What Data Is Removed
+
+The system removes:
+
+- **Orphaned voice embeddings**: Biometric voice data for speakers with no recordings
+- **Speaker records**: Entire speaker profile when completely orphaned
+- **Invalid references**: Recording IDs in embedding history that point to deleted recordings
+- **Usage statistics**: Use counts and timestamps for deleted speakers
+
+This ensures that biometric data is only retained when there's a legitimate purpose (active recordings), fulfilling GDPR's data minimization requirement.
+
+## Practical Use Cases
+
+The retention system solves real problems people have with accumulating recordings. Here's how it gets used:
+
+### Personal Use
+
+You record everything during your workday to capture ideas and discussions. Most of these recordings are ephemeral - useful for a week or two, then forgotten. Set a 30-day global retention with audio-only deletion. After a month, the audio files disappear but the searchable transcriptions remain. You can still find what was said in old recordings, but you're not paying to store hours of audio you'll never listen to again.
+
+If something turns out to be important, tag it with a protected tag before the 30 days expire. The tag prevents deletion, preserving both audio and transcript for as long as you need.
+
+### Group Collaboration
+
+Different types of group content need different lifecycles:
+
+| Content Type | Retention Approach | Why |
+|--------------|-------------------|-----|
+| Daily standups | Group tag with 14-day retention | Routine updates, no long-term value |
+| Sprint planning | Group tag with 90-day retention | Reference value for current quarter |
+| Architecture decisions | Group tag with protection enabled | Document important choices permanently |
+| Customer calls (sales) | Group tag with 1-year retention | Sales cycle duration + follow-up window |
+| Interviews (HR) | Group tag with 2-year retention | Typical employment litigation window |
+| Legal meetings | Protected tag | Indefinite retention for compliance |
+
+Each group sets up their tags once with appropriate retention. Members just tag recordings normally, and lifecycle management happens automatically. Nobody has to remember which recordings to keep or delete.
+
+### Compliance Requirements
+
+Organizations with data retention policies can enforce them automatically. Healthcare organization needs 7-year retention for patient consultations - set that in the relevant group tag. Law firm needs indefinite retention for client meetings - use protected tags. Financial services deletes routine internal calls after 90 days but keeps compliance-related recordings for 7 years - different tags with different retention.
+
+The system enforces policy without requiring anyone to remember the rules. Tag correctly, and retention happens automatically.
+
+### Storage Cost Management
+
+Audio files are large - a one-hour meeting might be 50-100MB. Transcriptions are text - the same meeting might be 10-20KB. Audio-only deletion mode keeps the valuable searchable text while reclaiming storage.
+
+Run audio-only deletion with a 90-day retention. Recordings older than 90 days lose their audio but remain fully searchable. You can still use Inquire Mode to find information, read transcripts, review summaries, and see notes. You just can't play the original audio. For most use cases, that's fine - once you've extracted the information into text, the audio serves no purpose.
+
+This approach lets you keep years of searchable conversation history without accumulating terabytes of audio files.
+
+## Best Practices
+
+### For Compliance
+
+1. **Set appropriate retention periods**
+ ```bash
+ # Example: 7-year retention for financial records
+ GLOBAL_RETENTION_DAYS=2555 # 7 years × 365 days
+ DELETION_MODE=full_recording
+ ```
+
+2. **Use tag-based protection** for records requiring indefinite retention
+ - Create "Legal Hold" or "Permanent" tags
+ - Enable protection on these tags
+ - Apply to relevant recordings
+
+3. **Document your retention policy** in your organization's compliance documentation
+
+### For Storage Management
+
+1. **Start with audio-only deletion**
+ ```bash
+ DELETION_MODE=audio_only
+ ```
+ - Keeps searchable transcriptions
+ - Frees up 95%+ of storage (audio files are large)
+ - Maintains business value of conversations
+
+2. **Use shorter retention periods** for routine recordings
+ ```bash
+ GLOBAL_RETENTION_DAYS=30 # Routine meetings
+ ```
+
+3. **Protect important content** with tags
+ - "Executive Meetings" tag → protect from deletion
+ - "Daily Standup" tag → no protection (routine)
+
+### For Groups
+
+When groups are enabled:
+1. **Set conservative global retention** (shorter period as a baseline)
+2. **Configure group tags with custom retention** to match each group's needs
+3. **Use protected group tags** for group content requiring permanent retention
+4. **Document retention policies** so group members understand lifecycle expectations
+
+Example group tag retention configuration:
+- Engineering group "Architecture Decisions": Protected (never deleted)
+- Sales group "Customer Calls": 365 days
+- HR group "Interviews": 90 days
+- Operations group "Daily Standups": 14 days
+
+## Deletion Process Flow
+
+```
+1. Automated Check (Daily/Manual Trigger)
+ ↓
+2. Find recordings older than retention period
+ ↓
+3. For each recording:
+ - Check manual exemption flag
+ - Check tags for protection
+ - Skip if exempt
+ ↓
+4. Delete based on mode:
+ - audio_only: Remove file, keep DB record, set audio_deleted_at
+ - full_recording: Remove file and DB record
+ ↓
+5. Return statistics
+```
+
+## Migration Guide
+
+### Enabling Auto-Deletion on Existing System
+
+1. **Test with audio-only mode first:**
+ ```bash
+ ENABLE_AUTO_DELETION=true
+ GLOBAL_RETENTION_DAYS=365 # Start with long period
+ DELETION_MODE=audio_only # Test safely
+ ```
+
+2. **Protect existing important content:**
+ - Create protected tags
+ - Apply to critical recordings
+ - Verify exemptions via `/admin/auto-deletion/stats`
+
+3. **Run manual test:**
+ ```bash
+ POST /admin/auto-deletion/run
+ ```
+
+4. **Monitor results** and adjust retention period as needed
+
+### Reverting Changes
+
+If you need to disable auto-deletion:
+```bash
+ENABLE_AUTO_DELETION=false
+```
+
+**Note:** Already deleted audio files cannot be recovered. Database records (if using audio-only mode) remain intact.
+
+## API Reference
+
+### Run Auto-Deletion (Admin Only)
+
+```http
+POST /admin/auto-deletion/run
+```
+
+Manually trigger the auto-deletion process.
+
+### Get Deletion Statistics (Admin Only)
+
+```http
+GET /admin/auto-deletion/stats
+```
+
+Get statistics about eligible recordings and current configuration.
+
+## Troubleshooting
+
+### Auto-Deletion Not Running
+
+**Check:**
+1. `ENABLE_AUTO_DELETION=true` in `.env`
+2. `GLOBAL_RETENTION_DAYS > 0`
+3. Admin status for manual triggers
+4. Server logs for errors
+
+### Too Many Recordings Being Deleted
+
+**Solutions:**
+1. Increase `GLOBAL_RETENTION_DAYS`
+2. Add protected tags to important categories
+3. Check tag assignments on recordings
+4. Review exemption status via stats endpoint
+
+### Archived Recordings Not Showing
+
+**Check:**
+1. Toggle "Archived Recordings" filter in sidebar
+2. Verify `DELETION_MODE=audio_only` (full_recording doesn't archive)
+3. Check `audio_deleted_at` field in database
+
+## Security Considerations
+
+1. **Admin-only endpoints**: Auto-deletion triggers require admin authentication
+2. **Irreversible deletion**: Deleted audio files cannot be recovered
+3. **Audit trail**: Check server logs for deletion events
+4. **GDPR compliance**: Full deletion mode helps meet "right to be forgotten" requirements
+
+## Support
+
+For issues or questions about auto-deletion:
+1. Check server logs for detailed error messages
+2. Verify environment variable configuration
+3. Test with `/admin/auto-deletion/stats` endpoint
+4. Review this documentation
+5. Submit issues on GitHub with logs attached
+
+---
+
+Return to [Admin Guide](index.md) →
diff --git a/docs/admin-guide/system-settings.md b/docs/admin-guide/system-settings.md
index 73a71383..907ad872 100644
--- a/docs/admin-guide/system-settings.md
+++ b/docs/admin-guide/system-settings.md
@@ -52,6 +52,54 @@ If API costs spike unexpectedly, review your transcript length limit. A single u
Processing backlogs might indicate your timeout is too high. If the system waits 30 minutes for each failed transcription attempt, a series of problematic files could block the queue for hours. Balance patience for slow processing with the need to fail fast when services are actually down.
+## Environment Variable Configuration
+
+Beyond the UI-configurable settings above, several environment variables in your `.env` file control fundamental system behaviors. These require instance restart to take effect.
+
+### Collaboration & Sharing
+
+**ENABLE_INTERNAL_SHARING**: Controls user-to-user sharing capabilities. Set to `true` to enable internal sharing features, allowing users to share recordings with specific colleagues. Required for group functionality. Default: `false`.
+
+**SHOW_USERNAMES_IN_UI**: Controls username visibility in the interface. When `true`, usernames are displayed throughout the UI when sharing and collaborating. When `false`, usernames are hidden - users must know each other's usernames to share recordings (they type the username manually). Default: `false`.
+
+**ENABLE_PUBLIC_SHARING**: Controls whether public share links can be created. When `true`, authorized users can generate secure links for external sharing. When `false`, only internal sharing is available. Default: `false`.
+
+### User Permissions
+
+**USERS_CAN_DELETE**: Determines whether regular users can delete their own recordings. When `true`, users see delete buttons for their recordings. When `false`, only administrators can delete recordings. This helps prevent accidental data loss and maintains content retention for compliance. Default: `true`.
+
+### Retention & Auto-Deletion
+
+**ENABLE_AUTO_DELETION**: Enables the automated retention system. When `true`, recordings older than the retention period are automatically processed for deletion. Default: `false`.
+
+**DEFAULT_RETENTION_DAYS**: Global retention period in days for recordings without tag-specific retention. Set to `0` to disable auto-deletion. Tag-level retention policies can override this default. Default: `0` (disabled).
+
+**DELETION_MODE**: Controls what gets deleted: `audio_only` removes audio files but preserves transcriptions and metadata, while `full_recording` removes everything. Audio-only mode maintains searchable records while saving storage space. Default: `audio_only`.
+
+For detailed retention configuration, see the [Retention & Auto-Deletion](retention.md) guide.
+
+### Configuration Example
+
+```bash
+# Enable collaboration features
+ENABLE_INTERNAL_SHARING=true
+SHOW_USERNAMES_IN_UI=true
+ENABLE_PUBLIC_SHARING=false
+
+# User permissions
+USERS_CAN_DELETE=false # Only admins can delete
+
+# Retention policy
+ENABLE_AUTO_DELETION=true
+DEFAULT_RETENTION_DAYS=90
+DELETION_MODE=audio_only
+```
+
+After modifying environment variables, restart your Speakr instance for changes to take effect:
+```bash
+docker compose restart
+```
+
---
Next: [Default Prompts](prompts.md) →
\ No newline at end of file
diff --git a/docs/admin-guide/user-management.md b/docs/admin-guide/user-management.md
index de3c2b3b..c750f5a7 100644
--- a/docs/admin-guide/user-management.md
+++ b/docs/admin-guide/user-management.md
@@ -18,6 +18,14 @@ The username becomes their identity within Speakr, appearing in the interface an
Admin privileges are powerful and should be granted sparingly. Admin users can see and modify all [system settings](system-settings.md), manage other users including other admins, configure [default prompts](prompts.md), and monitor the [vector store](vector-store.md). Most users will never need these capabilities.
+### User Permissions
+
+Beyond the admin role, Speakr offers granular per-user permissions that control specific capabilities:
+
+**Public Sharing Permission**: The public sharing icon button (globe icon) in each user's row toggles their ability to create public share links. When enabled (green), the user can generate secure links to share recordings externally with anyone. When disabled (gray), the user can only use internal sharing to share with other Speakr users. This permission is only available if `ENABLE_PUBLIC_SHARING=true` in your environment configuration.
+
+Use this permission to control external information sharing on a per-user basis. You might grant public sharing to executives, sales groups, or marketing staff who regularly communicate with external stakeholders, while restricting it for users handling sensitive internal data.
+
## Managing Existing Users
Each user row includes action buttons that give you complete control over that account. The edit button opens a modal where you can update their username or email address. This is useful when people change names, switch email providers, or when you need to correct initial entry mistakes.
diff --git a/docs/admin-guide/whisperx-setup.md b/docs/admin-guide/whisperx-setup.md
new file mode 100644
index 00000000..bab507bc
--- /dev/null
+++ b/docs/admin-guide/whisperx-setup.md
@@ -0,0 +1,418 @@
+---
+layout: default
+title: WhisperX ASR Setup
+parent: Admin Guide
+nav_order: 8
+---
+
+# WhisperX ASR Service Setup
+
+WhisperX is an advanced ASR (Automatic Speech Recognition) service that provides superior speaker diarization and word-level timestamps compared to standard Whisper implementations. This guide covers setting up WhisperX as an alternative ASR backend for Speakr.
+
+## Overview
+
+**WhisperX Benefits:**
+- ✅ Better speaker diarization accuracy (Pyannote.audio 4.0)
+- ✅ More precise word-level timestamps
+- ✅ Improved multi-speaker handling
+- ✅ Active development and updates
+- ✅ Production-ready Docker deployment
+
+**vs. Standard Whisper ASR:**
+- Standard: Simple, lightweight, good for single speakers
+- WhisperX: Advanced diarization, better for meetings/conversations
+
+## Prerequisites
+
+### Hardware Requirements
+
+**Minimum:**
+- NVIDIA GPU with 8GB+ VRAM (RTX 3060, RTX 2080, etc.)
+- 16GB RAM
+- 50GB free disk space
+
+**Recommended:**
+- NVIDIA GPU with 16GB+ VRAM (RTX 3080, RTX 4080, A100)
+- 32GB RAM
+- 100GB SSD storage
+
+### Software Requirements
+
+- Docker and Docker Compose
+- NVIDIA Container Toolkit
+- Hugging Face account with model access
+
+## Quick Start
+
+### 1. Get the WhisperX Service
+
+The WhisperX ASR service is maintained in a separate repository:
+
+```bash
+# Clone the WhisperX ASR service
+git clone https://github.com/murtaza-nasir/whisperx-asr-service.git
+cd whisperx-asr-service
+```
+
+### 2. Configure Hugging Face Access
+
+**Complete ALL steps below to enable speaker diarization:**
+
+#### Step 1: Create Account
+- Visit: [https://huggingface.co/join](https://huggingface.co/join)
+- Sign up with your email
+
+#### Step 2: Accept Model Agreements (CRITICAL - ALL THREE REQUIRED)
+
+You must accept agreements for **all three models** used by the diarization pipeline:
+
+1. **Main diarization model:**
+ - [https://huggingface.co/pyannote/speaker-diarization-community-1](https://huggingface.co/pyannote/speaker-diarization-community-1)
+
+2. **Segmentation model:**
+ - [https://huggingface.co/pyannote/segmentation-3.0](https://huggingface.co/pyannote/segmentation-3.0)
+
+3. **Speaker diarization 3.1:**
+ - [https://huggingface.co/pyannote/speaker-diarization-3.1](https://huggingface.co/pyannote/speaker-diarization-3.1)
+
+For each model:
+- Click the **"Agree and access repository"** button
+- Fill out form (Company/university: your organization, Use case: "Meeting note taker")
+- Submit (approval is instant)
+
+#### Step 3: Generate Access Token
+- Visit: [https://huggingface.co/settings/tokens](https://huggingface.co/settings/tokens)
+- Click **"New token"**
+- Name: `whisperx-diarization`
+- Permission: **Read**
+- Click **"Generate token"**
+- Copy the token (starts with `hf_...`)
+
+**⚠️ Important:** You MUST accept the model agreement in Step 2. Without this, you'll get "403 Access Denied" errors even with a valid token.
+
+### 3. Set Up Environment
+
+```bash
+# Copy example configuration
+cp .env.example .env
+
+# Edit and add your Hugging Face token
+nano .env
+```
+
+Update `.env`:
+```bash
+HF_TOKEN=hf_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
+DEVICE=cuda
+COMPUTE_TYPE=float16
+BATCH_SIZE=16
+```
+
+### 4. Deploy the Service
+
+```bash
+# Build Docker image
+docker compose build
+
+# Start service
+docker compose up -d
+
+# Check logs
+docker compose logs -f
+```
+
+### 5. Test the Service
+
+```bash
+# Health check
+curl http://localhost:9000/health
+
+# Should return:
+{
+ "status": "healthy",
+ "device": "cuda",
+ "loaded_models": []
+}
+```
+
+## Integration with Speakr
+
+### Same Machine Deployment
+
+If WhisperX is running on the same machine as Speakr:
+
+Update Speakr's `.env` file:
+
+```bash
+# Enable ASR endpoint
+USE_ASR_ENDPOINT=true
+
+# Point to WhisperX service
+ASR_BASE_URL=http://whisperx-asr-api:9000
+```
+
+Restart Speakr:
+
+```bash
+docker compose restart
+```
+
+### Separate GPU Machine Deployment
+
+If WhisperX is on a dedicated GPU server:
+
+**On GPU Machine:**
+
+1. Expose service to network in `docker-compose.yml`:
+ ```yaml
+ ports:
+ - "0.0.0.0:9000:9000"
+ ```
+
+2. Configure firewall:
+ ```bash
+ sudo ufw allow 9000/tcp
+ ```
+
+**On Speakr Machine:**
+
+Update Speakr's `.env`:
+
+```bash
+USE_ASR_ENDPOINT=true
+ASR_BASE_URL=http://GPU_MACHINE_IP:9000
+```
+
+Replace `GPU_MACHINE_IP` with actual IP address.
+
+## Configuration
+
+### Performance Tuning
+
+Edit WhisperX service `.env`:
+
+**High-End GPU (RTX 3080+, A100):**
+```bash
+BATCH_SIZE=32
+COMPUTE_TYPE=float16
+```
+
+**Mid-Range GPU (RTX 3060, RTX 2080):**
+```bash
+BATCH_SIZE=16
+COMPUTE_TYPE=float16
+```
+
+**Low-End GPU (GTX 1660, RTX 2060):**
+```bash
+BATCH_SIZE=8
+COMPUTE_TYPE=int8
+```
+
+### Model Selection
+
+Models are selected per-recording in Speakr. Available options:
+
+| Model | Quality | Speed | VRAM Required |
+|-------|---------|-------|---------------|
+| tiny | Low | Fastest | 1GB |
+| base | Low | Very Fast | 1GB |
+| small | Medium | Fast | 2GB |
+| medium | Good | Moderate | 5GB |
+| large-v2 | Excellent | Slow | 10GB |
+| large-v3 | Best | Slow | 10GB |
+
+**Recommendation:** Use `large-v3` for best quality, `small` for speed.
+
+## Speaker Diarization
+
+WhisperX provides superior speaker diarization compared to standard implementations.
+
+### Settings in Speakr
+
+When uploading or processing recordings:
+
+- **Min Speakers:** Minimum expected number of speakers
+- **Max Speakers:** Maximum expected number of speakers
+- Leave blank for automatic detection
+
+**Tips:**
+- Set `min_speakers=2` and `max_speakers=6` for typical meetings
+- For interviews: `min_speakers=2`, `max_speakers=2`
+- For panels: `min_speakers=3`, `max_speakers=8`
+
+### After Transcription
+
+Use Speakr's speaker identification feature to assign real names to detected speakers. WhisperX's improved diarization makes this more accurate.
+
+## Monitoring
+
+### Check Service Health
+
+```bash
+# Container status
+cd /path/to/whisperx-asr-service
+docker compose ps
+
+# View logs
+docker compose logs -f
+
+# Check GPU usage
+nvidia-smi -l 1
+```
+
+### Performance Metrics
+
+Monitor in Speakr's admin interface:
+- Transcription times
+- Error rates
+- Model usage statistics
+
+## Troubleshooting
+
+### WhisperX Service Won't Start
+
+**Check logs:**
+```bash
+docker compose logs whisperx-asr
+```
+
+**Common issues:**
+- GPU not accessible: Verify `nvidia-smi` works
+- Invalid HF_TOKEN: Check token and model agreements
+- Port conflict: Change port in `docker-compose.yml`
+
+### Speakr Can't Connect
+
+**Test connectivity:**
+```bash
+curl http://ASR_BASE_URL/health
+```
+
+**Solutions:**
+- Verify firewall rules
+- Check network connectivity
+- Ensure service is running
+- Try IP address instead of hostname
+
+### Slow Processing
+
+**Solutions:**
+- Increase `BATCH_SIZE` (if GPU has memory)
+- Use smaller model (`small` instead of `large-v3`)
+- Disable diarization for faster processing
+- Check GPU usage with `nvidia-smi`
+
+### Out of Memory
+
+**Error:** `CUDA out of memory`
+
+**Solutions:**
+1. Reduce `BATCH_SIZE`: Set to `8` or `4`
+2. Use smaller model
+3. Use `COMPUTE_TYPE=int8`
+4. Close other GPU applications
+
+### Speaker Diarization Fails
+
+**Check:**
+1. HF_TOKEN is set correctly in `.env`
+2. Accepted pyannote model agreements
+3. Service has internet access (for first-time model download)
+
+**Solutions:**
+- Regenerate HF token
+- Accept model agreements again
+- Check logs for specific errors
+
+## Upgrading
+
+### Update WhisperX Service
+
+```bash
+cd /path/to/whisperx-asr-service
+
+# Pull latest changes (if using Git)
+git pull
+
+# Rebuild image
+docker compose build --no-cache
+
+# Restart service
+docker compose up -d
+```
+
+### Update Models
+
+Models are cached automatically. To use newer models:
+
+```bash
+# Remove cache volume
+docker compose down -v
+
+# Restart (models will re-download)
+docker compose up -d
+```
+
+## Security Considerations
+
+### For Production
+
+1. **Use HTTPS:** Deploy behind reverse proxy with SSL
+2. **Firewall Rules:** Restrict access to Speakr machine only
+3. **API Authentication:** Add API key validation
+4. **Secrets Management:** Use Docker secrets for HF_TOKEN
+5. **Regular Updates:** Keep service updated monthly
+
+### Example Firewall Rule
+
+Only allow from Speakr machine:
+
+```bash
+sudo ufw allow from SPEAKR_IP to any port 9000
+sudo ufw deny 9000/tcp
+```
+
+## Performance Benchmarks
+
+Tested on RTX 3080 (10GB VRAM):
+
+| Model | 10min Audio | Processing Time | Real-time Factor |
+|-------|-------------|-----------------|------------------|
+| small | 10 min | 45 sec | 13x |
+| medium | 10 min | 90 sec | 6.7x |
+| large-v3 | 10 min | 180 sec | 3.3x |
+
+*With diarization: add ~30% processing time*
+
+## Comparison: WhisperX vs Standard Whisper
+
+| Feature | Standard Whisper | WhisperX |
+|---------|-----------------|----------|
+| Transcription Quality | Excellent | Excellent |
+| Word Timestamps | Good | Excellent |
+| Speaker Diarization | Good | Excellent |
+| Setup Complexity | Low | Medium |
+| Resource Usage | Lower | Higher |
+| Active Development | Moderate | High |
+| Production Ready | Yes | Yes |
+
+## Best Practices
+
+1. **Start with small model** to verify setup
+2. **Monitor GPU memory** during first runs
+3. **Use model caching** via Docker volumes
+4. **Set appropriate speaker counts** for better diarization
+5. **Regular backups** of cache volume
+6. **Monitor logs** for errors
+7. **Update monthly** for latest improvements
+
+## Getting Help
+
+- **Service Documentation:** See WhisperX service README
+- **WhisperX Issues:** [GitHub](https://github.com/m-bain/whisperX/issues)
+- **Speakr Integration:** Check Speakr logs and admin dashboard
+
+---
+
+For detailed setup instructions, see the [WhisperX Service Setup Guide](https://github.com/murtaza-nasir/whisperx-asr-service/blob/main/SETUP_GUIDE.md).
diff --git a/docs/assets/images/screenshots/Admin dashboard.png b/docs/assets/images/screenshots/Admin dashboard.png
index bf44097e..160a8d4e 100644
Binary files a/docs/assets/images/screenshots/Admin dashboard.png and b/docs/assets/images/screenshots/Admin dashboard.png differ
diff --git a/docs/assets/images/screenshots/Admin stats.png b/docs/assets/images/screenshots/Admin stats.png
index 30ac8148..2e36df2a 100644
Binary files a/docs/assets/images/screenshots/Admin stats.png and b/docs/assets/images/screenshots/Admin stats.png differ
diff --git a/docs/assets/images/screenshots/Admin system settings.png b/docs/assets/images/screenshots/Admin system settings.png
index 281a1564..ce3a15c6 100644
Binary files a/docs/assets/images/screenshots/Admin system settings.png and b/docs/assets/images/screenshots/Admin system settings.png differ
diff --git a/docs/assets/images/screenshots/Admin vector store.png b/docs/assets/images/screenshots/Admin vector store.png
index dacf6c70..f8fcef66 100644
Binary files a/docs/assets/images/screenshots/Admin vector store.png and b/docs/assets/images/screenshots/Admin vector store.png differ
diff --git a/docs/assets/images/screenshots/Inquire mode.png b/docs/assets/images/screenshots/Inquire mode.png
new file mode 100644
index 00000000..508fed8c
Binary files /dev/null and b/docs/assets/images/screenshots/Inquire mode.png differ
diff --git a/docs/assets/images/screenshots/Main view.png b/docs/assets/images/screenshots/Main view.png
new file mode 100644
index 00000000..791418df
Binary files /dev/null and b/docs/assets/images/screenshots/Main view.png differ
diff --git a/docs/assets/images/screenshots/Recording interface.png b/docs/assets/images/screenshots/Recording interface.png
new file mode 100644
index 00000000..09bd9116
Binary files /dev/null and b/docs/assets/images/screenshots/Recording interface.png differ
diff --git a/docs/assets/images/screenshots/Share link.png b/docs/assets/images/screenshots/Share link.png
new file mode 100644
index 00000000..536c0d0f
Binary files /dev/null and b/docs/assets/images/screenshots/Share link.png differ
diff --git a/docs/assets/images/screenshots/Share modal.png b/docs/assets/images/screenshots/Share modal.png
new file mode 100644
index 00000000..b5e65c7f
Binary files /dev/null and b/docs/assets/images/screenshots/Share modal.png differ
diff --git a/docs/assets/images/screenshots/admin-edit-group-modal.png b/docs/assets/images/screenshots/admin-edit-group-modal.png
new file mode 100644
index 00000000..bf4eb143
Binary files /dev/null and b/docs/assets/images/screenshots/admin-edit-group-modal.png differ
diff --git a/docs/assets/images/screenshots/admin-manage-group-modal.png b/docs/assets/images/screenshots/admin-manage-group-modal.png
new file mode 100644
index 00000000..44e39947
Binary files /dev/null and b/docs/assets/images/screenshots/admin-manage-group-modal.png differ
diff --git a/docs/assets/images/screenshots/admin-manage-group-tags.png b/docs/assets/images/screenshots/admin-manage-group-tags.png
new file mode 100644
index 00000000..e905637b
Binary files /dev/null and b/docs/assets/images/screenshots/admin-manage-group-tags.png differ
diff --git a/docs/assets/images/screenshots/admin-user-groups.png b/docs/assets/images/screenshots/admin-user-groups.png
new file mode 100644
index 00000000..9d0546e0
Binary files /dev/null and b/docs/assets/images/screenshots/admin-user-groups.png differ
diff --git a/docs/assets/images/screenshots/archived-recording.png b/docs/assets/images/screenshots/archived-recording.png
new file mode 100644
index 00000000..bf318ddd
Binary files /dev/null and b/docs/assets/images/screenshots/archived-recording.png differ
diff --git a/docs/assets/images/screenshots/audio-sync-bubble-view.png b/docs/assets/images/screenshots/audio-sync-bubble-view.png
new file mode 100644
index 00000000..e0badae0
Binary files /dev/null and b/docs/assets/images/screenshots/audio-sync-bubble-view.png differ
diff --git a/docs/assets/images/screenshots/audio-sync-simple-view.png b/docs/assets/images/screenshots/audio-sync-simple-view.png
new file mode 100644
index 00000000..b38a2994
Binary files /dev/null and b/docs/assets/images/screenshots/audio-sync-simple-view.png differ
diff --git a/docs/assets/images/screenshots/chat-chinese.png b/docs/assets/images/screenshots/chat-chinese.png
new file mode 100644
index 00000000..fc1d5af9
Binary files /dev/null and b/docs/assets/images/screenshots/chat-chinese.png differ
diff --git a/docs/assets/images/screenshots/chat-interface.png b/docs/assets/images/screenshots/chat-interface.png
new file mode 100644
index 00000000..885e07d5
Binary files /dev/null and b/docs/assets/images/screenshots/chat-interface.png differ
diff --git a/docs/assets/images/screenshots/edit-tags.png b/docs/assets/images/screenshots/edit-tags.png
new file mode 100644
index 00000000..b3670b36
Binary files /dev/null and b/docs/assets/images/screenshots/edit-tags.png differ
diff --git a/docs/assets/images/screenshots/edit-transcription-modal.png b/docs/assets/images/screenshots/edit-transcription-modal.png
new file mode 100644
index 00000000..fb4a49b5
Binary files /dev/null and b/docs/assets/images/screenshots/edit-transcription-modal.png differ
diff --git a/docs/assets/images/screenshots/filters-sidebar-expanded.png b/docs/assets/images/screenshots/filters-sidebar-expanded.png
new file mode 100644
index 00000000..99c0c99e
Binary files /dev/null and b/docs/assets/images/screenshots/filters-sidebar-expanded.png differ
diff --git a/docs/assets/images/screenshots/follow-mode-auto-scroll.png b/docs/assets/images/screenshots/follow-mode-auto-scroll.png
new file mode 100644
index 00000000..03c739f0
Binary files /dev/null and b/docs/assets/images/screenshots/follow-mode-auto-scroll.png differ
diff --git a/docs/assets/images/screenshots/highlighted-transcript-following-simple-dark.png b/docs/assets/images/screenshots/highlighted-transcript-following-simple-dark.png
new file mode 100644
index 00000000..e7b9e787
Binary files /dev/null and b/docs/assets/images/screenshots/highlighted-transcript-following-simple-dark.png differ
diff --git a/docs/assets/images/screenshots/highlighted-transcript-following-simple-light.png b/docs/assets/images/screenshots/highlighted-transcript-following-simple-light.png
new file mode 100644
index 00000000..7be3cc13
Binary files /dev/null and b/docs/assets/images/screenshots/highlighted-transcript-following-simple-light.png differ
diff --git a/docs/assets/images/screenshots/identify-speakers-modal.png b/docs/assets/images/screenshots/identify-speakers-modal.png
new file mode 100644
index 00000000..bb982d9f
Binary files /dev/null and b/docs/assets/images/screenshots/identify-speakers-modal.png differ
diff --git a/docs/assets/images/screenshots/inquire-dark-mode.png b/docs/assets/images/screenshots/inquire-dark-mode.png
new file mode 100644
index 00000000..45d2b2a9
Binary files /dev/null and b/docs/assets/images/screenshots/inquire-dark-mode.png differ
diff --git a/docs/assets/images/screenshots/main-view-notes-tab.png b/docs/assets/images/screenshots/main-view-notes-tab.png
new file mode 100644
index 00000000..80297d4d
Binary files /dev/null and b/docs/assets/images/screenshots/main-view-notes-tab.png differ
diff --git a/docs/assets/images/screenshots/main-view-summary-tab.png b/docs/assets/images/screenshots/main-view-summary-tab.png
new file mode 100644
index 00000000..204281b0
Binary files /dev/null and b/docs/assets/images/screenshots/main-view-summary-tab.png differ
diff --git a/docs/assets/images/screenshots/main-view-with-speakers.png b/docs/assets/images/screenshots/main-view-with-speakers.png
new file mode 100644
index 00000000..7454f3e2
Binary files /dev/null and b/docs/assets/images/screenshots/main-view-with-speakers.png differ
diff --git a/docs/assets/images/screenshots/markdown-editor-fullscreen.png b/docs/assets/images/screenshots/markdown-editor-fullscreen.png
new file mode 100644
index 00000000..911a5a5d
Binary files /dev/null and b/docs/assets/images/screenshots/markdown-editor-fullscreen.png differ
diff --git a/docs/assets/images/screenshots/markdown-editor.png b/docs/assets/images/screenshots/markdown-editor.png
new file mode 100644
index 00000000..a4736dd9
Binary files /dev/null and b/docs/assets/images/screenshots/markdown-editor.png differ
diff --git a/docs/assets/images/screenshots/multilingual-chinese.png b/docs/assets/images/screenshots/multilingual-chinese.png
new file mode 100644
index 00000000..6fcc6dbb
Binary files /dev/null and b/docs/assets/images/screenshots/multilingual-chinese.png differ
diff --git a/docs/assets/images/screenshots/processing-tooltip.png b/docs/assets/images/screenshots/processing-tooltip.png
new file mode 100644
index 00000000..9b76f87e
Binary files /dev/null and b/docs/assets/images/screenshots/processing-tooltip.png differ
diff --git a/docs/assets/images/screenshots/recording-dual-source.png b/docs/assets/images/screenshots/recording-dual-source.png
new file mode 100644
index 00000000..2f15b343
Binary files /dev/null and b/docs/assets/images/screenshots/recording-dual-source.png differ
diff --git a/docs/assets/images/screenshots/recording-single-source.png b/docs/assets/images/screenshots/recording-single-source.png
new file mode 100644
index 00000000..ed7b2679
Binary files /dev/null and b/docs/assets/images/screenshots/recording-single-source.png differ
diff --git a/docs/assets/images/screenshots/recording-upload-modal.png b/docs/assets/images/screenshots/recording-upload-modal.png
new file mode 100644
index 00000000..3872cb95
Binary files /dev/null and b/docs/assets/images/screenshots/recording-upload-modal.png differ
diff --git a/docs/assets/images/screenshots/settings-create-tag-modal.png b/docs/assets/images/screenshots/settings-create-tag-modal.png
new file mode 100644
index 00000000..448b0be2
Binary files /dev/null and b/docs/assets/images/screenshots/settings-create-tag-modal.png differ
diff --git a/docs/assets/images/screenshots/share-notes-view.png b/docs/assets/images/screenshots/share-notes-view.png
new file mode 100644
index 00000000..bb3ec394
Binary files /dev/null and b/docs/assets/images/screenshots/share-notes-view.png differ
diff --git a/docs/assets/images/screenshots/share-summary-view.png b/docs/assets/images/screenshots/share-summary-view.png
new file mode 100644
index 00000000..db78e42a
Binary files /dev/null and b/docs/assets/images/screenshots/share-summary-view.png differ
diff --git a/docs/assets/images/screenshots/share-translated.png b/docs/assets/images/screenshots/share-translated.png
new file mode 100644
index 00000000..3bc38d6a
Binary files /dev/null and b/docs/assets/images/screenshots/share-translated.png differ
diff --git a/docs/assets/images/screenshots/speaker-identification-voice-profiles.png b/docs/assets/images/screenshots/speaker-identification-voice-profiles.png
new file mode 100644
index 00000000..71291f93
Binary files /dev/null and b/docs/assets/images/screenshots/speaker-identification-voice-profiles.png differ
diff --git a/docs/assets/images/screenshots/speakers-management-voice-profiles.png b/docs/assets/images/screenshots/speakers-management-voice-profiles.png
new file mode 100644
index 00000000..a11df7f8
Binary files /dev/null and b/docs/assets/images/screenshots/speakers-management-voice-profiles.png differ
diff --git a/docs/assets/images/screenshots/tag-management-enhanced-badges.png b/docs/assets/images/screenshots/tag-management-enhanced-badges.png
new file mode 100644
index 00000000..577df1a5
Binary files /dev/null and b/docs/assets/images/screenshots/tag-management-enhanced-badges.png differ
diff --git a/docs/assets/images/screenshots/tag-management.png b/docs/assets/images/screenshots/tag-management.png
new file mode 100644
index 00000000..8bed8b4a
Binary files /dev/null and b/docs/assets/images/screenshots/tag-management.png differ
diff --git a/docs/assets/images/screenshots/template-selector.png b/docs/assets/images/screenshots/template-selector.png
new file mode 100644
index 00000000..5bb9b0cd
Binary files /dev/null and b/docs/assets/images/screenshots/template-selector.png differ
diff --git a/docs/assets/images/screenshots/ui-chinese.png b/docs/assets/images/screenshots/ui-chinese.png
new file mode 100644
index 00000000..e5c3edab
Binary files /dev/null and b/docs/assets/images/screenshots/ui-chinese.png differ
diff --git a/docs/assets/images/screenshots/upload-interface.png b/docs/assets/images/screenshots/upload-interface.png
new file mode 100644
index 00000000..2874c035
Binary files /dev/null and b/docs/assets/images/screenshots/upload-interface.png differ
diff --git a/docs/features.md b/docs/features.md
index 504e71da..87f3e177 100644
--- a/docs/features.md
+++ b/docs/features.md
@@ -12,6 +12,22 @@ Speakr supports multiple transcription engines to match your needs and budget. U
When using the [ASR endpoint](getting-started.md#option-b-custom-asr-endpoint-configuration), Speakr automatically identifies different speakers in your recordings. If you encounter issues, check the [troubleshooting guide](troubleshooting.md#speaker-identification-not-working). Each speaker gets a unique label that you can later customize with actual names. The system remembers these speaker profiles, building a library that improves identification accuracy over time. Manage your speaker library in [account settings](user-guide/settings.md). This feature transforms multi-person meetings from walls of text into organized conversations.
+### Interactive Audio Synchronization
+
+Speakr provides seamless bidirectional synchronization between audio playback and transcript text for recordings with speaker diarization. Click any part of the transcript to jump directly to that moment in the audio, making it easy to review specific sections. As the audio plays, the system automatically highlights the currently spoken text in real-time with smooth visual feedback. Enable auto-scroll follow mode to keep the active segment centered in view, allowing you to follow along effortlessly during playback.
+
+<div style="max-width: 800px; margin: 2em auto;">
+ <img src="assets/images/screenshots/audio-sync-simple-view.png" alt="Audio synchronization in simple view" style="border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1);">
+ <p style="text-align: center; margin-top: 0.5rem; font-style: italic; color: #666;">Active segment highlighting in simple view - click any text to jump to that moment in audio</p>
+</div>
+
+<div style="max-width: 800px; margin: 2em auto;">
+ <img src="assets/images/screenshots/follow-mode-auto-scroll.png" alt="Auto-scroll follow mode" style="border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1);">
+ <p style="text-align: center; margin-top: 0.5rem; font-style: italic; color: #666;">Auto-scroll follow mode keeps the current segment centered during playback</p>
+</div>
+
+This interactive experience works across both simple and bubble view modes. Learn more about [audio synchronization features](user-guide/transcripts.md#audio-synchronization-and-follow-mode).
+
### Language Support
Transcribe content in dozens of languages with automatic detection or manual selection. Major languages like English, Spanish, French, German, and Chinese receive excellent support with high accuracy. The system handles multilingual content gracefully, switching between languages as needed within the same recording.
@@ -40,19 +56,65 @@ Search across all your recordings using natural language questions instead of ke
Organize recordings with a flexible [tagging system](user-guide/settings.md#tag-management-tab) that goes beyond simple labels. Tags can include [custom AI prompts](admin-guide/prompts.md) for specialized processing. Each tag can carry [custom AI prompts](admin-guide/prompts.md) and transcription settings, enabling automatic specialized processing based on content type, automatically applying specialized processing to tagged recordings. Tags use colors for visual organization and stack intelligently when multiple tags apply to the same recording.
+### Retention Policies and Auto-Deletion
+
+Implement intelligent data lifecycle management with flexible retention policies. Set a global retention period for automatic cleanup of old recordings, with the choice to delete just audio files (preserving valuable transcriptions) or complete recordings. Tags can override global retention with custom retention periods - keep legal records for 7 years, marketing content for 6 months, and general meetings for 90 days, all through tag-level configuration. Protected tags prevent specific recordings from ever being auto-deleted, perfect for compliance requirements and permanent archives. Group tags can enforce group-wide retention policies. The system provides preview functionality to see exactly what will be deleted before any changes occur, and administrators can control whether users can delete their own recordings or if deletion requires admin approval.
+
+**Integrated Speaker Data Cleanup**: When recordings are deleted through auto-deletion or manual deletion, the system automatically manages associated speaker voice profiles to maintain privacy compliance. Orphaned speaker profiles (those with no remaining recordings) are automatically removed during scheduled cleanup, ensuring biometric voice data is not retained unnecessarily. This automatic cleanup works with both audio-only and full recording deletion modes, providing GDPR-compliant data minimization without requiring manual intervention.
+
### Speaker Management
Build and maintain a library of speaker profiles that persist across recordings. [Identify speakers](user-guide/transcripts.md#speaker-identification) after each transcription to build your library. Once identified, speakers are remembered and suggested in future recordings. The system tracks usage statistics, showing how often each speaker appears and when they were last identified. Bulk management tools help maintain a clean, organized speaker library.
+**Voice Profile Recognition**: The system builds voice recognition profiles from speaker identifications across multiple recordings. These profiles use 256-dimensional voice embeddings to suggest speaker matches when processing new recordings, making speaker identification faster and more consistent. The voice matching system calculates similarity scores to help identify speakers across recordings, even when audio quality varies. Voice profiles are automatically updated as more recordings are processed, improving recognition accuracy over time.
+
+**Privacy-First Cleanup**: Voice profiles are automatically managed alongside recording retention policies. When all recordings containing a particular speaker are deleted, the speaker's voice profile is automatically removed during the next scheduled cleanup. This ensures biometric voice data is only retained when actively used, maintaining compliance with data minimization principles. The cleanup process is fully automatic and requires no manual intervention when auto-deletion is enabled.
+
### Custom Prompts
Shape AI behavior with [custom prompts](admin-guide/prompts.md) at multiple levels. Understand the [prompt hierarchy](admin-guide/prompts.md#understanding-prompt-hierarchy) for effective configuration. Personal prompts apply to all your recordings, while tag-specific prompts activate for particular content types. The hierarchical system ensures the right prompt applies to each recording, with intelligent stacking when multiple prompts are relevant.
## Sharing and Collaboration
+Speakr provides comprehensive collaboration features that scale from individual sharing to organization-wide group management. Choose the right sharing method for each situation - collaborate with specific colleagues through user-to-user sharing, automate access for groups through group tags, or create public links for external stakeholders.
+
+### Internal Sharing (User-to-User)
+
+Share recordings directly with other users in your Speakr instance through secure, tracked internal shares. Search for colleagues by username and grant precisely the access level they need - view-only for information distribution, edit permissions for collaborative documentation, or re-share rights for group coordinators who need to extend access to others.
+
+Recipients with view access can read transcriptions, review summaries and notes, listen to audio, and use the AI chat feature to explore content. Edit permissions add the ability to modify metadata, update notes, and manage tags. Re-share permissions enable recipients to share with additional users and manage those downstream shares.
+
+Each user can maintain completely private personal notes on shared recordings. These notes remain invisible to the recording owner and other recipients, providing a secure space for individual observations and follow-ups. Access revocation is immediate and thorough - when you revoke someone's access, they lose all capabilities and their personal notes are automatically removed.
+
+The centralized share management interface shows all current shares with each recipient's permission level and share creation date. Modify permissions or revoke access instantly, maintaining complete control over collaborative access throughout the recording's lifecycle. Read more in the [Sharing & Collaboration guide](user-guide/sharing.md).
+
+### Group Management
+
+Organize users into groups for streamlined collaboration on projects, departments, or any grouping that regularly works together. Groups eliminate the tedious process of individually sharing each recording with multiple colleagues by automating access through group tags.
+
+Full instance administrators create groups and can assign group admin roles to group leads or managers. Group admins can manage membership, add or remove users, change roles, and control their group's organizational structure without requiring global administrative access. This distributed administration scales group management while maintaining security boundaries.
+
+Group members see group-specific tags in their interface and automatically receive recordings when any teammate applies group tags. This creates a collaborative space where information flows naturally to everyone who needs it. Groups integrate seamlessly with personal organization - users maintain their private tags alongside group tags, creating systems that serve both individual and group needs. Learn more in the [Group Collaboration guide](user-guide/groups.md).
+
+### Group Tags with Auto-Share
+
+Group tags are the automation engine for group collaboration. Unlike personal tags that organize individual content, group tags trigger automatic sharing with all group members when applied to any recording.
+
+Any group member can apply group tags to their recordings. The moment a group tag is applied, Speakr creates internal shares for all group members (excluding the owner), granting view and edit permissions. This automatic sharing happens intelligently - existing shares aren't duplicated, group leads can create admin-only tags for sensitive content, and the system tracks all sharing for audit purposes.
+
+Group tags appear with a distinctive users icon (👥) throughout the interface, making group content immediately recognizable. Apply multiple group tags to share with multiple groups simultaneously, enabling cross-functional collaboration. Custom retention policies can be attached to group tags, automatically managing content lifecycle based on group-specific requirements.
+
+Advanced auto-sharing options let group admins control sharing scope. Share with all group members for full collaboration, or restrict to group leads only for sensitive content requiring administrative oversight. Retroactive syncing can share existing group-tagged recordings with current members after group restructuring. See the [Group Management guide](admin-guide/group-management.md) for administrative details.
+
### Secure Share Links
-Generate cryptographically secure links to [share recordings](user-guide/sharing.md) with people outside your Speakr instance. Note the [requirements for sharing](user-guide/sharing.md#requirements-for-sharing). Control exactly what recipients see - include or exclude summaries and notes based on your needs. Share links work on any device without requiring accounts or authentication.
+Generate cryptographically secure links to [share recordings](user-guide/sharing.md) with people outside your Speakr instance - clients, partners, or anyone who needs access without an account. Each link uses unguessable tokens and works over HTTPS for security, providing read-only access to exactly the content you choose to share.
+
+Control precisely what recipients see by including or excluding summaries and notes. The transcription is always included as the core content, but you decide whether to add AI-generated insights or your personal annotations. Recipients get a clean, professional view optimized for content consumption without access to your administrative interface or other recordings.
+
+Administrators can control public sharing at multiple levels. Disable public sharing globally to prevent all public link creation, or leave it enabled and grant permissions per-user for granular control. This flexibility supports organizations with varying security requirements - some users might need external sharing capabilities while others should only share internally.
+
+Share links remain valid until explicitly revoked through the central share management interface. Modify what's included in a share without generating new links, or delete shares instantly to revoke access. All your shared recordings are tracked in one interface for easy management and audit. Security best practices are enforced - HTTPS is required for sharing operations, and the system warns against posting links publicly or sharing sensitive content inappropriately.
### Export Options
@@ -60,7 +122,7 @@ Export recordings in multiple formats for different purposes. Generate Word docu
### Real-Time Monitoring
-Track all your shared recordings from a central dashboard. See what's been shared, when, and with what permissions. Modify share settings without generating new links, or instantly revoke access when shares are no longer appropriate.
+Track all your shared recordings from a central dashboard. See what's been shared, when, and with what permissions. Modify share settings without generating new links, or instantly revoke access when shares are no longer appropriate. View shared recordings alongside your own content with clear visual indicators showing ownership and group affiliation.
## Advanced Capabilities
@@ -72,6 +134,10 @@ Handle large audio files that exceed API limits through intelligent chunking. Se
Set up a watched directory where dropped audio files are automatically processed. Configure this in [system settings](admin-guide/system-settings.md) for automated workflows. Perfect for automation workflows or batch processing, the black hole directory monitors for new files and queues them for transcription without manual intervention.
+### Automated Export
+
+Automatically export completed transcriptions and summaries to markdown files after processing. Configure the export directory to point to your Obsidian vault, Logseq directory, or any other note-taking system for seamless integration. Choose what to export (transcription, summary, or both) and let Speakr maintain synchronized copies of your recordings in your preferred format. Custom export templates allow you to format the output to match your note-taking workflow. Exports are organized in per-user subdirectories for multi-user instances.
+
### Custom ASR Configuration
Fine-tune transcription for specific scenarios with custom ASR settings. See [ASR configuration](troubleshooting.md#asr-endpoint-returns-405-or-404-errors) for common setup issues. Set expected speaker counts for different meeting types. Configure specialized models for technical vocabulary or specific accents. Apply these settings automatically through the tagging system.
@@ -94,7 +160,7 @@ Access Speakr from any device with interfaces that adapt to screen size. Desktop
### Multi-User Support
-Run a single Speakr instance for your entire team with isolated user spaces. See [user management](admin-guide/user-management.md) for details. The [FAQ](faq.md#can-multiple-people-use-the-same-speakr-instance) explains the multi-user architecture. Each user maintains their own recordings, settings, and speaker libraries. Administrators manage users, monitor usage, and configure system-wide settings without accessing individual recordings.
+Run a single Speakr instance for your entire group with isolated user spaces. See [user management](admin-guide/user-management.md) for details. The [FAQ](faq.md#can-multiple-people-use-the-same-speakr-instance) explains the multi-user architecture. Each user maintains their own recordings, settings, and speaker libraries. Administrators manage users, monitor usage, and configure system-wide settings without accessing individual recordings.
### System Monitoring
diff --git a/docs/getting-started.md b/docs/getting-started.md
index 094306ac..bb36dac0 100644
--- a/docs/getting-started.md
+++ b/docs/getting-started.md
@@ -133,6 +133,53 @@ Log in using the admin credentials you configured in Step 4. You should now see
After logging in, you can immediately start using Speakr. Click the "New Recording" button in the top navigation to either upload an existing audio file or start a [live recording](user-guide/recording.md). For detailed instructions, see the [recording guide](user-guide/recording.md). For uploads, Speakr supports [common audio formats](faq.md#what-audio-formats-does-speakr-support) like MP3, M4A, WAV, and more, with files up to 500MB by default. You can adjust this limit in [system settings](admin-guide/system-settings.md). For live recording, you can capture from your microphone, system audio, or both simultaneously.
+## Setting Up Collaboration (Optional)
+
+If you're using Speakr with your family or team, you can leverage powerful collaboration features including groups, group tags, and automatic sharing. These features work great for project teams, departments, or families who want to automatically share certain types of recordings.
+
+### Creating a Group
+
+As an admin, you can create groups to organize users who regularly collaborate:
+
+1. Navigate to **Admin → User Groups** in the admin dashboard
+2. Click "Create New Group" and enter a group name (e.g., "Engineering Team", "Family", "Sales Department")
+3. Optionally assign a group lead who can manage group settings
+4. Add members by searching for usernames and clicking to add them
+5. Save the group
+
+### Creating Group Tags
+
+Group tags automatically share recordings with all group members when applied:
+
+1. While editing or creating a group, navigate to the **Tags** section
+2. Click "Create Group Tag" and enter:
+ - **Tag Name**: What the tag will be called (e.g., "Team Meetings", "Family Events")
+ - **Color**: Choose a color for easy visual identification
+ - **Custom Prompt** (optional): AI instructions for how to summarize recordings with this tag
+ - **Protected**: Enable to prevent automatic deletion by retention policies
+ - **Retention Days** (optional): Auto-delete recordings after this many days (leave blank to keep forever)
+3. Save the tag
+
+When any group member applies this tag to a recording, all group members automatically get access to it.
+
+### Sharing a Recording with a Group
+
+There are two ways to share recordings with groups:
+
+**Method 1: Using Group Tags** (Automatic)
+1. When uploading or after creating a recording, click the tag icon
+2. Select any group tag you have access to
+3. All group members automatically receive access to this recording
+4. Future group members will NOT see historical recordings, only new ones tagged after they join
+
+**Method 2: Individual Sharing** (Manual)
+1. Open any recording and click the share icon (users icon) in the toolbar
+2. Search for and select users to share with
+3. Choose permission level: view-only, edit, or reshare
+4. Each user receives immediate access
+
+For more details on collaboration features, see the [Sharing & Collaboration guide](user-guide/sharing.md).
+
## Optional Features
### Enable Inquire Mode
diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md
index 6966052b..2dc010a3 100644
--- a/docs/getting-started/installation.md
+++ b/docs/getting-started/installation.md
@@ -88,13 +88,35 @@ WHISPER_MODEL=whisper-1
#### For Custom ASR Endpoint with Speaker Diarization
-If you want speaker diarization to identify who's speaking in your recordings, you'll need to use an ASR webservice endpoint. **This requires running an additional Docker container** (`onerahmet/openai-whisper-asr-webservice`) alongside Speakr, but provides powerful features for meeting transcriptions and multi-speaker recordings.
+If you want speaker diarization to identify who's speaking in your recordings, you'll need to use an ASR webservice endpoint. **This requires running an additional Docker container** alongside Speakr, but provides powerful features for meeting transcriptions and multi-speaker recordings.
-> **Important:** Before proceeding with this configuration, you'll need to set up the ASR service container. See [Running ASR Service for Speaker Diarization](#running-asr-service-for-speaker-diarization) for complete instructions on deploying both containers together or separately.
+**ASR Service Options:**
-Download the ASR configuration template:
+1. **WhisperX ASR Service (Recommended for Voice Profiles)** - Required for AI-powered voice profile features using speaker embeddings
+ - Repository: [murtaza-nasir/whisperx-asr-service](https://github.com/murtaza-nasir/whisperx-asr-service)
+ - Uses `pyannote/speaker-diarization-community-1` model with exclusive diarization
+ - Supports 256-dimensional speaker embeddings for voice profile identification
+ - Better timestamp alignment between speakers and words
+ - **Required for:** Voice profiles, automatic speaker recognition, speaker embeddings
+ - **Environment file:** `config/env.whisperx.example`
+
+2. **OpenAI Whisper ASR Webservice (Basic Diarization)** - For basic speaker diarization without voice profiles
+ - Repository: [ahmetoner/openai-whisper-asr-webservice](https://github.com/ahmetoner/openai-whisper-asr-webservice)
+ - Uses `pyannote/speaker-diarization-3.1` model
+ - Simpler setup, less resource intensive
+ - **Supports:** Basic speaker identification (Speaker 1, Speaker 2, etc.)
+ - **Does not support:** Voice profiles, speaker embeddings, automatic speaker recognition
+ - **Environment file:** `config/env.asr.example`
+
+> **Important:** Before proceeding with this configuration, you'll need to set up one of the ASR service containers. See [Running ASR Service for Speaker Diarization](#running-asr-service-for-speaker-diarization) for complete instructions on deploying both containers together or separately.
+
+Download the appropriate ASR configuration template:
```bash
+# For WhisperX ASR Service (with voice profiles):
+wget https://raw.githubusercontent.com/murtaza-nasir/speakr/master/config/env.whisperx.example -O .env
+
+# OR for basic ASR (without voice profiles):
wget https://raw.githubusercontent.com/murtaza-nasir/speakr/master/config/env.asr.example -O .env
```
@@ -102,10 +124,17 @@ The ASR configuration enables the custom endpoint and tells Speakr where to find
```bash
USE_ASR_ENDPOINT=true
-ASR_BASE_URL=http://your-asr-service:9000
+
+# For WhisperX ASR Service:
+ASR_BASE_URL=http://whisperx-asr:9000
+
+# OR for basic ASR Webservice:
+ASR_BASE_URL=http://whisper-asr:9000
```
-The ASR_BASE_URL depends on your deployment architecture. If you're running the ASR service in the same Docker Compose stack as Speakr, use the service name from your docker-compose.yml file, like `http://whisper-asr:9000`. This uses Docker's internal networking for communication. If the ASR service is running elsewhere, use its full URL with the appropriate IP address or domain name.
+The ASR_BASE_URL depends on your deployment architecture:
+- **Same Docker Compose stack:** Use the service name (e.g., `http://whisperx-asr:9000` or `http://whisper-asr:9000`) - Docker's internal networking
+- **Separate machine:** Use the full URL with IP address or domain name (e.g., `http://192.168.1.100:9000`)
Speaker diarization is automatically enabled when using ASR endpoints. The system will identify different speakers in your recordings and label them as Speaker 1, Speaker 2, and so on. You can optionally override the default speaker detection settings by uncommenting and adjusting ASR_MIN_SPEAKERS and ASR_MAX_SPEAKERS in your environment file.
@@ -129,7 +158,7 @@ TIMEZONE="America/New_York"
LOG_LEVEL="INFO"
```
-Setting `ALLOW_REGISTRATION=false` means only the admin can create new user accounts, which is recommended for private installations where you want to control access. If you're running Speakr for a team or family, this prevents random people from creating accounts. The timezone setting affects how dates and times are displayed throughout the interface, so set it to your local timezone for convenience. The log level controls how much information Speakr writes to its logs. Use `INFO` during initial setup and testing to see what's happening, then switch to `ERROR` for production to reduce log volume and improve performance.
+Setting `ALLOW_REGISTRATION=false` means only the admin can create new user accounts, which is recommended for private installations where you want to control access. If you're running Speakr for a group or family, this prevents random people from creating accounts. The timezone setting affects how dates and times are displayed throughout the interface, so set it to your local timezone for convenience. The log level controls how much information Speakr writes to its logs. Use `INFO` during initial setup and testing to see what's happening, then switch to `ERROR` for production to reduce log volume and improve performance.
### Step 5: Configure Advanced Features
@@ -222,32 +251,98 @@ If transcription fails, check the Docker logs for API authentication errors or c
### Running ASR Service for Speaker Diarization
-If you need speaker diarization to identify different speakers in your recordings, you'll need to run an ASR service alongside Speakr. This involves deploying an additional Docker container (`onerahmet/openai-whisper-asr-webservice`) that provides the ASR endpoint. The recommended approach is running both containers in the same Docker Compose stack for simplified networking and management.
+If you need speaker diarization to identify different speakers in your recordings, you'll need to run an ASR service alongside Speakr. There are two options depending on whether you need voice profile features:
+
+#### Option 1: WhisperX ASR Service (Recommended - Supports Voice Profiles)
+
+**Use this if you want:**
+- AI-powered speaker voice profiles with automatic recognition
+- 256-dimensional speaker embeddings
+- Better speaker-to-word timestamp alignment
+- Exclusive diarization for cleaner speaker transitions
+
+**Prerequisites:**
+1. **Hugging Face Account & Model Access** - Visit and accept terms for ALL models:
+ - [pyannote/speaker-diarization-community-1](https://huggingface.co/pyannote/speaker-diarization-community-1)
+ - [pyannote/speaker-diarization-3.1](https://huggingface.co/pyannote/speaker-diarization-3.1)
+ - [pyannote/segmentation-3.0](https://huggingface.co/pyannote/segmentation-3.0)
+
+2. **Generate HF Token** - Create a read-access token at [Hugging Face Settings](https://huggingface.co/settings/tokens)
+
+3. **GPU Requirements** - NVIDIA GPU with 14GB+ VRAM for large-v3 model (RTX 3090/4090 recommended)
+
+**Setup Instructions:**
+
+Clone the WhisperX ASR Service repository:
+```bash
+git clone https://github.com/murtaza-nasir/whisperx-asr-service.git
+cd whisperx-asr-service
+
+# Copy environment file
+cp .env.example .env
+
+# Edit .env and add your Hugging Face token
+nano .env # Set HF_TOKEN=hf_xxxxx...
+
+# Build and start
+docker compose up -d
+
+# Verify it's running
+curl http://localhost:9000/health
+```
+
+See the [WhisperX ASR Service README](https://github.com/murtaza-nasir/whisperx-asr-service#readme) for detailed configuration options, troubleshooting, and performance tuning.
+
+#### Option 2: OpenAI Whisper ASR Webservice (Basic Diarization Only)
-First, you'll need a Hugging Face token to access the speaker diarization models. Create an account at Hugging Face, generate an access token, and importantly, visit the model pages for pyannote/segmentation-3.0 and pyannote/speaker-diarization-3.1 to accept their terms. These are gated models that require explicit approval.
+**Use this if you:**
+- Only need basic speaker identification (Speaker 1, Speaker 2, etc.)
+- Don't need voice profiles or speaker embeddings
+- Want simpler setup with lower resource requirements
-Here's a complete Docker Compose configuration that includes both services:
+**Prerequisites:**
+1. **Hugging Face Account & Model Access** - Visit and accept terms:
+ - [pyannote/speaker-diarization-3.1](https://huggingface.co/pyannote/speaker-diarization-3.1)
+ - [pyannote/segmentation-3.0](https://huggingface.co/pyannote/segmentation-3.0)
+
+2. **Generate HF Token** - Create a read-access token at [Hugging Face Settings](https://huggingface.co/settings/tokens)
+
+**Setup Instructions:**
+
+Visit the [ahmetoner/whisper-asr-webservice repository](https://github.com/ahmetoner/whisper-asr-webservice) for complete setup instructions.
+
+#### Deploying ASR Service with Speakr
+
+Once you've chosen and set up your ASR service, you can deploy it alongside Speakr in several ways:
+
+**Same Machine - Combined Docker Compose (Recommended)**
+
+Example with WhisperX ASR Service (for voice profiles):
```yaml
services:
- whisper-asr:
- image: onerahmet/openai-whisper-asr-webservice:latest-gpu
- container_name: whisper-asr-webservice
+ whisperx-asr:
+ build:
+ context: ./whisperx-asr-service
+ dockerfile: Dockerfile
+ container_name: whisperx-asr-api
+ restart: unless-stopped
ports:
- "9000:9000"
environment:
- - ASR_MODEL=distil-large-v3
- - ASR_COMPUTE_TYPE=int8
- - ASR_ENGINE=whisperx
+ - DEVICE=cuda
+ - COMPUTE_TYPE=float16
+ - BATCH_SIZE=16
- HF_TOKEN=your_huggingface_token_here
deploy:
resources:
reservations:
devices:
- driver: nvidia
+ count: all
capabilities: [gpu]
- device_ids: ["0"]
- restart: unless-stopped
+ volumes:
+ - whisperx-cache:/.cache
networks:
- speakr-network
@@ -263,18 +358,28 @@ services:
- ./uploads:/data/uploads
- ./instance:/data/instance
depends_on:
- - whisper-asr
+ - whisperx-asr
networks:
- speakr-network
networks:
speakr-network:
driver: bridge
+
+volumes:
+ whisperx-cache:
+ driver: local
+```
+
+In Speakr's `.env` file:
+```bash
+USE_ASR_ENDPOINT=true
+ASR_BASE_URL=http://whisperx-asr:9000
```
-> **Note for Mac users:** GPU passthrough doesn't work on macOS due to Docker's architecture. Use `onerahmet/openai-whisper-asr-webservice:latest` (CPU version) instead of `:latest-gpu` and remove the `deploy` section. The ASR service will use CPU processing, which is slower but fully functional. See the [FAQ](../faq.md#can-i-use-the-asr-webservice-for-speaker-diarization-on-mac) for Mac-specific configuration examples.
+> **Note for Mac users:** GPU passthrough doesn't work on macOS due to Docker's architecture. Use CPU mode by setting `DEVICE=cpu` and `COMPUTE_TYPE=float32` in the environment variables. The ASR service will use CPU processing, which is slower but fully functional.
-When running both services in the same Docker Compose file, containers communicate using service names. In your `.env` file, set `ASR_BASE_URL=http://whisper-asr:9000` using the service name, not localhost or an IP address. This is a common source of confusion but is how Docker networking works.
+**Important:** When running both services in the same Docker Compose file, use the service name (e.g., `whisperx-asr` or `whisper-asr`) in `ASR_BASE_URL`, not `localhost` or an IP address.
#### Running Services in Separate Docker Compose Files
diff --git a/docs/index.md b/docs/index.md
index 64ea06ed..d0d84284 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -3,9 +3,20 @@
Speakr is a powerful self-hosted transcription platform that helps you capture, transcribe, and understand your audio content. Whether you're recording meetings, interviews, lectures, or personal notes, Speakr transforms spoken words into valuable, searchable knowledge.
<div style="max-width: 80%; margin: 2em auto;">
- <img src="assets/images/screenshots/Filters.png" alt="Main Interface" style="border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1);">
+ <img src="assets/images/screenshots/Main view.png" alt="Main Interface" style="border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1);">
</div>
+!!! warning "Latest Release: v0.5.9 - Major Update"
+ **⚠️ IMPORTANT:** This is a **major release** with significant architectural changes. **Before upgrading:**
+
+ - **BACKUP YOUR DATA** - Database schema changes require migration
+ - **Review new environment variables** - Many features require `.env` configuration
+ - **Test in development first** - Major refactoring may affect existing workflows
+
+ **Key Environment Variables:** `ENABLE_INTERNAL_SHARING`, `SHOW_USERNAMES_IN_UI`, `USERS_CAN_DELETE`, `ENABLE_AUTO_DELETION`, `GLOBAL_RETENTION_DAYS`, `ENABLE_AUTO_EXPORT`, `ENABLE_PUBLIC_SHARING`
+
+ See the [configuration guide](getting-started/installation.md#configuration-updates) for complete setup instructions. [View full release notes](https://github.com/murtaza-nasir/speakr/releases/tag/v0.5.9)
+
## Quick Navigation
<div class="grid cards">
@@ -69,6 +80,7 @@ Speakr is a powerful self-hosted transcription platform that helps you capture,
<ul>
<li><a href="features#language-support">Multi-language support</a></li>
<li><a href="features#speaker-diarization">Speaker identification</a></li>
+ <li><a href="features#speaker-management">Voice profiles with AI recognition</a></li>
<li>Custom vocabularies</li>
</ul>
</div>
@@ -86,8 +98,8 @@ Speakr is a powerful self-hosted transcription platform that helps you capture,
<h4>📊 Organization</h4>
<ul>
<li><a href="features#tagging-system">Smart tagging system</a></li>
- <li><a href="admin-guide/prompts">Custom AI prompts</a></li>
- <li><a href="features#speaker-management">Participant tracking</a></li>
+ <li><a href="admin-guide/prompts">Custom AI prompts with stacking</a></li>
+ <li><a href="features#speaker-management">Speaker voice profiles with auto-cleanup</a></li>
</ul>
</div>
@@ -110,9 +122,41 @@ Speakr is a powerful self-hosted transcription platform that helps you capture,
</div>
</div>
+## Interactive Audio Synchronization
+
+Experience seamless bidirectional synchronization between your audio and transcript. Click any part of the transcript to jump directly to that moment in the audio, or watch as the system automatically highlights the currently spoken text as the audio plays. Enable auto-scroll follow mode to keep the active segment centered in view, creating an effortless reading experience for even the longest recordings.
+
+<div style="max-width: 90%; margin: 2em auto;">
+ <img src="assets/images/screenshots/audio-sync-bubble-view.png" alt="Real-time audio-transcript synchronization" style="border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1);">
+ <p style="text-align: center; margin-top: 0.5rem; font-style: italic; color: #666;">Real-time transcript highlighting synchronized with audio playback, with auto-scroll follow mode</p>
+</div>
+
+Learn more about [audio synchronization features](user-guide/transcripts.md#audio-synchronization-and-follow-mode) in the user guide.
+
+!!! tip "Transform Your Recordings with Custom Tag Prompts"
+ Tags aren't just for organization - they transform content. Create a "Recipe" tag to convert cooking narration into formatted recipes. Use "Study Notes" tags to turn lecture recordings into organized outlines. Stack tags like "Client Meeting" + "Legal Review" for combined analysis. Learn more in the [Custom Prompts guide](admin-guide/prompts#creative-tag-prompt-use-cases).
+
## Latest Updates
-!!! info "Version 0.5.8 - Latest Release"
+!!! warning "Version 0.5.9 - Major Release"
+ **⚠️ Backup your data before upgrading!** This release includes database migrations and architectural changes.
+
+ **New Features:**
+ - **Complete Internal Sharing System** - Share recordings with users with granular permissions (view/edit/reshare), personal notes, and independent status tracking
+ - **Group Management & Collaboration** - Create groups with leads, group tags that auto-share recordings, custom retention policies per group
+ - **Speaker Voice Profiles** - AI-powered speaker recognition with 256-dimensional embeddings (requires WhisperX ASR)
+ - **Audio-Transcript Synchronization** - Click-to-jump, auto-highlight, and follow mode for interactive navigation
+ - **Auto-Deletion & Retention System** - Global and group-level retention policies, tag protection, per-recording exemptions
+ - **Automated Export** - Auto-export transcriptions to markdown for Obsidian, Logseq, and other note-taking apps
+ - **Permission System** - Fine-grained access control with user deletion rights, public sharing permissions, role-based access
+ - **Modular Architecture** - Backend refactored into blueprints, frontend composables for shared logic
+ - **UI/UX Enhancements** - Compact controls, inline editing, unified toast notifications, improved badges
+ - **Enhanced Internationalization** - 29 new tooltip translations across all languages (EN, DE, ES, FR, ZH)
+
+ **Required `.env` variables:** See [configuration guide](getting-started/installation.md#configuration-updates)
+
+ Previous release (v0.5.8):
+
- **Inline Transcript Editing** - Edit speaker assignments and text directly in the speaker identification modal
- **Add Speaker Functionality** - Dynamically add new speakers during transcript review
- **Enhanced Speaker Modal** - Improved UX with hover-based edit controls and real-time updates
diff --git a/docs/screenshots.md b/docs/screenshots.md
index 579cfb6a..61559499 100644
--- a/docs/screenshots.md
+++ b/docs/screenshots.md
@@ -8,21 +8,28 @@ Explore Speakr's powerful features through our visual gallery. Click on any imag
<div class="screenshot-grid">
<div class="screenshot-item">
- <img src="../assets/images/screenshots/Filters.png" alt="Main Dashboard with Filters" />
- <p class="caption">Main dashboard with advanced filtering options</p>
+ <img src="../assets/images/screenshots/Main view.png" alt="Main Dashboard" />
+ <p class="caption">Main dashboard with bubble chat interface</p>
</div>
-
+
<div class="screenshot-item">
- <img src="../assets/images/screenshots/main view no diarization.png" alt="Simple Transcription View" />
- <p class="caption">Clean interface for simple transcriptions</p>
+ <img src="../assets/images/screenshots/filters-sidebar-expanded.png" alt="Expanded Filters" />
+ <p class="caption">Advanced filtering options in expanded sidebar</p>
</div>
</div>
### Multi-language Support
-<div class="screenshot-item">
- <img src="../assets/images/screenshots/Multilingual.png" alt="Multi-language Interface" />
- <p class="caption">Full internationalization with support for 5 languages</p>
+<div class="screenshot-grid">
+ <div class="screenshot-item">
+ <img src="../assets/images/screenshots/ui-chinese.png" alt="Chinese UI" />
+ <p class="caption">Full interface in Chinese with language switching</p>
+ </div>
+
+ <div class="screenshot-item">
+ <img src="../assets/images/screenshots/multilingual-chinese.png" alt="Multilingual Chat" />
+ <p class="caption">AI chat and transcription translation in multiple languages</p>
+ </div>
</div>
## Recording & Upload
@@ -31,13 +38,13 @@ Explore Speakr's powerful features through our visual gallery. Click on any imag
<div class="screenshot-grid">
<div class="screenshot-item">
- <img src="../assets/images/screenshots/new recording view.png" alt="Recording Interface" />
+ <img src="../assets/images/screenshots/Recording interface.png" alt="Recording Interface" />
<p class="caption">Upload or record audio directly in your browser</p>
</div>
-
+
<div class="screenshot-item">
- <img src="../assets/images/screenshots/live recording view with notes.png" alt="Live Recording with Notes" />
- <p class="caption">Take notes while recording in real-time</p>
+ <img src="../assets/images/screenshots/upload-interface.png" alt="File Upload Interface" />
+ <p class="caption">Multi-file drag and drop with advanced options and tag selection</p>
</div>
</div>
@@ -45,35 +52,61 @@ Explore Speakr's powerful features through our visual gallery. Click on any imag
<div class="screenshot-grid">
<div class="screenshot-item">
- <img src="../assets/images/screenshots/record from tab.png" alt="Record from Tab" />
- <p class="caption">Record audio from a specific browser tab</p>
+ <img src="../assets/images/screenshots/recording-dual-source.png" alt="Dual Source Recording" />
+ <p class="caption">Record both system audio and microphone simultaneously</p>
</div>
-
+
<div class="screenshot-item">
- <img src="../assets/images/screenshots/record from screen.png" alt="Record from Screen" />
- <p class="caption">Capture system audio while screen sharing</p>
+ <img src="../assets/images/screenshots/recording-single-source.png" alt="Single Source Recording" />
+ <p class="caption">Single source recording with real-time notes</p>
</div>
</div>
### Post-Recording
<div class="screenshot-item">
- <img src="../assets/images/screenshots/after recording, finalize tags and settings and notes before uploading or discard.png" alt="Post-Recording Options" />
+ <img src="../assets/images/screenshots/recording-upload-modal.png" alt="Post-Recording Options" />
<p class="caption">Add tags, notes, and configure settings before processing</p>
</div>
## Transcription Features
+### Interactive Audio Synchronization
+
+<div class="screenshot-grid">
+ <div class="screenshot-item">
+ <img src="../assets/images/screenshots/audio-sync-simple-view.png" alt="Audio Sync Simple View" />
+ <p class="caption">Real-time transcript highlighting in simple view with auto-scroll follow mode</p>
+ </div>
+
+ <div class="screenshot-item">
+ <img src="../assets/images/screenshots/audio-sync-bubble-view.png" alt="Audio Sync Bubble View" />
+ <p class="caption">Interactive audio-transcript synchronization in bubble view</p>
+ </div>
+</div>
+
+<div class="screenshot-grid">
+ <div class="screenshot-item">
+ <img src="../assets/images/screenshots/highlighted-transcript-following-simple-light.png" alt="Follow Mode Light Theme" />
+ <p class="caption">Auto-scroll follow mode in light theme - click any text to jump to that point in audio</p>
+ </div>
+
+ <div class="screenshot-item">
+ <img src="../assets/images/screenshots/highlighted-transcript-following-simple-dark.png" alt="Follow Mode Dark Theme" />
+ <p class="caption">Follow mode in dark theme with active segment highlighting</p>
+ </div>
+</div>
+
### Transcription Views
<div class="screenshot-grid">
<div class="screenshot-item">
- <img src="../assets/images/screenshots/recording view with simple transcription view and chat visible.png" alt="Transcription with Chat" />
- <p class="caption">Simple transcription view with AI chat panel</p>
+ <img src="../assets/images/screenshots/main-view-with-speakers.png" alt="Transcription with Speakers" />
+ <p class="caption">Transcription with identified speakers and metadata</p>
</div>
-
+
<div class="screenshot-item">
- <img src="../assets/images/screenshots/Summary View.png" alt="Summary View" />
+ <img src="../assets/images/screenshots/main-view-summary-tab.png" alt="Summary View" />
<p class="caption">AI-generated summary with key points</p>
</div>
</div>
@@ -82,12 +115,12 @@ Explore Speakr's powerful features through our visual gallery. Click on any imag
<div class="screenshot-grid">
<div class="screenshot-item">
- <img src="../assets/images/screenshots/speaker id modal.png" alt="Speaker Identification" />
- <p class="caption">Identify and label speakers in your recordings</p>
+ <img src="../assets/images/screenshots/speaker-identification-voice-profiles.png" alt="Voice Profile Speaker Identification" />
+ <p class="caption">AI-powered speaker identification with voice profile suggestions and confidence scores</p>
</div>
-
+
<div class="screenshot-item">
- <img src="../assets/images/screenshots/edit transcript with ASR.png" alt="ASR Transcript Editor" />
+ <img src="../assets/images/screenshots/edit-transcription-modal.png" alt="ASR Transcript Editor" />
<p class="caption">Advanced segment-based editor for ASR transcriptions</p>
</div>
</div>
@@ -98,12 +131,12 @@ Explore Speakr's powerful features through our visual gallery. Click on any imag
<div class="screenshot-grid">
<div class="screenshot-item">
- <img src="../assets/images/screenshots/chat view with question.png" alt="AI Chat Interface" />
- <p class="caption">Ask questions about your recordings and get intelligent answers</p>
+ <img src="../assets/images/screenshots/chat-interface.png" alt="AI Chat Interface" />
+ <p class="caption">Ask questions about your recordings with expanded chat view</p>
</div>
-
+
<div class="screenshot-item">
- <img src="../assets/images/screenshots/notes tab.png" alt="Notes Tab" />
+ <img src="../assets/images/screenshots/main-view-notes-tab.png" alt="Notes Tab" />
<p class="caption">Organize your thoughts with markdown notes</p>
</div>
</div>
@@ -112,18 +145,18 @@ Explore Speakr's powerful features through our visual gallery. Click on any imag
<div class="screenshot-grid">
<div class="screenshot-item">
- <img src="../assets/images/screenshots/inquire mode.png" alt="Inquire Mode Search" />
+ <img src="../assets/images/screenshots/Inquire mode.png" alt="Inquire Mode Search" />
<p class="caption">Semantic search across all your recordings</p>
</div>
-
+
<div class="screenshot-item">
- <img src="../assets/images/screenshots/inquire mode 2.png" alt="Inquire Mode Results" />
- <p class="caption">Natural language search with contextual results</p>
+ <img src="../assets/images/screenshots/inquire-dark-mode.png" alt="Inquire Mode Dark" />
+ <p class="caption">Inquire mode with dark theme</p>
</div>
-
+
<div class="screenshot-item">
- <img src="../assets/images/screenshots/iinquire mode contextual searches.png" alt="Contextual Search Results" />
- <p class="caption">Find relevant content across multiple recordings</p>
+ <img src="../assets/images/screenshots/chat-chinese.png" alt="Multilingual Inquire" />
+ <p class="caption">Chat and inquire in multiple languages</p>
</div>
</div>
@@ -133,13 +166,13 @@ Explore Speakr's powerful features through our visual gallery. Click on any imag
<div class="screenshot-grid">
<div class="screenshot-item">
- <img src="../assets/images/screenshots/tag selection and stacking.png" alt="Tag Selection" />
- <p class="caption">Multi-tag selection with intelligent prompt stacking</p>
+ <img src="../assets/images/screenshots/edit-tags.png" alt="Edit Tags" />
+ <p class="caption">Edit and organize tags for recordings</p>
</div>
-
+
<div class="screenshot-item">
- <img src="../assets/images/screenshots/settings Tags that allow custom prompts stackable and custom asr settings.png" alt="Tag Management" />
- <p class="caption">Create tags with custom AI prompts and ASR settings</p>
+ <img src="../assets/images/screenshots/tag-management-enhanced-badges.png" alt="Enhanced Tag Management" />
+ <p class="caption">Comprehensive tag management with visual badges for retention policies, sharing settings, and custom prompts</p>
</div>
</div>
@@ -163,12 +196,12 @@ Explore Speakr's powerful features through our visual gallery. Click on any imag
<div class="screenshot-grid">
<div class="screenshot-item">
- <img src="../assets/images/screenshots/share recording modal.png" alt="Share Modal" />
+ <img src="../assets/images/screenshots/Share modal.png" alt="Share Modal" />
<p class="caption">Generate secure share links with customizable permissions</p>
</div>
-
+
<div class="screenshot-item">
- <img src="../assets/images/screenshots/shared recording.png" alt="Shared Recording View" />
+ <img src="../assets/images/screenshots/Share link.png" alt="Shared Recording View" />
<p class="caption">Clean public view for shared recordings</p>
</div>
</div>
@@ -177,16 +210,44 @@ Explore Speakr's powerful features through our visual gallery. Click on any imag
<div class="screenshot-grid">
<div class="screenshot-item">
- <img src="../assets/images/screenshots/shared transcript modal.png" alt="Manage Shares" />
- <p class="caption">Control and revoke shared links</p>
+ <img src="../assets/images/screenshots/share-notes-view.png" alt="Shared Notes View" />
+ <p class="caption">Public notes view for shared recordings</p>
</div>
-
+
+ <div class="screenshot-item">
+ <img src="../assets/images/screenshots/share-summary-view.png" alt="Shared Summary View" />
+ <p class="caption">Summary view of shared recordings</p>
+ </div>
+
+ <div class="screenshot-item">
+ <img src="../assets/images/screenshots/share-translated.png" alt="Shared Translated Recording" />
+ <p class="caption">Shared recording with AI translation</p>
+ </div>
+</div>
+
+## Content Creation & Editing
+
+### Markdown Editor
+
+<div class="screenshot-grid">
+ <div class="screenshot-item">
+ <img src="../assets/images/screenshots/markdown-editor.png" alt="Markdown Editor" />
+ <p class="caption">Rich markdown editor for notes and summaries</p>
+ </div>
+
<div class="screenshot-item">
- <img src="../assets/images/screenshots/settings shared transcripts.png" alt="Shared Transcripts Settings" />
- <p class="caption">Overview of all your shared recordings</p>
+ <img src="../assets/images/screenshots/markdown-editor-fullscreen.png" alt="Fullscreen Markdown Editor" />
+ <p class="caption">Fullscreen markdown editor with side-by-side preview</p>
</div>
</div>
+### Template Export
+
+<div class="screenshot-item">
+ <img src="../assets/images/screenshots/template-selector.png" alt="Template Selector" />
+ <p class="caption">Select templates for downloading transcripts in various formats</p>
+</div>
+
## User Settings
### Account Configuration
@@ -196,27 +257,53 @@ Explore Speakr's powerful features through our visual gallery. Click on any imag
<img src="../assets/images/screenshots/settings account info.png" alt="Account Settings" />
<p class="caption">Personal information and language preferences</p>
</div>
-
+
<div class="screenshot-item">
- <img src="../assets/images/screenshots/settings custom prompts.png" alt="Custom Prompts" />
- <p class="caption">Configure personal AI summarization prompts</p>
+ <img src="../assets/images/screenshots/settings-create-tag-modal.png" alt="Create Tag" />
+ <p class="caption">Create custom tags with specific processing options</p>
</div>
</div>
### Speaker Management
<div class="screenshot-item">
- <img src="../assets/images/screenshots/settings speakr management.png" alt="Speaker Management" />
- <p class="caption">Manage your speaker library with usage statistics</p>
+ <img src="../assets/images/screenshots/speakers-management-voice-profiles.png" alt="Enhanced Speaker Management" />
+ <p class="caption">Manage your speaker library with voice profile statistics, confidence scores, and voice sample playback</p>
</div>
## Admin Features
### User Management
-<div class="screenshot-item">
- <img src="../assets/images/screenshots/Admin dashboard.png" alt="Admin Dashboard" />
- <p class="caption">Manage users and monitor system usage</p>
+<div class="screenshot-grid">
+ <div class="screenshot-item">
+ <img src="../assets/images/screenshots/Admin dashboard.png" alt="Admin Dashboard" />
+ <p class="caption">Manage users and monitor system usage</p>
+ </div>
+
+ <div class="screenshot-item">
+ <img src="../assets/images/screenshots/admin-user-groups.png" alt="User Groups" />
+ <p class="caption">Manage user groups and permissions</p>
+ </div>
+</div>
+
+### Group Management
+
+<div class="screenshot-grid">
+ <div class="screenshot-item">
+ <img src="../assets/images/screenshots/admin-edit-group-modal.png" alt="Edit Group" />
+ <p class="caption">Edit group settings and properties</p>
+ </div>
+
+ <div class="screenshot-item">
+ <img src="../assets/images/screenshots/admin-manage-group-modal.png" alt="Manage Group Members" />
+ <p class="caption">Manage group members and permissions</p>
+ </div>
+
+ <div class="screenshot-item">
+ <img src="../assets/images/screenshots/admin-manage-group-tags.png" alt="Manage Group Tags" />
+ <p class="caption">Configure tags for specific user groups</p>
+ </div>
</div>
### System Configuration
@@ -251,13 +338,13 @@ Explore Speakr's powerful features through our visual gallery. Click on any imag
<div class="screenshot-grid">
<div class="screenshot-item">
- <img src="../assets/images/screenshots/full recording reprocessing.png" alt="Full Reprocessing" />
- <p class="caption">Reprocess recordings with updated settings</p>
+ <img src="../assets/images/screenshots/processing-tooltip.png" alt="Processing Tooltip" />
+ <p class="caption">View transcription and summary processing times</p>
</div>
-
+
<div class="screenshot-item">
- <img src="../assets/images/screenshots/summary reprocessing modal.png" alt="Summary Reprocessing" />
- <p class="caption">Regenerate summaries with new prompts</p>
+ <img src="../assets/images/screenshots/archived-recording.png" alt="Archived Recording" />
+ <p class="caption">Archived recordings are marked in sidebar with no audio playback</p>
</div>
</div>
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index 63834d49..0ed639f6 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -6,7 +6,7 @@ When something goes wrong with Speakr, this guide helps you identify and resolve
### Container Won't Start
-When your Docker container refuses to start or immediately exits, the problem usually lies in your configuration. Check your [environment file](getting-started.md#step-3-configure-your-transcription-service) first - a single typo in API keys or mismatched quotes can prevent startup. Review the [installation guide](getting-started/installation.md) for proper setup. Run `docker-compose logs app` to see the actual error messages. Common culprits include port conflicts (another service using 8899), missing volume mounts, or incorrect file permissions on your data directory.
+When your Docker container refuses to start or immediately exits, the problem usually lies in your configuration. Check your [environment file](getting-started.md#step-3-configure-your-transcription-service) first - a single typo in API keys or mismatched quotes can prevent startup. Review the [installation guide](getting-started/installation.md) for proper setup. Run `docker compose logs app` to see the actual error messages. Common culprits include port conflicts (another service using 8899), missing volume mounts, or incorrect file permissions on your data directory.
If you see database connection errors, ensure your database file has proper permissions. The container runs as a specific user and needs read/write access to the data directories. On Linux systems, you might need to adjust ownership with `chown -R 1000:1000 ./uploads ./instance`.
@@ -157,9 +157,9 @@ While Docker is the only officially supported installation method, you can attem
### Check the Logs
-Docker logs contain valuable debugging information. Use `docker-compose logs -f app` to see real-time logs. Look for ERROR or WARNING messages that correspond to when problems occurred. Python tracebacks indicate code-level issues that might require support.
+Docker logs contain valuable debugging information. Use `docker compose logs -f app` to see real-time logs. Look for ERROR or WARNING messages that correspond to when problems occurred. Python tracebacks indicate code-level issues that might require support.
-For ASR issues, also check the ASR container logs: `docker-compose logs -f whisper-asr-webservice`
+For ASR issues, also check the ASR container logs: `docker compose logs -f whisper-asr-webservice`
### System Information
diff --git a/docs/user-guide/first-steps.md b/docs/user-guide/first-steps.md
index ea24fd93..75368cab 100644
--- a/docs/user-guide/first-steps.md
+++ b/docs/user-guide/first-steps.md
@@ -2,7 +2,7 @@
The Speakr main view is where you'll spend most of your time. It's designed as a three-panel interface that makes it easy to navigate your recordings, review transcriptions, and interact with your content. Understanding each component will help you work more efficiently with your audio recordings.
-![Main View Interface](../assets/images/screenshots/recording view with simple transcription view and chat visible.png)
+![Main View Interface](../assets/images/screenshots/Main view.png)
## Understanding the Interface Layout
@@ -12,7 +12,7 @@ The main view is organized into three distinct sections that work together seaml
The navigation bar at the top of the screen provides quick access to essential features:
-![Navigation Elements](../assets/images/screenshots/Filters.png)
+![Navigation Elements](../assets/images/screenshots/Main view.png)
Starting from the left, you'll find the Speakr logo which always brings you back to the main view from anywhere in the application. The Inquire button opens the semantic search interface, allowing you to search across all your recordings using natural language questions. The New Recording button is your gateway to creating new content, either by uploading existing audio files or recording directly in your browser. On the right side, your username appears with a dropdown menu containing access to settings, language preferences, and the logout option.
@@ -22,7 +22,7 @@ The left sidebar is your command center for organizing and finding recordings. A
### Using Filters
-![Filter Interface](../assets/images/screenshots/Filters.png)
+![Filter Interface](../assets/images/screenshots/filters-sidebar-expanded.png)
The filter system in Speakr is designed to be both powerful and intuitive. Click on "Active filters" to expand the filtering panel. You can filter by tags, which appear as colored pills that you can click to select or deselect. The date range filter offers convenient presets like "Today", "Yesterday", "This Week", and "Last Week", or you can set a custom date range using the date pickers. When filters are active, their count appears next to the filter label, and a clear button lets you reset all filters at once.
@@ -36,8 +36,8 @@ The center panel is where you'll read and interact with your transcription. This
### Transcription Display
-![Transcription without Diarization](../assets/images/screenshots/main view no diarization.png)
-![Transcription with Diarization](../assets/images/screenshots/Summary View.png)
+![Transcription with Speakers](../assets/images/screenshots/main-view-with-speakers.png)
+![Summary View](../assets/images/screenshots/main-view-summary-tab.png)
The transcription display varies depending on how your audio was processed. If you used a standard Whisper API endpoint, you'll see a simple continuous text transcription without speaker identification. The text flows as a single narrative, which works well for single-speaker recordings or when speaker identification isn't needed.
@@ -109,6 +109,52 @@ For long recordings, the chat interface can save significant time. Instead of re
Remember that the interface updates in real-time. When you upload a new recording or when transcription completes, the interface will automatically refresh to show the latest status. You don't need to manually reload the page to see updates.
+## Collaboration Features (Optional)
+
+If you're working with a team or family, Speakr's collaboration features help you automatically share recordings with the right people. This section covers groups, group tags, and sharing - all optional but powerful when you need them.
+
+### Understanding Groups and Group Tags
+
+**Groups** are collections of users who regularly work together (e.g., "Engineering Team", "Family", "Sales Department"). Your administrator creates and manages groups, and you're automatically a member of any groups you've been added to.
+
+**Group Tags** are special tags that belong to a group. When you apply a group tag to a recording, all current members of that group automatically get access to it. This is perfect for project-specific content, department meetings, or family events that everyone should see.
+
+### Using Group Tags to Share Recordings
+
+If your administrator has created groups and group tags for you:
+
+1. When creating or editing a recording, click the **tag icon** in the metadata bar
+2. Look for tags that show a group indicator (these are your group tags)
+3. Select any group tag to apply it
+4. All group members instantly receive access to this recording
+
+Group tags can also include custom AI prompts for specialized summaries and retention policies for automatic cleanup. For example, a "Daily Standup" group tag might auto-delete recordings after 14 days, while a "Legal Consultations" tag keeps recordings permanently.
+
+### Individual Sharing
+
+For one-off collaborations or sharing with specific people outside your groups:
+
+1. Open the recording you want to share
+2. Click the **share icon** (users icon) in the toolbar
+3. Search for the user's name and select them
+4. Choose their permission level:
+ - **View Only**: Can read and listen, but not edit
+ - **Edit**: Can modify metadata, notes, and summary
+ - **Reshare**: Can share with additional users
+5. Click to add them - they immediately receive access
+
+### Personal Notes on Shared Recordings
+
+When someone shares a recording with you, you can add your own private notes that only you can see. This is perfect for tracking your action items or personal observations without cluttering the shared content. Your notes are completely separate from the recording owner's notes and the shared summary.
+
+To add personal notes to a shared recording, simply click on the **Notes** tab and start typing. These notes are yours alone and won't be visible to the recording owner or other people who have access.
+
+### Viewing Recordings Shared With You
+
+Recordings that others have shared with you appear in your main recording list with a subtle visual indicator. Use the **"Shared with Me"** filter in the sidebar to view only recordings others have shared with you, making it easy to focus on collaborative content.
+
+For complete details on all collaboration features, see the [Sharing & Collaboration guide](sharing.md).
+
## Creating New Content
Now that you understand how to navigate and interact with existing recordings in the main view, let's explore how to create new content. Speakr offers two ways to add recordings to your library: uploading existing audio files or recording directly in your browser.
diff --git a/docs/user-guide/groups.md b/docs/user-guide/groups.md
new file mode 100644
index 00000000..b9302f12
--- /dev/null
+++ b/docs/user-guide/groups.md
@@ -0,0 +1,158 @@
+---
+layout: default
+title: Group Collaboration
+parent: User Guide
+nav_order: 6
+---
+
+# Group Collaboration
+
+Groups transform how groups work together in Speakr, enabling seamless collaboration without manual sharing overhead. When your organization uses groups, recordings automatically reach the right people at the right time, eliminating the tedious process of individually sharing each conversation with every relevant group member.
+
+## Understanding Groups
+
+Groups in Speakr are organized groups of users who regularly need access to the same recordings. Unlike individual sharing where you manually grant access user-by-user, groups use smart tags that automatically share content with all group members when applied. This automation makes groups perfect for departments, project groups, or any collection of people who work together regularly.
+
+Your administrator creates and manages groups through the admin dashboard. Once you're added to a group, you gain access to group-specific tags and automatically receive recordings when teammates apply group tags. This creates a collaborative space where everyone stays informed without constant manual intervention.
+
+Groups work alongside personal organization tools. Your personal tags remain private and independent, while group tags create shared context. You can combine both - use personal tags for your workflow organization and group tags for automatic collaboration, creating a system that serves both individual and group needs.
+
+## Group Tags
+
+Group tags are the engine that powers group collaboration. They look and work like regular tags but carry special automatic sharing capabilities. When anyone applies a group tag to a recording, every group member instantly gains access without additional steps.
+
+### Recognizing Group Tags
+
+Group tags display with a distinctive users icon (👥) throughout the Speakr interface, making them immediately identifiable. Whether you're browsing the tag selector, viewing a recording's tags, or managing tags in settings, the users icon clearly marks group versus personal tags.
+
+In your tag management interface, group tags show the group name and cannot be deleted by regular users. Only group admins can create or remove group tags, ensuring centralized control over group-wide organizational systems. This prevents confusion where different group members create conflicting organizational structures.
+
+### Applying Group Tags
+
+Applying a group tag works exactly like applying a personal tag - open a recording, click the tags button, and select from your available tags. The difference happens behind the scenes: the moment you apply a group tag, Speakr automatically creates internal shares for every group member.
+
+This automatic sharing grants group members both view and edit access. They can read transcriptions and summaries, listen to audio, modify notes and metadata, and add their own tags. However, even with edit access, only the recording's original owner can delete it. This balance enables collaboration while protecting content ownership.
+
+The automatic sharing is intelligent. If a group member already has access through a previous share, Speakr doesn't create duplicates. If someone is added to the group later, they don't automatically gain access to old recordings - only recordings tagged after they join. This prevents retroactive access leakage while maintaining security.
+
+### Using Group Tags Effectively
+
+Apply group tags immediately after important meetings or discussions to ensure group-wide visibility while context is fresh. This creates a shared understanding quickly, letting everyone review content and add notes while details are clear. Prompt tagging turns recordings from individual resources into group knowledge.
+
+Combine group tags with personal tags for powerful organization. Use group tags to identify the audience (which group needs access) and personal tags for workflow status or content type. For example, tag a recording with both the "Engineering" group tag and your personal "Action Required" tag. The group tag shares with colleagues, while your personal tag tracks your follow-ups.
+
+When recordings touch multiple groups, you can apply multiple group tags. Each group tag grants access to its respective group members, creating overlapping access that matches cross-functional work. Be thoughtful with multi-group tagging - ensure all tagged groups actually need access to avoid overcommunicating.
+
+### Group Tag Features
+
+Some group tags carry special capabilities beyond basic sharing. Your administrator might configure group tags with custom retention policies that override global deletion rules. A "Legal Records" group tag might preserve recordings for seven years, while a "Daily Stand-ups" tag might auto-delete after two weeks. These tag-specific retention policies happen automatically - you just apply the tag and the system enforces the appropriate lifecycle.
+
+Protected group tags prevent automatic deletion entirely, regardless of age. Recordings with protected tags are never auto-deleted, making them perfect for compliance requirements, important decisions, or reference material. The protection is permanent until someone removes the tag, ensuring critical content remains accessible.
+
+Group tags can also include custom AI prompts that generate specialized summaries. When you apply a tag with a custom prompt, reprocessing the summary uses that prompt instead of your default. This lets different types of group content receive appropriate AI treatment - technical reviews get detailed technical summaries, while executive briefings get high-level overviews.
+
+## Working with Group Recordings
+
+Recordings shared via group tags appear in your main interface alongside your own recordings. Clear visual indicators help distinguish content sources and access levels, so you always know what you're looking at and what you can do with it.
+
+### Identifying Group Content
+
+The recording cards show multiple badges that communicate status at a glance. A blue "Group" badge indicates the recording has group tags applied, signaling it's group content. If you don't own the recording, a purple "Shared" badge appears, showing you've received access through sharing. Hovering over shared recordings reveals the owner's username, maintaining clarity about content source.
+
+Group tags themselves appear on recording cards, each marked with the users icon. When you see multiple tags on a recording, the icon helps identify which are group-wide (accessible to all group members) versus personal tags (visible only to the owner).
+
+The "Shared with Me" filter in the sidebar isolates recordings others have shared with you, including those shared via group tags. This filtered view helps focus on collaborative content when you need to review group discussions without distraction from your personal recordings.
+
+### Your Permissions on Group Recordings
+
+As a group member, you receive edit permissions on recordings with group tags. This means you can modify the title to add clarity, update the participant list with correct names, adjust the meeting date if needed, edit notes to add context or corrections, and add tags for better organization.
+
+Your edit capabilities come with important limitations. You cannot delete group recordings even with edit access - only the original owner can delete content. This prevents accidental data loss while enabling collaborative enhancement. You also cannot share group recordings with users outside the group without re-share permissions, which are typically reserved for group administrators.
+
+### Personal Notes on Group Recordings
+
+When you access a group recording, you can add personal notes that remain completely private. These personal notes never appear to the recording owner or other group members - they're your private space for observations, follow-ups, questions, or action items.
+
+Personal notes persist as long as you have access to the recording. If you leave the group or a group admin revokes your access, your personal notes are automatically deleted. This cleanup prevents orphaned data and ensures notes don't persist after access ends.
+
+Use personal notes to track what matters to you without cluttering shared notes. The recording owner's notes should contain universal context, while your personal notes capture your specific perspective, tasks, or concerns. This separation keeps shared notes focused while giving everyone space for individual tracking.
+
+## Group Membership
+
+Your group membership determines which group tags you can see and which recordings you automatically receive when teammates tag content. Group administrators can adjust membership as projects and roles evolve.
+
+### Joining a Group
+
+Group membership is managed by administrators through the admin dashboard. When you're added to a group, you immediately gain access to that group's tags and can apply them to your recordings. You also begin receiving recordings when teammates use group tags going forward.
+
+New group membership doesn't grant retroactive access. If a group has been using group tags before you joined, you won't automatically see older group-tagged recordings. This prevents information leakage and maintains security. Group admins can manually share historical recordings if needed.
+
+### Group Roles
+
+Groups have two roles that determine capabilities within the group structure. Regular members can use group tags on their recordings and access recordings tagged by others. They see group content, contribute their recordings to the group space, and participate in collaborative discussions.
+
+Group admins have additional responsibilities. They can add or remove group members, promoting collaboration flexibility. They can create new group tags with custom settings, defining the organizational structure for group content. They can modify or delete existing group tags, maintaining the group's tag taxonomy as needs evolve. For administrators, group admins can access a limited version of the admin dashboard focused solely on group management.
+
+### Leaving Groups
+
+When you leave a group (either voluntarily or through admin action), several things happen automatically. You lose access to group tags, so they disappear from your tag selectors. Your access to group-shared recordings continues if you received them before leaving, but you won't receive new group recordings going forward. Any personal notes you created on group recordings are preserved if you retain access through other sharing mechanisms.
+
+## Group Administration for Group Admins
+
+If you're a group admin rather than a regular member, you have access to group management capabilities through a special admin interface. This limited admin dashboard focuses exclusively on group management without exposing system-wide administrative features.
+
+### Accessing Group Management
+
+Group admins see a "Group Management" link in their account menu, replacing the regular admin link. Clicking this takes you to a focused interface showing only groups you administer. You cannot see or manage other groups, maintaining security boundaries between different group administrators.
+
+The group management interface lets you view group members with their roles, add new members from your organization, change member roles between admin and regular member, remove members who no longer need access, and manage group tags including retention and protection settings.
+
+### Managing Group Members
+
+Adding members to your group makes them immediately eligible to receive group-tagged recordings. Search for users by username, select their initial role, and add them. They gain access to group tags right away and will receive future group recordings.
+
+Changing roles between member and admin adjusts capabilities. Promoting a member to admin grants them group management abilities, useful for distributing administrative workload. Demoting an admin to member removes management capabilities while preserving their group access.
+
+Removing members cuts off their access to future group recordings. They keep access to recordings they've already received, but new group tags won't share with them anymore. If you need to fully revoke access to existing content, you'll need to manually revoke those internal shares.
+
+### Creating and Managing Group Tags
+
+Group tags are your group's organizational vocabulary. Create tags that match how your group thinks about content - project names, content types, meeting categories, or whatever organizational scheme makes sense for your work.
+
+When creating group tags, you can set custom retention periods that override global settings. This lets your group manage content lifecycle based on group-specific requirements. Legal groups might set long retention, while operations groups might prefer shorter retention for routine recordings.
+
+Protection flags prevent automatic deletion entirely. Use protection for recordings that must be kept permanently - compliance records, critical decisions, reference materials. Protected tags ensure content survives regardless of age or global retention policies.
+
+### Syncing Group Shares
+
+If your group started using group tags before automatic sharing was fully implemented, you might have tagged recordings that didn't automatically share with current group members. The "Sync Group Shares" feature retroactively applies automatic sharing to existing group-tagged recordings.
+
+This sync operation runs through all recordings with your group's tags and creates internal shares for current group members who don't already have access. It's a one-time operation that brings historical content into alignment with current group membership, useful after enabling new group features or fixing configuration issues.
+
+## Best Practices for Group Collaboration
+
+Start using group tags from the beginning of projects or group formation. This builds a complete record of group discussions from inception, creating valuable historical context. Retroactively organizing recordings is possible but more tedious than tagging promptly.
+
+Establish group conventions for when to use group tags versus individual sharing. Some content naturally belongs to the whole group, while other recordings might be relevant to specific individuals. Clear guidelines prevent over-sharing while ensuring important information reaches everyone who needs it.
+
+Use descriptive group tag names that clearly communicate content type or purpose. Names like "Sprint Planning" or "Customer Feedback" immediately convey content without requiring detective work. Avoid generic tags like "Important" or "Misc" that don't add meaningful organization.
+
+Review group tags periodically with your group admin to ensure they remain relevant. Projects end, organizational structures change, and tag systems that once made sense can become outdated. Regular maintenance keeps group organization clean and useful.
+
+Contribute to shared notes when you add valuable context, but avoid duplicating information. Read existing notes before adding your own to prevent redundant content. Well-maintained shared notes become valuable group resources, while cluttered notes lose utility.
+
+Use personal notes liberally for your individual tracking needs. Don't worry about perfect notes since only you see them. Personal notes are your space for rough thoughts, action items, questions, and observations that might not be polished enough for shared notes.
+
+## Integration with Inquire Mode
+
+When your instance has Inquire Mode enabled, groups enhance semantic search capabilities. Group tags appear in Inquire Mode's filter options, letting you scope searches to specific group contexts. Search for "budget discussion" and filter to just your project group, finding relevant conversations without noise from other groups.
+
+Recordings shared via group tags are automatically included in your Inquire Mode searches. This means semantic search spans both your personal recordings and group content, creating a comprehensive knowledge base. The AI understands context across all accessible recordings, providing better answers by drawing on collective group knowledge.
+
+Your personal notes on group recordings remain private even in Inquire Mode. When semantic search uses a group recording to answer questions, it draws on the transcription and shared notes, but never exposes your personal annotations. This maintains the privacy boundary while enabling powerful group-wide search.
+
+---
+
+Ready to start collaborating? If you're not yet part of any groups, contact your administrator about joining relevant groups. If you're a group admin, learn more in the [Group Management](../admin-guide/group-management.md) guide.
+
+Return to [User Guide](index.md) →
diff --git a/docs/user-guide/index.md b/docs/user-guide/index.md
index 2e048617..f776528c 100644
--- a/docs/user-guide/index.md
+++ b/docs/user-guide/index.md
@@ -41,11 +41,18 @@ Welcome to the Speakr User Guide! This documentation will help you master every
<div class="guide-card">
<div class="card-icon">🔗</div>
- <h3>Sharing Recordings</h3>
- <p>Create secure share links for recordings with control over what content is visible.</p>
+ <h3>Sharing & Collaboration</h3>
+ <p>Share recordings internally with colleagues or create public links for external stakeholders.</p>
<a href="sharing" class="card-link">Share Content →</a>
</div>
-
+
+ <div class="guide-card">
+ <div class="card-icon">👥</div>
+ <h3>Group Collaboration</h3>
+ <p>Work with groups using auto-sharing tags and organized group access to recordings.</p>
+ <a href="groups" class="card-link">Collaborate with Groups →</a>
+ </div>
+
<div class="guide-card">
<div class="card-icon">⚙️</div>
<h3>Account Settings</h3>
diff --git a/docs/user-guide/inquire-mode.md b/docs/user-guide/inquire-mode.md
index 4c3d9d7c..936eeb83 100644
--- a/docs/user-guide/inquire-mode.md
+++ b/docs/user-guide/inquire-mode.md
@@ -9,7 +9,7 @@ nav_order: 4
Inquire Mode transforms your entire recording library into an intelligent knowledge base that you can search using natural language questions. Instead of hunting through individual recordings or trying to remember which meeting contained a specific discussion, you can simply ask questions and receive comprehensive answers drawn from all your relevant recordings.
-![Inquire Mode Interface](../assets/images/screenshots/inquire mode.png)
+![Inquire Mode Interface](../assets/images/screenshots/Inquire mode.png)
## Understanding Inquire Mode
@@ -35,7 +35,7 @@ Date range filtering helps you focus on recent discussions or search within a sp
## Asking Effective Questions
-![Inquire Mode Example Results](../assets/images/screenshots/inquire mode 2.png)
+![Inquire Mode Example Results](../assets/images/screenshots/inquire-dark-mode.png)
The key to getting great results from Inquire Mode is asking clear, specific questions. The system works best when you provide context and be specific about what you're looking for.
@@ -45,7 +45,7 @@ The system excels at different types of queries. You can ask for summaries of sp
## Understanding Your Results
-![Contextual Search Results](../assets/images/screenshots/inquire mode.png)
+![Contextual Search Results](../assets/images/screenshots/Inquire mode.png)
When Inquire Mode returns results, it provides a synthesized answer that draws from all relevant recordings. The response isn't just a list of search hits - it's a coherent narrative that combines information from multiple sources into a unified answer.
@@ -57,7 +57,7 @@ The system intelligently organizes information, grouping related points together
Inquire Mode shines in numerous real-world scenarios. When preparing for meetings, you can quickly review what was previously discussed about agenda topics, what questions remained unresolved, and what commitments were made. This ensures you walk into meetings fully informed without spending hours reviewing old recordings.
-For project management, the system helps track decisions across multiple meetings, identify all action items assigned to team members, and monitor how project requirements or priorities have changed over time. You can ask questions like "What risks have been identified for the product launch?" and receive a comprehensive list drawn from all relevant discussions.
+For project management, the system helps track decisions across multiple meetings, identify all action items assigned to group members, and monitor how project requirements or priorities have changed over time. You can ask questions like "What risks have been identified for the product launch?" and receive a comprehensive list drawn from all relevant discussions.
Research and analysis become dramatically more efficient. Whether you're analyzing customer feedback patterns, tracking competitor mentions, or identifying recurring themes across interviews, Inquire Mode can surface insights that might otherwise remain buried in hours of recordings.
diff --git a/docs/user-guide/recording.md b/docs/user-guide/recording.md
index c9779d87..3ad13e67 100644
--- a/docs/user-guide/recording.md
+++ b/docs/user-guide/recording.md
@@ -12,7 +12,7 @@ When recording system audio, you'll need to grant screen sharing permissions and
Click the "+ New Recording" button in the top navigation bar to access the recording interface. This opens a dedicated screen where you can either upload files or start a live recording.
-![New Recording View](../assets/images/screenshots/new recording view.png)
+![New Recording View](../assets/images/screenshots/Recording interface.png)
## Uploading Audio Files
@@ -26,7 +26,7 @@ When you upload a file, it immediately appears in the upload queue with a progre
Below the upload area, you'll find the audio recording section with three distinct recording modes, each designed for different scenarios:
-![Recording Options](../assets/images/screenshots/after recording, finalize tags and settings and notes before uploading or discard.png)
+![Recording Options](../assets/images/screenshots/recording-upload-modal.png)
### Microphone Recording
@@ -34,7 +34,7 @@ The red microphone button captures audio from your selected microphone. This mod
### System Audio Recording
-The blue system audio button captures all sound playing through your computer. This is ideal for recording online meetings when you're primarily listening, webinars, video presentations, or any audio content playing on your computer. This feature uses the browser's screen capture API, so you'll need to select which screen or application to share when you start recording. Make sure to check the "Share system audio" checkbox in the sharing dialog.
+The blue system audio button captures all sound playing through your computer. This is ideal for recording online meetings when you're primarily listening, webinars, online presentations, podcasts, or any audio content playing on your computer. This feature uses the browser's screen capture API, so you'll need to select which screen or application to share when you start recording. Make sure to check the "Share system audio" checkbox in the sharing dialog.
### Combined Recording (Microphone + System)
@@ -46,7 +46,7 @@ When you click to record system audio (or both microphone and system), your brow
### Recording from a Browser Tab
-Choose the tab option if the audio you want to record is playing within a specific browser tab, such as a YouTube video, web-based meeting platform (like Google Meet or browser-based Zoom), or online training video.
+Choose the tab option if the audio you want to record is playing within a specific browser tab, such as audio/video content on YouTube, web-based meeting platforms (like Google Meet or browser-based Zoom), or online training sessions.
![Tab Selection with Audio](../assets/images/screenshots/record from tab.png)
@@ -61,7 +61,7 @@ Choose the screen option if the audio you want to record is coming from desktop
![Screen Selection Dialog](../assets/images/screenshots/record from screen.png)
This is the recommended option when recording:
-- Desktop applications like Zoom client, Microsoft Teams, Skype, or Discord
+- Desktop applications like Zoom client, Microsoft Groups, Skype, or Discord
- Audio from multiple browser tabs simultaneously
- System sounds or notifications you want to capture
- Any combination of audio sources on your computer
@@ -74,7 +74,7 @@ When you select "Your Entire Screen", you'll see previews of all your available
Once you start recording, the interface transforms to show the active recording session:
-![Live Recording Interface](../assets/images/screenshots/Record mic or system audio (for online meetings) and take markdown notes.png)
+![Live Recording Interface](../assets/images/screenshots/recording-dual-source.png)
### Real-Time Audio Monitoring
@@ -86,7 +86,7 @@ A prominent timer at the top shows the elapsed recording time in minutes and sec
One of Speakr's most powerful features is the ability to take structured notes while recording. The note-taking area appears below the audio visualizers and supports full markdown formatting.
-![Note Taking During Recording](../assets/images/screenshots/live recording view with notes.png)
+![Note Taking During Recording](../assets/images/screenshots/recording-single-source.png)
The markdown editor includes a formatting toolbar with buttons for common formatting options like bold, italic, headers, quotes, lists, and links. You can also type markdown syntax directly if you prefer. The editor supports all standard markdown elements, allowing you to create well-structured notes that complement your recording.
@@ -98,7 +98,7 @@ Common use cases for live notes include capturing action items and deadlines dur
After stopping a recording or selecting an uploaded file, you'll see the finalization screen where you can add metadata and configure processing options:
-![Upload Modal](../assets/images/screenshots/after recording, finalize tags and settings and notes before uploading or discard.png)
+![Upload Modal](../assets/images/screenshots/recording-upload-modal.png)
### Adding Tags
@@ -156,7 +156,7 @@ The quality of your transcription starts with the quality of your recording. Whe
**Important Note for Phone Recordings:** Many smartphones have aggressive noise cancellation algorithms designed to enhance single-speaker calls. When recording meetings or conversations with multiple speakers using a phone's microphone, these noise cancellation features may incorrectly identify other speakers as background noise and filter them out. This can result in muffled or missing audio from speakers who are farther from the phone. This is not a limitation of Speakr but rather how modern phones process audio. For multi-speaker recordings, consider using an external microphone without noise cancellation or positioning the phone equidistant from all speakers.
-For system audio recording, close unnecessary applications that might produce notification sounds or background audio. If you're recording a video call, ensure you have a stable internet connection to avoid audio dropouts. Using wired internet instead of WiFi can improve stability for important recordings.
+For system audio recording, close unnecessary applications that might produce notification sounds or background audio. If you're recording an online call or web meeting, ensure you have a stable internet connection to avoid audio dropouts. Using wired internet instead of WiFi can improve stability for important recordings.
When recording both microphone and system audio, use headphones to prevent echo and feedback. This ensures that the system audio doesn't get picked up by your microphone, which would create a confusing double recording.
diff --git a/docs/user-guide/settings.md b/docs/user-guide/settings.md
index d9286e32..373768a3 100644
--- a/docs/user-guide/settings.md
+++ b/docs/user-guide/settings.md
@@ -84,18 +84,30 @@ The delete button (trash icon) immediately revokes access. Once deleted, anyone
## Speakers Management Tab
-![Speakers Management](../assets/images/screenshots/settings speakr management.png)
+![Speakers Management with Voice Profiles](../assets/images/screenshots/speakers-management-voice-profiles.png)
+*Speakers Management with voice profile statistics, confidence scores, and voice sample playback*
-The Speakers Management tab provides a comprehensive interface for managing all speakers identified across your recordings.
+The Speakers Management tab provides a comprehensive interface for managing all speakers identified across your recordings, including advanced voice profile capabilities.
### Automatic Speaker Creation
-Speakers are automatically saved when you identify them during transcription editing. The system builds your library over time as you consistently name participants across recordings.
+Speakers are automatically saved when you identify them during transcription editing. The system builds your library over time as you consistently name participants across recordings. When speaker diarization is enabled, Speakr automatically collects voice embeddings to build recognition profiles.
### Speaker Card Information
Each speaker card displays essential information in a clean, scannable format. The speaker's name appears prominently, followed by usage statistics showing how many times they've been identified across your recordings. The last used date helps you understand which speakers are current versus historical. When a speaker was added to your library is tracked for reference.
+#### Voice Profile Information
+
+For speakers with voice recognition data, each card displays additional information:
+
+- **Voice Profile Badge**: Shows confidence level (high/medium/low) based on the number and quality of voice samples collected
+- **Sample Count**: Number of voice embeddings collected from different recordings, helping assess profile strength
+- **Voice Samples Button**: Click to hear representative audio clips of this speaker's voice for verification
+- **Profile Strength Indicator**: Visual feedback showing how well the system can recognize this speaker in future recordings
+
+The voice profile data improves speaker suggestion accuracy when identifying speakers in new recordings. When you open the speaker identification modal, Speakr analyzes voice patterns and suggests likely matches with confidence scores, making the identification process faster and more accurate over time.
+
### Interface Layout
The grid layout accommodates multiple speakers per row, making efficient use of screen space while maintaining readability. Each card includes action buttons - an edit icon for updating speaker details and a delete icon for removal. The red trash icon on each card provides individual deletion, while the "Delete All" button at the bottom enables bulk cleanup when needed.
@@ -108,15 +120,36 @@ At the bottom of the interface, a count shows your total saved speakers - "77 sp
Regular maintenance keeps your speaker library relevant. Remove speakers who no longer appear in recordings, consolidate duplicates created with slight name variations, and ensure names are consistent for better transcript coherence. Periodic reviews help keep your library manageable and useful.
+### Automatic Speaker Cleanup
+
+When recordings are deleted (either manually or through auto-deletion), Speakr automatically manages speaker voice profiles to protect your privacy:
+
+- **Speakers with remaining recordings**: Voice profiles are preserved and continue to provide recognition suggestions
+- **Speakers with no recordings**: Automatically removed during the next scheduled cleanup to ensure voice data is not retained unnecessarily
+- **No manual action needed**: Cleanup happens automatically when auto-deletion is enabled
+
+This automatic cleanup ensures your speaker list stays current and maintains compliance with data privacy regulations. Voice embeddings (biometric data) are only retained when there are active recordings that reference the speaker, following data minimization principles.
+
+**Note**: If you want to preserve a speaker's voice profile, ensure at least one recording containing that speaker is retained. Protected recordings (with protected tags) will preserve their associated speakers.
+
## Tag Management Tab
-![Tag Management](../assets/images/screenshots/settings Tags that allow custom prompts stackable and custom asr settings.png)
+![Tag Management with Enhanced Badges](../assets/images/screenshots/tag-management-enhanced-badges.png)
+*Tag Management with visual badges for retention policies, protection status, sharing settings, and ASR defaults*
-Tag Management transforms simple labels into powerful processing instructions. Each tag you create carries multiple capabilities - a color for visual identification, an optional custom prompt that shapes AI summaries, and even default ASR (Automatic Speech Recognition) settings that optimize transcription for specific scenarios.
+Tag Management transforms simple labels into powerful processing instructions. Each tag you create carries multiple capabilities - a color for visual identification, an optional custom prompt that shapes AI summaries, default ASR (Automatic Speech Recognition) settings, retention policies, and sharing configurations.
### Tag Display and Features
-The interface displays your tags as cards, each showing the tag name with its color indicator, custom prompt if configured, and ASR defaults when set. In the example shown, "BSB Meetings" has a blue indicator with instructions to summarize transcripts in extreme detail. "Court Action" uses red and includes both a custom prompt and ASR defaults set to "Max 10" speakers - perfect for legal proceedings with multiple participants. The green "Fun" tag keeps summaries light and backwards, showing how creative prompts can serve different purposes.
+The interface displays your tags as cards with clear visual badges indicating their configuration. Each card shows the tag name with its color indicator, and visual badges that make it easy to see at a glance:
+
+- **Retention Policy Badges**: Display retention periods (e.g., "90 days") or protection status (∞ infinity symbol for protected tags)
+- **Sharing Badges**: Indicate if this is a group tag with auto-share capabilities (👥 users icon)
+- **Language Badges**: Show custom language settings for transcription or summarization
+- **Speaker Range Badges**: Display ASR defaults like "Max 10" speakers for meetings with many participants
+- **Custom Prompts**: Preview of tag-specific AI summarization instructions
+
+These visual indicators make it immediately clear which tags have special behaviors, helping you quickly select the right tags when uploading or organizing recordings.
### Creating New Tags
@@ -158,7 +191,7 @@ Colorful cards remind you of Speakr's core capabilities. Audio Transcription hig
### Using This Information
-This information-rich tab serves multiple purposes. For troubleshooting, it provides all the version and configuration details support teams need. For planning, it shows which features are available and properly configured. For learning, it links to all the resources needed to master Speakr's capabilities.
+This information-rich tab serves multiple purposes. For troubleshooting, it provides all the version and configuration details support groups need. For planning, it shows which features are available and properly configured. For learning, it links to all the resources needed to master Speakr's capabilities.
## Privacy and Security Considerations
@@ -176,7 +209,7 @@ The most effective Speakr setup evolves with your needs. Start with basic config
Monitor which settings you actually use. If you never change certain preferences, they're probably fine at defaults. If you constantly adjust others, consider whether different base settings would reduce this friction. Your settings should work for you, not require constant attention.
-Share successful configurations with your team. If you've crafted an excellent prompt for technical summaries, share it with colleagues who might benefit. If your tag taxonomy works well, document it for others to adopt. Collective improvement benefits everyone.
+Share successful configurations with your group. If you've crafted an excellent prompt for technical summaries, share it with colleagues who might benefit. If your tag taxonomy works well, document it for others to adopt. Collective improvement benefits everyone.
Remember that settings are tools for productivity, not endpoints themselves. The goal isn't perfect configuration but effective recording management. When your settings fade into the background and Speakr just works how you expect, you've achieved the right balance.
diff --git a/docs/user-guide/sharing.md b/docs/user-guide/sharing.md
index fca5023a..75a2055d 100644
--- a/docs/user-guide/sharing.md
+++ b/docs/user-guide/sharing.md
@@ -1,15 +1,139 @@
---
layout: default
-title: Sharing Recordings
+title: Sharing & Collaboration
parent: User Guide
nav_order: 5
---
-# Sharing Recordings
+# Sharing & Collaboration
-Sometimes you need to share a recording with someone who doesn't have a Speakr account - perhaps a client needs to review a meeting, a colleague missed an important discussion, or you want to provide documentation to stakeholders. Speakr's sharing feature lets you create secure, read-only links to your recordings while maintaining complete control over what information is shared.
+Speakr offers flexible collaboration options to match your workflow. Share recordings internally with group members for collaborative work, organize access through groups for seamless project management, or create public links for external stakeholders. Each sharing method serves different needs while maintaining security and control over your content.
-## Understanding Recording Shares
+## Internal Sharing (User-to-User)
+
+Internal sharing enables direct collaboration between users in your Speakr instance. Share recordings one-on-one with family or colleagues, grant precise permissions based on trust levels, and maintain control over who can access your content.
+
+### Understanding Internal Sharing
+
+Unlike public share links that work for anyone with the URL, internal sharing creates secure connections between authenticated users within your Speakr instance. When you share internally, the recipient must log in to access the recording, and their permissions are tracked and enforceable. This makes internal sharing ideal for sensitive content and ongoing collaboration.
+
+### Requirements for Internal Sharing
+
+Your Speakr administrator must enable internal sharing before this feature becomes available. Once enabled, you'll see sharing buttons in the recording detail view. If you don't see these options, contact your administrator about enabling the `ENABLE_INTERNAL_SHARING` feature.
+
+### Sharing a Recording with Another User
+
+![Share with User Modal](../assets/images/screenshots/share-with-user.png)
+
+When viewing any recording you own, look for the blue users icon button in the toolbar. Clicking this opens the share modal where you can search for colleagues and configure access permissions.
+
+The search functionality makes finding the right person quick and intuitive. Type at least two characters of a username to see matching results. The system filters out your own name since you can't share recordings with yourself, and shows only other users in your instance.
+
+Before sharing, consider what level of access makes sense for this collaboration. Speakr offers three permission levels that build on each other, letting you grant exactly the access needed without oversharing control.
+
+**View-Only Access** provides the foundation - recipients can read the transcription, review your summary and notes, listen to the audio if it hasn't been deleted, and use the AI chat feature to ask questions about the content. They cannot modify anything, ensuring your original content remains intact. This works well when you're distributing information but don't need input or edits.
+
+**Edit Permissions** add the ability to modify the recording's metadata and shared content. Recipients with edit access can change the title, update participant lists, adjust the meeting date and time, modify the shared summary, and add or remove tags. However, they still cannot delete the recording or share it with others. Edit access works well for collaborative documentation where multiple group members contribute context and refinements. Note that all users can maintain their own personal notes regardless of edit permissions.
+
+**Re-share Permissions** grant the highest level of access short of full ownership. Recipients can do everything editors can do, plus share the recording with additional users and manage those shares by revoking access. This creates a chain of trust where you empower certain colleagues to extend access as needed. However, even with re-share permissions, recipients cannot delete the recording - only the original owner can do that.
+
+To share with view-only access, simply search for the user and click their name in the results. For edit or re-share permissions, check the appropriate boxes before clicking the username. The share takes effect immediately, and the recipient gains access to the recording in their main interface.
+
+### Managing Your Shares
+
+![Manage Shares Modal](../assets/images/screenshots/manage-shares.png)
+
+The unified share modal shows everyone who has access to a recording, making it easy to track and control sharing. Each entry displays the recipient's name, their permissions level, and when you granted access. The red user-times icon lets you instantly revoke access when collaboration ends or circumstances change.
+
+Revoking access is immediate and thorough. When you revoke someone's access, they lose the ability to view the recording, and any personal notes they created on the shared recording are removed. This ensures complete separation when collaboration ends.
+
+### Personal Notes on Shared Recordings
+
+One of internal sharing's most powerful features is support for personal notes. When someone shares a recording with you, you can add your own private notes that only you can see. These personal notes never appear to the original owner or other recipients - they're your private space for observations, follow-ups, or context.
+
+**Important: Notes vs. Summaries**
+- **Notes**: Always personal and private. Each user (owner and shared recipients) can create their own notes that only they can see. No edit permission is required to add personal notes to a shared recording.
+- **Summary**: Shared globally. The recording owner's AI-generated summary is visible to all users who have access to the recording. Only users with edit permission can modify the summary.
+
+This separation means you can freely annotate shared recordings with your own thoughts and action items without cluttering the shared content or requiring special permissions. The owner maintains control over the official summary while everyone can maintain their own personal notes.
+
+Personal notes persist until access is revoked. If the owner removes your access, your personal notes are automatically deleted since you no longer need notes on content you can't access. This automatic cleanup prevents orphaned data and maintains security.
+
+### Independent Inbox and Favorite Status
+
+Each user maintains their own inbox and favorite status for shared recordings. Your inbox and starred items are completely independent from other users - when you mark a shared recording as read or favorite it, this doesn't affect how it appears to the owner or other recipients. This allows everyone to organize their personal workspace without interfering with collaborators' views.
+
+### Viewing Recordings Shared With You
+
+Recordings that others have shared with you appear in your main recording list with distinctive visual indicators. Shared recordings display with an accent-colored title and a subtle border to make them immediately distinguishable from your own recordings. When you hover over a shared recording, you can see the owner's username (if your administrator has enabled username visibility), so you always know the content source.
+
+The "Shared with Me" toggle in the sidebar filters your view to show only recordings that others have shared with you. This focused view helps when you need to review collaborative content without distraction from your own recordings.
+
+Your permissions determine what you can do with shared recordings. View-only access means read and listen capabilities, while edit permissions let you contribute to the recording's metadata and shared summary. Regardless of your permission level, you can always add and edit your own personal notes - these are private to you and don't require any special permissions. The interface adapts to your permissions, showing or hiding controls based on your access level.
+
+### Security and Privacy
+
+Internal sharing implements multiple security layers to protect your content. Only authenticated users in your Speakr instance can receive shares - external parties cannot gain access through internal sharing mechanisms. Each share creates a tracked database record that links specific users to specific recordings with defined permissions.
+
+The permission system enforces strict boundaries. View-only recipients cannot accidentally or intentionally modify content. Edit permissions don't include deletion rights, preventing data loss from collaborative editing. Re-share permissions create an audit trail of who granted access to whom, maintaining accountability.
+
+When you delete a recording, all associated shares are automatically removed. Recipients lose access immediately, ensuring that content deletion is complete and final. Similarly, if an administrator disables a user's account, all their shares (both granted and received) become inactive.
+
+### Practical Use Cases
+
+Internal sharing and group features work together to handle different collaboration scenarios. Here's how people actually use them:
+
+### One-on-One Sharing
+
+Share individual recordings with specific people when you need targeted collaboration. Your manager asks about yesterday's client call - share it directly with view access so they can review what was discussed. A colleague missed the group meeting - share it with edit access so they can add their notes and questions. You're working on a project with someone from another department - share relevant recordings as you create them to keep them in the loop.
+
+This works well when the collaboration is temporary or involves people who don't regularly need access to your recordings. You control exactly who sees what, and you can revoke access when the collaboration ends.
+
+### Group-Based Sharing
+
+Groups automate sharing for groups who regularly work together. Create an engineering group and apply group tags to architecture discussions - everyone on the group automatically gets access. Sales group members tag customer calls with group tags so the whole group learns from each interaction. HR group shares interview recordings with all interviewers without manually sharing each one.
+
+Group sharing makes sense when the same group of people consistently needs access to similar content. Set it up once, and recordings flow to the right people automatically. The group structure persists, so new recordings tagged for the group reach all members without additional work.
+
+### Combining Both Approaches
+
+You can use groups for regular collaboration and individual sharing for exceptions. Your engineering group has automatic access to technical discussions through group tags. When a design decision needs executive review, you individually share that specific recording with your VP. The group gets their automated access, and you layer on targeted sharing for special cases.
+
+This combination handles both routine collaboration (groups) and exceptional needs (individual shares) without creating organizational overhead.
+
+### Real-World Scenarios
+
+| Scenario | Approach | Why It Works |
+|----------|----------|--------------|
+| Family recording memories | Create "Family" group, tag trips and events | Everyone gets access automatically, can add their own notes |
+| Book club discussions | Create "Book Club" group with protected tag | Recordings preserved permanently, all members auto-share |
+| Work project with 3 people | Share individually with edit access | Temporary collaboration, easy to revoke when project ends |
+| Department meetings | Create department group, tag all meetings | New group members get future meetings, not historical ones |
+| Client presentations | Individual share with view-only | Controlled access, clients can't accidentally edit |
+| Research group | Group with custom 7-year retention | Automatic sharing + compliance with retention policies |
+| Daily standups | Group with 14-day retention | Auto-share with group, auto-cleanup of routine recordings |
+
+### Combining with Retention Policies
+
+Group tags can enforce retention policies that match how your group works. Your daily standup group tag auto-deletes recordings after two weeks since they're routine updates. Your architecture decisions group tag protects recordings permanently because those discussions document important choices. Your client calls group tag keeps recordings for one year to match your data retention policy.
+
+This means the same recordings that automatically share with your group also automatically follow the right lifecycle. Tag it once, and both sharing and retention happen correctly.
+
+## Best Practices for Internal Sharing
+
+Share recordings promptly after meetings or discussions while context is fresh. Recipients can review content, add notes, and ask questions through the AI chat while details are still top-of-mind. This immediacy makes collaboration more effective and valuable.
+
+Use view-only access by default, granting edit permissions only when recipients truly need to contribute. This prevents accidental modifications while still enabling information sharing. Reserve re-share permissions for trusted group leads or project managers who need to coordinate access for their groups.
+
+Periodically review your shared recordings to ensure access remains appropriate. Group members change roles, projects end, and sensitive content that once needed sharing might now warrant restricted access. The manage shares interface makes regular audits quick and straightforward.
+
+When collaborating on sensitive content, verify recipient permissions match their role and need. Legal discussions might need view-only access even for close colleagues, while brainstorming sessions benefit from liberal edit permissions. Match permissions to content sensitivity and collaboration needs.
+
+## Public Share Links
+
+Sometimes you need to share a recording with someone who doesn't have a Speakr account - perhaps a client needs to review a meeting, a colleague missed an important discussion, or you want to provide documentation to stakeholders. Speakr's public sharing feature lets you create secure, read-only links to your recordings while maintaining complete control over what information is shared.
+
+### Understanding Public Shares
When you share a recording, Speakr generates a unique, secure link that provides access to that specific recording without requiring the recipient to log in or have an account. Each share link is cryptographically secure and impossible to guess, ensuring that only people you explicitly share with can access your content.
@@ -19,11 +143,11 @@ The sharing system gives you granular control over what recipients can see. You
Before you can share recordings, your Speakr instance must meet two critical requirements. First, it must be accessible via HTTPS with a valid SSL certificate. Second, it must be reachable from the internet with a proper domain name or public IP address.
-These requirements exist because share links need to be accessible to recipients who don't have accounts and may be accessing from anywhere. A local network installation or non-HTTPS setup cannot generate shareable links - the share button will either be disabled or display an error message explaining that sharing requires a secure, internet-accessible connection. If you're running Speakr internally without SSL or public access, you'll need to work with your IT team to set up proper HTTPS and internet routing before the sharing feature becomes available.
+These requirements exist because share links need to be accessible to recipients who don't have accounts and may be accessing from anywhere. A local network installation or non-HTTPS setup cannot generate shareable links - the share button will either be disabled or display an error message explaining that sharing requires a secure, internet-accessible connection. If you're running Speakr internally without SSL or public access, you'll need to work with your IT group to set up proper HTTPS and internet routing before the sharing feature becomes available.
## Creating a Share Link
-![Share Recording Modal](../assets/images/screenshots/share recording.png)
+![Share Recording Modal](../assets/images/screenshots/Share modal.png)
Once your instance meets the requirements, sharing a recording takes just a few clicks. While viewing any recording, click the share button in the toolbar to open the sharing modal. This presents you with two simple checkboxes that control what information will be visible to recipients.
@@ -35,7 +159,7 @@ Once you've selected your options, click "Create Share Link" to generate the sec
## What Recipients Experience
-![Shared Recording View](../assets/images/screenshots/shared recording.png)
+![Shared Recording View](../assets/images/screenshots/Share link.png)
When someone clicks your share link, they're taken to a streamlined view of your recording designed for easy consumption without distractions. The interface is clean and professional, branded with Speakr but showing only the content you've chosen to share.
@@ -49,7 +173,7 @@ At the bottom of the page, recipients see a subtle footer indicating the content
## Managing Your Shared Recordings
-![My Shared Transcripts](../assets/images/screenshots/shared transcript modal.png)
+![Shared Transcripts](../assets/images/screenshots/share-summary-view.png)
All your shared recordings are centrally managed through the Shared Transcripts section in your account settings. This gives you a complete overview of everything you've shared and with whom.
@@ -71,7 +195,7 @@ The system doesn't track who accesses shared links or how often they're viewed.
## Best Practices for Sharing
-When sharing internally within your organization, you can generally include both summaries and notes since colleagues have context about the discussions and need complete information. The notes often contain valuable action items, follow-ups, and clarifications that help team members understand not just what was said, but what needs to happen next.
+When sharing internally within your organization, you can generally include both summaries and notes since colleagues have context about the discussions and need complete information. The notes often contain valuable action items, follow-ups, and clarifications that help group members understand not just what was said, but what needs to happen next.
For external sharing with clients or partners, consider sharing only the summary without your internal notes. The summary provides them with professional, polished takeaways while your notes remain private for internal use. Review the content before sharing to ensure nothing confidential or inappropriate is included.
@@ -85,9 +209,9 @@ Meeting participants often appreciate receiving a share link after important dis
When updating clients on project progress, share recordings of internal discussions with summaries but without internal notes. This gives them transparency into your process and decisions while maintaining appropriate boundaries about internal deliberations.
-For training and onboarding, shared recordings become valuable learning resources. New team members can listen to past discussions to understand project history, decision rationale, and team dynamics. Include comprehensive notes to provide context that might not be obvious from the transcription alone.
+For training and onboarding, shared recordings become valuable learning resources. New group members can listen to past discussions to understand project history, decision rationale, and group dynamics. Include comprehensive notes to provide context that might not be obvious from the transcription alone.
-Legal and compliance teams may require unedited transcriptions of important conversations. In these cases, share only the transcription without summaries or notes that could be seen as interpretation or editorial commentary. The raw transcription provides an objective record of what was said.
+Legal and compliance groups may require unedited transcriptions of important conversations. In these cases, share only the transcription without summaries or notes that could be seen as interpretation or editorial commentary. The raw transcription provides an objective record of what was said.
## Limitations and Considerations
diff --git a/docs/user-guide/transcript-templates.md b/docs/user-guide/transcript-templates.md
index 8c1cc700..2dfd9b2f 100644
--- a/docs/user-guide/transcript-templates.md
+++ b/docs/user-guide/transcript-templates.md
@@ -179,8 +179,8 @@ If you have no templates, click **Create Default Templates** to generate a compr
- Interview Q&A - Professional interview format
- Meeting Minutes - Bulleted format for meeting notes
- Court Transcript - Legal deposition style with line numbers
-- SRT Subtitle - Standard subtitle format for videos
-- Screenplay - Film script formatting
+- SRT Subtitle - Standard subtitle format for content creation
+- Screenplay - Script formatting for creative projects
## Advanced Tips
@@ -223,7 +223,7 @@ Create an "Interview Format" template with timestamps and speaker labels for eas
Use a numbered format with timestamps to cite specific moments in recorded interviews or focus groups.
### For Content Creators
-Export in SRT format for adding subtitles to videos, or use screenplay format for video scripts.
+Export in SRT format for adding captions to podcasts or other multimedia content, or use screenplay format for creative audio scripts and productions.
### For Business Meetings
Create a "Meeting Minutes" template that clearly shows who said what and when, perfect for action items and follow-ups.
@@ -234,6 +234,94 @@ Use court transcript style formatting with line numbers and uppercase speaker na
### For Podcasters
Format transcripts for show notes with timestamps that listeners can click to jump to specific topics.
+## Integrating with External Tools
+
+Transcript templates become even more powerful when you combine them with external applications. Here are some practical integrations people use:
+
+### Obsidian and Note-Taking Apps
+
+If you use Obsidian, Logseq, or similar markdown-based note apps, you can set up automatic export of your transcripts. Speakr includes an auto-export feature that automatically writes completed transcripts to markdown files.
+
+Enable auto-export by adding these settings to your `.env` file:
+```bash
+ENABLE_AUTO_EXPORT=true
+AUTO_EXPORT_DIR=/data/exports
+AUTO_EXPORT_TRANSCRIPTION=true
+AUTO_EXPORT_SUMMARY=true
+```
+
+Then map the exports directory to your note app's folder in `docker-compose.yml`:
+```yaml
+volumes:
+ - ./uploads:/data/uploads
+ - ./instance:/data/instance
+ - /Users/username/Documents/Obsidian/Transcripts:/data/exports
+```
+
+Create a default transcript template in your Speakr settings that formats the way you want - the auto-export system uses your default template. When a recording finishes processing, Speakr automatically writes a markdown file to the exports directory with metadata, summary, and formatted transcription.
+
+Files are organized into subdirectories by username, so multiple users can export to the same vault without conflicts. Obsidian picks up these markdown files automatically, and you can reference them in daily notes, link them to related content, and search across all your transcripts.
+
+### Automated Processing Workflows
+
+Mount Speakr's upload directory as a Docker volume pointing to a location your automation tools can access. Create a template that exports in a structured format (like JSON or CSV), then use scripts to process the files automatically.
+
+For example, export client call transcripts to a folder that triggers a script to extract action items and add them to your project management tool. Or export interview transcripts to a research folder where analysis software picks them up for coding and categorization.
+
+The key is creating a template that produces the exact format your downstream tool expects, then using file system watching or scheduled scripts to move the files where they need to go.
+
+### Subtitle and Content Creation Workflows
+
+Create SRT-format templates and export transcripts for use in content creation projects. The SRT format provides time-coded text that can be used for subtitles in multimedia content, podcast show notes with timestamps, or any project where you need synchronized text.
+
+If you're creating multimedia content, you can export these transcripts to folders that your editing software monitors. Some tools watch specific directories for subtitle files - save your Speakr transcripts there, and they appear automatically for integration.
+
+This eliminates the manual export-import-format cycle when you're producing content from your audio recordings.
+
+### Documentation Systems
+
+Groups using wikis or documentation platforms can create templates that match their documentation format. Export meeting transcripts in the right format, clean them up minimally, and publish them to the group wiki. Some groups have scripts that take Speakr exports and create wiki pages automatically, preserving the discussion context for future reference.
+
+### Example: Obsidian Auto-Export Setup
+
+Here's a complete setup for automatic export to Obsidian:
+
+1. **Enable auto-export in `.env`**:
+ ```bash
+ ENABLE_AUTO_EXPORT=true
+ AUTO_EXPORT_DIR=/data/exports
+ AUTO_EXPORT_TRANSCRIPTION=true
+ AUTO_EXPORT_SUMMARY=true
+ ```
+
+2. **Map exports to Obsidian vault in `docker-compose.yml`**:
+ ```yaml
+ volumes:
+ - ./uploads:/data/uploads
+ - ./instance:/data/instance
+ - /Users/username/Documents/Obsidian/Transcripts:/data/exports
+ ```
+
+3. **Create a default transcript template** in Speakr settings with the format you want:
+ ```
+ [{{start_time}}] {{speaker}}: {{text}}
+ ```
+
+4. **Restart Speakr** to apply the changes:
+ ```bash
+ docker compose restart
+ ```
+
+Now when any recording finishes processing, Speakr automatically writes a markdown file to your Obsidian vault with:
+- Metadata (date, participants, tags, processing times)
+- Notes (if you added any)
+- AI-generated summary
+- Formatted transcription using your template
+
+Files appear in subdirectories by username, so `alice` gets her transcripts in `Transcripts/alice/` and `bob` gets his in `Transcripts/bob/`. Obsidian indexes these automatically, and you can link to them from daily notes, search across all transcripts, and reference them alongside your other knowledge.
+
+This same approach works with Logseq, Notion (if you set the export directory to Notion's import folder), or any markdown-based knowledge management system.
+
## Troubleshooting
### Template Not Appearing
diff --git a/docs/user-guide/transcripts.md b/docs/user-guide/transcripts.md
index 8a7f0d9f..e43dfa64 100644
--- a/docs/user-guide/transcripts.md
+++ b/docs/user-guide/transcripts.md
@@ -6,7 +6,8 @@ Once your audio has been processed, Speakr provides a rich set of tools for view
When you select a recording from the sidebar, the center panel displays the full transcription. The layout is designed for easy reading and navigation, with clear visual indicators for different speakers and timestamps.
-![Transcription View](../assets/images/screenshots/recording view with simple transcription view and chat visible.png)
+![Transcription View with Audio Sync](../assets/images/screenshots/audio-sync-bubble-view.png)
+*Transcription view with real-time audio synchronization and active segment highlighting*
## Speaker Identification
@@ -16,9 +17,10 @@ If your recording was processed with [speaker diarization](../features.md#speake
When you need to assign real names to speaker labels, click the speaker identification button in the toolbar. This opens a modal where you can:
-![Speaker ID Modal](../assets/images/screenshots/speaker id modal.png)
+![Speaker ID Modal with Voice Profiles](../assets/images/screenshots/speaker-identification-voice-profiles.png)
+*Speaker identification modal with AI-powered voice profile suggestions based on previous recordings*
-The speaker identification modal shows each detected speaker with a sample of their dialogue to help you identify them. You can enter real names for each speaker, and these names will replace the generic labels throughout the transcription. The system remembers these assignments for future reference, making it easier to identify the same speakers in subsequent recordings.
+The speaker identification modal shows each detected speaker with a sample of their dialogue to help you identify them. When you've identified speakers in previous recordings, Speakr's voice recognition system analyzes voice embeddings and provides intelligent suggestions with confidence scores. You can enter real names for each speaker, and these names will replace the generic labels throughout the transcription. The system remembers these assignments and builds voice profiles, making it easier and faster to identify the same speakers in subsequent recordings.
### Managing Saved Speakers
@@ -44,7 +46,7 @@ For standard transcriptions without speaker diarization, click the Edit button i
For transcriptions processed with [ASR](../features.md#speaker-diarization) and speaker diarization, Speakr offers a powerful segment-based editor that preserves the structure and timing of your transcription. If you encounter issues with speaker identification, see [troubleshooting](../troubleshooting.md#speaker-identification-not-working).
-![ASR Transcription Editor](../assets/images/screenshots/edit transcript with ASR.png)
+![ASR Transcription Editor](../assets/images/screenshots/edit-transcription-modal.png)
The ASR editor presents your transcription as a table of segments, where each row represents a single utterance with its associated metadata. For each segment, you can:
@@ -72,11 +74,48 @@ The default simple view presents the transcription as flowing text with inline s
The bubble view formats the transcription like a chat conversation, with each speaker's contributions in separate message bubbles. This format works particularly well for interviews, debates, or any recording with back-and-forth dialogue. The visual separation makes it easier to follow who said what in rapid exchanges.
+## Audio Synchronization and Follow Mode
+
+For recordings processed with [speaker diarization](../features.md#speaker-diarization), Speakr provides bidirectional synchronization between the audio player and transcript, creating an interactive reading experience.
+
+### Click-to-Play Navigation
+
+Click on any part of the transcript to jump directly to that moment in the audio. This works in both simple and bubble views, allowing you to quickly navigate to specific portions of the conversation you want to hear. Each transcript segment includes timestamp information that seamlessly syncs with the audio player.
+
+### Active Segment Highlighting
+
+As your audio plays, Speakr automatically highlights the currently spoken text in the transcript. The active segment is displayed with a prominent rounded box and subtle animation, making it effortless to follow along with the audio. This real-time highlighting works in both view modes:
+
+- **Simple View**: The current speaker segment is highlighted with rounded corners and increased padding for clear visibility
+- **Bubble View**: The active message bubble scales slightly and receives the same highlight treatment
+
+### Auto-Scroll Follow Mode
+
+Enable follow mode using the compact checkbox control in the transcript header (indicated by vertical arrows icon). When active, the transcript panel automatically scrolls to keep the currently playing segment centered in view. This is particularly useful for:
+
+- Following along during long recordings without manual scrolling
+- Reviewing specific sections while listening at different playback speeds
+- Accessibility - keeping visual and audio content synchronized
+
+Your follow mode preference is saved automatically and persists across sessions and different recordings. The feature intelligently resets when you switch between recordings, ensuring a clean slate for each playback session.
+
+### Follow Mode in Action
+
+The auto-scroll follow mode works seamlessly in both view modes and adapts to your theme preference:
+
+![Follow Mode Simple View - Dark Theme](../assets/images/screenshots/highlighted-transcript-following-simple-dark.png)
+*Auto-scroll follow mode in simple view with dark theme - transcript automatically scrolls to keep current segment visible*
+
+![Follow Mode Simple View - Light Theme](../assets/images/screenshots/highlighted-transcript-following-simple-light.png)
+*Follow mode works seamlessly in light theme, maintaining perfect readability and visual clarity*
+
+The highlighted segment uses rounded corners and subtle animations to draw your eye to the currently playing text without being distracting. The auto-scroll behavior is smooth and intelligent, maintaining the active segment in the center of your view for comfortable reading during long recordings.
+
## Using the Summary Feature
The Summary tab in the right panel contains an AI-generated overview of your recording. This summary is automatically created after transcription and captures key points, decisions, and action items.
-![Summary View](../assets/images/screenshots/Summary View.png)
+![Summary View](../assets/images/screenshots/main-view-summary-tab.png)
The summary is designed to save you time by highlighting the most important information from your recording. It typically includes main topics discussed, key decisions or conclusions reached, action items and assignments, important dates or deadlines mentioned, and any significant problems or concerns raised.
@@ -156,11 +195,11 @@ Event extraction can be toggled on or off in your Account Settings under the Cus
The Chat tab provides an AI assistant that can answer questions about your recording. This feature is particularly powerful for long recordings where finding specific information might be time-consuming.
-![Chat Interface](../assets/images/screenshots/chat view with question.png)
+![Chat Interface](../assets/images/screenshots/chat-interface.png)
### Effective Chat Queries
-The AI chat understands context and can answer various types of questions about your recording. You can ask for specific information like "What did Sarah say about the budget?" or "When is the deadline for the project?" The AI can also provide analysis, such as "What were the main concerns raised?" or "Summarize the action items for the marketing team."
+The AI chat understands context and can answer various types of questions about your recording. You can ask for specific information like "What did Sarah say about the budget?" or "When is the deadline for the project?" The AI can also provide analysis, such as "What were the main concerns raised?" or "Summarize the action items for the marketing group."
The chat maintains context throughout your conversation, so you can ask follow-up questions. For example, after asking about budget discussions, you might follow up with "What solutions were proposed?" The AI will understand you're still talking about the budget topic.
@@ -176,27 +215,33 @@ Your entire chat conversation can be exported for future reference or sharing. T
**Copy to Clipboard**: Click the copy button to copy the entire chat conversation to your clipboard. This preserves the question-and-answer format, making it easy to paste into emails, reports, or documentation. Each message includes a label indicating whether it's from you or the AI assistant.
-**Download as Word Document**: The download button exports your complete chat history as a formatted Microsoft Word (.docx) file. This includes all questions and responses in a clean, professional format that's easy to share with team members or include in reports. The file is automatically named with the recording title and export date, making it easy to organize multiple chat exports.
+**Download as Word Document**: The download button exports your complete chat history as a formatted Microsoft Word (.docx) file. This includes all questions and responses in a clean, professional format that's easy to share with group members or include in reports. The file is automatically named with the recording title and export date, making it easy to organize multiple chat exports.
These export features are particularly useful when you've used the chat to extract specific insights or conduct a detailed analysis of the recording, allowing you to preserve and share your findings without having to recreate the conversation.
## Adding and Managing Notes
-The Notes tab is your personal workspace for adding context and thoughts about the recording. These notes are private to you and complement the transcription with your own insights.
+The Notes tab is your personal workspace for adding context and thoughts about the recording. These notes are **always private** - only you can see them, whether you own the recording or it's been shared with you. This is different from summaries, which are shared with all users who have access to the recording.
-![Notes Tab](../assets/images/screenshots/notes tab.png)
+**Important: Notes are Personal, Summaries are Shared**
+- **Notes**: Always private to each user. You can add and edit your own notes on any recording (owned or shared) without needing any special permissions. Other users cannot see your notes, and you cannot see theirs.
+- **Summary**: Shared content created by the recording owner. Only users with edit permission can modify the summary, and all users with access to the recording see the same summary.
+
+![Notes Tab](../assets/images/screenshots/main-view-notes-tab.png)
Notes support full markdown formatting, allowing you to create structured documents with headers, lists, links, and emphasis. The markdown editor provides a toolbar with formatting options and supports keyboard shortcuts for efficient note-taking. You can switch between edit and preview modes to see how your formatted notes will appear.
Common uses for notes include:
-- Personal reflections on the meeting or conversation that wouldn't be appropriate in the shared transcription
+- Personal reflections on the meeting or conversation that you want to keep private
- Follow-up tasks that you need to complete based on the discussion
- Additional context about decisions made or why certain topics were discussed
- Links to related documents or resources mentioned in the recording
- Questions you want to research or clarify later
-Your notes are fully searchable alongside transcriptions, making them valuable for future reference. You can search for a specific term and find it whether it appears in a transcription or in your personal notes. Notes are auto-saved as you type, ensuring you never lose your thoughts.
+Your notes are fully searchable alongside transcriptions, making them valuable for future reference. You can search for a specific term and find it whether it appears in a transcription or in your personal notes. The search will only find results in your own personal notes - you cannot search through other users' notes on shared recordings since notes are always private. Notes are auto-saved as you type, ensuring you never lose your thoughts.
+
+When viewing a shared recording, you can always add and edit your own notes without needing any special permissions. This allows you to annotate shared content with your own thoughts, action items, and follow-ups while keeping them completely private from the recording owner and other users.
## Copying and Exporting
diff --git a/scripts/migrate_docker.sh b/scripts/migrate_docker.sh
index 780f1fa2..c2eaa7ce 100644
--- a/scripts/migrate_docker.sh
+++ b/scripts/migrate_docker.sh
@@ -7,9 +7,9 @@ echo "🎯 Inquire Mode Manual Migration for Docker"
echo "============================================="
# Check if container is running
-if ! docker-compose ps | grep -q "speakr.*Up"; then
+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"
+ echo " docker compose up -d"
exit 1
fi
@@ -19,7 +19,7 @@ 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
+docker compose exec app python migrate_existing_recordings.py --dry-run
echo ""
echo "⚠️ Do you want to proceed with processing these recordings?"
@@ -29,7 +29,7 @@ echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
echo "🚀 Starting migration..."
- docker-compose exec app python migrate_existing_recordings.py --process --batch-size 5
+ docker compose exec app python migrate_existing_recordings.py --process --batch-size 5
if [ $? -eq 0 ]; then
echo "✅ Migration completed successfully!"
diff --git a/scripts/migrate_team_to_group.py b/scripts/migrate_team_to_group.py
new file mode 100755
index 00000000..e7546c47
--- /dev/null
+++ b/scripts/migrate_team_to_group.py
@@ -0,0 +1,137 @@
+#!/usr/bin/env python3
+"""
+Migration script to rename team tables to group tables.
+This handles the refactoring from team-based to group-based terminology.
+"""
+import sys
+import os
+
+# Add the parent directory to the path to import app modules
+sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
+
+from src.app import app, db
+from sqlalchemy import text
+
+def migrate_tables():
+ """Copy data from team tables to group tables and remove old tables."""
+ with app.app_context():
+ try:
+ # Check if old tables exist
+ inspector = db.inspect(db.engine)
+ existing_tables = inspector.get_table_names()
+
+ print("Existing tables:", existing_tables)
+
+ # Check if we need to migrate data
+ if 'team' in existing_tables and 'group' in existing_tables:
+ # Both tables exist - need to copy data
+ print("\nBoth 'team' and 'group' tables exist. Copying data...")
+
+ # Check if there's data in the old table
+ result = db.session.execute(text('SELECT COUNT(*) FROM team'))
+ old_count = result.scalar()
+ print(f"Found {old_count} records in 'team' table")
+
+ if old_count > 0:
+ # Copy data from team to group
+ print("Copying data from 'team' to 'group'...")
+ db.session.execute(text(
+ 'INSERT INTO "group" (id, name, description, created_at) '
+ 'SELECT id, name, description, created_at FROM team'
+ ))
+ db.session.commit()
+ print(f"✓ Copied {old_count} records to 'group' table")
+
+ # Drop the old team table
+ print("Dropping old 'team' table...")
+ db.session.execute(text('DROP TABLE team'))
+ db.session.commit()
+ print("✓ Dropped old 'team' table")
+
+ elif 'team' in existing_tables and 'group' not in existing_tables:
+ # Only old table exists - rename it
+ print("\nRenaming 'team' table to 'group'...")
+ db.session.execute(text('ALTER TABLE team RENAME TO "group"'))
+ db.session.commit()
+ print("✓ Renamed 'team' to 'group'")
+ else:
+ print("\n'team' table not found or already migrated")
+
+ # Migrate team_membership
+ if 'team_membership' in existing_tables and 'group_membership' in existing_tables:
+ # Both tables exist - need to copy data
+ print("\nBoth 'team_membership' and 'group_membership' tables exist. Copying data...")
+
+ # Check if there's data in the old table
+ result = db.session.execute(text('SELECT COUNT(*) FROM team_membership'))
+ old_count = result.scalar()
+ print(f"Found {old_count} records in 'team_membership' table")
+
+ if old_count > 0:
+ # Copy data from team_membership to group_membership
+ print("Copying data from 'team_membership' to 'group_membership'...")
+ db.session.execute(text(
+ 'INSERT INTO group_membership (id, user_id, group_id, role, joined_at) '
+ 'SELECT id, user_id, team_id, role, joined_at FROM team_membership'
+ ))
+ db.session.commit()
+ print(f"✓ Copied {old_count} records to 'group_membership' table")
+
+ # Drop the old team_membership table
+ print("Dropping old 'team_membership' table...")
+ db.session.execute(text('DROP TABLE team_membership'))
+ db.session.commit()
+ print("✓ Dropped old 'team_membership' table")
+
+ elif 'team_membership' in existing_tables and 'group_membership' not in existing_tables:
+ # Only old table exists - rename it
+ print("\nRenaming 'team_membership' table to 'group_membership'...")
+ db.session.execute(text('ALTER TABLE team_membership RENAME TO group_membership'))
+ db.session.commit()
+ print("✓ Renamed 'team_membership' to 'group_membership'")
+ else:
+ print("\n'team_membership' table not found or already migrated")
+
+ # Migrate team_id to group_id in tags table
+ print("\nMigrating tag associations from team_id to group_id...")
+ result = db.session.execute(text(
+ 'UPDATE tag SET group_id = team_id WHERE team_id IS NOT NULL AND group_id IS NULL'
+ ))
+ db.session.commit()
+ print(f"✓ Migrated {result.rowcount} tag associations")
+
+ # Migrate share_with_team_lead to share_with_group_lead in tags
+ result = db.session.execute(text(
+ 'UPDATE tag SET share_with_group_lead = share_with_team_lead WHERE share_with_team_lead IS NOT NULL AND share_with_group_lead IS NULL'
+ ))
+ db.session.commit()
+ print(f"✓ Migrated {result.rowcount} share_with_lead settings")
+
+ print("\n✅ Migration completed successfully!")
+ print("\nPlease restart the application for changes to take full effect.")
+
+ except Exception as e:
+ print(f"\n❌ Error during migration: {e}")
+ db.session.rollback()
+ sys.exit(1)
+
+if __name__ == '__main__':
+ print("=" * 60)
+ print("Team to Group Migration Script")
+ print("=" * 60)
+ print("\nThis script will rename database tables:")
+ print(" - 'team' → 'group'")
+ print(" - 'team_membership' → 'group_membership'")
+
+ # Check for --yes flag to skip confirmation
+ if '--yes' in sys.argv or '-y' in sys.argv:
+ print("\nAuto-confirming migration (--yes flag detected)...\n")
+ else:
+ print("\nPress Ctrl+C to cancel, or Enter to continue...")
+ try:
+ input()
+ except KeyboardInterrupt:
+ print("\n\nMigration cancelled.")
+ sys.exit(0)
+
+ migrate_tables()
diff --git a/src/api/__init__.py b/src/api/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/api/admin.py b/src/api/admin.py
new file mode 100644
index 00000000..34dfa940
--- /dev/null
+++ b/src/api/admin.py
@@ -0,0 +1,868 @@
+"""
+Administrative functions and user management.
+
+This blueprint was auto-generated from app.py route extraction.
+"""
+
+import os
+import json
+import time
+from datetime import datetime, timedelta
+from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, send_file, Response, current_app
+from flask_login import login_required, current_user
+from werkzeug.utils import secure_filename
+
+from src.database import db
+from src.models import *
+from src.utils import *
+from src.services.retention import is_recording_exempt_from_deletion, get_retention_days_for_recording, process_auto_deletion
+from src.services.embeddings import EMBEDDINGS_AVAILABLE, process_recording_chunks
+from src.config.startup import get_file_monitor_functions
+
+# Create blueprint
+admin_bp = Blueprint('admin', __name__)
+
+# Configuration from environment
+ENABLE_INQUIRE_MODE = os.environ.get('ENABLE_INQUIRE_MODE', 'false').lower() == 'true'
+ENABLE_AUTO_DELETION = os.environ.get('ENABLE_AUTO_DELETION', 'false').lower() == 'true'
+USERS_CAN_DELETE = os.environ.get('USERS_CAN_DELETE', 'true').lower() == 'true'
+ENABLE_INTERNAL_SHARING = os.environ.get('ENABLE_INTERNAL_SHARING', 'false').lower() == 'true'
+USE_ASR_ENDPOINT = os.environ.get('USE_ASR_ENDPOINT', 'false').lower() == 'true'
+GLOBAL_RETENTION_DAYS = int(os.environ.get('GLOBAL_RETENTION_DAYS', '0'))
+DELETION_MODE = os.environ.get('DELETION_MODE', 'hard')
+
+# Global helpers (will be injected from app)
+has_recording_access = None
+bcrypt = None
+csrf = None
+limiter = None
+
+def init_admin_helpers(**kwargs):
+ """Initialize helper functions and extensions from app."""
+ global has_recording_access, bcrypt, csrf, limiter
+ has_recording_access = kwargs.get('has_recording_access')
+ bcrypt = kwargs.get('bcrypt')
+ csrf = kwargs.get('csrf')
+ limiter = kwargs.get('limiter')
+
+
+def csrf_exempt(f):
+ """Decorator placeholder for CSRF exemption - applied after initialization."""
+ from functools import wraps
+ @wraps(f)
+ def wrapper(*args, **kwargs):
+ return f(*args, **kwargs)
+ wrapper._csrf_exempt = True
+ return wrapper
+
+
+# --- Routes ---
+
+@admin_bp.route('/admin', methods=['GET'])
+@login_required
+def admin():
+ # Check if user is admin OR group admin
+ is_team_admin = GroupMembership.query.filter_by(
+ user_id=current_user.id,
+ role='admin'
+ ).first() is not None
+
+ if not current_user.is_admin and not is_team_admin:
+ flash('You do not have permission to access the admin page.', 'danger')
+ return redirect(url_for('recordings.index'))
+
+ # Redirect group admins to their dedicated management page
+ if is_team_admin and not current_user.is_admin:
+ return redirect(url_for('admin.group_management'))
+
+ # Full admins only get here
+ user_language = current_user.ui_language if current_user.is_authenticated and current_user.ui_language else 'en'
+ return render_template('admin.html',
+ title='Admin Dashboard',
+ inquire_mode_enabled=ENABLE_INQUIRE_MODE,
+ global_retention_days=GLOBAL_RETENTION_DAYS,
+ is_group_admin_only=False,
+ user_language=user_language)
+
+
+@admin_bp.route('/group-management', methods=['GET'])
+@login_required
+def group_management():
+ """Dedicated group management page for group admins (non-full admins)."""
+ # Check if user is a group admin
+ is_team_admin = GroupMembership.query.filter_by(
+ user_id=current_user.id,
+ role='admin'
+ ).first() is not None
+
+ if not is_team_admin:
+ flash('You do not have permission to access group management.', 'danger')
+ return redirect(url_for('recordings.index'))
+
+ # If they're a full admin, redirect to main admin dashboard
+ if current_user.is_admin:
+ return redirect(url_for('admin.admin'))
+
+ user_language = current_user.ui_language if current_user.is_authenticated and current_user.ui_language else 'en'
+ return render_template('group-admin.html',
+ title='Group Management',
+ global_retention_days=GLOBAL_RETENTION_DAYS,
+ user_language=user_language)
+
+
+
+@admin_bp.route('/admin/users', methods=['GET'])
+@login_required
+def admin_get_users():
+ # Check if user is admin OR group admin
+ is_team_admin = GroupMembership.query.filter_by(
+ user_id=current_user.id,
+ role='admin'
+ ).first() is not None
+
+ if not current_user.is_admin and not is_team_admin:
+ return jsonify({'error': 'Unauthorized'}), 403
+
+ users = User.query.all()
+ user_data = []
+
+ for user in users:
+ # Get recordings count and storage used
+ recordings_count = len(user.recordings)
+ storage_used = sum(r.file_size for r in user.recordings if r.file_size) or 0
+
+ user_data.append({
+ 'id': user.id,
+ 'username': user.username,
+ 'email': user.email,
+ 'is_admin': user.is_admin,
+ 'can_share_publicly': user.can_share_publicly,
+ 'recordings_count': recordings_count,
+ 'storage_used': storage_used
+ })
+
+ return jsonify(user_data)
+
+
+
+@admin_bp.route('/admin/users', methods=['POST'])
+@login_required
+def admin_add_user():
+ # Check if user is admin
+ if not current_user.is_admin:
+ return jsonify({'error': 'Unauthorized'}), 403
+
+ data = request.json
+ if not data:
+ return jsonify({'error': 'No data provided'}), 400
+
+ # Validate required fields
+ required_fields = ['username', 'email', 'password']
+ for field in required_fields:
+ if field not in data:
+ return jsonify({'error': f'Missing required field: {field}'}), 400
+
+ # Check if username or email already exists
+ if User.query.filter_by(username=data['username']).first():
+ return jsonify({'error': 'Username already exists'}), 400
+
+ if User.query.filter_by(email=data['email']).first():
+ return jsonify({'error': 'Email already exists'}), 400
+
+ # Create new user
+ hashed_password = bcrypt.generate_password_hash(data['password']).decode('utf-8')
+ new_user = User(
+ username=data['username'],
+ email=data['email'],
+ password=hashed_password,
+ is_admin=data.get('is_admin', False)
+ )
+
+ db.session.add(new_user)
+ db.session.commit()
+
+ return jsonify({
+ 'id': new_user.id,
+ 'username': new_user.username,
+ 'email': new_user.email,
+ 'is_admin': new_user.is_admin,
+ 'recordings_count': 0,
+ 'storage_used': 0
+ }), 201
+
+
+
+@admin_bp.route('/admin/users/<int:user_id>', methods=['PUT'])
+@login_required
+def admin_update_user(user_id):
+ # Check if user is admin
+ if not current_user.is_admin:
+ return jsonify({'error': 'Unauthorized'}), 403
+
+ user = db.session.get(User, user_id)
+ if not user:
+ return jsonify({'error': 'User not found'}), 404
+
+ data = request.json
+ if not data:
+ return jsonify({'error': 'No data provided'}), 400
+
+ # Update user fields
+ if 'username' in data and data['username'] != user.username:
+ # Check if username already exists
+ if User.query.filter_by(username=data['username']).first():
+ return jsonify({'error': 'Username already exists'}), 400
+ user.username = data['username']
+
+ if 'email' in data and data['email'] != user.email:
+ # Check if email already exists
+ if User.query.filter_by(email=data['email']).first():
+ return jsonify({'error': 'Email already exists'}), 400
+ user.email = data['email']
+
+ if 'password' in data and data['password']:
+ user.password = bcrypt.generate_password_hash(data['password']).decode('utf-8')
+
+ if 'is_admin' in data:
+ user.is_admin = data['is_admin']
+
+ if 'can_share_publicly' in data:
+ user.can_share_publicly = data['can_share_publicly']
+
+ db.session.commit()
+
+ # Get recordings count and storage used
+ recordings_count = len(user.recordings)
+ storage_used = sum(r.file_size for r in user.recordings if r.file_size) or 0
+
+ return jsonify({
+ 'id': user.id,
+ 'username': user.username,
+ 'email': user.email,
+ 'is_admin': user.is_admin,
+ 'can_share_publicly': user.can_share_publicly,
+ 'recordings_count': recordings_count,
+ 'storage_used': storage_used
+ })
+
+
+
+@admin_bp.route('/admin/users/<int:user_id>', methods=['DELETE'])
+@login_required
+def admin_delete_user(user_id):
+ # Check if user is admin
+ if not current_user.is_admin:
+ return jsonify({'error': 'Unauthorized'}), 403
+
+ # Prevent deleting self
+ if user_id == current_user.id:
+ return jsonify({'error': 'Cannot delete your own account'}), 400
+
+ user = db.session.get(User, user_id)
+ if not user:
+ 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:
+ current_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):
+ os.remove(recording.audio_path)
+ except Exception as e:
+ current_app.logger.error(f"Error deleting audio file {recording.audio_path}: {e}")
+
+ # 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:
+ current_app.logger.info(f"Successfully deleted {total_chunks} embeddings and chunks for user {user_id}")
+
+ return jsonify({'success': True})
+
+
+
+@admin_bp.route('/admin/users/<int:user_id>/toggle-admin', methods=['POST'])
+@login_required
+def admin_toggle_admin(user_id):
+ # Check if user is admin
+ if not current_user.is_admin:
+ return jsonify({'error': 'Unauthorized'}), 403
+
+ # Prevent changing own admin status
+ if user_id == current_user.id:
+ return jsonify({'error': 'Cannot change your own admin status'}), 400
+
+ user = db.session.get(User, user_id)
+ if not user:
+ return jsonify({'error': 'User not found'}), 404
+
+ # Toggle admin status
+ user.is_admin = not user.is_admin
+ db.session.commit()
+
+ return jsonify({'success': True, 'is_admin': user.is_admin})
+
+
+
+@admin_bp.route('/admin/stats', methods=['GET'])
+@login_required
+def admin_get_stats():
+ # Check if user is admin
+ if not current_user.is_admin:
+ return jsonify({'error': 'Unauthorized'}), 403
+
+ # Get total users
+ total_users = User.query.count()
+
+ # Get total recordings
+ total_recordings = Recording.query.count()
+
+ # Get recordings by status
+ completed_recordings = Recording.query.filter_by(status='COMPLETED').count()
+ processing_recordings = Recording.query.filter(Recording.status.in_(['PROCESSING', 'SUMMARIZING'])).count()
+ pending_recordings = Recording.query.filter_by(status='PENDING').count()
+ failed_recordings = Recording.query.filter_by(status='FAILED').count()
+
+ # Get total storage used
+ total_storage = db.session.query(db.func.sum(Recording.file_size)).scalar() or 0
+
+ # Get top users by storage
+ top_users_query = db.session.query(
+ User.id,
+ User.username,
+ db.func.count(Recording.id).label('recordings_count'),
+ db.func.sum(Recording.file_size).label('storage_used')
+ ).join(Recording, User.id == Recording.user_id, isouter=True) \
+ .group_by(User.id) \
+ .order_by(db.func.sum(Recording.file_size).desc()) \
+ .limit(5)
+
+ top_users = []
+ for user_id, username, recordings_count, storage_used in top_users_query:
+ top_users.append({
+ 'id': user_id,
+ 'username': username,
+ 'recordings_count': recordings_count or 0,
+ 'storage_used': storage_used or 0
+ })
+
+ # Get total queries (chat requests)
+ # This is a placeholder - you would need to track this in your database
+ total_queries = 0
+
+ return jsonify({
+ 'total_users': total_users,
+ 'total_recordings': total_recordings,
+ 'completed_recordings': completed_recordings,
+ 'processing_recordings': processing_recordings,
+ 'pending_recordings': pending_recordings,
+ 'failed_recordings': failed_recordings,
+ 'total_storage': total_storage,
+ 'top_users': top_users,
+ 'total_queries': total_queries
+ })
+
+# --- Transcript Template Routes ---
+
+
+@admin_bp.route('/admin/settings', methods=['GET'])
+@login_required
+def admin_get_settings():
+ # Check if user is admin
+ if not current_user.is_admin:
+ return jsonify({'error': 'Unauthorized'}), 403
+
+ settings = SystemSetting.query.all()
+ return jsonify([setting.to_dict() for setting in settings])
+
+
+
+@admin_bp.route('/admin/settings', methods=['POST'])
+@login_required
+def admin_update_setting():
+ # Check if user is admin
+ if not current_user.is_admin:
+ return jsonify({'error': 'Unauthorized'}), 403
+
+ data = request.json
+ if not data:
+ return jsonify({'error': 'No data provided'}), 400
+
+ key = data.get('key')
+ value = data.get('value')
+ description = data.get('description')
+ setting_type = data.get('setting_type', 'string')
+
+ if not key:
+ return jsonify({'error': 'Setting key is required'}), 400
+
+ # Validate setting type
+ valid_types = ['string', 'integer', 'boolean', 'float']
+ if setting_type not in valid_types:
+ return jsonify({'error': f'Invalid setting type. Must be one of: {", ".join(valid_types)}'}), 400
+
+ # Validate value based on type
+ if setting_type == 'integer':
+ try:
+ int(value) if value is not None and value != '' else None
+ except (ValueError, TypeError):
+ return jsonify({'error': 'Value must be a valid integer'}), 400
+ elif setting_type == 'float':
+ try:
+ float(value) if value is not None and value != '' else None
+ except (ValueError, TypeError):
+ return jsonify({'error': 'Value must be a valid number'}), 400
+ elif setting_type == 'boolean':
+ if value not in ['true', 'false', '1', '0', 'yes', 'no', True, False, 1, 0]:
+ return jsonify({'error': 'Value must be a valid boolean (true/false, 1/0, yes/no)'}), 400
+
+ try:
+ setting = SystemSetting.set_setting(key, value, description, setting_type)
+ return jsonify(setting.to_dict())
+ except Exception as e:
+ db.session.rollback()
+ current_app.logger.error(f"Error updating setting {key}: {e}")
+ return jsonify({'error': str(e)}), 500
+
+# --- Configuration API ---
+
+
+@admin_bp.route('/admin/auto-deletion/run', methods=['POST'])
+@login_required
+@csrf_exempt # Exempt since already protected by admin authentication
+def run_auto_deletion():
+ """Admin endpoint to manually trigger auto-deletion process."""
+ if not current_user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+
+ try:
+ stats = process_auto_deletion()
+ return jsonify(stats)
+ except Exception as e:
+ current_app.logger.error(f"Error running auto-deletion: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+
+@admin_bp.route('/admin/auto-deletion/stats', methods=['GET'])
+@login_required
+def get_auto_deletion_stats():
+ """Get statistics about recordings eligible for auto-deletion."""
+ if not current_user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+
+ try:
+ stats = {
+ 'enabled': ENABLE_AUTO_DELETION,
+ 'global_retention_days': GLOBAL_RETENTION_DAYS,
+ 'deletion_mode': DELETION_MODE,
+ 'eligible_count': 0,
+ 'exempted_count': 0,
+ 'no_retention_count': 0,
+ 'archived_count': 0
+ }
+
+ if ENABLE_AUTO_DELETION:
+ # Check ALL completed recordings (per-recording retention)
+ all_recordings = Recording.query.filter(
+ Recording.status == 'COMPLETED'
+ ).all()
+
+ eligible = 0
+ exempted = 0
+ no_retention = 0
+ current_time = datetime.utcnow()
+
+ for recording in all_recordings:
+ # Check if exempt from deletion entirely
+ if is_recording_exempt_from_deletion(recording):
+ exempted += 1
+ continue
+
+ # Get the effective retention period for this recording
+ retention_days = get_retention_days_for_recording(recording)
+
+ if not retention_days:
+ no_retention += 1
+ continue
+
+ # Calculate cutoff for this specific recording
+ cutoff_date = current_time - timedelta(days=retention_days)
+
+ # Check if past retention period
+ if recording.created_at < cutoff_date:
+ eligible += 1
+
+ stats['eligible_count'] = eligible
+ stats['exempted_count'] = exempted
+ stats['no_retention_count'] = no_retention
+
+ # Count already archived recordings
+ stats['archived_count'] = Recording.query.filter(
+ Recording.audio_deleted_at.is_not(None)
+ ).count()
+
+ return jsonify(stats)
+ except Exception as e:
+ current_app.logger.error(f"Error fetching auto-deletion stats: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+
+@admin_bp.route('/admin/auto-deletion/preview', methods=['GET'])
+@login_required
+def preview_auto_deletion():
+ """Preview what would be deleted without actually deleting (dry-run)."""
+ if not current_user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+
+ try:
+ if not ENABLE_AUTO_DELETION:
+ return jsonify({'error': 'Auto-deletion is not enabled'}), 400
+
+ # Check ALL completed recordings (per-recording retention)
+ all_recordings = Recording.query.filter(
+ Recording.status == 'COMPLETED'
+ ).all()
+
+ preview_data = {
+ 'total_checked': len(all_recordings),
+ 'would_delete': [],
+ 'would_exempt': [],
+ 'no_retention': [],
+ 'deletion_mode': DELETION_MODE,
+ 'global_retention_days': GLOBAL_RETENTION_DAYS,
+ 'supports_per_recording_retention': True
+ }
+
+ current_time = datetime.utcnow()
+
+ for recording in all_recordings:
+ rec_data = {
+ 'id': recording.id,
+ 'title': recording.title,
+ 'created_at': recording.created_at.isoformat(),
+ 'age_days': (current_time - recording.created_at).days,
+ 'tags': [tag.tag.name for tag in recording.tag_associations]
+ }
+
+ # Check if exempt from deletion entirely
+ if is_recording_exempt_from_deletion(recording):
+ rec_data['exempt_reason'] = []
+ if recording.deletion_exempt:
+ rec_data['exempt_reason'].append('manually_exempted')
+ for tag_assoc in recording.tag_associations:
+ if tag_assoc.tag.protect_from_deletion:
+ rec_data['exempt_reason'].append(f'tag:{tag_assoc.tag.name}')
+ preview_data['would_exempt'].append(rec_data)
+ continue
+
+ # Get the effective retention period for this recording
+ retention_days = get_retention_days_for_recording(recording)
+
+ if not retention_days:
+ rec_data['reason'] = 'no_retention_policy'
+ preview_data['no_retention'].append(rec_data)
+ continue
+
+ rec_data['retention_days'] = retention_days
+
+ # Calculate cutoff for this specific recording
+ cutoff_date = current_time - timedelta(days=retention_days)
+
+ # Check if past retention period
+ if recording.created_at < cutoff_date:
+ rec_data['days_past_retention'] = (current_time - cutoff_date).days
+ preview_data['would_delete'].append(rec_data)
+
+ return jsonify(preview_data)
+ except Exception as e:
+ current_app.logger.error(f"Error previewing auto-deletion: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+
+@admin_bp.route('/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:
+ current_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:
+ current_app.logger.error(f"Error in migration API: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+# --- Auto-Processing File Monitor Integration ---
+
+
+@admin_bp.route('/admin/auto-process/status', methods=['GET'])
+@login_required
+def admin_get_auto_process_status():
+ """Get the status of the automated file processing system."""
+ if not current_user.is_admin:
+ return jsonify({'error': 'Unauthorized'}), 403
+
+ try:
+ _, _, get_file_monitor_status = get_file_monitor_functions()
+ status = get_file_monitor_status()
+
+ # Add configuration info
+ config = {
+ 'enabled': os.environ.get('ENABLE_AUTO_PROCESSING', 'false').lower() == 'true',
+ 'watch_directory': os.environ.get('AUTO_PROCESS_WATCH_DIR', '/data/auto-process'),
+ 'check_interval': int(os.environ.get('AUTO_PROCESS_CHECK_INTERVAL', '30')),
+ 'mode': os.environ.get('AUTO_PROCESS_MODE', 'admin_only'),
+ 'default_username': os.environ.get('AUTO_PROCESS_DEFAULT_USERNAME')
+ }
+
+ return jsonify({
+ 'status': status,
+ 'config': config
+ })
+
+ except Exception as e:
+ current_app.logger.error(f"Error getting auto-process status: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+
+@admin_bp.route('/admin/auto-process/start', methods=['POST'])
+@login_required
+def admin_start_auto_process():
+ """Start the automated file processing system."""
+ if not current_user.is_admin:
+ return jsonify({'error': 'Unauthorized'}), 403
+
+ try:
+ start_file_monitor, _, _ = get_file_monitor_functions()
+ start_file_monitor()
+ return jsonify({'success': True, 'message': 'Auto-processing started'})
+ except Exception as e:
+ current_app.logger.error(f"Error starting auto-process: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+
+@admin_bp.route('/admin/auto-process/stop', methods=['POST'])
+@login_required
+def admin_stop_auto_process():
+ """Stop the automated file processing system."""
+ if not current_user.is_admin:
+ return jsonify({'error': 'Unauthorized'}), 403
+
+ try:
+ _, stop_file_monitor, _ = get_file_monitor_functions()
+ stop_file_monitor()
+ return jsonify({'success': True, 'message': 'Auto-processing stopped'})
+ except Exception as e:
+ current_app.logger.error(f"Error stopping auto-process: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+
+@admin_bp.route('/admin/auto-process/config', methods=['POST'])
+@login_required
+def admin_update_auto_process_config():
+ """Update auto-processing configuration (requires restart)."""
+ if not current_user.is_admin:
+ return jsonify({'error': 'Unauthorized'}), 403
+
+ try:
+ data = request.json
+ if not data:
+ return jsonify({'error': 'No configuration data provided'}), 400
+
+ # This endpoint would typically update environment variables or config files
+ # For now, we'll just return the current config and note that restart is required
+ return jsonify({
+ 'success': True,
+ 'message': 'Configuration updated. Restart required to apply changes.',
+ 'note': 'Environment variables need to be updated manually and application restarted.'
+ })
+
+ except Exception as e:
+ current_app.logger.error(f"Error updating auto-process config: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+
+@admin_bp.route('/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
+ current_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:
+ current_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:
+ current_app.logger.error(f"Error in admin process recordings endpoint: {e}")
+ db.session.rollback()
+ return jsonify({'error': str(e)}), 500
+
+
+
+@admin_bp.route('/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:
+ current_app.logger.error(f"Error getting inquire status: {e}")
+ return jsonify({'error': str(e)}), 500
+
+# --- Group Management API (Admin Only) ---
+
+
diff --git a/src/api/auth.py b/src/api/auth.py
new file mode 100644
index 00000000..a72b6e9e
--- /dev/null
+++ b/src/api/auth.py
@@ -0,0 +1,347 @@
+"""
+Authentication and user management routes.
+
+This blueprint handles user registration, login, logout, account management,
+and password changes.
+"""
+
+import os
+import re
+import mimetypes
+from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
+from flask_login import login_user, logout_user, login_required, current_user
+from flask_wtf import FlaskForm
+from wtforms import StringField, PasswordField, SubmitField, BooleanField
+from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError
+from werkzeug.security import generate_password_hash, check_password_hash
+from urllib.parse import urlparse, urljoin
+import markdown
+
+from src.database import db
+from src.models import User, SystemSetting, GroupMembership
+from src.utils import password_check
+
+# Create blueprint
+auth_bp = Blueprint('auth', __name__)
+
+# Import these from app after initialization
+bcrypt = None
+csrf = None
+limiter = None
+
+def init_auth_extensions(_bcrypt, _csrf, _limiter):
+ """Initialize extensions after app creation."""
+ global bcrypt, csrf, limiter
+ bcrypt = _bcrypt
+ csrf = _csrf
+ limiter = _limiter
+
+
+def rate_limit(limit_string):
+ """Decorator that applies rate limiting if limiter is available."""
+ def decorator(f):
+ from functools import wraps
+ @wraps(f)
+ def wrapper(*args, **kwargs):
+ return f(*args, **kwargs)
+ # Store the limit string for later application
+ wrapper._rate_limit = limit_string
+ return wrapper
+ return decorator
+
+
+def csrf_exempt(f):
+ """Decorator placeholder for CSRF exemption - applied after initialization."""
+ from functools import wraps
+ @wraps(f)
+ def wrapper(*args, **kwargs):
+ return f(*args, **kwargs)
+ wrapper._csrf_exempt = True
+ return wrapper
+
+
+# --- Forms ---
+
+class RegistrationForm(FlaskForm):
+ username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)])
+ email = StringField('Email', validators=[DataRequired(), Email()])
+ password = PasswordField('Password', validators=[DataRequired(), password_check])
+ confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
+ submit = SubmitField('Sign Up')
+
+ def validate_username(self, username):
+ user = User.query.filter_by(username=username.data).first()
+ if user:
+ raise ValidationError('That username is already taken. Please choose a different one.')
+
+ def validate_email(self, email):
+ user = User.query.filter_by(email=email.data).first()
+ if user:
+ raise ValidationError('That email is already registered. Please use a different one.')
+
+
+class LoginForm(FlaskForm):
+ email = StringField('Email', validators=[DataRequired(), Email()])
+ password = PasswordField('Password', validators=[DataRequired()])
+ remember = BooleanField('Remember Me')
+ submit = SubmitField('Login')
+
+
+# --- Helper Functions ---
+
+def is_safe_url(target):
+ ref_url = urlparse(request.host_url)
+ test_url = urlparse(urljoin(request.host_url, target))
+ return test_url.scheme in ('http', 'https') and ref_url.netloc == test_url.netloc
+
+
+# --- Routes ---
+
+@auth_bp.route('/register', methods=['GET', 'POST'])
+@rate_limit("10 per minute")
+def register():
+ # Check if registration is allowed
+ allow_registration = os.environ.get('ALLOW_REGISTRATION', 'true').lower() == 'true'
+
+ if not allow_registration:
+ flash('Registration is currently disabled. Please contact the administrator.', 'danger')
+ return redirect(url_for('auth.login'))
+
+ if current_user.is_authenticated:
+ return redirect(url_for('recordings.index'))
+
+ form = RegistrationForm()
+ if form.validate_on_submit():
+ hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
+ user = User(username=form.username.data, email=form.email.data, password=hashed_password)
+ db.session.add(user)
+ db.session.commit()
+ flash('Your account has been created! You can now log in.', 'success')
+ return redirect(url_for('auth.login'))
+
+ return render_template('register.html', title='Register', form=form)
+
+
+@auth_bp.route('/login', methods=['GET', 'POST'])
+@rate_limit("10 per minute")
+def login():
+ if current_user.is_authenticated:
+ return redirect(url_for('recordings.index'))
+
+ form = LoginForm()
+ if form.validate_on_submit():
+ user = User.query.filter_by(email=form.email.data).first()
+ if user and bcrypt.check_password_hash(user.password, form.password.data):
+ login_user(user, remember=form.remember.data)
+ next_page = request.args.get('next')
+ if not is_safe_url(next_page):
+ return redirect(url_for('recordings.index'))
+ return redirect(next_page) if next_page else redirect(url_for('recordings.index'))
+ else:
+ flash('Login unsuccessful. Please check email and password.', 'danger')
+
+ return render_template('login.html', title='Login', form=form)
+
+
+@auth_bp.route('/logout')
+@csrf_exempt
+def logout():
+ logout_user()
+ return redirect(url_for('auth.login'))
+
+
+@auth_bp.route('/account', methods=['GET', 'POST'])
+@login_required
+def account():
+ # Import here to avoid circular imports
+ from flask import current_app
+
+ if request.method == 'POST':
+ # Only update fields that are present in the form submission
+ # This prevents clearing data when switching between tabs
+
+ # Check if this is the account information form (has user_name field)
+ if 'user_name' in request.form:
+ # Handle personal information updates
+ user_name = request.form.get('user_name')
+ user_job_title = request.form.get('user_job_title')
+ user_company = request.form.get('user_company')
+ ui_lang = request.form.get('ui_language')
+ transcription_lang = request.form.get('transcription_language')
+ output_lang = request.form.get('output_language')
+
+ current_user.name = user_name if user_name else None
+ current_user.job_title = user_job_title if user_job_title else None
+ current_user.company = user_company if user_company else None
+ current_user.ui_language = ui_lang if ui_lang else 'en'
+ current_user.transcription_language = transcription_lang if transcription_lang else None
+ current_user.output_language = output_lang if output_lang else None
+
+ # Check if this is the custom prompts form (has summary_prompt field)
+ elif 'summary_prompt' in request.form:
+ # Handle custom prompt updates
+ summary_prompt_text = request.form.get('summary_prompt')
+ current_user.summary_prompt = summary_prompt_text if summary_prompt_text else None
+ # Handle event extraction setting
+ current_user.extract_events = 'extract_events' in request.form
+
+ # Only update diarize if it's not locked by env var
+ if 'ASR_DIARIZE' not in os.environ:
+ current_user.diarize = 'diarize' in request.form
+
+ db.session.commit()
+
+ # Return JSON response for AJAX requests
+ if request.headers.get('X-Requested-With') == 'XMLHttpRequest' or request.accept_mimetypes.best == 'application/json':
+ return jsonify({'success': True, 'message': 'Account details updated successfully!'})
+
+ # Regular form submission with redirect
+ flash('Account details updated successfully!', 'success')
+
+ # Preserve the active tab when redirecting
+ if 'summary_prompt' in request.form:
+ return redirect(url_for('auth.account') + '#prompts')
+ else:
+ return redirect(url_for('auth.account'))
+
+ # Get admin default prompt from system settings
+ admin_default_prompt = SystemSetting.get_setting('admin_default_summary_prompt', None)
+ if admin_default_prompt:
+ default_summary_prompt_text = admin_default_prompt
+ else:
+ # Fallback to hardcoded default if admin hasn't set one
+ default_summary_prompt_text = """Generate a comprehensive summary that includes the following sections:
+- **Key Issues Discussed**: A bulleted list of the main topics
+- **Key Decisions Made**: A bulleted list of any decisions reached
+- **Action Items**: A bulleted list of tasks assigned, including who is responsible if mentioned"""
+
+ asr_diarize_locked = 'ASR_DIARIZE' in os.environ
+ ASR_DIARIZE = os.environ.get('ASR_DIARIZE', 'false').lower() == 'true'
+ USE_ASR_ENDPOINT = os.environ.get('USE_ASR_ENDPOINT', 'false').lower() == 'true'
+ ENABLE_AUTO_DELETION = os.environ.get('ENABLE_AUTO_DELETION', 'false').lower() == 'true'
+ ENABLE_INTERNAL_SHARING = os.environ.get('ENABLE_INTERNAL_SHARING', 'false').lower() == 'true'
+
+ # Check if user is a team admin and get their admin groups
+ admin_memberships = GroupMembership.query.filter_by(
+ user_id=current_user.id,
+ role='admin'
+ ).all()
+
+ is_team_admin = len(admin_memberships) > 0
+
+ # Build list of groups where user is admin (for tag assignment)
+ user_admin_groups = []
+ for membership in admin_memberships:
+ if membership.group:
+ user_admin_groups.append({
+ 'id': membership.group.id,
+ 'name': membership.group.name
+ })
+
+ return render_template('account.html',
+ title='Account',
+ default_summary_prompt_text=default_summary_prompt_text,
+ use_asr_endpoint=USE_ASR_ENDPOINT,
+ enable_auto_deletion=ENABLE_AUTO_DELETION,
+ enable_internal_sharing=ENABLE_INTERNAL_SHARING,
+ user_admin_groups=user_admin_groups,
+ asr_diarize_locked=asr_diarize_locked,
+ asr_diarize_env_value=ASR_DIARIZE,
+ is_team_admin=is_team_admin)
+
+
+@auth_bp.route('/change_password', methods=['POST'])
+@login_required
+@rate_limit("10 per minute")
+def change_password():
+ current_password = request.form.get('current_password')
+ new_password = request.form.get('new_password')
+ confirm_password = request.form.get('confirm_password')
+
+ # Validate form data
+ if not current_password or not new_password or not confirm_password:
+ flash('All fields are required.', 'danger')
+ return redirect(url_for('auth.account'))
+
+ if new_password != confirm_password:
+ flash('New password and confirmation do not match.', 'danger')
+ return redirect(url_for('auth.account'))
+
+ # Custom validation for new password
+ try:
+ password_check(None, type('obj', (object,), {'data': new_password}))
+ except ValidationError as e:
+ flash(str(e), 'danger')
+ return redirect(url_for('auth.account'))
+
+ # Verify current password
+ if not bcrypt.check_password_hash(current_user.password, current_password):
+ flash('Current password is incorrect.', 'danger')
+ return redirect(url_for('auth.account'))
+
+ # Update password
+ hashed_password = bcrypt.generate_password_hash(new_password).decode('utf-8')
+ current_user.password = hashed_password
+ db.session.commit()
+
+ flash('Your password has been updated!', 'success')
+ return redirect(url_for('auth.account'))
+
+
+@auth_bp.route('/docs/transcript-templates-guide')
+def transcript_templates_guide():
+ """Serve the transcript templates documentation."""
+ from flask import current_app
+
+ docs_path = os.path.join(current_app.root_path, '..', 'docs', 'transcript-templates-guide.md')
+
+ if not os.path.exists(docs_path):
+ return "Documentation not found", 404
+
+ with open(docs_path, 'r', encoding='utf-8') as f:
+ content = f.read()
+
+ # Convert markdown to HTML
+ html_content = markdown.markdown(content, extensions=['tables', 'fenced_code', 'codehilite'])
+
+ # Wrap in basic HTML template with Speakr styling
+ html_template = f'''
+ <!DOCTYPE html>
+ <html lang="en">
+ <head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Transcript Templates Guide - Speakr</title>
+ <link rel="stylesheet" href="/static/css/output.css">
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
+ <style>
+ .markdown-body {{
+ max-width: 900px;
+ margin: 0 auto;
+ padding: 2rem;
+ line-height: 1.6;
+ }}
+ .markdown-body h1 {{ font-size: 2.5rem; margin-bottom: 1rem; }}
+ .markdown-body h2 {{ font-size: 2rem; margin-top: 2rem; margin-bottom: 1rem; }}
+ .markdown-body h3 {{ font-size: 1.5rem; margin-top: 1.5rem; margin-bottom: 0.75rem; }}
+ .markdown-body pre {{ background: #f4f4f4; padding: 1rem; border-radius: 0.5rem; overflow-x: auto; }}
+ .markdown-body code {{ background: #f4f4f4; padding: 0.2rem 0.4rem; border-radius: 0.25rem; }}
+ .markdown-body pre code {{ background: none; padding: 0; }}
+ .markdown-body ul, .markdown-body ol {{ margin-left: 2rem; margin-bottom: 1rem; }}
+ .markdown-body li {{ margin-bottom: 0.5rem; }}
+ .markdown-body blockquote {{ border-left: 4px solid #ddd; padding-left: 1rem; margin: 1rem 0; }}
+ .markdown-body table {{ border-collapse: collapse; width: 100%; margin: 1rem 0; }}
+ .markdown-body th, .markdown-body td {{ border: 1px solid #ddd; padding: 0.5rem; }}
+ .markdown-body th {{ background: #f4f4f4; font-weight: bold; }}
+ </style>
+ </head>
+ <body>
+ <div class="markdown-body">
+ <a href="/" class="btn-primary" style="display: inline-block; margin-bottom: 1rem; padding: 0.5rem 1rem; background: #3b82f6; color: white; text-decoration: none; border-radius: 0.5rem;">← Back to App</a>
+ {html_content}
+ </div>
+ </body>
+ </html>
+ '''
+
+ return html_template
diff --git a/src/api/events.py b/src/api/events.py
new file mode 100644
index 00000000..180fd02c
--- /dev/null
+++ b/src/api/events.py
@@ -0,0 +1,149 @@
+"""
+Calendar event extraction and export.
+
+This blueprint was auto-generated from app.py route extraction.
+"""
+
+import os
+import json
+from datetime import datetime, timedelta
+from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, send_file, Response, current_app, make_response
+from flask_login import login_required, current_user
+from werkzeug.utils import secure_filename
+
+from src.database import db
+from src.models import *
+from src.utils import *
+from src.services.calendar import generate_ics_content
+
+# Create blueprint
+events_bp = Blueprint('events', __name__)
+
+# Configuration from environment
+ENABLE_INQUIRE_MODE = os.environ.get('ENABLE_INQUIRE_MODE', 'false').lower() == 'true'
+ENABLE_AUTO_DELETION = os.environ.get('ENABLE_AUTO_DELETION', 'false').lower() == 'true'
+USERS_CAN_DELETE = os.environ.get('USERS_CAN_DELETE', 'true').lower() == 'true'
+ENABLE_INTERNAL_SHARING = os.environ.get('ENABLE_INTERNAL_SHARING', 'false').lower() == 'true'
+USE_ASR_ENDPOINT = os.environ.get('USE_ASR_ENDPOINT', 'false').lower() == 'true'
+
+# Global helpers (will be injected from app)
+has_recording_access = None
+bcrypt = None
+csrf = None
+limiter = None
+
+def init_events_helpers(**kwargs):
+ """Initialize helper functions and extensions from app."""
+ global has_recording_access, bcrypt, csrf, limiter
+ has_recording_access = kwargs.get('has_recording_access')
+ bcrypt = kwargs.get('bcrypt')
+ csrf = kwargs.get('csrf')
+ limiter = kwargs.get('limiter')
+
+
+# --- Routes ---
+
+@events_bp.route('/api/recording/<int:recording_id>/events', methods=['GET'])
+@login_required
+def get_recording_events(recording_id):
+ """Get all events extracted from a recording."""
+ try:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ if not has_recording_access(recording, current_user):
+ return jsonify({'error': 'Unauthorized'}), 403
+
+ events = Event.query.filter_by(recording_id=recording_id).all()
+ return jsonify({'events': [event.to_dict() for event in events]})
+
+ except Exception as e:
+ current_app.logger.error(f"Error fetching events for recording {recording_id}: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+@events_bp.route('/api/event/<int:event_id>/ics', methods=['GET'])
+@login_required
+def download_event_ics(event_id):
+ """Generate and download an ICS file for a single event."""
+ try:
+ event = db.session.get(Event, event_id)
+ if not event:
+ return jsonify({'error': 'Event not found'}), 404
+
+ # Check permissions through recording access
+ if not has_recording_access(event.recording, current_user):
+ return jsonify({'error': 'Unauthorized'}), 403
+
+ # Generate ICS content
+ ics_content = generate_ics_content(event)
+
+ # Create response with ICS file
+ response = make_response(ics_content)
+ response.headers['Content-Type'] = 'text/calendar; charset=utf-8'
+ response.headers['Content-Disposition'] = f'attachment; filename="{secure_filename(event.title)}.ics"'
+
+ return response
+
+ except Exception as e:
+ current_app.logger.error(f"Error generating ICS for event {event_id}: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+@events_bp.route('/api/recording/<int:recording_id>/events/ics', methods=['GET'])
+@login_required
+def download_all_events_ics(recording_id):
+ """Generate and download an ICS file containing all events from a recording."""
+ try:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ if not has_recording_access(recording, current_user):
+ return jsonify({'error': 'Unauthorized'}), 403
+
+ # Get all events for this recording
+ events = Event.query.filter_by(recording_id=recording_id).all()
+ if not events:
+ return jsonify({'error': 'No events found for this recording'}), 404
+
+ # Generate combined ICS content
+ ics_lines = []
+ ics_lines.append("BEGIN:VCALENDAR")
+ ics_lines.append("VERSION:2.0")
+ ics_lines.append("PRODID:-//Speakr//Event Export//EN")
+ ics_lines.append("CALSCALE:GREGORIAN")
+ ics_lines.append("METHOD:PUBLISH")
+
+ # Add each event
+ for event in events:
+ # Get the individual event's ICS content and extract just the VEVENT portion
+ individual_ics = generate_ics_content(event)
+ # Extract VEVENT block from individual ICS
+ lines = individual_ics.split('\n')
+ in_event = False
+ for line in lines:
+ if line.startswith('BEGIN:VEVENT'):
+ in_event = True
+ if in_event:
+ ics_lines.append(line)
+ if line.startswith('END:VEVENT'):
+ in_event = False
+
+ ics_lines.append("END:VCALENDAR")
+ ics_content = '\r\n'.join(ics_lines)
+
+ # Create response with ICS file
+ response = make_response(ics_content)
+ response.headers['Content-Type'] = 'text/calendar; charset=utf-8'
+ safe_title = secure_filename(recording.title) if recording.title else f'recording-{recording_id}'
+ response.headers['Content-Disposition'] = f'attachment; filename="{safe_title}-events.ics"'
+
+ return response
+
+ except Exception as e:
+ current_app.logger.error(f"Error generating ICS for all events in recording {recording_id}: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
diff --git a/src/api/groups.py b/src/api/groups.py
new file mode 100644
index 00000000..2eed5670
--- /dev/null
+++ b/src/api/groups.py
@@ -0,0 +1,394 @@
+"""
+Group management and collaboration.
+
+This blueprint was auto-generated from app.py route extraction.
+"""
+
+import os
+import json
+import re
+from datetime import datetime, timedelta
+from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, send_file, Response, current_app
+from flask_login import login_required, current_user
+from werkzeug.utils import secure_filename
+
+from src.database import db
+from src.models import *
+from src.utils import *
+
+# Create blueprint
+groups_bp = Blueprint('groups', __name__)
+
+# Configuration from environment
+ENABLE_INQUIRE_MODE = os.environ.get('ENABLE_INQUIRE_MODE', 'false').lower() == 'true'
+ENABLE_AUTO_DELETION = os.environ.get('ENABLE_AUTO_DELETION', 'false').lower() == 'true'
+USERS_CAN_DELETE = os.environ.get('USERS_CAN_DELETE', 'true').lower() == 'true'
+ENABLE_INTERNAL_SHARING = os.environ.get('ENABLE_INTERNAL_SHARING', 'false').lower() == 'true'
+USE_ASR_ENDPOINT = os.environ.get('USE_ASR_ENDPOINT', 'false').lower() == 'true'
+
+# Global helpers (will be injected from app)
+has_recording_access = None
+bcrypt = None
+csrf = None
+limiter = None
+
+def init_groups_helpers(**kwargs):
+ """Initialize helper functions and extensions from app."""
+ global has_recording_access, bcrypt, csrf, limiter
+ has_recording_access = kwargs.get('has_recording_access')
+ bcrypt = kwargs.get('bcrypt')
+ csrf = kwargs.get('csrf')
+ limiter = kwargs.get('limiter')
+
+
+# --- Routes ---
+
+@groups_bp.route('/api/groups/<int:group_id>/sync-shares', methods=['POST'])
+@login_required
+def sync_team_tag_shares(group_id):
+ """Retroactively share recordings with group members based on group tags with auto-sharing enabled."""
+ # Verify group exists
+ group = db.session.get(Group, group_id)
+ if not group:
+ return jsonify({'error': 'Group not found'}), 404
+
+ # Verify user is a group admin
+ membership = GroupMembership.query.filter_by(
+ group_id=group_id,
+ user_id=current_user.id,
+ role='admin'
+ ).first()
+
+ if not membership:
+ return jsonify({'error': 'Only group admins can sync shares'}), 403
+
+ if not ENABLE_INTERNAL_SHARING:
+ return jsonify({'error': 'Internal sharing is not enabled'}), 403
+
+ # Get all group tags with auto-sharing enabled
+ group_tags = Tag.query.filter(
+ Tag.group_id == group_id,
+ db.or_(
+ Tag.auto_share_on_apply == True,
+ Tag.share_with_group_lead == True
+ )
+ ).all()
+
+ shares_created = 0
+ recordings_processed = 0
+
+ for tag in group_tags:
+ # Get all completed recordings with this tag
+ recordings = db.session.query(Recording).join(RecordingTag).filter(
+ RecordingTag.tag_id == tag.id,
+ Recording.status == 'COMPLETED'
+ ).all()
+
+ for recording in recordings:
+ recordings_processed += 1
+
+ # Determine who to share with
+ if tag.auto_share_on_apply:
+ group_members = GroupMembership.query.filter_by(group_id=group_id).all()
+ elif tag.share_with_group_lead:
+ group_members = GroupMembership.query.filter_by(group_id=group_id, role='admin').all()
+ else:
+ continue
+
+ for membership_to_share in group_members:
+ # Skip the recording owner
+ if membership_to_share.user_id == recording.user_id:
+ continue
+
+ # Check if already shared
+ existing_share = InternalShare.query.filter_by(
+ recording_id=recording.id,
+ shared_with_user_id=membership_to_share.user_id
+ ).first()
+
+ if not existing_share:
+ # Create internal share with correct permissions
+ # Group admins get edit permission, regular members get read-only
+ share = InternalShare(
+ recording_id=recording.id,
+ owner_id=recording.user_id,
+ shared_with_user_id=membership_to_share.user_id,
+ can_edit=(membership_to_share.role == 'admin'),
+ can_reshare=False,
+ source_type='group_tag',
+ source_tag_id=tag.id
+ )
+ db.session.add(share)
+
+ # Create SharedRecordingState with default values for the recipient
+ state = SharedRecordingState(
+ recording_id=recording.id,
+ user_id=membership_to_share.user_id,
+ is_inbox=True, # New shares appear in inbox by default
+ is_highlighted=False # Not favorited by default
+ )
+ db.session.add(state)
+
+ shares_created += 1
+ current_app.logger.info(f"Synced share: Recording {recording.id} with user {membership_to_share.user_id} (role={membership_to_share.role}) via group tag '{tag.name}'")
+
+ db.session.commit()
+
+ return jsonify({
+ 'success': True,
+ 'shares_created': shares_created,
+ 'recordings_processed': recordings_processed,
+ 'message': f'Created {shares_created} new shares across {recordings_processed} recordings'
+ })
+
+
+
+@groups_bp.route('/api/admin/groups', methods=['GET'])
+@login_required
+def get_teams():
+ """Get all groups (admin) or groups user is admin of (group admin)."""
+ # Check if user is admin OR group admin
+ is_group_admin = GroupMembership.query.filter_by(
+ user_id=current_user.id,
+ role='admin'
+ ).first() is not None
+
+ if not current_user.is_admin and not is_group_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+
+ # If full admin, return all groups; if group admin, return only their groups
+ if current_user.is_admin:
+ groups = Group.query.all()
+ else:
+ # Get groups where user is an admin
+ group_memberships = GroupMembership.query.filter_by(
+ user_id=current_user.id,
+ role='admin'
+ ).all()
+ groups = [m.group for m in group_memberships]
+
+ return jsonify({'groups': [group.to_dict() for group in groups]})
+
+
+
+@groups_bp.route('/api/admin/groups', methods=['POST'])
+@login_required
+def create_team():
+ """Create a new group (admin only)."""
+ if not current_user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+
+ if not ENABLE_INTERNAL_SHARING:
+ return jsonify({'error': 'Groups require internal sharing to be enabled. Please set ENABLE_INTERNAL_SHARING=true in your configuration.'}), 403
+
+ data = request.get_json()
+ name = data.get('name', '').strip()
+ description = data.get('description', '').strip()
+
+ if not name:
+ return jsonify({'error': 'Group name is required'}), 400
+
+ # Check if group name already exists
+ existing = Group.query.filter_by(name=name).first()
+ if existing:
+ return jsonify({'error': 'A group with this name already exists'}), 400
+
+ group = Group(name=name, description=description)
+ db.session.add(group)
+ db.session.commit()
+
+ current_app.logger.info(f"Admin {current_user.username} created group: {name}")
+ return jsonify(group.to_dict()), 201
+
+
+
+@groups_bp.route('/api/admin/groups/<int:group_id>', methods=['GET'])
+@login_required
+def get_team(group_id):
+ """Get group details (admin or group admin)."""
+ group = db.session.get(Group, group_id)
+ if not group:
+ return jsonify({'error': 'Group not found'}), 404
+
+ # Check if user is admin OR admin of this specific group
+ is_group_admin = GroupMembership.query.filter_by(
+ group_id=group_id,
+ user_id=current_user.id,
+ role='admin'
+ ).first() is not None
+
+ if not current_user.is_admin and not is_group_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+
+ group_dict = group.to_dict()
+ group_dict['members'] = [m.to_dict() for m in group.memberships]
+ return jsonify(group_dict)
+
+
+
+@groups_bp.route('/api/admin/groups/<int:group_id>', methods=['PUT'])
+@login_required
+def update_team(group_id):
+ """Update group (admin or group admin)."""
+ group = db.session.get(Group, group_id)
+ if not group:
+ return jsonify({'error': 'Group not found'}), 404
+
+ # Check if user is admin OR admin of this specific group
+ is_group_admin = GroupMembership.query.filter_by(
+ group_id=group_id,
+ user_id=current_user.id,
+ role='admin'
+ ).first() is not None
+
+ if not current_user.is_admin and not is_group_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+
+ data = request.get_json()
+ name = data.get('name', '').strip()
+ description = data.get('description', '').strip()
+
+ if name:
+ # Check if new name conflicts with another group
+ existing = Group.query.filter(Group.name == name, Group.id != group_id).first()
+ if existing:
+ return jsonify({'error': 'A group with this name already exists'}), 400
+ group.name = name
+
+ group.description = description
+ db.session.commit()
+
+ current_app.logger.info(f"Admin {current_user.username} updated group: {group.name}")
+ return jsonify(group.to_dict())
+
+
+
+@groups_bp.route('/api/admin/groups/<int:group_id>', methods=['DELETE'])
+@login_required
+def delete_team(group_id):
+ """Delete group (admin only)."""
+ if not current_user.is_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+
+ group = db.session.get(Group, group_id)
+ if not group:
+ return jsonify({'error': 'Group not found'}), 404
+
+ group_name = group.name
+ db.session.delete(group)
+ db.session.commit()
+
+ current_app.logger.info(f"Admin {current_user.username} deleted group: {group_name}")
+ return jsonify({'success': True})
+
+
+
+@groups_bp.route('/api/admin/groups/<int:group_id>/members', methods=['POST'])
+@login_required
+def add_team_member(group_id):
+ """Add a member to a group (admin or group admin)."""
+ if not ENABLE_INTERNAL_SHARING:
+ return jsonify({'error': 'Groups require internal sharing to be enabled. Please set ENABLE_INTERNAL_SHARING=true in your configuration.'}), 403
+
+ group = db.session.get(Group, group_id)
+ if not group:
+ return jsonify({'error': 'Group not found'}), 404
+
+ # Check if user is admin OR admin of this specific group
+ is_group_admin = GroupMembership.query.filter_by(
+ group_id=group_id,
+ user_id=current_user.id,
+ role='admin'
+ ).first() is not None
+
+ if not current_user.is_admin and not is_group_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+
+ data = request.get_json()
+ user_id = data.get('user_id')
+ role = data.get('role', 'member')
+
+ if not user_id:
+ return jsonify({'error': 'User ID is required'}), 400
+
+ if role not in ['admin', 'member']:
+ return jsonify({'error': 'Role must be "admin" or "member"'}), 400
+
+ user = db.session.get(User, user_id)
+ if not user:
+ return jsonify({'error': 'User not found'}), 404
+
+ # Check if already a member
+ existing = GroupMembership.query.filter_by(group_id=group_id, user_id=user_id).first()
+ if existing:
+ return jsonify({'error': 'User is already a member of this group'}), 400
+
+ membership = GroupMembership(group_id=group_id, user_id=user_id, role=role)
+ db.session.add(membership)
+ db.session.commit()
+
+ current_app.logger.info(f"Admin {current_user.username} added {user.username} to group {group.name} as {role}")
+ return jsonify(membership.to_dict()), 201
+
+
+
+@groups_bp.route('/api/admin/groups/<int:group_id>/members/<int:user_id>', methods=['PUT'])
+@login_required
+def update_team_member(group_id, user_id):
+ """Update group member role (admin or group admin)."""
+ membership = GroupMembership.query.filter_by(group_id=group_id, user_id=user_id).first()
+ if not membership:
+ return jsonify({'error': 'Membership not found'}), 404
+
+ # Check if user is admin OR admin of this specific group
+ is_group_admin = GroupMembership.query.filter_by(
+ group_id=group_id,
+ user_id=current_user.id,
+ role='admin'
+ ).first() is not None
+
+ if not current_user.is_admin and not is_group_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+
+ data = request.get_json()
+ role = data.get('role')
+
+ if role not in ['admin', 'member']:
+ return jsonify({'error': 'Role must be "admin" or "member"'}), 400
+
+ membership.role = role
+ db.session.commit()
+
+ current_app.logger.info(f"Admin {current_user.username} updated {membership.user.username} role to {role} in group {membership.group.name}")
+ return jsonify(membership.to_dict())
+
+
+
+@groups_bp.route('/api/admin/groups/<int:group_id>/members/<int:user_id>', methods=['DELETE'])
+@login_required
+def remove_team_member(group_id, user_id):
+ """Remove a member from a group (admin or group admin)."""
+ membership = GroupMembership.query.filter_by(group_id=group_id, user_id=user_id).first()
+ if not membership:
+ return jsonify({'error': 'Membership not found'}), 404
+
+ # Check if user is admin OR admin of this specific group
+ is_group_admin = GroupMembership.query.filter_by(
+ group_id=group_id,
+ user_id=current_user.id,
+ role='admin'
+ ).first() is not None
+
+ if not current_user.is_admin and not is_group_admin:
+ return jsonify({'error': 'Admin access required'}), 403
+
+ username = membership.user.username
+ group_name = membership.group.name
+ db.session.delete(membership)
+ db.session.commit()
+
+ current_app.logger.info(f"Admin {current_user.username} removed {username} from group {group_name}")
+ return jsonify({'success': True})
+
+
+
diff --git a/src/api/inquire.py b/src/api/inquire.py
new file mode 100644
index 00000000..cb6b53fb
--- /dev/null
+++ b/src/api/inquire.py
@@ -0,0 +1,841 @@
+"""
+Semantic search and chat functionality.
+
+This blueprint was auto-generated from app.py route extraction.
+"""
+
+import os
+import json
+import re
+import time
+from datetime import datetime, timedelta
+from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, send_file, Response, current_app
+from flask_login import login_required, current_user
+from werkzeug.utils import secure_filename
+
+from src.database import db
+from src.models import *
+from src.utils import *
+from src.services.embeddings import get_accessible_recording_ids, semantic_search_chunks
+from src.services.llm import call_llm_completion, process_streaming_with_thinking, client
+
+# Create blueprint
+inquire_bp = Blueprint('inquire', __name__)
+
+# Configuration from environment
+ENABLE_INQUIRE_MODE = os.environ.get('ENABLE_INQUIRE_MODE', 'false').lower() == 'true'
+ENABLE_AUTO_DELETION = os.environ.get('ENABLE_AUTO_DELETION', 'false').lower() == 'true'
+USERS_CAN_DELETE = os.environ.get('USERS_CAN_DELETE', 'true').lower() == 'true'
+ENABLE_INTERNAL_SHARING = os.environ.get('ENABLE_INTERNAL_SHARING', 'false').lower() == 'true'
+USE_ASR_ENDPOINT = os.environ.get('USE_ASR_ENDPOINT', 'false').lower() == 'true'
+
+# Global helpers (will be injected from app)
+has_recording_access = None
+bcrypt = None
+csrf = None
+limiter = None
+
+def init_inquire_helpers(**kwargs):
+ """Initialize helper functions and extensions from app."""
+ global has_recording_access, bcrypt, csrf, limiter
+ has_recording_access = kwargs.get('has_recording_access')
+ bcrypt = kwargs.get('bcrypt')
+ csrf = kwargs.get('csrf')
+ limiter = kwargs.get('limiter')
+
+
+# --- Routes ---
+
+@inquire_bp.route('/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('recordings.index'))
+
+ # Check if user is a group admin
+ is_team_admin = GroupMembership.query.filter_by(
+ user_id=current_user.id,
+ role='admin'
+ ).first() is not None
+
+ # Render the inquire page with user context for theming
+ return render_template('inquire.html',
+ use_asr_endpoint=USE_ASR_ENDPOINT,
+ current_user=current_user,
+ is_team_admin=is_team_admin)
+
+
+
+@inquire_bp.route('/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:
+ current_app.logger.error(f"Error getting inquire sessions: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+
+@inquire_bp.route('/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:
+ current_app.logger.error(f"Error creating inquire session: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+
+@inquire_bp.route('/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'] = local_datetime_filter(chunk.recording.meeting_date)
+ results.append(result)
+
+ return jsonify({'results': results})
+
+ except Exception as e:
+ current_app.logger.error(f"Error in inquire search: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+
+@inquire_bp.route('/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
+ current_app.logger.info(f"Inquire chat - User: {current_user.username}, Query: '{user_message}', Filters: {filters}")
+
+ # Capture user context and app before generator to avoid context issues
+ 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
+ app = current_app._get_current_object() # Capture app for use in generator
+
+ # 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
+
+ # Push app context for entire generator execution
+ # This is needed because call_llm_completion uses current_app.logger internally
+ ctx = app.app_context()
+ ctx.push()
+
+ 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 = call_llm_completion(
+ 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
+ )
+
+ raw_decision = router_response.choices[0].message.content
+ if not raw_decision or not raw_decision.strip():
+ app.logger.warning("Router returned empty response, defaulting to RAG")
+ raise ValueError("Empty router response")
+
+ route_decision = raw_decision.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 = call_llm_completion(
+ 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
+ )
+
+ # Use helper function to process streaming with thinking tag support
+ for response in process_streaming_with_thinking(stream):
+ yield response
+ return
+
+ except Exception as e:
+ 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 = call_llm_completion(
+ messages=[
+ {"role": "system", "content": "You are a query enhancement assistant. Respond only with valid JSON arrays of search terms."},
+ {"role": "user", "content": enrichment_prompt}
+ ],
+ temperature=0.3,
+ max_tokens=200
+ )
+
+ raw_content = enrichment_response.choices[0].message.content
+ if not raw_content or not raw_content.strip():
+ app.logger.warning(f"Query enrichment returned empty response")
+ raise ValueError("Empty response from LLM")
+
+ # Try to extract JSON array if wrapped in other text
+ content = raw_content.strip()
+ if content.startswith('['):
+ enriched_terms = json.loads(content)
+ else:
+ # Try to find JSON array in the response
+ match = re.search(r'\[.*?\]', content, re.DOTALL)
+ if match:
+ enriched_terms = json.loads(match.group())
+ else:
+ app.logger.warning(f"Query enrichment response not JSON: {content[:200]}")
+ raise ValueError("No JSON array found in response")
+
+ 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 = call_llm_completion(
+ 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 = ""
+
+ # Buffer content to detect full transcript requests
+ response_buffer = ""
+ content_buffer = ""
+ in_thinking = False
+ thinking_buffer = ""
+
+ for chunk in stream:
+ content = chunk.choices[0].delta.content
+ if content:
+ response_buffer += content
+ content_buffer += content
+
+ # Check if this is a full transcript request
+ if response_buffer.strip().startswith("REQUEST_FULL_TRANSCRIPT:"):
+ 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 = call_llm_completion(
+ messages=updated_messages,
+ temperature=0.7,
+ max_tokens=int(os.environ.get("CHAT_MAX_TOKENS", "2000")),
+ stream=True
+ )
+
+ # Use helper function to process streaming with thinking tag support
+ for response in process_streaming_with_thinking(new_stream):
+ yield response
+ return
+ else:
+ # Recording not found or no permission
+ 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
+
+ # Process the buffer to detect and handle thinking tags
+ while True:
+ if not in_thinking:
+ # Look for opening thinking tag
+ think_start = re.search(r'<think(?:ing)?>', content_buffer, re.IGNORECASE)
+ if think_start:
+ # Send any content before the thinking tag
+ before_thinking = content_buffer[:think_start.start()]
+ if before_thinking:
+ yield f"data: {json.dumps({'delta': before_thinking})}\n\n"
+
+ # Start capturing thinking content
+ in_thinking = True
+ content_buffer = content_buffer[think_start.end():]
+ thinking_buffer = ""
+ else:
+ # No thinking tag found, send accumulated content
+ if content_buffer:
+ yield f"data: {json.dumps({'delta': content_buffer})}\n\n"
+ content_buffer = ""
+ break
+ else:
+ # We're inside a thinking tag, look for closing tag
+ think_end = re.search(r'</think(?:ing)?>', content_buffer, re.IGNORECASE)
+ if think_end:
+ # Capture thinking content up to the closing tag
+ thinking_buffer += content_buffer[:think_end.start()]
+
+ # Send the thinking content as a special type
+ if thinking_buffer.strip():
+ yield f"data: {json.dumps({'thinking': thinking_buffer.strip()})}\n\n"
+
+ # Continue processing after the closing tag
+ in_thinking = False
+ content_buffer = content_buffer[think_end.end():]
+ thinking_buffer = ""
+ else:
+ # Still inside thinking tag, accumulate content
+ thinking_buffer += content_buffer
+ content_buffer = ""
+ break
+
+ # Handle any remaining content
+ if in_thinking and thinking_buffer:
+ # Unclosed thinking tag - send as thinking content
+ yield f"data: {json.dumps({'thinking': thinking_buffer.strip()})}\n\n"
+ elif content_buffer:
+ # Regular content
+ yield f"data: {json.dumps({'delta': content_buffer})}\n\n"
+
+ yield f"data: {json.dumps({'end_of_stream': True})}\n\n"
+
+ except Exception as e:
+ app.logger.error(f"Error in enhanced chat generation: {e}")
+ yield f"data: {json.dumps({'error': str(e)})}\n\n"
+ finally:
+ ctx.pop()
+
+ return Response(generate_enhanced_chat(), mimetype='text/event-stream')
+
+ except Exception as e:
+ current_app.logger.error(f"Error in inquire chat endpoint: {str(e)}")
+ return jsonify({'error': str(e)}), 500
+
+
+
+@inquire_bp.route('/api/inquire/available_filters', methods=['GET'])
+@login_required
+def get_available_filters():
+ """Get available filter options for the user (includes shared recordings)."""
+ if not ENABLE_INQUIRE_MODE:
+ return jsonify({'error': 'Inquire mode is not enabled'}), 403
+ try:
+ # Get user's personal tags
+ user_tags = Tag.query.filter_by(user_id=current_user.id, group_id=None).all()
+
+ # Get group tags from user's teams
+ group_tags = []
+ memberships = GroupMembership.query.filter_by(user_id=current_user.id).all()
+ group_ids = [m.group_id for m in memberships]
+ if group_ids:
+ group_tags = Tag.query.filter(Tag.group_id.in_(group_ids)).all()
+
+ # Combine all tags
+ all_tags = user_tags + group_tags
+
+ # Get all accessible recording IDs (own + shared)
+ accessible_recording_ids = get_accessible_recording_ids(current_user.id)
+
+ # Get unique speakers from accessible recordings' participants field
+ recordings_with_participants = Recording.query.filter(
+ Recording.id.in_(accessible_recording_ids),
+ 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 accessible recordings for recording-specific filtering
+ recordings = Recording.query.filter(
+ Recording.id.in_(accessible_recording_ids),
+ Recording.status == 'COMPLETED'
+ ).order_by(Recording.created_at.desc()).all()
+
+ return jsonify({
+ 'tags': [tag.to_dict() for tag in all_tags],
+ 'speakers': speaker_names,
+ 'recordings': [{'id': r.id, 'title': r.title, 'meeting_date': f"{r.meeting_date.isoformat()}T00:00:00" if r.meeting_date else None} for r in recordings]
+ })
+
+ except Exception as e:
+ current_app.logger.error(f"Error getting available filters: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+
diff --git a/src/api/recordings.py b/src/api/recordings.py
new file mode 100644
index 00000000..499aebf0
--- /dev/null
+++ b/src/api/recordings.py
@@ -0,0 +1,2817 @@
+"""
+Recording upload, processing, and management.
+
+This blueprint was auto-generated from app.py route extraction.
+"""
+
+import os
+import json
+import re
+import mimetypes
+import threading
+import time
+import subprocess
+from datetime import datetime, timedelta
+from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, send_file, Response, current_app, make_response
+from flask_login import login_required, current_user
+from werkzeug.utils import secure_filename
+from werkzeug.exceptions import RequestEntityTooLarge
+from sqlalchemy import select
+from email.utils import encode_rfc2231
+
+from src.database import db
+from src.models import *
+from src.utils import *
+from src.config.app_config import ASR_MIN_SPEAKERS, ASR_MAX_SPEAKERS, ASR_DIARIZE
+from src.tasks.processing import (
+ transcribe_audio_asr, transcribe_audio_task, generate_summary_only_task,
+ format_transcription_for_llm, transcribe_with_chunking
+)
+from src.services.speaker import update_speaker_usage, identify_unidentified_speakers_from_text
+from src.services.speaker_embedding_matcher import update_speaker_embedding
+from src.services.speaker_snippets import create_speaker_snippets
+from src.services.document import process_markdown_to_docx
+from src.services.llm import client, call_llm_completion, process_streaming_with_thinking
+from src.services.embeddings import process_recording_chunks
+from src.file_exporter import export_recording, mark_export_as_deleted
+
+# Create blueprint
+recordings_bp = Blueprint('recordings', __name__)
+
+# Configuration from environment
+ENABLE_INQUIRE_MODE = os.environ.get('ENABLE_INQUIRE_MODE', 'false').lower() == 'true'
+ENABLE_AUTO_DELETION = os.environ.get('ENABLE_AUTO_DELETION', 'false').lower() == 'true'
+DELETION_MODE = os.environ.get('DELETION_MODE', 'full_recording') # 'audio_only' or 'full_recording'
+USERS_CAN_DELETE = os.environ.get('USERS_CAN_DELETE', 'true').lower() == 'true'
+ENABLE_INTERNAL_SHARING = os.environ.get('ENABLE_INTERNAL_SHARING', 'false').lower() == 'true'
+USE_ASR_ENDPOINT = os.environ.get('USE_ASR_ENDPOINT', 'false').lower() == 'true'
+ENABLE_CHUNKING = os.environ.get('ENABLE_CHUNKING', 'true').lower() == 'true'
+
+# Global helpers (will be injected from app)
+has_recording_access = None
+get_user_recording_status = None
+set_user_recording_status = None
+enrich_recording_dict_with_user_status = None
+bcrypt = None
+csrf = None
+limiter = None
+chunking_service = None
+
+def init_recordings_helpers(**kwargs):
+ """Initialize helper functions and extensions from app."""
+ global has_recording_access, get_user_recording_status, set_user_recording_status, enrich_recording_dict_with_user_status, bcrypt, csrf, limiter, chunking_service
+ has_recording_access = kwargs.get('has_recording_access')
+ get_user_recording_status = kwargs.get('get_user_recording_status')
+ set_user_recording_status = kwargs.get('set_user_recording_status')
+ enrich_recording_dict_with_user_status = kwargs.get('enrich_recording_dict_with_user_status')
+ bcrypt = kwargs.get('bcrypt')
+ csrf = kwargs.get('csrf')
+ limiter = kwargs.get('limiter')
+ chunking_service = kwargs.get('chunking_service')
+
+
+# --- Routes ---
+
+@recordings_bp.route('/recording/<int:recording_id>/download/transcript')
+@login_required
+def download_transcript_with_template(recording_id):
+ """Download transcript with custom template formatting."""
+ try:
+ import re
+ from datetime import timedelta
+
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ if not has_recording_access(recording, current_user):
+ return jsonify({'error': 'You do not have permission to access this recording'}), 403
+
+ if not recording.transcription:
+ return jsonify({'error': 'No transcription available for this recording'}), 400
+
+ # Get template ID from query params
+ template_id = request.args.get('template_id', type=int)
+
+ # Get the template
+ if template_id:
+ template = TranscriptTemplate.query.filter_by(
+ id=template_id,
+ user_id=current_user.id
+ ).first()
+ else:
+ # Use default template
+ template = TranscriptTemplate.query.filter_by(
+ user_id=current_user.id,
+ is_default=True
+ ).first()
+
+ # If no template found, use a basic format
+ if not template:
+ template_format = "[{{speaker}}]: {{text}}"
+ else:
+ template_format = template.template
+
+ # Helper functions for formatting
+ def format_time(seconds):
+ """Format seconds to HH:MM:SS"""
+ if seconds is None:
+ return "00:00:00"
+ td = timedelta(seconds=seconds)
+ hours = int(td.total_seconds() // 3600)
+ minutes = int((td.total_seconds() % 3600) // 60)
+ secs = int(td.total_seconds() % 60)
+ return f"{hours:02d}:{minutes:02d}:{secs:02d}"
+
+ def format_srt_time(seconds):
+ """Format seconds to SRT format HH:MM:SS,mmm"""
+ if seconds is None:
+ return "00:00:00,000"
+ td = timedelta(seconds=seconds)
+ hours = int(td.total_seconds() // 3600)
+ minutes = int((td.total_seconds() % 3600) // 60)
+ secs = int(td.total_seconds() % 60)
+ millis = int((td.total_seconds() % 1) * 1000)
+ return f"{hours:02d}:{minutes:02d}:{secs:02d},{millis:03d}"
+
+ # Parse transcription JSON
+ try:
+ transcription_data = json.loads(recording.transcription)
+ except:
+ return jsonify({'error': 'Invalid transcription format'}), 400
+
+ # Generate formatted transcript
+ output_lines = []
+ for index, segment in enumerate(transcription_data, 1):
+ line = template_format
+
+ # Replace variables
+ replacements = {
+ '{{index}}': str(index),
+ '{{speaker}}': segment.get('speaker', 'Unknown'),
+ '{{text}}': segment.get('sentence', ''),
+ '{{start_time}}': format_time(segment.get('start_time')),
+ '{{end_time}}': format_time(segment.get('end_time')),
+ }
+
+ for key, value in replacements.items():
+ line = line.replace(key, value)
+
+ # Handle filters
+ # Upper case filter
+ line = re.sub(r'{{(.*?)\|upper}}', lambda m: replacements.get('{{' + m.group(1) + '}}', '').upper(), line)
+ # SRT time filter
+ line = re.sub(r'{{start_time\|srt}}', format_srt_time(segment.get('start_time')), line)
+ line = re.sub(r'{{end_time\|srt}}', format_srt_time(segment.get('end_time')), line)
+
+ output_lines.append(line)
+
+ # Join lines
+ formatted_transcript = '\n'.join(output_lines)
+
+ # Create response
+ response = make_response(formatted_transcript)
+ filename = f"{recording.title or 'transcript'}_{template.name if template else 'formatted'}.txt"
+ filename = re.sub(r'[^a-zA-Z0-9_\-\.]', '_', filename)
+ response.headers['Content-Type'] = 'text/plain; charset=utf-8'
+ response.headers['Content-Disposition'] = f'attachment; filename="{filename}"'
+
+ return response
+
+ except Exception as e:
+ current_app.logger.error(f"Error downloading transcript: {e}")
+ return jsonify({'error': 'Failed to generate transcript download'}), 500
+
+
+
+
+@recordings_bp.route('/recording/<int:recording_id>/download/summary')
+@login_required
+def download_summary_word(recording_id):
+ """Download recording summary as a Word document."""
+ try:
+ from docx import Document
+ from docx.shared import Inches
+ import re
+ from io import BytesIO
+
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ if not has_recording_access(recording, current_user):
+ return jsonify({'error': 'You do not have permission to access this recording'}), 403
+
+ if not recording.summary:
+ return jsonify({'error': 'No summary available for this recording'}), 400
+
+ # Create Word document
+ doc = Document()
+
+ # Add title
+ title_text = f'Summary: {recording.title or "Untitled Recording"}'
+ title = doc.add_heading(title_text, 0)
+ # Check if title needs Unicode font support
+ try:
+ title_text.encode('ascii')
+ except UnicodeEncodeError:
+ # Title contains non-ASCII characters
+ from docx.oxml.ns import qn
+ for run in title.runs:
+ run.font.name = 'Arial'
+ r = run._element
+ r.rPr.rFonts.set(qn('w:eastAsia'), 'Arial')
+
+ # Helper function to add paragraph with Unicode support
+ def add_unicode_paragraph(doc, text):
+ p = doc.add_paragraph(text)
+ try:
+ text.encode('ascii')
+ except UnicodeEncodeError:
+ from docx.oxml.ns import qn
+ for run in p.runs:
+ run.font.name = 'Arial'
+ r = run._element
+ r.rPr.rFonts.set(qn('w:eastAsia'), 'Arial')
+ return p
+
+ # Add metadata
+ add_unicode_paragraph(doc, f'Uploaded: {recording.created_at.strftime("%Y-%m-%d %H:%M")}')
+ if recording.meeting_date:
+ add_unicode_paragraph(doc, f'Recording Date: {recording.meeting_date.strftime("%Y-%m-%d")}')
+ if recording.participants:
+ add_unicode_paragraph(doc, f'Participants: {recording.participants}')
+ visible_tags = recording.get_visible_tags(current_user)
+ if visible_tags:
+ tags_str = ', '.join([tag.name for tag in visible_tags])
+ add_unicode_paragraph(doc, f'Tags: {tags_str}')
+ doc.add_paragraph('') # Empty line
+
+ # Process markdown content using the helper function
+ process_markdown_to_docx(doc, recording.summary)
+
+ # Save to BytesIO
+ doc_stream = BytesIO()
+ doc.save(doc_stream)
+ doc_stream.seek(0)
+
+ # Create safe filename
+ safe_title = re.sub(r'[<>:"/\\|?*]', '', recording.title or 'Untitled')
+ safe_title = re.sub(r'[-\s]+', '-', safe_title).strip('-')
+ filename = f'summary-{safe_title}.docx' if safe_title else f'summary-recording-{recording_id}.docx'
+
+ # Create ASCII fallback for send_file - if title has non-ASCII chars, use generic name with ID
+ ascii_filename = filename.encode('ascii', 'ignore').decode('ascii')
+ if not ascii_filename.strip() or ascii_filename.strip() in ['summary-.docx', 'summary-recording-.docx']:
+ ascii_filename = f'summary-recording-{recording_id}.docx'
+
+ response = send_file(
+ doc_stream,
+ as_attachment=False,
+ mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
+ )
+ # Properly encode filename for international characters
+ # Check if filename contains non-ASCII characters
+ try:
+ # Try to encode as ASCII - if this works, use simple format
+ filename.encode('ascii')
+ # ASCII-only filename, use simple format
+ response.headers['Content-Disposition'] = f'attachment; filename="{filename}"'
+ except UnicodeEncodeError:
+ # Contains non-ASCII characters, use proper RFC 2231 encoding
+ try:
+ # Use Python's built-in RFC 2231 encoder
+ encoded_value = encode_rfc2231(filename, charset='utf-8')
+ header_value = f'attachment; filename*={encoded_value}'
+ current_app.logger.info(f"DEBUG CHINESE FILENAME (RFC2231): Original='{filename}', Header='{header_value}'")
+ response.headers['Content-Disposition'] = header_value
+ except Exception as e:
+ # Fallback to simple attachment with generic name
+ current_app.logger.error(f"RFC2231 encoding failed: {e}, using fallback")
+ response.headers['Content-Disposition'] = f'attachment; filename="download-{recording_id}.docx"'
+ return response
+
+ except Exception as e:
+ current_app.logger.error(f"Error generating summary Word document: {e}")
+ return jsonify({'error': 'Failed to generate Word document'}), 500
+
+
+
+@recordings_bp.route('/recording/<int:recording_id>/download/chat', methods=['POST'])
+@login_required
+def download_chat_word(recording_id):
+ """Download chat conversation as a Word document."""
+ try:
+ from docx import Document
+ from docx.shared import Inches
+ import re
+ from io import BytesIO
+
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ if not has_recording_access(recording, current_user):
+ return jsonify({'error': 'You do not have permission to access this recording'}), 403
+
+ # Get chat messages from request
+ data = request.json
+ if not data or 'messages' not in data:
+ return jsonify({'error': 'No messages provided'}), 400
+
+ messages = data['messages']
+ if not messages:
+ return jsonify({'error': 'No messages to download'}), 400
+
+ # Create Word document
+ doc = Document()
+
+ # Add title
+ title_text = f'Chat Conversation: {recording.title or "Untitled Recording"}'
+ title = doc.add_heading(title_text, 0)
+ # Check if title needs Unicode font support
+ try:
+ title_text.encode('ascii')
+ except UnicodeEncodeError:
+ from docx.oxml.ns import qn
+ for run in title.runs:
+ run.font.name = 'Arial'
+ r = run._element
+ r.rPr.rFonts.set(qn('w:eastAsia'), 'Arial')
+
+ # Helper function to add paragraph with Unicode support
+ def add_unicode_paragraph(doc, text):
+ p = doc.add_paragraph(text)
+ try:
+ text.encode('ascii')
+ except UnicodeEncodeError:
+ from docx.oxml.ns import qn
+ for run in p.runs:
+ run.font.name = 'Arial'
+ r = run._element
+ r.rPr.rFonts.set(qn('w:eastAsia'), 'Arial')
+ return p
+
+ # Add metadata
+ add_unicode_paragraph(doc, f'Recording Date: {recording.created_at.strftime("%Y-%m-%d %H:%M")}')
+ add_unicode_paragraph(doc, f'Chat Export Date: {datetime.utcnow().strftime("%Y-%m-%d %H:%M")}')
+ doc.add_paragraph('') # Empty line
+
+ # Add chat messages
+ for message in messages:
+ role = message.get('role', 'unknown')
+ content = message.get('content', '')
+ thinking = message.get('thinking', '')
+
+ # Add role header
+ if role == 'user':
+ p = doc.add_paragraph()
+ run = p.add_run('You: ')
+ run.bold = True
+ elif role == 'assistant':
+ p = doc.add_paragraph()
+ run = p.add_run('Assistant: ')
+ run.bold = True
+ else:
+ p = doc.add_paragraph()
+ run = p.add_run(f'{role.title()}: ')
+ run.bold = True
+
+ # Add thinking content if present
+ if thinking and role == 'assistant':
+ p = doc.add_paragraph()
+ p.add_run('[Model Reasoning]\n').italic = True
+ p.add_run(thinking).italic = True
+ doc.add_paragraph('') # Empty line
+
+ # Add message content with markdown formatting
+ process_markdown_to_docx(doc, content)
+
+ doc.add_paragraph('') # Empty line between messages
+
+ # Save to BytesIO
+ doc_stream = BytesIO()
+ doc.save(doc_stream)
+ doc_stream.seek(0)
+
+ # Create safe filename
+ safe_title = re.sub(r'[<>:"/\\|?*]', '', recording.title or 'Untitled')
+ safe_title = re.sub(r'[-\s]+', '-', safe_title).strip('-')
+ filename = f'chat-{safe_title}.docx' if safe_title else f'chat-recording-{recording_id}.docx'
+
+ # Create ASCII fallback for send_file - if title has non-ASCII chars, use generic name with ID
+ ascii_filename = filename.encode('ascii', 'ignore').decode('ascii')
+ if not ascii_filename.strip() or ascii_filename.strip() in ['chat-.docx', 'chat-recording-.docx']:
+ ascii_filename = f'chat-recording-{recording_id}.docx'
+
+ response = send_file(
+ doc_stream,
+ as_attachment=False,
+ mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
+ )
+
+ # Properly encode filename for international characters
+ # Check if filename contains non-ASCII characters
+ try:
+ # Try to encode as ASCII - if this works, use simple format
+ filename.encode('ascii')
+ # ASCII-only filename, use simple format
+ response.headers['Content-Disposition'] = f'attachment; filename="{filename}"'
+ except UnicodeEncodeError:
+ # Contains non-ASCII characters, use proper RFC 2231 encoding
+ try:
+ # Use Python's built-in RFC 2231 encoder
+ encoded_value = encode_rfc2231(filename, charset='utf-8')
+ header_value = f'attachment; filename*={encoded_value}'
+ current_app.logger.info(f"DEBUG CHINESE FILENAME (RFC2231): Original='{filename}', Header='{header_value}'")
+ response.headers['Content-Disposition'] = header_value
+ except Exception as e:
+ # Fallback to simple attachment with generic name
+ current_app.logger.error(f"RFC2231 encoding failed: {e}, using fallback")
+ response.headers['Content-Disposition'] = f'attachment; filename="download-{recording_id}.docx"'
+ return response
+
+ except Exception as e:
+ current_app.logger.error(f"Error generating chat Word document: {e}")
+ return jsonify({'error': 'Failed to generate Word document'}), 500
+
+
+
+@recordings_bp.route('/recording/<int:recording_id>/download/notes')
+@login_required
+def download_notes_word(recording_id):
+ """Download recording notes as a Word document."""
+ try:
+ from docx import Document
+ from docx.shared import Inches
+ import re
+ from io import BytesIO
+
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ if not has_recording_access(recording, current_user):
+ return jsonify({'error': 'You do not have permission to access this recording'}), 403
+
+ if not recording.notes:
+ return jsonify({'error': 'No notes available for this recording'}), 400
+
+ # Create Word document
+ doc = Document()
+
+ # Add title
+ title_text = f'Notes: {recording.title or "Untitled Recording"}'
+ title = doc.add_heading(title_text, 0)
+ # Check if title needs Unicode font support
+ try:
+ title_text.encode('ascii')
+ except UnicodeEncodeError:
+ from docx.oxml.ns import qn
+ for run in title.runs:
+ run.font.name = 'Arial'
+ r = run._element
+ r.rPr.rFonts.set(qn('w:eastAsia'), 'Arial')
+
+ # Helper function to add paragraph with Unicode support
+ def add_unicode_paragraph(doc, text):
+ p = doc.add_paragraph(text)
+ try:
+ text.encode('ascii')
+ except UnicodeEncodeError:
+ from docx.oxml.ns import qn
+ for run in p.runs:
+ run.font.name = 'Arial'
+ r = run._element
+ r.rPr.rFonts.set(qn('w:eastAsia'), 'Arial')
+ return p
+
+ # Add metadata
+ add_unicode_paragraph(doc, f'Uploaded: {recording.created_at.strftime("%Y-%m-%d %H:%M")}')
+ if recording.meeting_date:
+ add_unicode_paragraph(doc, f'Recording Date: {recording.meeting_date.strftime("%Y-%m-%d")}')
+ if recording.participants:
+ add_unicode_paragraph(doc, f'Participants: {recording.participants}')
+ visible_tags = recording.get_visible_tags(current_user)
+ if visible_tags:
+ tags_str = ', '.join([tag.name for tag in visible_tags])
+ add_unicode_paragraph(doc, f'Tags: {tags_str}')
+ doc.add_paragraph('') # Empty line
+
+ # Process markdown content using the helper function
+ process_markdown_to_docx(doc, recording.notes)
+
+ # Save to BytesIO
+ doc_stream = BytesIO()
+ doc.save(doc_stream)
+ doc_stream.seek(0)
+
+ # Create safe filename
+ safe_title = re.sub(r'[<>:"/\\|?*]', '', recording.title or 'Untitled')
+ safe_title = re.sub(r'[-\s]+', '-', safe_title).strip('-')
+ filename = f'notes-{safe_title}.docx' if safe_title else f'notes-recording-{recording_id}.docx'
+
+ # Create ASCII fallback for send_file - if title has non-ASCII chars, use generic name with ID
+ ascii_filename = filename.encode('ascii', 'ignore').decode('ascii')
+ if not ascii_filename.strip() or ascii_filename.strip() in ['notes-.docx', 'notes-recording-.docx']:
+ ascii_filename = f'notes-recording-{recording_id}.docx'
+
+ response = send_file(
+ doc_stream,
+ as_attachment=False,
+ mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
+ )
+ # Properly encode filename for international characters
+ # Check if filename contains non-ASCII characters
+ try:
+ # Try to encode as ASCII - if this works, use simple format
+ filename.encode('ascii')
+ # ASCII-only filename, use simple format
+ response.headers['Content-Disposition'] = f'attachment; filename="{filename}"'
+ except UnicodeEncodeError:
+ # Contains non-ASCII characters, use proper RFC 2231 encoding
+ try:
+ # Use Python's built-in RFC 2231 encoder
+ encoded_value = encode_rfc2231(filename, charset='utf-8')
+ header_value = f'attachment; filename*={encoded_value}'
+ current_app.logger.info(f"DEBUG CHINESE FILENAME (RFC2231): Original='{filename}', Header='{header_value}'")
+ response.headers['Content-Disposition'] = header_value
+ except Exception as e:
+ # Fallback to simple attachment with generic name
+ current_app.logger.error(f"RFC2231 encoding failed: {e}, using fallback")
+ response.headers['Content-Disposition'] = f'attachment; filename="download-{recording_id}.docx"'
+ return response
+
+ except Exception as e:
+ current_app.logger.error(f"Error generating notes Word document: {e}")
+ return jsonify({'error': 'Failed to generate Word document'}), 500
+
+
+
+@recordings_bp.route('/recording/<int:recording_id>/generate_summary', methods=['POST'])
+@login_required
+def generate_summary_endpoint(recording_id):
+ """Generate summary for a recording that doesn't have one."""
+ try:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ if not has_recording_access(recording, current_user, require_edit=True):
+ return jsonify({'error': 'You do not have permission to generate summary for this recording'}), 403
+
+ # Check if transcription exists
+ if not recording.transcription or len(recording.transcription.strip()) < 10:
+ return jsonify({'error': 'No valid transcription available for summary generation'}), 400
+
+ # Check if already processing
+ if recording.status in ['PROCESSING', 'SUMMARIZING']:
+ return jsonify({'error': 'Recording is already being processed'}), 400
+
+ # Check if OpenRouter client is available
+ if client is None:
+ return jsonify({'error': 'Summary service is not available (OpenRouter client not configured)'}), 503
+
+ current_app.logger.info(f"Starting summary generation for recording {recording_id}")
+
+ # Generate summary in background thread
+ thread = threading.Thread(
+ target=generate_summary_only_task,
+ args=(current_app._get_current_object().app_context(), recording_id)
+ )
+ thread.start()
+
+ return jsonify({
+ 'success': True,
+ 'message': 'Summary generation started'
+ })
+
+ except Exception as e:
+ db.session.rollback()
+ current_app.logger.error(f"Error starting summary generation for recording {recording_id}: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+
+@recordings_bp.route('/recording/<int:recording_id>/update_speakers', methods=['POST'])
+@login_required
+def update_speakers(recording_id):
+ """Updates speaker labels in a transcription with provided names."""
+ try:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ if not has_recording_access(recording, current_user, require_edit=True):
+ return jsonify({'error': 'You do not have permission to edit this recording'}), 403
+
+ data = request.json
+ speaker_map = data.get('speaker_map')
+ regenerate_summary = data.get('regenerate_summary', False)
+
+ if speaker_map is None:
+ return jsonify({'error': 'No speaker map provided'}), 400
+
+ transcription_text = recording.transcription
+ is_json = False
+ try:
+ transcription_data = json.loads(transcription_text)
+ # Updated check for our new simplified JSON format (a list of segment objects)
+ is_json = isinstance(transcription_data, list)
+ except (json.JSONDecodeError, TypeError):
+ is_json = False
+
+ speaker_names_used = []
+
+ if is_json:
+ # Handle new simplified JSON transcript (list of segments)
+ for segment in transcription_data:
+ original_speaker_label = segment.get('speaker')
+ if original_speaker_label in speaker_map:
+ new_name_info = speaker_map[original_speaker_label]
+ new_name = new_name_info.get('name', '').strip()
+ # If isMe is checked but no name provided, use current user's name
+ if new_name_info.get('isMe') and not new_name:
+ new_name = current_user.name or 'Me'
+
+ if new_name:
+ segment['speaker'] = new_name
+ if new_name not in speaker_names_used:
+ speaker_names_used.append(new_name)
+
+ recording.transcription = json.dumps(transcription_data)
+
+ # Update participants only from speakers that were actually given names (not default labels)
+ final_speakers = set()
+ for seg in transcription_data:
+ speaker = seg.get('speaker')
+ if speaker and str(speaker).strip():
+ # Only include speakers that have been given actual names (not default labels like "SPEAKER_01", "SPEAKER_09", etc.)
+ # Check if this speaker was updated with a real name (not a default label)
+ if not re.match(r'^SPEAKER_\d+$', str(speaker), re.IGNORECASE):
+ final_speakers.add(speaker)
+ recording.participants = ', '.join(sorted(list(final_speakers)))
+
+ else:
+ # Handle plain text transcript
+ new_participants = []
+ for speaker_label, new_name_info in speaker_map.items():
+ new_name = new_name_info.get('name', '').strip()
+ # If isMe is checked but no name provided, use current user's name
+ if new_name_info.get('isMe') and not new_name:
+ new_name = current_user.name or 'Me'
+
+ if new_name:
+ transcription_text = re.sub(r'\[\s*' + re.escape(speaker_label) + r'\s*\]', f'[{new_name}]', transcription_text, flags=re.IGNORECASE)
+ if new_name not in new_participants:
+ new_participants.append(new_name)
+
+ recording.transcription = transcription_text
+ if new_participants:
+ recording.participants = ', '.join(new_participants)
+ speaker_names_used = new_participants
+
+ # Update speaker usage statistics
+ if speaker_names_used:
+ update_speaker_usage(speaker_names_used)
+
+ # Update speaker voice embeddings if available
+ embeddings_updated = 0
+ snippets_created = 0
+ if recording.speaker_embeddings and speaker_map:
+ try:
+ # Parse embeddings from recording
+ embeddings_data = json.loads(recording.speaker_embeddings) if isinstance(recording.speaker_embeddings, str) else recording.speaker_embeddings
+
+ # Build reverse map: SPEAKER_XX -> actual name assigned
+ speaker_label_to_name = {}
+ for speaker_label, speaker_info in speaker_map.items():
+ name = speaker_info.get('name', '').strip()
+ # Handle isMe checkbox
+ if speaker_info.get('isMe') and not name:
+ name = current_user.name or 'Me'
+
+ # Only include speakers that were given real names (not SPEAKER_XX)
+ if name and not re.match(r'^SPEAKER_\d+$', name, re.IGNORECASE):
+ speaker_label_to_name[speaker_label] = name
+
+ # Update embeddings for each identified speaker
+ for speaker_label, embedding in embeddings_data.items():
+ if speaker_label in speaker_label_to_name and embedding and len(embedding) == 256:
+ speaker_name = speaker_label_to_name[speaker_label]
+
+ # Find or create the speaker
+ speaker = Speaker.query.filter_by(
+ user_id=current_user.id,
+ name=speaker_name
+ ).first()
+
+ if speaker:
+ # Update the speaker's voice embedding
+ similarity = update_speaker_embedding(speaker, embedding, recording.id)
+ embeddings_updated += 1
+
+ if similarity is not None:
+ current_app.logger.info(
+ f"Updated voice profile for '{speaker_name}' "
+ f"(similarity: {similarity*100:.1f}%)"
+ )
+ else:
+ current_app.logger.info(
+ f"Created initial voice profile for '{speaker_name}'"
+ )
+
+ # Create snippets for identified speakers
+ if speaker_label_to_name:
+ snippets_created = create_speaker_snippets(recording.id, speaker_map)
+ if snippets_created > 0:
+ current_app.logger.info(f"Created {snippets_created} speaker snippets")
+
+ except Exception as e:
+ current_app.logger.error(f"Error updating speaker embeddings: {e}", exc_info=True)
+ # Don't fail the whole request if embedding update fails
+
+ db.session.commit()
+
+ summary_queued = False
+ if regenerate_summary:
+ current_app.logger.info(f"Regenerating summary for recording {recording_id} after speaker update.")
+ thread = threading.Thread(
+ target=generate_summary_only_task,
+ args=(current_app._get_current_object().app_context(), recording.id)
+ )
+ thread.start()
+ summary_queued = True
+
+ # Return recording with per-user status
+ recording_dict = recording.to_dict(viewer_user=current_user)
+ enrich_recording_dict_with_user_status(recording_dict, recording, current_user)
+ return jsonify({
+ 'success': True,
+ 'message': 'Speakers updated successfully.',
+ 'recording': recording_dict,
+ 'summary_queued': summary_queued
+ })
+
+ except Exception as e:
+ db.session.rollback()
+ current_app.logger.error(f"Error updating speakers for recording {recording_id}: {e}", exc_info=True)
+ return jsonify({'error': str(e)}), 500
+
+
+
+@recordings_bp.route('/recording/<int:recording_id>/update_transcript', methods=['POST'])
+@login_required
+def update_transcript(recording_id):
+ """Updates the complete transcript data including text edits and speaker changes."""
+ try:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ if not has_recording_access(recording, current_user, require_edit=True):
+ return jsonify({'error': 'You do not have permission to edit this recording'}), 403
+
+ data = request.json
+ transcript_data = data.get('transcript_data')
+ speaker_map = data.get('speaker_map', {})
+ regenerate_summary = data.get('regenerate_summary', False)
+
+ if not transcript_data or not isinstance(transcript_data, list):
+ return jsonify({'error': 'Invalid transcript data provided'}), 400
+
+ # Update speaker names in the transcript data
+ speaker_names_used = []
+ for segment in transcript_data:
+ original_speaker_label = segment.get('speaker')
+
+ # Apply speaker name mapping if provided
+ if original_speaker_label in speaker_map:
+ new_name_info = speaker_map[original_speaker_label]
+ new_name = new_name_info.get('name', '').strip()
+ if new_name_info.get('isMe'):
+ new_name = current_user.name or 'Me'
+
+ if new_name:
+ segment['speaker'] = new_name
+ if new_name not in speaker_names_used:
+ speaker_names_used.append(new_name)
+
+ # Save the updated transcript
+ recording.transcription = json.dumps(transcript_data)
+
+ # Update participants
+ final_speakers = set()
+ for seg in transcript_data:
+ speaker = seg.get('speaker')
+ if speaker and str(speaker).strip():
+ # Only include speakers with real names (not default labels)
+ if not re.match(r'^SPEAKER_\d+$', str(speaker), re.IGNORECASE):
+ final_speakers.add(speaker)
+ recording.participants = ', '.join(sorted(list(final_speakers)))
+
+ # Update speaker usage statistics
+ if speaker_names_used:
+ update_speaker_usage(speaker_names_used)
+
+ db.session.commit()
+
+ summary_queued = False
+ if regenerate_summary:
+ current_app.logger.info(f"Regenerating summary for recording {recording_id} after transcript update.")
+ thread = threading.Thread(
+ target=generate_summary_only_task,
+ args=(current_app._get_current_object().app_context(), recording.id)
+ )
+ thread.start()
+ summary_queued = True
+ # Export will happen after summary regenerates
+ else:
+ # Re-export the recording if auto-export is enabled
+ export_recording(recording_id)
+
+ # Return recording with per-user status
+ recording_dict = recording.to_dict(viewer_user=current_user)
+ enrich_recording_dict_with_user_status(recording_dict, recording, current_user)
+ return jsonify({
+ 'success': True,
+ 'message': 'Transcript updated successfully.',
+ 'recording': recording_dict,
+ 'summary_queued': summary_queued
+ })
+
+ except Exception as e:
+ db.session.rollback()
+ current_app.logger.error(f"Error updating transcript for recording {recording_id}: {e}", exc_info=True)
+ return jsonify({'error': str(e)}), 500
+
+
+
+@recordings_bp.route('/recording/<int:recording_id>/auto_identify_speakers', methods=['POST'])
+@login_required
+def auto_identify_speakers(recording_id):
+ """
+ Automatically identifies speakers in a transcription using an LLM.
+ Strips existing names and re-identifies all speakers from scratch.
+ """
+ try:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ if not has_recording_access(recording, current_user):
+ return jsonify({'error': 'You do not have permission to modify this recording'}), 403
+
+ if not recording.transcription:
+ return jsonify({'error': 'No transcription available for speaker identification'}), 400
+
+ # Parse the transcription
+ try:
+ transcription_data = json.loads(recording.transcription)
+ except (json.JSONDecodeError, TypeError):
+ return jsonify({'error': 'Transcription format not supported for auto-identification'}), 400
+
+ if not isinstance(transcription_data, list):
+ return jsonify({'error': 'Transcription format not supported for auto-identification'}), 400
+
+ # Extract unique speakers in order of appearance
+ seen_speakers = set()
+ unique_speakers = []
+ for segment in transcription_data:
+ speaker = segment.get('speaker')
+ if speaker and speaker not in seen_speakers:
+ seen_speakers.add(speaker)
+ unique_speakers.append(speaker)
+
+ if not unique_speakers:
+ return jsonify({'error': 'No speakers found in transcription'}), 400
+
+ # Create a mapping from current names to SPEAKER_XX labels
+ speaker_to_label = {}
+ for idx, speaker in enumerate(unique_speakers):
+ speaker_to_label[speaker] = f'SPEAKER_{str(idx).zfill(2)}'
+
+ # Create a temporary transcript with SPEAKER_XX labels
+ temp_transcript = []
+ for segment in transcription_data:
+ temp_segment = segment.copy()
+ original_speaker = segment.get('speaker')
+ if original_speaker:
+ temp_segment['speaker'] = speaker_to_label[original_speaker]
+ temp_transcript.append(temp_segment)
+
+ # Format for LLM directly (don't pass JSON, pass formatted text)
+ formatted_lines = []
+ for segment in temp_transcript:
+ speaker = segment.get('speaker', 'Unknown Speaker')
+ sentence = segment.get('sentence', '')
+ formatted_lines.append(f"[{speaker}]: {sentence}")
+ formatted_transcription = "\n".join(formatted_lines)
+
+ # Get all SPEAKER_XX labels
+ speaker_labels = list(speaker_to_label.values())
+
+ current_app.logger.info(f"[Auto-Identify] Formatted transcript (first 500 chars): {formatted_transcription[:500]}")
+ current_app.logger.info(f"[Auto-Identify] Speaker labels: {speaker_labels}")
+
+ # Call identify_unidentified_speakers_from_text but pass the formatted text directly
+ # We need to bypass format_transcription_for_llm since we already formatted it
+ if not speaker_labels:
+ return jsonify({'error': 'No speakers found in transcription'}), 400
+
+ # Get configurable transcript length limit
+ transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)
+ if transcript_limit == -1:
+ transcript_text = formatted_transcription
+ else:
+ transcript_text = formatted_transcription[:transcript_limit]
+
+ prompt = f"""Analyze the following conversation transcript and identify the names of the speakers based on the context and content of their dialogue.
+
+The speakers that need to be identified are: {', '.join(speaker_labels)}
+
+Look for clues in the conversation such as:
+- Names mentioned by other speakers when addressing someone
+- Self-introductions or references to their own name
+- Context clues about roles, relationships, or positions
+- Any direct mentions of names in the dialogue
+
+Here is the complete conversation transcript:
+
+{transcript_text}
+
+Based on the conversation above, identify the most likely real names for the speakers. Pay close attention to how speakers address each other and any names that are mentioned in the dialogue.
+
+Respond with a single JSON object where keys are the speaker labels (e.g., "SPEAKER_01") and values are the identified full names. If a name cannot be determined from the conversation context, use an empty string "".
+
+Example format:
+{{
+ "SPEAKER_01": "Jane Smith",
+ "SPEAKER_03": "Bob Johnson",
+ "SPEAKER_05": ""
+}}
+
+JSON Response:
+"""
+
+ try:
+ from src.services.llm import call_llm_completion
+ current_app.logger.info(f"[Auto-Identify] Calling LLM directly with prompt")
+
+ completion = call_llm_completion(
+ messages=[
+ {"role": "system", "content": "You are an expert in analyzing conversation transcripts to identify speakers based on contextual clues in the dialogue. Analyze the conversation carefully to find names mentioned when speakers address each other or introduce themselves. Your response must be a single, valid JSON object containing only the requested speaker identifications."},
+ {"role": "user", "content": prompt}
+ ],
+ temperature=0.2,
+ response_format={"type": "json_object"}
+ )
+ response_content = completion.choices[0].message.content
+ current_app.logger.info(f"[Auto-Identify] LLM Raw Response: {response_content}")
+
+ from src.utils import safe_json_loads
+ identified_map = safe_json_loads(response_content, {})
+ current_app.logger.info(f"[Auto-Identify] Parsed identified_map: {identified_map}")
+
+ # Post-process the map to replace "Unknown" with an empty string
+ for speaker_label, identified_name in identified_map.items():
+ if identified_name and identified_name.strip().lower() in ["unknown", "n/a", "not available", "unclear"]:
+ identified_map[speaker_label] = ""
+ except Exception as e:
+ current_app.logger.error(f"[Auto-Identify] Error calling LLM: {e}", exc_info=True)
+ return jsonify({'error': f'Failed to identify speakers: {str(e)}'}), 500
+ current_app.logger.info(f"[Auto-Identify] LLM returned identified_map: {identified_map}")
+
+ # Map back to original speaker IDs
+ final_speaker_map = {}
+ for original_speaker, temp_label in speaker_to_label.items():
+ if temp_label in identified_map:
+ final_speaker_map[original_speaker] = identified_map[temp_label]
+
+ current_app.logger.info(f"[Auto-Identify] Final speaker_map to return: {final_speaker_map}")
+ current_app.logger.info(f"[Auto-Identify] Speaker mapping: {speaker_to_label}")
+
+ return jsonify({'success': True, 'speaker_map': final_speaker_map})
+
+ except ValueError as ve:
+ # Handle cases where API key is not set
+ return jsonify({'error': str(ve)}), 503
+ except Exception as e:
+ current_app.logger.error(f"Error during auto speaker identification for recording {recording_id}: {e}", exc_info=True)
+ return jsonify({'error': f'An unexpected error occurred: {str(e)}'}), 500
+
+# --- Chat with Transcription ---
+
+
+@recordings_bp.route('/recording/<int:recording_id>/reprocess_transcription', methods=['POST'])
+@login_required
+def reprocess_transcription(recording_id):
+ """Reprocess transcription for a given recording."""
+ try:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ if not has_recording_access(recording, current_user, require_edit=True):
+ return jsonify({'error': 'You do not have permission to reprocess this recording'}), 403
+
+ if not recording.audio_path or not os.path.exists(recording.audio_path):
+ return jsonify({'error': 'Audio file not found for reprocessing'}), 404
+
+ if recording.status in ['PROCESSING', 'SUMMARIZING']:
+ return jsonify({'error': 'Recording is already being processed'}), 400
+
+ # --- Convert file if necessary before reprocessing ---
+ filepath = recording.audio_path
+ filename_for_asr = recording.original_filename or os.path.basename(filepath)
+ filename_lower = filename_for_asr.lower()
+
+ supported_formats = ('.wav', '.mp3', '.flac')
+ if not filename_lower.endswith(supported_formats):
+ current_app.logger.info(f"Reprocessing: Converting {filename_lower} format to high-quality MP3.")
+ base_filepath, file_ext = os.path.splitext(filepath)
+ temp_mp3_filepath = f"{base_filepath}_temp.mp3"
+ final_mp3_filepath = f"{base_filepath}.mp3"
+
+ try:
+ # Convert to high-quality MP3 (128kbps, 44.1kHz)
+ subprocess.run(
+ ['ffmpeg', '-i', filepath, '-y', '-acodec', 'libmp3lame', '-b:a', '128k', '-ar', '44100', temp_mp3_filepath],
+ check=True, capture_output=True, text=True
+ )
+ current_app.logger.info(f"Successfully converted {filepath} to {temp_mp3_filepath} (128kbps MP3)")
+
+ # If the original file is not the same as the final mp3 file, remove it
+ if filepath.lower() != final_mp3_filepath.lower():
+ os.remove(filepath)
+
+ # Rename the temporary file to the final filename
+ os.rename(temp_mp3_filepath, final_mp3_filepath)
+
+ filepath = final_mp3_filepath
+ filename_for_asr = os.path.basename(filepath)
+
+ # Update database with new path and mime type
+ recording.audio_path = filepath
+ recording.mime_type, _ = mimetypes.guess_type(filepath)
+ db.session.commit()
+
+ except FileNotFoundError:
+ current_app.logger.error("ffmpeg command not found. Please ensure ffmpeg is installed and in the system's PATH.")
+ return jsonify({'error': 'Audio conversion tool (ffmpeg) not found on server.'}), 500
+ except subprocess.CalledProcessError as e:
+ current_app.logger.error(f"ffmpeg conversion failed for {filepath}: {e.stderr}")
+ return jsonify({'error': f'Failed to convert audio file: {e.stderr}'}), 500
+
+ # --- Proceed with reprocessing ---
+ recording.transcription = None
+ recording.summary = None
+ recording.status = 'PROCESSING'
+
+ # Clear existing events since they depend on the transcription
+ Event.query.filter_by(recording_id=recording_id).delete()
+
+ db.session.commit()
+
+ # Refresh the recording object to ensure it has the latest committed data
+ db.session.refresh(recording)
+
+ current_app.logger.info(f"Starting transcription reprocessing for recording {recording_id}")
+
+ # Decide which transcription method to use
+ if USE_ASR_ENDPOINT:
+ current_app.logger.info(f"Using ASR endpoint for reprocessing recording {recording_id}")
+
+ data = request.json or {}
+ language = data.get('language') or (recording.owner.transcription_language if recording.owner else None)
+ min_speakers = data.get('min_speakers') or None
+ max_speakers = data.get('max_speakers') or None
+
+ # Convert to int if provided
+ if min_speakers:
+ try:
+ min_speakers = int(min_speakers)
+ except (ValueError, TypeError):
+ min_speakers = None
+ if max_speakers:
+ try:
+ max_speakers = int(max_speakers)
+ except (ValueError, TypeError):
+ max_speakers = None
+
+ # Apply tag defaults if no user input provided (get merged defaults from all tags on this recording)
+ if (min_speakers is None or max_speakers is None) and recording.tags:
+ # Get tag defaults (use first non-None value from ordered tags)
+ for tag_association in sorted(recording.tag_associations, key=lambda x: x.order):
+ tag = tag_association.tag
+ if min_speakers is None and tag.default_min_speakers:
+ min_speakers = tag.default_min_speakers
+ if max_speakers is None and tag.default_max_speakers:
+ max_speakers = tag.default_max_speakers
+ # Stop once we have both values
+ if min_speakers is not None and max_speakers is not None:
+ break
+
+ # Apply environment variable defaults if still no values (reprocess hierarchy: user input > tag defaults > env vars > auto-detect)
+ if min_speakers is None and ASR_MIN_SPEAKERS:
+ try:
+ min_speakers = int(ASR_MIN_SPEAKERS)
+ except (ValueError, TypeError):
+ min_speakers = None
+ if max_speakers is None and ASR_MAX_SPEAKERS:
+ try:
+ max_speakers = int(ASR_MAX_SPEAKERS)
+ except (ValueError, TypeError):
+ max_speakers = None
+ if '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_DIARIZE
+ else:
+ diarize_setting = recording.owner.diarize if recording.owner else False
+
+ start_time = datetime.utcnow()
+ thread = threading.Thread(
+ target=transcribe_audio_asr,
+ args=(current_app._get_current_object().app_context(), recording.id, filepath, filename_for_asr, start_time, recording.mime_type, language, diarize_setting, min_speakers, max_speakers)
+ )
+ else:
+ current_app.logger.info(f"Using standard transcription API for reprocessing recording {recording_id}")
+ start_time = datetime.utcnow()
+ thread = threading.Thread(
+ target=transcribe_audio_task,
+ args=(current_app._get_current_object().app_context(), recording.id, filepath, filename_for_asr, start_time)
+ )
+
+ thread.start()
+
+ # Return recording with per-user status
+ recording_dict = recording.to_dict(viewer_user=current_user)
+ enrich_recording_dict_with_user_status(recording_dict, recording, current_user)
+ return jsonify({
+ 'success': True,
+ 'message': 'Transcription reprocessing started',
+ 'recording': recording_dict
+ })
+
+ except Exception as e:
+ db.session.rollback()
+ current_app.logger.error(f"Error reprocessing transcription for recording {recording_id}: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+
+
+@recordings_bp.route('/recording/<int:recording_id>/reprocess_summary', methods=['POST'])
+@login_required
+def reprocess_summary(recording_id):
+ """Reprocess summary for a given recording (requires existing transcription)."""
+ try:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ if not has_recording_access(recording, current_user, require_edit=True):
+ return jsonify({'error': 'You do not have permission to reprocess this recording'}), 403
+
+ # Check if transcription exists
+ if not recording.transcription or len(recording.transcription.strip()) < 10:
+ return jsonify({'error': 'No valid transcription available for summary generation'}), 400
+
+ # Check if already processing
+ if recording.status in ['PROCESSING', 'SUMMARIZING']:
+ return jsonify({'error': 'Recording is already being processed'}), 400
+
+ # Check if OpenRouter client is available
+ if client is None:
+ return jsonify({'error': 'Summary service is not available (OpenRouter client not configured)'}), 503
+
+ # Get custom prompt from request if provided
+ data = request.get_json() or {}
+ custom_prompt = data.get('custom_prompt', '').strip() if data.get('custom_prompt') else None
+
+ # Debug logging
+ if custom_prompt:
+ current_app.logger.info(f"Received custom prompt override for recording {recording_id} (length: {len(custom_prompt)})")
+ else:
+ current_app.logger.info(f"No custom prompt override provided for recording {recording_id}, will use default priority")
+
+ # Set status to SUMMARIZING and clear existing summary
+ recording.summary = None
+ recording.status = 'SUMMARIZING'
+
+ # Clear existing events since they might be re-extracted during summary generation
+ Event.query.filter_by(recording_id=recording_id).delete()
+
+ db.session.commit()
+
+ # Refresh the recording object to ensure it has the latest committed data
+ db.session.refresh(recording)
+
+ current_app.logger.info(f"Starting summary reprocessing for recording {recording_id}" +
+ (f" with custom prompt (length: {len(custom_prompt)})" if custom_prompt else ""))
+
+ # Start summary generation in background thread
+ def reprocess_summary_task(app_context, recording_id, custom_prompt_override=None, user_id=None):
+ with app_context:
+ current_app.logger.info(f"Starting summary reprocessing for recording {recording_id} using generate_summary_only_task")
+ generate_summary_only_task(app_context, recording_id, custom_prompt_override=custom_prompt_override, user_id=user_id)
+
+ thread = threading.Thread(
+ target=reprocess_summary_task,
+ args=(current_app._get_current_object().app_context(), recording.id, custom_prompt, current_user.id)
+ )
+ thread.start()
+
+ # Return recording with per-user status
+ recording_dict = recording.to_dict(viewer_user=current_user)
+ enrich_recording_dict_with_user_status(recording_dict, recording, current_user)
+ return jsonify({
+ 'success': True,
+ 'message': 'Summary reprocessing started',
+ 'recording': recording_dict
+ })
+
+ except Exception as e:
+ db.session.rollback()
+ current_app.logger.error(f"Error reprocessing summary for recording {recording_id}: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+
+@recordings_bp.route('/recording/<int:recording_id>/reset_status', methods=['POST'])
+@login_required
+def reset_status(recording_id):
+ """Resets the status of a stuck or failed recording."""
+ try:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ if not has_recording_access(recording, current_user, require_edit=True):
+ return jsonify({'error': 'You do not have permission to modify this recording'}), 403
+
+ # Allow resetting if it's stuck or failed
+ if recording.status in ['PENDING', 'PROCESSING', 'SUMMARIZING', 'FAILED']:
+ recording.status = 'FAILED'
+ recording.error_message = "Manually reset from stuck or failed state."
+ db.session.commit()
+ current_app.logger.info(f"Manually reset status for recording {recording_id} to FAILED.")
+
+ # Return recording with per-user status
+ recording_dict = recording.to_dict(viewer_user=current_user)
+ enrich_recording_dict_with_user_status(recording_dict, recording, current_user)
+ return jsonify({'success': True, 'message': 'Recording status has been reset.', 'recording': recording_dict})
+ else:
+ return jsonify({'error': f'Recording is not in a state that can be reset. Current status: {recording.status}'}), 400
+
+ except Exception as e:
+ db.session.rollback()
+ current_app.logger.error(f"Error resetting status for recording {recording_id}: {e}")
+ return jsonify({'error': str(e)}), 500
+
+# --- Authentication Routes ---
+
+
+@recordings_bp.route('/')
+@login_required
+def index():
+ # Check if user is a group admin
+ is_team_admin = GroupMembership.query.filter_by(
+ user_id=current_user.id,
+ role='admin'
+ ).first() is not None
+
+ # Pass the ASR config, inquire mode config, and user language preference to the template
+ user_language = current_user.ui_language if current_user.is_authenticated and current_user.ui_language else 'en'
+
+ # Calculate if archive toggle should be shown (only when audio-only deletion mode is active)
+ enable_archive_toggle = ENABLE_AUTO_DELETION and DELETION_MODE == 'audio_only'
+
+ return render_template('index.html',
+ use_asr_endpoint=USE_ASR_ENDPOINT,
+ inquire_mode_enabled=ENABLE_INQUIRE_MODE,
+ enable_archive_toggle=enable_archive_toggle,
+ enable_internal_sharing=ENABLE_INTERNAL_SHARING,
+ user_language=user_language,
+ is_team_admin=is_team_admin)
+
+
+
+def get_accessible_recording_ids(user_id):
+ """
+ Get all recording IDs that a user has access to.
+
+ Includes:
+ - Recordings owned by the user
+ - Recordings shared with the user via InternalShare
+ - Recordings shared via group tags (if team membership exists)
+
+ Args:
+ user_id (int): User ID to check access for
+
+ Returns:
+ list: List of recording IDs the user can access
+ """
+ accessible_ids = set()
+
+ # 1. User's own recordings
+ own_recordings = db.session.query(Recording.id).filter_by(user_id=user_id).all()
+ accessible_ids.update([r.id for r in own_recordings])
+
+ # 2. Internally shared recordings
+ if ENABLE_INTERNAL_SHARING:
+ shared_recordings = db.session.query(InternalShare.recording_id).filter_by(
+ shared_with_user_id=user_id
+ ).all()
+ accessible_ids.update([r.recording_id for r in shared_recordings])
+
+ return list(accessible_ids)
+
+
+@recordings_bp.route('/recordings', methods=['GET'])
+def get_recordings():
+ """Get all recordings for the current user (simple list)."""
+ try:
+ # Check if user is logged in
+ if not current_user.is_authenticated:
+ return jsonify([]) # Return empty array if not logged in
+
+ # Filter recordings by the current user
+ stmt = select(Recording).where(Recording.user_id == current_user.id).order_by(Recording.created_at.desc())
+ recordings = db.session.execute(stmt).scalars().all()
+ return jsonify([recording.to_dict(viewer_user=current_user) for recording in recordings])
+ except Exception as e:
+ current_app.logger.error(f"Error fetching recordings: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+@recordings_bp.route('/api/recordings', methods=['GET'])
+@login_required
+def get_recordings_paginated():
+ """Get recordings with pagination and server-side filtering (includes shared recordings)."""
+ import re
+ try:
+ # Parse query parameters
+ page = request.args.get('page', 1, type=int)
+ per_page = min(request.args.get('per_page', 25, type=int), 100) # Cap at 100 per page
+ search_query = request.args.get('q', '').strip()
+
+ # Get all accessible recording IDs (own + shared)
+ accessible_recording_ids = get_accessible_recording_ids(current_user.id)
+
+ if not accessible_recording_ids:
+ return jsonify({
+ 'recordings': [],
+ 'pagination': {
+ 'page': page,
+ 'per_page': per_page,
+ 'total': 0,
+ 'total_pages': 0,
+ 'has_next': False,
+ 'has_prev': False
+ }
+ })
+
+ # Build base query to include accessible recordings
+ stmt = select(Recording).where(Recording.id.in_(accessible_recording_ids))
+
+ # Apply search filters if provided
+ if search_query:
+ # Extract date filters
+ date_filters = re.findall(r'date:(\S+)', search_query.lower())
+ date_from_filters = re.findall(r'date_from:(\S+)', search_query.lower())
+ date_to_filters = re.findall(r'date_to:(\S+)', search_query.lower())
+ tag_filters = re.findall(r'tag:(\S+)', search_query.lower())
+
+ # Remove special syntax to get text search
+ text_query = re.sub(r'date:\S+', '', search_query, flags=re.IGNORECASE)
+ text_query = re.sub(r'date_from:\S+', '', text_query, flags=re.IGNORECASE)
+ text_query = re.sub(r'date_to:\S+', '', text_query, flags=re.IGNORECASE)
+ text_query = re.sub(r'tag:\S+', '', text_query, flags=re.IGNORECASE).strip()
+
+ # Apply date filters
+ for date_filter in date_filters:
+ if date_filter == 'today':
+ today = datetime.now().date()
+ stmt = stmt.where(
+ db.or_(
+ db.func.date(Recording.meeting_date) == today,
+ db.and_(
+ Recording.meeting_date.is_(None),
+ db.func.date(Recording.created_at) == today
+ )
+ )
+ )
+ elif date_filter == 'yesterday':
+ yesterday = datetime.now().date() - timedelta(days=1)
+ stmt = stmt.where(
+ db.or_(
+ db.func.date(Recording.meeting_date) == yesterday,
+ db.and_(
+ Recording.meeting_date.is_(None),
+ db.func.date(Recording.created_at) == yesterday
+ )
+ )
+ )
+ elif date_filter == 'thisweek':
+ today = datetime.now().date()
+ start_of_week = today - timedelta(days=today.weekday())
+ stmt = stmt.where(
+ db.or_(
+ Recording.meeting_date >= start_of_week,
+ db.and_(
+ Recording.meeting_date.is_(None),
+ db.func.date(Recording.created_at) >= start_of_week
+ )
+ )
+ )
+ elif date_filter == 'lastweek':
+ today = datetime.now().date()
+ end_of_last_week = today - timedelta(days=today.weekday())
+ start_of_last_week = end_of_last_week - timedelta(days=7)
+ stmt = stmt.where(
+ db.or_(
+ db.and_(
+ Recording.meeting_date >= start_of_last_week,
+ Recording.meeting_date < end_of_last_week
+ ),
+ db.and_(
+ Recording.meeting_date.is_(None),
+ db.func.date(Recording.created_at) >= start_of_last_week,
+ db.func.date(Recording.created_at) < end_of_last_week
+ )
+ )
+ )
+ elif date_filter == 'thismonth':
+ today = datetime.now().date()
+ start_of_month = today.replace(day=1)
+ stmt = stmt.where(
+ db.or_(
+ Recording.meeting_date >= start_of_month,
+ db.and_(
+ Recording.meeting_date.is_(None),
+ db.func.date(Recording.created_at) >= start_of_month
+ )
+ )
+ )
+ elif date_filter == 'lastmonth':
+ today = datetime.now().date()
+ first_day_this_month = today.replace(day=1)
+ last_day_last_month = first_day_this_month - timedelta(days=1)
+ first_day_last_month = last_day_last_month.replace(day=1)
+ stmt = stmt.where(
+ db.or_(
+ db.and_(
+ Recording.meeting_date >= first_day_last_month,
+ Recording.meeting_date <= last_day_last_month
+ ),
+ db.and_(
+ Recording.meeting_date.is_(None),
+ db.func.date(Recording.created_at) >= first_day_last_month,
+ db.func.date(Recording.created_at) <= last_day_last_month
+ )
+ )
+ )
+ elif re.match(r'^\d{4}-\d{2}-\d{2}$', date_filter):
+ # Specific date format YYYY-MM-DD
+ target_date = datetime.strptime(date_filter, '%Y-%m-%d').date()
+ stmt = stmt.where(
+ db.or_(
+ db.func.date(Recording.meeting_date) == target_date,
+ db.and_(
+ Recording.meeting_date.is_(None),
+ db.func.date(Recording.created_at) == target_date
+ )
+ )
+ )
+ elif re.match(r'^\d{4}-\d{2}$', date_filter):
+ # Month format YYYY-MM
+ year, month = map(int, date_filter.split('-'))
+ stmt = stmt.where(
+ db.or_(
+ db.and_(
+ db.extract('year', Recording.meeting_date) == year,
+ db.extract('month', Recording.meeting_date) == month
+ ),
+ db.and_(
+ Recording.meeting_date.is_(None),
+ db.extract('year', Recording.created_at) == year,
+ db.extract('month', Recording.created_at) == month
+ )
+ )
+ )
+ elif re.match(r'^\d{4}$', date_filter):
+ # Year format YYYY
+ year = int(date_filter)
+ stmt = stmt.where(
+ db.or_(
+ db.extract('year', Recording.meeting_date) == year,
+ db.and_(
+ Recording.meeting_date.is_(None),
+ db.extract('year', Recording.created_at) == year
+ )
+ )
+ )
+
+ # Apply date range filters
+ if date_from_filters and date_from_filters[0]:
+ try:
+ date_from = datetime.strptime(date_from_filters[0], '%Y-%m-%d').date()
+ stmt = stmt.where(
+ db.or_(
+ Recording.meeting_date >= date_from,
+ db.and_(
+ Recording.meeting_date.is_(None),
+ db.func.date(Recording.created_at) >= date_from
+ )
+ )
+ )
+ except ValueError:
+ pass # Invalid date format, ignore
+
+ if date_to_filters and date_to_filters[0]:
+ try:
+ date_to = datetime.strptime(date_to_filters[0], '%Y-%m-%d').date()
+ stmt = stmt.where(
+ db.or_(
+ Recording.meeting_date <= date_to,
+ db.and_(
+ Recording.meeting_date.is_(None),
+ db.func.date(Recording.created_at) <= date_to
+ )
+ )
+ )
+ except ValueError:
+ pass # Invalid date format, ignore
+
+ # Apply tag filters
+ if tag_filters:
+ # Join with tags table and filter by tag names
+ tag_conditions = []
+ for tag_filter in tag_filters:
+ # Replace underscores back to spaces for matching
+ tag_name = tag_filter.replace('_', ' ')
+ tag_conditions.append(Tag.name.ilike(f'%{tag_name}%'))
+
+ stmt = stmt.join(RecordingTag).join(Tag).where(db.or_(*tag_conditions))
+
+ # Apply text search
+ if text_query:
+ from src.models.sharing import SharedRecordingState
+
+ # Search in user-specific notes:
+ # - For owned recordings: search Recording.notes
+ # - For shared recordings: search SharedRecordingState.personal_notes
+
+ text_conditions = [
+ Recording.title.ilike(f'%{text_query}%'),
+ Recording.participants.ilike(f'%{text_query}%'),
+ Recording.transcription.ilike(f'%{text_query}%'),
+ # Search owner's notes for owned recordings
+ db.and_(
+ Recording.user_id == current_user.id,
+ Recording.notes.ilike(f'%{text_query}%')
+ )
+ ]
+
+ # Add search for personal notes in shared recordings
+ # Use a subquery to check if personal_notes match
+ shared_notes_subq = select(SharedRecordingState.recording_id).where(
+ db.and_(
+ SharedRecordingState.user_id == current_user.id,
+ SharedRecordingState.personal_notes.ilike(f'%{text_query}%')
+ )
+ ).scalar_subquery()
+
+ text_conditions.append(Recording.id.in_(shared_notes_subq))
+
+ stmt = stmt.where(db.or_(*text_conditions))
+
+ # Apply ordering (most recent first based on meeting_date or created_at)
+ stmt = stmt.order_by(
+ db.case(
+ (Recording.meeting_date.is_not(None), Recording.meeting_date),
+ else_=db.func.date(Recording.created_at)
+ ).desc(),
+ Recording.created_at.desc()
+ )
+
+ # Get total count for pagination info
+ count_stmt = select(db.func.count()).select_from(stmt.subquery())
+ total_count = db.session.execute(count_stmt).scalar()
+
+ # Apply pagination
+ offset = (page - 1) * per_page
+ stmt = stmt.offset(offset).limit(per_page)
+
+ # Execute query
+ recordings = db.session.execute(stmt).scalars().all()
+
+ # Enrich recordings with sharing metadata
+ enriched_recordings = []
+ for recording in recordings:
+ rec_dict = recording.to_list_dict(viewer_user=current_user)
+
+ # Add sharing metadata
+ is_owner = recording.user_id == current_user.id
+ rec_dict['is_owner'] = is_owner
+
+ # Get per-user status (owner uses Recording fields, recipients use SharedRecordingState)
+ user_inbox, user_highlighted = get_user_recording_status(recording, current_user)
+ rec_dict['is_inbox'] = user_inbox
+ rec_dict['is_highlighted'] = user_highlighted
+
+ # Add edit permission info (uses has_recording_access which checks group admin status)
+ rec_dict['can_edit'] = has_recording_access(recording, current_user, require_edit=True)
+
+ # Add delete permission info (only owner can delete)
+ rec_dict['can_delete'] = is_owner and (USERS_CAN_DELETE or current_user.is_admin)
+
+ if not is_owner:
+ # This is a shared recording - get owner info and share permissions
+ owner = User.query.get(recording.user_id)
+ rec_dict['owner_username'] = owner.username if owner else "Unknown"
+ rec_dict['is_shared'] = True
+ # Don't show outgoing share count for recordings you don't own
+ rec_dict['shared_with_count'] = 0
+ rec_dict['public_share_count'] = 0
+
+ # Get share permissions
+ share = InternalShare.query.filter_by(
+ recording_id=recording.id,
+ shared_with_user_id=current_user.id
+ ).first()
+
+ if share:
+ rec_dict['share_info'] = {
+ 'share_id': share.id,
+ 'owner_username': owner.username if owner else "Unknown",
+ 'can_edit': share.can_edit,
+ 'can_reshare': share.can_reshare,
+ 'shared_at': share.created_at.isoformat()
+ }
+ else:
+ # Fallback if share record not found (shouldn't happen)
+ rec_dict['share_info'] = {
+ 'can_edit': False,
+ 'can_reshare': False
+ }
+ else:
+ rec_dict['is_shared'] = False
+
+ # Check if recording has group tags (among visible tags)
+ visible_tags = recording.get_visible_tags(current_user)
+ has_group_tags = any(tag.is_group_tag for tag in visible_tags)
+ rec_dict['has_group_tags'] = has_group_tags
+
+ enriched_recordings.append(rec_dict)
+
+ # Calculate pagination metadata
+ total_pages = (total_count + per_page - 1) // per_page
+ has_next = page < total_pages
+ has_prev = page > 1
+
+ return jsonify({
+ 'recordings': enriched_recordings,
+ 'pagination': {
+ 'page': page,
+ 'per_page': per_page,
+ 'total': total_count,
+ 'total_pages': total_pages,
+ 'has_next': has_next,
+ 'has_prev': has_prev
+ }
+ })
+
+ except Exception as e:
+ current_app.logger.error(f"Error fetching paginated recordings: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+@recordings_bp.route('/save', methods=['POST'])
+@login_required
+def save_metadata():
+ """Save recording metadata (title, participants, notes, summary, etc.)."""
+ try:
+ data = request.json
+ if not data:
+ return jsonify({'error': 'No data provided'}), 400
+ recording_id = data.get('id')
+ if not recording_id:
+ return jsonify({'error': 'No recording ID provided'}), 400
+
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ # Check if user has at least view access
+ if not has_recording_access(recording, current_user, require_edit=False):
+ return jsonify({'error': 'You do not have permission to access this recording'}), 403
+
+ # Handle notes separately - no edit permission required (user-specific)
+ if 'notes' in data:
+ if recording.user_id == current_user.id:
+ # Owner saves to Recording.notes
+ recording.notes = sanitize_html(data['notes']) if data['notes'] else data['notes']
+ else:
+ # Shared user saves to personal_notes (requires SharedRecordingState)
+ from src.models.sharing import SharedRecordingState
+ state = SharedRecordingState.query.filter_by(
+ recording_id=recording.id,
+ user_id=current_user.id
+ ).first()
+
+ if not state:
+ # Create SharedRecordingState if it doesn't exist
+ state = SharedRecordingState(
+ recording_id=recording.id,
+ user_id=current_user.id,
+ is_inbox=True,
+ is_highlighted=False
+ )
+ db.session.add(state)
+
+ state.personal_notes = sanitize_html(data['notes']) if data['notes'] else data['notes']
+
+ # Determine if any fields requiring edit permission are being updated
+ edit_fields = ['title', 'participants', 'summary', 'meeting_date']
+ requires_edit = any(field in data for field in edit_fields)
+
+ # If edit fields are present, check for edit permission
+ if requires_edit and not has_recording_access(recording, current_user, require_edit=True):
+ return jsonify({'error': 'You do not have permission to edit this recording'}), 403
+
+ # Update fields requiring edit permission
+ if requires_edit:
+ if 'title' in data:
+ recording.title = data['title']
+ if 'participants' in data:
+ recording.participants = data['participants']
+ if 'summary' in data:
+ recording.summary = sanitize_html(data['summary']) if data['summary'] else data['summary']
+ if 'meeting_date' in data:
+ try:
+ date_str = data['meeting_date']
+ if date_str:
+ # Try to parse as full ISO datetime first
+ try:
+ recording.meeting_date = datetime.fromisoformat(date_str.replace('Z', '+00:00'))
+ except (ValueError, AttributeError):
+ # Fall back to date-only format, preserve existing time if available
+ parsed_date = datetime.strptime(date_str, '%Y-%m-%d')
+ if recording.meeting_date:
+ # Preserve existing time
+ existing_time = recording.meeting_date.time()
+ recording.meeting_date = datetime.combine(parsed_date.date(), existing_time)
+ else:
+ # No existing time, use the parsed date with midnight time
+ recording.meeting_date = parsed_date
+ else:
+ recording.meeting_date = None
+ except (ValueError, TypeError) as e:
+ current_app.logger.warning(f"Could not parse meeting_date '{data.get('meeting_date')}': {e}")
+
+ # Handle per-user status fields (only requires view permission)
+ if 'is_inbox' in data or 'is_highlighted' in data:
+ set_user_recording_status(
+ recording,
+ current_user,
+ is_inbox=data.get('is_inbox'),
+ is_highlighted=data.get('is_highlighted')
+ )
+
+ db.session.commit()
+
+ # Re-export the recording if auto-export is enabled and editable fields were changed
+ if requires_edit:
+ export_recording(recording_id)
+
+ # Return recording with per-user status
+ recording_dict = recording.to_dict(viewer_user=current_user)
+ enrich_recording_dict_with_user_status(recording_dict, recording, current_user)
+ return jsonify({'success': True, 'recording': recording_dict})
+
+ except Exception as e:
+ db.session.rollback()
+ current_app.logger.error(f"Error saving metadata for recording {data.get('id')}: {e}", exc_info=True)
+ return jsonify({'error': 'An unexpected error occurred while saving.'}), 500
+
+
+@recordings_bp.route('/recording/<int:recording_id>/update_transcription', methods=['POST'])
+@login_required
+def update_transcription(recording_id):
+ """Updates the transcription content for a recording."""
+ try:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ if not has_recording_access(recording, current_user, require_edit=True):
+ return jsonify({'error': 'You do not have permission to edit this recording'}), 403
+
+ data = request.json
+ new_transcription = data.get('transcription')
+
+ if new_transcription is None:
+ return jsonify({'error': 'No transcription data provided'}), 400
+
+ # The incoming data could be a JSON string (from ASR edit) or plain text
+ recording.transcription = new_transcription
+
+ # Optional: If the transcription changes, we might want to indicate that the summary is outdated.
+ # For now, we'll just save the transcript. A "regenerate summary" button could be a good follow-up.
+
+ db.session.commit()
+ current_app.logger.info(f"Transcription for recording {recording_id} was updated.")
+
+ # Re-export the recording if auto-export is enabled
+ export_recording(recording_id)
+
+ # Return recording with per-user status
+ recording_dict = recording.to_dict(viewer_user=current_user)
+ enrich_recording_dict_with_user_status(recording_dict, recording, current_user)
+ return jsonify({'success': True, 'message': 'Transcription updated successfully.', 'recording': recording_dict})
+
+ except Exception as e:
+ db.session.rollback()
+ current_app.logger.error(f"Error updating transcription for recording {recording_id}: {e}", exc_info=True)
+ return jsonify({'error': 'An unexpected error occurred while updating the transcription.'}), 500
+
+# Toggle inbox status endpoint
+
+
+@recordings_bp.route('/recording/<int:recording_id>/toggle_inbox', methods=['POST'])
+@login_required
+def toggle_inbox(recording_id):
+ try:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ # Only require view access (not edit) - users can manage their own inbox status
+ if not has_recording_access(recording, current_user, require_edit=False):
+ return jsonify({'error': 'You do not have permission to view this recording'}), 403
+
+ # Get current status and toggle it
+ current_inbox, current_highlighted = get_user_recording_status(recording, current_user)
+ new_inbox, new_highlighted = set_user_recording_status(recording, current_user, is_inbox=not current_inbox)
+
+ return jsonify({'success': True, 'is_inbox': new_inbox})
+ except Exception as e:
+ db.session.rollback()
+ current_app.logger.error(f"Error toggling inbox status for recording {recording_id}: {e}", exc_info=True)
+ return jsonify({'error': 'An unexpected error occurred.'}), 500
+
+# Toggle highlighted status endpoint
+
+
+@recordings_bp.route('/recording/<int:recording_id>/toggle_highlight', methods=['POST'])
+@login_required
+def toggle_highlight(recording_id):
+ try:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ # Only require view access (not edit) - users can manage their own highlight status
+ if not has_recording_access(recording, current_user, require_edit=False):
+ return jsonify({'error': 'You do not have permission to view this recording'}), 403
+
+ # Get current status and toggle it
+ current_inbox, current_highlighted = get_user_recording_status(recording, current_user)
+ new_inbox, new_highlighted = set_user_recording_status(recording, current_user, is_highlighted=not current_highlighted)
+
+ return jsonify({'success': True, 'is_highlighted': new_highlighted})
+ except Exception as e:
+ db.session.rollback()
+ current_app.logger.error(f"Error toggling highlighted status for recording {recording_id}: {e}", exc_info=True)
+ return jsonify({'error': 'An unexpected error occurred.'}), 500
+
+
+
+
+@recordings_bp.route('/upload', methods=['POST'])
+@login_required
+def upload_file():
+ try:
+ if 'file' not in request.files:
+ return jsonify({'error': 'No file provided'}), 400
+
+ file = request.files['file']
+ if file.filename == '':
+ return jsonify({'error': 'No file selected'}), 400
+
+ original_filename = file.filename
+ safe_filename = secure_filename(original_filename)
+ filepath = os.path.join(current_app.config['UPLOAD_FOLDER'], f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{safe_filename}")
+
+ # Get original file size
+ file.seek(0, os.SEEK_END)
+ original_file_size = file.tell()
+ file.seek(0)
+
+ # Check size limit before saving - only enforce if chunking is disabled or using ASR endpoint
+ max_content_length = current_app.config.get('MAX_CONTENT_LENGTH')
+
+ # Skip size check if chunking is enabled and using OpenAI Whisper API
+ should_enforce_size_limit = True
+ if ENABLE_CHUNKING and chunking_service and not USE_ASR_ENDPOINT:
+ should_enforce_size_limit = False
+ # Get chunking mode for better logging
+ mode, limit_value = chunking_service.parse_chunk_limit()
+ if mode == 'size':
+ current_app.logger.info(f"Size-based chunking enabled ({limit_value}MB limit) - skipping {original_file_size/1024/1024:.1f}MB size limit check")
+ else:
+ current_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()
+
+ file.save(filepath)
+ current_app.logger.info(f"File saved to {filepath}")
+
+ # --- Convert files only when chunking is needed ---
+ filename_lower = original_filename.lower()
+
+ # Check if chunking will be needed for this file
+ needs_chunking_for_processing = (chunking_service and
+ ENABLE_CHUNKING and
+ not USE_ASR_ENDPOINT and
+ chunking_service.needs_chunking(filepath, USE_ASR_ENDPOINT))
+
+ # Define supported formats based on whether chunking is needed
+ if needs_chunking_for_processing:
+ # For chunking: only support formats that work well with chunking
+ supported_formats = ('.wav', '.mp3', '.flac')
+ convertible_formats = ('.amr', '.3gp', '.3gpp', '.m4a', '.aac', '.ogg', '.wma', '.webm')
+ else:
+ # For direct transcription: support WebM and other formats directly
+ supported_formats = ('.wav', '.mp3', '.flac', '.webm', '.m4a', '.aac', '.ogg')
+ convertible_formats = ('.amr', '.3gp', '.3gpp', '.wma')
+
+ # Special handling for problematic AAC files when using ASR endpoint
+ is_problematic_aac = (USE_ASR_ENDPOINT and
+ (filename_lower.endswith('.aac') or
+ 'aac' in filename_lower.lower()))
+
+ # Convert if file is not in supported formats OR is problematic AAC for ASR
+ should_convert = ((not filename_lower.endswith(supported_formats) and needs_chunking_for_processing) or
+ is_problematic_aac)
+
+ if should_convert:
+ if is_problematic_aac:
+ current_app.logger.info(f"Converting AAC-encoded file {filename_lower} to high-quality MP3 for ASR endpoint compatibility.")
+ elif filename_lower.endswith(convertible_formats):
+ current_app.logger.info(f"Converting {filename_lower} format to high-quality MP3 for chunking processing.")
+ else:
+ current_app.logger.info(f"Attempting to convert unknown format ({filename_lower}) to high-quality MP3 for chunking.")
+
+ base_filepath, _ = os.path.splitext(filepath)
+ temp_mp3_filepath = f"{base_filepath}_temp.mp3"
+ mp3_filepath = f"{base_filepath}.mp3"
+
+ try:
+ # Convert to high-quality MP3 (128kbps, 44.1kHz) for better transcription accuracy
+ subprocess.run(
+ ['ffmpeg', '-i', filepath, '-y', '-acodec', 'libmp3lame', '-b:a', '128k', '-ar', '44100', '-ac', '1', temp_mp3_filepath],
+ check=True, capture_output=True, text=True
+ )
+ current_app.logger.info(f"Successfully converted {filepath} to {temp_mp3_filepath} (128kbps MP3)")
+
+ # If the original file is not the same as the final mp3 file, remove it
+ if filepath.lower() != mp3_filepath.lower():
+ os.remove(filepath)
+
+ # Rename the temporary file to the final filename
+ os.rename(temp_mp3_filepath, mp3_filepath)
+
+ filepath = mp3_filepath
+ except FileNotFoundError:
+ current_app.logger.error("ffmpeg command not found. Please ensure ffmpeg is installed and in the system's PATH.")
+ return jsonify({'error': 'Audio conversion tool (ffmpeg) not found on server.'}), 500
+ except subprocess.CalledProcessError as e:
+ current_app.logger.error(f"ffmpeg conversion failed for {filepath}: {e.stderr}")
+ return jsonify({'error': f'Failed to convert audio file: {e.stderr}'}), 500
+ elif not filename_lower.endswith(supported_formats):
+ # File is not supported and chunking is not needed - log but don't convert
+ current_app.logger.info(f"File format {filename_lower} will be processed directly without conversion (chunking not needed)")
+
+ # Get final file size (of original or converted file)
+ final_file_size = os.path.getsize(filepath)
+
+ # Determine MIME type of the final file
+ mime_type, _ = mimetypes.guess_type(filepath)
+ current_app.logger.info(f"Final MIME type: {mime_type} for file {filepath}")
+
+ # Get notes from the form
+ notes = request.form.get('notes')
+
+ # Get selected tags if provided (multiple tags support)
+ selected_tags = []
+ tag_index = 0
+ while True:
+ tag_id_key = f'tag_ids[{tag_index}]'
+ tag_id = request.form.get(tag_id_key)
+ if not tag_id:
+ break
+
+ # Check if tag belongs to user OR is a group tag where user is a member
+ tag = Tag.query.filter_by(id=tag_id).first()
+ if tag:
+ # Allow tag if it's user's own tag OR it's a group tag where user is a member
+ if tag.user_id == current_user.id or (tag.group_id and GroupMembership.query.filter_by(group_id=tag.group_id, user_id=current_user.id).first()):
+ selected_tags.append(tag)
+ tag_index += 1
+
+ # For backward compatibility with single tag uploads
+ if not selected_tags:
+ single_tag_id = request.form.get('tag_id')
+ if single_tag_id:
+ # Check if tag belongs to user OR is a group tag where user is a member
+ tag = Tag.query.filter_by(id=single_tag_id).first()
+ if tag and (tag.user_id == current_user.id or (tag.group_id and GroupMembership.query.filter_by(group_id=tag.group_id, user_id=current_user.id).first())):
+ selected_tags.append(tag)
+
+ # Get ASR advanced options if provided
+ language = request.form.get('language', '')
+ min_speakers = request.form.get('min_speakers') or None
+ max_speakers = request.form.get('max_speakers') or None
+
+ # Convert to int if provided
+ if min_speakers:
+ try:
+ min_speakers = int(min_speakers)
+ except (ValueError, TypeError):
+ min_speakers = None
+ if max_speakers:
+ try:
+ max_speakers = int(max_speakers)
+ except (ValueError, TypeError):
+ max_speakers = None
+
+ # Apply precedence hierarchy: user input > tag defaults > environment variables > auto-detect
+
+ # Apply tag defaults if tags are selected and values are not explicitly provided by user
+ # Use first tag's defaults (highest priority)
+ if selected_tags:
+ first_tag = selected_tags[0]
+ if not language and first_tag.default_language:
+ language = first_tag.default_language
+ if min_speakers is None and first_tag.default_min_speakers:
+ min_speakers = first_tag.default_min_speakers
+ if max_speakers is None and first_tag.default_max_speakers:
+ max_speakers = first_tag.default_max_speakers
+
+ # Apply environment variable defaults if still no values are set
+ if min_speakers is None and ASR_MIN_SPEAKERS:
+ try:
+ min_speakers = int(ASR_MIN_SPEAKERS)
+ except (ValueError, TypeError):
+ min_speakers = None
+ if max_speakers is None and ASR_MAX_SPEAKERS:
+ try:
+ max_speakers = int(ASR_MAX_SPEAKERS)
+ except (ValueError, TypeError):
+ max_speakers = None
+
+ # Create initial database entry
+ now = datetime.utcnow()
+ recording = Recording(
+ audio_path=filepath,
+ original_filename=original_filename,
+ title=f"Recording - {original_filename}",
+ file_size=final_file_size,
+ status='PENDING',
+ meeting_date=now,
+ user_id=current_user.id,
+ mime_type=mime_type,
+ notes=notes,
+ processing_source='upload' # Track that this was manually uploaded
+ )
+ db.session.add(recording)
+ db.session.commit()
+
+ # Add tags to recording if selected (preserve order)
+ for order, tag in enumerate(selected_tags, 1):
+ new_association = RecordingTag(
+ recording_id=recording.id,
+ tag_id=tag.id,
+ order=order,
+ added_at=datetime.utcnow()
+ )
+ db.session.add(new_association)
+
+ if selected_tags:
+ db.session.commit()
+ tag_names = [tag.name for tag in selected_tags]
+ current_app.logger.info(f"Added {len(selected_tags)} tags to recording {recording.id}: {', '.join(tag_names)}")
+
+ current_app.logger.info(f"Initial recording record created with ID: {recording.id}")
+
+ # --- Start transcription & summarization in background thread ---
+ start_time = datetime.utcnow()
+
+ # Pass ASR parameters and first tag to the transcription task (for compatibility with existing functions)
+ first_tag = selected_tags[0] if selected_tags else None
+ if USE_ASR_ENDPOINT:
+ current_app.logger.info(f"Starting ASR transcription thread for recording {recording.id} with params: language={language}, min_speakers={min_speakers}, max_speakers={max_speakers}, tag_id={first_tag.id if first_tag else None}")
+ thread = threading.Thread(
+ target=transcribe_audio_task,
+ args=(current_app._get_current_object().app_context(), recording.id, filepath, os.path.basename(filepath), start_time),
+ kwargs={'language': language, 'min_speakers': min_speakers, 'max_speakers': max_speakers, 'tag_id': first_tag.id if first_tag else None}
+ )
+ else:
+ current_app.logger.info(f"Starting Whisper transcription thread for recording {recording.id} with tag_id={first_tag.id if first_tag else None}")
+ thread = threading.Thread(
+ target=transcribe_audio_task,
+ args=(current_app._get_current_object().app_context(), recording.id, filepath, os.path.basename(filepath), start_time),
+ kwargs={'tag_id': first_tag.id if first_tag else None}
+ )
+ thread.start()
+ current_app.logger.info(f"Background processing thread started for recording ID: {recording.id}")
+
+ return jsonify(recording.to_dict(viewer_user=current_user)), 202
+
+ except RequestEntityTooLarge:
+ max_size_mb = current_app.config['MAX_CONTENT_LENGTH'] / (1024 * 1024)
+ current_app.logger.warning(f"Upload failed: File too large (>{max_size_mb}MB)")
+ return jsonify({
+ 'error': f'File too large. Maximum size is {max_size_mb:.0f} MB.',
+ 'max_size_mb': max_size_mb
+ }), 413
+ except Exception as e:
+ db.session.rollback()
+ current_app.logger.error(f"Error during file upload: {e}", exc_info=True)
+ return jsonify({'error': 'An unexpected error occurred during upload.'}), 500
+
+
+# Status Endpoint
+
+
+@recordings_bp.route('/recording/<int:recording_id>', methods=['DELETE'])
+@login_required
+def delete_recording(recording_id):
+ try:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ # Check if the recording belongs to the current user
+ if recording.user_id and recording.user_id != current_user.id:
+ return jsonify({'error': 'You do not have permission to delete this recording'}), 403
+
+ # Check deletion permissions (admin-only if USERS_CAN_DELETE is false)
+ if not USERS_CAN_DELETE and not current_user.is_admin:
+ return jsonify({'error': 'Only administrators can delete recordings'}), 403
+
+ # Delete the audio file first
+ try:
+ if recording.audio_path and os.path.exists(recording.audio_path):
+ os.remove(recording.audio_path)
+ current_app.logger.info(f"Deleted audio file: {recording.audio_path}")
+ except Exception as e:
+ current_app.logger.error(f"Error deleting audio file {recording.audio_path}: {e}")
+
+ # 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:
+ current_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()
+ current_app.logger.info(f"Deleted recording record ID: {recording_id}")
+
+ if ENABLE_INQUIRE_MODE and chunk_count > 0:
+ current_app.logger.info(f"Successfully deleted embeddings and chunks for recording {recording_id}")
+
+ # Mark the export file as deleted
+ mark_export_as_deleted(recording_id)
+
+ # Clean up orphaned speakers (run after successful deletion)
+ # This is a best-effort cleanup; failures are logged but don't affect the delete operation
+ try:
+ from src.services.speaker_cleanup import cleanup_orphaned_speakers
+ speaker_stats = cleanup_orphaned_speakers()
+ if speaker_stats.get('speakers_deleted', 0) > 0:
+ current_app.logger.info(
+ f"Cleaned up {speaker_stats['speakers_deleted']} orphaned speakers after recording deletion"
+ )
+ except Exception as cleanup_error:
+ # Log the error but don't fail the deletion
+ current_app.logger.warning(f"Speaker cleanup after recording deletion failed: {cleanup_error}")
+
+ return jsonify({'success': True})
+ except Exception as e:
+ db.session.rollback()
+ current_app.logger.error(f"Error deleting recording {recording_id}: {e}", exc_info=True)
+ return jsonify({'error': 'An unexpected error occurred while deleting.'}), 500
+
+
+# --- Inbox and Archive Endpoints ---
+
+@recordings_bp.route('/api/inbox_recordings', methods=['GET'])
+@login_required
+def get_inbox_recordings():
+ """Get recordings that are in the inbox and currently processing."""
+ from sqlalchemy import select
+ try:
+ stmt = select(Recording).where(
+ Recording.user_id == current_user.id,
+ Recording.is_inbox == True,
+ Recording.status.in_(['PENDING', 'PROCESSING', 'SUMMARIZING'])
+ ).order_by(Recording.created_at.desc())
+
+ recordings = db.session.execute(stmt).scalars().all()
+ return jsonify([recording.to_list_dict(viewer_user=current_user) for recording in recordings])
+ except Exception as e:
+ current_app.logger.error(f"Error fetching inbox recordings: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+@recordings_bp.route('/api/recordings/archived', methods=['GET'])
+@login_required
+def get_archived_recordings():
+ """Get recordings where audio has been deleted but transcription remains."""
+ from sqlalchemy import select
+ try:
+ search_query = request.args.get('q', '').strip()
+
+ # Find recordings owned by current user where audio_deleted_at is not null
+ stmt = select(Recording).where(
+ Recording.user_id == current_user.id,
+ Recording.audio_deleted_at.is_not(None)
+ ).order_by(Recording.audio_deleted_at.desc())
+
+ recordings = db.session.execute(stmt).scalars().all()
+ return jsonify([recording.to_list_dict(viewer_user=current_user) for recording in recordings])
+ except Exception as e:
+ current_app.logger.error(f"Error fetching archived recordings: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+# --- Recording Detail and Audio Endpoints ---
+
+@recordings_bp.route('/api/recordings/<int:recording_id>', methods=['GET'])
+@login_required
+def get_recording_detail(recording_id):
+ """Get full details for a specific recording including markdown HTML."""
+ try:
+ recording = db.session.get(Recording, recording_id)
+
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ # Check ownership or shared access
+ has_access = recording.user_id == current_user.id
+
+ # Check if recording has been shared with current user (if internal sharing is enabled)
+ if not has_access and ENABLE_INTERNAL_SHARING:
+ share = InternalShare.query.filter_by(
+ recording_id=recording_id,
+ shared_with_user_id=current_user.id
+ ).first()
+ has_access = share is not None
+
+ if not has_access:
+ return jsonify({'error': 'Access denied'}), 403
+
+ # Return full detail with HTML conversion
+ rec_dict = recording.to_dict(include_html=True, viewer_user=current_user)
+
+ # Add sharing metadata
+ is_owner = recording.user_id == current_user.id
+ rec_dict['is_owner'] = is_owner
+
+ # Add edit permission info (uses has_recording_access which checks group admin status)
+ rec_dict['can_edit'] = has_recording_access(recording, current_user, require_edit=True)
+
+ # Add delete permission info (only owner can delete)
+ rec_dict['can_delete'] = is_owner and (USERS_CAN_DELETE or current_user.is_admin)
+
+ # Add sharing-related fields
+ if not is_owner:
+ # This is a shared recording - get owner info and share permissions
+ owner = User.query.get(recording.user_id)
+ rec_dict['owner_username'] = owner.username if owner else "Unknown"
+ rec_dict['is_shared'] = True
+ # Don't show outgoing share count for recordings you don't own
+ rec_dict['shared_with_count'] = 0
+ rec_dict['public_share_count'] = 0
+
+ # Get share permissions
+ share = InternalShare.query.filter_by(
+ recording_id=recording.id,
+ shared_with_user_id=current_user.id
+ ).first()
+
+ if share:
+ rec_dict['share_info'] = {
+ 'share_id': share.id,
+ 'owner_username': owner.username if owner else "Unknown",
+ 'can_edit': share.can_edit,
+ 'can_reshare': share.can_reshare,
+ 'shared_at': share.created_at.isoformat()
+ }
+ else:
+ # Fallback if share record not found (shouldn't happen)
+ rec_dict['share_info'] = {
+ 'can_edit': False,
+ 'can_reshare': False
+ }
+ else:
+ rec_dict['is_shared'] = False
+
+ # Check if recording has group tags (among visible tags)
+ visible_tags = recording.get_visible_tags(current_user)
+ has_group_tags = any(tag.is_group_tag for tag in visible_tags) if visible_tags else False
+ rec_dict['has_group_tags'] = has_group_tags
+
+ # Enrich with per-user status
+ enrich_recording_dict_with_user_status(rec_dict, recording, current_user)
+
+ return jsonify(rec_dict)
+ except Exception as e:
+ current_app.logger.error(f"Error fetching recording detail: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+@recordings_bp.route('/recording/<int:recording_id>/status', methods=['GET'])
+@login_required
+def get_recording_status_only(recording_id):
+ """
+ Lightweight endpoint that returns only the status field.
+ Used for polling during processing/summarization.
+ """
+ try:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ if not has_recording_access(recording, current_user):
+ return jsonify({'error': 'You do not have permission to view this recording'}), 403
+
+ # Return only the status field
+ return jsonify({'status': recording.status})
+ except Exception as e:
+ current_app.logger.error(f"Error fetching status for recording {recording_id}: {e}", exc_info=True)
+ return jsonify({'error': 'An unexpected error occurred.'}), 500
+
+
+@recordings_bp.route('/status/<int:recording_id>', methods=['GET'])
+@login_required
+def get_status(recording_id):
+ """Endpoint to check the transcription/summarization status (full recording data)."""
+ try:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ if not has_recording_access(recording, current_user):
+ return jsonify({'error': 'You do not have permission to view this recording'}), 403
+
+ # Ensure events are loaded (refresh the recording to get latest relationships)
+ db.session.refresh(recording)
+
+ # Get recording dict and enrich with per-user status
+ recording_dict = recording.to_dict(viewer_user=current_user)
+ enrich_recording_dict_with_user_status(recording_dict, recording, current_user)
+
+ return jsonify(recording_dict)
+ except Exception as e:
+ current_app.logger.error(f"Error fetching status for recording {recording_id}: {e}", exc_info=True)
+ return jsonify({'error': 'An unexpected error occurred.'}), 500
+
+
+@recordings_bp.route('/audio/<int:recording_id>')
+@login_required
+def get_audio(recording_id):
+ """Serve audio file for a recording."""
+ try:
+ recording = db.session.get(Recording, recording_id)
+ if not recording or not recording.audio_path:
+ return jsonify({'error': 'Recording or audio file not found'}), 404
+
+ # Check if the recording belongs to the current user or has been shared with them
+ has_access = recording.user_id == current_user.id
+
+ # Check if recording has been shared with current user (if internal sharing is enabled)
+ if not has_access and ENABLE_INTERNAL_SHARING:
+ share = InternalShare.query.filter_by(
+ recording_id=recording_id,
+ shared_with_user_id=current_user.id
+ ).first()
+ has_access = share is not None
+
+ if not has_access:
+ return jsonify({'error': 'You do not have permission to access this audio file'}), 403
+ if not os.path.exists(recording.audio_path):
+ current_app.logger.error(f"Audio file missing from server: {recording.audio_path}")
+ return jsonify({'error': 'Audio file missing from server'}), 404
+ return send_file(recording.audio_path)
+ except Exception as e:
+ current_app.logger.error(f"Error serving audio for recording {recording_id}: {e}", exc_info=True)
+ return jsonify({'error': 'An unexpected error occurred.'}), 500
+
+
+# --- Chat with Transcription ---
+
+@recordings_bp.route('/chat', methods=['POST'])
+@login_required
+def chat_with_transcription():
+ """Chat with a specific recording's transcription."""
+ try:
+ data = request.json
+ if not data:
+ return jsonify({'error': 'No data provided'}), 400
+
+ recording_id = data.get('recording_id')
+ user_message = data.get('message')
+ message_history = data.get('message_history', [])
+
+ if not recording_id:
+ return jsonify({'error': 'No recording ID provided'}), 400
+ if not user_message:
+ return jsonify({'error': 'No message provided'}), 400
+
+ # Get the recording
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ if not has_recording_access(recording, current_user):
+ return jsonify({'error': 'You do not have permission to chat with this recording'}), 403
+
+ # Check if OpenRouter client is available
+ if client is None:
+ return jsonify({'error': 'Chat service is not available (OpenRouter client not configured)'}), 503
+
+ # Prepare the system prompt with the transcription
+ user_chat_output_language = current_user.output_language if current_user.is_authenticated else None
+
+ language_instruction = ""
+ if user_chat_output_language:
+ language_instruction = f"Please provide all your responses in {user_chat_output_language}."
+
+ user_name = current_user.name if current_user.is_authenticated and current_user.name else "User"
+ user_title = current_user.job_title if current_user.is_authenticated and current_user.job_title else "a professional"
+ user_company = current_user.company if current_user.is_authenticated and current_user.company else "their organization"
+
+ formatted_transcription = format_transcription_for_llm(recording.transcription)
+
+ # Get configurable transcript length limit for chat
+ transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)
+ if transcript_limit == -1:
+ # No limit
+ chat_transcript = formatted_transcription
+ else:
+ chat_transcript = formatted_transcription[:transcript_limit]
+
+ 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} Analyze the following meeting information and respond to the specific request.
+
+Following are the meeting participants and their roles:
+{recording.participants or "No specific participants information provided."}
+
+Following is the meeting transcript:
+<<start transcript>>
+{chat_transcript or "No transcript available."}
+<<end transcript>>
+
+Additional context and notes about the meeting:
+{recording.notes or "none"}
+"""
+
+ # Prepare messages array with system prompt and conversation history
+ messages = [{"role": "system", "content": system_prompt}]
+ if message_history:
+ messages.extend(message_history)
+ messages.append({"role": "user", "content": user_message})
+
+ def generate():
+ try:
+ # Enable streaming
+ stream = call_llm_completion(
+ messages=messages,
+ temperature=0.7,
+ max_tokens=int(os.environ.get("CHAT_MAX_TOKENS", "2000")),
+ stream=True
+ )
+
+ # Use helper function to process streaming with thinking tag support
+ for response in process_streaming_with_thinking(stream):
+ yield response
+
+ except Exception as e:
+ current_app.logger.error(f"Error during chat stream generation: {str(e)}")
+ # Yield an error message in SSE format
+ yield f"data: {json.dumps({'error': str(e)})}\n\n"
+
+ return Response(generate(), mimetype='text/event-stream')
+
+ except Exception as e:
+ current_app.logger.error(f"Error in chat endpoint: {str(e)}")
+ return jsonify({'error': str(e)}), 500
+
+
+# --- Tag Management for Recordings ---
+
+@recordings_bp.route('/api/recordings/<int:recording_id>/tags', methods=['POST'])
+@login_required
+def add_tag_to_recording(recording_id):
+ """Add a tag to a recording. Triggers auto-share for group tags."""
+ try:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ # Check if user has view access to this recording
+ # (Edit permission will be checked for group tags specifically)
+ if not has_recording_access(recording, current_user, require_edit=False):
+ return jsonify({'error': 'You do not have permission to access this recording'}), 403
+
+ data = request.get_json()
+ tag_id = data.get('tag_id')
+
+ if not tag_id:
+ return jsonify({'error': 'Tag ID is required'}), 400
+
+ tag = db.session.get(Tag, tag_id)
+ if not tag:
+ return jsonify({'error': 'Tag not found'}), 404
+
+ # Check if user has access to this tag and permission to apply it
+ if tag.group_id:
+ # Group tag - check membership first
+ membership = GroupMembership.query.filter_by(
+ group_id=tag.group_id,
+ user_id=current_user.id
+ ).first()
+ if not membership:
+ return jsonify({'error': 'You do not have access to this tag'}), 403
+
+ # Only file owner or group admin can apply group tags
+ if recording.user_id != current_user.id and membership.role != 'admin':
+ return jsonify({'error': 'Only recording owner or group admin can apply group tags'}), 403
+
+ # Group tags require edit permission
+ if not has_recording_access(recording, current_user, require_edit=True):
+ return jsonify({'error': 'You do not have permission to apply group tags to this recording'}), 403
+ else:
+ # Personal tag - only the tag owner can use it (view access is sufficient)
+ if tag.user_id != current_user.id:
+ return jsonify({'error': 'You can only apply your own personal tags'}), 403
+
+ # Check if tag is already on the recording
+ existing = RecordingTag.query.filter_by(
+ recording_id=recording_id,
+ tag_id=tag_id
+ ).first()
+
+ if existing:
+ return jsonify({'error': 'Tag is already on this recording'}), 400
+
+ # Get the next order position
+ max_order = db.session.query(db.func.max(RecordingTag.order)).filter_by(
+ recording_id=recording_id
+ ).scalar() or 0
+
+ # Add the tag
+ recording_tag = RecordingTag(
+ recording_id=recording_id,
+ tag_id=tag_id,
+ order=max_order + 1
+ )
+ db.session.add(recording_tag)
+
+ # If this is a group tag with sharing enabled, automatically share the recording
+ # Only auto-share if recording is completed (not during processing)
+ if tag.group_id and ENABLE_INTERNAL_SHARING and recording.status == 'COMPLETED' and (tag.auto_share_on_apply or tag.share_with_group_lead):
+ # Determine who to share with
+ if tag.auto_share_on_apply:
+ group_members = GroupMembership.query.filter_by(group_id=tag.group_id).all()
+ elif tag.share_with_group_lead:
+ group_members = GroupMembership.query.filter_by(group_id=tag.group_id, role='admin').all()
+ else:
+ group_members = []
+
+ shares_created = 0
+ for membership_to_share in group_members:
+ # Skip the recording owner
+ if membership_to_share.user_id == recording.user_id:
+ continue
+
+ # Check if already shared
+ existing_share = InternalShare.query.filter_by(
+ recording_id=recording_id,
+ shared_with_user_id=membership_to_share.user_id
+ ).first()
+
+ if not existing_share:
+ # Create internal share with correct permissions
+ # Group admins get edit permission, regular members get read-only
+ share = InternalShare(
+ recording_id=recording_id,
+ owner_id=recording.user_id,
+ shared_with_user_id=membership_to_share.user_id,
+ can_edit=(membership_to_share.role == 'admin'),
+ can_reshare=False,
+ source_type='group_tag',
+ source_tag_id=tag.id
+ )
+ db.session.add(share)
+
+ # Check if SharedRecordingState already exists (might exist from previous share)
+ existing_state = SharedRecordingState.query.filter_by(
+ recording_id=recording_id,
+ user_id=membership_to_share.user_id
+ ).first()
+
+ if not existing_state:
+ # Create SharedRecordingState with default values for the recipient
+ state = SharedRecordingState(
+ recording_id=recording_id,
+ user_id=membership_to_share.user_id,
+ is_inbox=True, # New shares appear in inbox by default
+ is_highlighted=False # Not favorited by default
+ )
+ db.session.add(state)
+
+ shares_created += 1
+ current_app.logger.info(f"Auto-shared recording {recording_id} with user {membership_to_share.user_id} (role={membership_to_share.role}) via group tag '{tag.name}'")
+
+ if shares_created > 0:
+ current_app.logger.info(f"Created {shares_created} auto-shares for recording {recording_id} via group tag '{tag.name}'")
+
+ db.session.commit()
+
+ # Return updated recording with per-user status
+ recording_dict = recording.to_dict(viewer_user=current_user)
+ enrich_recording_dict_with_user_status(recording_dict, recording, current_user)
+ return jsonify({
+ 'success': True,
+ 'recording': recording_dict,
+ 'tag': tag.to_dict()
+ })
+
+ except Exception as e:
+ db.session.rollback()
+ current_app.logger.error(f"Error adding tag to recording {recording_id}: {e}", exc_info=True)
+ return jsonify({'error': 'An unexpected error occurred.'}), 500
+
+
+@recordings_bp.route('/api/recordings/<int:recording_id>/tags/<int:tag_id>', methods=['DELETE'])
+@login_required
+def remove_tag_from_recording(recording_id, tag_id):
+ """Remove a tag from a recording. Cleans up auto-shares for group tags."""
+ try:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ # Check if user has view access to this recording
+ # (Edit permission will be checked for group tags specifically)
+ if not has_recording_access(recording, current_user, require_edit=False):
+ return jsonify({'error': 'You do not have permission to access this recording'}), 403
+
+ # Find the recording-tag association
+ recording_tag = RecordingTag.query.filter_by(
+ recording_id=recording_id,
+ tag_id=tag_id
+ ).first()
+
+ if not recording_tag:
+ return jsonify({'error': 'Tag is not on this recording'}), 404
+
+ # Get the tag to check permissions and for cleanup
+ tag = db.session.get(Tag, tag_id)
+ if tag:
+ # Check permissions to remove this specific tag
+ if tag.group_id:
+ # Group tag - only file owner or group admin can remove
+ membership = GroupMembership.query.filter_by(
+ group_id=tag.group_id,
+ user_id=current_user.id
+ ).first()
+ if recording.user_id != current_user.id:
+ if not membership or membership.role != 'admin':
+ return jsonify({'error': 'Only recording owner or group admin can remove group tags'}), 403
+
+ # Group tags require edit permission
+ if not has_recording_access(recording, current_user, require_edit=True):
+ return jsonify({'error': 'You do not have permission to remove group tags from this recording'}), 403
+ else:
+ # Personal tag - can be removed by tag owner (view access) or recording owner (edit access)
+ if tag.user_id != current_user.id:
+ # Not the tag owner, must be recording owner with edit permission
+ if not has_recording_access(recording, current_user, require_edit=True):
+ return jsonify({'error': 'You can only remove your own personal tags'}), 403
+
+ # Remove the association
+ db.session.delete(recording_tag)
+
+ # Clean up shares created by this group tag
+ if tag and tag.group_id and ENABLE_INTERNAL_SHARING:
+ shares_to_check = InternalShare.query.filter_by(
+ recording_id=recording_id,
+ source_tag_id=tag_id
+ ).all()
+
+ shares_removed = 0
+ for share in shares_to_check:
+ # Check if user still has access via another group tag on this recording
+ other_team_tag_access = db.session.query(Tag).join(
+ RecordingTag, RecordingTag.tag_id == Tag.id
+ ).join(
+ GroupMembership, GroupMembership.group_id == Tag.group_id
+ ).filter(
+ RecordingTag.recording_id == recording_id,
+ GroupMembership.user_id == share.shared_with_user_id,
+ Tag.id != tag_id, # Exclude the tag being removed
+ Tag.group_id.isnot(None),
+ db.or_(Tag.auto_share_on_apply == True, Tag.share_with_group_lead == True)
+ ).first()
+
+ # Only remove share if user has no other group tag access
+ if not other_team_tag_access:
+ db.session.delete(share)
+ shares_removed += 1
+ current_app.logger.info(f"Removed auto-share for user {share.shared_with_user_id} from recording {recording_id} (group tag '{tag.name}' removed)")
+
+ if shares_removed > 0:
+ current_app.logger.info(f"Cleaned up {shares_removed} auto-shares for recording {recording_id} after removing group tag '{tag.name}'")
+
+ db.session.commit()
+
+ # Return updated recording with per-user status
+ recording_dict = recording.to_dict(viewer_user=current_user)
+ enrich_recording_dict_with_user_status(recording_dict, recording, current_user)
+ return jsonify({
+ 'success': True,
+ 'recording': recording_dict
+ })
+
+ except Exception as e:
+ db.session.rollback()
+ current_app.logger.error(f"Error removing tag from recording {recording_id}: {e}", exc_info=True)
+ return jsonify({'error': 'An unexpected error occurred.'}), 500
+
+
+# --- Auto-deletion and Chunks Processing ---
+
+@recordings_bp.route('/api/recordings/<int:recording_id>/toggle_deletion_exempt', methods=['POST'])
+@login_required
+def toggle_deletion_exempt(recording_id):
+ """Toggle the deletion_exempt flag for a recording."""
+ try:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ # Check ownership
+ if recording.user_id != current_user.id and not current_user.is_admin:
+ return jsonify({'error': 'Permission denied'}), 403
+
+ # Toggle the flag
+ recording.deletion_exempt = not recording.deletion_exempt
+ db.session.commit()
+
+ return jsonify({
+ 'success': True,
+ 'deletion_exempt': recording.deletion_exempt
+ })
+ except Exception as e:
+ db.session.rollback()
+ current_app.logger.error(f"Error toggling deletion exempt for recording {recording_id}: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+@recordings_bp.route('/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:
+ current_app.logger.error(f"Error in process chunks endpoint: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+# --- Inquire Mode API Endpoints ---
+
+
+
diff --git a/src/api/shares.py b/src/api/shares.py
new file mode 100644
index 00000000..96b30c07
--- /dev/null
+++ b/src/api/shares.py
@@ -0,0 +1,534 @@
+"""
+Sharing routes for public and internal recording shares.
+
+This blueprint handles:
+- Public sharing (shareable links)
+- Internal sharing (user-to-user sharing)
+- Share management (CRUD operations)
+"""
+
+import os
+import re
+from flask import Blueprint, render_template, request, redirect, url_for, jsonify, send_file, current_app
+from flask_login import login_required, current_user
+
+from src.database import db
+from src.models import Recording, Share, InternalShare, SharedRecordingState, User, TranscriptChunk, ShareAuditLog
+from src.utils import md_to_html
+
+# Configuration from environment
+ENABLE_PUBLIC_SHARING = os.environ.get('ENABLE_PUBLIC_SHARING', 'true').lower() == 'true'
+ENABLE_INTERNAL_SHARING = os.environ.get('ENABLE_INTERNAL_SHARING', 'false').lower() == 'true'
+SHOW_USERNAMES_IN_UI = os.environ.get('SHOW_USERNAMES_IN_UI', 'false').lower() == 'true'
+ENABLE_INQUIRE_MODE = os.environ.get('ENABLE_INQUIRE_MODE', 'false').lower() == 'true'
+
+# Create blueprint
+shares_bp = Blueprint('shares', __name__)
+
+# Import has_recording_access from app context
+has_recording_access = None
+
+def init_shares_helpers(_has_recording_access):
+ """Initialize helper functions from app."""
+ global has_recording_access
+ has_recording_access = _has_recording_access
+
+
+# --- Public Sharing Routes ---
+
+@shares_bp.route('/share/<string:public_id>', methods=['GET'])
+def view_shared_recording(public_id):
+ """View a publicly shared recording."""
+ share = Share.query.filter_by(public_id=public_id).first_or_404()
+ recording = share.recording
+
+ # Create a limited dictionary for the public view
+ recording_data = {
+ 'id': recording.id,
+ 'public_id': share.public_id,
+ 'title': recording.title,
+ 'participants': recording.participants,
+ 'transcription': recording.transcription,
+ 'summary': md_to_html(recording.summary) if share.share_summary else None,
+ 'summary_raw': recording.summary if share.share_summary else None,
+ 'notes': md_to_html(recording.notes) if share.share_notes else None,
+ 'notes_raw': recording.notes if share.share_notes else None,
+ 'meeting_date': f"{recording.meeting_date.isoformat()}T00:00:00" if recording.meeting_date else None,
+ 'mime_type': recording.mime_type,
+ 'audio_deleted_at': recording.audio_deleted_at.isoformat() if recording.audio_deleted_at else None
+ }
+
+ return render_template('share.html', recording=recording_data)
+
+
+@shares_bp.route('/share/audio/<string:public_id>')
+def get_shared_audio(public_id):
+ """Serve audio file for a publicly shared recording."""
+ try:
+ share = Share.query.filter_by(public_id=public_id).first_or_404()
+ recording = share.recording
+ if not recording or not recording.audio_path:
+ return jsonify({'error': 'Recording or audio file not found'}), 404
+ if not os.path.exists(recording.audio_path):
+ current_app.logger.error(f"Audio file missing from server: {recording.audio_path}")
+ return jsonify({'error': 'Audio file missing from server'}), 404
+ return send_file(recording.audio_path)
+ except Exception as e:
+ current_app.logger.error(f"Error serving shared audio for public_id {public_id}: {e}", exc_info=True)
+ return jsonify({'error': 'An unexpected error occurred.'}), 500
+
+
+@shares_bp.route('/api/recording/<int:recording_id>/share', methods=['GET'])
+@login_required
+def get_existing_share(recording_id):
+ """Check if a share already exists for this recording."""
+ recording = db.session.get(Recording, recording_id)
+ if not recording or recording.user_id != current_user.id:
+ return jsonify({'error': 'Recording not found or you do not have permission to view it.'}), 404
+
+ existing_share = Share.query.filter_by(
+ recording_id=recording.id,
+ user_id=current_user.id
+ ).order_by(Share.created_at.desc()).first()
+
+ if existing_share:
+ share_url = url_for('shares.view_shared_recording', public_id=existing_share.public_id, _external=True)
+ return jsonify({
+ 'success': True,
+ 'exists': True,
+ 'share_url': share_url,
+ 'share': existing_share.to_dict()
+ }), 200
+ else:
+ return jsonify({
+ 'success': True,
+ 'exists': False
+ }), 200
+
+
+@shares_bp.route('/api/recording/<int:recording_id>/share', methods=['POST'])
+@login_required
+def create_share(recording_id):
+ """Create a public share link for a recording."""
+ # Check if public sharing is globally enabled
+ if not ENABLE_PUBLIC_SHARING:
+ return jsonify({'error': 'Public sharing is not enabled on this server'}), 403
+
+ # Check if user has permission to create public shares
+ if not current_user.can_share_publicly:
+ return jsonify({'error': 'You do not have permission to create public share links. Contact your administrator.'}), 403
+
+ if not request.is_secure:
+ return jsonify({'error': 'Sharing is only available over a secure (HTTPS) connection.'}), 403
+
+ recording = db.session.get(Recording, recording_id)
+ if not recording or recording.user_id != current_user.id:
+ return jsonify({'error': 'Recording not found or you do not have permission to share it.'}), 404
+
+ data = request.json
+ share_summary = data.get('share_summary', True)
+ share_notes = data.get('share_notes', True)
+ force_new = data.get('force_new', False)
+
+ # Check if ANY share already exists for this recording by this user
+ existing_share = Share.query.filter_by(
+ recording_id=recording.id,
+ user_id=current_user.id
+ ).order_by(Share.created_at.desc()).first()
+
+ if existing_share and not force_new:
+ # Update the share permissions if they've changed
+ if existing_share.share_summary != share_summary or existing_share.share_notes != share_notes:
+ existing_share.share_summary = share_summary
+ existing_share.share_notes = share_notes
+ db.session.commit()
+
+ # Return existing share info
+ share_url = url_for('shares.view_shared_recording', public_id=existing_share.public_id, _external=True)
+ return jsonify({
+ 'success': True,
+ 'share_url': share_url,
+ 'share': existing_share.to_dict(),
+ 'existing': True,
+ 'message': 'Using existing share link for this recording'
+ }), 200
+
+ # Create new share
+ share = Share(
+ recording_id=recording.id,
+ user_id=current_user.id,
+ share_summary=share_summary,
+ share_notes=share_notes
+ )
+ db.session.add(share)
+ db.session.commit()
+
+ share_url = url_for('shares.view_shared_recording', public_id=share.public_id, _external=True)
+
+ return jsonify({
+ 'success': True,
+ 'share_url': share_url,
+ 'share': share.to_dict(),
+ 'existing': False
+ }), 201
+
+
+@shares_bp.route('/api/shares', methods=['GET'])
+@login_required
+def get_shares():
+ """Get all public shares for the current user."""
+ shares = Share.query.filter_by(user_id=current_user.id).order_by(Share.created_at.desc()).all()
+ return jsonify([share.to_dict() for share in shares])
+
+
+@shares_bp.route('/api/share/<int:share_id>', methods=['PUT'])
+@login_required
+def update_share(share_id):
+ """Update a public share's settings."""
+ share = Share.query.filter_by(id=share_id, user_id=current_user.id).first_or_404()
+ data = request.json
+
+ if 'share_summary' in data:
+ share.share_summary = data['share_summary']
+ if 'share_notes' in data:
+ share.share_notes = data['share_notes']
+
+ db.session.commit()
+ return jsonify({'success': True, 'share': share.to_dict()})
+
+
+@shares_bp.route('/api/share/<int:share_id>', methods=['DELETE'])
+@login_required
+def delete_share(share_id):
+ """Delete a public share."""
+ share = Share.query.filter_by(id=share_id, user_id=current_user.id).first_or_404()
+ db.session.delete(share)
+ db.session.commit()
+ return jsonify({'success': True})
+
+
+# --- Internal Sharing Routes ---
+
+@shares_bp.route('/api/users/search', methods=['GET'])
+@login_required
+def search_users():
+ """Search for users by username (for internal sharing)."""
+ if not ENABLE_INTERNAL_SHARING:
+ return jsonify({'error': 'Internal sharing is not enabled'}), 403
+
+ query = request.args.get('q', '').strip()
+
+ # If SHOW_USERNAMES_IN_UI is enabled and no query, return all users for quick selection
+ if SHOW_USERNAMES_IN_UI and len(query) < 2:
+ users = User.query.filter(User.id != current_user.id).order_by(User.username).all()
+ elif len(query) < 2:
+ # If usernames are hidden and no query, return empty
+ return jsonify([])
+ else:
+ if SHOW_USERNAMES_IN_UI:
+ # If usernames are shown, allow partial match (autocomplete)
+ users = User.query.filter(
+ User.id != current_user.id,
+ User.username.ilike(f'%{query}%')
+ ).limit(10).all()
+ else:
+ # If usernames are hidden (privacy mode), require exact match only
+ users = User.query.filter(
+ User.id != current_user.id,
+ User.username == query
+ ).all()
+
+ return jsonify([{
+ 'id': user.id,
+ 'username': user.username,
+ 'email': user.email if SHOW_USERNAMES_IN_UI else None
+ } for user in users])
+
+
+@shares_bp.route('/api/recordings/<int:recording_id>/share-internal', methods=['POST'])
+@login_required
+def share_recording_internal(recording_id):
+ """Share a recording with another user internally."""
+ if not ENABLE_INTERNAL_SHARING:
+ return jsonify({'error': 'Internal sharing is not enabled'}), 403
+
+ try:
+ data = request.json
+ shared_with_user_id = data.get('user_id')
+ can_edit = data.get('can_edit', False)
+ can_reshare = data.get('can_reshare', False)
+
+ if not shared_with_user_id:
+ return jsonify({'error': 'User ID is required'}), 400
+
+ # Check recording exists and user has permission to share it
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ if not has_recording_access(recording, current_user, require_reshare=True):
+ return jsonify({'error': 'You do not have permission to share this recording'}), 403
+
+ # Check target user exists
+ target_user = db.session.get(User, shared_with_user_id)
+ if not target_user:
+ return jsonify({'error': 'Target user not found'}), 404
+
+ # Prevent sharing back to owner (circular share)
+ if shared_with_user_id == recording.user_id:
+ return jsonify({'error': 'Cannot share a recording with its owner'}), 400
+
+ # Prevent sharing with self
+ if shared_with_user_id == current_user.id:
+ return jsonify({'error': 'Cannot share a recording with yourself'}), 400
+
+ # Check if already shared
+ existing_share = InternalShare.query.filter_by(
+ recording_id=recording_id,
+ shared_with_user_id=shared_with_user_id
+ ).first()
+
+ if existing_share:
+ return jsonify({'error': 'Recording already shared with this user'}), 409
+
+ # PERMISSION VALIDATION: Validate that current user can grant the requested permissions
+ requested_permissions = {'can_edit': can_edit, 'can_reshare': can_reshare}
+ is_valid, error_message = InternalShare.validate_reshare_permissions(
+ recording, current_user, requested_permissions
+ )
+
+ if not is_valid:
+ return jsonify({'error': error_message}), 403
+
+ # Get current user's permissions for audit log
+ actor_permissions = InternalShare.get_user_max_permissions(recording, current_user)
+
+ # Create share
+ share = InternalShare(
+ recording_id=recording_id,
+ owner_id=current_user.id,
+ shared_with_user_id=shared_with_user_id,
+ can_edit=can_edit,
+ can_reshare=can_reshare
+ )
+ db.session.add(share)
+
+ # Create or update SharedRecordingState for the recipient
+ state = SharedRecordingState.query.filter_by(
+ recording_id=recording_id,
+ user_id=shared_with_user_id
+ ).first()
+
+ if not state:
+ # Create new state if it doesn't exist
+ state = SharedRecordingState(
+ recording_id=recording_id,
+ user_id=shared_with_user_id,
+ is_inbox=True, # New shares appear in inbox by default
+ is_highlighted=False # Not favorited by default
+ )
+ db.session.add(state)
+ else:
+ # Reset to inbox if it already exists (e.g., from previous share that was deleted)
+ state.is_inbox = True
+
+ db.session.commit()
+
+ # AUDIT LOGGING: Log the share creation
+ try:
+ ShareAuditLog.log_share_created(
+ recording_id=recording_id,
+ actor_id=current_user.id,
+ target_user_id=shared_with_user_id,
+ permissions={'can_edit': can_edit, 'can_reshare': can_reshare},
+ actor_permissions=actor_permissions,
+ notes=f"Shared by {'owner' if recording.user_id == current_user.id else 'delegated user'}",
+ ip_address=request.remote_addr
+ )
+ db.session.commit()
+ except Exception as audit_error:
+ # Don't fail the share if audit logging fails
+ current_app.logger.error(f"Failed to log share creation: {audit_error}")
+
+ return jsonify({
+ 'success': True,
+ 'share': share.to_dict()
+ }), 201
+
+ except Exception as e:
+ db.session.rollback()
+ current_app.logger.error(f"Error sharing recording internally: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+@shares_bp.route('/api/recordings/<int:recording_id>/shares-internal', methods=['GET'])
+@login_required
+def get_internal_shares(recording_id):
+ """Get list of users a recording is shared with, including owner."""
+ if not ENABLE_INTERNAL_SHARING:
+ return jsonify({'error': 'Internal sharing is not enabled'}), 403
+
+ # Check recording exists and user has permission to view shares
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ if not has_recording_access(recording, current_user, require_reshare=True):
+ return jsonify({'error': 'You do not have permission to view shares for this recording'}), 403
+
+ # Get all internal shares
+ shares = InternalShare.query.filter_by(recording_id=recording_id).all()
+ shares_list = [share.to_dict() for share in shares]
+
+ # Add owner as first entry (owner always has full permissions)
+ owner = db.session.get(User, recording.user_id)
+ if owner:
+ owner_entry = {
+ 'id': None, # No share ID for owner
+ 'recording_id': recording_id,
+ 'owner_id': owner.id,
+ 'owner_username': owner.username,
+ 'user_id': owner.id,
+ 'username': owner.username,
+ 'can_edit': True,
+ 'can_reshare': True,
+ 'is_owner': True, # Mark as owner
+ 'source_type': 'owner',
+ 'source_tag_id': None,
+ 'created_at': recording.created_at.isoformat() if recording.created_at else None
+ }
+ # Insert owner at the beginning
+ shares_list.insert(0, owner_entry)
+
+ return jsonify({'shares': shares_list})
+
+
+@shares_bp.route('/api/internal-shares/<int:share_id>', methods=['DELETE'])
+@login_required
+def revoke_internal_share(share_id):
+ """Revoke an internal share with cascade revocation."""
+ if not ENABLE_INTERNAL_SHARING:
+ return jsonify({'error': 'Internal sharing is not enabled'}), 403
+
+ share = db.session.get(InternalShare, share_id)
+ if not share:
+ return jsonify({'error': 'Share not found'}), 404
+
+ # Only owner can revoke
+ if share.owner_id != current_user.id:
+ return jsonify({'error': 'You do not have permission to revoke this share'}), 403
+
+ recording_id = share.recording_id
+ revoked_user_id = share.shared_with_user_id
+ revoked_count = 0
+
+ try:
+ # CASCADE REVOCATION: Find downstream shares created by the user losing access
+ downstream_shares = InternalShare.find_downstream_shares(recording_id, revoked_user_id)
+
+ # Recursively revoke downstream shares that don't have alternate paths
+ for downstream in downstream_shares:
+ # Check for alternate access paths (diamond pattern protection)
+ has_alternate = InternalShare.has_alternate_access_path(
+ recording_id,
+ downstream.shared_with_user_id,
+ excluding_grantor_id=revoked_user_id
+ )
+
+ if not has_alternate:
+ # No alternate path - cascade revoke
+ # Audit log cascade revocation
+ try:
+ ShareAuditLog.log_share_revoked(
+ share_id=downstream.id,
+ recording_id=recording_id,
+ actor_id=current_user.id,
+ target_user_id=downstream.shared_with_user_id,
+ was_cascade=True,
+ notes=f"Cascaded from revoking user {revoked_user_id}",
+ ip_address=request.remote_addr
+ )
+ except Exception as audit_error:
+ current_app.logger.error(f"Failed to log cascade revocation: {audit_error}")
+
+ db.session.delete(downstream)
+ revoked_count += 1
+
+ # Audit log the primary revocation
+ try:
+ ShareAuditLog.log_share_revoked(
+ share_id=share.id,
+ recording_id=recording_id,
+ actor_id=current_user.id,
+ target_user_id=revoked_user_id,
+ was_cascade=False,
+ notes=f"Revoked by user {current_user.id}, cascaded to {revoked_count} downstream shares",
+ ip_address=request.remote_addr
+ )
+ except Exception as audit_error:
+ current_app.logger.error(f"Failed to log revocation: {audit_error}")
+
+ # Delete the primary share
+ db.session.delete(share)
+ db.session.commit()
+
+ return jsonify({
+ 'success': True,
+ 'revoked_count': revoked_count + 1, # Include primary share
+ 'cascaded': revoked_count
+ })
+
+ except Exception as e:
+ db.session.rollback()
+ current_app.logger.error(f"Error revoking internal share: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+@shares_bp.route('/api/recordings/shared-with-me', methods=['GET'])
+@login_required
+def get_shared_with_me():
+ """Get recordings that have been shared with the current user."""
+ if not ENABLE_INTERNAL_SHARING:
+ return jsonify({'error': 'Internal sharing is not enabled'}), 403
+
+ try:
+ # Get shares where current user is the recipient
+ shares = InternalShare.query.filter_by(shared_with_user_id=current_user.id).all()
+
+ result = []
+ for share in shares:
+ recording = share.recording
+ if recording and recording.status == 'COMPLETED':
+ rec_data = recording.to_list_dict(viewer_user=current_user)
+ # Mark as shared recording with owner info
+ rec_data['is_shared'] = True
+ rec_data['owner_username'] = share.owner.username if SHOW_USERNAMES_IN_UI else None
+ # Don't show outgoing share counts for recordings you don't own
+ rec_data['shared_with_count'] = 0
+ rec_data['public_share_count'] = 0
+ # Check if recording has group tags (among visible tags)
+ visible_tags = recording.get_visible_tags(current_user)
+ rec_data['has_group_tags'] = any(tag.is_group_tag for tag in visible_tags) if visible_tags else False
+ rec_data['share_info'] = {
+ 'share_id': share.id,
+ 'owner_username': share.owner.username if SHOW_USERNAMES_IN_UI else None,
+ 'can_edit': share.can_edit,
+ 'can_reshare': share.can_reshare,
+ 'shared_at': share.created_at.isoformat()
+ }
+ result.append(rec_data)
+
+ return jsonify(result)
+
+ except Exception as e:
+ current_app.logger.error(f"Error fetching shared recordings: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+@shares_bp.route('/api/permissions/can-share-publicly', methods=['GET'])
+@login_required
+def can_share_publicly():
+ """Check if the current user has permission to create public shares."""
+ return jsonify({
+ 'can_share_publicly': current_user.can_share_publicly and ENABLE_PUBLIC_SHARING
+ })
diff --git a/src/api/speakers.py b/src/api/speakers.py
new file mode 100644
index 00000000..9a8c4124
--- /dev/null
+++ b/src/api/speakers.py
@@ -0,0 +1,558 @@
+"""
+Speaker identification and management.
+
+This blueprint was auto-generated from app.py route extraction.
+"""
+
+import os
+import json
+import time
+from datetime import datetime, timedelta
+from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, send_file, Response, current_app
+from flask_login import login_required, current_user
+from werkzeug.utils import secure_filename
+
+from src.database import db
+from src.models import *
+from src.utils import *
+from src.services.speaker_embedding_matcher import find_matching_speakers
+from src.services.speaker_snippets import get_speaker_snippets, get_speaker_recordings_with_snippets
+from src.services.speaker_merge import merge_speakers, preview_merge, can_merge_speakers
+
+# Create blueprint
+speakers_bp = Blueprint('speakers', __name__)
+
+# Configuration from environment
+ENABLE_INQUIRE_MODE = os.environ.get('ENABLE_INQUIRE_MODE', 'false').lower() == 'true'
+ENABLE_AUTO_DELETION = os.environ.get('ENABLE_AUTO_DELETION', 'false').lower() == 'true'
+USERS_CAN_DELETE = os.environ.get('USERS_CAN_DELETE', 'true').lower() == 'true'
+ENABLE_INTERNAL_SHARING = os.environ.get('ENABLE_INTERNAL_SHARING', 'false').lower() == 'true'
+USE_ASR_ENDPOINT = os.environ.get('USE_ASR_ENDPOINT', 'false').lower() == 'true'
+
+# Global helpers (will be injected from app)
+has_recording_access = None
+bcrypt = None
+csrf = None
+limiter = None
+
+def init_speakers_helpers(**kwargs):
+ """Initialize helper functions and extensions from app."""
+ global has_recording_access, bcrypt, csrf, limiter
+ has_recording_access = kwargs.get('has_recording_access')
+ bcrypt = kwargs.get('bcrypt')
+ csrf = kwargs.get('csrf')
+ limiter = kwargs.get('limiter')
+
+
+# --- Routes ---
+
+@speakers_bp.route('/speakers', methods=['GET'])
+@login_required
+def get_speakers():
+ """Get all speakers for the current user, ordered by usage frequency and recency."""
+ try:
+ speakers = Speaker.query.filter_by(user_id=current_user.id)\
+ .order_by(Speaker.use_count.desc(), Speaker.last_used.desc())\
+ .all()
+ return jsonify([speaker.to_dict() for speaker in speakers])
+ except Exception as e:
+ current_app.logger.error(f"Error fetching speakers: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+
+@speakers_bp.route('/speakers/search', methods=['GET'])
+@login_required
+def search_speakers():
+ """Search speakers by name for autocomplete functionality."""
+ try:
+ query = request.args.get('q', '').strip()
+ if not query:
+ return jsonify([])
+
+ speakers = Speaker.query.filter_by(user_id=current_user.id)\
+ .filter(Speaker.name.ilike(f'%{query}%'))\
+ .order_by(Speaker.use_count.desc(), Speaker.last_used.desc())\
+ .limit(10)\
+ .all()
+
+ return jsonify([speaker.to_dict() for speaker in speakers])
+ except Exception as e:
+ current_app.logger.error(f"Error searching speakers: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+
+@speakers_bp.route('/speakers', methods=['POST'])
+@login_required
+def create_speaker():
+ """Create a new speaker or update existing one."""
+ try:
+ data = request.json
+ name = data.get('name', '').strip()
+
+ if not name:
+ return jsonify({'error': 'Speaker name is required'}), 400
+
+ # Check if speaker already exists for this user
+ existing_speaker = Speaker.query.filter_by(user_id=current_user.id, name=name).first()
+
+ if existing_speaker:
+ # Update usage statistics
+ existing_speaker.use_count += 1
+ existing_speaker.last_used = datetime.utcnow()
+ db.session.commit()
+ return jsonify(existing_speaker.to_dict())
+ else:
+ # Create new speaker
+ speaker = Speaker(
+ name=name,
+ user_id=current_user.id,
+ use_count=1,
+ created_at=datetime.utcnow(),
+ last_used=datetime.utcnow()
+ )
+ db.session.add(speaker)
+ db.session.commit()
+ return jsonify(speaker.to_dict()), 201
+
+ except Exception as e:
+ db.session.rollback()
+ current_app.logger.error(f"Error creating speaker: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+
+@speakers_bp.route('/speakers/<int:speaker_id>', methods=['PUT'])
+@login_required
+def update_speaker(speaker_id):
+ """Update a speaker's name and cascade the change to all recordings."""
+ try:
+ speaker = Speaker.query.filter_by(id=speaker_id, user_id=current_user.id).first()
+ if not speaker:
+ return jsonify({'error': 'Speaker not found'}), 404
+
+ data = request.json
+ new_name = data.get('name', '').strip()
+
+ if not new_name:
+ return jsonify({'error': 'Speaker name cannot be empty'}), 400
+
+ # Check if another speaker with this name already exists for this user
+ existing_speaker = Speaker.query.filter_by(user_id=current_user.id, name=new_name).first()
+ if existing_speaker and existing_speaker.id != speaker_id:
+ return jsonify({'error': f'A speaker named "{new_name}" already exists'}), 400
+
+ # Store old name for updating transcript chunks and recordings
+ old_name = speaker.name
+
+ # Update the speaker name
+ speaker.name = new_name
+
+ # Update all transcript chunks that reference this speaker's old name
+ # This ensures the name change cascades to all recordings
+ from src.models import TranscriptChunk
+ chunks_updated = TranscriptChunk.query.filter_by(
+ user_id=current_user.id,
+ speaker_name=old_name
+ ).update({'speaker_name': new_name})
+
+ # Update Recording.participants field (comma-separated list of speakers)
+ # AND update speaker names in the transcription JSON
+ recordings_updated = 0
+ user_recordings = Recording.query.filter_by(user_id=current_user.id).all()
+
+ for recording in user_recordings:
+ updated = False
+
+ # Update participants field if it contains the old name
+ if recording.participants and old_name in recording.participants:
+ # Replace exact speaker name matches in participants list
+ # Handle various formats: "Ross", "Ross, John", "John, Ross", etc.
+ participants_list = [p.strip() for p in recording.participants.split(',')]
+ if old_name in participants_list:
+ # Replace the old name with new name
+ participants_list = [new_name if p == old_name else p for p in participants_list]
+ recording.participants = ', '.join(participants_list)
+ updated = True
+
+ # Update speaker names in the transcription JSON
+ # This is what displays in the transcript view speaker badges
+ if recording.transcription:
+ try:
+ transcription_data = json.loads(recording.transcription)
+
+ # Handle JSON format (array of segments with speaker field)
+ if isinstance(transcription_data, list):
+ segments_updated = False
+ for segment in transcription_data:
+ if segment.get('speaker') == old_name:
+ segment['speaker'] = new_name
+ segments_updated = True
+
+ if segments_updated:
+ recording.transcription = json.dumps(transcription_data)
+ updated = True
+ except (json.JSONDecodeError, TypeError):
+ # Not JSON or invalid format, skip
+ pass
+
+ if updated:
+ recordings_updated += 1
+
+ db.session.commit()
+
+ current_app.logger.info(
+ f"Updated speaker {speaker_id} from '{old_name}' to '{new_name}': "
+ f"{chunks_updated} transcript chunks, {recordings_updated} recordings"
+ )
+
+ return jsonify({
+ 'success': True,
+ 'speaker': speaker.to_dict(),
+ 'chunks_updated': chunks_updated,
+ 'recordings_updated': recordings_updated
+ })
+
+ except Exception as e:
+ db.session.rollback()
+ current_app.logger.error(f"Error updating speaker: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+@speakers_bp.route('/speakers/<int:speaker_id>', methods=['DELETE'])
+@login_required
+def delete_speaker(speaker_id):
+ """Delete a speaker."""
+ try:
+ speaker = Speaker.query.filter_by(id=speaker_id, user_id=current_user.id).first()
+ if not speaker:
+ return jsonify({'error': 'Speaker not found'}), 404
+
+ db.session.delete(speaker)
+ db.session.commit()
+ return jsonify({'success': True})
+
+ except Exception as e:
+ db.session.rollback()
+ current_app.logger.error(f"Error deleting speaker: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+
+@speakers_bp.route('/speakers/delete_all', methods=['DELETE'])
+@login_required
+def delete_all_speakers():
+ """Delete all speakers for the current user."""
+ try:
+ deleted_count = Speaker.query.filter_by(user_id=current_user.id).delete()
+ db.session.commit()
+ return jsonify({'success': True, 'deleted_count': deleted_count})
+
+ except Exception as e:
+ db.session.rollback()
+ current_app.logger.error(f"Error deleting all speakers: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+@speakers_bp.route('/speakers/suggestions/<int:recording_id>', methods=['GET'])
+@login_required
+def get_speaker_suggestions(recording_id):
+ """
+ Get speaker suggestions based on voice embeddings from a recording.
+
+ For each speaker in the recording, returns matching speakers from the user's
+ speaker database based on voice similarity.
+
+ Returns:
+ {
+ 'SPEAKER_00': [
+ {'speaker_id': 5, 'name': 'John', 'similarity': 85.3, 'confidence': 0.92},
+ ...
+ ],
+ 'SPEAKER_01': [...],
+ ...
+ }
+ """
+ try:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ if not has_recording_access(recording, current_user, require_edit=False):
+ return jsonify({'error': 'You do not have permission to access this recording'}), 403
+
+ # Get speaker embeddings from recording
+ if not recording.speaker_embeddings:
+ return jsonify({'suggestions': {}, 'message': 'No speaker embeddings available'}), 200
+
+ try:
+ embeddings_data = json.loads(recording.speaker_embeddings) if isinstance(recording.speaker_embeddings, str) else recording.speaker_embeddings
+ except (json.JSONDecodeError, TypeError):
+ return jsonify({'error': 'Invalid speaker embeddings data'}), 500
+
+ # Get similarity threshold from query params (default 70%)
+ threshold = float(request.args.get('threshold', 0.70))
+
+ # Find matches for each speaker
+ suggestions = {}
+ for speaker_label, embedding in embeddings_data.items():
+ if embedding and len(embedding) == 256: # Validate embedding dimension
+ matches = find_matching_speakers(embedding, current_user.id, threshold)
+ suggestions[speaker_label] = matches
+ else:
+ suggestions[speaker_label] = []
+
+ return jsonify({
+ 'success': True,
+ 'suggestions': suggestions,
+ 'recording_id': recording_id
+ })
+
+ except Exception as e:
+ current_app.logger.error(f"Error getting speaker suggestions: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+@speakers_bp.route('/speakers/<int:speaker_id>/snippets', methods=['GET'])
+@login_required
+def get_snippets(speaker_id):
+ """
+ Get representative speech snippets for a speaker.
+
+ Returns recent quotes from recordings where this speaker appeared.
+ """
+ try:
+ # Verify speaker belongs to user
+ speaker = Speaker.query.filter_by(id=speaker_id, user_id=current_user.id).first()
+ if not speaker:
+ return jsonify({'error': 'Speaker not found'}), 404
+
+ limit = int(request.args.get('limit', 5))
+ snippets = get_speaker_snippets(speaker_id, limit)
+
+ return jsonify({
+ 'success': True,
+ 'speaker_id': speaker_id,
+ 'speaker_name': speaker.name,
+ 'snippets': snippets
+ })
+
+ except Exception as e:
+ current_app.logger.error(f"Error getting speaker snippets: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+@speakers_bp.route('/speakers/<int:speaker_id>/recordings', methods=['GET'])
+@login_required
+def get_speaker_recordings(speaker_id):
+ """
+ Get list of recordings that contain snippets from this speaker.
+
+ Returns recording metadata with snippet counts.
+ """
+ try:
+ # Verify speaker belongs to user
+ speaker = Speaker.query.filter_by(id=speaker_id, user_id=current_user.id).first()
+ if not speaker:
+ return jsonify({'error': 'Speaker not found'}), 404
+
+ recordings = get_speaker_recordings_with_snippets(speaker_id)
+
+ return jsonify({
+ 'success': True,
+ 'speaker_id': speaker_id,
+ 'speaker_name': speaker.name,
+ 'recordings': recordings
+ })
+
+ except Exception as e:
+ current_app.logger.error(f"Error getting speaker recordings: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+@speakers_bp.route('/speakers/<int:speaker_id>/clear_embeddings', methods=['POST'])
+@login_required
+def clear_speaker_embeddings(speaker_id):
+ """
+ Clear all voice embeddings for a speaker.
+
+ This removes all voice recognition data but keeps the speaker name and metadata.
+ Useful for resetting voice profiles or removing outdated/incorrect voice data.
+ """
+ try:
+ # Verify speaker belongs to user
+ speaker = Speaker.query.filter_by(id=speaker_id, user_id=current_user.id).first()
+ if not speaker:
+ return jsonify({'error': 'Speaker not found'}), 404
+
+ # Clear all embeddings
+ speaker.voice_embeddings = None
+ speaker.embedding_count = 0
+ speaker.confidence_score = None
+
+ db.session.commit()
+
+ current_app.logger.info(f"Cleared voice embeddings for speaker {speaker_id} ({speaker.name})")
+
+ return jsonify({
+ 'success': True,
+ 'message': f'Voice profile cleared for {speaker.name}',
+ 'speaker': {
+ 'id': speaker.id,
+ 'name': speaker.name,
+ 'embedding_count': 0
+ }
+ })
+
+ except Exception as e:
+ db.session.rollback()
+ current_app.logger.error(f"Error clearing speaker embeddings: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+@speakers_bp.route('/speakers/snippet-audio/<int:recording_id>', methods=['GET'])
+@login_required
+def get_snippet_audio(recording_id):
+ """
+ Serve a short audio snippet from a recording.
+
+ Query parameters:
+ start: Start time in seconds (float)
+ duration: Duration in seconds (float, max 5.0)
+
+ Returns:
+ Audio file segment in the original format
+ """
+ import subprocess
+ import tempfile
+ import os
+ from pathlib import Path
+
+ try:
+ # Get query parameters
+ start_time = float(request.args.get('start', 0))
+ duration = min(float(request.args.get('duration', 4.0)), 5.0) # Max 5 seconds
+
+ # Get the recording
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return jsonify({'error': 'Recording not found'}), 404
+
+ if not has_recording_access(recording, current_user, require_edit=False):
+ return jsonify({'error': 'You do not have permission to access this recording'}), 403
+
+ if recording.audio_deleted_at:
+ return jsonify({'error': 'Audio file has been deleted'}), 410
+
+ if not recording.audio_path or not os.path.exists(recording.audio_path):
+ return jsonify({'error': 'Audio file not found'}), 404
+
+ # Create temporary file for the snippet
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.mp3') as tmp_file:
+ output_path = tmp_file.name
+
+ try:
+ # Use FFmpeg to extract the audio segment
+ ffmpeg_cmd = [
+ 'ffmpeg',
+ '-i', recording.audio_path,
+ '-ss', str(start_time),
+ '-t', str(duration),
+ '-c', 'copy',
+ '-y',
+ output_path
+ ]
+
+ subprocess.run(ffmpeg_cmd, check=True, capture_output=True)
+
+ # Send the file
+ response = send_file(
+ output_path,
+ mimetype='audio/mpeg',
+ as_attachment=False,
+ download_name=f'snippet_{recording_id}_{start_time:.1f}s.mp3'
+ )
+
+ # Clean up temporary file after sending
+ @response.call_on_close
+ def cleanup():
+ try:
+ os.unlink(output_path)
+ except:
+ pass
+
+ return response
+
+ except subprocess.CalledProcessError as e:
+ current_app.logger.error(f"FFmpeg error extracting snippet: {e}")
+ try:
+ os.unlink(output_path)
+ except:
+ pass
+ return jsonify({'error': 'Failed to extract audio snippet'}), 500
+
+ except ValueError:
+ return jsonify({'error': 'Invalid start time or duration'}), 400
+ except Exception as e:
+ current_app.logger.error(f"Error serving audio snippet: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+@speakers_bp.route('/speakers/merge', methods=['POST'])
+@login_required
+def merge_speaker_profiles():
+ """
+ Merge multiple speaker profiles into one.
+
+ Request body:
+ {
+ 'target_id': 5, # Speaker to keep
+ 'source_ids': [6, 7, 8], # Speakers to merge into target
+ 'preview': false # Optional: if true, just preview without executing
+ }
+
+ Returns merged speaker data or preview statistics.
+ """
+ try:
+ data = request.json
+ target_id = data.get('target_id')
+ source_ids = data.get('source_ids', [])
+ preview = data.get('preview', False)
+
+ if not target_id:
+ return jsonify({'error': 'target_id is required'}), 400
+
+ if not source_ids or not isinstance(source_ids, list):
+ return jsonify({'error': 'source_ids must be a non-empty list'}), 400
+
+ # Validate speakers can be merged
+ can_merge, error_msg = can_merge_speakers([target_id] + source_ids, current_user.id)
+ if not can_merge:
+ return jsonify({'error': error_msg}), 400
+
+ if preview:
+ # Just return preview statistics
+ preview_data = preview_merge(target_id, source_ids, current_user.id)
+ return jsonify({
+ 'success': True,
+ 'preview': preview_data
+ })
+ else:
+ # Execute the merge
+ merged_speaker = merge_speakers(target_id, source_ids, current_user.id)
+ return jsonify({
+ 'success': True,
+ 'message': f'Successfully merged {len(source_ids)} speaker(s) into {merged_speaker.name}',
+ 'speaker': merged_speaker.to_dict()
+ })
+
+ except ValueError as e:
+ return jsonify({'error': str(e)}), 400
+ except Exception as e:
+ db.session.rollback()
+ current_app.logger.error(f"Error merging speakers: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+
diff --git a/src/api/system.py b/src/api/system.py
new file mode 100644
index 00000000..e1db2ea0
--- /dev/null
+++ b/src/api/system.py
@@ -0,0 +1,194 @@
+"""
+System info and configuration.
+
+This blueprint was auto-generated from app.py route extraction.
+"""
+
+import os
+import json
+from datetime import datetime, timedelta
+from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, send_file, Response, current_app
+from flask_login import login_required, current_user
+from werkzeug.utils import secure_filename
+
+from src.database import db
+from src.models import *
+from src.utils import *
+from src.config.version import get_version
+from src.services.llm import TEXT_MODEL_BASE_URL, TEXT_MODEL_NAME
+from src.config.app_config import ASR_BASE_URL
+
+# Create blueprint
+system_bp = Blueprint('system', __name__)
+
+# Configuration from environment
+ENABLE_INQUIRE_MODE = os.environ.get('ENABLE_INQUIRE_MODE', 'false').lower() == 'true'
+ENABLE_AUTO_DELETION = os.environ.get('ENABLE_AUTO_DELETION', 'false').lower() == 'true'
+DELETION_MODE = os.environ.get('DELETION_MODE', 'full_recording') # 'audio_only' or 'full_recording'
+USERS_CAN_DELETE = os.environ.get('USERS_CAN_DELETE', 'true').lower() == 'true'
+ENABLE_INTERNAL_SHARING = os.environ.get('ENABLE_INTERNAL_SHARING', 'false').lower() == 'true'
+USE_ASR_ENDPOINT = os.environ.get('USE_ASR_ENDPOINT', 'false').lower() == 'true'
+ENABLE_CHUNKING = os.environ.get('ENABLE_CHUNKING', 'true').lower() == 'true'
+SHOW_USERNAMES_IN_UI = os.environ.get('SHOW_USERNAMES_IN_UI', 'false').lower() == 'true'
+
+# Import chunking service (will be set from app)
+chunking_service = None
+
+# Global helpers (will be injected from app)
+has_recording_access = None
+bcrypt = None
+csrf = None
+limiter = None
+
+def init_system_helpers(**kwargs):
+ """Initialize helper functions and extensions from app."""
+ global has_recording_access, bcrypt, csrf, limiter, chunking_service
+ has_recording_access = kwargs.get('has_recording_access')
+ bcrypt = kwargs.get('bcrypt')
+ csrf = kwargs.get('csrf')
+ limiter = kwargs.get('limiter')
+ chunking_service = kwargs.get('chunking_service')
+
+
+def csrf_exempt(f):
+ """Decorator placeholder for CSRF exemption - applied after initialization."""
+ from functools import wraps
+ @wraps(f)
+ def wrapper(*args, **kwargs):
+ return f(*args, **kwargs)
+ wrapper._csrf_exempt = True
+ return wrapper
+
+
+# --- Routes ---
+
+@system_bp.route('/api/user/preferences', methods=['POST'])
+@login_required
+def save_user_preferences():
+ """Save user preferences including UI language"""
+ data = request.json
+
+ if 'language' in data:
+ current_user.ui_language = data['language']
+
+ db.session.commit()
+
+ return jsonify({
+ 'success': True,
+ 'message': 'Preferences saved successfully',
+ 'ui_language': current_user.ui_language
+ })
+
+# --- System Info API Endpoint ---
+
+
+@system_bp.route('/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:
+ current_app.logger.error(f"Error getting system info: {e}")
+ return jsonify({'error': 'Unable to retrieve system information'}), 500
+
+# --- Tag API Endpoints ---
+
+
+@system_bp.route('/api/config', methods=['GET'])
+def get_config():
+ """Get application configuration settings for the frontend."""
+ try:
+ # Get configurable file size limit
+ max_file_size_mb = SystemSetting.get_setting('max_file_size_mb', 250)
+
+ # Get chunking configuration (supports both legacy and new formats)
+ chunking_info = {}
+ if ENABLE_CHUNKING and chunking_service:
+ mode, limit_value = chunking_service.parse_chunk_limit()
+ chunking_info = {
+ 'chunking_enabled': True,
+ 'chunking_mode': mode, # 'size' or 'duration'
+ 'chunking_limit': limit_value, # Value in MB or seconds
+ 'chunking_limit_display': f"{limit_value}{'MB' if mode == 'size' else 's'}"
+ }
+ else:
+ chunking_info = {
+ 'chunking_enabled': False,
+ 'chunking_mode': 'size',
+ 'chunking_limit': 20,
+ 'chunking_limit_display': '20MB'
+ }
+
+ # Check if current user can delete (for authenticated requests)
+ can_delete = True # Default to true for unauthenticated config requests
+ try:
+ from flask_login import current_user
+ if current_user and current_user.is_authenticated:
+ can_delete = USERS_CAN_DELETE or current_user.is_admin
+ except:
+ pass # If not authenticated, use default
+
+ # Calculate if archive toggle should be shown (only when audio-only deletion mode is active)
+ enable_archive_toggle = ENABLE_AUTO_DELETION and DELETION_MODE == 'audio_only'
+
+ return jsonify({
+ 'max_file_size_mb': max_file_size_mb,
+ 'recording_disclaimer': SystemSetting.get_setting('recording_disclaimer', ''),
+ 'use_asr_endpoint': USE_ASR_ENDPOINT,
+ 'enable_internal_sharing': ENABLE_INTERNAL_SHARING,
+ 'enable_archive_toggle': enable_archive_toggle,
+ 'show_usernames_in_ui': SHOW_USERNAMES_IN_UI,
+ 'can_delete_recordings': can_delete,
+ 'users_can_delete_enabled': USERS_CAN_DELETE,
+ **chunking_info
+ })
+ except Exception as e:
+ current_app.logger.error(f"Error fetching configuration: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+
+
+@system_bp.route('/api/csrf-token', methods=['GET'])
+@csrf_exempt # Exempt this endpoint from CSRF protection since it's providing tokens
+def get_csrf_token():
+ """Get a fresh CSRF token for the frontend."""
+ try:
+ from flask_wtf.csrf import generate_csrf
+ token = generate_csrf()
+ current_app.logger.info("Fresh CSRF token generated successfully")
+ return jsonify({'csrf_token': token})
+ except Exception as e:
+ current_app.logger.error(f"Error generating CSRF token: {e}")
+ return jsonify({'error': str(e)}), 500
+
+# --- Flask Routes ---
+
+
+@system_bp.route('/api/permissions/can-delete', methods=['GET'])
+@login_required
+def check_deletion_permission():
+ """Check if the current user can delete recordings."""
+ try:
+ can_delete = USERS_CAN_DELETE or current_user.is_admin
+ return jsonify({
+ 'can_delete': can_delete,
+ 'is_admin': current_user.is_admin,
+ 'users_can_delete_enabled': USERS_CAN_DELETE
+ })
+ except Exception as e:
+ current_app.logger.error(f"Error checking deletion permissions: {e}")
+ return jsonify({'error': str(e)}), 500
+
+
+
diff --git a/src/api/tags.py b/src/api/tags.py
new file mode 100644
index 00000000..e03a4c5f
--- /dev/null
+++ b/src/api/tags.py
@@ -0,0 +1,370 @@
+"""
+Tag management and assignment.
+
+This blueprint was auto-generated from app.py route extraction.
+"""
+
+import os
+import json
+import time
+from datetime import datetime, timedelta
+from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, send_file, Response, current_app
+from flask_login import login_required, current_user
+from werkzeug.utils import secure_filename
+
+from sqlalchemy.exc import IntegrityError
+
+from src.database import db
+from src.models import *
+from src.utils import *
+
+# Create blueprint
+tags_bp = Blueprint('tags', __name__)
+
+# Configuration from environment
+ENABLE_INQUIRE_MODE = os.environ.get('ENABLE_INQUIRE_MODE', 'false').lower() == 'true'
+ENABLE_AUTO_DELETION = os.environ.get('ENABLE_AUTO_DELETION', 'false').lower() == 'true'
+USERS_CAN_DELETE = os.environ.get('USERS_CAN_DELETE', 'true').lower() == 'true'
+ENABLE_INTERNAL_SHARING = os.environ.get('ENABLE_INTERNAL_SHARING', 'false').lower() == 'true'
+USE_ASR_ENDPOINT = os.environ.get('USE_ASR_ENDPOINT', 'false').lower() == 'true'
+
+# Global helpers (will be injected from app)
+has_recording_access = None
+bcrypt = None
+csrf = None
+limiter = None
+
+def init_tags_helpers(**kwargs):
+ """Initialize helper functions and extensions from app."""
+ global has_recording_access, bcrypt, csrf, limiter
+ has_recording_access = kwargs.get('has_recording_access')
+ bcrypt = kwargs.get('bcrypt')
+ csrf = kwargs.get('csrf')
+ limiter = kwargs.get('limiter')
+
+
+# --- Routes ---
+
+@tags_bp.route('/api/tags', methods=['GET'])
+@login_required
+def get_tags():
+ """Get all tags for the current user, including group tags they have access to."""
+ # Get user's personal tags
+ user_tags = Tag.query.filter_by(user_id=current_user.id, group_id=None).order_by(Tag.name).all()
+
+ # Get user's team memberships with roles
+ memberships = GroupMembership.query.filter_by(user_id=current_user.id).all()
+ team_roles = {m.group_id: m.role for m in memberships}
+ team_ids = list(team_roles.keys())
+
+ # Get group tags for all teams the user is a member of
+ team_tags = []
+ if team_ids:
+ team_tags = Tag.query.filter(Tag.group_id.in_(team_ids)).order_by(Tag.name).all()
+
+ # Build response with edit permissions
+ result = []
+
+ # Personal tags - user can always edit their own
+ for tag in user_tags:
+ tag_dict = tag.to_dict()
+ tag_dict['can_edit'] = True
+ tag_dict['user_role'] = None
+ result.append(tag_dict)
+
+ # Group tags - only admins can edit
+ for tag in team_tags:
+ tag_dict = tag.to_dict()
+ user_role = team_roles.get(tag.group_id, 'member')
+ tag_dict['can_edit'] = (user_role == 'admin')
+ tag_dict['user_role'] = user_role
+ result.append(tag_dict)
+
+ return jsonify(result)
+
+
+
+@tags_bp.route('/api/tags', methods=['POST'])
+@login_required
+def create_tag():
+ """Create a new tag (personal or group tag)."""
+ data = request.get_json()
+
+ if not data or not data.get('name'):
+ return jsonify({'error': 'Tag name is required'}), 400
+
+ group_id = data.get('group_id')
+
+ # If creating a group tag, verify user is admin of that group
+ if group_id:
+ membership = GroupMembership.query.filter_by(
+ group_id=group_id,
+ user_id=current_user.id
+ ).first()
+
+ if not membership or membership.role != 'admin':
+ return jsonify({'error': 'Only group admins can create group tags'}), 403
+
+ # Check if group tag with same name already exists for this group
+ existing_tag = Tag.query.filter_by(name=data['name'], group_id=group_id).first()
+ if existing_tag:
+ return jsonify({'error': 'A tag with this name already exists for this group'}), 400
+ else:
+ # Check if personal tag with same name already exists for this user
+ existing_tag = Tag.query.filter_by(name=data['name'], user_id=current_user.id, group_id=None).first()
+ if existing_tag:
+ return jsonify({'error': 'Tag with this name already exists'}), 400
+
+ # Handle retention_days: -1 means protected from deletion
+ retention_days = data.get('retention_days')
+ protect_from_deletion = False
+
+ if retention_days == -1:
+ # -1 indicates infinite retention (protected from auto-deletion)
+ protect_from_deletion = True if ENABLE_AUTO_DELETION else False
+
+ tag = Tag(
+ name=data['name'],
+ user_id=current_user.id,
+ group_id=group_id,
+ color=data.get('color', '#3B82F6'),
+ custom_prompt=data.get('custom_prompt'),
+ default_language=data.get('default_language'),
+ default_min_speakers=data.get('default_min_speakers'),
+ default_max_speakers=data.get('default_max_speakers'),
+ protect_from_deletion=protect_from_deletion,
+ retention_days=retention_days,
+ auto_share_on_apply=data.get('auto_share_on_apply', True) if group_id else True,
+ share_with_group_lead=data.get('share_with_group_lead', True) if group_id else True
+ )
+
+ db.session.add(tag)
+
+ try:
+ db.session.commit()
+ except IntegrityError as e:
+ db.session.rollback()
+ current_app.logger.error(f"Tag creation failed due to integrity constraint: {str(e)}")
+ return jsonify({'error': 'A tag with this name already exists'}), 400
+
+ return jsonify(tag.to_dict()), 201
+
+
+
+@tags_bp.route('/api/tags/<int:tag_id>', methods=['PUT'])
+@login_required
+def update_tag(tag_id):
+ """Update a tag."""
+ tag = db.session.get(Tag, tag_id)
+ if not tag:
+ return jsonify({'error': 'Tag not found'}), 404
+
+ # Check permissions
+ if tag.group_id:
+ # Group tag - user must be a team admin
+ membership = GroupMembership.query.filter_by(
+ group_id=tag.group_id,
+ user_id=current_user.id
+ ).first()
+
+ if not membership or membership.role != 'admin':
+ return jsonify({'error': 'Only group admins can edit group tags'}), 403
+ else:
+ # Personal tag - must be the owner
+ if tag.user_id != current_user.id:
+ return jsonify({'error': 'You do not have permission to edit this tag'}), 403
+
+ data = request.get_json()
+
+ if 'name' in data:
+ # Check if new name conflicts with another tag
+ if tag.group_id:
+ existing_tag = Tag.query.filter_by(name=data['name'], group_id=tag.group_id).filter(Tag.id != tag_id).first()
+ else:
+ existing_tag = Tag.query.filter_by(name=data['name'], user_id=current_user.id).filter(Tag.id != tag_id).first()
+
+ if existing_tag:
+ return jsonify({'error': 'Another tag with this name already exists'}), 400
+ tag.name = data['name']
+
+ # Handle group_id changes (converting between personal and group tags)
+ if 'group_id' in data:
+ new_group_id = data['group_id'] if data['group_id'] else None
+
+ # If changing to a group tag, verify user is admin of that group
+ if new_group_id:
+ membership = GroupMembership.query.filter_by(
+ group_id=new_group_id,
+ user_id=current_user.id
+ ).first()
+
+ if not membership or membership.role != 'admin':
+ return jsonify({'error': 'Only group admins can assign tags to groups'}), 403
+
+ tag.group_id = new_group_id
+
+ if 'color' in data:
+ tag.color = data['color']
+ if 'custom_prompt' in data:
+ tag.custom_prompt = data['custom_prompt']
+ if 'default_language' in data:
+ tag.default_language = data['default_language']
+ if 'default_min_speakers' in data:
+ tag.default_min_speakers = data['default_min_speakers']
+ if 'default_max_speakers' in data:
+ tag.default_max_speakers = data['default_max_speakers']
+
+ # Handle retention_days: -1 means protected from deletion
+ if 'retention_days' in data:
+ retention_days = data['retention_days']
+
+ if retention_days == -1:
+ # -1 indicates infinite retention (protected from auto-deletion)
+ if ENABLE_AUTO_DELETION:
+ tag.protect_from_deletion = True
+ tag.retention_days = -1
+ else:
+ # Regular retention period or null (use global)
+ tag.protect_from_deletion = False
+ tag.retention_days = retention_days if retention_days else None
+ if 'auto_share_on_apply' in data:
+ # Only applicable to group tags
+ if tag.group_id:
+ tag.auto_share_on_apply = bool(data['auto_share_on_apply'])
+ if 'share_with_group_lead' in data:
+ # Only applicable to group tags
+ if tag.group_id:
+ tag.share_with_group_lead = bool(data['share_with_group_lead'])
+
+ tag.updated_at = datetime.utcnow()
+
+ try:
+ db.session.commit()
+ except IntegrityError as e:
+ db.session.rollback()
+ current_app.logger.error(f"Tag update failed due to integrity constraint: {str(e)}")
+ return jsonify({'error': 'A tag with this name already exists'}), 400
+
+ return jsonify(tag.to_dict())
+
+
+
+@tags_bp.route('/api/tags/<int:tag_id>', methods=['DELETE'])
+@login_required
+def delete_tag(tag_id):
+ """Delete a tag."""
+ tag = db.session.get(Tag, tag_id)
+ if not tag:
+ return jsonify({'error': 'Tag not found'}), 404
+
+ # Check permissions
+ if tag.group_id:
+ # Group tag - user must be a team admin
+ membership = GroupMembership.query.filter_by(
+ group_id=tag.group_id,
+ user_id=current_user.id
+ ).first()
+
+ if not membership or membership.role != 'admin':
+ return jsonify({'error': 'Only group admins can delete group tags'}), 403
+ else:
+ # Personal tag - must belong to the user
+ if tag.user_id != current_user.id:
+ return jsonify({'error': 'You do not have permission to delete this tag'}), 403
+
+ db.session.delete(tag)
+ db.session.commit()
+ return jsonify({'success': True})
+
+
+
+@tags_bp.route('/api/groups/<int:group_id>/tags', methods=['POST'])
+@login_required
+def create_group_tag(group_id):
+ """Create a group-scoped tag (group admins only)."""
+ if not ENABLE_INTERNAL_SHARING:
+ return jsonify({'error': 'Group tags require internal sharing to be enabled. Please set ENABLE_INTERNAL_SHARING=true in your configuration.'}), 403
+
+ # Verify team exists
+ team = db.session.get(Group, group_id)
+ if not team:
+ return jsonify({'error': 'Group not found'}), 404
+
+ # Verify user is a team admin
+ membership = GroupMembership.query.filter_by(
+ group_id=group_id,
+ user_id=current_user.id
+ ).first()
+
+ if not membership or membership.role != 'admin':
+ return jsonify({'error': 'Only group admins can create group tags'}), 403
+
+ data = request.get_json()
+ name = data.get('name', '').strip()
+
+ if not name:
+ return jsonify({'error': 'Tag name is required'}), 400
+
+ # Check if a group tag with this name already exists for this team
+ existing_tag = Tag.query.filter_by(
+ name=name,
+ group_id=group_id
+ ).first()
+
+ if existing_tag:
+ return jsonify({'error': 'A group tag with this name already exists'}), 400
+
+ # Create the group tag with all supported parameters
+ tag = Tag(
+ name=name,
+ user_id=current_user.id, # Creator
+ group_id=group_id,
+ color=data.get('color', '#3B82F6'),
+ custom_prompt=data.get('custom_prompt'),
+ default_language=data.get('default_language'),
+ default_min_speakers=data.get('default_min_speakers'),
+ default_max_speakers=data.get('default_max_speakers'),
+ protect_from_deletion=data.get('protect_from_deletion', False),
+ retention_days=data.get('retention_days'),
+ auto_share_on_apply=data.get('auto_share_on_apply', True), # Default to True for group tags
+ share_with_group_lead=data.get('share_with_group_lead', True) # Default to True for group tags
+ )
+
+ db.session.add(tag)
+
+ try:
+ db.session.commit()
+ except IntegrityError as e:
+ db.session.rollback()
+ current_app.logger.error(f"Tag creation failed due to integrity constraint: {str(e)}")
+ return jsonify({'error': 'A tag with this name already exists'}), 400
+
+ return jsonify(tag.to_dict()), 201
+
+
+
+@tags_bp.route('/api/groups/<int:group_id>/tags', methods=['GET'])
+@login_required
+def get_group_tags(group_id):
+ """Get all tags for a team (team members only)."""
+ # Verify team exists
+ team = db.session.get(Group, group_id)
+ if not team:
+ return jsonify({'error': 'Group not found'}), 404
+
+ # Verify user is a team member
+ membership = GroupMembership.query.filter_by(
+ group_id=group_id,
+ user_id=current_user.id
+ ).first()
+
+ if not membership:
+ return jsonify({'error': 'You must be a team member to view group tags'}), 403
+
+ # Get all group tags
+ tags = Tag.query.filter_by(group_id=group_id).all()
+
+ return jsonify({'tags': [tag.to_dict() for tag in tags]})
+
+
+
diff --git a/src/api/templates.py b/src/api/templates.py
new file mode 100644
index 00000000..2f4724ce
--- /dev/null
+++ b/src/api/templates.py
@@ -0,0 +1,232 @@
+"""
+Transcript template management.
+
+This blueprint was auto-generated from app.py route extraction.
+"""
+
+import os
+import json
+import time
+from datetime import datetime, timedelta
+from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, send_file, Response, current_app
+from flask_login import login_required, current_user
+from werkzeug.utils import secure_filename
+
+from src.database import db
+from src.models import *
+from src.utils import *
+
+# Create blueprint
+templates_bp = Blueprint('templates', __name__)
+
+# Configuration from environment
+ENABLE_INQUIRE_MODE = os.environ.get('ENABLE_INQUIRE_MODE', 'false').lower() == 'true'
+ENABLE_AUTO_DELETION = os.environ.get('ENABLE_AUTO_DELETION', 'false').lower() == 'true'
+USERS_CAN_DELETE = os.environ.get('USERS_CAN_DELETE', 'true').lower() == 'true'
+ENABLE_INTERNAL_SHARING = os.environ.get('ENABLE_INTERNAL_SHARING', 'false').lower() == 'true'
+USE_ASR_ENDPOINT = os.environ.get('USE_ASR_ENDPOINT', 'false').lower() == 'true'
+
+# Global helpers (will be injected from app)
+has_recording_access = None
+bcrypt = None
+csrf = None
+limiter = None
+
+def init_templates_helpers(**kwargs):
+ """Initialize helper functions and extensions from app."""
+ global has_recording_access, bcrypt, csrf, limiter
+ has_recording_access = kwargs.get('has_recording_access')
+ bcrypt = kwargs.get('bcrypt')
+ csrf = kwargs.get('csrf')
+ limiter = kwargs.get('limiter')
+
+
+# --- Routes ---
+
+@templates_bp.route('/api/transcript-templates', methods=['GET'])
+@login_required
+def get_transcript_templates():
+ """Get all transcript templates for the current user."""
+ templates = TranscriptTemplate.query.filter_by(user_id=current_user.id).all()
+ return jsonify([template.to_dict() for template in templates])
+
+
+
+@templates_bp.route('/api/transcript-templates', methods=['POST'])
+@login_required
+def create_transcript_template():
+ """Create a new transcript template."""
+ data = request.json
+ if not data or not data.get('name') or not data.get('template'):
+ return jsonify({'error': 'Name and template are required'}), 400
+
+ # If this is set as default, unset other defaults
+ if data.get('is_default'):
+ TranscriptTemplate.query.filter_by(
+ user_id=current_user.id,
+ is_default=True
+ ).update({'is_default': False})
+
+ template = TranscriptTemplate(
+ user_id=current_user.id,
+ name=data['name'],
+ template=data['template'],
+ description=data.get('description'),
+ is_default=data.get('is_default', False)
+ )
+
+ db.session.add(template)
+ db.session.commit()
+
+ return jsonify(template.to_dict()), 201
+
+
+
+@templates_bp.route('/api/transcript-templates/<int:template_id>', methods=['PUT'])
+@login_required
+def update_transcript_template(template_id):
+ """Update an existing transcript template."""
+ template = TranscriptTemplate.query.filter_by(
+ id=template_id,
+ user_id=current_user.id
+ ).first()
+
+ if not template:
+ return jsonify({'error': 'Template not found'}), 404
+
+ data = request.json
+ if not data:
+ return jsonify({'error': 'No data provided'}), 400
+
+ # If this is set as default, unset other defaults
+ if data.get('is_default'):
+ TranscriptTemplate.query.filter_by(
+ user_id=current_user.id,
+ is_default=True
+ ).update({'is_default': False})
+
+ template.name = data.get('name', template.name)
+ template.template = data.get('template', template.template)
+ template.description = data.get('description', template.description)
+ template.is_default = data.get('is_default', template.is_default)
+ template.updated_at = datetime.utcnow()
+
+ db.session.commit()
+
+ return jsonify(template.to_dict())
+
+
+
+@templates_bp.route('/api/transcript-templates/<int:template_id>', methods=['DELETE'])
+@login_required
+def delete_transcript_template(template_id):
+ """Delete a transcript template."""
+ template = TranscriptTemplate.query.filter_by(
+ id=template_id,
+ user_id=current_user.id
+ ).first()
+
+ if not template:
+ return jsonify({'error': 'Template not found'}), 404
+
+ db.session.delete(template)
+ db.session.commit()
+
+ return jsonify({'success': True})
+
+
+
+@templates_bp.route('/api/transcript-templates/create-defaults', methods=['POST'])
+@login_required
+def create_default_templates():
+ """Create default templates for the user if they don't have any."""
+ existing_templates = TranscriptTemplate.query.filter_by(user_id=current_user.id).count()
+
+ if existing_templates > 0:
+ return jsonify({'message': 'User already has templates'}), 200
+
+ templates = []
+
+ # Default template 1: Simple conversation
+ template1 = TranscriptTemplate(
+ user_id=current_user.id,
+ name="Simple Conversation",
+ template="{{speaker}}: {{text}}",
+ description="Clean format with just speaker names and text",
+ is_default=True
+ )
+ templates.append(template1)
+
+ # Default template 2: Timestamped format
+ template2 = TranscriptTemplate(
+ user_id=current_user.id,
+ name="Timestamped",
+ template="[{{start_time}} - {{end_time}}] {{speaker}}: {{text}}",
+ description="Format with timestamps and speaker names",
+ is_default=False
+ )
+ templates.append(template2)
+
+ # Default template 3: Interview Q&A
+ template3 = TranscriptTemplate(
+ user_id=current_user.id,
+ name="Interview Q&A",
+ template="{{speaker|upper}}:\n{{text}}\n",
+ description="Interview format with speaker names in uppercase",
+ is_default=False
+ )
+ templates.append(template3)
+
+ # Default template 4: Meeting Minutes
+ template4 = TranscriptTemplate(
+ user_id=current_user.id,
+ name="Meeting Minutes",
+ template="• [{{start_time}}] {{speaker}}: {{text}}",
+ description="Bulleted format ideal for meeting notes",
+ is_default=False
+ )
+ templates.append(template4)
+
+ # Default template 5: Court Transcript
+ template5 = TranscriptTemplate(
+ user_id=current_user.id,
+ name="Court Transcript",
+ template="{{index}} {{speaker|upper}}: {{text}}",
+ description="Legal deposition format with line numbers",
+ is_default=False
+ )
+ templates.append(template5)
+
+ # Default template 6: SRT Subtitle
+ template6 = TranscriptTemplate(
+ user_id=current_user.id,
+ name="SRT Subtitle",
+ template="{{index}}\n{{start_time|srt}} --> {{end_time|srt}}\n{{text}}\n",
+ description="SRT subtitle format for video editing",
+ is_default=False
+ )
+ templates.append(template6)
+
+ # Default template 7: Screenplay
+ template7 = TranscriptTemplate(
+ user_id=current_user.id,
+ name="Screenplay",
+ template=" {{speaker|upper}}\n {{text}}\n",
+ description="Film script format with centered names",
+ is_default=False
+ )
+ templates.append(template7)
+
+ # Add all templates to database
+ for template in templates:
+ db.session.add(template)
+
+ db.session.commit()
+
+ return jsonify({
+ 'success': True,
+ 'templates': [template.to_dict() for template in templates]
+ }), 201
+
+
+
diff --git a/src/app.py b/src/app.py
index 4633bc65..8aaa7e53 100644
--- a/src/app.py
+++ b/src/app.py
@@ -73,6 +73,21 @@ load_dotenv()
# Early check for Inquire Mode configuration (needed for startup message)
ENABLE_INQUIRE_MODE = os.environ.get('ENABLE_INQUIRE_MODE', 'false').lower() == 'true'
+# Auto-deletion and retention configuration
+ENABLE_AUTO_DELETION = os.environ.get('ENABLE_AUTO_DELETION', 'false').lower() == 'true'
+GLOBAL_RETENTION_DAYS = int(os.environ.get('GLOBAL_RETENTION_DAYS', '0')) # 0 = disabled
+DELETION_MODE = os.environ.get('DELETION_MODE', 'full_recording') # 'audio_only' or 'full_recording'
+
+# Permission-based deletion control
+USERS_CAN_DELETE = os.environ.get('USERS_CAN_DELETE', 'true').lower() == 'true' # true = all users can delete, false = admin only
+
+# Internal sharing configuration
+ENABLE_INTERNAL_SHARING = os.environ.get('ENABLE_INTERNAL_SHARING', 'false').lower() == 'true'
+SHOW_USERNAMES_IN_UI = os.environ.get('SHOW_USERNAMES_IN_UI', 'false').lower() == 'true'
+
+# Public sharing configuration
+ENABLE_PUBLIC_SHARING = os.environ.get('ENABLE_PUBLIC_SHARING', 'true').lower() == 'true'
+
# Log embedding status on startup
if ENABLE_INQUIRE_MODE and EMBEDDINGS_AVAILABLE:
print("✅ Inquire Mode: Full semantic search enabled (embeddings available)")
@@ -82,6 +97,34 @@ elif ENABLE_INQUIRE_MODE and not EMBEDDINGS_AVAILABLE:
elif not ENABLE_INQUIRE_MODE:
print("ℹ️ Inquire Mode: Disabled (set ENABLE_INQUIRE_MODE=true to enable)")
+# Log auto-deletion status
+if ENABLE_AUTO_DELETION:
+ if GLOBAL_RETENTION_DAYS > 0:
+ print(f"✅ Auto-deletion: Enabled (global retention: {GLOBAL_RETENTION_DAYS} days, mode: {DELETION_MODE})")
+ else:
+ print("⚠️ Auto-deletion: Enabled but no global retention period set (configure GLOBAL_RETENTION_DAYS)")
+else:
+ print("ℹ️ Auto-deletion: Disabled (set ENABLE_AUTO_DELETION=true to enable)")
+
+# Log deletion permissions
+if USERS_CAN_DELETE:
+ print("ℹ️ User deletion: Enabled (all users can delete their recordings)")
+else:
+ print("🔒 User deletion: Restricted (only admins can delete recordings)")
+
+# Log internal sharing status
+if ENABLE_INTERNAL_SHARING:
+ username_visibility = "visible" if SHOW_USERNAMES_IN_UI else "hidden"
+ print(f"✅ Internal sharing: Enabled (usernames {username_visibility})")
+else:
+ print("ℹ️ Internal sharing: Disabled (set ENABLE_INTERNAL_SHARING=true to enable)")
+
+# Log public sharing status
+if ENABLE_PUBLIC_SHARING:
+ print("✅ Public sharing: Enabled (users can create public share links)")
+else:
+ print("🔒 Public sharing: Disabled (public share links are not allowed)")
+
# Configure logging
log_level = os.environ.get('LOG_LEVEL', 'INFO').upper()
handler = logging.StreamHandler(sys.stdout)
@@ -89,15 +132,28 @@ handler.setLevel(log_level)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
-# Get the root logger
+# Get the root logger and clear any existing handlers to avoid duplicates
root_logger = logging.getLogger()
+root_logger.handlers.clear()
root_logger.setLevel(log_level)
root_logger.addHandler(handler)
-# Also configure Flask's logger
-app_logger = logging.getLogger('werkzeug')
-app_logger.setLevel(log_level)
-app_logger.addHandler(handler)
+# Silence noisy markdown extension debug logs
+markdown_logger = logging.getLogger('MARKDOWN')
+markdown_logger.setLevel(logging.WARNING)
+
+# --- Initialize Markdown Once (Performance Optimization) ---
+# Create a single reusable Markdown instance to avoid reinitializing extensions on every call
+_markdown_instance = markdown.Markdown(extensions=[
+ 'fenced_code', # Fenced code blocks
+ 'tables', # Table support
+ 'attr_list', # Attribute lists
+ 'def_list', # Definition lists
+ 'footnotes', # Footnotes
+ 'abbr', # Abbreviations
+ 'codehilite', # Syntax highlighting for code blocks
+ 'smarty' # Smart quotes, dashes, etc.
+])
# --- Rate Limiting Setup (will be configured after app creation) ---
# TEMPORARILY INCREASED FOR TESTING - REVERT FOR PRODUCTION!
@@ -107,451 +163,173 @@ limiter = Limiter(
default_limits=["5000 per day", "1000 per hour"] # Increased from 200/day, 50/hour for testing
)
-def auto_close_json(json_string):
+# --- Utility Functions ---
+# Utility functions (JSON parsing, markdown, datetime, security) have been extracted
+# to src/utils/ and imported at the top of this file
+
+def has_recording_access(recording, user, require_edit=False, require_reshare=False):
"""
- Attempts to close an incomplete JSON string by appending necessary brackets and braces.
- This is a simplified parser and may not handle all edge cases, but is
- designed to fix unterminated strings from API responses.
+ Check if a user has access to a recording.
+
+ Args:
+ recording: Recording object to check access for
+ user: User object (typically current_user)
+ require_edit: If True, check for edit permission (default: False for view-only)
+ require_reshare: If True, check for reshare permission (default: False)
+
+ Returns:
+ Boolean indicating if user has the required access level
"""
- if not isinstance(json_string, str):
- return json_string
+ # Owner always has full access
+ if recording.user_id == user.id:
+ return True
+
+ # If internal sharing is not enabled, only owner has access
+ if not ENABLE_INTERNAL_SHARING:
+ return False
- stack = []
- in_string = False
- escape_next = False
+ # Check for shared access
+ share = InternalShare.query.filter_by(
+ recording_id=recording.id,
+ shared_with_user_id=user.id
+ ).first()
- for char in json_string:
- if escape_next:
- escape_next = False
- continue
+ if not share:
+ return False
- if char == '\\':
- escape_next = True
- continue
+ # If edit permission is required, check for it
+ if require_edit:
+ # First check if share directly grants edit permission
+ if share.can_edit:
+ pass # Has direct edit permission
+ else:
+ # Check if user is a group admin for any group tag on this recording
+ # This grants edit permission even if share.can_edit is False
+ is_group_admin_for_recording = db.session.query(GroupMembership).join(
+ Tag, Tag.group_id == GroupMembership.group_id
+ ).join(
+ RecordingTag, RecordingTag.tag_id == Tag.id
+ ).filter(
+ RecordingTag.recording_id == recording.id,
+ GroupMembership.user_id == user.id,
+ GroupMembership.role == 'admin',
+ Tag.group_id.isnot(None),
+ db.or_(Tag.auto_share_on_apply == True, Tag.share_with_group_lead == True)
+ ).first()
- if char == '"':
- # We don't handle escaped quotes inside strings perfectly,
- # but this is a simple heuristic.
- if not escape_next:
- in_string = not in_string
+ if not is_group_admin_for_recording:
+ return False
- if not in_string:
- if char == '{':
- stack.append('}')
- elif char == '[':
- stack.append(']')
- elif char == '}':
- if stack and stack[-1] == '}':
- stack.pop()
- elif char == ']':
- if stack and stack[-1] == ']':
- stack.pop()
+ # If reshare permission is required, check for it
+ if require_reshare and not share.can_reshare:
+ return False
- # If we are inside a string at the end, close it.
- if in_string:
- json_string += '"'
-
- # Close any remaining open structures
- while stack:
- json_string += stack.pop()
+ # User has at least view access
+ return True
- return json_string
-def safe_json_loads(json_string, fallback_value=None):
+def get_user_recording_status(recording, user):
"""
- Safely parse JSON with preprocessing to handle common LLM JSON formatting issues.
-
+ Get the inbox and highlighted status for a recording from a user's perspective.
+
+ For owners: Returns status from Recording model
+ For shared recipients: Returns status from SharedRecordingState (creates default if not exists)
+
Args:
- json_string (str): The JSON string to parse
- fallback_value: Value to return if parsing fails (default: None)
-
+ recording: Recording object
+ user: User object (typically current_user)
+
Returns:
- Parsed JSON object or fallback_value if parsing fails
+ Tuple of (is_inbox, is_highlighted)
"""
- if not json_string or not isinstance(json_string, str):
- app.logger.warning(f"Invalid JSON input: {type(json_string)} - {json_string}")
- return fallback_value
-
- # Step 1: Clean the input string
- cleaned_json = json_string.strip()
-
- # Step 2: Extract JSON from markdown code blocks if present
- json_match = re.search(r'```(?:json)?\s*(.*?)\s*```', cleaned_json, re.DOTALL)
- if json_match:
- cleaned_json = json_match.group(1).strip()
-
- # Step 3: Try multiple parsing strategies
- parsing_strategies = [
- # Strategy 1: Direct parsing (for well-formed JSON)
- lambda x: json.loads(x),
-
- # Strategy 2: Fix common escape issues
- lambda x: json.loads(preprocess_json_escapes(x)),
-
- # Strategy 3: Use ast.literal_eval as fallback for simple cases
- lambda x: ast.literal_eval(x) if x.startswith(('{', '[')) else None,
-
- # Strategy 4: Extract JSON object/array using regex
- lambda x: json.loads(extract_json_object(x)),
-
- # Strategy 5: Auto-close incomplete JSON and parse
- lambda x: json.loads(auto_close_json(x)),
- ]
-
- for i, strategy in enumerate(parsing_strategies):
- try:
- result = strategy(cleaned_json)
- if result is not None:
- if i > 0: # Log if we had to use a fallback strategy
- app.logger.info(f"JSON parsed successfully using strategy {i+1}")
- return result
- except (json.JSONDecodeError, ValueError, SyntaxError) as e:
- if i == 0: # Only log the first failure to avoid spam
- app.logger.debug(f"JSON parsing strategy {i+1} failed: {e}")
- continue
-
- # All strategies failed
- app.logger.error(f"All JSON parsing strategies failed for: {cleaned_json[:200]}...")
- return fallback_value
+ # Owner uses the Recording model's global fields
+ if recording.user_id == user.id:
+ return (recording.is_inbox, recording.is_highlighted)
-def preprocess_json_escapes(json_string):
- """
- Preprocess JSON string to fix common escape issues from LLM responses.
- Uses a more sophisticated approach to handle nested quotes properly.
- """
- if not json_string:
- return json_string
-
- result = []
- i = 0
- in_string = False
- escape_next = False
- expecting_value = False # Track if we're expecting a value (after :)
-
- while i < len(json_string):
- char = json_string[i]
-
- if escape_next:
- # This character is escaped, add it as-is
- result.append(char)
- escape_next = False
- elif char == '\\':
- # This is an escape character
- result.append(char)
- escape_next = True
- elif char == ':' and not in_string:
- # We found a colon, next string will be a value
- result.append(char)
- expecting_value = True
- elif char == ',' and not in_string:
- # We found a comma, reset expecting_value
- result.append(char)
- expecting_value = False
- elif char == '"':
- if not in_string:
- # Starting a string
- in_string = True
- result.append(char)
- else:
- # We're in a string, check if this quote should be escaped
- # Look ahead to see if this is the end of the string value
- j = i + 1
- while j < len(json_string) and json_string[j].isspace():
- j += 1
-
- # For keys (not expecting_value), only end on colon
- # For values (expecting_value), end on comma, closing brace, or closing bracket
- if expecting_value:
- end_chars = ',}]'
- else:
- end_chars = ':'
-
- if j < len(json_string) and json_string[j] in end_chars:
- # This is the end of the string
- in_string = False
- result.append(char)
- if not expecting_value:
- # We just finished a key, next will be expecting value
- expecting_value = True
- else:
- # This is an inner quote that should be escaped
- result.append('\\"')
- else:
- result.append(char)
-
- i += 1
-
- return ''.join(result)
+ # Shared recipient uses SharedRecordingState
+ state = SharedRecordingState.query.filter_by(
+ recording_id=recording.id,
+ user_id=user.id
+ ).first()
-def extract_json_object(text):
- """
- Extract the first complete JSON object or array from text using regex.
- """
- # Look for JSON object
- obj_match = re.search(r'\{.*\}', text, re.DOTALL)
- if obj_match:
- return obj_match.group(0)
-
- # Look for JSON array
- arr_match = re.search(r'\[.*\]', text, re.DOTALL)
- if arr_match:
- return arr_match.group(0)
-
- # Return original if no JSON structure found
- return text
+ if state:
+ return (state.is_inbox, state.is_highlighted)
+ else:
+ # Return defaults if no state exists yet (inbox=True, highlighted=False)
+ return (True, False)
-# Initialize Flask-Bcrypt
-bcrypt = Bcrypt()
-# Helper function to convert markdown to HTML
-def sanitize_html(text):
+def set_user_recording_status(recording, user, is_inbox=None, is_highlighted=None):
"""
- Sanitize HTML content to prevent XSS attacks and code execution.
- This function removes dangerous content while preserving safe formatting.
- """
- if not text:
- return ""
-
- # First, remove any template syntax that could be dangerous
- # Remove Jinja2/Flask template syntax
- text = re.sub(r'\{\{.*?\}\}', '', text, flags=re.DOTALL)
- text = re.sub(r'\{%.*?%\}', '', text, flags=re.DOTALL)
-
- # Remove other template-like syntax
- text = re.sub(r'<%.*?%>', '', text, flags=re.DOTALL)
- text = re.sub(r'<\?.*?\?>', '', text, flags=re.DOTALL)
-
- # Define allowed tags and attributes for safe HTML
- allowed_tags = [
- 'p', 'br', 'strong', 'b', 'em', 'i', 'u', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
- 'ul', 'ol', 'li', 'blockquote', 'code', 'pre', 'a', 'img', 'table', 'thead',
- 'tbody', 'tr', 'th', 'td', 'dl', 'dt', 'dd', 'div', 'span', 'hr', 'sup', 'sub'
- ]
-
- allowed_attributes = {
- 'a': ['href', 'title'],
- 'img': ['src', 'alt', 'title', 'width', 'height'],
- 'code': ['class'], # For syntax highlighting
- 'pre': ['class'], # For syntax highlighting
- 'div': ['class'], # For code blocks
- 'span': ['class'], # For syntax highlighting
- 'th': ['align'],
- 'td': ['align'],
- 'table': ['class']
- }
-
- # Sanitize the HTML to remove dangerous content
- sanitized_html = bleach.clean(
- text,
- tags=allowed_tags,
- attributes=allowed_attributes,
- protocols=['http', 'https', 'mailto'],
- strip=True # Strip disallowed tags instead of escaping them
- )
-
- return sanitized_html
+ Set the inbox and/or highlighted status for a recording from a user's perspective.
-def md_to_html(text):
- if not text:
- return ""
-
- # Fix list spacing
- def fix_list_spacing(text):
- lines = text.split('\n')
- result = []
- in_list = False
-
- for line in lines:
- stripped = line.strip()
-
- # Check if this line is a list item (starts with -, *, +, or number.)
- is_list_item = (
- stripped.startswith(('- ', '* ', '+ ')) or
- (stripped and stripped[0].isdigit() and '. ' in stripped[:10])
- )
-
- # If we're starting a new list or continuing a list, ensure proper spacing
- if is_list_item:
- if not in_list and result and result[-1].strip():
- # Starting a new list - add blank line before
- result.append('')
- in_list = True
- elif in_list and stripped and not is_list_item:
- # Ending a list - add blank line after the list
- if result and result[-1].strip():
- result.append('')
- in_list = False
-
- result.append(line)
-
- return '\n'.join(result)
-
- # Fix list spacing
- processed_text = fix_list_spacing(text)
-
- # Convert markdown to HTML with extensions for tables, code highlighting, etc.
- html = markdown.markdown(processed_text, extensions=[
- 'fenced_code', # Fenced code blocks
- 'tables', # Table support
- 'attr_list', # Attribute lists
- 'def_list', # Definition lists
- 'footnotes', # Footnotes
- 'abbr', # Abbreviations
- 'codehilite', # Syntax highlighting for code blocks
- 'smarty' # Smart quotes, dashes, etc.
- ])
-
- # Apply sanitization to the generated HTML
- return sanitize_html(html)
+ For owners: Updates Recording model
+ For shared recipients: Updates or creates SharedRecordingState
-def format_transcription_for_llm(transcription_text):
- """
- Formats transcription for LLM. If it's our simplified JSON, convert it to plain text.
- Otherwise, return as is.
- """
- try:
- transcription_data = json.loads(transcription_text)
- if isinstance(transcription_data, list):
- # It's our simplified JSON format
- formatted_lines = []
- for segment in transcription_data:
- speaker = segment.get('speaker', 'Unknown Speaker')
- sentence = segment.get('sentence', '')
- formatted_lines.append(f"[{speaker}]: {sentence}")
- return "\n".join(formatted_lines)
- except (json.JSONDecodeError, TypeError):
- # Not a JSON, or not the format we expect, so return as is.
- pass
- return transcription_text
+ Args:
+ recording: Recording object
+ user: User object (typically current_user)
+ is_inbox: Boolean or None (None means don't change)
+ is_highlighted: Boolean or None (None means don't change)
-def clean_llm_response(text):
- """
- Clean LLM responses by removing thinking tags and excessive whitespace.
- This handles responses from reasoning models that include <think> tags.
- """
- if not text:
- return ""
-
- # Remove thinking tags and their content
- # Handle both <think> and <thinking> tags with various closing formats
- cleaned = re.sub(r'<think(?:ing)?>.*?</think(?:ing)?>', '', text, flags=re.DOTALL | re.IGNORECASE)
-
- # Also handle unclosed thinking tags (in case the model doesn't close them)
- cleaned = re.sub(r'<think(?:ing)?>.*$', '', cleaned, flags=re.DOTALL | re.IGNORECASE)
-
- # Remove any remaining XML-like tags that might be related to thinking
- # but preserve markdown formatting
- cleaned = re.sub(r'<(?!/?(?:code|pre|blockquote|p|br|hr|ul|ol|li|h[1-6]|em|strong|b|i|a|img)(?:\s|>|/))[^>]+>', '', cleaned)
-
- # Clean up excessive whitespace while preserving intentional formatting
- # Remove leading/trailing whitespace from each line
- lines = cleaned.split('\n')
- cleaned_lines = []
- for line in lines:
- # Preserve lines that are part of code blocks or lists
- if line.strip() or (len(cleaned_lines) > 0 and cleaned_lines[-1].strip().startswith(('```', '-', '*', '1.', '2.', '3.', '4.', '5.', '6.', '7.', '8.', '9.'))):
- cleaned_lines.append(line.rstrip())
-
- # Join lines and remove multiple consecutive blank lines
- cleaned = '\n'.join(cleaned_lines)
- cleaned = re.sub(r'\n{3,}', '\n\n', cleaned)
-
- # Final strip to remove leading/trailing whitespace
- return cleaned.strip()
+ Returns:
+ Tuple of (is_inbox, is_highlighted) after update
+ """
+ # Owner updates the Recording model's global fields
+ if recording.user_id == user.id:
+ if is_inbox is not None:
+ recording.is_inbox = is_inbox
+ if is_highlighted is not None:
+ recording.is_highlighted = is_highlighted
+ db.session.commit()
+ return (recording.is_inbox, recording.is_highlighted)
-def extract_thinking_content(text):
- """
- Extract thinking content from LLM responses.
- Returns a tuple of (thinking_content, main_content).
- """
- if not text:
- return ("", "")
-
- # Find all thinking tags and their content
- thinking_pattern = r'<think(?:ing)?>.*?</think(?:ing)?>'
- thinking_matches = re.findall(thinking_pattern, text, flags=re.DOTALL | re.IGNORECASE)
-
- # Extract the content from within the tags
- thinking_content = ""
- for match in thinking_matches:
- # Remove the opening and closing tags
- content = re.sub(r'^<think(?:ing)?>', '', match, flags=re.IGNORECASE)
- content = re.sub(r'</think(?:ing)?>$', '', content, flags=re.IGNORECASE)
- if thinking_content:
- thinking_content += "\n\n"
- thinking_content += content.strip()
-
- # Get the main content by removing thinking tags
- main_content = clean_llm_response(text)
-
- return (thinking_content, main_content)
+ # Shared recipient uses SharedRecordingState
+ state = SharedRecordingState.query.filter_by(
+ recording_id=recording.id,
+ user_id=user.id
+ ).first()
-def process_streaming_with_thinking(stream):
+ if not state:
+ # Create new state with defaults
+ state = SharedRecordingState(
+ recording_id=recording.id,
+ user_id=user.id,
+ is_inbox=True,
+ is_highlighted=False
+ )
+ db.session.add(state)
+
+ # Update the requested fields
+ if is_inbox is not None:
+ state.is_inbox = is_inbox
+ if is_highlighted is not None:
+ state.is_highlighted = is_highlighted
+
+ db.session.commit()
+ return (state.is_inbox, state.is_highlighted)
+
+
+def enrich_recording_dict_with_user_status(recording_dict, recording, user):
"""
- Generator that processes a streaming response and separates thinking content.
- Yields SSE-formatted data with 'delta' for regular content and 'thinking' for thinking content.
+ Enrich a recording dictionary with per-user status (inbox, highlighted).
+
+ This should be called after recording.to_dict() or recording.to_list_dict()
+ to replace the owner's status with the current user's per-user status.
+
+ Args:
+ recording_dict: Dictionary from recording.to_dict() or recording.to_list_dict()
+ recording: Recording object
+ user: User object (typically current_user)
+
+ Returns:
+ The enriched recording_dict (modified in place, but also returned for convenience)
"""
- content_buffer = ""
- in_thinking = False
- thinking_buffer = ""
-
- for chunk in stream:
- content = chunk.choices[0].delta.content
- if content:
- content_buffer += content
-
- # Process the buffer to detect and handle thinking tags
- while True:
- if not in_thinking:
- # Look for opening thinking tag
- think_start = re.search(r'<think(?:ing)?>', content_buffer, re.IGNORECASE)
- if think_start:
- # Send any content before the thinking tag
- before_thinking = content_buffer[:think_start.start()]
- if before_thinking:
- yield f"data: {json.dumps({'delta': before_thinking})}\n\n"
-
- # Start capturing thinking content
- in_thinking = True
- content_buffer = content_buffer[think_start.end():]
- thinking_buffer = ""
- else:
- # No thinking tag found, send accumulated content
- if content_buffer:
- yield f"data: {json.dumps({'delta': content_buffer})}\n\n"
- content_buffer = ""
- break
- else:
- # We're inside a thinking tag, look for closing tag
- think_end = re.search(r'</think(?:ing)?>', content_buffer, re.IGNORECASE)
- if think_end:
- # Capture thinking content up to the closing tag
- thinking_buffer += content_buffer[:think_end.start()]
-
- # Send the thinking content as a special type
- if thinking_buffer.strip():
- yield f"data: {json.dumps({'thinking': thinking_buffer.strip()})}\n\n"
-
- # Continue processing after the closing tag
- in_thinking = False
- content_buffer = content_buffer[think_end.end():]
- thinking_buffer = ""
- else:
- # Still inside thinking tag, accumulate content
- thinking_buffer += content_buffer
- content_buffer = ""
- break
-
- # Handle any remaining content
- if in_thinking and thinking_buffer:
- # Unclosed thinking tag - send as thinking content
- yield f"data: {json.dumps({'thinking': thinking_buffer.strip()})}\n\n"
- elif content_buffer:
- # Regular content
- yield f"data: {json.dumps({'delta': content_buffer})}\n\n"
-
- # Signal the end of the stream
- yield f"data: {json.dumps({'end_of_stream': True})}\n\n"
+ user_inbox, user_highlighted = get_user_recording_status(recording, user)
+ recording_dict['is_inbox'] = user_inbox
+ recording_dict['is_highlighted'] = user_highlighted
+ return recording_dict
+
app = Flask(__name__,
template_folder='../templates',
@@ -581,14 +359,58 @@ app.config['SESSION_COOKIE_SECURE'] = False # Allow HTTP for local network usag
app.config['SESSION_COOKIE_HTTPONLY'] = True # Still protect against XSS
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax' # CSRF protection
-db = SQLAlchemy()
+# Import database instance from extracted module
+from src.database import db
db.init_app(app)
+# Import all models from extracted modules
+from src.models import (
+ User, Speaker, Recording, TranscriptChunk, Share, InternalShare,
+ SharedRecordingState, Group, GroupMembership, Tag, RecordingTag,
+ Event, TranscriptTemplate, InquireSession, SystemSetting
+)
+
+# Import utility functions from extracted modules
+from src.utils import (
+ auto_close_json, safe_json_loads, preprocess_json_escapes, extract_json_object,
+ md_to_html, sanitize_html, local_datetime_filter, password_check,
+ add_column_if_not_exists, is_safe_url
+)
+
+# Import service layer functions
+from src.services.embeddings import (
+ get_embedding_model, chunk_transcription, generate_embeddings,
+ serialize_embedding, deserialize_embedding, get_accessible_recording_ids,
+ process_recording_chunks, basic_text_search_chunks, semantic_search_chunks
+)
+from src.services.llm import (
+ is_gpt5_model, is_using_openai_api, call_llm_completion, format_api_error_message
+)
+from src.services.document import process_markdown_to_docx
+from src.services.retention import (
+ is_recording_exempt_from_deletion, get_retention_days_for_recording, process_auto_deletion
+)
+from src.services.calendar import generate_ics_content, escape_ical_text
+from src.services.speaker import (
+ update_speaker_usage, identify_speakers_from_text, identify_unidentified_speakers_from_text
+)
+
+# Import background task functions
+from src.tasks.processing import (
+ generate_title_task, generate_summary_only_task, extract_events_from_transcript,
+ extract_audio_from_video, transcribe_audio_asr, transcribe_audio_task,
+ transcribe_single_file, transcribe_with_chunking
+)
+
+# Import configuration helpers
+from src.config.version import get_version
+
# Initialize Flask-Login and other extensions
login_manager = LoginManager()
login_manager.init_app(app)
-login_manager.login_view = 'login'
+login_manager.login_view = 'auth.login'
login_manager.login_message_category = 'info'
+bcrypt = Bcrypt()
bcrypt.init_app(app)
limiter.init_app(app) # Initialize the limiter (uses in-memory storage by default)
@@ -599,6 +421,21 @@ csrf = CSRFProtect(app)
def inject_now():
return {'now': datetime.now()}
+def inject_group_admin_status():
+ """Inject is_group_admin flag into all templates."""
+ from flask_login import current_user
+ from src.models.organization import GroupMembership
+
+ is_group_admin = False
+ if current_user.is_authenticated:
+ is_group_admin = GroupMembership.query.filter_by(
+ user_id=current_user.id,
+ role='admin'
+ ).first() is not None
+
+ return {'is_group_admin': is_group_admin}
+
# --- Timezone Formatting Filter ---
@app.template_filter('localdatetime')
def local_datetime_filter(dt):
@@ -640,7165 +477,84 @@ def load_user(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 []
-
-# --- Helper Functions for Document Processing ---
-
-def process_markdown_to_docx(doc, content):
- """Convert markdown content to properly formatted Word document elements.
-
- Supports:
- - Tables (markdown pipe tables)
- - Headings (# ## ###)
- - Bold text (**text**)
- - Italic text (*text* or _text_)
- - Bold italic (***text***)
- - Inline code (`code`)
- - Code blocks (```code```)
- - Strikethrough (~~text~~)
- - Links ([text](url))
- - Bullet lists (- or *)
- - Numbered lists (1. 2. 3.)
- - Horizontal rules (--- or ***)
- """
- from docx.shared import RGBColor, Pt
- from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
- from docx.oxml.ns import qn
- import re
-
- def ensure_unicode_font(run, text):
- """Ensure the run uses a font that supports the characters in the text."""
- # Check if text contains non-ASCII characters
- try:
- text.encode('ascii')
- # Text is pure ASCII, no special font needed
- except UnicodeEncodeError:
- # Text contains non-ASCII characters, use a font with better Unicode support
- # Use Arial for broad compatibility - it has good Unicode support on most systems
- run.font.name = 'Arial'
- # Set the East Asian font for CJK (Chinese, Japanese, Korean) text
- # This ensures proper rendering in Word
- r = run._element
- r.rPr.rFonts.set(qn('w:eastAsia'), 'Arial')
- return run
-
- def add_formatted_run(paragraph, text):
- """Add a run with inline formatting to a paragraph."""
- if not text:
- return
-
- # Pattern for all inline formatting
- # Order matters: check triple asterisk before double/single
- patterns = [
- (r'\*\*\*(.*?)\*\*\*', lambda p, t: (lambda r: (setattr(r, 'bold', True), setattr(r, 'italic', True), ensure_unicode_font(r, t)))(p.add_run(t))), # Bold italic
- (r'\*\*(.*?)\*\*', lambda p, t: (lambda r: (setattr(r, 'bold', True), ensure_unicode_font(r, t)))(p.add_run(t))), # Bold
- (r'(?<!\*)\*(?!\*)(.*?)\*(?!\*)', lambda p, t: (lambda r: (setattr(r, 'italic', True), ensure_unicode_font(r, t)))(p.add_run(t))), # Italic with *
- (r'\b_(.*?)_\b', lambda p, t: (lambda r: (setattr(r, 'italic', True), ensure_unicode_font(r, t)))(p.add_run(t))), # Italic with _
- (r'~~(.*?)~~', lambda p, t: (lambda r: (setattr(r, 'strike', True), ensure_unicode_font(r, t)))(p.add_run(t))), # Strikethrough
- (r'`([^`]+)`', lambda p, t: add_code_run(p, t)), # Inline code
- (r'\[([^\]]+)\]\(([^)]+)\)', lambda p, t, u: add_link_run(p, t, u)), # Links
- ]
-
- def add_code_run(para, text):
- """Add inline code with monospace font and background."""
- run = para.add_run(text)
- run.font.name = 'Courier New'
- run.font.size = Pt(10)
- run.font.color.rgb = RGBColor(220, 20, 60) # Crimson color for code
- # Check if we need Unicode support for code
- try:
- text.encode('ascii')
- except UnicodeEncodeError:
- # Use Consolas as fallback for better Unicode support in monospace
- r = run._element
- r.rPr.rFonts.set(qn('w:eastAsia'), 'Consolas')
- return run
-
- def add_link_run(para, text, url):
- """Add a hyperlink-styled run (note: actual hyperlinks require more complex handling)."""
- full_text = f"{text} ({url})"
- run = para.add_run(full_text)
- run.font.color.rgb = RGBColor(0, 0, 255) # Blue color for links
- run.font.underline = True
- ensure_unicode_font(run, full_text)
- return run
-
- # Process the text with all patterns
- remaining_text = text
- while remaining_text:
- earliest_match = None
- earliest_pos = len(remaining_text)
- matched_pattern = None
-
- # Find the earliest matching pattern
- for pattern, handler in patterns:
- match = re.search(pattern, remaining_text)
- if match and match.start() < earliest_pos:
- earliest_match = match
- earliest_pos = match.start()
- matched_pattern = handler
-
- if earliest_match:
- # Add text before the match
- if earliest_pos > 0:
- run = paragraph.add_run(remaining_text[:earliest_pos])
- ensure_unicode_font(run, remaining_text[:earliest_pos])
-
- # Apply formatting for the matched text
- if '[' in earliest_match.group(0) and '](' in earliest_match.group(0):
- # Special handling for links (two groups)
- matched_pattern(paragraph, earliest_match.group(1), earliest_match.group(2))
- else:
- matched_pattern(paragraph, earliest_match.group(1))
-
- # Continue with remaining text
- remaining_text = remaining_text[earliest_match.end():]
- else:
- # No more patterns, add the rest as plain text
- run = paragraph.add_run(remaining_text)
- ensure_unicode_font(run, remaining_text)
- break
-
- def parse_table(lines, start_idx):
- """Parse a markdown table starting at the given index."""
- if start_idx >= len(lines):
- return None, start_idx
-
- # Check if this looks like a table
- if '|' not in lines[start_idx]:
- return None, start_idx
-
- table_data = []
- idx = start_idx
-
- while idx < len(lines) and '|' in lines[idx]:
- # Skip separator lines
- if re.match(r'^[\s\|\-:]+$', lines[idx]):
- idx += 1
- continue
-
- # Parse cells
- cells = [cell.strip() for cell in lines[idx].split('|')]
- # Remove empty cells at start and end
- if cells and not cells[0]:
- cells = cells[1:]
- if cells and not cells[-1]:
- cells = cells[:-1]
-
- if cells:
- table_data.append(cells)
- idx += 1
-
- if table_data:
- return table_data, idx
- return None, start_idx
-
- # Split content into lines
- lines = content.split('\n')
- i = 0
- in_code_block = False
- code_block_content = []
-
- while i < len(lines):
- line = lines[i]
-
- # Handle code blocks
- if line.strip().startswith('```'):
- if not in_code_block:
- in_code_block = True
- code_block_content = []
- else:
- # End of code block - add it as preformatted text
- in_code_block = False
- if code_block_content:
- p = doc.add_paragraph()
- p.style = 'Normal'
- code_text = '\n'.join(code_block_content)
- run = p.add_run(code_text)
- run.font.name = 'Courier New'
- run.font.size = Pt(10)
- run.font.color.rgb = RGBColor(64, 64, 64)
- # Check if we need Unicode support for code blocks
- try:
- code_text.encode('ascii')
- except UnicodeEncodeError:
- r = run._element
- r.rPr.rFonts.set(qn('w:eastAsia'), 'Consolas')
- i += 1
- continue
-
- if in_code_block:
- code_block_content.append(line)
- i += 1
- continue
-
- # Check for table
- table_data, end_idx = parse_table(lines, i)
- if table_data:
- # Create Word table
- table = doc.add_table(rows=len(table_data), cols=len(table_data[0]))
- table.style = 'Table Grid'
-
- # Populate table
- for row_idx, row_data in enumerate(table_data):
- for col_idx, cell_text in enumerate(row_data):
- if col_idx < len(table.rows[row_idx].cells):
- cell = table.rows[row_idx].cells[col_idx]
- # Clear existing paragraphs and add new one
- cell.text = ""
- p = cell.add_paragraph()
- add_formatted_run(p, cell_text)
- # Make header row bold
- if row_idx == 0:
- for run in p.runs:
- run.bold = True
-
- doc.add_paragraph('') # Space after table
- i = end_idx
- continue
-
- line = line.rstrip()
-
- # Skip empty lines
- if not line:
- doc.add_paragraph('')
- i += 1
- continue
-
- # Horizontal rule
- if re.match(r'^(\*{3,}|-{3,}|_{3,})$', line.strip()):
- p = doc.add_paragraph('─' * 50)
- p.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
- i += 1
- continue
-
- # Headings
- if line.startswith('# '):
- doc.add_heading(line[2:], 1)
- elif line.startswith('## '):
- doc.add_heading(line[3:], 2)
- elif line.startswith('### '):
- doc.add_heading(line[4:], 3)
- elif line.startswith('#### '):
- doc.add_heading(line[5:], 4)
- # Bullet points
- elif line.lstrip().startswith('- ') or line.lstrip().startswith('* '):
- # Get the indentation level
- indent = len(line) - len(line.lstrip())
- bullet_text = line.lstrip()[2:]
- p = doc.add_paragraph(style='List Bullet')
- # Add indentation if nested
- if indent > 0:
- p.paragraph_format.left_indent = Pt(indent * 10)
- add_formatted_run(p, bullet_text)
- # Numbered lists
- elif re.match(r'^\s*\d+\.', line):
- match = re.match(r'^(\s*)(\d+)\.\s*(.*)', line)
- if match:
- indent = len(match.group(1))
- list_text = match.group(3)
- p = doc.add_paragraph(style='List Number')
- if indent > 0:
- p.paragraph_format.left_indent = Pt(indent * 10)
- add_formatted_run(p, list_text)
- # Blockquote
- elif line.startswith('> '):
- p = doc.add_paragraph()
- p.paragraph_format.left_indent = Pt(30)
- add_formatted_run(p, line[2:])
- # Add a gray color to indicate quote
- for run in p.runs:
- run.font.color.rgb = RGBColor(100, 100, 100)
- else:
- # Regular paragraph
- p = doc.add_paragraph()
- add_formatted_run(p, line)
-
- i += 1
-
-# --- Database Models ---
-class User(db.Model, UserMixin):
- id = db.Column(db.Integer, primary_key=True)
- username = db.Column(db.String(20), unique=True, nullable=False)
- email = db.Column(db.String(120), unique=True, nullable=False)
- password = db.Column(db.String(60), nullable=False)
- is_admin = db.Column(db.Boolean, default=False)
- recordings = db.relationship('Recording', backref='owner', lazy=True)
- transcription_language = db.Column(db.String(10), nullable=True) # For ISO 639-1 codes
- output_language = db.Column(db.String(50), nullable=True) # For full language names like "Spanish"
- ui_language = db.Column(db.String(10), nullable=True, default='en') # For UI language preference (en, es, fr, zh)
- summary_prompt = db.Column(db.Text, nullable=True)
- extract_events = db.Column(db.Boolean, default=False) # Enable event extraction from transcripts
- name = db.Column(db.String(100), nullable=True)
- job_title = db.Column(db.String(100), nullable=True)
- company = db.Column(db.String(100), nullable=True)
- diarize = db.Column(db.Boolean, default=False)
-
- def __repr__(self):
- return f"User('{self.username}', '{self.email}')"
-class Speaker(db.Model):
- id = db.Column(db.Integer, primary_key=True)
- name = db.Column(db.String(100), nullable=False)
- user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
- created_at = db.Column(db.DateTime, default=datetime.utcnow)
- last_used = db.Column(db.DateTime, default=datetime.utcnow)
- use_count = db.Column(db.Integer, default=1)
-
- # Relationship to user
- user = db.relationship('User', backref=db.backref('speakers', lazy=True, cascade='all, delete-orphan'))
-
- def to_dict(self):
- return {
- 'id': self.id,
- 'name': self.name,
- 'created_at': self.created_at,
- 'last_used': self.last_used,
- 'use_count': self.use_count
- }
-
-class SystemSetting(db.Model):
- id = db.Column(db.Integer, primary_key=True)
- key = db.Column(db.String(100), unique=True, nullable=False)
- value = db.Column(db.Text, nullable=True)
- description = db.Column(db.Text, nullable=True)
- setting_type = db.Column(db.String(50), nullable=False, default='string') # string, integer, boolean, float
- created_at = db.Column(db.DateTime, default=datetime.utcnow)
- updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
-
- def to_dict(self):
- return {
- 'id': self.id,
- 'key': self.key,
- 'value': self.value,
- 'description': self.description,
- 'setting_type': self.setting_type,
- 'created_at': self.created_at,
- 'updated_at': self.updated_at
- }
-
- @staticmethod
- def get_setting(key, default_value=None):
- """Get a system setting value by key, with optional default."""
- setting = SystemSetting.query.filter_by(key=key).first()
- if setting:
- # Convert value based on type
- if setting.setting_type == 'integer':
- try:
- return int(setting.value) if setting.value is not None else default_value
- except (ValueError, TypeError):
- return default_value
- elif setting.setting_type == 'boolean':
- return setting.value.lower() in ('true', '1', 'yes') if setting.value else default_value
- elif setting.setting_type == 'float':
- try:
- return float(setting.value) if setting.value is not None else default_value
- except (ValueError, TypeError):
- return default_value
- else: # string
- return setting.value if setting.value is not None else default_value
- return default_value
-
- @staticmethod
- def set_setting(key, value, description=None, setting_type='string'):
- """Set a system setting value."""
- setting = SystemSetting.query.filter_by(key=key).first()
- if setting:
- setting.value = str(value) if value is not None else None
- setting.updated_at = datetime.utcnow()
- if description:
- setting.description = description
- if setting_type:
- setting.setting_type = setting_type
- else:
- setting = SystemSetting(
- key=key,
- value=str(value) if value is not None else None,
- description=description,
- setting_type=setting_type
- )
- db.session.add(setting)
- db.session.commit()
- return setting
-
-# Many-to-many relationship table for recordings and tags
-class RecordingTag(db.Model):
- __tablename__ = 'recording_tags'
- recording_id = db.Column(db.Integer, db.ForeignKey('recording.id'), primary_key=True)
- tag_id = db.Column(db.Integer, db.ForeignKey('tag.id'), primary_key=True)
- added_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=True)
- order = db.Column(db.Integer, nullable=False, default=0)
-
- # Relationships
- recording = db.relationship('Recording', back_populates='tag_associations')
- tag = db.relationship('Tag', back_populates='recording_associations')
-
-class Tag(db.Model):
- id = db.Column(db.Integer, primary_key=True)
- name = db.Column(db.String(50), nullable=False)
- user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
- color = db.Column(db.String(7), default='#3B82F6') # Hex color for UI
-
- # Custom settings for this tag
- custom_prompt = db.Column(db.Text, nullable=True) # Custom summarization prompt
- default_language = db.Column(db.String(10), nullable=True) # Default transcription language
- default_min_speakers = db.Column(db.Integer, nullable=True) # Default min speakers for ASR
- default_max_speakers = db.Column(db.Integer, nullable=True) # Default max speakers for ASR
-
- created_at = db.Column(db.DateTime, default=datetime.utcnow)
- updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
-
- # Relationships
- user = db.relationship('User', backref=db.backref('tags', lazy=True, cascade='all, delete-orphan'))
- # Use association object for many-to-many with order tracking
- recording_associations = db.relationship('RecordingTag', back_populates='tag', cascade='all, delete-orphan')
-
- # Unique constraint: tag name must be unique per user
- __table_args__ = (db.UniqueConstraint('name', 'user_id', name='_user_tag_uc'),)
-
- def to_dict(self):
- return {
- 'id': self.id,
- 'name': self.name,
- 'color': self.color,
- 'custom_prompt': self.custom_prompt,
- 'default_language': self.default_language,
- 'default_min_speakers': self.default_min_speakers,
- 'default_max_speakers': self.default_max_speakers,
- 'created_at': self.created_at.isoformat() if self.created_at else None,
- 'recording_count': len(self.recording_associations)
- }
-
-class Event(db.Model):
- id = db.Column(db.Integer, primary_key=True)
- recording_id = db.Column(db.Integer, db.ForeignKey('recording.id'), nullable=False)
- title = db.Column(db.String(200), nullable=False)
- description = db.Column(db.Text, nullable=True)
- start_datetime = db.Column(db.DateTime, nullable=False)
- end_datetime = db.Column(db.DateTime, nullable=True)
- location = db.Column(db.String(500), nullable=True)
- attendees = db.Column(db.Text, nullable=True) # JSON list of attendees
- reminder_minutes = db.Column(db.Integer, nullable=True, default=15)
- created_at = db.Column(db.DateTime, default=datetime.utcnow)
-
- # Relationship
- recording = db.relationship('Recording', backref=db.backref('events', lazy=True, cascade='all, delete-orphan'))
-
- def to_dict(self):
- return {
- 'id': self.id,
- 'recording_id': self.recording_id,
- 'title': self.title,
- 'description': self.description,
- 'start_datetime': self.start_datetime.isoformat() if self.start_datetime else None,
- 'end_datetime': self.end_datetime.isoformat() if self.end_datetime else None,
- 'location': self.location,
- 'attendees': json.loads(self.attendees) if self.attendees else [],
- 'reminder_minutes': self.reminder_minutes,
- 'created_at': self.created_at.isoformat() if self.created_at else None
- }
-
-class Share(db.Model):
- id = db.Column(db.Integer, primary_key=True)
- public_id = db.Column(db.String(32), unique=True, nullable=False, default=lambda: secrets.token_urlsafe(16))
- recording_id = db.Column(db.Integer, db.ForeignKey('recording.id'), nullable=False)
- user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
- created_at = db.Column(db.DateTime, default=datetime.utcnow)
- share_summary = db.Column(db.Boolean, default=True)
- share_notes = db.Column(db.Boolean, default=True)
-
- user = db.relationship('User', backref=db.backref('shares', lazy=True, cascade='all, delete-orphan'))
- recording = db.relationship('Recording', backref=db.backref('shares', lazy=True, cascade='all, delete-orphan'))
-
- def to_dict(self):
- return {
- 'id': self.id,
- 'public_id': self.public_id,
- 'recording_id': self.recording_id,
- 'created_at': local_datetime_filter(self.created_at),
- 'share_summary': self.share_summary,
- 'share_notes': self.share_notes,
- 'recording_title': self.recording.title if self.recording else "N/A"
- }
-
-class Recording(db.Model):
- # Add user_id foreign key to associate recordings with users
- user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True)
- id = db.Column(db.Integer, primary_key=True)
- # Title will now often be AI-generated, maybe start with filename?
- title = db.Column(db.String(200), nullable=True) # Allow Null initially
- participants = db.Column(db.String(500))
- notes = db.Column(db.Text)
- transcription = db.Column(db.Text, nullable=True)
- summary = db.Column(db.Text, nullable=True) # <-- ADDED: Summary field
- status = db.Column(db.String(50), default='PENDING') # PENDING, PROCESSING, SUMMARIZING, COMPLETED, FAILED
- audio_path = db.Column(db.String(500))
- created_at = db.Column(db.DateTime, default=datetime.utcnow)
- meeting_date = db.Column(db.Date, nullable=True) # <-- ADDED: Meeting Date field
- file_size = db.Column(db.Integer) # Store file size in bytes
- original_filename = db.Column(db.String(500), nullable=True) # Store the original uploaded filename
- is_inbox = db.Column(db.Boolean, default=True) # New recordings are marked as inbox by default
- is_highlighted = db.Column(db.Boolean, default=False) # Recordings can be highlighted by the user
- mime_type = db.Column(db.String(100), nullable=True)
- completed_at = db.Column(db.DateTime, nullable=True)
- processing_time_seconds = db.Column(db.Integer, nullable=True)
- processing_source = db.Column(db.String(50), default='upload') # upload, auto_process, recording
- error_message = db.Column(db.Text, nullable=True) # Store detailed error messages
-
- # Relationships
- tag_associations = db.relationship('RecordingTag', back_populates='recording', cascade='all, delete-orphan', order_by='RecordingTag.order')
-
- @property
- def tags(self):
- """Get tags ordered by the order they were added to this recording."""
- return [assoc.tag for assoc in sorted(self.tag_associations, key=lambda x: x.order)]
-
- def to_dict(self):
- return {
- 'id': self.id,
- 'title': self.title,
- 'participants': self.participants,
- 'notes': self.notes,
- 'notes_html': md_to_html(self.notes) if self.notes else "",
- 'transcription': self.transcription,
- 'summary': self.summary,
- 'summary_html': md_to_html(self.summary) if self.summary else "",
- 'status': self.status,
- 'created_at': local_datetime_filter(self.created_at),
- 'completed_at': local_datetime_filter(self.completed_at),
- 'processing_time_seconds': self.processing_time_seconds,
- 'meeting_date': f"{self.meeting_date.isoformat()}T00:00:00" if self.meeting_date else None, # <-- ADDED: Include meeting_date with time component
- 'file_size': self.file_size,
- 'original_filename': self.original_filename, # <-- ADDED: Include original filename
- 'user_id': self.user_id,
- 'is_inbox': self.is_inbox,
- 'is_highlighted': self.is_highlighted,
- 'mime_type': self.mime_type,
- 'tags': [tag.to_dict() for tag in self.tags] if self.tags else [],
- 'events': [event.to_dict() for event in self.events] if self.events 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 TranscriptTemplate(db.Model):
- """Stores user-defined templates for transcript formatting."""
- id = db.Column(db.Integer, primary_key=True)
- user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
- name = db.Column(db.String(100), nullable=False)
- template = db.Column(db.Text, nullable=False)
- description = db.Column(db.String(500), nullable=True)
- is_default = db.Column(db.Boolean, default=False)
- created_at = db.Column(db.DateTime, default=datetime.utcnow)
- updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
-
- # Relationships
- user = db.relationship('User', backref=db.backref('transcript_templates', lazy=True, cascade='all, delete-orphan'))
-
- def to_dict(self):
- return {
- 'id': self.id,
- 'name': self.name,
- 'template': self.template,
- 'description': self.description,
- 'is_default': self.is_default,
- 'created_at': self.created_at.isoformat() if self.created_at else None,
- 'updated_at': self.updated_at.isoformat() if self.updated_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):
- password = field.data
- if len(password) < 8:
- raise ValidationError('Password must be at least 8 characters long.')
- if not re.search(r'[A-Z]', password):
- raise ValidationError('Password must contain at least one uppercase letter.')
- if not re.search(r'[a-z]', password):
- raise ValidationError('Password must contain at least one lowercase letter.')
- if not re.search(r'[0-9]', password):
- raise ValidationError('Password must contain at least one number.')
- if not re.search(r'[!@#$%^&*(),.?":{}|<>]', password):
- raise ValidationError('Password must contain at least one special character.')
-
-# --- Share Routes ---
[email protected]('/share/<string:public_id>', methods=['GET'])
-def view_shared_recording(public_id):
- share = Share.query.filter_by(public_id=public_id).first_or_404()
- recording = share.recording
-
- # Create a limited dictionary for the public view
- recording_data = {
- 'id': recording.id,
- 'public_id': share.public_id,
- 'title': recording.title,
- 'participants': recording.participants,
- 'transcription': recording.transcription,
- 'summary': md_to_html(recording.summary) if share.share_summary else None,
- 'notes': md_to_html(recording.notes) if share.share_notes else None,
- 'meeting_date': f"{recording.meeting_date.isoformat()}T00:00:00" if recording.meeting_date else None,
- 'mime_type': recording.mime_type
- }
-
- return render_template('share.html', recording=recording_data)
+from src.api.auth import auth_bp, init_auth_extensions
+from src.api.shares import shares_bp, init_shares_helpers
+from src.api.recordings import recordings_bp, init_recordings_helpers
+from src.api.tags import tags_bp, init_tags_helpers
+from src.api.groups import groups_bp, init_groups_helpers
+from src.api.admin import admin_bp, init_admin_helpers
+from src.api.speakers import speakers_bp, init_speakers_helpers
+from src.api.inquire import inquire_bp, init_inquire_helpers
+from src.api.templates import templates_bp, init_templates_helpers
+from src.api.events import events_bp, init_events_helpers
+from src.api.system import system_bp, init_system_helpers
+
+# Database initialization (extracted to src/init_db.py)
+from src.init_db import initialize_database
+with app.app_context():
+ initialize_database(app)
+
+# Application configuration (extracted to src/config/app_config.py)
+from src.config.app_config import initialize_config
+client, chunking_service, version = initialize_config(app)
+
+# Initialize blueprint helpers (inject extensions and utility functions)
+init_auth_extensions(bcrypt, csrf, limiter)
+init_shares_helpers(has_recording_access)
+init_recordings_helpers(has_recording_access=has_recording_access, get_user_recording_status=get_user_recording_status, set_user_recording_status=set_user_recording_status, enrich_recording_dict_with_user_status=enrich_recording_dict_with_user_status, bcrypt=bcrypt, csrf=csrf, limiter=limiter, chunking_service=chunking_service)
+init_tags_helpers(has_recording_access=has_recording_access, bcrypt=bcrypt, csrf=csrf, limiter=limiter)
+init_groups_helpers(has_recording_access=has_recording_access, bcrypt=bcrypt, csrf=csrf, limiter=limiter)
+init_admin_helpers(has_recording_access=has_recording_access, bcrypt=bcrypt, csrf=csrf, limiter=limiter)
+init_speakers_helpers(has_recording_access=has_recording_access, bcrypt=bcrypt, csrf=csrf, limiter=limiter)
+init_inquire_helpers(has_recording_access=has_recording_access, bcrypt=bcrypt, csrf=csrf, limiter=limiter)
+init_templates_helpers(has_recording_access=has_recording_access, bcrypt=bcrypt, csrf=csrf, limiter=limiter)
+init_events_helpers(has_recording_access=has_recording_access, bcrypt=bcrypt, csrf=csrf, limiter=limiter)
+init_system_helpers(has_recording_access=has_recording_access, bcrypt=bcrypt, csrf=csrf, limiter=limiter, chunking_service=chunking_service)
+
+# Register blueprints
+app.register_blueprint(auth_bp)
+app.register_blueprint(shares_bp)
+app.register_blueprint(recordings_bp)
+app.register_blueprint(tags_bp)
+app.register_blueprint(groups_bp)
+app.register_blueprint(admin_bp)
+app.register_blueprint(speakers_bp)
+app.register_blueprint(inquire_bp)
+app.register_blueprint(templates_bp)
+app.register_blueprint(events_bp)
+app.register_blueprint(system_bp)
+
+# File monitor and scheduler initialization functions below
+
+# Startup functions (extracted to src/config/startup.py)
+from src.config.startup import initialize_file_monitor, get_file_monitor_functions, initialize_auto_deletion_scheduler, run_startup_tasks
+
+# Run startup tasks
+run_startup_tasks(app)
+
+# --- No-Crawl System: HTTP Headers ---
+def add_no_crawl_headers(response):
+ """
+ Add HTTP headers to discourage search engine crawling and indexing.
+ This provides defense-in-depth alongside robots.txt and meta tags.
+ """
+ response.headers['X-Robots-Tag'] = 'noindex, nofollow, noarchive, nosnippet, noimageindex'
+ return response
+
+# --- No-Crawl System: Serve robots.txt ---
[email protected]('/robots.txt')
+def robots_txt():
+ """Serve robots.txt to instruct crawlers not to index the site."""
+ return send_file(os.path.join(app.static_folder, 'robots.txt'), mimetype='text/plain')
[email protected]('/api/recording/<int:recording_id>/share', methods=['GET'])
-@login_required
-def get_existing_share(recording_id):
- """Check if a share already exists for this recording."""
- recording = db.session.get(Recording, recording_id)
- if not recording or recording.user_id != current_user.id:
- return jsonify({'error': 'Recording not found or you do not have permission to view it.'}), 404
-
- existing_share = Share.query.filter_by(
- recording_id=recording.id,
- user_id=current_user.id
- ).order_by(Share.created_at.desc()).first()
-
- if existing_share:
- share_url = url_for('view_shared_recording', public_id=existing_share.public_id, _external=True)
- return jsonify({
- 'success': True,
- 'exists': True,
- 'share_url': share_url,
- 'share': existing_share.to_dict()
- }), 200
- else:
- return jsonify({
- 'success': True,
- 'exists': False
- }), 200
+if __name__ == '__main__':
+ import argparse
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--debug', action='store_true', help='Run in debug mode')
+ args = parser.parse_args()
[email protected]('/api/recording/<int:recording_id>/share', methods=['POST'])
-@login_required
-def create_share(recording_id):
- if not request.is_secure:
- return jsonify({'error': 'Sharing is only available over a secure (HTTPS) connection.'}), 403
-
- recording = db.session.get(Recording, recording_id)
- if not recording or recording.user_id != current_user.id:
- return jsonify({'error': 'Recording not found or you do not have permission to share it.'}), 404
-
- data = request.json
- share_summary = data.get('share_summary', True)
- share_notes = data.get('share_notes', True)
- force_new = data.get('force_new', False)
-
- # Check if ANY share already exists for this recording by this user
- # Get the most recent one if there are multiple
- existing_share = Share.query.filter_by(
- recording_id=recording.id,
- user_id=current_user.id
- ).order_by(Share.created_at.desc()).first()
-
- if existing_share and not force_new:
- # Update the share permissions if they've changed
- if existing_share.share_summary != share_summary or existing_share.share_notes != share_notes:
- existing_share.share_summary = share_summary
- existing_share.share_notes = share_notes
- db.session.commit()
-
- # Return existing share info
- share_url = url_for('view_shared_recording', public_id=existing_share.public_id, _external=True)
- return jsonify({
- 'success': True,
- 'share_url': share_url,
- 'share': existing_share.to_dict(),
- 'existing': True,
- 'message': 'Using existing share link for this recording'
- }), 200
-
- # Create new share (either no existing share or force_new is True)
- share = Share(
- recording_id=recording.id,
- user_id=current_user.id,
- share_summary=share_summary,
- share_notes=share_notes
- )
- db.session.add(share)
- db.session.commit()
-
- share_url = url_for('view_shared_recording', public_id=share.public_id, _external=True)
-
- return jsonify({
- 'success': True,
- 'share_url': share_url,
- 'share': share.to_dict(),
- 'existing': False
- }), 201
-
[email protected]('/api/shares', methods=['GET'])
-@login_required
-def get_shares():
- shares = Share.query.filter_by(user_id=current_user.id).order_by(Share.created_at.desc()).all()
- return jsonify([share.to_dict() for share in shares])
-
[email protected]('/api/share/<int:share_id>', methods=['PUT'])
-@login_required
-def update_share(share_id):
- share = Share.query.filter_by(id=share_id, user_id=current_user.id).first_or_404()
- data = request.json
-
- if 'share_summary' in data:
- share.share_summary = data['share_summary']
- if 'share_notes' in data:
- share.share_notes = data['share_notes']
-
- db.session.commit()
- return jsonify({'success': True, 'share': share.to_dict()})
-
[email protected]('/api/share/<int:share_id>', methods=['DELETE'])
-@login_required
-def delete_share(share_id):
- share = Share.query.filter_by(id=share_id, user_id=current_user.id).first_or_404()
- db.session.delete(share)
- db.session.commit()
- return jsonify({'success': True})
-
-# --- User Preferences API Endpoint ---
[email protected]('/api/user/preferences', methods=['POST'])
-@login_required
-def save_user_preferences():
- """Save user preferences including UI language"""
- data = request.json
-
- if 'language' in data:
- current_user.ui_language = data['language']
-
- db.session.commit()
-
- return jsonify({
- 'success': True,
- 'message': 'Preferences saved successfully',
- 'ui_language': current_user.ui_language
- })
-
-# --- 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 ---
[email protected]('/api/tags', methods=['GET'])
-@login_required
-def get_tags():
- """Get all tags for the current user."""
- tags = Tag.query.filter_by(user_id=current_user.id).order_by(Tag.name).all()
- return jsonify([tag.to_dict() for tag in tags])
-
[email protected]('/api/tags', methods=['POST'])
-@login_required
-def create_tag():
- """Create a new tag."""
- data = request.get_json()
-
- if not data or not data.get('name'):
- return jsonify({'error': 'Tag name is required'}), 400
-
- # Check if tag with same name already exists for this user
- existing_tag = Tag.query.filter_by(name=data['name'], user_id=current_user.id).first()
- if existing_tag:
- return jsonify({'error': 'Tag with this name already exists'}), 400
-
- tag = Tag(
- name=data['name'],
- user_id=current_user.id,
- color=data.get('color', '#3B82F6'),
- custom_prompt=data.get('custom_prompt'),
- default_language=data.get('default_language'),
- default_min_speakers=data.get('default_min_speakers'),
- default_max_speakers=data.get('default_max_speakers')
- )
-
- db.session.add(tag)
- db.session.commit()
-
- return jsonify(tag.to_dict()), 201
-
[email protected]('/api/tags/<int:tag_id>', methods=['PUT'])
-@login_required
-def update_tag(tag_id):
- """Update a tag."""
- tag = Tag.query.filter_by(id=tag_id, user_id=current_user.id).first_or_404()
- data = request.get_json()
-
- if 'name' in data:
- # Check if new name conflicts with another tag
- existing_tag = Tag.query.filter_by(name=data['name'], user_id=current_user.id).filter(Tag.id != tag_id).first()
- if existing_tag:
- return jsonify({'error': 'Another tag with this name already exists'}), 400
- tag.name = data['name']
-
- if 'color' in data:
- tag.color = data['color']
- if 'custom_prompt' in data:
- tag.custom_prompt = data['custom_prompt']
- if 'default_language' in data:
- tag.default_language = data['default_language']
- if 'default_min_speakers' in data:
- tag.default_min_speakers = data['default_min_speakers']
- if 'default_max_speakers' in data:
- tag.default_max_speakers = data['default_max_speakers']
-
- tag.updated_at = datetime.utcnow()
- db.session.commit()
-
- return jsonify(tag.to_dict())
-
[email protected]('/api/tags/<int:tag_id>', methods=['DELETE'])
-@login_required
-def delete_tag(tag_id):
- """Delete a tag."""
- tag = Tag.query.filter_by(id=tag_id, user_id=current_user.id).first_or_404()
- db.session.delete(tag)
- db.session.commit()
- return jsonify({'success': True})
-
[email protected]('/api/recordings/<int:recording_id>/tags', methods=['POST'])
-@login_required
-def add_tag_to_recording(recording_id):
- """Add a tag to a recording."""
- recording = Recording.query.filter_by(id=recording_id, user_id=current_user.id).first_or_404()
- data = request.get_json()
-
- tag_id = data.get('tag_id')
- if not tag_id:
- return jsonify({'error': 'tag_id is required'}), 400
-
- tag = Tag.query.filter_by(id=tag_id, user_id=current_user.id).first_or_404()
-
- # Check if tag is already associated with recording
- existing_association = RecordingTag.query.filter_by(recording_id=recording_id, tag_id=tag_id).first()
- if not existing_association:
- # Get the next order number for this recording
- max_order = db.session.query(db.func.max(RecordingTag.order)).filter_by(recording_id=recording_id).scalar() or 0
-
- # Create new association with proper order
- new_association = RecordingTag(
- recording_id=recording_id,
- tag_id=tag_id,
- order=max_order + 1,
- added_at=datetime.utcnow()
- )
- db.session.add(new_association)
- db.session.commit()
-
- return jsonify({'success': True, 'tags': [t.to_dict() for t in recording.tags]})
-
[email protected]('/api/recordings/<int:recording_id>/tags/<int:tag_id>', methods=['DELETE'])
-@login_required
-def remove_tag_from_recording(recording_id, tag_id):
- """Remove a tag from a recording."""
- recording = Recording.query.filter_by(id=recording_id, user_id=current_user.id).first_or_404()
- tag = Tag.query.filter_by(id=tag_id, user_id=current_user.id).first_or_404()
-
- # Find and remove the association
- association = RecordingTag.query.filter_by(recording_id=recording_id, tag_id=tag_id).first()
- if association:
- db.session.delete(association)
- db.session.commit()
-
- return jsonify({'success': True, 'tags': [t.to_dict() for t in recording.tags]})
-
-class RegistrationForm(FlaskForm):
- username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)])
- email = StringField('Email', validators=[DataRequired(), Email()])
- password = PasswordField('Password', validators=[DataRequired(), password_check])
- confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
- submit = SubmitField('Sign Up')
-
- def validate_username(self, username):
- user = User.query.filter_by(username=username.data).first()
- if user:
- raise ValidationError('That username is already taken. Please choose a different one.')
-
- def validate_email(self, email):
- user = User.query.filter_by(email=email.data).first()
- if user:
- raise ValidationError('That email is already registered. Please use a different one.')
-
-class LoginForm(FlaskForm):
- email = StringField('Email', validators=[DataRequired(), Email()])
- password = PasswordField('Password', validators=[DataRequired()])
- remember = BooleanField('Remember Me')
- submit = SubmitField('Login')
-
-# Function to check and add columns if they don't exist
-def add_column_if_not_exists(engine, table_name, column_name, column_type):
- """Add a column to a table if it doesn't exist."""
- from sqlalchemy import text
-
- try:
- # Check if column exists
- with engine.connect() as conn:
- # For SQLite, we can query the pragma table_info using text()
- result = conn.execute(text(f"PRAGMA table_info({table_name})"))
- columns = [row[1] for row in result]
-
- if column_name not in columns:
- app.logger.info(f"Adding column {column_name} to {table_name}")
- conn.execute(text(f"ALTER TABLE {table_name} ADD COLUMN {column_name} {column_type}"))
- return True
- return False
- except Exception as e:
- app.logger.error(f"Error checking/adding column {column_name} to {table_name}: {e}")
- return False
-
-with app.app_context():
- db.create_all()
-
- # Check and add new columns if they don't exist
- engine = db.engine
- try:
- # Add is_inbox column with default value of 1 (True)
- if add_column_if_not_exists(engine, 'recording', 'is_inbox', 'BOOLEAN DEFAULT 1'):
- app.logger.info("Added is_inbox column to recording table")
-
- # Add is_highlighted column with default value of 0 (False)
- if add_column_if_not_exists(engine, 'recording', 'is_highlighted', 'BOOLEAN DEFAULT 0'):
- app.logger.info("Added is_highlighted column to recording table")
-
- # Add language preference columns to User table
- if add_column_if_not_exists(engine, 'user', 'transcription_language', 'VARCHAR(10)'):
- app.logger.info("Added transcription_language column to user table")
-
- # Add extract_events column to User table
- if add_column_if_not_exists(engine, 'user', 'extract_events', 'BOOLEAN DEFAULT 0'):
- app.logger.info("Added extract_events column to user table")
- if add_column_if_not_exists(engine, 'user', 'output_language', 'VARCHAR(50)'):
- app.logger.info("Added output_language column to user table")
- if add_column_if_not_exists(engine, 'user', 'summary_prompt', 'TEXT'):
- app.logger.info("Added summary_prompt column to user table")
- if add_column_if_not_exists(engine, 'user', 'name', 'VARCHAR(100)'):
- app.logger.info("Added name column to user table")
- if add_column_if_not_exists(engine, 'user', 'job_title', 'VARCHAR(100)'):
- app.logger.info("Added job_title column to user table")
- if add_column_if_not_exists(engine, 'user', 'company', 'VARCHAR(100)'):
- app.logger.info("Added company column to user table")
- if add_column_if_not_exists(engine, 'user', 'diarize', 'BOOLEAN'):
- app.logger.info("Added diarize column to user table")
- if add_column_if_not_exists(engine, 'user', 'ui_language', 'VARCHAR(10) DEFAULT "en"'):
- app.logger.info("Added ui_language column to user table")
- if add_column_if_not_exists(engine, 'recording', 'mime_type', 'VARCHAR(100)'):
- app.logger.info("Added mime_type column to recording table")
- if add_column_if_not_exists(engine, 'recording', 'completed_at', 'DATETIME'):
- app.logger.info("Added completed_at column to recording table")
- if add_column_if_not_exists(engine, 'recording', 'processing_time_seconds', 'INTEGER'):
- app.logger.info("Added processing_time_seconds column to recording table")
- if add_column_if_not_exists(engine, 'recording', 'processing_source', 'VARCHAR(50) DEFAULT "upload"'):
- app.logger.info("Added processing_source column to recording table")
- if add_column_if_not_exists(engine, 'recording', 'error_message', 'TEXT'):
- app.logger.info("Added error_message column to recording table")
-
- # Add columns to recording_tags for order tracking
- if add_column_if_not_exists(engine, 'recording_tags', 'added_at', 'DATETIME'):
- app.logger.info("Added added_at column to recording_tags table")
- if add_column_if_not_exists(engine, 'recording_tags', 'order', '"order" INTEGER DEFAULT 0'):
- app.logger.info("Added order column to recording_tags table")
-
- # Update existing records to have proper order values (approximate by tag_id)
- try:
- from sqlalchemy import text
- with engine.connect() as conn:
- # Get existing associations without order values and assign them
- existing_associations = conn.execute(text('''
- SELECT recording_id, tag_id,
- ROW_NUMBER() OVER (PARTITION BY recording_id ORDER BY tag_id) as row_num
- FROM recording_tags
- WHERE "order" = 0
- ''')).fetchall()
-
- for assoc in existing_associations:
- conn.execute(text('''
- UPDATE recording_tags
- SET "order" = :order_num
- WHERE recording_id = :rec_id AND tag_id = :tag_id
- '''), {"order_num": assoc.row_num, "rec_id": assoc.recording_id, "tag_id": assoc.tag_id})
-
- conn.commit()
- app.logger.info(f"Updated order values for {len(existing_associations)} existing tag associations")
- except Exception as e:
- app.logger.warning(f"Could not update existing tag order values: {e}")
-
- # Initialize default system settings
- if not SystemSetting.query.filter_by(key='transcript_length_limit').first():
- SystemSetting.set_setting(
- key='transcript_length_limit',
- value='30000',
- description='Maximum number of characters to send from transcript to LLM for summarization and chat. Use -1 for no limit.',
- setting_type='integer'
- )
- app.logger.info("Initialized default transcript_length_limit setting")
-
- if not SystemSetting.query.filter_by(key='max_file_size_mb').first():
- SystemSetting.set_setting(
- key='max_file_size_mb',
- value='250',
- description='Maximum file size allowed for audio uploads in megabytes (MB).',
- setting_type='integer'
- )
- app.logger.info("Initialized default max_file_size_mb setting")
-
- if not SystemSetting.query.filter_by(key='asr_timeout_seconds').first():
- SystemSetting.set_setting(
- key='asr_timeout_seconds',
- value='1800',
- description='Maximum time in seconds to wait for ASR transcription to complete. Default is 1800 seconds (30 minutes).',
- setting_type='integer'
- )
- app.logger.info("Initialized default asr_timeout_seconds setting")
-
- if not SystemSetting.query.filter_by(key='admin_default_summary_prompt').first():
- default_prompt = """Generate a comprehensive summary that includes the following sections:
-- **Key Issues Discussed**: A bulleted list of the main topics
-- **Key Decisions Made**: A bulleted list of any decisions reached
-- **Action Items**: A bulleted list of tasks assigned, including who is responsible if mentioned"""
- SystemSetting.set_setting(
- key='admin_default_summary_prompt',
- value=default_prompt,
- description='Default summarization prompt used when users have not set their own prompt. This serves as the base prompt for all users.',
- setting_type='string'
- )
- app.logger.info("Initialized admin_default_summary_prompt setting")
-
- if not SystemSetting.query.filter_by(key='recording_disclaimer').first():
- SystemSetting.set_setting(
- key='recording_disclaimer',
- value='',
- description='Legal disclaimer shown to users before recording starts. Supports Markdown formatting. Leave empty to disable.',
- setting_type='string'
- )
- app.logger.info("Initialized recording_disclaimer 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}")
-
-# --- API client setup for OpenRouter ---
-# Use environment variables from .env
-TEXT_MODEL_API_KEY = os.environ.get("TEXT_MODEL_API_KEY")
-# Strip any inline comments from URLs (users might add "# comment" in .env files)
-TEXT_MODEL_BASE_URL = os.environ.get("TEXT_MODEL_BASE_URL", "https://openrouter.ai/api/v1")
-if TEXT_MODEL_BASE_URL:
- TEXT_MODEL_BASE_URL = TEXT_MODEL_BASE_URL.split('#')[0].strip()
-TEXT_MODEL_NAME = os.environ.get("TEXT_MODEL_NAME", "openai/gpt-3.5-turbo") # Default if not set
-
-# Set up HTTP client with custom headers for OpenRouter app identification
-app_headers = {
- "HTTP-Referer": "https://github.com/murtaza-nasir/speakr", # Your app's repo URL for OpenRouter visibility
- "X-Title": "Speakr - AI Audio Transcription", # Your app name for OpenRouter visibility
- "User-Agent": "Speakr/1.0 (https://github.com/murtaza-nasir/speakr)" # Custom user agent for better tracking
-}
-
-http_client_no_proxy = httpx.Client(
- verify=True,
- headers=app_headers
-)
-
-try:
- # Always attempt to create client - use API key if provided, otherwise use placeholder
- api_key = TEXT_MODEL_API_KEY or "not-needed"
- client = OpenAI(
- api_key=api_key,
- base_url=TEXT_MODEL_BASE_URL,
- http_client=http_client_no_proxy
- )
- app.logger.info(f"LLM client initialized for endpoint: {TEXT_MODEL_BASE_URL}. Using model: {TEXT_MODEL_NAME}")
- if "openrouter" in TEXT_MODEL_BASE_URL.lower():
- app.logger.info("OpenRouter integration: App identification headers added for visibility in logs")
-except Exception as client_init_e:
- app.logger.error(f"Failed to initialize LLM client: {client_init_e}", exc_info=True)
- client = None
-
-def is_gpt5_model(model_name):
- """
- Check if the model is a GPT-5 series model that requires special API parameters.
-
- Args:
- model_name: The model name string
-
- Returns:
- Boolean indicating if this is a GPT-5 model
- """
- if not model_name:
- return False
- model_lower = model_name.lower()
- return model_lower.startswith('gpt-5') or model_lower in ['gpt-5', 'gpt-5-mini', 'gpt-5-nano', 'gpt-5-chat-latest']
-
-def is_using_openai_api():
- """
- Check if we're using the official OpenAI API (not OpenRouter or other providers).
-
- Returns:
- Boolean indicating if this is the OpenAI API
- """
- return TEXT_MODEL_BASE_URL and 'api.openai.com' in TEXT_MODEL_BASE_URL
-
-def call_llm_completion(messages, temperature=0.7, response_format=None, stream=False, max_tokens=None):
- """
- Centralized function for LLM API calls with proper error handling and logging.
-
- Args:
- messages: List of message dicts with 'role' and 'content'
- temperature: Sampling temperature (0-1) - ignored for GPT-5 models
- response_format: Optional response format dict (e.g., {"type": "json_object"})
- stream: Whether to stream the response
- max_tokens: Optional maximum tokens to generate
-
- Returns:
- OpenAI completion object or generator (if streaming)
- """
- if not client:
- raise ValueError("LLM client not initialized")
-
- if not TEXT_MODEL_API_KEY:
- raise ValueError("TEXT_MODEL_API_KEY not configured")
-
- try:
- # Check if we're using GPT-5 with OpenAI API
- using_gpt5 = is_gpt5_model(TEXT_MODEL_NAME) and is_using_openai_api()
-
- completion_args = {
- "model": TEXT_MODEL_NAME,
- "messages": messages,
- "stream": stream
- }
-
- if using_gpt5:
- # GPT-5 models don't support temperature, top_p, or logprobs
- # They use reasoning_effort and verbosity instead
- app.logger.debug(f"Using GPT-5 model: {TEXT_MODEL_NAME} - applying GPT-5 specific parameters")
-
- # Get GPT-5 specific parameters from environment variables
- reasoning_effort = os.environ.get("GPT5_REASONING_EFFORT", "medium") # minimal, low, medium, high
- verbosity = os.environ.get("GPT5_VERBOSITY", "medium") # low, medium, high
-
- # Add GPT-5 specific parameters
- completion_args["reasoning_effort"] = reasoning_effort
- completion_args["verbosity"] = verbosity
-
- # Use max_completion_tokens instead of max_tokens for GPT-5
- if max_tokens:
- completion_args["max_completion_tokens"] = max_tokens
- else:
- # Non-GPT-5 models use standard parameters
- completion_args["temperature"] = temperature
-
- if max_tokens:
- completion_args["max_tokens"] = max_tokens
-
- if response_format:
- completion_args["response_format"] = response_format
-
- return client.chat.completions.create(**completion_args)
-
- except Exception as e:
- app.logger.error(f"LLM API call failed: {e}")
- raise
-
-# Store details for the transcription client (potentially different)
-transcription_api_key = os.environ.get("TRANSCRIPTION_API_KEY", "")
-# Strip any inline comments from URLs (users might add "# comment" in .env files)
-transcription_base_url = os.environ.get("TRANSCRIPTION_BASE_URL", "")
-if transcription_base_url:
- transcription_base_url = transcription_base_url.split('#')[0].strip()
-
-
-# ASR endpoint configuration
-USE_ASR_ENDPOINT = os.environ.get('USE_ASR_ENDPOINT', 'false').lower() == 'true'
-# Strip any inline comments from ASR_BASE_URL (users might add "# comment" in .env files)
-ASR_BASE_URL = os.environ.get('ASR_BASE_URL')
-if ASR_BASE_URL:
- # Remove everything after '#' if it exists (inline comment)
- ASR_BASE_URL = ASR_BASE_URL.split('#')[0].strip()
-
-# When using ASR endpoint, automatically enable diarization and set sensible defaults
-# Users can still override these if needed, but they default to the expected ASR behavior
-if USE_ASR_ENDPOINT:
- # Default to diarization enabled for ASR (can be overridden by setting ASR_DIARIZE=false)
- ASR_DIARIZE = os.environ.get('ASR_DIARIZE', 'true').lower() == 'true'
- # Default speaker range for most conversations (None means auto-detect)
- ASR_MIN_SPEAKERS = os.environ.get('ASR_MIN_SPEAKERS')
- ASR_MAX_SPEAKERS = os.environ.get('ASR_MAX_SPEAKERS')
-else:
- # When not using ASR, these settings are irrelevant
- ASR_DIARIZE = False
- ASR_MIN_SPEAKERS = None
- ASR_MAX_SPEAKERS = None
-
-# Audio chunking configuration for large files with OpenAI Whisper API
-ENABLE_CHUNKING = os.environ.get('ENABLE_CHUNKING', 'true').lower() == 'true'
-CHUNK_SIZE_MB = int(os.environ.get('CHUNK_SIZE_MB', '20')) # 20MB default for safety margin
-CHUNK_OVERLAP_SECONDS = int(os.environ.get('CHUNK_OVERLAP_SECONDS', '3')) # 3 seconds overlap
-
-# Initialize chunking service
-chunking_service = AudioChunkingService(
- max_chunk_size_mb=CHUNK_SIZE_MB,
- overlap_seconds=CHUNK_OVERLAP_SECONDS
-) if ENABLE_CHUNKING else None
-
-# 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}")
-
-# Validate transcription service configuration
-if USE_ASR_ENDPOINT:
- if not ASR_BASE_URL:
- app.logger.error("ERROR: ASR endpoint is enabled but ASR_BASE_URL is not configured!")
- app.logger.error("Please set ASR_BASE_URL in your .env file or disable USE_ASR_ENDPOINT")
- sys.exit(1)
- app.logger.info(f"Using ASR endpoint for transcription at: {ASR_BASE_URL}")
-else:
- # Check if Whisper API is configured
- if not transcription_base_url or not transcription_api_key:
- app.logger.error("ERROR: No transcription service configured!")
- app.logger.error("You must configure either:")
- app.logger.error(" 1. ASR endpoint: Set USE_ASR_ENDPOINT=true and ASR_BASE_URL=<your-asr-url>")
- app.logger.error(" 2. Whisper API: Set TRANSCRIPTION_BASE_URL and TRANSCRIPTION_API_KEY")
- app.logger.error("Please check your .env file configuration.")
- sys.exit(1)
- app.logger.info(f"Using Whisper API at: {transcription_base_url}")
-
-# --- Background Transcription & Summarization Task ---
-def format_api_error_message(error_str):
- """
- Formats API error messages to be more user-friendly.
- Specifically handles token limit errors with helpful suggestions.
- """
- error_lower = error_str.lower()
-
- # Check for token limit errors
- if 'maximum context length' in error_lower and 'tokens' in error_lower:
- return "[Summary generation failed: The transcription is too long for AI processing. Request your admin to try using a different LLM with a larger context size, or set a limit for the transcript_length_limit in the system settings.]"
-
- # Check for other common API errors
- if 'rate limit' in error_lower:
- return "[Summary generation failed: API rate limit exceeded. Please try again in a few minutes.]"
-
- if 'insufficient funds' in error_lower or 'quota exceeded' in error_lower:
- return "[Summary generation failed: API quota exceeded. Please contact support.]"
-
- if 'timeout' in error_lower:
- return "[Summary generation failed: Request timed out. Please try again.]"
-
- # For other errors, show a generic message
- return f"[Summary generation failed: {error_str}]"
-
-def generate_title_task(app_context, recording_id):
- """Generates only a title for a recording based on transcription.
-
- Args:
- app_context: Flask app context
- recording_id: ID of the recording
- """
- with app_context:
- recording = db.session.get(Recording, recording_id)
- if not recording:
- app.logger.error(f"Error: Recording {recording_id} not found for title generation.")
- return
-
- if client is None:
- app.logger.warning(f"Skipping title generation for {recording_id}: OpenRouter client not configured.")
- # Still mark as completed even if we can't generate a title
- recording.status = 'COMPLETED'
- recording.completed_at = datetime.utcnow()
- db.session.commit()
- return
-
- if not recording.transcription or len(recording.transcription.strip()) < 10:
- app.logger.warning(f"Transcription for recording {recording_id} is too short or empty. Skipping title generation.")
- # Still mark as completed even if we can't generate a title
- recording.status = 'COMPLETED'
- recording.completed_at = datetime.utcnow()
- db.session.commit()
- return
-
- # Get configurable transcript length limit and format transcription for LLM
- transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)
- if transcript_limit == -1:
- raw_transcription = recording.transcription
- else:
- raw_transcription = recording.transcription[:transcript_limit]
-
- # Convert ASR JSON to clean text format
- transcript_text = format_transcription_for_llm(raw_transcription)
-
-
- # Get user language preference
- user_output_language = None
- if recording.owner:
- user_output_language = recording.owner.output_language
-
- language_directive = f"Please provide the title in {user_output_language}." if user_output_language else ""
-
- prompt_text = f"""Create a short title for this conversation:
-
-{transcript_text}
-
-Requirements:
-- Maximum 8 words
-- No phrases like "Discussion about" or "Meeting on"
-- Just the main topic
-
-{language_directive}
-
-Title:"""
-
- system_message_content = "You are an AI assistant that generates concise titles for audio transcriptions. Respond only with the title."
- if user_output_language:
- system_message_content += f" Ensure your response is in {user_output_language}."
-
-
- try:
- completion = call_llm_completion(
- messages=[
- {"role": "system", "content": system_message_content},
- {"role": "user", "content": prompt_text}
- ],
- temperature=0.7,
- max_tokens=5000
- )
-
-
- raw_response = completion.choices[0].message.content
- reasoning = getattr(completion.choices[0].message, 'reasoning', None)
-
- # Use reasoning content if main content is empty (fallback for reasoning models)
- if not raw_response and reasoning:
- app.logger.info(f"Title generation for recording {recording_id}: Using reasoning field as fallback")
- # Try to extract a title from the reasoning field
- lines = reasoning.strip().split('\n')
- # Look for the last line that might be the title
- for line in reversed(lines):
- line = line.strip()
- if line and not line.startswith('I') and len(line.split()) <= 8:
- raw_response = line
- break
-
- title = clean_llm_response(raw_response) if raw_response else ""
-
- if title:
- recording.title = title
- app.logger.info(f"Title generated for recording {recording_id}: {title}")
- else:
- app.logger.warning(f"Empty title generated for recording {recording_id}")
-
- except Exception as e:
- app.logger.error(f"Error generating title for recording {recording_id}: {str(e)}")
- app.logger.error(f"Exception details:", exc_info=True)
-
- # Always set status to COMPLETED after title generation (successful or not)
- # This ensures transcription processing is marked as complete
- 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, custom_prompt_override=None):
- """Generates only a summary for a recording (no title, no JSON response).
-
- Args:
- app_context: Flask app context
- recording_id: ID of the recording
- custom_prompt_override: Optional custom prompt that overrides all other prompts (for reprocessing)
- """
- with app_context:
- recording = db.session.get(Recording, recording_id)
- if not recording:
- app.logger.error(f"Error: Recording {recording_id} not found for summary generation.")
- return
-
- if client is None:
- app.logger.warning(f"Skipping summary generation for {recording_id}: OpenRouter client not configured.")
- recording.summary = "[Summary skipped: OpenRouter client not configured]"
- db.session.commit()
- return
-
- recording.status = 'SUMMARIZING'
- db.session.commit()
-
- app.logger.info(f"Requesting summary from OpenRouter for recording {recording_id} using model {TEXT_MODEL_NAME}...")
-
- if not recording.transcription or len(recording.transcription.strip()) < 10:
- app.logger.warning(f"Transcription for recording {recording_id} is too short or empty. Skipping summarization.")
- recording.summary = "[Summary skipped due to short transcription]"
- recording.status = 'COMPLETED'
- db.session.commit()
- return
-
- # Get user preferences and tag custom prompts
- user_summary_prompt = None
- user_output_language = None
- tag_custom_prompt = None
-
- # Collect all custom prompts from tags in the order they were added to this recording
- tag_custom_prompts = []
- if recording.tags:
- # Tags are now automatically ordered by the order they were added to this recording
- for tag in recording.tags:
- if tag.custom_prompt and tag.custom_prompt.strip():
- tag_custom_prompts.append({
- 'name': tag.name,
- 'prompt': tag.custom_prompt.strip()
- })
- app.logger.info(f"Found custom prompt from tag '{tag.name}' for recording {recording_id}")
-
- # Create merged prompt if we have multiple tag prompts
- if tag_custom_prompts:
- if len(tag_custom_prompts) == 1:
- tag_custom_prompt = tag_custom_prompts[0]['prompt']
- app.logger.info(f"Using single custom prompt from tag '{tag_custom_prompts[0]['name']}' for recording {recording_id}")
- else:
- # Merge multiple prompts seamlessly as unified instructions
- merged_parts = []
- for tag_prompt in tag_custom_prompts:
- merged_parts.append(tag_prompt['prompt'])
- tag_custom_prompt = "\n\n".join(merged_parts)
- tag_names = [tp['name'] for tp in tag_custom_prompts]
- app.logger.info(f"Combined custom prompts from {len(tag_custom_prompts)} tags in order added ({', '.join(tag_names)}) for recording {recording_id}")
- else:
- tag_custom_prompt = None
-
- if recording.owner:
- user_summary_prompt = recording.owner.summary_prompt
- user_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 limit
- transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)
- if transcript_limit == -1:
- transcript_text = formatted_transcription
- else:
- transcript_text = formatted_transcription[:transcript_limit]
-
- language_directive = f"IMPORTANT: You MUST provide the summary in {user_output_language}. The entire response must be in {user_output_language}." if user_output_language else ""
-
- # Determine which summarization instructions to use
- # Priority order: custom_prompt_override > tag custom prompt > user summary prompt > admin default prompt > hardcoded fallback
- summarization_instructions = ""
- if custom_prompt_override:
- app.logger.info(f"Using custom prompt override for recording {recording_id} (length: {len(custom_prompt_override)})")
- summarization_instructions = custom_prompt_override
- elif tag_custom_prompt:
- app.logger.info(f"Using tag custom prompt for recording {recording_id}")
- summarization_instructions = tag_custom_prompt
- elif user_summary_prompt:
- app.logger.info(f"Using user custom prompt for recording {recording_id}")
- summarization_instructions = user_summary_prompt
- else:
- # Get admin default prompt from system settings
- admin_default_prompt = SystemSetting.get_setting('admin_default_summary_prompt', None)
- if admin_default_prompt:
- app.logger.info(f"Using admin default prompt for recording {recording_id}")
- summarization_instructions = admin_default_prompt
- else:
- # Fallback to hardcoded default if admin hasn't set one
- summarization_instructions = """Generate a comprehensive summary that includes the following sections:
-- **Key Issues Discussed**: A bulleted list of the main topics
-- **Key Decisions Made**: A bulleted list of any decisions reached
-- **Action Items**: A bulleted list of tasks assigned, including who is responsible if mentioned"""
- app.logger.info(f"Using hardcoded default prompt for recording {recording_id}")
-
- # Build context information
- current_date = datetime.now().strftime("%B %d, %Y")
- context_parts = []
- context_parts.append(f"Current date: {current_date}")
-
- # Add selected tags information
- if recording.tags:
- tag_names = [tag.name for tag in recording.tags]
- context_parts.append(f"Tags applied to this transcript by the user: {', '.join(tag_names)}")
-
- # Add user profile information if available
- if recording.owner:
- user_context_parts = []
- if recording.owner.name:
- user_context_parts.append(f"Name: {recording.owner.name}")
- if recording.owner.job_title:
- user_context_parts.append(f"Job title: {recording.owner.job_title}")
- if recording.owner.company:
- user_context_parts.append(f"Company: {recording.owner.company}")
-
- if user_context_parts:
- context_parts.append(f"Information about the user: {', '.join(user_context_parts)}")
-
- context_section = "Context:\n" + "\n".join(f"- {part}" for part in context_parts)
-
- # Build SYSTEM message: Initial instructions + Context + Language
- system_message_content = "You are an AI assistant that generates comprehensive summaries for meeting transcripts. Respond only with the summary in Markdown format. Do NOT use markdown code blocks (```markdown). Provide raw markdown content directly."
- system_message_content += f"\n\n{context_section}"
- if user_output_language:
- system_message_content += f"\n\nLanguage Requirement: You MUST generate the entire summary in {user_output_language}. This is mandatory."
-
- # Build USER message: Transcription + Summarization Instructions + Language Directive
- prompt_text = f"""Transcription:
-\"\"\"
-{transcript_text}
-\"\"\"
-
-Summarization Instructions:
-{summarization_instructions}
-
-{language_directive}"""
-
- # 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 = call_llm_completion(
- messages=[
- {"role": "system", "content": system_message_content},
- {"role": "user", "content": prompt_text}
- ],
- temperature=0.5,
- max_tokens=int(os.environ.get("SUMMARY_MAX_TOKENS", "3000"))
- )
-
- raw_response = completion.choices[0].message.content
- app.logger.info(f"Raw LLM response for recording {recording_id}: '{raw_response}'")
-
- summary = clean_llm_response(raw_response) if raw_response else ""
- app.logger.info(f"Processed summary length for recording {recording_id}: {len(summary)} characters")
-
- if summary:
- recording.summary = summary
- db.session.commit()
- app.logger.info(f"Summary generated successfully for recording {recording_id}")
-
- # Extract events if enabled for this user BEFORE marking as completed
- if recording.owner and recording.owner.extract_events:
- extract_events_from_transcript(recording_id, formatted_transcription, summary)
-
- # Mark as completed AFTER event extraction
- recording.status = 'COMPLETED'
- recording.completed_at = datetime.utcnow()
- db.session.commit()
- else:
- app.logger.warning(f"Empty summary generated for recording {recording_id}")
- recording.summary = "[Summary not generated]"
- recording.status = 'COMPLETED'
- db.session.commit()
-
- except Exception as e:
- error_msg = format_api_error_message(str(e))
- app.logger.error(f"Error generating summary for recording {recording_id}: {str(e)}")
- recording.summary = error_msg
- recording.status = 'FAILED'
- db.session.commit()
-
-def extract_events_from_transcript(recording_id, transcript_text, summary_text):
- """Extract calendar events from transcript using LLM.
-
- Args:
- recording_id: ID of the recording
- transcript_text: The formatted transcript text
- summary_text: The generated summary text
- """
- try:
- recording = db.session.get(Recording, recording_id)
- if not recording or not recording.owner or not recording.owner.extract_events:
- return # Event extraction not enabled for this user
-
- app.logger.info(f"Extracting events for recording {recording_id}")
-
- # Get user language preference
- user_output_language = None
- if recording.owner:
- user_output_language = recording.owner.output_language
-
- # Build comprehensive context information
- current_date = datetime.now()
- context_parts = []
-
- # CRITICAL: Determine the reference date for relative date calculations
- reference_date = None
- reference_date_source = ""
-
- if recording.meeting_date:
- # Prefer meeting date if available
- reference_date = recording.meeting_date
- reference_date_source = "Meeting Date"
- context_parts.append(f"**MEETING DATE (use this for relative date calculations): {recording.meeting_date.strftime('%A, %B %d, %Y')}**")
- elif recording.created_at:
- # Fall back to upload date
- reference_date = recording.created_at.date()
- reference_date_source = "Upload Date (no meeting date available)"
- context_parts.append(f"**REFERENCE DATE (use this for relative date calculations): {recording.created_at.strftime('%A, %B %d, %Y')}**")
-
- context_parts.append(f"Today's actual date: {current_date.strftime('%A, %B %d, %Y')}")
- context_parts.append(f"Current time: {current_date.strftime('%I:%M %p')}")
-
- # Add additional recording context
- if recording.created_at:
- context_parts.append(f"Recording uploaded on: {recording.created_at.strftime('%B %d, %Y at %I:%M %p')}")
- if recording.meeting_date and reference_date_source == "Meeting Date":
- # Calculate days between meeting and today for context
- days_since = (current_date.date() - recording.meeting_date).days
- if days_since == 0:
- context_parts.append("This meeting happened today")
- elif days_since == 1:
- context_parts.append("This meeting happened yesterday")
- else:
- context_parts.append(f"This meeting happened {days_since} days ago")
-
- # Add user context for better understanding
- if recording.owner:
- user_context = []
- if recording.owner.name:
- user_context.append(f"User's name: {recording.owner.name}")
- if recording.owner.job_title:
- user_context.append(f"Job title: {recording.owner.job_title}")
- if recording.owner.company:
- user_context.append(f"Company: {recording.owner.company}")
- if user_context:
- context_parts.append("User information: " + ", ".join(user_context))
-
- # Add participants if available
- if recording.participants:
- context_parts.append(f"Participants in the meeting: {recording.participants}")
-
- context_section = "\n".join(context_parts)
-
- # Add language directive if user has a language preference
- language_directive = ""
- if user_output_language:
- language_directive = f"\n\nLANGUAGE REQUIREMENT:\n**CRITICAL**: You MUST generate ALL event titles and descriptions in {user_output_language}. This is mandatory. The entire event content (title, description, location) must be in {user_output_language}."
-
- # Prepare the prompt for event extraction
- event_prompt = f"""You are analyzing a meeting transcript to extract calendar events. Use the context below to correctly interpret relative dates and times.
-
-IMPORTANT CONTEXT:
-{context_section}{language_directive}
-
-INSTRUCTIONS:
-1. **CRITICAL**: Use the MEETING DATE shown above as your reference point for ALL relative date calculations
-2. When people say "next Wednesday" or "tomorrow" or "next week", calculate from the MEETING DATE, not today's date
-3. Example: If the meeting date is September 13, 2025 and someone says "next Wednesday", that means September 17, 2025
-4. If no specific time is mentioned for an event, use 09:00:00 (9 AM) as the default start time
-5. Pay attention to time zones if mentioned
-6. Extract ONLY events that are explicitly discussed as future appointments, meetings, or deadlines
-7. Do NOT create events for past occurrences or general discussions
-
-For each event found, extract:
-- Title: A clear, concise title for the event
-- Description: Brief description including context from the meeting
-- Start date/time: The calculated actual date/time (in ISO format YYYY-MM-DDTHH:MM:SS, use 09:00:00 if no time specified)
-- End date/time: When the event ends (if mentioned, in ISO format, default to 1 hour after start if not specified)
-- Location: Where the event will take place (if mentioned)
-- Attendees: List of people who should attend (if mentioned)
-- Reminder minutes: How many minutes before to remind (default 15)
-
-Transcript Summary:
-{summary_text}
-
-Transcript excerpt (for additional context):
-{transcript_text[:8000]}
-
-RESPONSE FORMAT:
-Respond with a JSON object containing an "events" array. If no events are found, return a JSON object with an empty events array.
-
-Example response:
-{{
- "events": [
- {{
- "title": "Project Review Meeting",
- "description": "Quarterly review to discuss project progress and next steps as discussed in the meeting",
- "start_datetime": "2025-07-22T14:00:00",
- "end_datetime": "2025-07-22T15:30:00",
- "location": "Conference Room A",
- "attendees": ["John Smith", "Jane Doe", "Bob Johnson"],
- "reminder_minutes": 15
- }}
- ]
-}}
-
-CRITICAL RULES:
-1. **BASE ALL DATE CALCULATIONS ON THE MEETING DATE PROVIDED IN THE CONTEXT ABOVE**
-2. Only extract events that are FUTURE relative to the MEETING DATE (not today's date)
-3. Convert all relative dates using the MEETING DATE as the reference point
-4. Example: If the meeting date is September 13, 2025 (Friday) and someone says:
- - "next Wednesday" = September 17, 2025
- - "tomorrow" = September 14, 2025
- - "next week" = week of September 15-19, 2025
-5. IMPORTANT: If no time is mentioned, always use 09:00:00 (9 AM) as the start time, NOT midnight
-6. Include context from the discussion in the description
-7. Do NOT invent or assume events not explicitly discussed
-8. If unsure about a date/time, do not include that event"""
-
- # Build system message with language requirement if applicable
- system_message_content = """You are an expert at extracting calendar events from meeting transcripts. You excel at:
-1. Understanding relative date references ("next Tuesday", "tomorrow", "in two weeks") and converting them to absolute dates
-2. Identifying genuine future appointments, meetings, and deadlines from conversations
-3. Distinguishing between actual planned events vs. general discussions
-4. Extracting participant names and meeting details accurately
-
-You must respond with valid JSON format only."""
-
- if user_output_language:
- system_message_content += f"\n\nLanguage Requirement: You MUST generate ALL event titles, descriptions, and locations in {user_output_language}. This is mandatory."
-
- completion = call_llm_completion(
- messages=[
- {"role": "system", "content": system_message_content},
- {"role": "user", "content": event_prompt}
- ],
- temperature=0.2,
- response_format={"type": "json_object"},
- max_tokens=3000
- )
-
- response_content = completion.choices[0].message.content
- events_data = safe_json_loads(response_content, {})
-
- # Handle both {"events": [...]} and direct array format
- if isinstance(events_data, dict) and 'events' in events_data:
- events_list = events_data['events']
- elif isinstance(events_data, list):
- events_list = events_data
- else:
- events_list = []
-
- app.logger.info(f"Found {len(events_list)} events for recording {recording_id}")
-
- # Save events to database
- for event_data in events_list:
- try:
- # Parse dates
- start_dt = None
- end_dt = None
-
- if 'start_datetime' in event_data:
- try:
- # Try ISO format first
- start_dt = datetime.fromisoformat(event_data['start_datetime'].replace('Z', '+00:00'))
- except:
- # Try other common formats
- from dateutil import parser
- try:
- start_dt = parser.parse(event_data['start_datetime'])
- except:
- app.logger.warning(f"Could not parse start_datetime: {event_data['start_datetime']}")
- continue # Skip this event if we can't parse the date
-
- if 'end_datetime' in event_data and event_data['end_datetime']:
- try:
- end_dt = datetime.fromisoformat(event_data['end_datetime'].replace('Z', '+00:00'))
- except:
- from dateutil import parser
- try:
- end_dt = parser.parse(event_data['end_datetime'])
- except:
- pass # End time is optional
-
- # Create event record
- event = Event(
- recording_id=recording_id,
- title=event_data.get('title', 'Untitled Event')[:200],
- description=event_data.get('description', ''),
- start_datetime=start_dt,
- end_datetime=end_dt,
- location=event_data.get('location', '')[:500] if event_data.get('location') else None,
- attendees=json.dumps(event_data.get('attendees', [])) if event_data.get('attendees') else None,
- reminder_minutes=event_data.get('reminder_minutes', 15)
- )
-
- db.session.add(event)
- app.logger.info(f"Added event '{event.title}' for recording {recording_id}")
-
- except Exception as e:
- app.logger.error(f"Error saving event for recording {recording_id}: {str(e)}")
- continue
-
- db.session.commit()
-
- # Refresh the recording to ensure events relationship is loaded
- recording = db.session.get(Recording, recording_id)
- if recording:
- db.session.refresh(recording)
-
- except Exception as e:
- app.logger.error(f"Error extracting events for recording {recording_id}: {str(e)}")
- db.session.rollback()
-
-def extract_audio_from_video(video_filepath, output_format='mp3', cleanup_original=True):
- """Extract audio from video containers using FFmpeg.
-
- Uses MP3 codec for optimal compatibility and predictable file sizes.
- 64kbps MP3 provides good speech quality at ~480KB per minute.
- """
- try:
- # Generate output filename with audio extension
- base_filepath, file_ext = os.path.splitext(video_filepath)
- 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 - using high-quality MP3 for better transcription
- subprocess.run([
- 'ffmpeg', '-i', video_filepath, '-y',
- '-vn', # No video
- '-codec:a', 'libmp3lame', # Use LAME MP3 encoder explicitly
- '-b:a', '128k', # 128kbps bitrate for high quality
- '-ar', '44100', # 44.1kHz sample rate for better quality
- '-ac', '1', # Mono (sufficient for speech, reduces file size)
- '-compression_level', '2', # Better compression
- temp_audio_filepath
- ], check=True, capture_output=True, text=True)
-
- app.logger.info(f"Successfully extracted audio to {temp_audio_filepath}")
-
- # Optionally preserve temp file for debugging (set PRESERVE_TEMP_AUDIO=true in env)
- if os.getenv('PRESERVE_TEMP_AUDIO', 'false').lower() == 'true':
- import shutil
- shutil.copy2(temp_audio_filepath, temp_audio_filepath.replace('_temp', '_debug'))
- app.logger.info(f"Debug: Preserved temp audio file as {temp_audio_filepath.replace('_temp', '_debug')}")
-
- # Rename temp file to final filename
- os.rename(temp_audio_filepath, final_audio_filepath)
-
- # 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:
- recording = db.session.get(Recording, recording_id)
- if not recording:
- app.logger.error(f"Error: Recording {recording_id} not found for ASR transcription.")
- return
-
- try:
- app.logger.info(f"Starting ASR transcription for recording {recording_id}...")
- recording.status = 'PROCESSING'
- db.session.commit()
-
- # 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, 'mp3')
-
- # 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
-
- # Keep track of whether we've already tried WAV conversion
- wav_conversion_attempted = False
- wav_converted_filepath = None
-
- # Retry loop for handling 500 errors with WAV conversion
- max_attempts = 2
- for attempt in range(max_attempts):
- try:
- # Use converted MP3 if available from previous attempt
- current_filepath = wav_converted_filepath if wav_converted_filepath else actual_filepath
- current_content_type = 'audio/mpeg' if wav_converted_filepath else actual_content_type
- current_filename = os.path.basename(current_filepath)
-
- with open(current_filepath, 'rb') as audio_file:
- url = f"{ASR_BASE_URL}/asr"
- params = {
- 'encode': True,
- 'task': 'transcribe',
- 'output': 'json'
- }
- if language:
- params['language'] = language
- if diarize:
- params['diarize'] = diarize
- if min_speakers:
- params['min_speakers'] = min_speakers
- if max_speakers:
- params['max_speakers'] = max_speakers
-
- content_type = current_content_type
- app.logger.info(f"Using MIME type {content_type} for ASR upload.")
- files = {'audio_file': (current_filename, audio_file, content_type)}
-
- with httpx.Client() as client:
- # Get configurable ASR timeout from database (default 30 minutes)
- asr_timeout_seconds = SystemSetting.get_setting('asr_timeout_seconds', 1800)
- timeout = httpx.Timeout(None, connect=30.0, read=float(asr_timeout_seconds), write=30.0, pool=30.0)
- app.logger.info(f"Sending ASR request to {url} with params: {params} (timeout: {asr_timeout_seconds}s)")
- response = client.post(url, params=params, files=files, timeout=timeout)
- app.logger.info(f"ASR request completed with status: {response.status_code}")
- response.raise_for_status()
-
- # Parse the JSON response from ASR (moved here so it's accessible)
- asr_response_data = response.json()
-
- # If we reach here, the request was successful
- break
-
- except httpx.HTTPStatusError as e:
- # Check if it's a 500 error and we haven't tried WAV conversion yet
- if e.response.status_code == 500 and attempt == 0 and not wav_conversion_attempted:
- app.logger.warning(f"ASR returned 500 error for recording {recording_id}, attempting high-quality MP3 conversion and retry...")
-
- # Convert to high-quality MP3 for better compatibility
- filename_lower = actual_filename.lower()
- if not filename_lower.endswith('.mp3'):
- try:
- base_filepath, file_ext = os.path.splitext(actual_filepath)
- temp_mp3_filepath = f"{base_filepath}_temp.mp3"
-
- app.logger.info(f"Converting {actual_filename} to high-quality MP3 format for retry...")
- subprocess.run(
- ['ffmpeg', '-i', actual_filepath, '-y', '-acodec', 'libmp3lame', '-b:a', '128k', '-ar', '44100', temp_mp3_filepath],
- check=True, capture_output=True, text=True
- )
- app.logger.info(f"Successfully converted {actual_filepath} to {temp_mp3_filepath}")
-
- wav_converted_filepath = temp_mp3_filepath # Keep variable name for compatibility
- wav_conversion_attempted = True
- # Continue to next iteration to retry with WAV
- continue
- except subprocess.CalledProcessError as conv_error:
- app.logger.error(f"Failed to convert to WAV: {conv_error}")
- # Re-raise the original HTTP error if conversion fails
- raise e
- else:
- # Already a WAV file, can't convert further
- app.logger.error(f"File is already WAV but still getting 500 error")
- raise e
- else:
- # Not a 500 error or already tried conversion, propagate the error
- raise e
-
- # DEBUG: Preserve converted file for quality checking
- if wav_converted_filepath and os.path.exists(wav_converted_filepath):
- try:
- # Get file size and basic info for debugging
- converted_size = os.path.getsize(wav_converted_filepath)
- converted_size_mb = converted_size / (1024 * 1024)
-
- # Create a debug copy in a known location
- debug_dir = os.path.join(app.config['UPLOAD_FOLDER'], 'debug_converted')
- os.makedirs(debug_dir, exist_ok=True)
-
- # Copy the converted file with a timestamp (MP3 now)
- from shutil import copy2
- file_ext = os.path.splitext(wav_converted_filepath)[1] or '.mp3'
- debug_filename = f"debug_{recording_id}_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}{file_ext}"
- debug_filepath = os.path.join(debug_dir, debug_filename)
- copy2(wav_converted_filepath, debug_filepath)
-
- app.logger.info(f"DEBUG: Converted file preserved at: {debug_filepath}")
- app.logger.info(f"DEBUG: Converted file size: {converted_size_mb:.2f} MB ({converted_size} bytes)")
- app.logger.info(f"DEBUG: Original file: {actual_filename}")
- app.logger.info(f"DEBUG: Recording ID: {recording_id}")
- app.logger.info(f"DEBUG: You can download this file from the container at: {debug_filepath}")
-
- except Exception as debug_error:
- app.logger.warning(f"DEBUG: Failed to preserve converted file: {debug_error}")
-
- # Clean up the original temporary converted file (but keep debug copy)
- try:
- if wav_converted_filepath and os.path.exists(wav_converted_filepath):
- os.remove(wav_converted_filepath)
- app.logger.info(f"Cleaned up original temporary converted file: {wav_converted_filepath}")
- except Exception as cleanup_error:
- app.logger.warning(f"Failed to clean up temporary converted file: {cleanup_error}")
-
- # Debug logging for ASR response
- app.logger.info(f"ASR response keys: {list(asr_response_data.keys())}")
-
- # Log the complete raw JSON response (truncated for readability)
- import json as json_module
- raw_json_str = json_module.dumps(asr_response_data, indent=2)
- if len(raw_json_str) > 5000:
- app.logger.info(f"Raw ASR response (first 5000 chars): {raw_json_str[:5000]}...")
- else:
- app.logger.info(f"Raw ASR response: {raw_json_str}")
-
- if 'segments' in asr_response_data:
- app.logger.info(f"Number of segments: {len(asr_response_data['segments'])}")
-
- # Collect all unique speakers from the response
- all_speakers = set()
- segments_with_speakers = 0
- segments_without_speakers = 0
-
- for segment in asr_response_data['segments']:
- if 'speaker' in segment and segment['speaker'] is not None:
- all_speakers.add(segment['speaker'])
- segments_with_speakers += 1
- else:
- segments_without_speakers += 1
-
- app.logger.info(f"Unique speakers found in raw response: {sorted(list(all_speakers))}")
- app.logger.info(f"Segments with speakers: {segments_with_speakers}, without speakers: {segments_without_speakers}")
-
- # Log first few segments for debugging
- for i, segment in enumerate(asr_response_data['segments'][:5]):
- segment_keys = list(segment.keys())
- app.logger.info(f"Segment {i} keys: {segment_keys}")
- app.logger.info(f"Segment {i}: speaker='{segment.get('speaker')}', text='{segment.get('text', '')[:50]}...'")
-
- # Simplify the JSON data
- simplified_segments = []
- if 'segments' in asr_response_data and isinstance(asr_response_data['segments'], list):
- last_known_speaker = None
-
- for i, segment in enumerate(asr_response_data['segments']):
- speaker = segment.get('speaker')
- text = segment.get('text', '').strip()
-
- # If segment doesn't have a speaker, use the previous segment's speaker
- if speaker is None:
- if last_known_speaker is not None:
- speaker = last_known_speaker
- app.logger.info(f"Assigned speaker '{speaker}' to segment {i} from previous segment")
- else:
- speaker = 'UNKNOWN_SPEAKER'
- app.logger.warning(f"No previous speaker available for segment {i}, using UNKNOWN_SPEAKER")
- else:
- # Update the last known speaker when we have a valid one
- last_known_speaker = speaker
-
- simplified_segments.append({
- 'speaker': speaker,
- 'sentence': text,
- 'start_time': segment.get('start'),
- 'end_time': segment.get('end')
- })
-
- # Log final simplified segments count
- app.logger.info(f"Created {len(simplified_segments)} simplified segments")
- null_speaker_count = sum(1 for seg in simplified_segments if seg['speaker'] is None)
- if null_speaker_count > 0:
- app.logger.warning(f"Found {null_speaker_count} segments with null speakers in final output")
-
- # Store the simplified JSON as a string
- recording.transcription = json.dumps(simplified_segments)
-
- # Commit the transcription data
- db.session.commit()
- app.logger.info(f"ASR transcription completed for recording {recording_id}.")
-
- # Generate title immediately
- generate_title_task(app_context, recording_id)
-
- # Always auto-generate summary for all recordings
- app.logger.info(f"Auto-generating summary for recording {recording_id}")
- generate_summary_only_task(app_context, recording_id)
-
- except Exception as e:
- db.session.rollback()
-
- # Handle timeout errors specifically
- error_msg = str(e)
- if "timed out" in error_msg.lower() or "timeout" in error_msg.lower():
- asr_timeout = SystemSetting.get_setting('asr_timeout_seconds', 1800)
- app.logger.error(f"ASR processing TIMED OUT for recording {recording_id} after {asr_timeout} seconds. Consider increasing 'asr_timeout_seconds' in Admin Dashboard > System Settings.")
- user_error_msg = f"ASR processing timed out after {asr_timeout} seconds. The file may be too long for the current timeout setting."
- else:
- # For non-timeout errors, include more detail
- app.logger.error(f"ASR processing FAILED for recording {recording_id}: {error_msg}")
- user_error_msg = f"ASR processing failed: {error_msg}"
-
- recording = db.session.get(Recording, recording_id)
- if recording:
- recording.status = 'FAILED'
- recording.transcription = user_error_msg
- db.session.commit()
-
-def transcribe_audio_task(app_context, recording_id, filepath, filename_for_asr, start_time, language=None, min_speakers=None, max_speakers=None, tag_id=None):
- """Runs the transcription and summarization in a background thread.
-
- Args:
- app_context: Flask app context
- recording_id: ID of the recording to process
- filepath: Path to the audio file
- filename_for_asr: Filename to use for ASR
- start_time: Processing start time
- language: Optional language code override (from upload form)
- min_speakers: Optional minimum speakers override (from upload form)
- max_speakers: Optional maximum speakers override (from upload form)
- tag_id: Optional tag ID to apply custom prompt from
- """
- if USE_ASR_ENDPOINT:
- with app_context:
- recording = db.session.get(Recording, recording_id)
- # Environment variable ASR_DIARIZE overrides user setting
- if '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_DIARIZE
- else:
- diarize_setting = recording.owner.diarize if recording.owner else False
-
- # Use language from upload form if provided, otherwise use user's default
- if language:
- user_transcription_language = language
- else:
- user_transcription_language = recording.owner.transcription_language if recording.owner else None
- # Use min/max speakers from upload form (already processed with precedence hierarchy)
- # If None, ASR will auto-detect the number of speakers
- final_min_speakers = min_speakers
- final_max_speakers = max_speakers
-
- transcribe_audio_asr(app_context, recording_id, filepath, filename_for_asr, start_time,
- mime_type=recording.mime_type,
- language=user_transcription_language,
- diarize=diarize_setting,
- min_speakers=final_min_speakers,
- max_speakers=final_max_speakers,
- tag_id=tag_id)
-
- # After ASR task completes, calculate processing time
- with app_context:
- recording = db.session.get(Recording, recording_id)
- if recording.status in ['COMPLETED', 'FAILED']:
- end_time = datetime.utcnow()
- recording.processing_time_seconds = (end_time - start_time).total_seconds()
- db.session.commit()
- return
-
- with app_context: # Need app context for db operations in thread
- recording = db.session.get(Recording, recording_id)
- if not recording:
- app.logger.error(f"Error: Recording {recording_id} not found for transcription.")
- return
-
- try:
- app.logger.info(f"Starting transcription for recording {recording_id} ({filename_for_asr})...")
- recording.status = 'PROCESSING'
- db.session.commit()
-
- # Check if chunking is needed for large files
- needs_chunking = (chunking_service and
- ENABLE_CHUNKING and
- chunking_service.needs_chunking(filepath, USE_ASR_ENDPOINT))
-
- if needs_chunking:
- app.logger.info(f"File {filepath} is large ({os.path.getsize(filepath)/1024/1024:.1f}MB), using chunking for transcription")
- transcription_text = transcribe_with_chunking(app_context, recording_id, filepath, filename_for_asr)
- else:
- # --- Standard transcription for smaller files ---
- transcription_text = transcribe_single_file(filepath, recording)
-
- recording.transcription = transcription_text
- app.logger.info(f"Transcription completed for recording {recording_id}. Text length: {len(recording.transcription)}")
-
- # Generate title immediately
- generate_title_task(app_context, recording_id)
-
- # Always auto-generate summary for all recordings
- app.logger.info(f"Auto-generating summary for recording {recording_id}")
- generate_summary_only_task(app_context, recording_id)
-
- except Exception as e:
- db.session.rollback() # Rollback if any step failed critically
- app.logger.error(f"Processing FAILED for recording {recording_id}: {str(e)}", exc_info=True)
- # Retrieve recording again in case session was rolled back
- recording = db.session.get(Recording, recording_id)
- if recording:
- # Ensure status reflects failure even after rollback/retrieve attempt
- if recording.status not in ['COMPLETED', 'FAILED']: # Avoid overwriting final state
- recording.status = 'FAILED'
- if not recording.transcription: # If transcription itself failed
- recording.transcription = f"Processing failed: {str(e)}"
- # Add error note to summary if appropriate stage was reached
- if recording.status == 'SUMMARIZING' and not recording.summary:
- recording.summary = f"[Processing failed during summarization: {str(e)}]"
-
- end_time = datetime.utcnow()
- recording.processing_time_seconds = (end_time - start_time).total_seconds()
- db.session.commit()
-
-def transcribe_single_file(filepath, recording):
- """Transcribe a single audio file using OpenAI Whisper API."""
-
- # 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)}")
-
- # List of formats supported by Whisper API
- WHISPER_SUPPORTED_FORMATS = ['flac', 'm4a', 'mp3', 'mp4', 'mpeg', 'mpga', 'oga', 'ogg', 'wav', 'webm']
-
- # Check if the file format needs conversion
- file_ext = os.path.splitext(actual_filepath)[1].lower().lstrip('.')
- converted_filepath = None
-
- try:
- with open(actual_filepath, 'rb') as audio_file:
- transcription_client = OpenAI(
- api_key=transcription_api_key,
- base_url=transcription_base_url,
- http_client=http_client_no_proxy
- )
- whisper_model = os.environ.get("WHISPER_MODEL", "Systran/faster-distil-whisper-large-v3")
-
- user_transcription_language = None
- if recording and recording.owner:
- user_transcription_language = recording.owner.transcription_language
-
- transcription_language = user_transcription_language
-
- transcription_params = {
- "model": whisper_model,
- "file": audio_file
- }
-
- if transcription_language:
- transcription_params["language"] = transcription_language
- app.logger.info(f"Using transcription language: {transcription_language}")
- else:
- app.logger.info("Transcription language not set, using auto-detection or service default.")
-
- transcript = transcription_client.audio.transcriptions.create(**transcription_params)
- return transcript.text
-
- except Exception as e:
- # Check if it's a format error
- error_message = str(e)
- if "Invalid file format" in error_message or "Supported formats" in error_message:
- app.logger.warning(f"Unsupported audio format '{file_ext}' detected, converting to MP3...")
-
- # Convert to MP3
- import tempfile
- temp_mp3_filepath = None
- try:
- with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as temp_mp3:
- temp_mp3_filepath = temp_mp3.name
-
- # Use ffmpeg to convert to MP3 with consistent settings
- subprocess.run(
- ['ffmpeg', '-i', actual_filepath, '-y', '-acodec', 'libmp3lame', '-b:a', '128k', '-ar', '44100', temp_mp3_filepath],
- check=True,
- capture_output=True
- )
- app.logger.info(f"Successfully converted {actual_filepath} to MP3 format")
- converted_filepath = temp_mp3_filepath
-
- # Retry transcription with converted file
- with open(converted_filepath, 'rb') as audio_file:
- transcription_client = OpenAI(
- api_key=transcription_api_key,
- base_url=transcription_base_url,
- http_client=http_client_no_proxy
- )
-
- transcription_params = {
- "model": whisper_model,
- "file": audio_file
- }
-
- if transcription_language:
- transcription_params["language"] = transcription_language
-
- transcript = transcription_client.audio.transcriptions.create(**transcription_params)
- return transcript.text
-
- finally:
- # Clean up temporary converted file
- if converted_filepath and os.path.exists(converted_filepath):
- try:
- os.unlink(converted_filepath)
- app.logger.info(f"Cleaned up temporary converted file: {converted_filepath}")
- except Exception as cleanup_error:
- app.logger.warning(f"Failed to clean up temporary file {converted_filepath}: {cleanup_error}")
- else:
- # Re-raise if it's not a format error
- raise
-
-def transcribe_with_chunking(app_context, recording_id, filepath, filename_for_asr):
- """Transcribe a large audio file using chunking."""
- import tempfile
-
- with app_context:
- recording = db.session.get(Recording, recording_id)
- if not recording:
- raise ValueError(f"Recording {recording_id} not found")
-
- # Create temporary directory for chunks
- with tempfile.TemporaryDirectory() as temp_dir:
- try:
- # Create chunks
- app.logger.info(f"Creating chunks for large file: {filepath}")
- chunks = chunking_service.create_chunks(filepath, temp_dir)
-
- if not chunks:
- raise ChunkProcessingError("No chunks were created from the audio file")
-
- app.logger.info(f"Created {len(chunks)} chunks, processing each with Whisper API...")
-
- # Process each chunk with proper timeout and retry handling
- chunk_results = []
-
- # Create HTTP client with proper timeouts
- timeout_config = httpx.Timeout(
- connect=30.0, # 30 seconds to establish connection
- read=300.0, # 5 minutes to read response (for large audio files)
- write=60.0, # 1 minute to write request
- pool=10.0 # 10 seconds to get connection from pool
- )
-
- http_client_with_timeout = httpx.Client(
- verify=True,
- timeout=timeout_config,
- limits=httpx.Limits(max_connections=5, max_keepalive_connections=2)
- )
-
- transcription_client = OpenAI(
- api_key=transcription_api_key,
- base_url=transcription_base_url,
- http_client=http_client_with_timeout,
- max_retries=3, # Increased retries for better reliability
- timeout=300.0 # 5 minute timeout for API calls
- )
- whisper_model = os.environ.get("WHISPER_MODEL", "Systran/faster-distil-whisper-large-v3")
-
- # Get user language preference
- user_transcription_language = None
- with app_context:
- recording = db.session.get(Recording, recording_id)
- if recording and recording.owner:
- user_transcription_language = recording.owner.transcription_language
-
- for i, chunk in enumerate(chunks):
- max_chunk_retries = 3
- chunk_retry_count = 0
- chunk_success = False
-
- while chunk_retry_count < max_chunk_retries and not chunk_success:
- try:
- retry_suffix = f" (retry {chunk_retry_count + 1}/{max_chunk_retries})" if chunk_retry_count > 0 else ""
- app.logger.info(f"Processing chunk {i+1}/{len(chunks)}: {chunk['filename']} ({chunk['size_mb']:.1f}MB){retry_suffix}")
-
- # Log detailed timing for each step
- step_start_time = time.time()
-
- # Step 1: File opening
- file_open_start = time.time()
- with open(chunk['path'], 'rb') as chunk_file:
- file_open_time = time.time() - file_open_start
- app.logger.info(f"Chunk {i+1}: File opened in {file_open_time:.2f}s")
-
- # Step 2: Prepare transcription parameters
- param_start = time.time()
- transcription_params = {
- "model": whisper_model,
- "file": chunk_file
- }
-
- if user_transcription_language:
- transcription_params["language"] = user_transcription_language
-
- param_time = time.time() - param_start
- app.logger.info(f"Chunk {i+1}: Parameters prepared in {param_time:.2f}s")
-
- # Step 3: API call with detailed timing
- api_start = time.time()
- app.logger.info(f"Chunk {i+1}: Starting API call to {transcription_base_url}")
-
- # Log connection details
- app.logger.info(f"Chunk {i+1}: Using timeout config - connect: 30s, read: 300s, write: 60s")
- app.logger.info(f"Chunk {i+1}: Max retries: 2, API timeout: 300s")
-
- try:
- transcript = transcription_client.audio.transcriptions.create(**transcription_params)
- except Exception as chunk_error:
- # Check if it's a format error (unlikely for chunks since they're MP3, but handle it)
- error_msg = str(chunk_error)
- if "Invalid file format" in error_msg or "Supported formats" in error_msg:
- app.logger.warning(f"Chunk {i+1} format issue, attempting conversion...")
- # Convert chunk to MP3 if needed
- import tempfile
- with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as temp_mp3:
- temp_mp3_path = temp_mp3.name
- try:
- subprocess.run(
- ['ffmpeg', '-i', chunk['path'], '-y', '-acodec', 'libmp3lame', '-b:a', '128k', '-ar', '44100', temp_mp3_path],
- check=True,
- capture_output=True
- )
- with open(temp_mp3_path, 'rb') as converted_chunk:
- transcription_params['file'] = converted_chunk
- transcript = transcription_client.audio.transcriptions.create(**transcription_params)
- finally:
- if os.path.exists(temp_mp3_path):
- os.unlink(temp_mp3_path)
- else:
- raise
-
- api_time = time.time() - api_start
- app.logger.info(f"Chunk {i+1}: API call completed in {api_time:.2f}s")
-
- # Step 4: Process response
- response_start = time.time()
- chunk_result = {
- 'index': chunk['index'],
- 'start_time': chunk['start_time'],
- 'end_time': chunk['end_time'],
- 'duration': chunk['duration'],
- 'size_mb': chunk['size_mb'],
- 'transcription': transcript.text,
- 'filename': chunk['filename'],
- 'processing_time': api_time # Store the actual API processing time
- }
- chunk_results.append(chunk_result)
- response_time = time.time() - response_start
-
- total_time = time.time() - step_start_time
- app.logger.info(f"Chunk {i+1}: Response processed in {response_time:.2f}s")
- app.logger.info(f"Chunk {i+1}: Total processing time: {total_time:.2f}s")
- app.logger.info(f"Chunk {i+1} transcribed successfully: {len(transcript.text)} characters")
- chunk_success = True
-
- except Exception as chunk_error:
- chunk_retry_count += 1
- error_msg = str(chunk_error)
-
- if chunk_retry_count < max_chunk_retries:
- # Determine wait time based on error type
- if "timeout" in error_msg.lower() or "timed out" in error_msg.lower():
- wait_time = 30 # 30 seconds for timeout errors
- elif "rate limit" in error_msg.lower():
- wait_time = 60 # 1 minute for rate limit errors
- else:
- wait_time = 15 # 15 seconds for other errors
-
- app.logger.warning(f"Chunk {i+1} failed (attempt {chunk_retry_count}/{max_chunk_retries}): {chunk_error}. Retrying in {wait_time} seconds...")
- time.sleep(wait_time)
- else:
- app.logger.error(f"Chunk {i+1} failed after {max_chunk_retries} attempts: {chunk_error}")
- # Add failed chunk to results
- chunk_result = {
- 'index': chunk['index'],
- 'start_time': chunk['start_time'],
- 'end_time': chunk['end_time'],
- 'transcription': f"[Chunk {i+1} transcription failed after {max_chunk_retries} attempts: {str(chunk_error)}]",
- 'filename': chunk['filename']
- }
- chunk_results.append(chunk_result)
-
- # Add small delay between chunks to avoid overwhelming the API
- if i < len(chunks) - 1: # Don't delay after the last chunk
- time.sleep(2)
-
- # Merge transcriptions
- app.logger.info(f"Merging {len(chunk_results)} chunk transcriptions...")
- merged_transcription = chunking_service.merge_transcriptions(chunk_results)
-
- if not merged_transcription.strip():
- raise ChunkProcessingError("Merged transcription is empty")
-
- # Log detailed performance statistics and analysis
- chunking_service.log_processing_statistics(chunk_results)
-
- # Get performance recommendations
- recommendations = chunking_service.get_performance_recommendations(chunk_results)
- if recommendations:
- app.logger.info("=== PERFORMANCE RECOMMENDATIONS ===")
- for i, rec in enumerate(recommendations, 1):
- app.logger.info(f"{i}. {rec}")
- app.logger.info("=== END RECOMMENDATIONS ===")
-
- app.logger.info(f"Chunked transcription completed. Final length: {len(merged_transcription)} characters")
- return merged_transcription
-
- except Exception as e:
- app.logger.error(f"Chunking transcription failed for {filepath}: {e}")
- # Clean up chunks if they exist
- if 'chunks' in locals():
- chunking_service.cleanup_chunks(chunks)
- raise ChunkProcessingError(f"Chunked transcription failed: {str(e)}")
- finally:
- # Cleanup is handled by tempfile.TemporaryDirectory context manager
- pass
-
[email protected]('/speakers', methods=['GET'])
-@login_required
-def get_speakers():
- """Get all speakers for the current user, ordered by usage frequency and recency."""
- try:
- speakers = Speaker.query.filter_by(user_id=current_user.id)\
- .order_by(Speaker.use_count.desc(), Speaker.last_used.desc())\
- .all()
- return jsonify([speaker.to_dict() for speaker in speakers])
- except Exception as e:
- app.logger.error(f"Error fetching speakers: {e}")
- return jsonify({'error': str(e)}), 500
-
[email protected]('/speakers/search', methods=['GET'])
-@login_required
-def search_speakers():
- """Search speakers by name for autocomplete functionality."""
- try:
- query = request.args.get('q', '').strip()
- if not query:
- return jsonify([])
-
- speakers = Speaker.query.filter_by(user_id=current_user.id)\
- .filter(Speaker.name.ilike(f'%{query}%'))\
- .order_by(Speaker.use_count.desc(), Speaker.last_used.desc())\
- .limit(10)\
- .all()
-
- return jsonify([speaker.to_dict() for speaker in speakers])
- except Exception as e:
- app.logger.error(f"Error searching speakers: {e}")
- return jsonify({'error': str(e)}), 500
-
[email protected]('/speakers', methods=['POST'])
-@login_required
-def create_speaker():
- """Create a new speaker or update existing one."""
- try:
- data = request.json
- name = data.get('name', '').strip()
-
- if not name:
- return jsonify({'error': 'Speaker name is required'}), 400
-
- # Check if speaker already exists for this user
- existing_speaker = Speaker.query.filter_by(user_id=current_user.id, name=name).first()
-
- if existing_speaker:
- # Update usage statistics
- existing_speaker.use_count += 1
- existing_speaker.last_used = datetime.utcnow()
- db.session.commit()
- return jsonify(existing_speaker.to_dict())
- else:
- # Create new speaker
- speaker = Speaker(
- name=name,
- user_id=current_user.id,
- use_count=1,
- created_at=datetime.utcnow(),
- last_used=datetime.utcnow()
- )
- db.session.add(speaker)
- db.session.commit()
- return jsonify(speaker.to_dict()), 201
-
- except Exception as e:
- db.session.rollback()
- app.logger.error(f"Error creating speaker: {e}")
- return jsonify({'error': str(e)}), 500
-
[email protected]('/speakers/<int:speaker_id>', methods=['DELETE'])
-@login_required
-def delete_speaker(speaker_id):
- """Delete a speaker."""
- try:
- speaker = Speaker.query.filter_by(id=speaker_id, user_id=current_user.id).first()
- if not speaker:
- return jsonify({'error': 'Speaker not found'}), 404
-
- db.session.delete(speaker)
- db.session.commit()
- return jsonify({'success': True})
-
- except Exception as e:
- db.session.rollback()
- app.logger.error(f"Error deleting speaker: {e}")
- return jsonify({'error': str(e)}), 500
-
[email protected]('/speakers/delete_all', methods=['DELETE'])
-@login_required
-def delete_all_speakers():
- """Delete all speakers for the current user."""
- try:
- deleted_count = Speaker.query.filter_by(user_id=current_user.id).delete()
- db.session.commit()
- return jsonify({'success': True, 'deleted_count': deleted_count})
-
- except Exception as e:
- db.session.rollback()
- app.logger.error(f"Error deleting all speakers: {e}")
- return jsonify({'error': str(e)}), 500
-
[email protected]('/recording/<int:recording_id>/download/transcript')
-@login_required
-def download_transcript_with_template(recording_id):
- """Download transcript with custom template formatting."""
- try:
- import re
- from datetime import timedelta
-
- recording = db.session.get(Recording, recording_id)
- if not recording:
- return jsonify({'error': 'Recording not found'}), 404
-
- # Check if the recording belongs to the current user
- if recording.user_id and recording.user_id != current_user.id:
- return jsonify({'error': 'You do not have permission to access this recording'}), 403
-
- if not recording.transcription:
- return jsonify({'error': 'No transcription available for this recording'}), 400
-
- # Get template ID from query params
- template_id = request.args.get('template_id', type=int)
-
- # Get the template
- if template_id:
- template = TranscriptTemplate.query.filter_by(
- id=template_id,
- user_id=current_user.id
- ).first()
- else:
- # Use default template
- template = TranscriptTemplate.query.filter_by(
- user_id=current_user.id,
- is_default=True
- ).first()
-
- # If no template found, use a basic format
- if not template:
- template_format = "[{{speaker}}]: {{text}}"
- else:
- template_format = template.template
-
- # Helper functions for formatting
- def format_time(seconds):
- """Format seconds to HH:MM:SS"""
- if seconds is None:
- return "00:00:00"
- td = timedelta(seconds=seconds)
- hours = int(td.total_seconds() // 3600)
- minutes = int((td.total_seconds() % 3600) // 60)
- secs = int(td.total_seconds() % 60)
- return f"{hours:02d}:{minutes:02d}:{secs:02d}"
-
- def format_srt_time(seconds):
- """Format seconds to SRT format HH:MM:SS,mmm"""
- if seconds is None:
- return "00:00:00,000"
- td = timedelta(seconds=seconds)
- hours = int(td.total_seconds() // 3600)
- minutes = int((td.total_seconds() % 3600) // 60)
- secs = int(td.total_seconds() % 60)
- millis = int((td.total_seconds() % 1) * 1000)
- return f"{hours:02d}:{minutes:02d}:{secs:02d},{millis:03d}"
-
- # Parse transcription JSON
- try:
- transcription_data = json.loads(recording.transcription)
- except:
- return jsonify({'error': 'Invalid transcription format'}), 400
-
- # Generate formatted transcript
- output_lines = []
- for index, segment in enumerate(transcription_data, 1):
- line = template_format
-
- # Replace variables
- replacements = {
- '{{index}}': str(index),
- '{{speaker}}': segment.get('speaker', 'Unknown'),
- '{{text}}': segment.get('sentence', ''),
- '{{start_time}}': format_time(segment.get('start_time')),
- '{{end_time}}': format_time(segment.get('end_time')),
- }
-
- for key, value in replacements.items():
- line = line.replace(key, value)
-
- # Handle filters
- # Upper case filter
- line = re.sub(r'{{(.*?)\|upper}}', lambda m: replacements.get('{{' + m.group(1) + '}}', '').upper(), line)
- # SRT time filter
- line = re.sub(r'{{start_time\|srt}}', format_srt_time(segment.get('start_time')), line)
- line = re.sub(r'{{end_time\|srt}}', format_srt_time(segment.get('end_time')), line)
-
- output_lines.append(line)
-
- # Join lines
- formatted_transcript = '\n'.join(output_lines)
-
- # Create response
- response = make_response(formatted_transcript)
- filename = f"{recording.title or 'transcript'}_{template.name if template else 'formatted'}.txt"
- filename = re.sub(r'[^a-zA-Z0-9_\-\.]', '_', filename)
- response.headers['Content-Type'] = 'text/plain; charset=utf-8'
- response.headers['Content-Disposition'] = f'attachment; filename="{filename}"'
-
- return response
-
- except Exception as e:
- app.logger.error(f"Error downloading transcript: {e}")
- return jsonify({'error': 'Failed to generate transcript download'}), 500
-
-
[email protected]('/recording/<int:recording_id>/download/summary')
-@login_required
-def download_summary_word(recording_id):
- """Download recording summary as a Word document."""
- try:
- from docx import Document
- from docx.shared import Inches
- import re
- from io import BytesIO
-
- recording = db.session.get(Recording, recording_id)
- if not recording:
- return jsonify({'error': 'Recording not found'}), 404
-
- # Check if the recording belongs to the current user
- if recording.user_id and recording.user_id != current_user.id:
- return jsonify({'error': 'You do not have permission to access this recording'}), 403
-
- if not recording.summary:
- return jsonify({'error': 'No summary available for this recording'}), 400
-
- # Create Word document
- doc = Document()
-
- # Add title
- title_text = f'Summary: {recording.title or "Untitled Recording"}'
- title = doc.add_heading(title_text, 0)
- # Check if title needs Unicode font support
- try:
- title_text.encode('ascii')
- except UnicodeEncodeError:
- # Title contains non-ASCII characters
- from docx.oxml.ns import qn
- for run in title.runs:
- run.font.name = 'Arial'
- r = run._element
- r.rPr.rFonts.set(qn('w:eastAsia'), 'Arial')
-
- # Helper function to add paragraph with Unicode support
- def add_unicode_paragraph(doc, text):
- p = doc.add_paragraph(text)
- try:
- text.encode('ascii')
- except UnicodeEncodeError:
- from docx.oxml.ns import qn
- for run in p.runs:
- run.font.name = 'Arial'
- r = run._element
- r.rPr.rFonts.set(qn('w:eastAsia'), 'Arial')
- return p
-
- # Add metadata
- add_unicode_paragraph(doc, f'Uploaded: {recording.created_at.strftime("%Y-%m-%d %H:%M")}')
- if recording.meeting_date:
- add_unicode_paragraph(doc, f'Recording Date: {recording.meeting_date.strftime("%Y-%m-%d")}')
- if recording.participants:
- add_unicode_paragraph(doc, f'Participants: {recording.participants}')
- if recording.tags:
- tags_str = ', '.join([tag.name for tag in recording.tags])
- add_unicode_paragraph(doc, f'Tags: {tags_str}')
- doc.add_paragraph('') # Empty line
-
- # Process markdown content using the helper function
- process_markdown_to_docx(doc, recording.summary)
-
- # Save to BytesIO
- doc_stream = BytesIO()
- doc.save(doc_stream)
- doc_stream.seek(0)
-
- # Create safe filename
- safe_title = re.sub(r'[<>:"/\\|?*]', '', recording.title or 'Untitled')
- safe_title = re.sub(r'[-\s]+', '-', safe_title).strip('-')
- filename = f'summary-{safe_title}.docx' if safe_title else f'summary-recording-{recording_id}.docx'
-
- # Create ASCII fallback for send_file - if title has non-ASCII chars, use generic name with ID
- ascii_filename = filename.encode('ascii', 'ignore').decode('ascii')
- if not ascii_filename.strip() or ascii_filename.strip() in ['summary-.docx', 'summary-recording-.docx']:
- ascii_filename = f'summary-recording-{recording_id}.docx'
-
- response = send_file(
- doc_stream,
- as_attachment=False,
- mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
- )
- # Properly encode filename for international characters
- # Check if filename contains non-ASCII characters
- try:
- # Try to encode as ASCII - if this works, use simple format
- filename.encode('ascii')
- # ASCII-only filename, use simple format
- response.headers['Content-Disposition'] = f'attachment; filename="{filename}"'
- except UnicodeEncodeError:
- # Contains non-ASCII characters, use proper RFC 2231 encoding
- try:
- # Use Python's built-in RFC 2231 encoder
- encoded_value = encode_rfc2231(filename, charset='utf-8')
- header_value = f'attachment; filename*={encoded_value}'
- app.logger.info(f"DEBUG CHINESE FILENAME (RFC2231): Original='{filename}', Header='{header_value}'")
- response.headers['Content-Disposition'] = header_value
- except Exception as e:
- # Fallback to simple attachment with generic name
- app.logger.error(f"RFC2231 encoding failed: {e}, using fallback")
- response.headers['Content-Disposition'] = f'attachment; filename="download-{recording_id}.docx"'
- return response
-
- except Exception as e:
- app.logger.error(f"Error generating summary Word document: {e}")
- return jsonify({'error': 'Failed to generate Word document'}), 500
-
[email protected]('/recording/<int:recording_id>/download/chat', methods=['POST'])
-@login_required
-def download_chat_word(recording_id):
- """Download chat conversation as a Word document."""
- try:
- from docx import Document
- from docx.shared import Inches
- import re
- from io import BytesIO
-
- recording = db.session.get(Recording, recording_id)
- if not recording:
- return jsonify({'error': 'Recording not found'}), 404
-
- # Check if the recording belongs to the current user
- if recording.user_id and recording.user_id != current_user.id:
- return jsonify({'error': 'You do not have permission to access this recording'}), 403
-
- # Get chat messages from request
- data = request.json
- if not data or 'messages' not in data:
- return jsonify({'error': 'No messages provided'}), 400
-
- messages = data['messages']
- if not messages:
- return jsonify({'error': 'No messages to download'}), 400
-
- # Create Word document
- doc = Document()
-
- # Add title
- title_text = f'Chat Conversation: {recording.title or "Untitled Recording"}'
- title = doc.add_heading(title_text, 0)
- # Check if title needs Unicode font support
- try:
- title_text.encode('ascii')
- except UnicodeEncodeError:
- from docx.oxml.ns import qn
- for run in title.runs:
- run.font.name = 'Arial'
- r = run._element
- r.rPr.rFonts.set(qn('w:eastAsia'), 'Arial')
-
- # Helper function to add paragraph with Unicode support
- def add_unicode_paragraph(doc, text):
- p = doc.add_paragraph(text)
- try:
- text.encode('ascii')
- except UnicodeEncodeError:
- from docx.oxml.ns import qn
- for run in p.runs:
- run.font.name = 'Arial'
- r = run._element
- r.rPr.rFonts.set(qn('w:eastAsia'), 'Arial')
- return p
-
- # Add metadata
- add_unicode_paragraph(doc, f'Recording Date: {recording.created_at.strftime("%Y-%m-%d %H:%M")}')
- add_unicode_paragraph(doc, f'Chat Export Date: {datetime.utcnow().strftime("%Y-%m-%d %H:%M")}')
- doc.add_paragraph('') # Empty line
-
- # Add chat messages
- for message in messages:
- role = message.get('role', 'unknown')
- content = message.get('content', '')
- thinking = message.get('thinking', '')
-
- # Add role header
- if role == 'user':
- p = doc.add_paragraph()
- run = p.add_run('You: ')
- run.bold = True
- elif role == 'assistant':
- p = doc.add_paragraph()
- run = p.add_run('Assistant: ')
- run.bold = True
- else:
- p = doc.add_paragraph()
- run = p.add_run(f'{role.title()}: ')
- run.bold = True
-
- # Add thinking content if present
- if thinking and role == 'assistant':
- p = doc.add_paragraph()
- p.add_run('[Model Reasoning]\n').italic = True
- p.add_run(thinking).italic = True
- doc.add_paragraph('') # Empty line
-
- # Add message content with markdown formatting
- process_markdown_to_docx(doc, content)
-
- doc.add_paragraph('') # Empty line between messages
-
- # Save to BytesIO
- doc_stream = BytesIO()
- doc.save(doc_stream)
- doc_stream.seek(0)
-
- # Create safe filename
- safe_title = re.sub(r'[<>:"/\\|?*]', '', recording.title or 'Untitled')
- safe_title = re.sub(r'[-\s]+', '-', safe_title).strip('-')
- filename = f'chat-{safe_title}.docx' if safe_title else f'chat-recording-{recording_id}.docx'
-
- # Create ASCII fallback for send_file - if title has non-ASCII chars, use generic name with ID
- ascii_filename = filename.encode('ascii', 'ignore').decode('ascii')
- if not ascii_filename.strip() or ascii_filename.strip() in ['chat-.docx', 'chat-recording-.docx']:
- ascii_filename = f'chat-recording-{recording_id}.docx'
-
- response = send_file(
- doc_stream,
- as_attachment=False,
- mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
- )
-
- # Properly encode filename for international characters
- # Check if filename contains non-ASCII characters
- try:
- # Try to encode as ASCII - if this works, use simple format
- filename.encode('ascii')
- # ASCII-only filename, use simple format
- response.headers['Content-Disposition'] = f'attachment; filename="{filename}"'
- except UnicodeEncodeError:
- # Contains non-ASCII characters, use proper RFC 2231 encoding
- try:
- # Use Python's built-in RFC 2231 encoder
- encoded_value = encode_rfc2231(filename, charset='utf-8')
- header_value = f'attachment; filename*={encoded_value}'
- app.logger.info(f"DEBUG CHINESE FILENAME (RFC2231): Original='{filename}', Header='{header_value}'")
- response.headers['Content-Disposition'] = header_value
- except Exception as e:
- # Fallback to simple attachment with generic name
- app.logger.error(f"RFC2231 encoding failed: {e}, using fallback")
- response.headers['Content-Disposition'] = f'attachment; filename="download-{recording_id}.docx"'
- return response
-
- except Exception as e:
- app.logger.error(f"Error generating chat Word document: {e}")
- return jsonify({'error': 'Failed to generate Word document'}), 500
-
[email protected]('/api/recording/<int:recording_id>/events', methods=['GET'])
-@login_required
-def get_recording_events(recording_id):
- """Get all events extracted from a recording."""
- try:
- recording = db.session.get(Recording, recording_id)
- if not recording:
- return jsonify({'error': 'Recording not found'}), 404
-
- if recording.user_id and recording.user_id != current_user.id:
- return jsonify({'error': 'Unauthorized'}), 403
-
- events = Event.query.filter_by(recording_id=recording_id).all()
- return jsonify({'events': [event.to_dict() for event in events]})
-
- except Exception as e:
- app.logger.error(f"Error fetching events for recording {recording_id}: {e}")
- return jsonify({'error': str(e)}), 500
-
[email protected]('/api/event/<int:event_id>/ics', methods=['GET'])
-@login_required
-def download_event_ics(event_id):
- """Generate and download an ICS file for a single event."""
- try:
- event = db.session.get(Event, event_id)
- if not event:
- return jsonify({'error': 'Event not found'}), 404
-
- # Check permissions through recording ownership
- if event.recording.user_id != current_user.id:
- return jsonify({'error': 'Unauthorized'}), 403
-
- # Generate ICS content
- ics_content = generate_ics_content(event)
-
- # Create response with ICS file
- response = make_response(ics_content)
- response.headers['Content-Type'] = 'text/calendar; charset=utf-8'
- response.headers['Content-Disposition'] = f'attachment; filename="{secure_filename(event.title)}.ics"'
-
- return response
-
- except Exception as e:
- app.logger.error(f"Error generating ICS for event {event_id}: {e}")
- return jsonify({'error': str(e)}), 500
-
[email protected]('/api/recording/<int:recording_id>/events/ics', methods=['GET'])
-@login_required
-def download_all_events_ics(recording_id):
- """Generate and download an ICS file containing all events from a recording."""
- try:
- recording = db.session.get(Recording, recording_id)
- if not recording:
- return jsonify({'error': 'Recording not found'}), 404
-
- # Check permissions
- if recording.user_id != current_user.id:
- return jsonify({'error': 'Unauthorized'}), 403
-
- # Get all events for this recording
- events = Event.query.filter_by(recording_id=recording_id).all()
- if not events:
- return jsonify({'error': 'No events found for this recording'}), 404
-
- # Generate combined ICS content
- ics_lines = []
- ics_lines.append("BEGIN:VCALENDAR")
- ics_lines.append("VERSION:2.0")
- ics_lines.append("PRODID:-//Speakr//Event Export//EN")
- ics_lines.append("CALSCALE:GREGORIAN")
- ics_lines.append("METHOD:PUBLISH")
-
- # Add each event
- for event in events:
- # Get the individual event's ICS content and extract just the VEVENT portion
- individual_ics = generate_ics_content(event)
- # Extract VEVENT block from individual ICS
- lines = individual_ics.split('\n')
- in_event = False
- for line in lines:
- if line.startswith('BEGIN:VEVENT'):
- in_event = True
- if in_event:
- ics_lines.append(line)
- if line.startswith('END:VEVENT'):
- in_event = False
-
- ics_lines.append("END:VCALENDAR")
- ics_content = '\n'.join(ics_lines)
-
- # Create response with ICS file
- response = make_response(ics_content)
- response.headers['Content-Type'] = 'text/calendar; charset=utf-8'
- filename = f"events-{secure_filename(recording.title or f'recording-{recording_id}')}.ics"
- response.headers['Content-Disposition'] = f'attachment; filename="{filename}"'
-
- return response
-
- except Exception as e:
- app.logger.error(f"Error generating ICS for recording {recording_id}: {e}")
- return jsonify({'error': str(e)}), 500
-
-def generate_ics_content(event):
- """Generate ICS calendar file content for an event."""
- import uuid
- from datetime import datetime, timedelta
-
- # Generate unique ID for the event
- uid = f"{event.id}-{uuid.uuid4()}@speakr.app"
-
- # Format dates in iCalendar format (YYYYMMDDTHHMMSS)
- def format_ical_date(dt):
- if dt:
- return dt.strftime('%Y%m%dT%H%M%S')
- return None
-
- # Start building ICS content
- lines = [
- 'BEGIN:VCALENDAR',
- 'VERSION:2.0',
- 'PRODID:-//Speakr//Event Export//EN',
- 'CALSCALE:GREGORIAN',
- 'METHOD:PUBLISH',
- 'BEGIN:VEVENT',
- f'UID:{uid}',
- f'DTSTAMP:{format_ical_date(datetime.utcnow())}',
- ]
-
- # Add event details
- if event.start_datetime:
- lines.append(f'DTSTART:{format_ical_date(event.start_datetime)}')
-
- if event.end_datetime:
- lines.append(f'DTEND:{format_ical_date(event.end_datetime)}')
- elif event.start_datetime:
- # If no end time, default to 1 hour after start
- end_time = event.start_datetime + timedelta(hours=1)
- lines.append(f'DTEND:{format_ical_date(end_time)}')
-
- # Add title and description
- lines.append(f'SUMMARY:{escape_ical_text(event.title)}')
-
- if event.description:
- lines.append(f'DESCRIPTION:{escape_ical_text(event.description)}')
-
- # Add location if available
- if event.location:
- lines.append(f'LOCATION:{escape_ical_text(event.location)}')
-
- # Add attendees if available
- if event.attendees:
- try:
- attendees_list = json.loads(event.attendees)
- for attendee in attendees_list:
- if attendee:
- lines.append(f'ATTENDEE:CN={escape_ical_text(attendee)}:mailto:{attendee.replace(" ", ".").lower()}@example.com')
- except:
- pass
-
- # Add reminder/alarm if specified
- if event.reminder_minutes and event.reminder_minutes > 0:
- lines.extend([
- 'BEGIN:VALARM',
- 'TRIGGER:-PT{}M'.format(event.reminder_minutes),
- 'ACTION:DISPLAY',
- f'DESCRIPTION:Reminder: {escape_ical_text(event.title)}',
- 'END:VALARM'
- ])
-
- # Close event and calendar
- lines.extend([
- 'STATUS:CONFIRMED',
- 'TRANSP:OPAQUE',
- 'END:VEVENT',
- 'END:VCALENDAR'
- ])
-
- return '\r\n'.join(lines)
-
-def escape_ical_text(text):
- """Escape special characters for iCalendar format."""
- if not text:
- return ''
- # Escape special characters
- text = str(text)
- text = text.replace('\\', '\\\\')
- text = text.replace(',', '\\,')
- text = text.replace(';', '\\;')
- text = text.replace('\n', '\\n')
- return text
-
[email protected]('/recording/<int:recording_id>/download/notes')
-@login_required
-def download_notes_word(recording_id):
- """Download recording notes as a Word document."""
- try:
- from docx import Document
- from docx.shared import Inches
- import re
- from io import BytesIO
-
- recording = db.session.get(Recording, recording_id)
- if not recording:
- return jsonify({'error': 'Recording not found'}), 404
-
- # Check if the recording belongs to the current user
- if recording.user_id and recording.user_id != current_user.id:
- return jsonify({'error': 'You do not have permission to access this recording'}), 403
-
- if not recording.notes:
- return jsonify({'error': 'No notes available for this recording'}), 400
-
- # Create Word document
- doc = Document()
-
- # Add title
- title_text = f'Notes: {recording.title or "Untitled Recording"}'
- title = doc.add_heading(title_text, 0)
- # Check if title needs Unicode font support
- try:
- title_text.encode('ascii')
- except UnicodeEncodeError:
- from docx.oxml.ns import qn
- for run in title.runs:
- run.font.name = 'Arial'
- r = run._element
- r.rPr.rFonts.set(qn('w:eastAsia'), 'Arial')
-
- # Helper function to add paragraph with Unicode support
- def add_unicode_paragraph(doc, text):
- p = doc.add_paragraph(text)
- try:
- text.encode('ascii')
- except UnicodeEncodeError:
- from docx.oxml.ns import qn
- for run in p.runs:
- run.font.name = 'Arial'
- r = run._element
- r.rPr.rFonts.set(qn('w:eastAsia'), 'Arial')
- return p
-
- # Add metadata
- add_unicode_paragraph(doc, f'Uploaded: {recording.created_at.strftime("%Y-%m-%d %H:%M")}')
- if recording.meeting_date:
- add_unicode_paragraph(doc, f'Recording Date: {recording.meeting_date.strftime("%Y-%m-%d")}')
- if recording.participants:
- add_unicode_paragraph(doc, f'Participants: {recording.participants}')
- if recording.tags:
- tags_str = ', '.join([tag.name for tag in recording.tags])
- add_unicode_paragraph(doc, f'Tags: {tags_str}')
- doc.add_paragraph('') # Empty line
-
- # Process markdown content using the helper function
- process_markdown_to_docx(doc, recording.notes)
-
- # Save to BytesIO
- doc_stream = BytesIO()
- doc.save(doc_stream)
- doc_stream.seek(0)
-
- # Create safe filename
- safe_title = re.sub(r'[<>:"/\\|?*]', '', recording.title or 'Untitled')
- safe_title = re.sub(r'[-\s]+', '-', safe_title).strip('-')
- filename = f'notes-{safe_title}.docx' if safe_title else f'notes-recording-{recording_id}.docx'
-
- # Create ASCII fallback for send_file - if title has non-ASCII chars, use generic name with ID
- ascii_filename = filename.encode('ascii', 'ignore').decode('ascii')
- if not ascii_filename.strip() or ascii_filename.strip() in ['notes-.docx', 'notes-recording-.docx']:
- ascii_filename = f'notes-recording-{recording_id}.docx'
-
- response = send_file(
- doc_stream,
- as_attachment=False,
- mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
- )
- # Properly encode filename for international characters
- # Check if filename contains non-ASCII characters
- try:
- # Try to encode as ASCII - if this works, use simple format
- filename.encode('ascii')
- # ASCII-only filename, use simple format
- response.headers['Content-Disposition'] = f'attachment; filename="{filename}"'
- except UnicodeEncodeError:
- # Contains non-ASCII characters, use proper RFC 2231 encoding
- try:
- # Use Python's built-in RFC 2231 encoder
- encoded_value = encode_rfc2231(filename, charset='utf-8')
- header_value = f'attachment; filename*={encoded_value}'
- app.logger.info(f"DEBUG CHINESE FILENAME (RFC2231): Original='{filename}', Header='{header_value}'")
- response.headers['Content-Disposition'] = header_value
- except Exception as e:
- # Fallback to simple attachment with generic name
- app.logger.error(f"RFC2231 encoding failed: {e}, using fallback")
- response.headers['Content-Disposition'] = f'attachment; filename="download-{recording_id}.docx"'
- return response
-
- except Exception as e:
- app.logger.error(f"Error generating notes Word document: {e}")
- return jsonify({'error': 'Failed to generate Word document'}), 500
-
[email protected]('/recording/<int:recording_id>/generate_summary', methods=['POST'])
-@login_required
-def generate_summary_endpoint(recording_id):
- """Generate summary for a recording that doesn't have one."""
- try:
- recording = db.session.get(Recording, recording_id)
- if not recording:
- return jsonify({'error': 'Recording not found'}), 404
-
- # Check if the recording belongs to the current user
- if recording.user_id and recording.user_id != current_user.id:
- return jsonify({'error': 'You do not have permission to generate summary for this recording'}), 403
-
- # Check if transcription exists
- if not recording.transcription or len(recording.transcription.strip()) < 10:
- return jsonify({'error': 'No valid transcription available for summary generation'}), 400
-
- # Check if already processing
- if recording.status in ['PROCESSING', 'SUMMARIZING']:
- return jsonify({'error': 'Recording is already being processed'}), 400
-
- # Check if OpenRouter client is available
- if client is None:
- return jsonify({'error': 'Summary service is not available (OpenRouter client not configured)'}), 503
-
- app.logger.info(f"Starting summary generation for recording {recording_id}")
-
- # Generate summary in background thread
- thread = threading.Thread(
- target=generate_summary_only_task,
- args=(app.app_context(), recording_id)
- )
- thread.start()
-
- return jsonify({
- 'success': True,
- 'message': 'Summary generation started'
- })
-
- except Exception as e:
- db.session.rollback()
- app.logger.error(f"Error starting summary generation for recording {recording_id}: {e}")
- return jsonify({'error': str(e)}), 500
-
-def update_speaker_usage(speaker_names):
- """Helper function to update speaker usage statistics."""
- if not speaker_names or not current_user.is_authenticated:
- return
-
- try:
- for name in speaker_names:
- name = name.strip()
- if not name:
- continue
-
- speaker = Speaker.query.filter_by(user_id=current_user.id, name=name).first()
- if speaker:
- speaker.use_count += 1
- speaker.last_used = datetime.utcnow()
- else:
- # Create new speaker
- speaker = Speaker(
- name=name,
- user_id=current_user.id,
- use_count=1,
- created_at=datetime.utcnow(),
- last_used=datetime.utcnow()
- )
- db.session.add(speaker)
-
- db.session.commit()
- except Exception as e:
- app.logger.error(f"Error updating speaker usage: {e}")
- db.session.rollback()
-
[email protected]('/recording/<int:recording_id>/update_speakers', methods=['POST'])
-@login_required
-def update_speakers(recording_id):
- """Updates speaker labels in a transcription with provided names."""
- try:
- recording = db.session.get(Recording, recording_id)
- if not recording:
- return jsonify({'error': 'Recording not found'}), 404
-
- if recording.user_id and recording.user_id != current_user.id:
- return jsonify({'error': 'You do not have permission to edit this recording'}), 403
-
- data = request.json
- speaker_map = data.get('speaker_map')
- regenerate_summary = data.get('regenerate_summary', False)
-
- if not speaker_map:
- return jsonify({'error': 'No speaker map provided'}), 400
-
- transcription_text = recording.transcription
- is_json = False
- try:
- transcription_data = json.loads(transcription_text)
- # Updated check for our new simplified JSON format (a list of segment objects)
- is_json = isinstance(transcription_data, list)
- except (json.JSONDecodeError, TypeError):
- is_json = False
-
- speaker_names_used = []
-
- if is_json:
- # Handle new simplified JSON transcript (list of segments)
- for segment in transcription_data:
- original_speaker_label = segment.get('speaker')
- if original_speaker_label in speaker_map:
- new_name_info = speaker_map[original_speaker_label]
- new_name = new_name_info.get('name', '').strip()
- if new_name_info.get('isMe'):
- new_name = current_user.name or 'Me'
-
- if new_name:
- segment['speaker'] = new_name
- if new_name not in speaker_names_used:
- speaker_names_used.append(new_name)
-
- recording.transcription = json.dumps(transcription_data)
-
- # Update participants only from speakers that were actually given names (not default labels)
- final_speakers = set()
- for seg in transcription_data:
- speaker = seg.get('speaker')
- if speaker and str(speaker).strip():
- # Only include speakers that have been given actual names (not default labels like "SPEAKER_01", "SPEAKER_09", etc.)
- # Check if this speaker was updated with a real name (not a default label)
- if not re.match(r'^SPEAKER_\d+$', str(speaker), re.IGNORECASE):
- final_speakers.add(speaker)
- recording.participants = ', '.join(sorted(list(final_speakers)))
-
- else:
- # Handle plain text transcript
- new_participants = []
- for speaker_label, new_name_info in speaker_map.items():
- new_name = new_name_info.get('name', '').strip()
- if new_name_info.get('isMe'):
- new_name = current_user.name or 'Me'
-
- if new_name:
- transcription_text = re.sub(r'\[\s*' + re.escape(speaker_label) + r'\s*\]', f'[{new_name}]', transcription_text, flags=re.IGNORECASE)
- if new_name not in new_participants:
- new_participants.append(new_name)
-
- recording.transcription = transcription_text
- if new_participants:
- recording.participants = ', '.join(new_participants)
- speaker_names_used = new_participants
-
- # Update speaker usage statistics
- if speaker_names_used:
- update_speaker_usage(speaker_names_used)
-
- db.session.commit()
-
- if regenerate_summary:
- app.logger.info(f"Regenerating summary for recording {recording_id} after speaker update.")
- thread = threading.Thread(
- target=generate_summary_only_task,
- args=(app.app_context(), recording.id)
- )
- thread.start()
-
- return jsonify({
- 'success': True,
- 'message': 'Speakers updated successfully.',
- 'recording': recording.to_dict()
- })
-
- except Exception as e:
- db.session.rollback()
- app.logger.error(f"Error updating speakers for recording {recording_id}: {e}", exc_info=True)
- return jsonify({'error': str(e)}), 500
-
[email protected]('/recording/<int:recording_id>/update_transcript', methods=['POST'])
-@login_required
-def update_transcript(recording_id):
- """Updates the complete transcript data including text edits and speaker changes."""
- try:
- recording = db.session.get(Recording, recording_id)
- if not recording:
- return jsonify({'error': 'Recording not found'}), 404
-
- if recording.user_id and recording.user_id != current_user.id:
- return jsonify({'error': 'You do not have permission to edit this recording'}), 403
-
- data = request.json
- transcript_data = data.get('transcript_data')
- speaker_map = data.get('speaker_map', {})
- regenerate_summary = data.get('regenerate_summary', False)
-
- if not transcript_data or not isinstance(transcript_data, list):
- return jsonify({'error': 'Invalid transcript data provided'}), 400
-
- # Update speaker names in the transcript data
- speaker_names_used = []
- for segment in transcript_data:
- original_speaker_label = segment.get('speaker')
-
- # Apply speaker name mapping if provided
- if original_speaker_label in speaker_map:
- new_name_info = speaker_map[original_speaker_label]
- new_name = new_name_info.get('name', '').strip()
- if new_name_info.get('isMe'):
- new_name = current_user.name or 'Me'
-
- if new_name:
- segment['speaker'] = new_name
- if new_name not in speaker_names_used:
- speaker_names_used.append(new_name)
-
- # Save the updated transcript
- recording.transcription = json.dumps(transcript_data)
-
- # Update participants
- final_speakers = set()
- for seg in transcript_data:
- speaker = seg.get('speaker')
- if speaker and str(speaker).strip():
- # Only include speakers with real names (not default labels)
- if not re.match(r'^SPEAKER_\d+$', str(speaker), re.IGNORECASE):
- final_speakers.add(speaker)
- recording.participants = ', '.join(sorted(list(final_speakers)))
-
- # Update speaker usage statistics
- if speaker_names_used:
- update_speaker_usage(speaker_names_used)
-
- db.session.commit()
-
- if regenerate_summary:
- app.logger.info(f"Regenerating summary for recording {recording_id} after transcript update.")
- thread = threading.Thread(
- target=generate_summary_only_task,
- args=(app.app_context(), recording.id)
- )
- thread.start()
-
- return jsonify({
- 'success': True,
- 'message': 'Transcript updated successfully.',
- 'recording': recording.to_dict()
- })
-
- except Exception as e:
- db.session.rollback()
- app.logger.error(f"Error updating transcript for recording {recording_id}: {e}", exc_info=True)
- return jsonify({'error': str(e)}), 500
-
-def identify_speakers_from_text(transcription):
- """
- Uses an LLM to identify speakers from a transcription.
- """
- if not TEXT_MODEL_API_KEY:
- raise ValueError("TEXT_MODEL_API_KEY not configured.")
-
- # The transcription passed here could be JSON, so we format it.
- formatted_transcription = format_transcription_for_llm(transcription)
-
- # Extract existing speaker labels (e.g., SPEAKER_00, SPEAKER_01) in order of appearance
- all_labels = re.findall(r'\[(SPEAKER_\d+)\]', formatted_transcription)
- seen = set()
- speaker_labels = [x for x in all_labels if not (x in seen or seen.add(x))]
-
- if not speaker_labels:
- return {}
-
- # Get configurable transcript length limit
- transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)
- if transcript_limit == -1:
- # No limit
- transcript_text = formatted_transcription
- else:
- transcript_text = formatted_transcription[:transcript_limit]
-
- prompt = f"""Analyze the following transcription and identify the names of the speakers. The speakers are labeled as {', '.join(speaker_labels)}. Based on the context of the conversation, determine the most likely name for each speaker label.
-
-Transcription:
----
-{transcript_text}
----
-
-Respond with a single JSON object where keys are the speaker labels (e.g., "SPEAKER_00") and values are the identified full names. If a name cannot be determined, use the value "Unknown".
-
-Example:
-{{
- "SPEAKER_00": "John Doe",
- "SPEAKER_01": "Jane Smith",
- "SPEAKER_02": "Unknown"
-}}
-
-JSON Response:
-"""
-
- try:
- completion = call_llm_completion(
- messages=[
- {"role": "system", "content": "You are an expert in analyzing conversation transcripts to identify speakers. Your response must be a single, valid JSON object."},
- {"role": "user", "content": prompt}
- ],
- temperature=0.2,
- response_format={"type": "json_object"}
- )
- response_content = completion.choices[0].message.content
- speaker_map = safe_json_loads(response_content, {})
-
- # Post-process the map to replace "Unknown" with an empty string
- for speaker_label, identified_name in speaker_map.items():
- if identified_name.strip().lower() == "unknown":
- speaker_map[speaker_label] = ""
-
- return speaker_map
- except Exception as e:
- app.logger.error(f"Error calling LLM for speaker identification: {e}")
- raise
-
-def identify_unidentified_speakers_from_text(transcription, unidentified_speakers):
- """
- Uses an LLM to identify only the unidentified speakers from a transcription.
- """
- if not TEXT_MODEL_API_KEY:
- raise ValueError("TEXT_MODEL_API_KEY not configured.")
-
- # The transcription passed here could be JSON, so we format it.
- formatted_transcription = format_transcription_for_llm(transcription)
-
- if not unidentified_speakers:
- return {}
-
- # Get configurable transcript length limit
- transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)
- if transcript_limit == -1:
- # No limit
- transcript_text = formatted_transcription
- else:
- transcript_text = formatted_transcription[:transcript_limit]
-
- prompt = f"""Analyze the following conversation transcript and identify the names of the UNIDENTIFIED speakers based on the context and content of their dialogue.
-
-The speakers that need to be identified are: {', '.join(unidentified_speakers)}
-
-Look for clues in the conversation such as:
-- Names mentioned by other speakers when addressing someone
-- Self-introductions or references to their own name
-- Context clues about roles, relationships, or positions
-- Any direct mentions of names in the dialogue
-
-Here is the complete conversation transcript:
-
-{transcript_text}
-
-Based on the conversation above, identify the most likely real names for the unidentified speakers. Pay close attention to how speakers address each other and any names that are mentioned in the dialogue.
-
-Respond with a single JSON object where keys are the speaker labels (e.g., "SPEAKER_01") and values are the identified full names. If a name cannot be determined from the conversation context, use an empty string "".
-
-Example format:
-{{
- "SPEAKER_01": "Jane Smith",
- "SPEAKER_03": "Bob Johnson",
- "SPEAKER_05": ""
-}}
-
-JSON Response:
-"""
-
- try:
- completion = call_llm_completion(
- messages=[
- {"role": "system", "content": "You are an expert in analyzing conversation transcripts to identify speakers based on contextual clues in the dialogue. Analyze the conversation carefully to find names mentioned when speakers address each other or introduce themselves. Your response must be a single, valid JSON object containing only the requested speaker identifications."},
- {"role": "user", "content": prompt}
- ],
- temperature=0.2,
- response_format={"type": "json_object"}
- )
- response_content = completion.choices[0].message.content
- speaker_map = safe_json_loads(response_content, {})
-
- # Post-process the map to replace "Unknown" with an empty string
- for speaker_label, identified_name in speaker_map.items():
- if identified_name and identified_name.strip().lower() in ["unknown", "n/a", "not available", "unclear"]:
- speaker_map[speaker_label] = ""
-
- return speaker_map
- except Exception as e:
- app.logger.error(f"Error calling LLM for speaker identification: {e}")
- raise
-
[email protected]('/recording/<int:recording_id>/auto_identify_speakers', methods=['POST'])
-@login_required
-def auto_identify_speakers(recording_id):
- """
- Automatically identifies speakers in a transcription using an LLM.
- Only identifies speakers that haven't been identified yet.
- """
- try:
- recording = db.session.get(Recording, recording_id)
- if not recording:
- return jsonify({'error': 'Recording not found'}), 404
-
- if recording.user_id and recording.user_id != current_user.id:
- return jsonify({'error': 'You do not have permission to modify this recording'}), 403
-
- if not recording.transcription:
- return jsonify({'error': 'No transcription available for speaker identification'}), 400
-
- # Get the current speaker map from the request
- data = request.json or {}
- current_speaker_map = data.get('current_speaker_map', {})
-
- # Extract all speaker labels from transcription
- formatted_transcription = format_transcription_for_llm(recording.transcription)
- all_labels = re.findall(r'\[(SPEAKER_\d+)\]', formatted_transcription)
- seen = set()
- speaker_labels = [x for x in all_labels if not (x in seen or seen.add(x))]
-
- # Filter out speakers that already have names assigned
- unidentified_speakers = []
- for speaker_label in speaker_labels:
- speaker_info = current_speaker_map.get(speaker_label, {})
- speaker_name = speaker_info.get('name', '').strip() if isinstance(speaker_info, dict) else str(speaker_info).strip()
-
- # Only include speakers that don't have names or have empty names
- if not speaker_name:
- unidentified_speakers.append(speaker_label)
-
- if not unidentified_speakers:
- return jsonify({'success': True, 'speaker_map': {}, 'message': 'All speakers are already identified'})
-
- # Call the helper function with only unidentified speakers
- speaker_map = identify_unidentified_speakers_from_text(recording.transcription, unidentified_speakers)
-
- return jsonify({'success': True, 'speaker_map': speaker_map})
-
- except ValueError as ve:
- # Handle cases where API key is not set
- return jsonify({'error': str(ve)}), 503
- except Exception as e:
- app.logger.error(f"Error during auto speaker identification for recording {recording_id}: {e}", exc_info=True)
- return jsonify({'error': f'An unexpected error occurred: {e}'}), 500
-
-# --- Chat with Transcription ---
[email protected]('/chat', methods=['POST'])
-@login_required
-def chat_with_transcription():
- try:
- data = request.json
- if not data:
- return jsonify({'error': 'No data provided'}), 400
-
- recording_id = data.get('recording_id')
- user_message = data.get('message')
- message_history = data.get('message_history', [])
-
- if not recording_id:
- return jsonify({'error': 'No recording ID provided'}), 400
- if not user_message:
- return jsonify({'error': 'No message provided'}), 400
-
- # Get the recording
- recording = db.session.get(Recording, recording_id)
- if not recording:
- return jsonify({'error': 'Recording not found'}), 404
-
- # Check if the recording belongs to the current user
- if recording.user_id and recording.user_id != current_user.id:
- return jsonify({'error': 'You do not have permission to chat with this recording'}), 403
-
- # Check if OpenRouter client is available
- if client is None:
- return jsonify({'error': 'Chat service is not available (OpenRouter client not configured)'}), 503
-
- # Prepare the system prompt with the transcription
- user_chat_output_language = current_user.output_language if current_user.is_authenticated else None
-
- language_instruction = ""
- if user_chat_output_language:
- language_instruction = f"Please provide all your responses in {user_chat_output_language}."
-
- user_name = current_user.name if current_user.is_authenticated and current_user.name else "User"
- user_title = current_user.job_title if current_user.is_authenticated and current_user.job_title else "a professional"
- user_company = current_user.company if current_user.is_authenticated and current_user.company else "their organization"
-
- formatted_transcription = format_transcription_for_llm(recording.transcription)
-
- # Get configurable transcript length limit for chat
- transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)
- if transcript_limit == -1:
- # No limit
- chat_transcript = formatted_transcription
- else:
- chat_transcript = formatted_transcription[:transcript_limit]
-
- 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} Analyze the following meeting information and respond to the specific request.
-
-Following are the meeting participants and their roles:
-{recording.participants or "No specific participants information provided."}
-
-Following is the meeting transcript:
-<<start transcript>>
-{chat_transcript or "No transcript available."}
-<<end transcript>>
-
-Additional context and notes about the meeting:
-{recording.notes or "none"}
-"""
-
- # Prepare messages array with system prompt and conversation history
- messages = [{"role": "system", "content": system_prompt}]
- if message_history:
- messages.extend(message_history)
- messages.append({"role": "user", "content": user_message})
-
- def generate():
- try:
- # Enable streaming
- stream = call_llm_completion(
- messages=messages,
- temperature=0.7,
- max_tokens=int(os.environ.get("CHAT_MAX_TOKENS", "2000")),
- stream=True
- )
-
- # Use helper function to process streaming with thinking tag support
- for response in process_streaming_with_thinking(stream):
- yield response
-
- except Exception as e:
- app.logger.error(f"Error during chat stream generation: {str(e)}")
- # Yield an error message in SSE format
- yield f"data: {json.dumps({'error': str(e)})}\n\n"
-
- return Response(generate(), mimetype='text/event-stream')
-
- except Exception as e:
- app.logger.error(f"Error in chat endpoint: {str(e)}")
- return jsonify({'error': str(e)}), 500
-
-
-# --- Reprocessing Endpoints ---
[email protected]('/recording/<int:recording_id>/reprocess_transcription', methods=['POST'])
-@login_required
-def reprocess_transcription(recording_id):
- """Reprocess transcription for a given recording."""
- try:
- recording = db.session.get(Recording, recording_id)
- if not recording:
- return jsonify({'error': 'Recording not found'}), 404
-
- if recording.user_id and recording.user_id != current_user.id:
- return jsonify({'error': 'You do not have permission to reprocess this recording'}), 403
-
- if not recording.audio_path or not os.path.exists(recording.audio_path):
- return jsonify({'error': 'Audio file not found for reprocessing'}), 404
-
- if recording.status in ['PROCESSING', 'SUMMARIZING']:
- return jsonify({'error': 'Recording is already being processed'}), 400
-
- # --- Convert file if necessary before reprocessing ---
- filepath = recording.audio_path
- filename_for_asr = recording.original_filename or os.path.basename(filepath)
- filename_lower = filename_for_asr.lower()
-
- supported_formats = ('.wav', '.mp3', '.flac')
- if not filename_lower.endswith(supported_formats):
- app.logger.info(f"Reprocessing: Converting {filename_lower} format to high-quality MP3.")
- base_filepath, file_ext = os.path.splitext(filepath)
- temp_mp3_filepath = f"{base_filepath}_temp.mp3"
- final_mp3_filepath = f"{base_filepath}.mp3"
-
- try:
- # Convert to high-quality MP3 (128kbps, 44.1kHz)
- subprocess.run(
- ['ffmpeg', '-i', filepath, '-y', '-acodec', 'libmp3lame', '-b:a', '128k', '-ar', '44100', temp_mp3_filepath],
- check=True, capture_output=True, text=True
- )
- app.logger.info(f"Successfully converted {filepath} to {temp_mp3_filepath} (128kbps MP3)")
-
- # If the original file is not the same as the final mp3 file, remove it
- if filepath.lower() != final_mp3_filepath.lower():
- os.remove(filepath)
-
- # Rename the temporary file to the final filename
- os.rename(temp_mp3_filepath, final_mp3_filepath)
-
- filepath = final_mp3_filepath
- filename_for_asr = os.path.basename(filepath)
-
- # Update database with new path and mime type
- recording.audio_path = filepath
- recording.mime_type, _ = mimetypes.guess_type(filepath)
- db.session.commit()
-
- except FileNotFoundError:
- app.logger.error("ffmpeg command not found. Please ensure ffmpeg is installed and in the system's PATH.")
- return jsonify({'error': 'Audio conversion tool (ffmpeg) not found on server.'}), 500
- except subprocess.CalledProcessError as e:
- app.logger.error(f"ffmpeg conversion failed for {filepath}: {e.stderr}")
- return jsonify({'error': f'Failed to convert audio file: {e.stderr}'}), 500
-
- # --- Proceed with reprocessing ---
- recording.transcription = None
- recording.summary = None
- recording.status = 'PROCESSING'
-
- # Clear existing events since they depend on the transcription
- Event.query.filter_by(recording_id=recording_id).delete()
-
- db.session.commit()
-
- # Refresh the recording object to ensure it has the latest committed data
- db.session.refresh(recording)
-
- app.logger.info(f"Starting transcription reprocessing for recording {recording_id}")
-
- # Decide which transcription method to use
- if USE_ASR_ENDPOINT:
- app.logger.info(f"Using ASR endpoint for reprocessing recording {recording_id}")
-
- data = request.json or {}
- language = data.get('language') or (recording.owner.transcription_language if recording.owner else None)
- min_speakers = data.get('min_speakers') or None
- max_speakers = data.get('max_speakers') or None
-
- # Convert to int if provided
- if min_speakers:
- try:
- min_speakers = int(min_speakers)
- except (ValueError, TypeError):
- min_speakers = None
- if max_speakers:
- try:
- max_speakers = int(max_speakers)
- except (ValueError, TypeError):
- max_speakers = None
-
- # Apply tag defaults if no user input provided (get merged defaults from all tags on this recording)
- if (min_speakers is None or max_speakers is None) and recording.tags:
- # Get tag defaults (use first non-None value from ordered tags)
- for tag_association in sorted(recording.tag_associations, key=lambda x: x.order):
- tag = tag_association.tag
- if min_speakers is None and tag.default_min_speakers:
- min_speakers = tag.default_min_speakers
- if max_speakers is None and tag.default_max_speakers:
- max_speakers = tag.default_max_speakers
- # Stop once we have both values
- if min_speakers is not None and max_speakers is not None:
- break
-
- # Apply environment variable defaults if still no values (reprocess hierarchy: user input > tag defaults > env vars > auto-detect)
- if min_speakers is None and ASR_MIN_SPEAKERS:
- try:
- min_speakers = int(ASR_MIN_SPEAKERS)
- except (ValueError, TypeError):
- min_speakers = None
- if max_speakers is None and ASR_MAX_SPEAKERS:
- try:
- max_speakers = int(ASR_MAX_SPEAKERS)
- except (ValueError, TypeError):
- max_speakers = None
- if '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_DIARIZE
- else:
- diarize_setting = recording.owner.diarize if recording.owner else False
-
- start_time = datetime.utcnow()
- thread = threading.Thread(
- target=transcribe_audio_asr,
- args=(app.app_context(), recording.id, filepath, filename_for_asr, start_time, recording.mime_type, language, diarize_setting, min_speakers, max_speakers)
- )
- else:
- app.logger.info(f"Using standard transcription API for reprocessing recording {recording_id}")
- start_time = datetime.utcnow()
- thread = threading.Thread(
- target=transcribe_audio_task,
- args=(app.app_context(), recording.id, filepath, filename_for_asr, start_time)
- )
-
- thread.start()
-
- return jsonify({
- 'success': True,
- 'message': 'Transcription reprocessing started',
- 'recording': recording.to_dict()
- })
-
- except Exception as e:
- db.session.rollback()
- app.logger.error(f"Error reprocessing transcription for recording {recording_id}: {e}")
- return jsonify({'error': str(e)}), 500
-
-
[email protected]('/recording/<int:recording_id>/reprocess_summary', methods=['POST'])
-@login_required
-def reprocess_summary(recording_id):
- """Reprocess summary for a given recording (requires existing transcription)."""
- try:
- recording = db.session.get(Recording, recording_id)
- if not recording:
- return jsonify({'error': 'Recording not found'}), 404
-
- # Check if the recording belongs to the current user
- if recording.user_id and recording.user_id != current_user.id:
- return jsonify({'error': 'You do not have permission to reprocess this recording'}), 403
-
- # Check if transcription exists
- if not recording.transcription or len(recording.transcription.strip()) < 10:
- return jsonify({'error': 'No valid transcription available for summary generation'}), 400
-
- # Check if already processing
- if recording.status in ['PROCESSING', 'SUMMARIZING']:
- return jsonify({'error': 'Recording is already being processed'}), 400
-
- # Check if OpenRouter client is available
- if client is None:
- return jsonify({'error': 'Summary service is not available (OpenRouter client not configured)'}), 503
-
- # Get custom prompt from request if provided
- data = request.get_json() or {}
- custom_prompt = data.get('custom_prompt', '').strip() if data.get('custom_prompt') else None
-
- # Debug logging
- if custom_prompt:
- app.logger.info(f"Received custom prompt override for recording {recording_id} (length: {len(custom_prompt)})")
- else:
- app.logger.info(f"No custom prompt override provided for recording {recording_id}, will use default priority")
-
- # Set status to SUMMARIZING and clear existing summary
- recording.summary = None
- recording.status = 'SUMMARIZING'
-
- # Clear existing events since they might be re-extracted during summary generation
- Event.query.filter_by(recording_id=recording_id).delete()
-
- db.session.commit()
-
- # Refresh the recording object to ensure it has the latest committed data
- db.session.refresh(recording)
-
- app.logger.info(f"Starting summary reprocessing for recording {recording_id}" +
- (f" with custom prompt (length: {len(custom_prompt)})" if custom_prompt else ""))
-
- # Start summary generation in background thread
- def reprocess_summary_task(app_context, recording_id, custom_prompt_override=None):
- app.logger.info(f"Starting summary reprocessing for recording {recording_id} using generate_summary_only_task")
- generate_summary_only_task(app_context, recording_id, custom_prompt_override=custom_prompt_override)
-
- thread = threading.Thread(
- target=reprocess_summary_task,
- args=(app.app_context(), recording.id, custom_prompt)
- )
- thread.start()
-
- return jsonify({
- 'success': True,
- 'message': 'Summary reprocessing started',
- 'recording': recording.to_dict()
- })
-
- except Exception as e:
- db.session.rollback()
- app.logger.error(f"Error reprocessing summary for recording {recording_id}: {e}")
- return jsonify({'error': str(e)}), 500
-
[email protected]('/recording/<int:recording_id>/reset_status', methods=['POST'])
-@login_required
-def reset_status(recording_id):
- """Resets the status of a stuck or failed recording."""
- try:
- recording = db.session.get(Recording, recording_id)
- if not recording:
- return jsonify({'error': 'Recording not found'}), 404
-
- if recording.user_id and recording.user_id != current_user.id:
- return jsonify({'error': 'You do not have permission to modify this recording'}), 403
-
- # Allow resetting if it's stuck or failed
- if recording.status in ['PROCESSING', 'SUMMARIZING', 'FAILED']:
- recording.status = 'FAILED'
- recording.error_message = "Manually reset from stuck or failed state."
- db.session.commit()
- app.logger.info(f"Manually reset status for recording {recording_id} to FAILED.")
- return jsonify({'success': True, 'message': 'Recording status has been reset.', 'recording': recording.to_dict()})
- else:
- return jsonify({'error': f'Recording is not in a state that can be reset. Current status: {recording.status}'}), 400
-
- except Exception as e:
- db.session.rollback()
- app.logger.error(f"Error resetting status for recording {recording_id}: {e}")
- return jsonify({'error': str(e)}), 500
-
-# --- Authentication Routes ---
[email protected]('/register', methods=['GET', 'POST'])
[email protected]("10 per minute")
-def register():
- # Check if registration is allowed
- allow_registration = os.environ.get('ALLOW_REGISTRATION', 'true').lower() == 'true'
-
- if not allow_registration:
- flash('Registration is currently disabled. Please contact the administrator.', 'danger')
- return redirect(url_for('login'))
-
- if current_user.is_authenticated:
- return redirect(url_for('index'))
-
- form = RegistrationForm()
- if form.validate_on_submit():
- hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
- user = User(username=form.username.data, email=form.email.data, password=hashed_password)
- db.session.add(user)
- db.session.commit()
- flash('Your account has been created! You can now log in.', 'success')
- return redirect(url_for('login'))
-
- return render_template('register.html', title='Register', form=form)
-
-def is_safe_url(target):
- ref_url = urlparse(request.host_url)
- test_url = urlparse(urljoin(request.host_url, target))
- return test_url.scheme in ('http', 'https') and ref_url.netloc == test_url.netloc
-
[email protected]('/login', methods=['GET', 'POST'])
[email protected]("10 per minute")
-def login():
- if current_user.is_authenticated:
- return redirect(url_for('index'))
-
- form = LoginForm()
- if form.validate_on_submit():
- user = User.query.filter_by(email=form.email.data).first()
- if user and bcrypt.check_password_hash(user.password, form.password.data):
- login_user(user, remember=form.remember.data)
- next_page = request.args.get('next')
- if not is_safe_url(next_page):
- return redirect(url_for('index'))
- return redirect(next_page) if next_page else redirect(url_for('index'))
- else:
- flash('Login unsuccessful. Please check email and password.', 'danger')
-
- return render_template('login.html', title='Login', form=form)
-
-def logout():
- logout_user()
- return redirect(url_for('login'))
-
[email protected]('/docs/transcript-templates-guide')
-def transcript_templates_guide():
- """Serve the transcript templates documentation."""
- import os
- import markdown
-
- docs_path = os.path.join(app.root_path, '..', 'docs', 'transcript-templates-guide.md')
-
- if not os.path.exists(docs_path):
- return "Documentation not found", 404
-
- with open(docs_path, 'r', encoding='utf-8') as f:
- content = f.read()
-
- # Convert markdown to HTML
- html_content = markdown.markdown(content, extensions=['tables', 'fenced_code', 'codehilite'])
-
- # Wrap in basic HTML template with Speakr styling
- html_template = f'''
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Transcript Templates Guide - Speakr</title>
- <link rel="stylesheet" href="/static/css/output.css">
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
- <style>
- .markdown-body {{
- max-width: 900px;
- margin: 0 auto;
- padding: 2rem;
- line-height: 1.6;
- }}
- .markdown-body h1 {{ font-size: 2.5rem; margin-bottom: 1rem; }}
- .markdown-body h2 {{ font-size: 2rem; margin-top: 2rem; margin-bottom: 1rem; }}
- .markdown-body h3 {{ font-size: 1.5rem; margin-top: 1.5rem; margin-bottom: 0.75rem; }}
- .markdown-body pre {{ background: #f4f4f4; padding: 1rem; border-radius: 0.5rem; overflow-x: auto; }}
- .markdown-body code {{ background: #f4f4f4; padding: 0.2rem 0.4rem; border-radius: 0.25rem; }}
- .markdown-body pre code {{ background: none; padding: 0; }}
- .markdown-body ul, .markdown-body ol {{ margin-left: 2rem; margin-bottom: 1rem; }}
- .markdown-body li {{ margin-bottom: 0.5rem; }}
- .markdown-body blockquote {{ border-left: 4px solid #ddd; padding-left: 1rem; margin: 1rem 0; }}
- .markdown-body table {{ border-collapse: collapse; width: 100%; margin: 1rem 0; }}
- .markdown-body th, .markdown-body td {{ border: 1px solid #ddd; padding: 0.5rem; }}
- .markdown-body th {{ background: #f4f4f4; }}
- </style>
- </head>
- <body class="bg-[var(--bg-primary)]">
- <div class="min-h-screen">
- <div class="bg-[var(--bg-secondary)] border-b border-[var(--border-primary)] p-4">
- <div class="max-w-6xl mx-auto flex items-center justify-between">
- <a href="/" class="text-2xl font-bold text-[var(--text-primary)]">
- <i class="fas fa-microphone-alt mr-2"></i>Speakr
- </a>
- <a href="/account" class="text-[var(--text-secondary)] hover:text-[var(--text-primary)]">
- Back to Account
- </a>
- </div>
- </div>
- <div class="markdown-body text-[var(--text-primary)]">
- {html_content}
- </div>
- </div>
- </body>
- </html>
- '''
-
- return html_template
-
[email protected]('/account', methods=['GET', 'POST'])
-@login_required
-def account():
- if request.method == 'POST':
- # Only update fields that are present in the form submission
- # This prevents clearing data when switching between tabs
-
- # Check if this is the account information form (has user_name field)
- if 'user_name' in request.form:
- # Handle personal information updates
- user_name = request.form.get('user_name')
- user_job_title = request.form.get('user_job_title')
- user_company = request.form.get('user_company')
- ui_lang = request.form.get('ui_language')
- transcription_lang = request.form.get('transcription_language')
- output_lang = request.form.get('output_language')
-
- current_user.name = user_name if user_name else None
- current_user.job_title = user_job_title if user_job_title else None
- current_user.company = user_company if user_company else None
- current_user.ui_language = ui_lang if ui_lang else 'en'
- current_user.transcription_language = transcription_lang if transcription_lang else None
- current_user.output_language = output_lang if output_lang else None
-
- # Check if this is the custom prompts form (has summary_prompt field)
- elif 'summary_prompt' in request.form:
- # Handle custom prompt updates
- summary_prompt_text = request.form.get('summary_prompt')
- current_user.summary_prompt = summary_prompt_text if summary_prompt_text else None
- # Handle event extraction setting
- current_user.extract_events = 'extract_events' in request.form
-
- # Only update diarize if it's not locked by env var
- if 'ASR_DIARIZE' not in os.environ:
- current_user.diarize = 'diarize' in request.form
-
- db.session.commit()
-
- # Return JSON response for AJAX requests
- if request.headers.get('X-Requested-With') == 'XMLHttpRequest' or request.accept_mimetypes.best == 'application/json':
- return jsonify({'success': True, 'message': 'Account details updated successfully!'})
-
- # Regular form submission with redirect
- flash('Account details updated successfully!', 'success')
-
- # Preserve the active tab when redirecting
- if 'summary_prompt' in request.form:
- return redirect(url_for('account') + '#prompts')
- else:
- return redirect(url_for('account'))
-
- # Get admin default prompt from system settings
- admin_default_prompt = SystemSetting.get_setting('admin_default_summary_prompt', None)
- if admin_default_prompt:
- default_summary_prompt_text = admin_default_prompt
- else:
- # Fallback to hardcoded default if admin hasn't set one
- default_summary_prompt_text = """Generate a comprehensive summary that includes the following sections:
-- **Key Issues Discussed**: A bulleted list of the main topics
-- **Key Decisions Made**: A bulleted list of any decisions reached
-- **Action Items**: A bulleted list of tasks assigned, including who is responsible if mentioned"""
-
- asr_diarize_locked = 'ASR_DIARIZE' in os.environ
-
- return render_template('account.html',
- title='Account',
- default_summary_prompt_text=default_summary_prompt_text,
- use_asr_endpoint=USE_ASR_ENDPOINT,
- asr_diarize_locked=asr_diarize_locked,
- asr_diarize_env_value=ASR_DIARIZE)
-
[email protected]('/change_password', methods=['POST'])
-@login_required
[email protected]("10 per minute")
-def change_password():
- current_password = request.form.get('current_password')
- new_password = request.form.get('new_password')
- confirm_password = request.form.get('confirm_password')
-
- # Validate form data
- if not current_password or not new_password or not confirm_password:
- flash('All fields are required.', 'danger')
- return redirect(url_for('account'))
-
- if new_password != confirm_password:
- flash('New password and confirmation do not match.', 'danger')
- return redirect(url_for('account'))
-
- # Custom validation for new password
- try:
- password_check(None, type('obj', (object,), {'data': new_password}))
- except ValidationError as e:
- flash(str(e), 'danger')
- return redirect(url_for('account'))
-
- # Check if current password is correct
- if not bcrypt.check_password_hash(current_user.password, current_password):
- flash('Current password is incorrect.', 'danger')
- return redirect(url_for('account'))
-
- # Update password
- current_user.password = bcrypt.generate_password_hash(new_password).decode('utf-8')
- db.session.commit()
-
- flash('Your password has been updated successfully.', 'success')
- return redirect(url_for('account'))
-
-# --- Admin Routes ---
[email protected]('/admin', methods=['GET'])
-@login_required
-def admin():
- # Check if user is 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', inquire_mode_enabled=ENABLE_INQUIRE_MODE)
-
[email protected]('/admin/users', methods=['GET'])
-@login_required
-def admin_get_users():
- # Check if user is admin
- if not current_user.is_admin:
- return jsonify({'error': 'Unauthorized'}), 403
-
- users = User.query.all()
- user_data = []
-
- for user in users:
- # Get recordings count and storage used
- recordings_count = len(user.recordings)
- storage_used = sum(r.file_size for r in user.recordings if r.file_size) or 0
-
- user_data.append({
- 'id': user.id,
- 'username': user.username,
- 'email': user.email,
- 'is_admin': user.is_admin,
- 'recordings_count': recordings_count,
- 'storage_used': storage_used
- })
-
- return jsonify(user_data)
-
[email protected]('/admin/users', methods=['POST'])
-@login_required
-def admin_add_user():
- # Check if user is admin
- if not current_user.is_admin:
- return jsonify({'error': 'Unauthorized'}), 403
-
- data = request.json
- if not data:
- return jsonify({'error': 'No data provided'}), 400
-
- # Validate required fields
- required_fields = ['username', 'email', 'password']
- for field in required_fields:
- if field not in data:
- return jsonify({'error': f'Missing required field: {field}'}), 400
-
- # Check if username or email already exists
- if User.query.filter_by(username=data['username']).first():
- return jsonify({'error': 'Username already exists'}), 400
-
- if User.query.filter_by(email=data['email']).first():
- return jsonify({'error': 'Email already exists'}), 400
-
- # Create new user
- hashed_password = bcrypt.generate_password_hash(data['password']).decode('utf-8')
- new_user = User(
- username=data['username'],
- email=data['email'],
- password=hashed_password,
- is_admin=data.get('is_admin', False)
- )
-
- db.session.add(new_user)
- db.session.commit()
-
- return jsonify({
- 'id': new_user.id,
- 'username': new_user.username,
- 'email': new_user.email,
- 'is_admin': new_user.is_admin,
- 'recordings_count': 0,
- 'storage_used': 0
- }), 201
-
[email protected]('/admin/users/<int:user_id>', methods=['PUT'])
-@login_required
-def admin_update_user(user_id):
- # Check if user is admin
- if not current_user.is_admin:
- return jsonify({'error': 'Unauthorized'}), 403
-
- user = db.session.get(User, user_id)
- if not user:
- return jsonify({'error': 'User not found'}), 404
-
- data = request.json
- if not data:
- return jsonify({'error': 'No data provided'}), 400
-
- # Update user fields
- if 'username' in data and data['username'] != user.username:
- # Check if username already exists
- if User.query.filter_by(username=data['username']).first():
- return jsonify({'error': 'Username already exists'}), 400
- user.username = data['username']
-
- if 'email' in data and data['email'] != user.email:
- # Check if email already exists
- if User.query.filter_by(email=data['email']).first():
- return jsonify({'error': 'Email already exists'}), 400
- user.email = data['email']
-
- if 'password' in data and data['password']:
- user.password = bcrypt.generate_password_hash(data['password']).decode('utf-8')
-
- if 'is_admin' in data:
- user.is_admin = data['is_admin']
-
- db.session.commit()
-
- # Get recordings count and storage used
- recordings_count = len(user.recordings)
- storage_used = sum(r.file_size for r in user.recordings if r.file_size) or 0
-
- return jsonify({
- 'id': user.id,
- 'username': user.username,
- 'email': user.email,
- 'is_admin': user.is_admin,
- 'recordings_count': recordings_count,
- 'storage_used': storage_used
- })
-
[email protected]('/admin/users/<int:user_id>', methods=['DELETE'])
-@login_required
-def admin_delete_user(user_id):
- # Check if user is admin
- if not current_user.is_admin:
- return jsonify({'error': 'Unauthorized'}), 403
-
- # Prevent deleting self
- if user_id == current_user.id:
- return jsonify({'error': 'Cannot delete your own account'}), 400
-
- user = db.session.get(User, user_id)
- if not user:
- 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):
- os.remove(recording.audio_path)
- except Exception as e:
- app.logger.error(f"Error deleting audio file {recording.audio_path}: {e}")
-
- # 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})
-
[email protected]('/admin/users/<int:user_id>/toggle-admin', methods=['POST'])
-@login_required
-def admin_toggle_admin(user_id):
- # Check if user is admin
- if not current_user.is_admin:
- return jsonify({'error': 'Unauthorized'}), 403
-
- # Prevent changing own admin status
- if user_id == current_user.id:
- return jsonify({'error': 'Cannot change your own admin status'}), 400
-
- user = db.session.get(User, user_id)
- if not user:
- return jsonify({'error': 'User not found'}), 404
-
- # Toggle admin status
- user.is_admin = not user.is_admin
- db.session.commit()
-
- return jsonify({'success': True, 'is_admin': user.is_admin})
-
[email protected]('/admin/stats', methods=['GET'])
-@login_required
-def admin_get_stats():
- # Check if user is admin
- if not current_user.is_admin:
- return jsonify({'error': 'Unauthorized'}), 403
-
- # Get total users
- total_users = User.query.count()
-
- # Get total recordings
- total_recordings = Recording.query.count()
-
- # Get recordings by status
- completed_recordings = Recording.query.filter_by(status='COMPLETED').count()
- processing_recordings = Recording.query.filter(Recording.status.in_(['PROCESSING', 'SUMMARIZING'])).count()
- pending_recordings = Recording.query.filter_by(status='PENDING').count()
- failed_recordings = Recording.query.filter_by(status='FAILED').count()
-
- # Get total storage used
- total_storage = db.session.query(db.func.sum(Recording.file_size)).scalar() or 0
-
- # Get top users by storage
- top_users_query = db.session.query(
- User.id,
- User.username,
- db.func.count(Recording.id).label('recordings_count'),
- db.func.sum(Recording.file_size).label('storage_used')
- ).join(Recording, User.id == Recording.user_id, isouter=True) \
- .group_by(User.id) \
- .order_by(db.func.sum(Recording.file_size).desc()) \
- .limit(5)
-
- top_users = []
- for user_id, username, recordings_count, storage_used in top_users_query:
- top_users.append({
- 'id': user_id,
- 'username': username,
- 'recordings_count': recordings_count or 0,
- 'storage_used': storage_used or 0
- })
-
- # Get total queries (chat requests)
- # This is a placeholder - you would need to track this in your database
- total_queries = 0
-
- return jsonify({
- 'total_users': total_users,
- 'total_recordings': total_recordings,
- 'completed_recordings': completed_recordings,
- 'processing_recordings': processing_recordings,
- 'pending_recordings': pending_recordings,
- 'failed_recordings': failed_recordings,
- 'total_storage': total_storage,
- 'top_users': top_users,
- 'total_queries': total_queries
- })
-
-# --- Transcript Template Routes ---
[email protected]('/api/transcript-templates', methods=['GET'])
-@login_required
-def get_transcript_templates():
- """Get all transcript templates for the current user."""
- templates = TranscriptTemplate.query.filter_by(user_id=current_user.id).all()
- return jsonify([template.to_dict() for template in templates])
-
[email protected]('/api/transcript-templates', methods=['POST'])
-@login_required
-def create_transcript_template():
- """Create a new transcript template."""
- data = request.json
- if not data or not data.get('name') or not data.get('template'):
- return jsonify({'error': 'Name and template are required'}), 400
-
- # If this is set as default, unset other defaults
- if data.get('is_default'):
- TranscriptTemplate.query.filter_by(
- user_id=current_user.id,
- is_default=True
- ).update({'is_default': False})
-
- template = TranscriptTemplate(
- user_id=current_user.id,
- name=data['name'],
- template=data['template'],
- description=data.get('description'),
- is_default=data.get('is_default', False)
- )
-
- db.session.add(template)
- db.session.commit()
-
- return jsonify(template.to_dict()), 201
-
[email protected]('/api/transcript-templates/<int:template_id>', methods=['PUT'])
-@login_required
-def update_transcript_template(template_id):
- """Update an existing transcript template."""
- template = TranscriptTemplate.query.filter_by(
- id=template_id,
- user_id=current_user.id
- ).first()
-
- if not template:
- return jsonify({'error': 'Template not found'}), 404
-
- data = request.json
- if not data:
- return jsonify({'error': 'No data provided'}), 400
-
- # If this is set as default, unset other defaults
- if data.get('is_default'):
- TranscriptTemplate.query.filter_by(
- user_id=current_user.id,
- is_default=True
- ).update({'is_default': False})
-
- template.name = data.get('name', template.name)
- template.template = data.get('template', template.template)
- template.description = data.get('description', template.description)
- template.is_default = data.get('is_default', template.is_default)
- template.updated_at = datetime.utcnow()
-
- db.session.commit()
-
- return jsonify(template.to_dict())
-
[email protected]('/api/transcript-templates/<int:template_id>', methods=['DELETE'])
-@login_required
-def delete_transcript_template(template_id):
- """Delete a transcript template."""
- template = TranscriptTemplate.query.filter_by(
- id=template_id,
- user_id=current_user.id
- ).first()
-
- if not template:
- return jsonify({'error': 'Template not found'}), 404
-
- db.session.delete(template)
- db.session.commit()
-
- return jsonify({'success': True})
-
[email protected]('/api/transcript-templates/create-defaults', methods=['POST'])
-@login_required
-def create_default_templates():
- """Create default templates for the user if they don't have any."""
- existing_templates = TranscriptTemplate.query.filter_by(user_id=current_user.id).count()
-
- if existing_templates > 0:
- return jsonify({'message': 'User already has templates'}), 200
-
- templates = []
-
- # Default template 1: Simple conversation
- template1 = TranscriptTemplate(
- user_id=current_user.id,
- name="Simple Conversation",
- template="{{speaker}}: {{text}}",
- description="Clean format with just speaker names and text",
- is_default=True
- )
- templates.append(template1)
-
- # Default template 2: Timestamped format
- template2 = TranscriptTemplate(
- user_id=current_user.id,
- name="Timestamped",
- template="[{{start_time}} - {{end_time}}] {{speaker}}: {{text}}",
- description="Format with timestamps and speaker names",
- is_default=False
- )
- templates.append(template2)
-
- # Default template 3: Interview Q&A
- template3 = TranscriptTemplate(
- user_id=current_user.id,
- name="Interview Q&A",
- template="{{speaker|upper}}:\n{{text}}\n",
- description="Interview format with speaker names in uppercase",
- is_default=False
- )
- templates.append(template3)
-
- # Default template 4: Meeting Minutes
- template4 = TranscriptTemplate(
- user_id=current_user.id,
- name="Meeting Minutes",
- template="• [{{start_time}}] {{speaker}}: {{text}}",
- description="Bulleted format ideal for meeting notes",
- is_default=False
- )
- templates.append(template4)
-
- # Default template 5: Court Transcript
- template5 = TranscriptTemplate(
- user_id=current_user.id,
- name="Court Transcript",
- template="{{index}} {{speaker|upper}}: {{text}}",
- description="Legal deposition format with line numbers",
- is_default=False
- )
- templates.append(template5)
-
- # Default template 6: SRT Subtitle
- template6 = TranscriptTemplate(
- user_id=current_user.id,
- name="SRT Subtitle",
- template="{{index}}\n{{start_time|srt}} --> {{end_time|srt}}\n{{text}}\n",
- description="SRT subtitle format for video editing",
- is_default=False
- )
- templates.append(template6)
-
- # Default template 7: Screenplay
- template7 = TranscriptTemplate(
- user_id=current_user.id,
- name="Screenplay",
- template=" {{speaker|upper}}\n {{text}}\n",
- description="Film script format with centered names",
- is_default=False
- )
- templates.append(template7)
-
- # Add all templates to database
- for template in templates:
- db.session.add(template)
-
- db.session.commit()
-
- return jsonify({
- 'success': True,
- 'templates': [template.to_dict() for template in templates]
- }), 201
-
[email protected]('/admin/settings', methods=['GET'])
-@login_required
-def admin_get_settings():
- # Check if user is admin
- if not current_user.is_admin:
- return jsonify({'error': 'Unauthorized'}), 403
-
- settings = SystemSetting.query.all()
- return jsonify([setting.to_dict() for setting in settings])
-
[email protected]('/admin/settings', methods=['POST'])
-@login_required
-def admin_update_setting():
- # Check if user is admin
- if not current_user.is_admin:
- return jsonify({'error': 'Unauthorized'}), 403
-
- data = request.json
- if not data:
- return jsonify({'error': 'No data provided'}), 400
-
- key = data.get('key')
- value = data.get('value')
- description = data.get('description')
- setting_type = data.get('setting_type', 'string')
-
- if not key:
- return jsonify({'error': 'Setting key is required'}), 400
-
- # Validate setting type
- valid_types = ['string', 'integer', 'boolean', 'float']
- if setting_type not in valid_types:
- return jsonify({'error': f'Invalid setting type. Must be one of: {", ".join(valid_types)}'}), 400
-
- # Validate value based on type
- if setting_type == 'integer':
- try:
- int(value) if value is not None and value != '' else None
- except (ValueError, TypeError):
- return jsonify({'error': 'Value must be a valid integer'}), 400
- elif setting_type == 'float':
- try:
- float(value) if value is not None and value != '' else None
- except (ValueError, TypeError):
- return jsonify({'error': 'Value must be a valid number'}), 400
- elif setting_type == 'boolean':
- if value not in ['true', 'false', '1', '0', 'yes', 'no', True, False, 1, 0]:
- return jsonify({'error': 'Value must be a valid boolean (true/false, 1/0, yes/no)'}), 400
-
- try:
- setting = SystemSetting.set_setting(key, value, description, setting_type)
- return jsonify(setting.to_dict())
- except Exception as e:
- db.session.rollback()
- app.logger.error(f"Error updating setting {key}: {e}")
- return jsonify({'error': str(e)}), 500
-
-# --- Configuration API ---
[email protected]('/api/config', methods=['GET'])
-def get_config():
- """Get application configuration settings for the frontend."""
- try:
- # Get configurable file size limit
- max_file_size_mb = SystemSetting.get_setting('max_file_size_mb', 250)
-
- # Get chunking configuration (supports both legacy and new formats)
- chunking_info = {}
- if ENABLE_CHUNKING and chunking_service:
- mode, limit_value = chunking_service.parse_chunk_limit()
- chunking_info = {
- 'chunking_enabled': True,
- 'chunking_mode': mode, # 'size' or 'duration'
- 'chunking_limit': limit_value, # Value in MB or seconds
- 'chunking_limit_display': f"{limit_value}{'MB' if mode == 'size' else 's'}"
- }
- else:
- chunking_info = {
- 'chunking_enabled': False,
- 'chunking_mode': 'size',
- 'chunking_limit': 20,
- 'chunking_limit_display': '20MB'
- }
-
- return jsonify({
- 'max_file_size_mb': max_file_size_mb,
- 'recording_disclaimer': SystemSetting.get_setting('recording_disclaimer', ''),
- 'use_asr_endpoint': USE_ASR_ENDPOINT,
- **chunking_info
- })
- except Exception as e:
- app.logger.error(f"Error fetching configuration: {e}")
- return jsonify({'error': str(e)}), 500
-
-
[email protected]('/api/csrf-token', methods=['GET'])
[email protected] # Exempt this endpoint from CSRF protection since it's providing tokens
-def get_csrf_token():
- """Get a fresh CSRF token for the frontend."""
- try:
- from flask_wtf.csrf import generate_csrf
- token = generate_csrf()
- app.logger.info("Fresh CSRF token generated successfully")
- return jsonify({'csrf_token': token})
- except Exception as e:
- app.logger.error(f"Error generating CSRF token: {e}")
- return jsonify({'error': str(e)}), 500
-
-# --- Flask Routes ---
-@login_required
-def index():
- # Pass the ASR config, inquire mode config, and user language preference to the template
- user_language = current_user.ui_language if current_user.is_authenticated and current_user.ui_language else 'en'
- return render_template('index.html',
- use_asr_endpoint=USE_ASR_ENDPOINT,
- inquire_mode_enabled=ENABLE_INQUIRE_MODE,
- user_language=user_language)
-
[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)
-
[email protected]('/recordings', methods=['GET'])
-def get_recordings():
- try:
- # Check if user is logged in
- if not current_user.is_authenticated:
- return jsonify([]) # Return empty array if not logged in
-
- # Filter recordings by the current user
- stmt = select(Recording).where(Recording.user_id == current_user.id).order_by(Recording.created_at.desc())
- recordings = db.session.execute(stmt).scalars().all()
- return jsonify([recording.to_dict() for recording in recordings])
- except Exception as e:
- app.logger.error(f"Error fetching recordings: {e}")
- return jsonify({'error': str(e)}), 500
-
[email protected]('/api/recordings', methods=['GET'])
-@login_required
[email protected]("1250 per hour")
-def get_recordings_paginated():
- """Get recordings with pagination and server-side filtering."""
- try:
- # Parse query parameters
- page = request.args.get('page', 1, type=int)
- per_page = min(request.args.get('per_page', 25, type=int), 100) # Cap at 100 per page
- search_query = request.args.get('q', '').strip()
-
- # Build base query
- stmt = select(Recording).where(Recording.user_id == current_user.id)
-
- # Apply search filters if provided
- if search_query:
- # Parse search query for special syntax
- import re
-
- # Extract date filters
- date_filters = re.findall(r'date:(\S+)', search_query.lower())
- date_from_filters = re.findall(r'date_from:(\S+)', search_query.lower())
- date_to_filters = re.findall(r'date_to:(\S+)', search_query.lower())
- tag_filters = re.findall(r'tag:(\S+)', search_query.lower())
-
- # Remove special syntax to get text search
- text_query = re.sub(r'date:\S+', '', search_query, flags=re.IGNORECASE)
- text_query = re.sub(r'date_from:\S+', '', text_query, flags=re.IGNORECASE)
- text_query = re.sub(r'date_to:\S+', '', text_query, flags=re.IGNORECASE)
- text_query = re.sub(r'tag:\S+', '', text_query, flags=re.IGNORECASE).strip()
-
- # Apply date filters
- for date_filter in date_filters:
- if date_filter == 'today':
- today = datetime.now().date()
- stmt = stmt.where(
- db.or_(
- db.func.date(Recording.meeting_date) == today,
- db.and_(
- Recording.meeting_date.is_(None),
- db.func.date(Recording.created_at) == today
- )
- )
- )
- elif date_filter == 'yesterday':
- yesterday = datetime.now().date() - timedelta(days=1)
- stmt = stmt.where(
- db.or_(
- db.func.date(Recording.meeting_date) == yesterday,
- db.and_(
- Recording.meeting_date.is_(None),
- db.func.date(Recording.created_at) == yesterday
- )
- )
- )
- elif date_filter == 'thisweek':
- today = datetime.now().date()
- start_of_week = today - timedelta(days=today.weekday())
- stmt = stmt.where(
- db.or_(
- Recording.meeting_date >= start_of_week,
- db.and_(
- Recording.meeting_date.is_(None),
- db.func.date(Recording.created_at) >= start_of_week
- )
- )
- )
- elif date_filter == 'lastweek':
- today = datetime.now().date()
- end_of_last_week = today - timedelta(days=today.weekday())
- start_of_last_week = end_of_last_week - timedelta(days=7)
- stmt = stmt.where(
- db.or_(
- db.and_(
- Recording.meeting_date >= start_of_last_week,
- Recording.meeting_date < end_of_last_week
- ),
- db.and_(
- Recording.meeting_date.is_(None),
- db.func.date(Recording.created_at) >= start_of_last_week,
- db.func.date(Recording.created_at) < end_of_last_week
- )
- )
- )
- elif date_filter == 'thismonth':
- today = datetime.now().date()
- start_of_month = today.replace(day=1)
- stmt = stmt.where(
- db.or_(
- Recording.meeting_date >= start_of_month,
- db.and_(
- Recording.meeting_date.is_(None),
- db.func.date(Recording.created_at) >= start_of_month
- )
- )
- )
- elif date_filter == 'lastmonth':
- today = datetime.now().date()
- first_day_this_month = today.replace(day=1)
- last_day_last_month = first_day_this_month - timedelta(days=1)
- first_day_last_month = last_day_last_month.replace(day=1)
- stmt = stmt.where(
- db.or_(
- db.and_(
- Recording.meeting_date >= first_day_last_month,
- Recording.meeting_date <= last_day_last_month
- ),
- db.and_(
- Recording.meeting_date.is_(None),
- db.func.date(Recording.created_at) >= first_day_last_month,
- db.func.date(Recording.created_at) <= last_day_last_month
- )
- )
- )
- elif re.match(r'^\d{4}-\d{2}-\d{2}$', date_filter):
- # Specific date format YYYY-MM-DD
- target_date = datetime.strptime(date_filter, '%Y-%m-%d').date()
- stmt = stmt.where(
- db.or_(
- db.func.date(Recording.meeting_date) == target_date,
- db.and_(
- Recording.meeting_date.is_(None),
- db.func.date(Recording.created_at) == target_date
- )
- )
- )
- elif re.match(r'^\d{4}-\d{2}$', date_filter):
- # Month format YYYY-MM
- year, month = map(int, date_filter.split('-'))
- stmt = stmt.where(
- db.or_(
- db.and_(
- db.extract('year', Recording.meeting_date) == year,
- db.extract('month', Recording.meeting_date) == month
- ),
- db.and_(
- Recording.meeting_date.is_(None),
- db.extract('year', Recording.created_at) == year,
- db.extract('month', Recording.created_at) == month
- )
- )
- )
- elif re.match(r'^\d{4}$', date_filter):
- # Year format YYYY
- year = int(date_filter)
- stmt = stmt.where(
- db.or_(
- db.extract('year', Recording.meeting_date) == year,
- db.and_(
- Recording.meeting_date.is_(None),
- db.extract('year', Recording.created_at) == year
- )
- )
- )
-
- # Apply date range filters
- if date_from_filters and date_from_filters[0]:
- try:
- date_from = datetime.strptime(date_from_filters[0], '%Y-%m-%d').date()
- stmt = stmt.where(
- db.or_(
- Recording.meeting_date >= date_from,
- db.and_(
- Recording.meeting_date.is_(None),
- db.func.date(Recording.created_at) >= date_from
- )
- )
- )
- except ValueError:
- pass # Invalid date format, ignore
-
- if date_to_filters and date_to_filters[0]:
- try:
- date_to = datetime.strptime(date_to_filters[0], '%Y-%m-%d').date()
- stmt = stmt.where(
- db.or_(
- Recording.meeting_date <= date_to,
- db.and_(
- Recording.meeting_date.is_(None),
- db.func.date(Recording.created_at) <= date_to
- )
- )
- )
- except ValueError:
- pass # Invalid date format, ignore
-
- # Apply tag filters
- if tag_filters:
- # Join with tags table and filter by tag names
- tag_conditions = []
- for tag_filter in tag_filters:
- # Replace underscores back to spaces for matching
- tag_name = tag_filter.replace('_', ' ')
- tag_conditions.append(Tag.name.ilike(f'%{tag_name}%'))
-
- stmt = stmt.join(RecordingTag).join(Tag).where(db.or_(*tag_conditions))
-
- # Apply text search
- if text_query:
- text_conditions = [
- Recording.title.ilike(f'%{text_query}%'),
- Recording.participants.ilike(f'%{text_query}%'),
- Recording.transcription.ilike(f'%{text_query}%'),
- Recording.notes.ilike(f'%{text_query}%')
- ]
- stmt = stmt.where(db.or_(*text_conditions))
-
- # Apply ordering (most recent first based on meeting_date or created_at)
- stmt = stmt.order_by(
- db.case(
- (Recording.meeting_date.is_not(None), Recording.meeting_date),
- else_=db.func.date(Recording.created_at)
- ).desc(),
- Recording.created_at.desc()
- )
-
- # Get total count for pagination info
- count_stmt = select(db.func.count()).select_from(stmt.subquery())
- total_count = db.session.execute(count_stmt).scalar()
-
- # Apply pagination
- offset = (page - 1) * per_page
- stmt = stmt.offset(offset).limit(per_page)
-
- # Execute query
- recordings = db.session.execute(stmt).scalars().all()
-
- # Calculate pagination metadata
- total_pages = (total_count + per_page - 1) // per_page
- has_next = page < total_pages
- has_prev = page > 1
-
- return jsonify({
- 'recordings': [recording.to_dict() for recording in recordings],
- 'pagination': {
- 'page': page,
- 'per_page': per_page,
- 'total': total_count,
- 'total_pages': total_pages,
- 'has_next': has_next,
- 'has_prev': has_prev
- }
- })
-
- except Exception as e:
- app.logger.error(f"Error fetching paginated recordings: {e}")
- return jsonify({'error': str(e)}), 500
-
[email protected]('/api/inbox_recordings', methods=['GET'])
-@login_required
[email protected]("1250 per hour") # Allow frequent polling for inbox recordings
-def get_inbox_recordings():
- """Get recordings that are in the inbox and currently processing."""
- try:
- stmt = select(Recording).where(
- Recording.user_id == current_user.id,
- Recording.is_inbox == True,
- Recording.status.in_(['PENDING', 'PROCESSING', 'SUMMARIZING'])
- ).order_by(Recording.created_at.desc())
-
- recordings = db.session.execute(stmt).scalars().all()
- return jsonify([recording.to_dict() for recording in recordings])
- except Exception as e:
- app.logger.error(f"Error fetching inbox recordings: {e}")
- return jsonify({'error': str(e)}), 500
-
[email protected]('/save', methods=['POST'])
-@login_required
-def save_metadata():
- try:
- data = request.json
- if not data: return jsonify({'error': 'No data provided'}), 400
- recording_id = data.get('id')
- if not recording_id: return jsonify({'error': 'No recording ID provided'}), 400
-
- recording = db.session.get(Recording, recording_id)
- if not recording: return jsonify({'error': 'Recording not found'}), 404
-
- # Check if the recording belongs to the current user
- if recording.user_id and recording.user_id != current_user.id:
- return jsonify({'error': 'You do not have permission to edit this recording'}), 403
-
- # Update fields if provided (with sanitization for notes and summary)
- if 'title' in data: recording.title = data['title']
- if 'participants' in data: recording.participants = data['participants']
- if 'notes' in data: recording.notes = sanitize_html(data['notes']) if data['notes'] else data['notes']
- if 'summary' in data: recording.summary = sanitize_html(data['summary']) if data['summary'] else data['summary']
- if 'is_inbox' in data: recording.is_inbox = data['is_inbox']
- if 'is_highlighted' in data: recording.is_highlighted = data['is_highlighted']
- if 'meeting_date' in data:
- try:
- # Attempt to parse date string (e.g., "YYYY-MM-DD")
- date_str = data['meeting_date']
- if date_str:
- recording.meeting_date = datetime.strptime(date_str, '%Y-%m-%d').date()
- else:
- recording.meeting_date = None # Allow clearing the date
- except (ValueError, TypeError) as e:
- app.logger.warning(f"Could not parse meeting_date '{data.get('meeting_date')}': {e}")
- # Optionally return an error or just ignore the invalid date
- # return jsonify({'error': f"Invalid date format for meeting_date. Use YYYY-MM-DD."}), 400
-
- # Do not update transcription or status here
- db.session.commit()
- return jsonify({'success': True, 'recording': recording.to_dict()})
-
- except Exception as e:
- db.session.rollback()
- app.logger.error(f"Error saving metadata for recording {recording_id}: {e}", exc_info=True)
- return jsonify({'error': 'An unexpected error occurred while saving.'}), 500
-
[email protected]('/recording/<int:recording_id>/update_transcription', methods=['POST'])
-@login_required
-def update_transcription(recording_id):
- """Updates the transcription content for a recording."""
- try:
- recording = db.session.get(Recording, recording_id)
- if not recording:
- return jsonify({'error': 'Recording not found'}), 404
-
- if recording.user_id and recording.user_id != current_user.id:
- return jsonify({'error': 'You do not have permission to edit this recording'}), 403
-
- data = request.json
- new_transcription = data.get('transcription')
-
- if new_transcription is None:
- return jsonify({'error': 'No transcription data provided'}), 400
-
- # The incoming data could be a JSON string (from ASR edit) or plain text
- recording.transcription = new_transcription
-
- # Optional: If the transcription changes, we might want to indicate that the summary is outdated.
- # For now, we'll just save the transcript. A "regenerate summary" button could be a good follow-up.
-
- db.session.commit()
- app.logger.info(f"Transcription for recording {recording_id} was updated.")
-
- return jsonify({'success': True, 'message': 'Transcription updated successfully.', 'recording': recording.to_dict()})
-
- except Exception as e:
- db.session.rollback()
- app.logger.error(f"Error updating transcription for recording {recording_id}: {e}", exc_info=True)
- return jsonify({'error': 'An unexpected error occurred while updating the transcription.'}), 500
-
-# Toggle inbox status endpoint
[email protected]('/recording/<int:recording_id>/toggle_inbox', methods=['POST'])
-@login_required
-def toggle_inbox(recording_id):
- try:
- recording = db.session.get(Recording, recording_id)
- if not recording:
- return jsonify({'error': 'Recording not found'}), 404
-
- # Check if the recording belongs to the current user
- if recording.user_id and recording.user_id != current_user.id:
- return jsonify({'error': 'You do not have permission to modify this recording'}), 403
-
- # Toggle the inbox status
- recording.is_inbox = not recording.is_inbox
- db.session.commit()
-
- return jsonify({'success': True, 'is_inbox': recording.is_inbox})
- except Exception as e:
- db.session.rollback()
- app.logger.error(f"Error toggling inbox status for recording {recording_id}: {e}", exc_info=True)
- return jsonify({'error': 'An unexpected error occurred.'}), 500
-
-# Toggle highlighted status endpoint
[email protected]('/recording/<int:recording_id>/toggle_highlight', methods=['POST'])
-@login_required
-def toggle_highlight(recording_id):
- try:
- recording = db.session.get(Recording, recording_id)
- if not recording:
- return jsonify({'error': 'Recording not found'}), 404
-
- # Check if the recording belongs to the current user
- if recording.user_id and recording.user_id != current_user.id:
- return jsonify({'error': 'You do not have permission to modify this recording'}), 403
-
- # Toggle the highlighted status
- recording.is_highlighted = not recording.is_highlighted
- db.session.commit()
-
- return jsonify({'success': True, 'is_highlighted': recording.is_highlighted})
- except Exception as e:
- db.session.rollback()
- app.logger.error(f"Error toggling highlighted status for recording {recording_id}: {e}", exc_info=True)
- return jsonify({'error': 'An unexpected error occurred.'}), 500
-
-
[email protected]('/upload', methods=['POST'])
-@login_required
-def upload_file():
- try:
- if 'file' not in request.files:
- return jsonify({'error': 'No file provided'}), 400
-
- file = request.files['file']
- if file.filename == '':
- return jsonify({'error': 'No file selected'}), 400
-
- original_filename = file.filename
- safe_filename = secure_filename(original_filename)
- filepath = os.path.join(app.config['UPLOAD_FOLDER'], f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{safe_filename}")
-
- # Get original file size
- file.seek(0, os.SEEK_END)
- original_file_size = file.tell()
- file.seek(0)
-
- # Check size limit before saving - only enforce if chunking is disabled or using ASR endpoint
- max_content_length = app.config.get('MAX_CONTENT_LENGTH')
-
- # Skip size check if chunking is enabled and using OpenAI Whisper API
- should_enforce_size_limit = True
- if ENABLE_CHUNKING and chunking_service and not USE_ASR_ENDPOINT:
- should_enforce_size_limit = False
- # 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()
-
- file.save(filepath)
- app.logger.info(f"File saved to {filepath}")
-
- # --- Convert files only when chunking is needed ---
- filename_lower = original_filename.lower()
-
- # Check if chunking will be needed for this file
- needs_chunking_for_processing = (chunking_service and
- ENABLE_CHUNKING and
- not USE_ASR_ENDPOINT and
- chunking_service.needs_chunking(filepath, USE_ASR_ENDPOINT))
-
- # Define supported formats based on whether chunking is needed
- if needs_chunking_for_processing:
- # For chunking: only support formats that work well with chunking
- supported_formats = ('.wav', '.mp3', '.flac')
- convertible_formats = ('.amr', '.3gp', '.3gpp', '.m4a', '.aac', '.ogg', '.wma', '.webm')
- else:
- # For direct transcription: support WebM and other formats directly
- supported_formats = ('.wav', '.mp3', '.flac', '.webm', '.m4a', '.aac', '.ogg')
- convertible_formats = ('.amr', '.3gp', '.3gpp', '.wma')
-
- # Special handling for problematic AAC files when using ASR endpoint
- is_problematic_aac = (USE_ASR_ENDPOINT and
- (filename_lower.endswith('.aac') or
- 'aac' in filename_lower.lower()))
-
- # Convert if file is not in supported formats OR is problematic AAC for ASR
- should_convert = ((not filename_lower.endswith(supported_formats) and needs_chunking_for_processing) or
- is_problematic_aac)
-
- if should_convert:
- if is_problematic_aac:
- app.logger.info(f"Converting AAC-encoded file {filename_lower} to high-quality MP3 for ASR endpoint compatibility.")
- elif filename_lower.endswith(convertible_formats):
- app.logger.info(f"Converting {filename_lower} format to high-quality MP3 for chunking processing.")
- else:
- app.logger.info(f"Attempting to convert unknown format ({filename_lower}) to high-quality MP3 for chunking.")
-
- base_filepath, _ = os.path.splitext(filepath)
- temp_mp3_filepath = f"{base_filepath}_temp.mp3"
- mp3_filepath = f"{base_filepath}.mp3"
-
- try:
- # Convert to high-quality MP3 (128kbps, 44.1kHz) for better transcription accuracy
- subprocess.run(
- ['ffmpeg', '-i', filepath, '-y', '-acodec', 'libmp3lame', '-b:a', '128k', '-ar', '44100', '-ac', '1', temp_mp3_filepath],
- check=True, capture_output=True, text=True
- )
- app.logger.info(f"Successfully converted {filepath} to {temp_mp3_filepath} (128kbps MP3)")
-
- # If the original file is not the same as the final mp3 file, remove it
- if filepath.lower() != mp3_filepath.lower():
- os.remove(filepath)
-
- # Rename the temporary file to the final filename
- os.rename(temp_mp3_filepath, mp3_filepath)
-
- filepath = mp3_filepath
- except FileNotFoundError:
- app.logger.error("ffmpeg command not found. Please ensure ffmpeg is installed and in the system's PATH.")
- return jsonify({'error': 'Audio conversion tool (ffmpeg) not found on server.'}), 500
- except subprocess.CalledProcessError as e:
- app.logger.error(f"ffmpeg conversion failed for {filepath}: {e.stderr}")
- return jsonify({'error': f'Failed to convert audio file: {e.stderr}'}), 500
- elif not filename_lower.endswith(supported_formats):
- # File is not supported and chunking is not needed - log but don't convert
- app.logger.info(f"File format {filename_lower} will be processed directly without conversion (chunking not needed)")
-
- # Get final file size (of original or converted file)
- final_file_size = os.path.getsize(filepath)
-
- # Determine MIME type of the final file
- mime_type, _ = mimetypes.guess_type(filepath)
- app.logger.info(f"Final MIME type: {mime_type} for file {filepath}")
-
- # Get notes from the form
- notes = request.form.get('notes')
-
- # Get selected tags if provided (multiple tags support)
- selected_tags = []
- tag_index = 0
- while True:
- tag_id_key = f'tag_ids[{tag_index}]'
- tag_id = request.form.get(tag_id_key)
- if not tag_id:
- break
-
- tag = Tag.query.filter_by(id=tag_id, user_id=current_user.id).first()
- if tag:
- selected_tags.append(tag)
- tag_index += 1
-
- # For backward compatibility with single tag uploads
- if not selected_tags:
- single_tag_id = request.form.get('tag_id')
- if single_tag_id:
- tag = Tag.query.filter_by(id=single_tag_id, user_id=current_user.id).first()
- if tag:
- selected_tags.append(tag)
-
- # Get ASR advanced options if provided
- language = request.form.get('language', '')
- min_speakers = request.form.get('min_speakers') or None
- max_speakers = request.form.get('max_speakers') or None
-
- # Convert to int if provided
- if min_speakers:
- try:
- min_speakers = int(min_speakers)
- except (ValueError, TypeError):
- min_speakers = None
- if max_speakers:
- try:
- max_speakers = int(max_speakers)
- except (ValueError, TypeError):
- max_speakers = None
-
- # Apply precedence hierarchy: user input > tag defaults > environment variables > auto-detect
-
- # Apply tag defaults if tags are selected and values are not explicitly provided by user
- # Use first tag's defaults (highest priority)
- if selected_tags:
- first_tag = selected_tags[0]
- if not language and first_tag.default_language:
- language = first_tag.default_language
- if min_speakers is None and first_tag.default_min_speakers:
- min_speakers = first_tag.default_min_speakers
- if max_speakers is None and first_tag.default_max_speakers:
- max_speakers = first_tag.default_max_speakers
-
- # Apply environment variable defaults if still no values are set
- if min_speakers is None and ASR_MIN_SPEAKERS:
- try:
- min_speakers = int(ASR_MIN_SPEAKERS)
- except (ValueError, TypeError):
- min_speakers = None
- if max_speakers is None and ASR_MAX_SPEAKERS:
- try:
- max_speakers = int(ASR_MAX_SPEAKERS)
- except (ValueError, TypeError):
- max_speakers = None
-
- # Create initial database entry
- now = datetime.utcnow()
- recording = Recording(
- audio_path=filepath,
- original_filename=original_filename,
- title=f"Recording - {original_filename}",
- file_size=final_file_size,
- status='PENDING',
- meeting_date=now.date(),
- user_id=current_user.id,
- mime_type=mime_type,
- notes=notes,
- processing_source='upload' # Track that this was manually uploaded
- )
- db.session.add(recording)
- db.session.commit()
-
- # Add tags to recording if selected (preserve order)
- for order, tag in enumerate(selected_tags, 1):
- new_association = RecordingTag(
- recording_id=recording.id,
- tag_id=tag.id,
- order=order,
- added_at=datetime.utcnow()
- )
- db.session.add(new_association)
-
- if selected_tags:
- db.session.commit()
- tag_names = [tag.name for tag in selected_tags]
- app.logger.info(f"Added {len(selected_tags)} tags to recording {recording.id}: {', '.join(tag_names)}")
-
- app.logger.info(f"Initial recording record created with ID: {recording.id}")
-
- # --- Start transcription & summarization in background thread ---
- start_time = datetime.utcnow()
-
- # Pass ASR parameters and first tag to the transcription task (for compatibility with existing functions)
- first_tag = selected_tags[0] if selected_tags else None
- if USE_ASR_ENDPOINT:
- app.logger.info(f"Starting ASR transcription thread for recording {recording.id} with params: language={language}, min_speakers={min_speakers}, max_speakers={max_speakers}, tag_id={first_tag.id if first_tag else None}")
- thread = threading.Thread(
- target=transcribe_audio_task,
- args=(app.app_context(), recording.id, filepath, os.path.basename(filepath), start_time),
- kwargs={'language': language, 'min_speakers': min_speakers, 'max_speakers': max_speakers, 'tag_id': first_tag.id if first_tag else None}
- )
- else:
- app.logger.info(f"Starting Whisper transcription thread for recording {recording.id} with tag_id={first_tag.id if first_tag else None}")
- thread = threading.Thread(
- target=transcribe_audio_task,
- args=(app.app_context(), recording.id, filepath, os.path.basename(filepath), start_time),
- kwargs={'tag_id': first_tag.id if first_tag else None}
- )
- thread.start()
- app.logger.info(f"Background processing thread started for recording ID: {recording.id}")
-
- return jsonify(recording.to_dict()), 202
-
- except RequestEntityTooLarge:
- max_size_mb = app.config['MAX_CONTENT_LENGTH'] / (1024 * 1024)
- app.logger.warning(f"Upload failed: File too large (>{max_size_mb}MB)")
- return jsonify({
- 'error': f'File too large. Maximum size is {max_size_mb:.0f} MB.',
- 'max_size_mb': max_size_mb
- }), 413
- except Exception as e:
- db.session.rollback()
- app.logger.error(f"Error during file upload: {e}", exc_info=True)
- return jsonify({'error': 'An unexpected error occurred during upload.'}), 500
-
-
-# Status Endpoint
[email protected]('/status/<int:recording_id>', methods=['GET'])
-@login_required
[email protected]("1250 per hour") # Allow frequent polling for status checks
-def get_status(recording_id):
- """Endpoint to check the transcription/summarization status."""
- try:
- recording = db.session.get(Recording, recording_id)
- if not recording:
- return jsonify({'error': 'Recording not found'}), 404
-
- # Check if the recording belongs to the current user
- if recording.user_id and recording.user_id != current_user.id:
- return jsonify({'error': 'You do not have permission to view this recording'}), 403
-
- # Ensure events are loaded (refresh the recording to get latest relationships)
- db.session.refresh(recording)
-
- return jsonify(recording.to_dict())
- except Exception as e:
- app.logger.error(f"Error fetching status for recording {recording_id}: {e}", exc_info=True)
- return jsonify({'error': 'An unexpected error occurred.'}), 500
-
-# Get Audio Endpoint
[email protected]('/audio/<int:recording_id>')
-@login_required
-def get_audio(recording_id):
- try:
- recording = db.session.get(Recording, recording_id)
- if not recording or not recording.audio_path:
- return jsonify({'error': 'Recording or audio file not found'}), 404
-
- # Check if the recording belongs to the current user
- if recording.user_id and recording.user_id != current_user.id:
- return jsonify({'error': 'You do not have permission to access this audio file'}), 403
- if not os.path.exists(recording.audio_path):
- app.logger.error(f"Audio file missing from server: {recording.audio_path}")
- return jsonify({'error': 'Audio file missing from server'}), 404
- return send_file(recording.audio_path)
- except Exception as e:
- app.logger.error(f"Error serving audio for recording {recording_id}: {e}", exc_info=True)
- return jsonify({'error': 'An unexpected error occurred.'}), 500
-
[email protected]('/share/audio/<string:public_id>')
-def get_shared_audio(public_id):
- try:
- share = Share.query.filter_by(public_id=public_id).first_or_404()
- recording = share.recording
- if not recording or not recording.audio_path:
- return jsonify({'error': 'Recording or audio file not found'}), 404
- if not os.path.exists(recording.audio_path):
- app.logger.error(f"Audio file missing from server: {recording.audio_path}")
- return jsonify({'error': 'Audio file missing from server'}), 404
- return send_file(recording.audio_path)
- except Exception as e:
- app.logger.error(f"Error serving shared audio for public_id {public_id}: {e}", exc_info=True)
- return jsonify({'error': 'An unexpected error occurred.'}), 500
-
-# Delete Recording Endpoint
[email protected]('/recording/<int:recording_id>', methods=['DELETE'])
-@login_required
-def delete_recording(recording_id):
- try:
- recording = db.session.get(Recording, recording_id)
- if not recording:
- return jsonify({'error': 'Recording not found'}), 404
-
- # Check if the recording belongs to the current user
- if recording.user_id and recording.user_id != current_user.id:
- return jsonify({'error': 'You do not have permission to delete this recording'}), 403
-
- # Delete the audio file first
- try:
- if recording.audio_path and os.path.exists(recording.audio_path):
- os.remove(recording.audio_path)
- app.logger.info(f"Deleted audio file: {recording.audio_path}")
- except Exception as e:
- app.logger.error(f"Error deleting audio file {recording.audio_path}: {e}")
-
- # 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:
- db.session.rollback()
- app.logger.error(f"Error deleting recording {recording_id}: {e}", exc_info=True)
- 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'] = f"{chunk.recording.meeting_date.isoformat()}T00:00:00" 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 = call_llm_completion(
- 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 = call_llm_completion(
- 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
- )
-
- # Use helper function to process streaming with thinking tag support
- for response in process_streaming_with_thinking(stream):
- yield response
- return
-
- except Exception as e:
- 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 = call_llm_completion(
- messages=[
- {"role": "system", "content": "You are a query enhancement assistant. Respond only with valid JSON arrays of search terms."},
- {"role": "user", "content": enrichment_prompt}
- ],
- 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 = call_llm_completion(
- 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 = ""
-
- # Buffer content to detect full transcript requests
- response_buffer = ""
- content_buffer = ""
- in_thinking = False
- thinking_buffer = ""
-
- for chunk in stream:
- content = chunk.choices[0].delta.content
- if content:
- response_buffer += content
- content_buffer += content
-
- # Check if this is a full transcript request
- if response_buffer.strip().startswith("REQUEST_FULL_TRANSCRIPT:"):
- 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 = call_llm_completion(
- messages=updated_messages,
- temperature=0.7,
- max_tokens=int(os.environ.get("CHAT_MAX_TOKENS", "2000")),
- stream=True
- )
-
- # Use helper function to process streaming with thinking tag support
- for response in process_streaming_with_thinking(new_stream):
- yield response
- return
- else:
- # Recording not found or no permission
- 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
-
- # Process the buffer to detect and handle thinking tags
- while True:
- if not in_thinking:
- # Look for opening thinking tag
- think_start = re.search(r'<think(?:ing)?>', content_buffer, re.IGNORECASE)
- if think_start:
- # Send any content before the thinking tag
- before_thinking = content_buffer[:think_start.start()]
- if before_thinking:
- yield f"data: {json.dumps({'delta': before_thinking})}\n\n"
-
- # Start capturing thinking content
- in_thinking = True
- content_buffer = content_buffer[think_start.end():]
- thinking_buffer = ""
- else:
- # No thinking tag found, send accumulated content
- if content_buffer:
- yield f"data: {json.dumps({'delta': content_buffer})}\n\n"
- content_buffer = ""
- break
- else:
- # We're inside a thinking tag, look for closing tag
- think_end = re.search(r'</think(?:ing)?>', content_buffer, re.IGNORECASE)
- if think_end:
- # Capture thinking content up to the closing tag
- thinking_buffer += content_buffer[:think_end.start()]
-
- # Send the thinking content as a special type
- if thinking_buffer.strip():
- yield f"data: {json.dumps({'thinking': thinking_buffer.strip()})}\n\n"
-
- # Continue processing after the closing tag
- in_thinking = False
- content_buffer = content_buffer[think_end.end():]
- thinking_buffer = ""
- else:
- # Still inside thinking tag, accumulate content
- thinking_buffer += content_buffer
- content_buffer = ""
- break
-
- # Handle any remaining content
- if in_thinking and thinking_buffer:
- # Unclosed thinking tag - send as thinking content
- yield f"data: {json.dumps({'thinking': thinking_buffer.strip()})}\n\n"
- elif content_buffer:
- # Regular content
- yield f"data: {json.dumps({'delta': content_buffer})}\n\n"
-
- yield f"data: {json.dumps({'end_of_stream': True})}\n\n"
-
- 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': f"{r.meeting_date.isoformat()}T00:00:00" 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."""
- try:
- # Import here to avoid circular imports
- import src.file_monitor as file_monitor
- file_monitor.start_file_monitor()
- app.logger.info("File monitor initialization completed")
- except Exception as e:
- app.logger.warning(f"File monitor initialization failed: {e}")
-
-def get_file_monitor_functions():
- """Get file monitor functions, handling import errors gracefully."""
- try:
- import src.file_monitor as file_monitor
- return file_monitor.start_file_monitor, file_monitor.stop_file_monitor, file_monitor.get_file_monitor_status
- except ImportError as e:
- app.logger.warning(f"File monitor not available: {e}")
-
- # Create stub functions if file_monitor is not available
- def start_file_monitor():
- pass
- def stop_file_monitor():
- pass
- def get_file_monitor_status():
- return {'running': False, 'error': 'File monitor module not available'}
-
- return start_file_monitor, stop_file_monitor, get_file_monitor_status
-
-# --- Auto-Processing API Endpoints ---
[email protected]('/admin/auto-process/status', methods=['GET'])
-@login_required
-def admin_get_auto_process_status():
- """Get the status of the automated file processing system."""
- if not current_user.is_admin:
- return jsonify({'error': 'Unauthorized'}), 403
-
- try:
- _, _, get_file_monitor_status = get_file_monitor_functions()
- status = get_file_monitor_status()
-
- # Add configuration info
- config = {
- 'enabled': os.environ.get('ENABLE_AUTO_PROCESSING', 'false').lower() == 'true',
- 'watch_directory': os.environ.get('AUTO_PROCESS_WATCH_DIR', '/data/auto-process'),
- 'check_interval': int(os.environ.get('AUTO_PROCESS_CHECK_INTERVAL', '30')),
- 'mode': os.environ.get('AUTO_PROCESS_MODE', 'admin_only'),
- 'default_username': os.environ.get('AUTO_PROCESS_DEFAULT_USERNAME')
- }
-
- return jsonify({
- 'status': status,
- 'config': config
- })
-
- except Exception as e:
- app.logger.error(f"Error getting auto-process status: {e}")
- return jsonify({'error': str(e)}), 500
-
[email protected]('/admin/auto-process/start', methods=['POST'])
-@login_required
-def admin_start_auto_process():
- """Start the automated file processing system."""
- if not current_user.is_admin:
- return jsonify({'error': 'Unauthorized'}), 403
-
- try:
- start_file_monitor, _, _ = get_file_monitor_functions()
- start_file_monitor()
- return jsonify({'success': True, 'message': 'Auto-processing started'})
- except Exception as e:
- app.logger.error(f"Error starting auto-process: {e}")
- return jsonify({'error': str(e)}), 500
-
[email protected]('/admin/auto-process/stop', methods=['POST'])
-@login_required
-def admin_stop_auto_process():
- """Stop the automated file processing system."""
- if not current_user.is_admin:
- return jsonify({'error': 'Unauthorized'}), 403
-
- try:
- _, stop_file_monitor, _ = get_file_monitor_functions()
- stop_file_monitor()
- return jsonify({'success': True, 'message': 'Auto-processing stopped'})
- except Exception as e:
- app.logger.error(f"Error stopping auto-process: {e}")
- return jsonify({'error': str(e)}), 500
-
[email protected]('/admin/auto-process/config', methods=['POST'])
-@login_required
-def admin_update_auto_process_config():
- """Update auto-processing configuration (requires restart)."""
- if not current_user.is_admin:
- return jsonify({'error': 'Unauthorized'}), 403
-
- try:
- data = request.json
- if not data:
- return jsonify({'error': 'No configuration data provided'}), 400
-
- # This endpoint would typically update environment variables or config files
- # For now, we'll just return the current config and note that restart is required
- return jsonify({
- 'success': True,
- 'message': 'Configuration updated. Restart required to apply changes.',
- 'note': 'Environment variables need to be updated manually and application restarted.'
- })
-
- except Exception as e:
- 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 setting
- max_file_size_mb = SystemSetting.get_setting('max_file_size_mb', 250)
- app.config['MAX_CONTENT_LENGTH'] = max_file_size_mb * 1024 * 1024
- app.logger.info(f"Set MAX_CONTENT_LENGTH to {max_file_size_mb}MB from database setting")
-
- # Initialize file monitor after app setup
- initialize_file_monitor()
-
-if __name__ == '__main__':
# Consider using waitress or gunicorn for production
# waitress-serve --host 0.0.0.0 --port 8899 app:app
# For development:
- app.run(host='0.0.0.0', port=8899, debug=True) # Set debug=False if thread issues arise
+ app.run(host='0.0.0.0', port=8899, debug=args.debug)
diff --git a/src/config/__init__.py b/src/config/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/config/app_config.py b/src/config/app_config.py
new file mode 100644
index 00000000..8938aaeb
--- /dev/null
+++ b/src/config/app_config.py
@@ -0,0 +1,78 @@
+"""
+Application configuration and initialization.
+"""
+
+import os
+import sys
+import httpx
+from openai import OpenAI
+
+from src.audio_chunking import AudioChunkingService
+from src.config.version import get_version
+
+# Configuration from environment
+TEXT_MODEL_API_KEY = os.environ.get("TEXT_MODEL_API_KEY")
+TEXT_MODEL_BASE_URL = os.environ.get("TEXT_MODEL_BASE_URL", "https://openrouter.ai/api/v1")
+if TEXT_MODEL_BASE_URL:
+ TEXT_MODEL_BASE_URL = TEXT_MODEL_BASE_URL.split('#')[0].strip()
+TEXT_MODEL_NAME = os.environ.get("TEXT_MODEL_NAME", "openai/gpt-3.5-turbo")
+
+transcription_api_key = os.environ.get("TRANSCRIPTION_API_KEY", "")
+transcription_base_url = os.environ.get("TRANSCRIPTION_BASE_URL", "")
+if transcription_base_url:
+ transcription_base_url = transcription_base_url.split('#')[0].strip()
+
+USE_ASR_ENDPOINT = os.environ.get('USE_ASR_ENDPOINT', 'false').lower() == 'true'
+ASR_BASE_URL = os.environ.get('ASR_BASE_URL')
+if ASR_BASE_URL:
+ ASR_BASE_URL = ASR_BASE_URL.split('#')[0].strip()
+
+if USE_ASR_ENDPOINT:
+ ASR_DIARIZE = os.environ.get('ASR_DIARIZE', 'true').lower() == 'true'
+ ASR_MIN_SPEAKERS = os.environ.get('ASR_MIN_SPEAKERS')
+ ASR_MAX_SPEAKERS = os.environ.get('ASR_MAX_SPEAKERS')
+else:
+ ASR_DIARIZE = False
+ ASR_MIN_SPEAKERS = None
+ ASR_MAX_SPEAKERS = None
+
+ENABLE_CHUNKING = os.environ.get('ENABLE_CHUNKING', 'true').lower() == 'true'
+CHUNK_SIZE_MB = int(os.environ.get('CHUNK_SIZE_MB', '20'))
+CHUNK_OVERLAP_SECONDS = int(os.environ.get('CHUNK_OVERLAP_SECONDS', '3'))
+
+
+def initialize_config(app):
+ """Initialize application configuration."""
+ app_headers = {
+ "HTTP-Referer": "https://github.com/murtaza-nasir/speakr",
+ "X-Title": "Speakr - AI Audio Transcription",
+ "User-Agent": "Speakr/1.0 (https://github.com/murtaza-nasir/speakr)"
+ }
+
+ http_client_no_proxy = httpx.Client(verify=True, headers=app_headers)
+
+ client = None
+ try:
+ api_key = TEXT_MODEL_API_KEY or "not-needed"
+ client = OpenAI(api_key=api_key, base_url=TEXT_MODEL_BASE_URL, http_client=http_client_no_proxy)
+ app.logger.info(f"LLM client initialized: {TEXT_MODEL_BASE_URL} / {TEXT_MODEL_NAME}")
+ except Exception as e:
+ app.logger.error(f"Failed to initialize LLM client: {e}")
+
+ chunking_service = AudioChunkingService(CHUNK_SIZE_MB, CHUNK_OVERLAP_SECONDS) if ENABLE_CHUNKING else None
+ version = get_version()
+
+ app.logger.info(f"=== Speakr {version} Starting Up ===")
+
+ if USE_ASR_ENDPOINT:
+ if not ASR_BASE_URL:
+ app.logger.error("ERROR: ASR enabled but ASR_BASE_URL not configured!")
+ sys.exit(1)
+ app.logger.info(f"Using ASR endpoint: {ASR_BASE_URL}")
+ else:
+ if not transcription_base_url or not transcription_api_key:
+ app.logger.error("ERROR: No transcription service configured!")
+ sys.exit(1)
+ app.logger.info(f"Using Whisper API: {transcription_base_url}")
+
+ return client, chunking_service, version
diff --git a/src/config/startup.py b/src/config/startup.py
new file mode 100644
index 00000000..10e113d8
--- /dev/null
+++ b/src/config/startup.py
@@ -0,0 +1,128 @@
+"""
+Application startup functions.
+"""
+
+import os
+import time
+import threading
+from datetime import datetime, timedelta
+from flask import current_app
+
+ENABLE_AUTO_DELETION = os.environ.get('ENABLE_AUTO_DELETION', 'false').lower() == 'true'
+GLOBAL_RETENTION_DAYS = int(os.environ.get('GLOBAL_RETENTION_DAYS', '0'))
+
+
+def initialize_file_monitor(app):
+ """Initialize file monitor after app is fully loaded to avoid circular imports."""
+ try:
+ # Import here to avoid circular imports
+ import src.file_monitor as file_monitor
+ file_monitor.start_file_monitor()
+ app.logger.info("File monitor initialization completed")
+ except Exception as e:
+ app.logger.warning(f"File monitor initialization failed: {e}")
+
+def get_file_monitor_functions(app):
+ """Get file monitor functions, handling import errors gracefully."""
+ try:
+ import src.file_monitor as file_monitor
+ return file_monitor.start_file_monitor, file_monitor.stop_file_monitor, file_monitor.get_file_monitor_status
+ except ImportError as e:
+ app.logger.warning(f"File monitor not available: {e}")
+
+ # Create stub functions if file_monitor is not available
+ def start_file_monitor():
+ pass
+ def stop_file_monitor():
+ pass
+ def get_file_monitor_status():
+ return {'running': False, 'error': 'File monitor module not available'}
+
+ return start_file_monitor, stop_file_monitor, get_file_monitor_status
+
+# --- Auto-Processing API Endpoints ---
+def initialize_auto_deletion_scheduler(app):
+ """Initialize the daily auto-deletion scheduler if enabled."""
+ from src.services.retention import process_auto_deletion
+
+ if not ENABLE_AUTO_DELETION:
+ app.logger.info("Auto-deletion scheduler not started (ENABLE_AUTO_DELETION=false)")
+ return
+
+ if GLOBAL_RETENTION_DAYS <= 0:
+ app.logger.info("Auto-deletion scheduler not started (GLOBAL_RETENTION_DAYS not set)")
+ return
+
+ def run_daily_deletion():
+ """Background thread that runs auto-deletion daily at 2 AM."""
+ import time
+ from datetime import datetime, timedelta
+
+ app.logger.info("Auto-deletion scheduler started - will run daily at 2:00 AM")
+
+ while True:
+ try:
+ # Calculate time until next 2 AM
+ now = datetime.now()
+ next_run = now.replace(hour=2, minute=0, second=0, microsecond=0)
+
+ # If it's past 2 AM today, schedule for tomorrow
+ if now.hour >= 2:
+ next_run += timedelta(days=1)
+
+ sleep_seconds = (next_run - now).total_seconds()
+
+ app.logger.info(f"Next auto-deletion scheduled for: {next_run.strftime('%Y-%m-%d %H:%M:%S')} (in {sleep_seconds/3600:.1f} hours)")
+
+ # Sleep until next run time
+ time.sleep(sleep_seconds)
+
+ # Run auto-deletion
+ app.logger.info("Running scheduled auto-deletion...")
+ with app.app_context():
+ stats = process_auto_deletion()
+ app.logger.info(f"Scheduled auto-deletion completed: {stats}")
+
+ except Exception as e:
+ app.logger.error(f"Error in auto-deletion scheduler: {e}", exc_info=True)
+ # Sleep for 1 hour before retrying on error
+ time.sleep(3600)
+
+ # Start the scheduler thread
+ import threading
+ scheduler_thread = threading.Thread(target=run_daily_deletion, daemon=True, name="AutoDeletionScheduler")
+ scheduler_thread.start()
+ app.logger.info("✅ Auto-deletion scheduler initialized - running daily at 2:00 AM")
+
+
+def initialize_file_exporter(app):
+ """Initialize file exporter after app is fully loaded."""
+ try:
+ from src.file_exporter import initialize_export_directory, ENABLE_AUTO_EXPORT
+ if ENABLE_AUTO_EXPORT:
+ initialize_export_directory()
+ app.logger.info("✅ Auto-export initialized")
+ else:
+ app.logger.info("ℹ️ Auto-export: Disabled (set ENABLE_AUTO_EXPORT=true to enable)")
+ except Exception as e:
+ app.logger.warning(f"File exporter initialization failed: {e}")
+
+
+def run_startup_tasks(app):
+ """Run all startup tasks that need to happen after app creation."""
+ from src.models import SystemSetting
+
+ with app.app_context():
+ # Set dynamic MAX_CONTENT_LENGTH based on database setting
+ max_file_size_mb = SystemSetting.get_setting('max_file_size_mb', 250)
+ app.config['MAX_CONTENT_LENGTH'] = max_file_size_mb * 1024 * 1024
+ app.logger.info(f"Set MAX_CONTENT_LENGTH to {max_file_size_mb}MB from database setting")
+
+ # Initialize file monitor after app setup
+ initialize_file_monitor(app)
+
+ # Initialize file exporter
+ initialize_file_exporter(app)
+
+ # Initialize auto-deletion scheduler
+ initialize_auto_deletion_scheduler(app)
diff --git a/src/config/version.py b/src/config/version.py
new file mode 100644
index 00000000..19d66bea
--- /dev/null
+++ b/src/config/version.py
@@ -0,0 +1,29 @@
+"""
+Version information helper.
+"""
+
+import os
+
+
+
+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"
+
+
+
diff --git a/src/database.py b/src/database.py
new file mode 100644
index 00000000..2b146975
--- /dev/null
+++ b/src/database.py
@@ -0,0 +1,12 @@
+"""
+Database initialization module.
+
+This module creates and exports the SQLAlchemy database instance
+that is used across all models.
+"""
+
+from flask_sqlalchemy import SQLAlchemy
+
+# Create the SQLAlchemy database instance
+# This will be initialized with the Flask app using db.init_app(app)
+db = SQLAlchemy()
diff --git a/src/file_exporter.py b/src/file_exporter.py
new file mode 100644
index 00000000..c9f81b6c
--- /dev/null
+++ b/src/file_exporter.py
@@ -0,0 +1,377 @@
+#!/usr/bin/env python3
+"""
+File Exporter for Automated Recording Export
+
+Exports transcriptions and summaries as markdown files to a configured directory.
+Supports per-user subdirectories based on username.
+"""
+
+import os
+import re
+import json
+import logging
+from datetime import datetime, timedelta
+from pathlib import Path
+from werkzeug.utils import secure_filename
+
+# Configuration from environment
+ENABLE_AUTO_EXPORT = os.environ.get('ENABLE_AUTO_EXPORT', 'false').lower() == 'true'
+AUTO_EXPORT_DIR = os.environ.get('AUTO_EXPORT_DIR', '/data/exports')
+AUTO_EXPORT_TRANSCRIPTION = os.environ.get('AUTO_EXPORT_TRANSCRIPTION', 'true').lower() == 'true'
+AUTO_EXPORT_SUMMARY = os.environ.get('AUTO_EXPORT_SUMMARY', 'true').lower() == 'true'
+
+# Setup logging
+logger = logging.getLogger('file_exporter')
+logger.setLevel(logging.INFO)
+
+
+def format_transcription_with_template(transcription_text, user):
+ """
+ Format transcription using the user's default template.
+
+ Args:
+ transcription_text: Raw transcription (JSON or plain text)
+ user: User object to get template from
+
+ Returns:
+ Formatted transcription string
+ """
+ # Import here to avoid circular imports
+ from src.models import TranscriptTemplate
+
+ # Try to parse as JSON
+ try:
+ transcription_data = json.loads(transcription_text)
+ if not isinstance(transcription_data, list):
+ # Not our expected format, return as-is
+ return transcription_text
+ except (json.JSONDecodeError, TypeError):
+ # Not JSON, return as-is
+ return transcription_text
+
+ # Get user's default template
+ template = TranscriptTemplate.query.filter_by(
+ user_id=user.id,
+ is_default=True
+ ).first()
+
+ # Default format if no template set
+ if not template:
+ template_format = "[{{speaker}}]: {{text}}"
+ else:
+ template_format = template.template
+
+ # Helper functions for formatting
+ def format_time(seconds):
+ """Format seconds to HH:MM:SS"""
+ if seconds is None:
+ return "00:00:00"
+ td = timedelta(seconds=seconds)
+ hours = int(td.total_seconds() // 3600)
+ minutes = int((td.total_seconds() % 3600) // 60)
+ secs = int(td.total_seconds() % 60)
+ return f"{hours:02d}:{minutes:02d}:{secs:02d}"
+
+ def format_srt_time(seconds):
+ """Format seconds to SRT format HH:MM:SS,mmm"""
+ if seconds is None:
+ return "00:00:00,000"
+ td = timedelta(seconds=seconds)
+ hours = int(td.total_seconds() // 3600)
+ minutes = int((td.total_seconds() % 3600) // 60)
+ secs = int(td.total_seconds() % 60)
+ millis = int((td.total_seconds() % 1) * 1000)
+ return f"{hours:02d}:{minutes:02d}:{secs:02d},{millis:03d}"
+
+ # Generate formatted transcript
+ output_lines = []
+ for index, segment in enumerate(transcription_data, 1):
+ line = template_format
+
+ # Replace variables
+ replacements = {
+ '{{index}}': str(index),
+ '{{speaker}}': segment.get('speaker', 'Unknown'),
+ '{{text}}': segment.get('sentence', ''),
+ '{{start_time}}': format_time(segment.get('start_time')),
+ '{{end_time}}': format_time(segment.get('end_time')),
+ }
+
+ for key, value in replacements.items():
+ line = line.replace(key, value)
+
+ # Handle filters
+ # Upper case filter
+ line = re.sub(r'{{(.*?)\|upper}}', lambda m: replacements.get('{{' + m.group(1) + '}}', '').upper(), line)
+ # SRT time filter
+ line = re.sub(r'{{start_time\|srt}}', format_srt_time(segment.get('start_time')), line)
+ line = re.sub(r'{{end_time\|srt}}', format_srt_time(segment.get('end_time')), line)
+
+ output_lines.append(line)
+
+ return '\n'.join(output_lines)
+
+
+def get_export_directory(user):
+ """Get the export directory for a user, creating if needed."""
+ base_dir = Path(AUTO_EXPORT_DIR)
+
+ # Create per-user subdirectory based on username
+ user_dir = base_dir / secure_filename(user.username)
+ user_dir.mkdir(parents=True, exist_ok=True)
+
+ return user_dir
+
+
+def generate_safe_filename(recording):
+ """Generate a safe filename for the export based on recording ID only."""
+ # Use only recording ID for consistent filename that doesn't change
+ return f"recording_{recording.id}"
+
+
+def get_export_filepath(user, recording):
+ """Get the full export filepath for a recording."""
+ export_dir = get_export_directory(user)
+ filename = generate_safe_filename(recording)
+ return export_dir / f"{filename}.md"
+
+
+def mark_export_as_deleted(recording_id):
+ """
+ Rename the export file to indicate the recording was deleted.
+
+ Args:
+ recording_id: ID of the deleted recording
+
+ Returns:
+ New filepath if renamed, None otherwise
+ """
+ if not ENABLE_AUTO_EXPORT:
+ return None
+
+ # Import here to avoid circular imports
+ from src.app import app, db
+ from src.models import Recording, User
+
+ with app.app_context():
+ try:
+ # We need to find the file - check all user directories
+ base_dir = Path(AUTO_EXPORT_DIR)
+ if not base_dir.exists():
+ return None
+
+ # Look for the file in all user subdirectories
+ for user_dir in base_dir.iterdir():
+ if user_dir.is_dir():
+ old_filepath = user_dir / f"recording_{recording_id}.md"
+ if old_filepath.exists():
+ new_filepath = user_dir / f"[deleted]_recording_{recording_id}.md"
+ old_filepath.rename(new_filepath)
+ logger.info(f"Marked export as deleted: {new_filepath}")
+ return str(new_filepath)
+
+ return None
+
+ except Exception as e:
+ logger.error(f"Failed to mark export as deleted for recording {recording_id}: {e}")
+ return None
+
+
+def format_duration(seconds):
+ """Format duration in seconds to human-readable string."""
+ if not seconds:
+ return "Unknown"
+
+ hours = seconds // 3600
+ minutes = (seconds % 3600) // 60
+ secs = seconds % 60
+
+ if hours > 0:
+ return f"{hours}h {minutes}m {secs}s"
+ elif minutes > 0:
+ return f"{minutes}m {secs}s"
+ else:
+ return f"{secs}s"
+
+
+def format_file_size(bytes_size):
+ """Format file size in bytes to human-readable string."""
+ if not bytes_size:
+ return "Unknown"
+
+ for unit in ['B', 'KB', 'MB', 'GB']:
+ if bytes_size < 1024:
+ return f"{bytes_size:.1f} {unit}"
+ bytes_size /= 1024
+ return f"{bytes_size:.1f} TB"
+
+
+def generate_markdown_content(recording, user, include_transcription=True, include_summary=True):
+ """Generate markdown content for a recording export.
+
+ Args:
+ recording: Recording object to export
+ user: User object for getting template preferences
+ include_transcription: Whether to include transcription
+ include_summary: Whether to include summary
+ """
+ lines = []
+
+ # Header with title
+ title = recording.title or f"Recording {recording.id}"
+ lines.append(f"# {title}")
+ lines.append("")
+
+ # Metadata section
+ lines.append("## Metadata")
+ lines.append("")
+
+ if recording.meeting_date:
+ lines.append(f"- **Date:** {recording.meeting_date.strftime('%B %d, %Y')}")
+
+ if recording.created_at:
+ lines.append(f"- **Created:** {recording.created_at.strftime('%B %d, %Y at %I:%M %p')}")
+
+ if recording.original_filename:
+ lines.append(f"- **Original File:** {recording.original_filename}")
+
+ if recording.file_size:
+ lines.append(f"- **File Size:** {format_file_size(recording.file_size)}")
+
+ if recording.participants:
+ lines.append(f"- **Participants:** {recording.participants}")
+
+ if recording.tags:
+ tag_names = [tag.name for tag in recording.tags]
+ lines.append(f"- **Tags:** {', '.join(tag_names)}")
+
+ if recording.transcription_duration_seconds:
+ lines.append(f"- **Transcription Time:** {format_duration(recording.transcription_duration_seconds)}")
+
+ if recording.summarization_duration_seconds:
+ lines.append(f"- **Summarization Time:** {format_duration(recording.summarization_duration_seconds)}")
+
+ lines.append("")
+
+ # Notes section (if available)
+ if recording.notes:
+ lines.append("## Notes")
+ lines.append("")
+ lines.append(recording.notes)
+ lines.append("")
+
+ # Summary section
+ if include_summary and recording.summary:
+ lines.append("## Summary")
+ lines.append("")
+ lines.append(recording.summary)
+ lines.append("")
+
+ # Transcription section
+ if include_transcription and recording.transcription:
+ lines.append("## Transcription")
+ lines.append("")
+ # Format transcription using user's template
+ formatted_transcription = format_transcription_with_template(recording.transcription, user)
+ lines.append(formatted_transcription)
+ lines.append("")
+
+ # Footer
+ lines.append("---")
+ lines.append("")
+ lines.append("*Generated with [Speakr](https://github.com/learnedmachine/speakr)*")
+ lines.append("")
+
+ return "\n".join(lines)
+
+
+def export_recording(recording_id):
+ """
+ Export a recording to markdown file.
+
+ Args:
+ recording_id: ID of the recording to export
+
+ Returns:
+ Path to the exported file, or None if export failed/disabled
+ """
+ if not ENABLE_AUTO_EXPORT:
+ return None
+
+ # Check if we should export anything
+ if not AUTO_EXPORT_TRANSCRIPTION and not AUTO_EXPORT_SUMMARY:
+ logger.warning("Auto-export is enabled but both transcription and summary export are disabled")
+ return None
+
+ # Import here to avoid circular imports
+ from src.app import app, db
+ from src.models import Recording, User
+
+ with app.app_context():
+ try:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ logger.error(f"Recording {recording_id} not found for export")
+ return None
+
+ # Get the owner
+ user = db.session.get(User, recording.user_id)
+ if not user:
+ logger.error(f"User not found for recording {recording_id}")
+ return None
+
+ # Check if we have content to export
+ has_transcription = bool(recording.transcription) and AUTO_EXPORT_TRANSCRIPTION
+ has_summary = bool(recording.summary) and AUTO_EXPORT_SUMMARY
+
+ if not has_transcription and not has_summary:
+ logger.debug(f"Recording {recording_id} has no content to export")
+ return None
+
+ # Get export directory for user
+ export_dir = get_export_directory(user)
+
+ # Generate filename and path
+ filename = generate_safe_filename(recording)
+ filepath = export_dir / f"{filename}.md"
+
+ # Generate content
+ content = generate_markdown_content(
+ recording,
+ user,
+ include_transcription=AUTO_EXPORT_TRANSCRIPTION,
+ include_summary=AUTO_EXPORT_SUMMARY
+ )
+
+ # Write to file (overwrites if exists)
+ filepath.write_text(content, encoding='utf-8')
+
+ logger.info(f"Exported recording {recording_id} to {filepath}")
+ return str(filepath)
+
+ except Exception as e:
+ logger.error(f"Failed to export recording {recording_id}: {e}")
+ return None
+
+
+def initialize_export_directory():
+ """Initialize the export directory on startup."""
+ if not ENABLE_AUTO_EXPORT:
+ return
+
+ try:
+ export_dir = Path(AUTO_EXPORT_DIR)
+ export_dir.mkdir(parents=True, exist_ok=True)
+ logger.info(f"Auto-export enabled, directory: {AUTO_EXPORT_DIR}")
+
+ if AUTO_EXPORT_TRANSCRIPTION and AUTO_EXPORT_SUMMARY:
+ logger.info("Exporting: transcription and summary")
+ elif AUTO_EXPORT_TRANSCRIPTION:
+ logger.info("Exporting: transcription only")
+ elif AUTO_EXPORT_SUMMARY:
+ logger.info("Exporting: summary only")
+ else:
+ logger.warning("Auto-export enabled but no content types selected")
+
+ except Exception as e:
+ logger.error(f"Failed to initialize export directory: {e}")
diff --git a/src/file_monitor.py b/src/file_monitor.py
index 15e5ac63..ac67f2ae 100644
--- a/src/file_monitor.py
+++ b/src/file_monitor.py
@@ -324,7 +324,7 @@ class FileMonitor:
title=f"Auto-processed - {original_filename}",
file_size=file_size,
status='PENDING',
- meeting_date=now.date(),
+ meeting_date=now,
user_id=user_id,
mime_type=mime_type,
is_inbox=True, # Auto-processed files go to inbox
diff --git a/src/init_db.py b/src/init_db.py
new file mode 100644
index 00000000..a303749d
--- /dev/null
+++ b/src/init_db.py
@@ -0,0 +1,485 @@
+"""
+Database initialization and migration logic.
+
+This module handles:
+- Database schema creation
+- Column migrations (adding missing columns to existing tables)
+- Default system settings initialization
+- Existing recordings migration for inquire mode
+"""
+
+import os
+import fcntl
+import tempfile
+from sqlalchemy import text, inspect
+
+from src.database import db
+from src.models import Recording, TranscriptChunk, SystemSetting
+from src.services.embeddings import process_recording_chunks
+from src.utils import add_column_if_not_exists, migrate_column_type
+
+# Configuration
+ENABLE_INQUIRE_MODE = os.environ.get('ENABLE_INQUIRE_MODE', 'false').lower() == 'true'
+
+
+def initialize_database(app):
+ """
+ Initialize database schema and run migrations.
+
+ This function should be called within an app context.
+ """
+ db.create_all()
+
+ # Check and add new columns if they don't exist
+ engine = db.engine
+ try:
+ # Add is_inbox column with default value of 1 (True)
+ if add_column_if_not_exists(engine, 'recording', 'is_inbox', 'BOOLEAN DEFAULT 1'):
+ app.logger.info("Added is_inbox column to recording table")
+
+ # Add is_highlighted column with default value of 0 (False)
+ if add_column_if_not_exists(engine, 'recording', 'is_highlighted', 'BOOLEAN DEFAULT 0'):
+ app.logger.info("Added is_highlighted column to recording table")
+
+ # Add language preference columns to User table
+ if add_column_if_not_exists(engine, 'user', 'transcription_language', 'VARCHAR(10)'):
+ app.logger.info("Added transcription_language column to user table")
+
+ # Add extract_events column to User table
+ if add_column_if_not_exists(engine, 'user', 'extract_events', 'BOOLEAN DEFAULT 0'):
+ app.logger.info("Added extract_events column to user table")
+ if add_column_if_not_exists(engine, 'user', 'output_language', 'VARCHAR(50)'):
+ app.logger.info("Added output_language column to user table")
+ if add_column_if_not_exists(engine, 'user', 'summary_prompt', 'TEXT'):
+ app.logger.info("Added summary_prompt column to user table")
+ if add_column_if_not_exists(engine, 'user', 'name', 'VARCHAR(100)'):
+ app.logger.info("Added name column to user table")
+ if add_column_if_not_exists(engine, 'user', 'job_title', 'VARCHAR(100)'):
+ app.logger.info("Added job_title column to user table")
+ if add_column_if_not_exists(engine, 'user', 'company', 'VARCHAR(100)'):
+ app.logger.info("Added company column to user table")
+ if add_column_if_not_exists(engine, 'user', 'diarize', 'BOOLEAN'):
+ app.logger.info("Added diarize column to user table")
+ if add_column_if_not_exists(engine, 'user', 'ui_language', 'VARCHAR(10) DEFAULT "en"'):
+ app.logger.info("Added ui_language column to user table")
+ if add_column_if_not_exists(engine, 'recording', 'mime_type', 'VARCHAR(100)'):
+ app.logger.info("Added mime_type column to recording table")
+ if add_column_if_not_exists(engine, 'recording', 'completed_at', 'DATETIME'):
+ app.logger.info("Added completed_at column to recording table")
+ if add_column_if_not_exists(engine, 'recording', 'processing_time_seconds', 'INTEGER'):
+ app.logger.info("Added processing_time_seconds column to recording table")
+ if add_column_if_not_exists(engine, 'recording', 'transcription_duration_seconds', 'INTEGER'):
+ app.logger.info("Added transcription_duration_seconds column to recording table")
+ if add_column_if_not_exists(engine, 'recording', 'summarization_duration_seconds', 'INTEGER'):
+ app.logger.info("Added summarization_duration_seconds column to recording table")
+ if add_column_if_not_exists(engine, 'recording', 'processing_source', 'VARCHAR(50) DEFAULT "upload"'):
+ app.logger.info("Added processing_source column to recording table")
+ if add_column_if_not_exists(engine, 'recording', 'error_message', 'TEXT'):
+ app.logger.info("Added error_message column to recording table")
+
+ # Add columns to recording_tags for order tracking
+ if add_column_if_not_exists(engine, 'recording_tags', 'added_at', 'DATETIME'):
+ app.logger.info("Added added_at column to recording_tags table")
+ if add_column_if_not_exists(engine, 'recording_tags', 'order', '"order" INTEGER DEFAULT 0'):
+ app.logger.info("Added order column to recording_tags table")
+
+ # Add auto-deletion and retention columns
+ if add_column_if_not_exists(engine, 'recording', 'audio_deleted_at', 'DATETIME'):
+ app.logger.info("Added audio_deleted_at column to recording table")
+ if add_column_if_not_exists(engine, 'recording', 'deletion_exempt', 'BOOLEAN DEFAULT 0'):
+ app.logger.info("Added deletion_exempt column to recording table")
+ if add_column_if_not_exists(engine, 'tag', 'protect_from_deletion', 'BOOLEAN DEFAULT 0'):
+ app.logger.info("Added protect_from_deletion column to tag table")
+
+ # Add speaker embeddings column for storing voice embeddings from diarization
+ if add_column_if_not_exists(engine, 'recording', 'speaker_embeddings', 'JSON'):
+ app.logger.info("Added speaker_embeddings column to recording table")
+
+ # Add speaker voice profile embedding fields
+ if add_column_if_not_exists(engine, 'speaker', 'average_embedding', 'BLOB'):
+ app.logger.info("Added average_embedding column to speaker table")
+ if add_column_if_not_exists(engine, 'speaker', 'embeddings_history', 'JSON'):
+ app.logger.info("Added embeddings_history column to speaker table")
+ if add_column_if_not_exists(engine, 'speaker', 'embedding_count', 'INTEGER DEFAULT 0'):
+ app.logger.info("Added embedding_count column to speaker table")
+ if add_column_if_not_exists(engine, 'speaker', 'confidence_score', 'REAL'):
+ app.logger.info("Added confidence_score column to speaker table")
+
+ if add_column_if_not_exists(engine, 'tag', 'group_id', 'INTEGER'):
+ app.logger.info("Added group_id column to tag table")
+
+ if add_column_if_not_exists(engine, 'tag', 'retention_days', 'INTEGER'):
+ app.logger.info("Added retention_days column to tag table")
+
+ # Migrate existing protected tags to use retention_days = -1 for consistency
+ # This standardizes the protection mechanism: retention_days = -1 means protected/infinite retention
+ try:
+ with engine.connect() as conn:
+ # Find tags with protect_from_deletion=True but retention_days != -1
+ result = conn.execute(text("""
+ SELECT COUNT(*) FROM tag
+ WHERE protect_from_deletion = 1
+ AND (retention_days IS NULL OR retention_days != -1)
+ """))
+ count = result.scalar()
+
+ if count and count > 0:
+ # Migrate these tags to use retention_days = -1
+ conn.execute(text("""
+ UPDATE tag
+ SET retention_days = -1
+ WHERE protect_from_deletion = 1
+ AND (retention_days IS NULL OR retention_days != -1)
+ """))
+ conn.commit()
+ app.logger.info(f"Migrated {count} protected tags to use retention_days=-1 (standardized protection format)")
+ except Exception as e:
+ app.logger.warning(f"Could not migrate protected tags to retention_days=-1: {e}")
+
+ if add_column_if_not_exists(engine, 'tag', 'auto_share_on_apply', 'BOOLEAN DEFAULT 1'):
+ app.logger.info("Added auto_share_on_apply column to tag table")
+
+ if add_column_if_not_exists(engine, 'tag', 'share_with_group_lead', 'BOOLEAN DEFAULT 1'):
+ app.logger.info("Added share_with_group_lead column to tag table")
+
+ if add_column_if_not_exists(engine, 'user', 'can_share_publicly', 'BOOLEAN DEFAULT 1'):
+ app.logger.info("Added can_share_publicly column to user table")
+
+ # Add source tracking columns to internal_share table
+ if add_column_if_not_exists(engine, 'internal_share', 'source_type', 'VARCHAR(20) DEFAULT "manual"'):
+ app.logger.info("Added source_type column to internal_share table")
+
+ if add_column_if_not_exists(engine, 'internal_share', 'source_tag_id', 'INTEGER'):
+ app.logger.info("Added source_tag_id column to internal_share table")
+
+ # Migrate existing shares: infer source based on group tag presence
+ try:
+ with engine.connect() as conn:
+ # For each existing share, check if it was likely created by a group tag
+ # by looking for group tags on the recording where the shared user is a group member
+ result = conn.execute(text('''
+ UPDATE internal_share
+ SET source_type = 'group_tag',
+ source_tag_id = (
+ SELECT t.id FROM tag t
+ INNER JOIN recording_tags rt ON rt.tag_id = t.id
+ INNER JOIN group_membership gm ON gm.group_id = t.group_id
+ WHERE rt.recording_id = internal_share.recording_id
+ AND gm.user_id = internal_share.shared_with_user_id
+ AND t.group_id IS NOT NULL
+ AND (t.auto_share_on_apply = 1 OR t.share_with_group_lead = 1)
+ LIMIT 1
+ )
+ WHERE source_type = 'manual'
+ AND EXISTS (
+ SELECT 1 FROM tag t
+ INNER JOIN recording_tags rt ON rt.tag_id = t.id
+ INNER JOIN group_membership gm ON gm.group_id = t.group_id
+ WHERE rt.recording_id = internal_share.recording_id
+ AND gm.user_id = internal_share.shared_with_user_id
+ AND t.group_id IS NOT NULL
+ AND (t.auto_share_on_apply = 1 OR t.share_with_group_lead = 1)
+ )
+ '''))
+ conn.commit()
+ app.logger.info("Inferred source tracking for existing shares based on group tag presence")
+ except Exception as e:
+ app.logger.warning(f"Could not infer source tracking for existing shares: {e}")
+
+ # Update existing records to have proper order values (approximate by tag_id)
+ try:
+ with engine.connect() as conn:
+ # Get existing associations without order values and assign them
+ existing_associations = conn.execute(text('''
+ SELECT recording_id, tag_id,
+ ROW_NUMBER() OVER (PARTITION BY recording_id ORDER BY tag_id) as row_num
+ FROM recording_tags
+ WHERE "order" = 0
+ ''')).fetchall()
+
+ for assoc in existing_associations:
+ conn.execute(text('''
+ UPDATE recording_tags
+ SET "order" = :order_num
+ WHERE recording_id = :rec_id AND tag_id = :tag_id
+ '''), {"order_num": assoc.row_num, "rec_id": assoc.recording_id, "tag_id": assoc.tag_id})
+
+ conn.commit()
+ app.logger.info(f"Updated order values for {len(existing_associations)} existing tag associations")
+ except Exception as e:
+ app.logger.warning(f"Could not update existing tag order values: {e}")
+
+ # Add per-user status columns to shared_recording_state table
+ if add_column_if_not_exists(engine, 'shared_recording_state', 'is_inbox', 'BOOLEAN DEFAULT 1'):
+ app.logger.info("Added is_inbox column to shared_recording_state table")
+
+ # Handle is_starred -> is_highlighted migration
+ inspector = inspect(engine)
+ if 'shared_recording_state' in inspector.get_table_names():
+ columns = [col['name'] for col in inspector.get_columns('shared_recording_state')]
+ has_is_starred = 'is_starred' in columns
+ has_is_highlighted = 'is_highlighted' in columns
+
+ if has_is_starred and not has_is_highlighted:
+ # Rename is_starred to is_highlighted by copying data
+ try:
+ with engine.connect() as conn:
+ # Add is_highlighted column
+ conn.execute(text('ALTER TABLE shared_recording_state ADD COLUMN is_highlighted BOOLEAN DEFAULT 0'))
+ # Copy data from is_starred to is_highlighted
+ conn.execute(text('UPDATE shared_recording_state SET is_highlighted = is_starred'))
+ conn.commit()
+ app.logger.info("Migrated is_starred to is_highlighted in shared_recording_state table")
+ # Note: We keep is_starred for now to avoid breaking existing code during transition
+ except Exception as e:
+ app.logger.warning(f"Could not migrate is_starred to is_highlighted: {e}")
+ elif not has_is_highlighted:
+ # Neither column exists, add is_highlighted
+ if add_column_if_not_exists(engine, 'shared_recording_state', 'is_highlighted', 'BOOLEAN DEFAULT 0'):
+ app.logger.info("Added is_highlighted column to shared_recording_state table")
+
+ # Migrate meeting_date from DATE to DATETIME format
+ # This migration handles both:
+ # 1. Converting existing DATE columns to DATETIME (for fresh pulls)
+ # 2. Restoring NULL dates from created_at (for failed migrations)
+ try:
+ inspector = inspect(engine)
+ columns_info = {col['name']: col for col in inspector.get_columns('recording')}
+
+ if 'meeting_date' in columns_info:
+ col_type = str(columns_info['meeting_date']['type']).upper()
+
+ # Check if column needs migration from DATE to DATETIME
+ needs_migration = False
+
+ # For SQLite: Both DATE and DATETIME are TEXT, check data format
+ if engine.name == 'sqlite':
+ with engine.connect() as conn:
+ # Check if we have date-only format (no time component)
+ result = conn.execute(text("""
+ SELECT meeting_date FROM recording
+ WHERE meeting_date IS NOT NULL
+ AND meeting_date NOT LIKE '%:%'
+ LIMIT 1
+ """))
+ has_date_only = result.fetchone() is not None
+ needs_migration = has_date_only
+
+ # For PostgreSQL/MySQL: Check actual column type
+ elif 'DATE' in col_type and 'DATETIME' not in col_type and 'TIMESTAMP' not in col_type:
+ needs_migration = True
+
+ if needs_migration:
+ app.logger.info(f"Migrating meeting_date from DATE to DATETIME format (engine: {engine.name})")
+
+ with engine.connect() as conn:
+ if engine.name == 'sqlite':
+ # SQLite: Add time component to date-only values
+ conn.execute(text("""
+ UPDATE recording
+ SET meeting_date = datetime(date(meeting_date) || ' 12:00:00')
+ WHERE meeting_date IS NOT NULL
+ AND meeting_date NOT LIKE '%:%'
+ """))
+ conn.commit()
+ app.logger.info("Migrated SQLite meeting_date to include time")
+
+ elif engine.name == 'postgresql':
+ # PostgreSQL: Change column type
+ conn.execute(text("""
+ ALTER TABLE recording
+ ALTER COLUMN meeting_date TYPE TIMESTAMP
+ USING (meeting_date + TIME '12:00:00')
+ """))
+ conn.commit()
+ app.logger.info("Migrated PostgreSQL meeting_date to TIMESTAMP")
+
+ elif engine.name == 'mysql':
+ # MySQL: Change column type
+ conn.execute(text("""
+ ALTER TABLE recording
+ MODIFY COLUMN meeting_date DATETIME
+ """))
+ # Add time component to existing date values
+ conn.execute(text("""
+ UPDATE recording
+ SET meeting_date = TIMESTAMP(meeting_date, '12:00:00')
+ WHERE meeting_date IS NOT NULL
+ """))
+ conn.commit()
+ app.logger.info("Migrated MySQL meeting_date to DATETIME")
+ else:
+ app.logger.info("meeting_date already in DATETIME format, skipping migration")
+
+ # Safety net: Restore any NULL meeting_dates from created_at
+ with engine.connect() as conn:
+ result = conn.execute(text("""
+ SELECT COUNT(*) FROM recording
+ WHERE meeting_date IS NULL AND created_at IS NOT NULL
+ """))
+ null_count = result.scalar()
+
+ if null_count and null_count > 0:
+ conn.execute(text("""
+ UPDATE recording
+ SET meeting_date = created_at
+ WHERE meeting_date IS NULL AND created_at IS NOT NULL
+ """))
+ conn.commit()
+ app.logger.info(f"Restored {null_count} NULL meeting dates from created_at")
+
+ except Exception as e:
+ app.logger.warning(f"Error during meeting_date migration: {e}")
+ app.logger.warning("New recordings will work correctly, but existing dates may need manual migration")
+
+ # Add index on TranscriptChunk.speaker_name for performance
+ # This improves speaker rename operations which update all chunks
+ try:
+ inspector = inspect(engine)
+ if 'transcript_chunk' in inspector.get_table_names():
+ existing_indexes = [idx['name'] for idx in inspector.get_indexes('transcript_chunk')]
+
+ # Create composite index on (user_id, speaker_name) if it doesn't exist
+ if 'idx_user_speaker_name' not in existing_indexes:
+ with engine.connect() as conn:
+ conn.execute(text(
+ 'CREATE INDEX IF NOT EXISTS idx_user_speaker_name ON transcript_chunk (user_id, speaker_name)'
+ ))
+ conn.commit()
+ app.logger.info("Created index idx_user_speaker_name on transcript_chunk (user_id, speaker_name) for speaker rename performance")
+
+ # Create single-column index on speaker_name if it doesn't exist
+ if 'ix_transcript_chunk_speaker_name' not in existing_indexes:
+ with engine.connect() as conn:
+ conn.execute(text(
+ 'CREATE INDEX IF NOT EXISTS ix_transcript_chunk_speaker_name ON transcript_chunk (speaker_name)'
+ ))
+ conn.commit()
+ app.logger.info("Created index ix_transcript_chunk_speaker_name on transcript_chunk (speaker_name)")
+ except Exception as e:
+ app.logger.warning(f"Could not create speaker_name indexes: {e}")
+
+ # Initialize default system settings
+ if not SystemSetting.query.filter_by(key='transcript_length_limit').first():
+ SystemSetting.set_setting(
+ key='transcript_length_limit',
+ value='30000',
+ description='Maximum number of characters to send from transcript to LLM for summarization and chat. Use -1 for no limit.',
+ setting_type='integer'
+ )
+ app.logger.info("Initialized default transcript_length_limit setting")
+
+ if not SystemSetting.query.filter_by(key='max_file_size_mb').first():
+ SystemSetting.set_setting(
+ key='max_file_size_mb',
+ value='250',
+ description='Maximum file size allowed for audio uploads in megabytes (MB).',
+ setting_type='integer'
+ )
+ app.logger.info("Initialized default max_file_size_mb setting")
+
+ if not SystemSetting.query.filter_by(key='asr_timeout_seconds').first():
+ SystemSetting.set_setting(
+ key='asr_timeout_seconds',
+ value='1800',
+ description='Maximum time in seconds to wait for ASR transcription to complete. Default is 1800 seconds (30 minutes).',
+ setting_type='integer'
+ )
+ app.logger.info("Initialized default asr_timeout_seconds setting")
+
+ if not SystemSetting.query.filter_by(key='admin_default_summary_prompt').first():
+ default_prompt = """Generate a comprehensive summary that includes the following sections:
+- **Key Issues Discussed**: A bulleted list of the main topics
+- **Key Decisions Made**: A bulleted list of any decisions reached
+- **Action Items**: A bulleted list of tasks assigned, including who is responsible if mentioned"""
+ SystemSetting.set_setting(
+ key='admin_default_summary_prompt',
+ value=default_prompt,
+ description='Default summarization prompt used when users have not set their own prompt. This serves as the base prompt for all users.',
+ setting_type='string'
+ )
+ app.logger.info("Initialized admin_default_summary_prompt setting")
+
+ if not SystemSetting.query.filter_by(key='recording_disclaimer').first():
+ SystemSetting.set_setting(
+ key='recording_disclaimer',
+ value='',
+ description='Legal disclaimer shown to users before recording starts. Supports Markdown formatting. Leave empty to disable.',
+ setting_type='string'
+ )
+ app.logger.info("Initialized recording_disclaimer setting")
+
+ if not SystemSetting.query.filter_by(key='disable_auto_summarization').first():
+ SystemSetting.set_setting(
+ key='disable_auto_summarization',
+ value='false',
+ description='Disable automatic summarization after transcription completes. When enabled, recordings will only be transcribed and users must manually trigger summarization.',
+ setting_type='boolean'
+ )
+ app.logger.info("Initialized disable_auto_summarization 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
+ 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}")
+
+
+if __name__ == '__main__':
+ # For standalone migration script
+ from src.app import app
+ with app.app_context():
+ initialize_database(app)
diff --git a/src/models/__init__.py b/src/models/__init__.py
new file mode 100644
index 00000000..d79f2ddc
--- /dev/null
+++ b/src/models/__init__.py
@@ -0,0 +1,54 @@
+"""
+Database models package for the Speakr application.
+
+This package contains all database models organized by domain:
+- User and authentication models
+- Recording and transcript models
+- Sharing models (public and internal)
+- Organization models (groups and tags)
+- Event, template, and search session models
+- System configuration models
+"""
+
+# Import database instance
+from src.database import db
+
+# Import all models
+from .user import User, Speaker
+from .speaker_snippet import SpeakerSnippet
+from .recording import Recording, TranscriptChunk
+from .sharing import Share, InternalShare, SharedRecordingState
+from .organization import Group, GroupMembership, Tag, RecordingTag
+from .events import Event
+from .templates import TranscriptTemplate
+from .inquire import InquireSession
+from .system import SystemSetting
+from .audit import ShareAuditLog
+
+# Export all models
+__all__ = [
+ # Database instance
+ 'db',
+ # User models
+ 'User',
+ 'Speaker',
+ 'SpeakerSnippet',
+ # Recording models
+ 'Recording',
+ 'TranscriptChunk',
+ # Sharing models
+ 'Share',
+ 'InternalShare',
+ 'SharedRecordingState',
+ 'ShareAuditLog',
+ # Organization models
+ 'Group',
+ 'GroupMembership',
+ 'Tag',
+ 'RecordingTag',
+ # Other models
+ 'Event',
+ 'TranscriptTemplate',
+ 'InquireSession',
+ 'SystemSetting',
+]
diff --git a/src/models/audit.py b/src/models/audit.py
new file mode 100644
index 00000000..ad24d098
--- /dev/null
+++ b/src/models/audit.py
@@ -0,0 +1,109 @@
+"""
+Audit logging models for tracking share operations.
+
+Provides comprehensive audit trail for security and compliance.
+"""
+
+from datetime import datetime
+from src.database import db
+
+
+class ShareAuditLog(db.Model):
+ """Audit trail for share operations."""
+
+ __tablename__ = 'share_audit_log'
+
+ id = db.Column(db.Integer, primary_key=True)
+
+ # Action details
+ action = db.Column(db.String(20), nullable=False) # 'created', 'modified', 'revoked', 'cascade_revoked'
+ recording_id = db.Column(db.Integer, db.ForeignKey('recording.id'), nullable=False)
+
+ # Actor (who performed the action)
+ actor_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
+ actor = db.relationship('User', foreign_keys=[actor_id], backref='audit_actions_performed')
+
+ # Target (who was affected - optional for some actions)
+ target_user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True)
+ target_user = db.relationship('User', foreign_keys=[target_user_id])
+
+ # Permission snapshot at time of action
+ permissions_granted = db.Column(db.JSON, nullable=True) # What was granted/revoked
+ actor_permissions = db.Column(db.JSON, nullable=True) # What actor had at time
+
+ # Metadata
+ timestamp = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
+ share_id = db.Column(db.Integer, nullable=True) # Reference to share if applicable
+
+ # Context and notes
+ notes = db.Column(db.Text, nullable=True) # System-generated notes (e.g., "Permission constrained", "Cascade revocation")
+ ip_address = db.Column(db.String(45), nullable=True) # Actor's IP address
+
+ # Recording relationship
+ recording = db.relationship('Recording', backref='share_audit_logs')
+
+ def to_dict(self):
+ """Convert to dictionary for API responses."""
+ return {
+ 'id': self.id,
+ 'action': self.action,
+ 'recording_id': self.recording_id,
+ 'actor_id': self.actor_id,
+ 'actor_username': self.actor.username if self.actor else None,
+ 'target_user_id': self.target_user_id,
+ 'target_username': self.target_user.username if self.target_user else None,
+ 'permissions_granted': self.permissions_granted,
+ 'actor_permissions': self.actor_permissions,
+ 'timestamp': self.timestamp.isoformat() if self.timestamp else None,
+ 'share_id': self.share_id,
+ 'notes': self.notes,
+ 'ip_address': self.ip_address
+ }
+
+ @staticmethod
+ def log_share_created(recording_id, actor_id, target_user_id, permissions, actor_permissions=None, notes=None, ip_address=None):
+ """Log share creation."""
+ log = ShareAuditLog(
+ action='created',
+ recording_id=recording_id,
+ actor_id=actor_id,
+ target_user_id=target_user_id,
+ permissions_granted=permissions,
+ actor_permissions=actor_permissions,
+ notes=notes,
+ ip_address=ip_address
+ )
+ db.session.add(log)
+ return log
+
+ @staticmethod
+ def log_share_modified(share_id, recording_id, actor_id, target_user_id, old_permissions, new_permissions, notes=None, ip_address=None):
+ """Log share modification."""
+ log = ShareAuditLog(
+ action='modified',
+ recording_id=recording_id,
+ actor_id=actor_id,
+ target_user_id=target_user_id,
+ permissions_granted={'old': old_permissions, 'new': new_permissions},
+ share_id=share_id,
+ notes=notes,
+ ip_address=ip_address
+ )
+ db.session.add(log)
+ return log
+
+ @staticmethod
+ def log_share_revoked(share_id, recording_id, actor_id, target_user_id, was_cascade=False, notes=None, ip_address=None):
+ """Log share revocation."""
+ action = 'cascade_revoked' if was_cascade else 'revoked'
+ log = ShareAuditLog(
+ action=action,
+ recording_id=recording_id,
+ actor_id=actor_id,
+ target_user_id=target_user_id,
+ share_id=share_id,
+ notes=notes,
+ ip_address=ip_address
+ )
+ db.session.add(log)
+ return log
diff --git a/src/models/events.py b/src/models/events.py
new file mode 100644
index 00000000..d967b687
--- /dev/null
+++ b/src/models/events.py
@@ -0,0 +1,43 @@
+"""
+Event model for calendar events extracted from transcripts.
+
+This module defines the Event model for storing calendar events
+that are extracted from transcriptions.
+"""
+
+import json
+from datetime import datetime
+from src.database import db
+
+
+class Event(db.Model):
+ """Calendar events extracted from transcripts."""
+
+ id = db.Column(db.Integer, primary_key=True)
+ recording_id = db.Column(db.Integer, db.ForeignKey('recording.id'), nullable=False)
+ title = db.Column(db.String(200), nullable=False)
+ description = db.Column(db.Text, nullable=True)
+ start_datetime = db.Column(db.DateTime, nullable=False)
+ end_datetime = db.Column(db.DateTime, nullable=True)
+ location = db.Column(db.String(500), nullable=True)
+ attendees = db.Column(db.Text, nullable=True) # JSON list of attendees
+ reminder_minutes = db.Column(db.Integer, nullable=True, default=15)
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+
+ # Relationship
+ recording = db.relationship('Recording', backref=db.backref('events', lazy=True, cascade='all, delete-orphan'))
+
+ def to_dict(self):
+ """Convert model to dictionary representation."""
+ return {
+ 'id': self.id,
+ 'recording_id': self.recording_id,
+ 'title': self.title,
+ 'description': self.description,
+ 'start_datetime': self.start_datetime.isoformat() if self.start_datetime else None,
+ 'end_datetime': self.end_datetime.isoformat() if self.end_datetime else None,
+ 'location': self.location,
+ 'attendees': json.loads(self.attendees) if self.attendees else [],
+ 'reminder_minutes': self.reminder_minutes,
+ 'created_at': self.created_at.isoformat() if self.created_at else None
+ }
diff --git a/src/models/inquire.py b/src/models/inquire.py
new file mode 100644
index 00000000..eb841861
--- /dev/null
+++ b/src/models/inquire.py
@@ -0,0 +1,45 @@
+"""
+InquireSession model for semantic search sessions.
+
+This module defines the InquireSession model for tracking
+inquire mode sessions and their filtering criteria.
+"""
+
+import json
+from datetime import datetime
+from src.database import db
+
+
+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):
+ """Convert model to dictionary representation."""
+ 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
+ }
diff --git a/src/models/organization.py b/src/models/organization.py
new file mode 100644
index 00000000..38dbe10e
--- /dev/null
+++ b/src/models/organization.py
@@ -0,0 +1,142 @@
+"""
+Organization models for groups, tags, and related structures.
+
+This module defines models for organizing users into groups and tagging recordings.
+"""
+
+from datetime import datetime
+from src.database import db
+
+
+class Group(db.Model):
+ """Groups for organizing users and sharing recordings."""
+
+ __tablename__ = 'group'
+
+ id = db.Column(db.Integer, primary_key=True)
+ name = db.Column(db.String(100), nullable=False, unique=True)
+ description = db.Column(db.Text, nullable=True)
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+
+ # Relationships
+ memberships = db.relationship('GroupMembership', back_populates='group', cascade='all, delete-orphan')
+
+ def to_dict(self):
+ """Convert model to dictionary representation."""
+ return {
+ 'id': self.id,
+ 'name': self.name,
+ 'description': self.description,
+ 'member_count': len(self.memberships),
+ 'created_at': self.created_at.isoformat() if self.created_at else None,
+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None
+ }
+
+
+class GroupMembership(db.Model):
+ """Tracks user membership in groups with roles."""
+
+ __tablename__ = 'group_membership'
+
+ id = db.Column(db.Integer, primary_key=True)
+ group_id = db.Column(db.Integer, db.ForeignKey('group.id', ondelete='CASCADE'), nullable=False)
+ user_id = db.Column(db.Integer, db.ForeignKey('user.id', ondelete='CASCADE'), nullable=False)
+ role = db.Column(db.String(20), default='member') # 'admin' or 'member'
+ joined_at = db.Column(db.DateTime, default=datetime.utcnow)
+
+ # Relationships
+ group = db.relationship('Group', back_populates='memberships')
+ user = db.relationship('User', backref=db.backref('group_memberships', lazy=True))
+
+ # Unique constraint: user can only be in a group once
+ __table_args__ = (db.UniqueConstraint('group_id', 'user_id', name='unique_group_membership'),)
+
+ def to_dict(self):
+ """Convert model to dictionary representation."""
+ return {
+ 'id': self.id,
+ 'group_id': self.group_id,
+ 'group_name': self.group.name if self.group else None,
+ 'user_id': self.user_id,
+ 'username': self.user.username if self.user else None,
+ 'role': self.role,
+ 'joined_at': self.joined_at.isoformat() if self.joined_at else None
+ }
+
+
+class RecordingTag(db.Model):
+ """Many-to-many relationship table for recordings and tags."""
+
+ __tablename__ = 'recording_tags'
+
+ recording_id = db.Column(db.Integer, db.ForeignKey('recording.id'), primary_key=True)
+ tag_id = db.Column(db.Integer, db.ForeignKey('tag.id'), primary_key=True)
+ added_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=True)
+ order = db.Column(db.Integer, nullable=False, default=0)
+
+ # Relationships
+ recording = db.relationship('Recording', back_populates='tag_associations')
+ tag = db.relationship('Tag', back_populates='recording_associations')
+
+
+class Tag(db.Model):
+ """Tags for organizing and categorizing recordings."""
+
+ id = db.Column(db.Integer, primary_key=True)
+ name = db.Column(db.String(50), nullable=False)
+ user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
+ group_id = db.Column(db.Integer, db.ForeignKey('group.id', ondelete='CASCADE'), nullable=True) # Group-scoped tag
+ color = db.Column(db.String(7), default='#3B82F6') # Hex color for UI
+
+ # Custom settings for this tag
+ custom_prompt = db.Column(db.Text, nullable=True) # Custom summarization prompt
+ default_language = db.Column(db.String(10), nullable=True) # Default transcription language
+ default_min_speakers = db.Column(db.Integer, nullable=True) # Default min speakers for ASR
+ default_max_speakers = db.Column(db.Integer, nullable=True) # Default max speakers for ASR
+
+ # Retention and deletion settings
+ protect_from_deletion = db.Column(db.Boolean, default=False) # Exempt tagged recordings from auto-deletion
+ retention_days = db.Column(db.Integer, nullable=True) # Group-specific retention override (overrides global)
+
+ # Group tag settings
+ auto_share_on_apply = db.Column(db.Boolean, default=True) # Auto-share recording with group when this tag is applied
+ share_with_group_lead = db.Column(db.Boolean, default=True) # Share with group admins when this tag is applied
+
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+
+ # Relationships
+ user = db.relationship('User', backref=db.backref('tags', lazy=True, cascade='all, delete-orphan'))
+ group = db.relationship('Group', backref=db.backref('tags', lazy=True))
+ # Use association object for many-to-many with order tracking
+ recording_associations = db.relationship('RecordingTag', back_populates='tag', cascade='all, delete-orphan')
+
+ # Unique constraint: tag name must be unique per user (or per group if group_id is set)
+ __table_args__ = (db.UniqueConstraint('name', 'user_id', name='_user_tag_uc'),)
+
+ @property
+ def is_group_tag(self):
+ """Check if this is a group-scoped tag."""
+ return self.group_id is not None
+
+ def to_dict(self):
+ """Convert model to dictionary representation."""
+ return {
+ 'id': self.id,
+ 'name': self.name,
+ 'color': self.color,
+ 'group_id': self.group_id,
+ 'is_group_tag': self.is_group_tag,
+ 'group_name': self.group.name if self.group else None,
+ 'custom_prompt': self.custom_prompt,
+ 'default_language': self.default_language,
+ 'default_min_speakers': self.default_min_speakers,
+ 'default_max_speakers': self.default_max_speakers,
+ 'protect_from_deletion': self.protect_from_deletion,
+ 'retention_days': self.retention_days,
+ 'auto_share_on_apply': self.auto_share_on_apply,
+ 'share_with_group_lead': self.share_with_group_lead,
+ 'created_at': self.created_at.isoformat() if self.created_at else None,
+ 'recording_count': len(self.recording_associations)
+ }
diff --git a/src/models/recording.py b/src/models/recording.py
new file mode 100644
index 00000000..e475d0bb
--- /dev/null
+++ b/src/models/recording.py
@@ -0,0 +1,271 @@
+"""
+Recording and TranscriptChunk database models.
+
+This module defines models for audio recordings and their chunked transcriptions.
+"""
+
+from datetime import datetime
+from sqlalchemy import func
+from src.database import db
+from src.utils import local_datetime_filter, md_to_html
+
+
+class Recording(db.Model):
+ """Main recording model storing audio files and their metadata."""
+
+ # Add user_id foreign key to associate recordings with users
+ user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True)
+ id = db.Column(db.Integer, primary_key=True)
+ # Title will now often be AI-generated, maybe start with filename?
+ title = db.Column(db.String(200), nullable=True) # Allow Null initially
+ participants = db.Column(db.String(500))
+ notes = db.Column(db.Text)
+ transcription = db.Column(db.Text, nullable=True)
+ summary = db.Column(db.Text, nullable=True)
+ status = db.Column(db.String(50), default='PENDING') # PENDING, PROCESSING, SUMMARIZING, COMPLETED, FAILED
+ audio_path = db.Column(db.String(500))
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+ meeting_date = db.Column(db.DateTime, nullable=True)
+ file_size = db.Column(db.Integer) # Store file size in bytes
+ original_filename = db.Column(db.String(500), nullable=True) # Store the original uploaded filename
+ is_inbox = db.Column(db.Boolean, default=True) # New recordings are marked as inbox by default
+ is_highlighted = db.Column(db.Boolean, default=False) # Recordings can be highlighted by the user
+ mime_type = db.Column(db.String(100), nullable=True)
+ completed_at = db.Column(db.DateTime, nullable=True)
+ processing_time_seconds = db.Column(db.Integer, nullable=True)
+ transcription_duration_seconds = db.Column(db.Integer, nullable=True) # Time taken for transcription
+ summarization_duration_seconds = db.Column(db.Integer, nullable=True) # Time taken for summarization
+ processing_source = db.Column(db.String(50), default='upload') # upload, auto_process, recording
+ error_message = db.Column(db.Text, nullable=True) # Store detailed error messages
+
+ # Auto-deletion and archival fields
+ audio_deleted_at = db.Column(db.DateTime, nullable=True) # When audio file was deleted (null = not deleted)
+ deletion_exempt = db.Column(db.Boolean, default=False) # Manual exemption from auto-deletion
+
+ # Speaker embeddings from diarization (JSON dict mapping speaker IDs to 256-dimensional vectors)
+ speaker_embeddings = db.Column(db.JSON, nullable=True)
+
+ # Relationships
+ tag_associations = db.relationship('RecordingTag', back_populates='recording', cascade='all, delete-orphan', order_by='RecordingTag.order')
+
+ @property
+ def tags(self):
+ """Get tags ordered by the order they were added to this recording."""
+ return [assoc.tag for assoc in sorted(self.tag_associations, key=lambda x: x.order)]
+
+ def get_visible_tags(self, viewer_user):
+ """
+ Get tags that are visible to a specific user viewing this recording.
+
+ Visibility rules:
+ - Group tags: visible if viewer is a member of the tag's group
+ - Personal tags: visible only to the tag creator
+
+ Note: These rules apply to ALL users, including the recording owner.
+ Personal tags are private to their creator regardless of recording ownership.
+
+ Args:
+ viewer_user: User object viewing the recording (or None for backward compatibility)
+
+ Returns:
+ List of Tag objects visible to the viewer
+ """
+ # If no viewer specified, return all tags (backward compatibility)
+ if viewer_user is None:
+ return self.tags
+
+ if not self.tags:
+ return []
+
+ # Import here to avoid circular dependencies
+ from src.models.organization import GroupMembership
+
+ visible_tags = []
+ for tag in self.tags:
+ # Group tags: visible if viewer is a member of the group
+ if tag.group_id:
+ membership = GroupMembership.query.filter_by(
+ group_id=tag.group_id,
+ user_id=viewer_user.id
+ ).first()
+ if membership:
+ visible_tags.append(tag)
+ # Personal tags: visible only to tag creator
+ else:
+ if tag.user_id == viewer_user.id:
+ visible_tags.append(tag)
+
+ return visible_tags
+
+ def get_user_notes(self, user):
+ """
+ Get notes from user's perspective (owner or shared recipient).
+
+ - Recording owner sees Recording.notes
+ - Shared users see their personal_notes from SharedRecordingState
+
+ Args:
+ user: User object viewing the recording
+
+ Returns:
+ String notes content or None
+ """
+ if user is None:
+ return self.notes
+
+ if self.user_id == user.id:
+ return self.notes # Owner sees Recording.notes
+ else:
+ # Shared user sees their personal notes
+ from src.models.sharing import SharedRecordingState
+ state = SharedRecordingState.query.filter_by(
+ recording_id=self.id,
+ user_id=user.id
+ ).first()
+ return state.personal_notes if state else None
+
+ def to_list_dict(self, viewer_user=None):
+ """
+ Lightweight dict for list views - excludes expensive HTML conversions.
+
+ Args:
+ viewer_user: User viewing the recording (for tag visibility filtering)
+ """
+ # Import here to avoid circular dependencies
+ from src.models.sharing import InternalShare, Share
+
+ # Count internal shares for this recording
+ shared_with_count = db.session.query(func.count(InternalShare.id)).filter(
+ InternalShare.recording_id == self.id
+ ).scalar() or 0
+
+ # Count public shares (link shares) for this recording
+ public_share_count = db.session.query(func.count(Share.id)).filter(
+ Share.recording_id == self.id
+ ).scalar() or 0
+
+ # Get visible tags for this viewer
+ visible_tags = self.get_visible_tags(viewer_user)
+
+ return {
+ 'id': self.id,
+ 'title': self.title,
+ 'participants': self.participants,
+ 'status': self.status,
+ 'created_at': local_datetime_filter(self.created_at),
+ 'completed_at': local_datetime_filter(self.completed_at),
+ 'meeting_date': local_datetime_filter(self.meeting_date),
+ 'file_size': self.file_size,
+ 'original_filename': self.original_filename,
+ 'is_inbox': self.is_inbox,
+ 'is_highlighted': self.is_highlighted,
+ 'audio_deleted_at': local_datetime_filter(self.audio_deleted_at),
+ 'audio_available': self.audio_deleted_at is None,
+ 'deletion_exempt': self.deletion_exempt,
+ 'tags': [tag.to_dict() for tag in visible_tags] if visible_tags else [],
+ 'shared_with_count': shared_with_count,
+ 'public_share_count': public_share_count
+ }
+
+ def to_dict(self, include_html=True, viewer_user=None):
+ """
+ Full dict with optional HTML conversion for notes/summary.
+
+ Args:
+ include_html: Whether to include HTML-rendered markdown fields
+ viewer_user: User viewing the recording (for tag visibility filtering)
+ """
+ # Import here to avoid circular dependencies
+ from src.models.sharing import InternalShare, Share
+
+ # Count internal shares for this recording
+ shared_with_count = db.session.query(func.count(InternalShare.id)).filter(
+ InternalShare.recording_id == self.id
+ ).scalar() or 0
+
+ # Count public shares (link shares) for this recording
+ public_share_count = db.session.query(func.count(Share.id)).filter(
+ Share.recording_id == self.id
+ ).scalar() or 0
+
+ # Get visible tags for this viewer
+ visible_tags = self.get_visible_tags(viewer_user)
+
+ # Get user-specific notes
+ user_notes = self.get_user_notes(viewer_user)
+
+ data = {
+ 'id': self.id,
+ 'title': self.title,
+ 'participants': self.participants,
+ 'notes': user_notes,
+ 'transcription': self.transcription,
+ 'summary': self.summary,
+ 'status': self.status,
+ 'created_at': local_datetime_filter(self.created_at),
+ 'completed_at': local_datetime_filter(self.completed_at),
+ 'processing_time_seconds': self.processing_time_seconds,
+ 'transcription_duration_seconds': self.transcription_duration_seconds,
+ 'summarization_duration_seconds': self.summarization_duration_seconds,
+ 'meeting_date': local_datetime_filter(self.meeting_date),
+ 'file_size': self.file_size,
+ 'original_filename': self.original_filename,
+ 'user_id': self.user_id,
+ 'is_inbox': self.is_inbox,
+ 'is_highlighted': self.is_highlighted,
+ 'mime_type': self.mime_type,
+ 'audio_deleted_at': local_datetime_filter(self.audio_deleted_at),
+ 'audio_available': self.audio_deleted_at is None,
+ 'deletion_exempt': self.deletion_exempt,
+ 'tags': [tag.to_dict() for tag in visible_tags] if visible_tags else [],
+ 'events': [event.to_dict() for event in self.events] if self.events else [],
+ 'shared_with_count': shared_with_count,
+ 'public_share_count': public_share_count
+ }
+
+ # Only compute expensive HTML conversions when explicitly requested
+ if include_html:
+ data['notes_html'] = md_to_html(user_notes) if user_notes else ""
+ data['summary_html'] = md_to_html(self.summary) if self.summary else ""
+ else:
+ data['notes_html'] = ""
+ data['summary_html'] = ""
+
+ return data
+
+
+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, index=True) # Speaker for this chunk (indexed for speaker rename operations)
+ embedding = db.Column(db.LargeBinary, nullable=True) # Stored as binary vector
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+
+ # Composite index for efficient speaker name lookups scoped to user
+ __table_args__ = (
+ db.Index('idx_user_speaker_name', 'user_id', 'speaker_name'),
+ )
+
+ # 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):
+ """Convert model to dictionary representation."""
+ 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
+ }
diff --git a/src/models/sharing.py b/src/models/sharing.py
new file mode 100644
index 00000000..83bf3a62
--- /dev/null
+++ b/src/models/sharing.py
@@ -0,0 +1,236 @@
+"""
+Sharing models for public and internal recording shares.
+
+This module defines models for sharing recordings both publicly (via links)
+and internally (between users).
+"""
+
+import os
+import secrets
+from datetime import datetime
+from src.database import db
+from src.utils import local_datetime_filter
+
+
+# Get sharing configuration from environment
+SHOW_USERNAMES_IN_UI = os.environ.get('SHOW_USERNAMES_IN_UI', 'false').lower() == 'true'
+
+
+class Share(db.Model):
+ """Public sharing via shareable links."""
+
+ id = db.Column(db.Integer, primary_key=True)
+ public_id = db.Column(db.String(32), unique=True, nullable=False, default=lambda: secrets.token_urlsafe(16))
+ recording_id = db.Column(db.Integer, db.ForeignKey('recording.id'), nullable=False)
+ user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+ share_summary = db.Column(db.Boolean, default=True)
+ share_notes = db.Column(db.Boolean, default=True)
+
+ user = db.relationship('User', backref=db.backref('shares', lazy=True, cascade='all, delete-orphan'))
+ recording = db.relationship('Recording', backref=db.backref('shares', lazy=True, cascade='all, delete-orphan'))
+
+ def to_dict(self):
+ """Convert model to dictionary representation."""
+ return {
+ 'id': self.id,
+ 'public_id': self.public_id,
+ 'recording_id': self.recording_id,
+ 'created_at': local_datetime_filter(self.created_at),
+ 'share_summary': self.share_summary,
+ 'share_notes': self.share_notes,
+ 'recording_title': self.recording.title if self.recording else "N/A",
+ 'audio_available': self.recording.audio_deleted_at is None if self.recording else True
+ }
+
+
+class InternalShare(db.Model):
+ """Tracks internal sharing of recordings between users (independent of teams)."""
+
+ __tablename__ = 'internal_share'
+
+ id = db.Column(db.Integer, primary_key=True)
+ recording_id = db.Column(db.Integer, db.ForeignKey('recording.id', ondelete='CASCADE'), nullable=False)
+ owner_id = db.Column(db.Integer, db.ForeignKey('user.id', ondelete='CASCADE'), nullable=False) # User who shared
+ shared_with_user_id = db.Column(db.Integer, db.ForeignKey('user.id', ondelete='CASCADE'), nullable=False) # User it was shared with
+
+ # Permissions
+ can_edit = db.Column(db.Boolean, default=False) # Can edit notes/metadata
+ can_reshare = db.Column(db.Boolean, default=False) # Can share with others
+
+ # Source tracking for share cleanup
+ source_type = db.Column(db.String(20), default='manual') # 'manual' or 'group_tag'
+ source_tag_id = db.Column(db.Integer, db.ForeignKey('tag.id', ondelete='SET NULL'), nullable=True)
+
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+
+ # Relationship for source tag
+ source_tag = db.relationship('Tag', foreign_keys=[source_tag_id], backref=db.backref('created_shares', lazy=True))
+
+ # Relationships
+ recording = db.relationship('Recording', backref=db.backref('internal_shares', lazy=True, cascade='all, delete-orphan'))
+ owner = db.relationship('User', foreign_keys=[owner_id], backref=db.backref('shared_recordings', lazy=True))
+ shared_with = db.relationship('User', foreign_keys=[shared_with_user_id], backref=db.backref('received_shares', lazy=True))
+
+ # Unique constraint: can't share same recording with same user twice
+ __table_args__ = (db.UniqueConstraint('recording_id', 'shared_with_user_id', name='unique_recording_share'),)
+
+ def to_dict(self):
+ """Convert model to dictionary representation."""
+ return {
+ 'id': self.id,
+ 'recording_id': self.recording_id,
+ 'owner_id': self.owner_id,
+ 'owner_username': self.owner.username if SHOW_USERNAMES_IN_UI else None,
+ 'user_id': self.shared_with_user_id, # For frontend compatibility
+ 'username': self.shared_with.username, # Always include username
+ 'can_edit': self.can_edit,
+ 'can_reshare': self.can_reshare,
+ 'source_type': self.source_type,
+ 'source_tag_id': self.source_tag_id,
+ 'created_at': self.created_at.isoformat() if self.created_at else None
+ }
+
+ @staticmethod
+ def get_user_max_permissions(recording, user):
+ """
+ Get the maximum permissions a user can grant for a recording.
+
+ Args:
+ recording: Recording object
+ user: User object attempting to share
+
+ Returns:
+ Dict with 'can_edit' and 'can_reshare' boolean flags
+ """
+ # Owner has unlimited permissions
+ if recording.user_id == user.id:
+ return {'can_edit': True, 'can_reshare': True}
+
+ # Get user's share for this recording
+ user_share = InternalShare.query.filter_by(
+ recording_id=recording.id,
+ shared_with_user_id=user.id
+ ).first()
+
+ if not user_share:
+ # User has no access
+ return {'can_edit': False, 'can_reshare': False}
+
+ # User can only grant what they have
+ return {
+ 'can_edit': user_share.can_edit,
+ 'can_reshare': user_share.can_reshare
+ }
+
+ @staticmethod
+ def validate_reshare_permissions(recording, grantor_user, requested_permissions):
+ """
+ Validate that a user can grant the requested permissions.
+
+ Args:
+ recording: Recording object being shared
+ grantor_user: User attempting to share (current_user)
+ requested_permissions: Dict with 'can_edit' and 'can_reshare' flags
+
+ Returns:
+ Tuple of (is_valid: bool, error_message: str or None)
+ """
+ # Owner can grant anything
+ if recording.user_id == grantor_user.id:
+ return True, None
+
+ # Get grantor's permissions
+ max_permissions = InternalShare.get_user_max_permissions(recording, grantor_user)
+
+ # Validate edit permission
+ if requested_permissions.get('can_edit', False) and not max_permissions['can_edit']:
+ return False, "You cannot grant edit permission because you do not have edit access"
+
+ # Validate reshare permission
+ if requested_permissions.get('can_reshare', False) and not max_permissions['can_reshare']:
+ return False, "You cannot grant reshare permission because you do not have reshare access"
+
+ return True, None
+
+ @staticmethod
+ def find_downstream_shares(recording_id, user_id):
+ """
+ Find all shares created by a specific user for a recording.
+ Used for cascade revocation.
+
+ Args:
+ recording_id: ID of the recording
+ user_id: ID of the user whose downstream shares to find
+
+ Returns:
+ List of InternalShare objects
+ """
+ return InternalShare.query.filter_by(
+ recording_id=recording_id,
+ owner_id=user_id
+ ).all()
+
+ @staticmethod
+ def has_alternate_access_path(recording_id, user_id, excluding_grantor_id=None):
+ """
+ Check if a user has alternate access to a recording through other shares.
+ Used to prevent cascade revocation when user has multiple access paths (diamond pattern).
+
+ Args:
+ recording_id: ID of the recording
+ user_id: ID of the user to check
+ excluding_grantor_id: Exclude shares from this grantor (the one being revoked)
+
+ Returns:
+ Boolean - True if user has alternate access path
+ """
+ query = InternalShare.query.filter(
+ InternalShare.recording_id == recording_id,
+ InternalShare.shared_with_user_id == user_id
+ )
+
+ if excluding_grantor_id is not None:
+ query = query.filter(InternalShare.owner_id != excluding_grantor_id)
+
+ return query.count() > 0
+
+
+class SharedRecordingState(db.Model):
+ """Tracks per-user state for shared recordings (notes, highlights, etc)."""
+
+ __tablename__ = 'shared_recording_state'
+
+ id = db.Column(db.Integer, primary_key=True)
+ recording_id = db.Column(db.Integer, db.ForeignKey('recording.id', ondelete='CASCADE'), nullable=False)
+ user_id = db.Column(db.Integer, db.ForeignKey('user.id', ondelete='CASCADE'), nullable=False)
+
+ # User-specific state
+ personal_notes = db.Column(db.Text, nullable=True) # Private notes only this user can see
+ is_inbox = db.Column(db.Boolean, default=True) # User's personal inbox status
+ is_highlighted = db.Column(db.Boolean, default=False) # User's personal highlight/favorite status
+ last_viewed = db.Column(db.DateTime, default=datetime.utcnow)
+
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+
+ # Relationships
+ recording = db.relationship('Recording', backref=db.backref('user_states', lazy=True, cascade='all, delete-orphan'))
+ user = db.relationship('User', backref=db.backref('recording_states', lazy=True))
+
+ # Unique constraint: one state per user per recording
+ __table_args__ = (db.UniqueConstraint('recording_id', 'user_id', name='unique_user_recording_state'),)
+
+ def to_dict(self):
+ """Convert model to dictionary representation."""
+ return {
+ 'id': self.id,
+ 'recording_id': self.recording_id,
+ 'user_id': self.user_id,
+ 'personal_notes': self.personal_notes,
+ 'is_inbox': self.is_inbox,
+ 'is_highlighted': self.is_highlighted,
+ 'last_viewed': self.last_viewed.isoformat() if self.last_viewed else None,
+ 'created_at': self.created_at.isoformat() if self.created_at else None,
+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None
+ }
diff --git a/src/models/speaker_snippet.py b/src/models/speaker_snippet.py
new file mode 100644
index 00000000..1accbfc4
--- /dev/null
+++ b/src/models/speaker_snippet.py
@@ -0,0 +1,43 @@
+"""
+SpeakerSnippet database model.
+
+This module defines the SpeakerSnippet model for storing example quotes/snippets
+from recordings that feature specific speakers. These snippets provide context
+when viewing speaker profiles and help users verify speaker identifications.
+"""
+
+from datetime import datetime
+from src.database import db
+
+
+class SpeakerSnippet(db.Model):
+ """Model for storing representative speech snippets from speakers."""
+
+ __tablename__ = 'speaker_snippet'
+
+ id = db.Column(db.Integer, primary_key=True)
+ speaker_id = db.Column(db.Integer, db.ForeignKey('speaker.id', ondelete='CASCADE'), nullable=False)
+ recording_id = db.Column(db.Integer, db.ForeignKey('recording.id', ondelete='CASCADE'), nullable=False)
+ segment_index = db.Column(db.Integer, nullable=False) # Index in the transcript
+ text_snippet = db.Column(db.String(200), nullable=False) # The actual quote
+ timestamp = db.Column(db.Float, nullable=True) # Seconds into the recording
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+
+ # Relationships
+ speaker = db.relationship('Speaker', backref=db.backref('snippets', lazy=True, cascade='all, delete-orphan'))
+ recording = db.relationship('Recording', backref=db.backref('speaker_snippets', lazy=True))
+
+ def to_dict(self):
+ """Convert model to dictionary representation."""
+ return {
+ 'id': self.id,
+ 'speaker_id': self.speaker_id,
+ 'recording_id': self.recording_id,
+ 'text': self.text_snippet,
+ 'timestamp': self.timestamp,
+ 'recording_title': self.recording.title if self.recording else 'Unknown',
+ 'created_at': self.created_at.isoformat() if self.created_at else None
+ }
+
+ def __repr__(self):
+ return f"SpeakerSnippet(speaker_id={self.speaker_id}, recording_id={self.recording_id}, text='{self.text_snippet[:30]}...')"
diff --git a/src/models/system.py b/src/models/system.py
new file mode 100644
index 00000000..a3aae988
--- /dev/null
+++ b/src/models/system.py
@@ -0,0 +1,77 @@
+"""
+SystemSetting model for application configuration.
+
+This module defines the SystemSetting model for storing
+dynamic system configuration in the database.
+"""
+
+from datetime import datetime
+from src.database import db
+
+
+class SystemSetting(db.Model):
+ """Stores system-wide configuration settings."""
+
+ id = db.Column(db.Integer, primary_key=True)
+ key = db.Column(db.String(100), unique=True, nullable=False)
+ value = db.Column(db.Text, nullable=True)
+ description = db.Column(db.Text, nullable=True)
+ setting_type = db.Column(db.String(50), nullable=False, default='string') # string, integer, boolean, float
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+
+ def to_dict(self):
+ """Convert model to dictionary representation."""
+ return {
+ 'id': self.id,
+ 'key': self.key,
+ 'value': self.value,
+ 'description': self.description,
+ 'setting_type': self.setting_type,
+ 'created_at': self.created_at,
+ 'updated_at': self.updated_at
+ }
+
+ @staticmethod
+ def get_setting(key, default_value=None):
+ """Get a system setting value by key, with optional default."""
+ setting = SystemSetting.query.filter_by(key=key).first()
+ if setting:
+ # Convert value based on type
+ if setting.setting_type == 'integer':
+ try:
+ return int(setting.value) if setting.value is not None else default_value
+ except (ValueError, TypeError):
+ return default_value
+ elif setting.setting_type == 'boolean':
+ return setting.value.lower() in ('true', '1', 'yes') if setting.value else default_value
+ elif setting.setting_type == 'float':
+ try:
+ return float(setting.value) if setting.value is not None else default_value
+ except (ValueError, TypeError):
+ return default_value
+ else: # string
+ return setting.value if setting.value is not None else default_value
+ return default_value
+
+ @staticmethod
+ def set_setting(key, value, description=None, setting_type='string'):
+ """Set a system setting value."""
+ setting = SystemSetting.query.filter_by(key=key).first()
+ if setting:
+ setting.value = str(value) if value is not None else None
+ setting.updated_at = datetime.utcnow()
+ if description:
+ setting.description = description
+ if setting_type:
+ setting.setting_type = setting_type
+ else:
+ setting = SystemSetting(
+ key=key,
+ value=str(value) if value is not None else None,
+ description=description,
+ setting_type=setting_type
+ )
+ db.session.add(setting)
+ db.session.commit()
+ return setting
diff --git a/src/models/templates.py b/src/models/templates.py
new file mode 100644
index 00000000..1d98da1b
--- /dev/null
+++ b/src/models/templates.py
@@ -0,0 +1,37 @@
+"""
+TranscriptTemplate model for user-defined transcript formatting.
+
+This module defines the TranscriptTemplate model for storing
+custom templates for transcript formatting.
+"""
+
+from datetime import datetime
+from src.database import db
+
+
+class TranscriptTemplate(db.Model):
+ """Stores user-defined templates for transcript formatting."""
+
+ id = db.Column(db.Integer, primary_key=True)
+ user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
+ name = db.Column(db.String(100), nullable=False)
+ template = db.Column(db.Text, nullable=False)
+ description = db.Column(db.String(500), nullable=True)
+ is_default = db.Column(db.Boolean, default=False)
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
+
+ # Relationships
+ user = db.relationship('User', backref=db.backref('transcript_templates', lazy=True, cascade='all, delete-orphan'))
+
+ def to_dict(self):
+ """Convert model to dictionary representation."""
+ return {
+ 'id': self.id,
+ 'name': self.name,
+ 'template': self.template,
+ 'description': self.description,
+ 'is_default': self.is_default,
+ 'created_at': self.created_at.isoformat() if self.created_at else None,
+ 'updated_at': self.updated_at.isoformat() if self.updated_at else None
+ }
diff --git a/src/models/user.py b/src/models/user.py
new file mode 100644
index 00000000..199703dc
--- /dev/null
+++ b/src/models/user.py
@@ -0,0 +1,66 @@
+"""
+User and Speaker database models.
+
+This module defines the User model for authentication and user profiles,
+and the Speaker model for tracking speaker profiles used in diarization.
+"""
+
+from datetime import datetime
+from flask_login import UserMixin
+from src.database import db
+
+
+class User(db.Model, UserMixin):
+ """User model for authentication and profile management."""
+
+ id = db.Column(db.Integer, primary_key=True)
+ username = db.Column(db.String(20), unique=True, nullable=False)
+ email = db.Column(db.String(120), unique=True, nullable=False)
+ password = db.Column(db.String(60), nullable=False)
+ is_admin = db.Column(db.Boolean, default=False)
+ can_share_publicly = db.Column(db.Boolean, default=True) # Permission to create public share links
+ recordings = db.relationship('Recording', backref='owner', lazy=True)
+ transcription_language = db.Column(db.String(10), nullable=True) # For ISO 639-1 codes
+ output_language = db.Column(db.String(50), nullable=True) # For full language names like "Spanish"
+ ui_language = db.Column(db.String(10), nullable=True, default='en') # For UI language preference (en, es, fr, zh)
+ summary_prompt = db.Column(db.Text, nullable=True)
+ extract_events = db.Column(db.Boolean, default=False) # Enable event extraction from transcripts
+ name = db.Column(db.String(100), nullable=True)
+ job_title = db.Column(db.String(100), nullable=True)
+ company = db.Column(db.String(100), nullable=True)
+ diarize = db.Column(db.Boolean, default=False)
+
+ def __repr__(self):
+ return f"User('{self.username}', '{self.email}')"
+
+
+class Speaker(db.Model):
+ """Speaker model for tracking voice profiles used in diarization."""
+
+ id = db.Column(db.Integer, primary_key=True)
+ name = db.Column(db.String(100), nullable=False)
+ user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+ last_used = db.Column(db.DateTime, default=datetime.utcnow)
+ use_count = db.Column(db.Integer, default=1)
+
+ # Voice embedding fields (256 dimensions from WhisperX)
+ average_embedding = db.Column(db.LargeBinary, nullable=True) # Binary numpy array (256 × 4 bytes = 1024 bytes)
+ embeddings_history = db.Column(db.JSON, nullable=True) # List of metadata: [{recording_id, timestamp, similarity}, ...]
+ embedding_count = db.Column(db.Integer, default=0) # Number of embeddings collected
+ confidence_score = db.Column(db.Float, nullable=True) # 0-1 score based on embedding consistency
+
+ # Relationship to user
+ user = db.relationship('User', backref=db.backref('speakers', lazy=True, cascade='all, delete-orphan'))
+
+ def to_dict(self):
+ """Convert model to dictionary representation."""
+ return {
+ 'id': self.id,
+ 'name': self.name,
+ 'created_at': self.created_at,
+ 'last_used': self.last_used,
+ 'use_count': self.use_count,
+ 'embedding_count': self.embedding_count,
+ 'confidence_score': self.confidence_score
+ }
diff --git a/src/services/__init__.py b/src/services/__init__.py
new file mode 100644
index 00000000..cd5ad305
--- /dev/null
+++ b/src/services/__init__.py
@@ -0,0 +1,32 @@
+"""
+Service layer for business logic.
+"""
+
+from .embeddings import *
+from .llm import *
+from .document import *
+from .retention import *
+
+__all__ = [
+ # Embedding services
+ 'get_embedding_model',
+ 'chunk_transcription',
+ 'generate_embeddings',
+ 'serialize_embedding',
+ 'deserialize_embedding',
+ 'get_accessible_recording_ids',
+ 'process_recording_chunks',
+ 'basic_text_search_chunks',
+ 'semantic_search_chunks',
+ # LLM services
+ 'is_gpt5_model',
+ 'is_using_openai_api',
+ 'call_llm_completion',
+ 'format_api_error_message',
+ # Document services
+ 'process_markdown_to_docx',
+ # Retention services
+ 'is_recording_exempt_from_deletion',
+ 'get_retention_days_for_recording',
+ 'process_auto_deletion',
+]
diff --git a/src/services/calendar.py b/src/services/calendar.py
new file mode 100644
index 00000000..9266b436
--- /dev/null
+++ b/src/services/calendar.py
@@ -0,0 +1,102 @@
+"""
+Calendar/ICS file generation services.
+"""
+
+import json
+import uuid
+from datetime import datetime, timedelta
+
+
+def generate_ics_content(event):
+ """Generate ICS calendar file content for an event."""
+ import uuid
+ from datetime import datetime, timedelta
+
+ # Generate unique ID for the event
+ uid = f"{event.id}-{uuid.uuid4()}@speakr.app"
+
+ # Format dates in iCalendar format (YYYYMMDDTHHMMSS)
+ def format_ical_date(dt):
+ if dt:
+ return dt.strftime('%Y%m%dT%H%M%S')
+ return None
+
+ # Start building ICS content
+ lines = [
+ 'BEGIN:VCALENDAR',
+ 'VERSION:2.0',
+ 'PRODID:-//Speakr//Event Export//EN',
+ 'CALSCALE:GREGORIAN',
+ 'METHOD:PUBLISH',
+ 'BEGIN:VEVENT',
+ f'UID:{uid}',
+ f'DTSTAMP:{format_ical_date(datetime.utcnow())}',
+ ]
+
+ # Add event details
+ if event.start_datetime:
+ lines.append(f'DTSTART:{format_ical_date(event.start_datetime)}')
+
+ if event.end_datetime:
+ lines.append(f'DTEND:{format_ical_date(event.end_datetime)}')
+ elif event.start_datetime:
+ # If no end time, default to 1 hour after start
+ end_time = event.start_datetime + timedelta(hours=1)
+ lines.append(f'DTEND:{format_ical_date(end_time)}')
+
+ # Add title and description
+ lines.append(f'SUMMARY:{escape_ical_text(event.title)}')
+
+ if event.description:
+ lines.append(f'DESCRIPTION:{escape_ical_text(event.description)}')
+
+ # Add location if available
+ if event.location:
+ lines.append(f'LOCATION:{escape_ical_text(event.location)}')
+
+ # Add attendees if available
+ if event.attendees:
+ try:
+ attendees_list = json.loads(event.attendees)
+ for attendee in attendees_list:
+ if attendee:
+ lines.append(f'ATTENDEE:CN={escape_ical_text(attendee)}:mailto:{attendee.replace(" ", ".").lower()}@example.com')
+ except:
+ pass
+
+ # Add reminder/alarm if specified
+ if event.reminder_minutes and event.reminder_minutes > 0:
+ lines.extend([
+ 'BEGIN:VALARM',
+ 'TRIGGER:-PT{}M'.format(event.reminder_minutes),
+ 'ACTION:DISPLAY',
+ f'DESCRIPTION:Reminder: {escape_ical_text(event.title)}',
+ 'END:VALARM'
+ ])
+
+ # Close event and calendar
+ lines.extend([
+ 'STATUS:CONFIRMED',
+ 'TRANSP:OPAQUE',
+ 'END:VEVENT',
+ 'END:VCALENDAR'
+ ])
+
+ return '\r\n'.join(lines)
+
+
+
+def escape_ical_text(text):
+ """Escape special characters for iCalendar format."""
+ if not text:
+ return ''
+ # Escape special characters
+ text = str(text)
+ text = text.replace('\\', '\\\\')
+ text = text.replace(',', '\\,')
+ text = text.replace(';', '\\;')
+ text = text.replace('\n', '\\n')
+ return text
+
+
+
diff --git a/src/services/document.py b/src/services/document.py
new file mode 100644
index 00000000..aae988a1
--- /dev/null
+++ b/src/services/document.py
@@ -0,0 +1,296 @@
+"""
+Document processing and conversion services.
+"""
+
+import re
+from docx import Document
+from docx.shared import Pt, RGBColor
+
+
+
+def process_markdown_to_docx(doc, content):
+ """Convert markdown content to properly formatted Word document elements.
+
+ Supports:
+ - Tables (markdown pipe tables)
+ - Headings (# ## ###)
+ - Bold text (**text**)
+ - Italic text (*text* or _text_)
+ - Bold italic (***text***)
+ - Inline code (`code`)
+ - Code blocks (```code```)
+ - Strikethrough (~~text~~)
+ - Links ([text](url))
+ - Bullet lists (- or *)
+ - Numbered lists (1. 2. 3.)
+ - Horizontal rules (--- or ***)
+ """
+ from docx.shared import RGBColor, Pt
+ from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
+ from docx.oxml.ns import qn
+ import re
+
+ def ensure_unicode_font(run, text):
+ """Ensure the run uses a font that supports the characters in the text."""
+ # Check if text contains non-ASCII characters
+ try:
+ text.encode('ascii')
+ # Text is pure ASCII, no special font needed
+ except UnicodeEncodeError:
+ # Text contains non-ASCII characters, use a font with better Unicode support
+ # Use Arial for broad compatibility - it has good Unicode support on most systems
+ run.font.name = 'Arial'
+ # Set the East Asian font for CJK (Chinese, Japanese, Korean) text
+ # This ensures proper rendering in Word
+ r = run._element
+ r.rPr.rFonts.set(qn('w:eastAsia'), 'Arial')
+ return run
+
+ def add_formatted_run(paragraph, text):
+ """Add a run with inline formatting to a paragraph."""
+ if not text:
+ return
+
+ # Pattern for all inline formatting
+ # Order matters: check triple asterisk before double/single
+ patterns = [
+ (r'\*\*\*(.*?)\*\*\*', lambda p, t: (lambda r: (setattr(r, 'bold', True), setattr(r, 'italic', True), ensure_unicode_font(r, t)))(p.add_run(t))), # Bold italic
+ (r'\*\*(.*?)\*\*', lambda p, t: (lambda r: (setattr(r, 'bold', True), ensure_unicode_font(r, t)))(p.add_run(t))), # Bold
+ (r'(?<!\*)\*(?!\*)(.*?)\*(?!\*)', lambda p, t: (lambda r: (setattr(r, 'italic', True), ensure_unicode_font(r, t)))(p.add_run(t))), # Italic with *
+ (r'\b_(.*?)_\b', lambda p, t: (lambda r: (setattr(r, 'italic', True), ensure_unicode_font(r, t)))(p.add_run(t))), # Italic with _
+ (r'~~(.*?)~~', lambda p, t: (lambda r: (setattr(r, 'strike', True), ensure_unicode_font(r, t)))(p.add_run(t))), # Strikethrough
+ (r'`([^`]+)`', lambda p, t: add_code_run(p, t)), # Inline code
+ (r'\[([^\]]+)\]\(([^)]+)\)', lambda p, t, u: add_link_run(p, t, u)), # Links
+ ]
+
+ def add_code_run(para, text):
+ """Add inline code with monospace font and background."""
+ run = para.add_run(text)
+ run.font.name = 'Courier New'
+ run.font.size = Pt(10)
+ run.font.color.rgb = RGBColor(220, 20, 60) # Crimson color for code
+ # Check if we need Unicode support for code
+ try:
+ text.encode('ascii')
+ except UnicodeEncodeError:
+ # Use Consolas as fallback for better Unicode support in monospace
+ r = run._element
+ r.rPr.rFonts.set(qn('w:eastAsia'), 'Consolas')
+ return run
+
+ def add_link_run(para, text, url):
+ """Add a hyperlink-styled run (note: actual hyperlinks require more complex handling)."""
+ full_text = f"{text} ({url})"
+ run = para.add_run(full_text)
+ run.font.color.rgb = RGBColor(0, 0, 255) # Blue color for links
+ run.font.underline = True
+ ensure_unicode_font(run, full_text)
+ return run
+
+ # Process the text with all patterns
+ remaining_text = text
+ while remaining_text:
+ earliest_match = None
+ earliest_pos = len(remaining_text)
+ matched_pattern = None
+
+ # Find the earliest matching pattern
+ for pattern, handler in patterns:
+ match = re.search(pattern, remaining_text)
+ if match and match.start() < earliest_pos:
+ earliest_match = match
+ earliest_pos = match.start()
+ matched_pattern = handler
+
+ if earliest_match:
+ # Add text before the match
+ if earliest_pos > 0:
+ run = paragraph.add_run(remaining_text[:earliest_pos])
+ ensure_unicode_font(run, remaining_text[:earliest_pos])
+
+ # Apply formatting for the matched text
+ if '[' in earliest_match.group(0) and '](' in earliest_match.group(0):
+ # Special handling for links (two groups)
+ matched_pattern(paragraph, earliest_match.group(1), earliest_match.group(2))
+ else:
+ matched_pattern(paragraph, earliest_match.group(1))
+
+ # Continue with remaining text
+ remaining_text = remaining_text[earliest_match.end():]
+ else:
+ # No more patterns, add the rest as plain text
+ run = paragraph.add_run(remaining_text)
+ ensure_unicode_font(run, remaining_text)
+ break
+
+ def parse_table(lines, start_idx):
+ """Parse a markdown table starting at the given index."""
+ if start_idx >= len(lines):
+ return None, start_idx
+
+ # Check if this looks like a table
+ if '|' not in lines[start_idx]:
+ return None, start_idx
+
+ table_data = []
+ idx = start_idx
+
+ while idx < len(lines) and '|' in lines[idx]:
+ # Skip separator lines
+ if re.match(r'^[\s\|\-:]+$', lines[idx]):
+ idx += 1
+ continue
+
+ # Parse cells
+ cells = [cell.strip() for cell in lines[idx].split('|')]
+ # Remove empty cells at start and end
+ if cells and not cells[0]:
+ cells = cells[1:]
+ if cells and not cells[-1]:
+ cells = cells[:-1]
+
+ if cells:
+ table_data.append(cells)
+ idx += 1
+
+ if table_data:
+ return table_data, idx
+ return None, start_idx
+
+ # Split content into lines
+ lines = content.split('\n')
+ i = 0
+ in_code_block = False
+ code_block_content = []
+
+ while i < len(lines):
+ line = lines[i]
+
+ # Handle code blocks
+ if line.strip().startswith('```'):
+ if not in_code_block:
+ in_code_block = True
+ code_block_content = []
+ else:
+ # End of code block - add it as preformatted text
+ in_code_block = False
+ if code_block_content:
+ p = doc.add_paragraph()
+ p.style = 'Normal'
+ code_text = '\n'.join(code_block_content)
+ run = p.add_run(code_text)
+ run.font.name = 'Courier New'
+ run.font.size = Pt(10)
+ run.font.color.rgb = RGBColor(64, 64, 64)
+ # Check if we need Unicode support for code blocks
+ try:
+ code_text.encode('ascii')
+ except UnicodeEncodeError:
+ r = run._element
+ r.rPr.rFonts.set(qn('w:eastAsia'), 'Consolas')
+ i += 1
+ continue
+
+ if in_code_block:
+ code_block_content.append(line)
+ i += 1
+ continue
+
+ # Check for table
+ table_data, end_idx = parse_table(lines, i)
+ if table_data:
+ # Create Word table
+ table = doc.add_table(rows=len(table_data), cols=len(table_data[0]))
+ table.style = 'Table Grid'
+
+ # Populate table
+ for row_idx, row_data in enumerate(table_data):
+ for col_idx, cell_text in enumerate(row_data):
+ if col_idx < len(table.rows[row_idx].cells):
+ cell = table.rows[row_idx].cells[col_idx]
+ # Clear existing paragraphs and add new one
+ cell.text = ""
+ p = cell.add_paragraph()
+ add_formatted_run(p, cell_text)
+ # Make header row bold
+ if row_idx == 0:
+ for run in p.runs:
+ run.bold = True
+
+ doc.add_paragraph('') # Space after table
+ i = end_idx
+ continue
+
+ line = line.rstrip()
+
+ # Skip empty lines
+ if not line:
+ doc.add_paragraph('')
+ i += 1
+ continue
+
+ # Horizontal rule
+ if re.match(r'^(\*{3,}|-{3,}|_{3,})$', line.strip()):
+ p = doc.add_paragraph('─' * 50)
+ p.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
+ i += 1
+ continue
+
+ # Headings
+ if line.startswith('# '):
+ doc.add_heading(line[2:], 1)
+ elif line.startswith('## '):
+ doc.add_heading(line[3:], 2)
+ elif line.startswith('### '):
+ doc.add_heading(line[4:], 3)
+ elif line.startswith('#### '):
+ doc.add_heading(line[5:], 4)
+ # Bullet points
+ elif line.lstrip().startswith('- ') or line.lstrip().startswith('* '):
+ # Get the indentation level
+ indent = len(line) - len(line.lstrip())
+ bullet_text = line.lstrip()[2:]
+ p = doc.add_paragraph(style='List Bullet')
+ # Add indentation if nested
+ if indent > 0:
+ p.paragraph_format.left_indent = Pt(indent * 10)
+ add_formatted_run(p, bullet_text)
+ # Numbered lists
+ elif re.match(r'^\s*\d+\.', line):
+ match = re.match(r'^(\s*)(\d+)\.\s*(.*)', line)
+ if match:
+ indent = len(match.group(1))
+ list_text = match.group(3)
+ p = doc.add_paragraph(style='List Number')
+ if indent > 0:
+ p.paragraph_format.left_indent = Pt(indent * 10)
+ add_formatted_run(p, list_text)
+ # Blockquote
+ elif line.startswith('> '):
+ p = doc.add_paragraph()
+ p.paragraph_format.left_indent = Pt(30)
+ add_formatted_run(p, line[2:])
+ # Add a gray color to indicate quote
+ for run in p.runs:
+ run.font.color.rgb = RGBColor(100, 100, 100)
+ else:
+ # Regular paragraph
+ p = doc.add_paragraph()
+ add_formatted_run(p, line)
+
+ i += 1
+
+# --- Database Models ---
+# --- Database Models ---
+# Models have been extracted to src/models/ and imported at the top of this file
+
+# --- Forms for Authentication ---
+# --- Custom Password Validator ---
+# password_check utility has been extracted to src/utils/security.py
+
+
+# --- Blueprint Registration ---
+# Import and register all blueprints for modular route organization
+
+
+
diff --git a/src/services/embeddings.py b/src/services/embeddings.py
new file mode 100644
index 00000000..26590a9f
--- /dev/null
+++ b/src/services/embeddings.py
@@ -0,0 +1,395 @@
+"""
+Embedding generation and semantic search services.
+"""
+
+import os
+import numpy as np
+from flask import current_app
+from sqlalchemy.orm import joinedload
+
+try:
+ from sentence_transformers import SentenceTransformer
+ from sklearn.metrics.pairwise import cosine_similarity
+ EMBEDDINGS_AVAILABLE = True
+except ImportError:
+ EMBEDDINGS_AVAILABLE = False
+ cosine_similarity = None
+
+from src.database import db
+from src.models import Recording, TranscriptChunk, InternalShare, RecordingTag
+
+ENABLE_INTERNAL_SHARING = os.environ.get('ENABLE_INTERNAL_SHARING', 'false').lower() == 'true'
+
+# 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')
+ current_app.logger.info("Embedding model loaded successfully")
+ except Exception as e:
+ current_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:
+ current_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:
+ current_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 get_accessible_recording_ids(user_id):
+ """
+ Get all recording IDs that a user has access to.
+
+ Includes:
+ - Recordings owned by the user
+ - Recordings shared with the user via InternalShare
+ - Recordings shared via group tags (if team membership exists)
+
+ Args:
+ user_id (int): User ID to check access for
+
+ Returns:
+ list: List of recording IDs the user can access
+ """
+ accessible_ids = set()
+
+ # 1. User's own recordings
+ own_recordings = db.session.query(Recording.id).filter_by(user_id=user_id).all()
+ accessible_ids.update([r.id for r in own_recordings])
+
+ # 2. Internally shared recordings
+ if ENABLE_INTERNAL_SHARING:
+ shared_recordings = db.session.query(InternalShare.recording_id).filter_by(
+ shared_with_user_id=user_id
+ ).all()
+ accessible_ids.update([r.recording_id for r in shared_recordings])
+
+ return list(accessible_ids)
+
+
+
+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()
+ current_app.logger.info(f"Created {len(chunks)} chunks for recording {recording_id}")
+ return True
+
+ except Exception as e:
+ current_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.
+ Searches across user's own recordings and recordings shared with them.
+ """
+ try:
+ # Get all accessible recording IDs (own + shared)
+ accessible_recording_ids = get_accessible_recording_ids(user_id)
+
+ if not accessible_recording_ids:
+ return []
+
+ # Build base query for chunks from accessible recordings
+ chunks_query = TranscriptChunk.query.filter(
+ TranscriptChunk.recording_id.in_(accessible_recording_ids)
+ )
+
+ # 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))
+ current_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:
+ current_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.
+ Searches across user's own recordings and recordings shared with them.
+
+ 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:
+ current_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]
+
+ # Get all accessible recording IDs (own + shared)
+ accessible_recording_ids = get_accessible_recording_ids(user_id)
+
+ if not accessible_recording_ids:
+ return []
+
+ # Build base query for chunks from accessible recordings with eager loading
+ chunks_query = TranscriptChunk.query.options(joinedload(TranscriptChunk.recording)).filter(
+ TranscriptChunk.recording_id.in_(accessible_recording_ids)
+ )
+
+ # 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))
+ current_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:
+ current_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:
+ current_app.logger.error(f"Error in semantic search: {e}")
+ return []
+
+# --- Helper Functions for Document Processing ---
+
+
+
diff --git a/src/services/llm.py b/src/services/llm.py
new file mode 100644
index 00000000..2225eec5
--- /dev/null
+++ b/src/services/llm.py
@@ -0,0 +1,248 @@
+"""
+LLM API integration services (OpenAI/OpenRouter).
+"""
+
+import os
+import re
+import json
+import logging
+import httpx
+from openai import OpenAI
+
+# Use standard logging instead of current_app.logger for context independence
+logger = logging.getLogger(__name__)
+
+from src.utils import safe_json_loads, extract_json_object
+
+# Configuration - use TEXT_MODEL_* variables for LLM
+TEXT_MODEL_API_KEY = os.environ.get("TEXT_MODEL_API_KEY")
+TEXT_MODEL_BASE_URL = os.environ.get("TEXT_MODEL_BASE_URL", "https://openrouter.ai/api/v1")
+if TEXT_MODEL_BASE_URL:
+ TEXT_MODEL_BASE_URL = TEXT_MODEL_BASE_URL.split('#')[0].strip()
+TEXT_MODEL_NAME = os.environ.get("TEXT_MODEL_NAME", "openai/gpt-3.5-turbo")
+
+# Set up HTTP client with custom headers for OpenRouter app identification
+app_headers = {
+ "HTTP-Referer": "https://github.com/murtaza-nasir/speakr",
+ "X-Title": "Speakr - AI Audio Transcription",
+ "User-Agent": "Speakr/1.0 (https://github.com/murtaza-nasir/speakr)"
+}
+
+http_client_no_proxy = httpx.Client(
+ verify=True,
+ headers=app_headers
+)
+
+# Create client with placeholder key if not provided (allows app to start)
+try:
+ api_key = TEXT_MODEL_API_KEY or "not-needed"
+ client = OpenAI(
+ api_key=api_key,
+ base_url=TEXT_MODEL_BASE_URL,
+ http_client=http_client_no_proxy
+ )
+except Exception as client_init_e:
+ client = None
+
+
+
+def is_gpt5_model(model_name):
+ """
+ Check if the model is a GPT-5 series model that requires special API parameters.
+
+ Args:
+ model_name: The model name string
+
+ Returns:
+ Boolean indicating if this is a GPT-5 model
+ """
+ if not model_name:
+ return False
+ model_lower = model_name.lower()
+ return model_lower.startswith('gpt-5') or model_lower in ['gpt-5', 'gpt-5-mini', 'gpt-5-nano', 'gpt-5-chat-latest']
+
+
+
+def is_using_openai_api():
+ """
+ Check if we're using the official OpenAI API (not OpenRouter or other providers).
+
+ Returns:
+ Boolean indicating if this is the OpenAI API
+ """
+ return TEXT_MODEL_BASE_URL and 'api.openai.com' in TEXT_MODEL_BASE_URL
+
+
+
+def call_llm_completion(messages, temperature=0.7, response_format=None, stream=False, max_tokens=None):
+ """
+ Centralized function for LLM API calls with proper error handling and logging.
+
+ Args:
+ messages: List of message dicts with 'role' and 'content'
+ temperature: Sampling temperature (0-1) - ignored for GPT-5 models
+ response_format: Optional response format dict (e.g., {"type": "json_object"})
+ stream: Whether to stream the response
+ max_tokens: Optional maximum tokens to generate
+
+ Returns:
+ OpenAI completion object or generator (if streaming)
+ """
+ if not client:
+ raise ValueError("LLM client not initialized")
+
+ if not TEXT_MODEL_API_KEY:
+ raise ValueError("TEXT_MODEL_API_KEY not configured")
+
+ try:
+ # Check if we're using GPT-5 with OpenAI API
+ using_gpt5 = is_gpt5_model(TEXT_MODEL_NAME) and is_using_openai_api()
+
+ completion_args = {
+ "model": TEXT_MODEL_NAME,
+ "messages": messages,
+ "stream": stream
+ }
+
+ if using_gpt5:
+ # GPT-5 models don't support temperature, top_p, or logprobs
+ # They use reasoning_effort and verbosity instead
+ logger.debug(f"Using GPT-5 model: {TEXT_MODEL_NAME} - applying GPT-5 specific parameters")
+
+ # Get GPT-5 specific parameters from environment variables
+ reasoning_effort = os.environ.get("GPT5_REASONING_EFFORT", "medium") # minimal, low, medium, high
+ verbosity = os.environ.get("GPT5_VERBOSITY", "medium") # low, medium, high
+
+ # Add GPT-5 specific parameters
+ completion_args["reasoning_effort"] = reasoning_effort
+ completion_args["verbosity"] = verbosity
+
+ # Use max_completion_tokens instead of max_tokens for GPT-5
+ if max_tokens:
+ completion_args["max_completion_tokens"] = max_tokens
+ else:
+ # Non-GPT-5 models use standard parameters
+ completion_args["temperature"] = temperature
+
+ if max_tokens:
+ completion_args["max_tokens"] = max_tokens
+
+ if response_format:
+ completion_args["response_format"] = response_format
+
+ response = client.chat.completions.create(**completion_args)
+
+ # Debug log for empty responses
+ if not stream and response.choices:
+ content = response.choices[0].message.content
+ if not content:
+ logger.warning(f"LLM returned empty content. Model: {TEXT_MODEL_NAME}, finish_reason: {response.choices[0].finish_reason}")
+ # Log more details if available
+ if hasattr(response.choices[0].message, 'refusal'):
+ logger.warning(f"Refusal: {response.choices[0].message.refusal}")
+ if hasattr(response.choices[0].message, 'tool_calls') and response.choices[0].message.tool_calls:
+ logger.warning(f"Tool calls present: {response.choices[0].message.tool_calls}")
+
+ return response
+
+ except Exception as e:
+ logger.error(f"LLM API call failed: {e}")
+ raise
+
+# Store details for the transcription client (potentially different)
+
+
+def format_api_error_message(error_str):
+ """
+ Formats API error messages to be more user-friendly.
+ Specifically handles token limit errors with helpful suggestions.
+ """
+ error_lower = error_str.lower()
+
+ # Check for token limit errors
+ if 'maximum context length' in error_lower and 'tokens' in error_lower:
+ return "[Summary generation failed: The transcription is too long for AI processing. Request your admin to try using a different LLM with a larger context size, or set a limit for the transcript_length_limit in the system settings.]"
+
+ # Check for other common API errors
+ if 'rate limit' in error_lower:
+ return "[Summary generation failed: API rate limit exceeded. Please try again in a few minutes.]"
+
+ if 'insufficient funds' in error_lower or 'quota exceeded' in error_lower:
+ return "[Summary generation failed: API quota exceeded. Please contact support.]"
+
+ if 'timeout' in error_lower:
+ return "[Summary generation failed: Request timed out. Please try again.]"
+
+ # For other errors, show a generic message
+ return f"[Summary generation failed: {error_str}]"
+
+
+def process_streaming_with_thinking(stream):
+ """
+ Generator that processes a streaming response and separates thinking content.
+ Yields SSE-formatted data with 'delta' for regular content and 'thinking' for thinking content.
+ """
+ content_buffer = ""
+ in_thinking = False
+ thinking_buffer = ""
+
+ for chunk in stream:
+ content = chunk.choices[0].delta.content
+ if content:
+ content_buffer += content
+
+ # Process the buffer to detect and handle thinking tags
+ while True:
+ if not in_thinking:
+ # Look for opening thinking tag
+ think_start = re.search(r'<think(?:ing)?>', content_buffer, re.IGNORECASE)
+ if think_start:
+ # Send any content before the thinking tag
+ before_thinking = content_buffer[:think_start.start()]
+ if before_thinking:
+ yield f"data: {json.dumps({'delta': before_thinking})}\n\n"
+
+ # Start capturing thinking content
+ in_thinking = True
+ content_buffer = content_buffer[think_start.end():]
+ thinking_buffer = ""
+ else:
+ # No thinking tag found, send accumulated content
+ if content_buffer:
+ yield f"data: {json.dumps({'delta': content_buffer})}\n\n"
+ content_buffer = ""
+ break
+ else:
+ # We're inside a thinking tag, look for closing tag
+ think_end = re.search(r'</think(?:ing)?>', content_buffer, re.IGNORECASE)
+ if think_end:
+ # Capture thinking content up to the closing tag
+ thinking_buffer += content_buffer[:think_end.start()]
+
+ # Send the thinking content as a special type
+ if thinking_buffer.strip():
+ yield f"data: {json.dumps({'thinking': thinking_buffer.strip()})}\n\n"
+
+ # Continue processing after the closing tag
+ in_thinking = False
+ content_buffer = content_buffer[think_end.end():]
+ thinking_buffer = ""
+ else:
+ # Still inside thinking tag, accumulate content
+ thinking_buffer += content_buffer
+ content_buffer = ""
+ break
+
+ # Handle any remaining content
+ if in_thinking and thinking_buffer:
+ # Unclosed thinking tag - send as thinking content
+ yield f"data: {json.dumps({'thinking': thinking_buffer.strip()})}\n\n"
+ elif content_buffer:
+ # Regular content
+ yield f"data: {json.dumps({'delta': content_buffer})}\n\n"
+
+ # Signal the end of the stream
+ yield f"data: {json.dumps({'end_of_stream': True})}\n\n"
+
+
+
diff --git a/src/services/retention.py b/src/services/retention.py
new file mode 100644
index 00000000..a85b29b4
--- /dev/null
+++ b/src/services/retention.py
@@ -0,0 +1,215 @@
+"""
+Recording retention and auto-deletion services.
+"""
+
+import os
+from datetime import datetime, timedelta
+from flask import current_app
+
+from src.database import db
+from src.models import Recording, RecordingTag, Tag
+
+ENABLE_AUTO_DELETION = os.environ.get('ENABLE_AUTO_DELETION', 'false').lower() == 'true'
+GLOBAL_RETENTION_DAYS = int(os.environ.get('GLOBAL_RETENTION_DAYS', '0'))
+DELETION_MODE = os.environ.get('DELETION_MODE', 'full_recording')
+
+
+
+def is_recording_exempt_from_deletion(recording):
+ """
+ Check if a recording is exempt from auto-deletion.
+
+ Args:
+ recording: Recording object to check
+
+ Returns:
+ Boolean indicating if the recording should be kept
+ """
+ # Manual exemption flag
+ if recording.deletion_exempt:
+ return True
+
+ # Check if any of the recording's tags protect it from deletion
+ # Protection can be indicated by either protect_from_deletion flag OR retention_days == -1
+ for tag_assoc in recording.tag_associations:
+ if tag_assoc.tag.protect_from_deletion:
+ return True
+ if tag_assoc.tag.retention_days == -1:
+ return True
+
+ return False
+
+
+
+def get_retention_days_for_recording(recording):
+ """
+ Get the effective retention period for a recording.
+ Multi-tier system: tag retention (shortest) → global retention
+
+ Tags with retention_days set override the global retention policy.
+ If multiple tags have retention_days, the SHORTEST period is used (most conservative).
+ Note: retention_days == -1 indicates infinite retention (protected), which is handled separately.
+
+ Args:
+ recording: Recording object
+
+ Returns:
+ Integer days for retention period, or None if no retention applies
+ """
+ # Collect all tag-level retention periods
+ # Skip -1 (infinite retention/protected) as that's handled in is_recording_exempt_from_deletion
+ tag_retention_periods = []
+ for tag_assoc in recording.tag_associations:
+ if tag_assoc.tag.retention_days and tag_assoc.tag.retention_days > 0:
+ tag_retention_periods.append(tag_assoc.tag.retention_days)
+
+ # If any tags have retention periods, use the shortest one (most conservative)
+ if tag_retention_periods:
+ return min(tag_retention_periods)
+
+ # Fall back to global retention
+ if GLOBAL_RETENTION_DAYS > 0:
+ return GLOBAL_RETENTION_DAYS
+
+ return None
+
+
+
+def process_auto_deletion():
+ """
+ Process auto-deletion of recordings based on retention policies.
+ This can be called by a scheduled job or admin endpoint.
+
+ Supports per-recording retention via tag-level retention_days overrides.
+ Tags with retention_days set take precedence over global retention.
+
+ Returns:
+ Dictionary with deletion statistics
+ """
+ if not ENABLE_AUTO_DELETION:
+ return {'error': 'Auto-deletion is not enabled'}
+
+ # Check if any retention policy exists (global or tag-level)
+ has_global_retention = GLOBAL_RETENTION_DAYS > 0
+ # We'll check for tag-level retention on a per-recording basis
+
+ if not has_global_retention:
+ # Still check recordings in case they have tag-level retention
+ current_app.logger.info("No global retention configured, checking for tag-level retention policies")
+
+ stats = {
+ 'checked': 0,
+ 'deleted_audio_only': 0,
+ 'deleted_full': 0,
+ 'exempted': 0,
+ 'skipped_no_retention': 0,
+ 'errors': 0
+ }
+
+ try:
+ # Get completed recordings to check
+ # In audio_only mode: Skip recordings where audio was already deleted
+ # In full_recording mode: Include all (to catch audio-only deletions for full cleanup)
+ if DELETION_MODE == 'audio_only':
+ all_recordings = Recording.query.filter(
+ Recording.status == 'COMPLETED',
+ Recording.audio_deleted_at.is_(None) # Skip already-deleted audio
+ ).all()
+ else: # full_recording mode
+ all_recordings = Recording.query.filter(
+ Recording.status == 'COMPLETED'
+ ).all()
+
+ stats['checked'] = len(all_recordings)
+ current_time = datetime.utcnow()
+
+ for recording in all_recordings:
+ try:
+ # Check if exempt from deletion entirely
+ if is_recording_exempt_from_deletion(recording):
+ stats['exempted'] += 1
+ continue
+
+ # Get the effective retention period for this specific recording
+ retention_days = get_retention_days_for_recording(recording)
+
+ if not retention_days:
+ # No retention policy applies to this recording
+ stats['skipped_no_retention'] += 1
+ continue
+
+ # Calculate the cutoff date for this specific recording
+ cutoff_date = current_time - timedelta(days=retention_days)
+
+ # Check if recording is past its retention period
+ if recording.created_at >= cutoff_date:
+ # Recording is still within retention period
+ continue
+
+ # Recording is past retention period - process deletion
+
+ # Determine deletion mode
+ if DELETION_MODE == 'audio_only':
+ # Delete only the audio file, keep transcription
+ if recording.audio_path and os.path.exists(recording.audio_path):
+ current_app.logger.info(f"Recording {recording.id} is past retention ({retention_days} days), deleting audio")
+ os.remove(recording.audio_path)
+ current_app.logger.info(f"Auto-deleted audio file: {recording.audio_path}")
+ recording.audio_deleted_at = datetime.utcnow()
+ db.session.commit()
+ stats['deleted_audio_only'] += 1
+ else:
+ # Audio already deleted or doesn't exist - just mark timestamp
+ if not recording.audio_deleted_at:
+ recording.audio_deleted_at = datetime.utcnow()
+ db.session.commit()
+ current_app.logger.debug(f"Recording {recording.id} audio file not found, marked as deleted")
+
+ else: # full_recording mode
+ # Check if this is completing a previous audio_only deletion
+ if recording.audio_deleted_at:
+ current_app.logger.info(f"Recording {recording.id} has deleted audio (mode changed), completing full deletion")
+ else:
+ current_app.logger.info(f"Recording {recording.id} is past retention ({retention_days} days), deleting fully")
+
+ # Delete audio file if it exists
+ if recording.audio_path and os.path.exists(recording.audio_path):
+ os.remove(recording.audio_path)
+
+ # Delete the database record (cascades to chunks, shares, etc.)
+ db.session.delete(recording)
+ db.session.commit()
+ stats['deleted_full'] += 1
+ current_app.logger.info(f"Auto-deleted full recording ID: {recording.id}")
+
+ except Exception as e:
+ stats['errors'] += 1
+ current_app.logger.error(f"Error auto-deleting recording {recording.id}: {e}")
+ db.session.rollback()
+
+ # After processing recording deletions, clean up orphaned speaker profiles
+ try:
+ from src.services.speaker_cleanup import cleanup_orphaned_speakers
+ speaker_stats = cleanup_orphaned_speakers()
+ stats['speakers_deleted'] = speaker_stats['speakers_deleted']
+ stats['embeddings_cleaned'] = speaker_stats['embeddings_removed']
+ stats['speakers_evaluated'] = speaker_stats['speakers_evaluated']
+ current_app.logger.info(
+ f"Speaker cleanup completed: {speaker_stats['speakers_deleted']} speakers deleted, "
+ f"{speaker_stats['embeddings_removed']} embedding references removed"
+ )
+ except Exception as e:
+ current_app.logger.error(f"Error during speaker cleanup: {e}", exc_info=True)
+ stats['speaker_cleanup_error'] = str(e)
+
+ current_app.logger.info(f"Auto-deletion completed: {stats}")
+ return stats
+
+ except Exception as e:
+ current_app.logger.error(f"Error during auto-deletion process: {e}", exc_info=True)
+ return {'error': str(e)}
+
+# --- API client setup for OpenRouter ---
+# Use environment variables from .env
+
+
diff --git a/src/services/speaker.py b/src/services/speaker.py
new file mode 100644
index 00000000..d6559767
--- /dev/null
+++ b/src/services/speaker.py
@@ -0,0 +1,219 @@
+"""
+Speaker identification and management services.
+"""
+
+import os
+import re
+from datetime import datetime
+from flask import current_app
+from flask_login import current_user
+
+from src.database import db
+from src.models import Speaker, SystemSetting
+from src.services.llm import call_llm_completion
+from src.utils import safe_json_loads
+
+# NOTE: format_transcription_for_llm is referenced but not defined - needs to be implemented
+def format_transcription_for_llm(transcription):
+ """
+ Format transcription for LLM processing.
+
+ TODO: This function needs proper implementation.
+ If transcription is JSON, extract and format the text.
+ Otherwise return as-is.
+ """
+ if isinstance(transcription, str):
+ try:
+ import json
+ data = json.loads(transcription)
+ # If it's JSON diarized format, extract text
+ if isinstance(data, list):
+ return '\n'.join([f"[{seg.get('speaker', 'UNKNOWN')}] {seg.get('text', '')}"
+ for seg in data if 'text' in seg])
+ except:
+ pass
+ return str(transcription)
+
+# Import TEXT_MODEL_API_KEY from llm service
+from src.services.llm import TEXT_MODEL_API_KEY
+
+
+def update_speaker_usage(speaker_names):
+ """Helper function to update speaker usage statistics."""
+ if not speaker_names or not current_user.is_authenticated:
+ return
+
+ try:
+ for name in speaker_names:
+ name = name.strip()
+ if not name:
+ continue
+
+ speaker = Speaker.query.filter_by(user_id=current_user.id, name=name).first()
+ if speaker:
+ speaker.use_count += 1
+ speaker.last_used = datetime.utcnow()
+ else:
+ # Create new speaker
+ speaker = Speaker(
+ name=name,
+ user_id=current_user.id,
+ use_count=1,
+ created_at=datetime.utcnow(),
+ last_used=datetime.utcnow()
+ )
+ db.session.add(speaker)
+
+ db.session.commit()
+ except Exception as e:
+ current_app.logger.error(f"Error updating speaker usage: {e}")
+ db.session.rollback()
+
+
+
+def identify_speakers_from_text(transcription):
+ """
+ Uses an LLM to identify speakers from a transcription.
+ """
+ if not TEXT_MODEL_API_KEY:
+ raise ValueError("TEXT_MODEL_API_KEY not configured.")
+
+ # The transcription passed here could be JSON, so we format it.
+ formatted_transcription = format_transcription_for_llm(transcription)
+
+ # Extract existing speaker labels (e.g., SPEAKER_00, SPEAKER_01) in order of appearance
+ all_labels = re.findall(r'\[(SPEAKER_\d+)\]', formatted_transcription)
+ seen = set()
+ speaker_labels = [x for x in all_labels if not (x in seen or seen.add(x))]
+
+ if not speaker_labels:
+ return {}
+
+ # Get configurable transcript length limit
+ transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)
+ if transcript_limit == -1:
+ # No limit
+ transcript_text = formatted_transcription
+ else:
+ transcript_text = formatted_transcription[:transcript_limit]
+
+ prompt = f"""Analyze the following transcription and identify the names of the speakers. The speakers are labeled as {', '.join(speaker_labels)}. Based on the context of the conversation, determine the most likely name for each speaker label.
+
+Transcription:
+---
+{transcript_text}
+---
+
+Respond with a single JSON object where keys are the speaker labels (e.g., "SPEAKER_00") and values are the identified full names. If a name cannot be determined, use the value "Unknown".
+
+Example:
+{{
+ "SPEAKER_00": "John Doe",
+ "SPEAKER_01": "Jane Smith",
+ "SPEAKER_02": "Unknown"
+}}
+
+JSON Response:
+"""
+
+ try:
+ completion = call_llm_completion(
+ messages=[
+ {"role": "system", "content": "You are an expert in analyzing conversation transcripts to identify speakers. Your response must be a single, valid JSON object."},
+ {"role": "user", "content": prompt}
+ ],
+ temperature=0.2,
+ response_format={"type": "json_object"}
+ )
+ response_content = completion.choices[0].message.content
+ speaker_map = safe_json_loads(response_content, {})
+
+ # Post-process the map to replace "Unknown" with an empty string
+ for speaker_label, identified_name in speaker_map.items():
+ if identified_name.strip().lower() == "unknown":
+ speaker_map[speaker_label] = ""
+
+ return speaker_map
+ except Exception as e:
+ current_app.logger.error(f"Error calling LLM for speaker identification: {e}")
+ raise
+
+
+def identify_unidentified_speakers_from_text(transcription, unidentified_speakers):
+ """
+ Uses an LLM to identify only the unidentified speakers from a transcription.
+ """
+ if not TEXT_MODEL_API_KEY:
+ raise ValueError("TEXT_MODEL_API_KEY not configured.")
+
+ # The transcription passed here could be JSON, so we format it.
+ formatted_transcription = format_transcription_for_llm(transcription)
+
+ if not unidentified_speakers:
+ return {}
+
+ # Get configurable transcript length limit
+ transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)
+ if transcript_limit == -1:
+ # No limit
+ transcript_text = formatted_transcription
+ else:
+ transcript_text = formatted_transcription[:transcript_limit]
+
+ prompt = f"""Analyze the following conversation transcript and identify the names of the UNIDENTIFIED speakers based on the context and content of their dialogue.
+
+The speakers that need to be identified are: {', '.join(unidentified_speakers)}
+
+Look for clues in the conversation such as:
+- Names mentioned by other speakers when addressing someone
+- Self-introductions or references to their own name
+- Context clues about roles, relationships, or positions
+- Any direct mentions of names in the dialogue
+
+Here is the complete conversation transcript:
+
+{transcript_text}
+
+Based on the conversation above, identify the most likely real names for the unidentified speakers. Pay close attention to how speakers address each other and any names that are mentioned in the dialogue.
+
+Respond with a single JSON object where keys are the speaker labels (e.g., "SPEAKER_01") and values are the identified full names. If a name cannot be determined from the conversation context, use an empty string "".
+
+Example format:
+{{
+ "SPEAKER_01": "Jane Smith",
+ "SPEAKER_03": "Bob Johnson",
+ "SPEAKER_05": ""
+}}
+
+JSON Response:
+"""
+
+ try:
+ current_app.logger.info(f"[Auto-Identify] Calling LLM to identify speakers: {unidentified_speakers}")
+ current_app.logger.info(f"[Auto-Identify] Transcript excerpt (first 500 chars): {transcript_text[:500]}")
+
+ completion = call_llm_completion(
+ messages=[
+ {"role": "system", "content": "You are an expert in analyzing conversation transcripts to identify speakers based on contextual clues in the dialogue. Analyze the conversation carefully to find names mentioned when speakers address each other or introduce themselves. Your response must be a single, valid JSON object containing only the requested speaker identifications."},
+ {"role": "user", "content": prompt}
+ ],
+ temperature=0.2,
+ response_format={"type": "json_object"}
+ )
+ response_content = completion.choices[0].message.content
+ current_app.logger.info(f"[Auto-Identify] LLM Raw Response: {response_content}")
+
+ speaker_map = safe_json_loads(response_content, {})
+ current_app.logger.info(f"[Auto-Identify] Parsed speaker_map: {speaker_map}")
+
+ # Post-process the map to replace "Unknown" with an empty string
+ for speaker_label, identified_name in speaker_map.items():
+ if identified_name and identified_name.strip().lower() in ["unknown", "n/a", "not available", "unclear"]:
+ speaker_map[speaker_label] = ""
+
+ current_app.logger.info(f"[Auto-Identify] Final speaker_map after post-processing: {speaker_map}")
+ return speaker_map
+ except Exception as e:
+ current_app.logger.error(f"Error calling LLM for speaker identification: {e}", exc_info=True)
+ raise
+
diff --git a/src/services/speaker_cleanup.py b/src/services/speaker_cleanup.py
new file mode 100644
index 00000000..7e6be6bc
--- /dev/null
+++ b/src/services/speaker_cleanup.py
@@ -0,0 +1,274 @@
+"""
+Speaker cleanup service for managing orphaned speaker voice profiles.
+
+This module provides automatic cleanup of speaker records when their associated
+recordings are deleted through auto-deletion or manual deletion processes.
+"""
+
+import logging
+import json
+from datetime import datetime
+from sqlalchemy import exists
+from src.database import db
+from src.models import Speaker, SpeakerSnippet, Recording
+
+logger = logging.getLogger(__name__)
+
+
+def cleanup_orphaned_speakers(dry_run=False):
+ """
+ Clean up speaker records that no longer have any associated recordings.
+
+ A speaker is considered orphaned when:
+ - It has no SpeakerSnippet records
+ - Its embeddings_history contains no valid recording references
+
+ Args:
+ dry_run (bool): If True, only report what would be deleted without actually deleting
+
+ Returns:
+ dict: Statistics about cleanup operation
+ {
+ 'speakers_deleted': int,
+ 'embeddings_removed': int,
+ 'speakers_evaluated': int,
+ 'orphaned_speakers': list of dict (if dry_run=True)
+ }
+ """
+ logger.info("Starting speaker cleanup process (dry_run=%s)", dry_run)
+
+ stats = {
+ 'speakers_deleted': 0,
+ 'embeddings_removed': 0,
+ 'speakers_evaluated': 0,
+ 'orphaned_speakers': []
+ }
+
+ try:
+ # Clean embeddings_history references first
+ embeddings_cleaned = clean_embeddings_history_references(dry_run=dry_run)
+ stats['embeddings_removed'] = embeddings_cleaned
+
+ # Find and process orphaned speakers
+ orphaned_speaker_ids = get_orphaned_speakers()
+ stats['speakers_evaluated'] = Speaker.query.count()
+
+ if not orphaned_speaker_ids:
+ logger.info("No orphaned speakers found")
+ return stats
+
+ logger.info("Found %d orphaned speaker(s)", len(orphaned_speaker_ids))
+
+ if dry_run:
+ # Report what would be deleted
+ for speaker_id in orphaned_speaker_ids:
+ speaker = Speaker.query.get(speaker_id)
+ if speaker:
+ stats['orphaned_speakers'].append({
+ 'id': speaker.id,
+ 'name': speaker.name,
+ 'user_id': speaker.user_id,
+ 'embedding_count': speaker.embedding_count
+ })
+ logger.info("Dry run: Would delete %d speakers", len(orphaned_speaker_ids))
+ else:
+ # Actually delete orphaned speakers
+ for speaker_id in orphaned_speaker_ids:
+ speaker = Speaker.query.get(speaker_id)
+ if speaker:
+ logger.debug(
+ "Deleting orphaned speaker: id=%d, name='%s', user_id=%d, embedding_count=%d",
+ speaker.id, speaker.name, speaker.user_id, speaker.embedding_count or 0
+ )
+ db.session.delete(speaker)
+ stats['speakers_deleted'] += 1
+
+ # Commit all deletions
+ db.session.commit()
+ logger.info("Speaker cleanup completed: %d speakers deleted", stats['speakers_deleted'])
+
+ # Warning if large number deleted
+ if stats['speakers_deleted'] >= 50:
+ logger.warning(
+ "Large number of speakers deleted (%d). Review cleanup logic if unexpected.",
+ stats['speakers_deleted']
+ )
+
+ return stats
+
+ except Exception as e:
+ db.session.rollback()
+ logger.error("Error during speaker cleanup: %s", str(e), exc_info=True)
+ raise
+
+
+def clean_embeddings_history_references(dry_run=False):
+ """
+ Clean embeddings_history JSON fields to remove references to deleted recordings.
+
+ Scans all speakers' embeddings_history and removes entries where the
+ recording_id no longer exists in the database.
+
+ Args:
+ dry_run (bool): If True, only count what would be cleaned
+
+ Returns:
+ int: Number of embedding references removed
+ """
+ logger.debug("Cleaning embeddings_history references (dry_run=%s)", dry_run)
+
+ references_removed = 0
+
+ try:
+ # Get all speakers with embeddings_history
+ speakers = Speaker.query.filter(Speaker.embeddings_history.isnot(None)).all()
+
+ for speaker in speakers:
+ try:
+ # Parse embeddings_history JSON
+ if not speaker.embeddings_history:
+ continue
+
+ history = speaker.embeddings_history if isinstance(speaker.embeddings_history, list) else json.loads(speaker.embeddings_history)
+
+ if not history or not isinstance(history, list):
+ continue
+
+ # Filter out entries with deleted recording_ids
+ cleaned_history = []
+ for entry in history:
+ if not isinstance(entry, dict) or 'recording_id' not in entry:
+ continue
+
+ recording_id = entry['recording_id']
+
+ # Check if recording still exists
+ recording_exists = db.session.query(
+ exists().where(Recording.id == recording_id)
+ ).scalar()
+
+ if recording_exists:
+ cleaned_history.append(entry)
+ else:
+ references_removed += 1
+ logger.debug(
+ "Removing deleted recording reference: speaker_id=%d, recording_id=%d",
+ speaker.id, recording_id
+ )
+
+ # Update speaker if history changed
+ if len(cleaned_history) < len(history):
+ if not dry_run:
+ speaker.embeddings_history = cleaned_history
+ logger.debug(
+ "Updated speaker %d embeddings_history: %d -> %d entries",
+ speaker.id, len(history), len(cleaned_history)
+ )
+
+ except (json.JSONDecodeError, TypeError, KeyError) as e:
+ logger.warning(
+ "Error processing embeddings_history for speaker %d: %s",
+ speaker.id, str(e)
+ )
+ continue
+
+ if not dry_run and references_removed > 0:
+ db.session.commit()
+ logger.debug("Cleaned %d embedding references", references_removed)
+
+ return references_removed
+
+ except Exception as e:
+ db.session.rollback()
+ logger.error("Error cleaning embeddings_history: %s", str(e), exc_info=True)
+ raise
+
+
+def get_orphaned_speakers(user_id=None):
+ """
+ Get list of speaker IDs that are orphaned (no associated recordings).
+
+ A speaker is orphaned when:
+ - It has no SpeakerSnippet records
+ - After cleaning embeddings_history, it has no valid recording references
+
+ Args:
+ user_id (int, optional): Filter to specific user's speakers
+
+ Returns:
+ list: List of speaker IDs that are orphaned
+ """
+ logger.debug("Finding orphaned speakers (user_id=%s)", user_id)
+
+ # Query for speakers with no snippets
+ query = Speaker.query.filter(
+ ~exists().where(SpeakerSnippet.speaker_id == Speaker.id)
+ )
+
+ if user_id is not None:
+ query = query.filter(Speaker.user_id == user_id)
+
+ speakers_without_snippets = query.all()
+
+ orphaned_ids = []
+
+ for speaker in speakers_without_snippets:
+ # Check if embeddings_history has any valid recording references
+ has_valid_recordings = False
+
+ if speaker.embeddings_history:
+ try:
+ history = speaker.embeddings_history if isinstance(speaker.embeddings_history, list) else json.loads(speaker.embeddings_history)
+
+ if history and isinstance(history, list):
+ for entry in history:
+ if isinstance(entry, dict) and 'recording_id' in entry:
+ recording_id = entry['recording_id']
+
+ # Check if this recording exists
+ recording_exists = db.session.query(
+ exists().where(Recording.id == recording_id)
+ ).scalar()
+
+ if recording_exists:
+ has_valid_recordings = True
+ break
+ except (json.JSONDecodeError, TypeError, KeyError):
+ pass
+
+ # If no snippets AND no valid recording references, it's orphaned
+ if not has_valid_recordings:
+ orphaned_ids.append(speaker.id)
+ logger.debug(
+ "Speaker %d ('%s') is orphaned: no snippets, no valid recordings",
+ speaker.id, speaker.name
+ )
+
+ return orphaned_ids
+
+
+def get_speaker_cleanup_statistics():
+ """
+ Get statistics about speaker data for monitoring.
+
+ Returns:
+ dict: Statistics about speakers
+ {
+ 'total_speakers': int,
+ 'speakers_with_snippets': int,
+ 'speakers_with_embeddings': int,
+ 'potential_orphans': int
+ }
+ """
+ stats = {
+ 'total_speakers': Speaker.query.count(),
+ 'speakers_with_snippets': db.session.query(Speaker.id).join(
+ SpeakerSnippet, Speaker.id == SpeakerSnippet.speaker_id
+ ).distinct().count(),
+ 'speakers_with_embeddings': Speaker.query.filter(
+ Speaker.average_embedding.isnot(None)
+ ).count(),
+ 'potential_orphans': len(get_orphaned_speakers())
+ }
+
+ return stats
diff --git a/src/services/speaker_embedding_matcher.py b/src/services/speaker_embedding_matcher.py
new file mode 100644
index 00000000..74626486
--- /dev/null
+++ b/src/services/speaker_embedding_matcher.py
@@ -0,0 +1,253 @@
+"""
+Speaker Embedding Matcher Service.
+
+This service handles voice embedding comparison and matching for speaker identification.
+It provides functions to:
+- Serialize/deserialize speaker embeddings for database storage
+- Calculate cosine similarity between voice embeddings
+- Find matching speakers based on voice similarity
+- Update speaker profiles with new embeddings
+- Calculate confidence scores for speaker profiles
+
+Uses 256-dimensional embeddings from WhisperX diarization.
+"""
+
+import numpy as np
+from datetime import datetime
+from sklearn.metrics.pairwise import cosine_similarity
+from src.database import db
+from src.models import Speaker
+
+
+def serialize_embedding(embedding_array):
+ """
+ Convert numpy array or list to binary for database storage.
+
+ Args:
+ embedding_array: numpy array or list of floats (256 dimensions)
+
+ Returns:
+ bytes: Binary representation (1,024 bytes for 256 × float32)
+ """
+ return np.array(embedding_array, dtype=np.float32).tobytes()
+
+
+def deserialize_embedding(binary_data):
+ """
+ Convert binary data back to numpy array.
+
+ Args:
+ binary_data: bytes from database (1,024 bytes)
+
+ Returns:
+ numpy.ndarray: 256-dimensional float32 array
+ """
+ return np.frombuffer(binary_data, dtype=np.float32)
+
+
+def calculate_similarity(embedding1, embedding2):
+ """
+ Compute cosine similarity between two 256-dimensional voice embeddings.
+
+ Args:
+ embedding1: numpy array, list, or binary data
+ embedding2: numpy array, list, or binary data
+
+ Returns:
+ float: Similarity score (0-1, where 1 is identical)
+ """
+ # Convert to numpy arrays if needed
+ e1 = np.array(embedding1, dtype=np.float32).reshape(1, -1)
+ e2 = np.array(embedding2, dtype=np.float32).reshape(1, -1)
+
+ # Cosine similarity returns values from -1 to 1
+ # For voice embeddings, we typically see 0.6-0.99 range
+ return float(cosine_similarity(e1, e2)[0][0])
+
+
+def find_matching_speakers(target_embedding, user_id, threshold=0.70):
+ """
+ Find speakers matching a target voice embedding for a specific user.
+
+ Args:
+ target_embedding: The voice embedding to match against (256-dim array/list)
+ user_id: User ID to search within
+ threshold: Minimum similarity score (0-1, default 0.70 = 70%)
+
+ Returns:
+ list: Sorted list of matching speakers with scores
+ [{'speaker_id': 5, 'name': 'John', 'similarity': 85.3, 'confidence': 0.92}, ...]
+ """
+ # Get all speakers with embeddings for this user
+ speakers = Speaker.query.filter_by(user_id=user_id).filter(
+ Speaker.average_embedding.isnot(None)
+ ).all()
+
+ if not speakers:
+ return []
+
+ matches = []
+ for speaker in speakers:
+ try:
+ # Deserialize and compare
+ speaker_emb = deserialize_embedding(speaker.average_embedding)
+ similarity = calculate_similarity(target_embedding, speaker_emb)
+
+ if similarity >= threshold:
+ matches.append({
+ 'speaker_id': speaker.id,
+ 'name': speaker.name,
+ 'similarity': round(similarity * 100, 1), # Convert to percentage
+ 'confidence': speaker.confidence_score or 0.5,
+ 'embedding_count': speaker.embedding_count or 0
+ })
+ except Exception as e:
+ # Skip speakers with corrupted embeddings
+ continue
+
+ # Sort by similarity (highest first)
+ return sorted(matches, key=lambda x: x['similarity'], reverse=True)
+
+
+def update_speaker_embedding(speaker, new_embedding, recording_id):
+ """
+ Update a speaker's average embedding and history with a new sample.
+
+ Uses weighted moving average to update the profile:
+ - New embeddings get 30% weight
+ - Existing average gets 70% weight
+
+ Args:
+ speaker: Speaker model instance
+ new_embedding: New voice embedding (256-dim array/list)
+ recording_id: ID of the recording this embedding came from
+
+ Returns:
+ float: Similarity between new embedding and previous average (None if first)
+ """
+ new_emb_array = np.array(new_embedding, dtype=np.float32)
+ similarity_to_avg = None
+
+ if speaker.average_embedding is None:
+ # First embedding for this speaker
+ speaker.average_embedding = serialize_embedding(new_emb_array)
+ speaker.embedding_count = 1
+ speaker.embeddings_history = [{
+ 'recording_id': recording_id,
+ 'timestamp': datetime.utcnow().isoformat(),
+ 'similarity': 100.0 # Perfect match to itself
+ }]
+ else:
+ # Update existing average
+ current_avg = deserialize_embedding(speaker.average_embedding)
+ similarity_to_avg = calculate_similarity(new_emb_array, current_avg)
+
+ # Weighted average: 30% new, 70% existing
+ # This prevents sudden shifts while still adapting to voice changes
+ weight = 0.3
+ updated_avg = (1 - weight) * current_avg + weight * new_emb_array
+
+ speaker.average_embedding = serialize_embedding(updated_avg)
+ speaker.embedding_count += 1
+
+ # Add to history (keep last 10 entries)
+ history = speaker.embeddings_history or []
+ history.append({
+ 'recording_id': recording_id,
+ 'timestamp': datetime.utcnow().isoformat(),
+ 'similarity': round(similarity_to_avg * 100, 1)
+ })
+ speaker.embeddings_history = history[-10:] # Keep most recent 10
+
+ # Recalculate confidence score
+ speaker.confidence_score = calculate_confidence(speaker)
+
+ # Commit changes
+ db.session.commit()
+
+ return similarity_to_avg
+
+
+def calculate_confidence(speaker):
+ """
+ Calculate confidence score based on embedding consistency.
+
+ Confidence is based on:
+ - Number of samples (more is better)
+ - Consistency of embeddings (high similarity scores = high confidence)
+
+ Args:
+ speaker: Speaker model instance with embeddings_history
+
+ Returns:
+ float: Confidence score (0-1)
+ """
+ if speaker.embedding_count is None or speaker.embedding_count < 1:
+ return 0.0
+
+ if speaker.embedding_count == 1:
+ return 0.5 # Medium confidence with single sample
+
+ # Get recent similarity scores from history
+ history = speaker.embeddings_history or []
+ if len(history) < 2:
+ return 0.5
+
+ # Use last 5 samples
+ recent_history = history[-5:]
+ similarities = [h.get('similarity', 0) / 100.0 for h in recent_history]
+
+ # Average similarity to the profile
+ avg_similarity = sum(similarities) / len(similarities)
+
+ # Penalize if we have very few samples
+ sample_factor = min(1.0, speaker.embedding_count / 5.0)
+
+ # Confidence = average similarity × sample factor
+ confidence = avg_similarity * sample_factor
+
+ return min(1.0, max(0.0, confidence))
+
+
+def get_speaker_voice_profile_summary(speaker):
+ """
+ Get a human-readable summary of a speaker's voice profile.
+
+ Args:
+ speaker: Speaker model instance
+
+ Returns:
+ dict: Profile summary with statistics and status
+ """
+ if not speaker.average_embedding:
+ return {
+ 'has_profile': False,
+ 'message': 'No voice profile yet'
+ }
+
+ return {
+ 'has_profile': True,
+ 'embedding_count': speaker.embedding_count or 0,
+ 'confidence_score': speaker.confidence_score or 0.0,
+ 'confidence_level': _get_confidence_level(speaker.confidence_score),
+ 'last_updated': speaker.embeddings_history[-1]['timestamp'] if speaker.embeddings_history else None,
+ 'recordings': len(speaker.embeddings_history or [])
+ }
+
+
+def _get_confidence_level(score):
+ """
+ Convert numeric confidence score to human-readable level.
+
+ Args:
+ score: float (0-1)
+
+ Returns:
+ str: 'low', 'medium', or 'high'
+ """
+ if score is None or score < 0.6:
+ return 'low'
+ elif score < 0.8:
+ return 'medium'
+ else:
+ return 'high'
diff --git a/src/services/speaker_merge.py b/src/services/speaker_merge.py
new file mode 100644
index 00000000..c5300bc7
--- /dev/null
+++ b/src/services/speaker_merge.py
@@ -0,0 +1,226 @@
+"""
+Speaker Merge Service.
+
+This service handles merging multiple speaker profiles into one.
+Useful when users accidentally create duplicate speakers for the same person.
+
+When speakers are merged:
+- Voice embeddings are combined using weighted average
+- All snippets are transferred to the target speaker
+- Usage statistics are combined
+- Source speakers are deleted
+- Confidence score is recalculated
+"""
+
+import numpy as np
+from src.database import db
+from src.models import Speaker, SpeakerSnippet
+from src.services.speaker_embedding_matcher import (
+ serialize_embedding,
+ deserialize_embedding,
+ calculate_confidence
+)
+
+
+def merge_speakers(target_id, source_ids, user_id):
+ """
+ Merge multiple speaker profiles into one target speaker.
+
+ All embeddings, snippets, and usage data from source speakers are
+ combined into the target speaker. Source speakers are then deleted.
+
+ Args:
+ target_id: ID of the speaker to keep (receives all merged data)
+ source_ids: List of speaker IDs to merge into target
+ user_id: ID of the user (for security check)
+
+ Returns:
+ Speaker: The updated target speaker
+
+ Raises:
+ ValueError: If speakers don't exist or don't belong to user
+ """
+ # Validate target speaker
+ target = Speaker.query.filter_by(id=target_id, user_id=user_id).first()
+ if not target:
+ raise ValueError(f"Target speaker {target_id} not found or doesn't belong to user")
+
+ # Validate source speakers
+ sources = Speaker.query.filter(
+ Speaker.id.in_(source_ids),
+ Speaker.user_id == user_id
+ ).all()
+
+ if len(sources) == 0:
+ raise ValueError("No valid source speakers found")
+
+ if len(sources) != len(source_ids):
+ raise ValueError("Some source speakers don't exist or don't belong to user")
+
+ # Can't merge a speaker with itself
+ if target_id in source_ids:
+ raise ValueError("Cannot merge a speaker with itself")
+
+ # Combine embeddings
+ _combine_embeddings(target, sources)
+
+ # Transfer snippets
+ for source in sources:
+ SpeakerSnippet.query.filter_by(speaker_id=source.id).update(
+ {'speaker_id': target_id}
+ )
+
+ # Combine usage statistics
+ for source in sources:
+ target.use_count += source.use_count
+
+ # Update last_used to most recent
+ if source.last_used and (not target.last_used or source.last_used > target.last_used):
+ target.last_used = source.last_used
+
+ # Combine embedding histories
+ if source.embeddings_history:
+ target_history = target.embeddings_history or []
+ source_history = source.embeddings_history or []
+ combined_history = target_history + source_history
+
+ # Sort by timestamp (most recent last) and keep last 10
+ try:
+ combined_history.sort(key=lambda x: x.get('timestamp', ''))
+ target.embeddings_history = combined_history[-10:]
+ except:
+ # If sorting fails, just concatenate and truncate
+ target.embeddings_history = (target_history + source_history)[-10:]
+
+ # Recalculate confidence score
+ target.confidence_score = calculate_confidence(target)
+
+ # Delete source speakers
+ for source in sources:
+ db.session.delete(source)
+
+ # Commit all changes
+ db.session.commit()
+
+ return target
+
+
+def _combine_embeddings(target, sources):
+ """
+ Combine embeddings from multiple speakers using weighted average.
+
+ Weight is based on embedding_count (more samples = more weight).
+
+ Args:
+ target: Target Speaker instance
+ sources: List of source Speaker instances
+ """
+ all_embeddings = []
+ all_counts = []
+
+ # Add target's embedding if it exists
+ if target.average_embedding:
+ all_embeddings.append(deserialize_embedding(target.average_embedding))
+ all_counts.append(target.embedding_count or 1)
+
+ # Add all source embeddings
+ for source in sources:
+ if source.average_embedding:
+ all_embeddings.append(deserialize_embedding(source.average_embedding))
+ all_counts.append(source.embedding_count or 1)
+
+ if not all_embeddings:
+ # No embeddings to combine
+ return
+
+ # Calculate weighted average
+ total_count = sum(all_counts)
+ weights = [c / total_count for c in all_counts]
+
+ combined_emb = np.average(all_embeddings, axis=0, weights=weights)
+
+ # Update target
+ target.average_embedding = serialize_embedding(combined_emb)
+ target.embedding_count = total_count
+
+
+def preview_merge(target_id, source_ids, user_id):
+ """
+ Preview what a merge would look like without executing it.
+
+ Args:
+ target_id: ID of the target speaker
+ source_ids: List of source speaker IDs
+ user_id: ID of the user
+
+ Returns:
+ dict: Preview of the merge results
+ {
+ 'target_name': '...',
+ 'source_names': [...],
+ 'combined_use_count': 123,
+ 'combined_embedding_count': 45,
+ 'total_snippets': 67
+ }
+ """
+ # Validate speakers
+ target = Speaker.query.filter_by(id=target_id, user_id=user_id).first()
+ if not target:
+ raise ValueError("Target speaker not found")
+
+ sources = Speaker.query.filter(
+ Speaker.id.in_(source_ids),
+ Speaker.user_id == user_id
+ ).all()
+
+ if len(sources) == 0:
+ raise ValueError("No valid source speakers found")
+
+ # Calculate combined statistics
+ combined_use_count = target.use_count
+ combined_embedding_count = target.embedding_count or 0
+ total_snippets = SpeakerSnippet.query.filter_by(speaker_id=target_id).count()
+
+ source_names = []
+ for source in sources:
+ combined_use_count += source.use_count
+ combined_embedding_count += (source.embedding_count or 0)
+ total_snippets += SpeakerSnippet.query.filter_by(speaker_id=source.id).count()
+ source_names.append(source.name)
+
+ return {
+ 'target_name': target.name,
+ 'source_names': source_names,
+ 'combined_use_count': combined_use_count,
+ 'combined_embedding_count': combined_embedding_count,
+ 'total_snippets': total_snippets,
+ 'has_embeddings': target.average_embedding is not None or any(s.average_embedding for s in sources)
+ }
+
+
+def can_merge_speakers(speaker_ids, user_id):
+ """
+ Check if speakers can be merged (all belong to same user, no duplicates).
+
+ Args:
+ speaker_ids: List of speaker IDs
+ user_id: ID of the user
+
+ Returns:
+ tuple: (bool, str) - (can_merge, error_message)
+ """
+ if len(speaker_ids) < 2:
+ return False, "Need at least 2 speakers to merge"
+
+ if len(speaker_ids) != len(set(speaker_ids)):
+ return False, "Duplicate speaker IDs provided"
+
+ speakers = Speaker.query.filter(
+ Speaker.id.in_(speaker_ids),
+ Speaker.user_id == user_id
+ ).all()
+
+ if len(speakers) != len(speaker_ids):
+ return False, "Some speakers don't exist or don't belong to user"
+
+ return True, ""
diff --git a/src/services/speaker_snippets.py b/src/services/speaker_snippets.py
new file mode 100644
index 00000000..3196f2e9
--- /dev/null
+++ b/src/services/speaker_snippets.py
@@ -0,0 +1,334 @@
+"""
+Speaker Snippets Service.
+
+This service handles the extraction and management of representative speech snippets
+from recordings. Snippets provide context when viewing speaker profiles and help
+users verify speaker identifications.
+
+Key functions:
+- Extract snippets when speakers are identified in recordings
+- Retrieve snippets for display in speaker profiles
+- Clean up old snippets to prevent database bloat
+"""
+
+import json
+from src.database import db
+from src.models import Speaker, SpeakerSnippet, Recording
+
+
+def create_speaker_snippets(recording_id, speaker_map):
+ """
+ Extract and store representative snippets for each identified speaker.
+
+ This function is called after a user saves speaker identifications in a recording.
+ It extracts 3-5 representative quotes per speaker for display in speaker profiles.
+
+ Args:
+ recording_id: ID of the recording
+ speaker_map: Dict mapping SPEAKER_XX to speaker info
+ {'SPEAKER_00': {'name': 'John Doe', 'isMe': False}, ...}
+
+ Returns:
+ int: Number of snippets created
+ """
+ recording = Recording.query.get(recording_id)
+ if not recording or not recording.transcription:
+ return 0
+
+ try:
+ transcript = json.loads(recording.transcription)
+ except (json.JSONDecodeError, TypeError):
+ return 0
+
+ snippets_created = 0
+
+ for segment_idx, segment in enumerate(transcript):
+ speaker_label = segment.get('speaker') # SPEAKER_00, SPEAKER_01, etc.
+
+ if not speaker_label or speaker_label not in speaker_map:
+ continue
+
+ speaker_info = speaker_map[speaker_label]
+ speaker_name = speaker_info.get('name')
+
+ if not speaker_name or speaker_name.startswith('SPEAKER_'):
+ # Skip if not actually identified
+ continue
+
+ # Find the speaker in database
+ speaker = Speaker.query.filter_by(
+ user_id=recording.user_id,
+ name=speaker_name
+ ).first()
+
+ if not speaker:
+ continue
+
+ # Limit to 5 snippets per recording per speaker
+ existing_count = SpeakerSnippet.query.filter_by(
+ speaker_id=speaker.id,
+ recording_id=recording_id
+ ).count()
+
+ if existing_count >= 5:
+ continue
+
+ # Get the text (limit to 200 chars)
+ text = segment.get('sentence', '').strip()
+ if len(text) < 10: # Skip very short segments
+ continue
+
+ text_snippet = text[:200]
+
+ # Create snippet
+ snippet = SpeakerSnippet(
+ speaker_id=speaker.id,
+ recording_id=recording_id,
+ segment_index=segment_idx,
+ text_snippet=text_snippet,
+ timestamp=segment.get('start_time')
+ )
+ db.session.add(snippet)
+ snippets_created += 1
+
+ if snippets_created > 0:
+ db.session.commit()
+
+ return snippets_created
+
+
+def _generate_dynamic_snippets(speaker_id, limit=3):
+ """
+ Dynamically generate audio snippets from a speaker's recent recordings.
+
+ This function finds short audio segments (3-4 seconds) from recent recordings
+ where the speaker appears. These can be played back to verify speaker identity.
+
+ Args:
+ speaker_id: ID of the speaker
+ limit: Maximum number of snippets to return (default 3)
+
+ Returns:
+ list: List of snippet dictionaries with audio segment information
+ [{'recording_id': 123, 'start_time': 45.2, 'duration': 3.5, ...}, ...]
+ """
+ # Get the speaker
+ speaker = Speaker.query.get(speaker_id)
+ if not speaker:
+ return []
+
+ # Find recordings that have this speaker's name in transcription
+ # We'll look at the last 10 recordings and extract snippets from them
+ recordings = Recording.query.filter_by(user_id=speaker.user_id)\
+ .filter(Recording.transcription.isnot(None))\
+ .filter(Recording.transcription != '')\
+ .filter(Recording.audio_deleted_at.is_(None))\
+ .order_by(Recording.created_at.desc())\
+ .limit(10).all()
+
+ snippets = []
+
+ for recording in recordings:
+ if len(snippets) >= limit:
+ break
+
+ try:
+ # Parse transcription JSON
+ transcript = json.loads(recording.transcription)
+
+ if not isinstance(transcript, list):
+ continue
+
+ # Find segments where this speaker appears
+ speaker_segments = []
+ for idx, segment in enumerate(transcript):
+ # Check if segment has speaker identification matching our speaker's name
+ speaker_label = segment.get('speaker')
+
+ # In identified transcripts, the speaker field contains the actual name
+ if speaker_label != speaker.name:
+ continue
+
+ start_time = segment.get('start_time')
+ end_time = segment.get('end_time')
+
+ if start_time is None or end_time is None:
+ continue
+
+ duration = end_time - start_time
+
+ # Skip very short segments (less than 2 seconds)
+ if duration < 2.0:
+ continue
+
+ speaker_segments.append({
+ 'index': idx,
+ 'start_time': start_time,
+ 'end_time': end_time,
+ 'duration': duration,
+ 'text': segment.get('sentence', '').strip()[:100] # Preview text
+ })
+
+ if not speaker_segments:
+ continue
+
+ # Take snippets from middle portions (skip first and last 10%)
+ total_segments = len(speaker_segments)
+ if total_segments > 4:
+ # Skip first and last 10%
+ start_idx = max(1, int(total_segments * 0.1))
+ end_idx = min(total_segments - 1, int(total_segments * 0.9))
+ middle_segments = speaker_segments[start_idx:end_idx]
+ else:
+ middle_segments = speaker_segments
+
+ # Take 1 snippet per recording from the middle
+ if middle_segments:
+ # Pick a segment from the middle
+ middle_idx = len(middle_segments) // 2
+ segment = middle_segments[middle_idx]
+
+ # Limit audio snippet to 3-4 seconds
+ snippet_duration = min(4.0, segment['duration'])
+
+ snippets.append({
+ 'id': None, # Dynamic snippet, no database ID
+ 'speaker_id': speaker_id,
+ 'recording_id': recording.id,
+ 'start_time': segment['start_time'],
+ 'duration': snippet_duration,
+ 'text': segment['text'], # Preview text for context
+ 'recording_title': recording.title or 'Untitled Recording',
+ 'created_at': recording.created_at.isoformat() if recording.created_at else None
+ })
+
+ except (json.JSONDecodeError, TypeError, KeyError) as e:
+ # Skip recordings with invalid transcription format
+ continue
+
+ return snippets
+
+
+def get_speaker_snippets(speaker_id, limit=3):
+ """
+ Get recent audio snippets for a speaker.
+
+ Returns short audio segments (3-4 seconds) from recent recordings where this
+ speaker appears. These audio snippets can be played to verify speaker identity.
+
+ Args:
+ speaker_id: ID of the speaker
+ limit: Maximum number of snippets to return (default 3)
+
+ Returns:
+ list: List of snippet dictionaries with audio segment information
+ [{'recording_id': 123, 'start_time': 45.2, 'duration': 3.5, ...}, ...]
+ """
+ # Always dynamically generate audio snippets from recent recordings
+ return _generate_dynamic_snippets(speaker_id, limit)
+
+
+def get_snippets_by_recording(recording_id, speaker_id):
+ """
+ Get all snippets for a specific speaker in a specific recording.
+
+ Args:
+ recording_id: ID of the recording
+ speaker_id: ID of the speaker
+
+ Returns:
+ list: List of snippet dictionaries
+ """
+ snippets = SpeakerSnippet.query.filter_by(
+ recording_id=recording_id,
+ speaker_id=speaker_id
+ ).order_by(SpeakerSnippet.segment_index).all()
+
+ return [snippet.to_dict() for snippet in snippets]
+
+
+def cleanup_old_snippets(speaker_id, keep=10):
+ """
+ Clean up old snippets for a speaker, keeping only the most recent ones.
+
+ Args:
+ speaker_id: ID of the speaker
+ keep: Number of snippets to keep (default 10)
+
+ Returns:
+ int: Number of snippets deleted
+ """
+ # Get all snippets for this speaker, ordered by creation date
+ all_snippets = SpeakerSnippet.query.filter_by(speaker_id=speaker_id)\
+ .order_by(SpeakerSnippet.created_at.desc()).all()
+
+ if len(all_snippets) <= keep:
+ return 0
+
+ # Delete old snippets beyond the keep limit
+ snippets_to_delete = all_snippets[keep:]
+ deleted_count = 0
+
+ for snippet in snippets_to_delete:
+ db.session.delete(snippet)
+ deleted_count += 1
+
+ if deleted_count > 0:
+ db.session.commit()
+
+ return deleted_count
+
+
+def delete_snippets_for_recording(recording_id):
+ """
+ Delete all snippets associated with a recording.
+
+ This is typically called when a recording is deleted or reprocessed.
+
+ Args:
+ recording_id: ID of the recording
+
+ Returns:
+ int: Number of snippets deleted
+ """
+ deleted_count = SpeakerSnippet.query.filter_by(recording_id=recording_id).delete()
+ db.session.commit()
+ return deleted_count
+
+
+def get_speaker_recordings_with_snippets(speaker_id):
+ """
+ Get a list of recordings that have snippets for this speaker.
+
+ Args:
+ speaker_id: ID of the speaker
+
+ Returns:
+ list: List of recording dictionaries with snippet counts
+ [{'id': 123, 'title': '...', 'snippet_count': 3, 'date': '...'}, ...]
+ """
+ # Get distinct recordings with snippet counts
+ from sqlalchemy import func
+
+ recordings_with_counts = db.session.query(
+ Recording.id,
+ Recording.title,
+ Recording.created_at,
+ func.count(SpeakerSnippet.id).label('snippet_count')
+ ).join(
+ SpeakerSnippet,
+ Recording.id == SpeakerSnippet.recording_id
+ ).filter(
+ SpeakerSnippet.speaker_id == speaker_id
+ ).group_by(
+ Recording.id
+ ).order_by(
+ Recording.created_at.desc()
+ ).all()
+
+ return [{
+ 'id': r.id,
+ 'title': r.title,
+ 'snippet_count': r.snippet_count,
+ 'created_at': r.created_at.isoformat() if r.created_at else None
+ } for r in recordings_with_counts]
diff --git a/src/tasks/__init__.py b/src/tasks/__init__.py
new file mode 100644
index 00000000..4e52fbbe
--- /dev/null
+++ b/src/tasks/__init__.py
@@ -0,0 +1,25 @@
+"""
+Background task functions for asynchronous processing.
+"""
+
+from .processing import (
+ generate_title_task,
+ generate_summary_only_task,
+ extract_events_from_transcript,
+ extract_audio_from_video,
+ transcribe_audio_asr,
+ transcribe_audio_task,
+ transcribe_single_file,
+ transcribe_with_chunking
+)
+
+__all__ = [
+ 'generate_title_task',
+ 'generate_summary_only_task',
+ 'extract_events_from_transcript',
+ 'extract_audio_from_video',
+ 'transcribe_audio_asr',
+ 'transcribe_audio_task',
+ 'transcribe_single_file',
+ 'transcribe_with_chunking',
+]
diff --git a/src/tasks/processing.py b/src/tasks/processing.py
new file mode 100644
index 00000000..8623ed3c
--- /dev/null
+++ b/src/tasks/processing.py
@@ -0,0 +1,1661 @@
+"""
+Background task functions for audio processing, transcription, and summarization.
+
+These functions handle asynchronous processing tasks:
+- Audio transcription (Whisper API and custom ASR endpoints)
+- Title and summary generation
+- Event extraction from transcripts
+- Audio/video format conversion
+"""
+
+import os
+import re
+import json
+import time
+import mimetypes
+import tempfile
+import subprocess
+import httpx
+from datetime import datetime
+from flask import current_app
+
+from src.database import db
+from src.models import Recording, Tag, Event, TranscriptChunk, SystemSetting, GroupMembership, RecordingTag, InternalShare, SharedRecordingState, User
+from src.services.embeddings import process_recording_chunks
+from src.services.llm import is_using_openai_api, call_llm_completion, format_api_error_message, TEXT_MODEL_NAME, client, http_client_no_proxy
+from src.utils import extract_json_object, safe_json_loads
+from src.audio_chunking import AudioChunkingService, ChunkProcessingError, ChunkingNotSupportedError
+from src.config.app_config import ASR_DIARIZE, ASR_BASE_URL, transcription_api_key, transcription_base_url
+from src.file_exporter import export_recording, ENABLE_AUTO_EXPORT
+
+# Configuration for internal sharing
+ENABLE_INTERNAL_SHARING = os.environ.get('ENABLE_INTERNAL_SHARING', 'false').lower() == 'true'
+
+
+def apply_team_tag_auto_shares(recording_id):
+ """
+ Apply auto-shares for all group tags on a recording after processing completes.
+
+ This function should be called after a recording status changes to COMPLETED.
+ It creates InternalShare records for team members based on group tag settings.
+
+ Args:
+ recording_id: ID of the recording to apply auto-shares for
+ """
+ if not ENABLE_INTERNAL_SHARING:
+ return
+
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ return
+
+ # Get all group tags on this recording with auto-share enabled
+ group_tags = db.session.query(Tag).join(
+ RecordingTag, RecordingTag.tag_id == Tag.id
+ ).filter(
+ RecordingTag.recording_id == recording_id,
+ Tag.group_id.isnot(None),
+ db.or_(Tag.auto_share_on_apply == True, Tag.share_with_group_lead == True)
+ ).all()
+
+ if not group_tags:
+ return
+
+ shares_created = 0
+
+ for tag in group_tags:
+ # Determine who to share with
+ if tag.auto_share_on_apply:
+ group_members = GroupMembership.query.filter_by(group_id=tag.group_id).all()
+ elif tag.share_with_group_lead:
+ group_members = GroupMembership.query.filter_by(group_id=tag.group_id, role='admin').all()
+ else:
+ continue
+
+ for membership in group_members:
+ # Skip the recording owner
+ if membership.user_id == recording.user_id:
+ continue
+
+ # Check if already shared
+ existing_share = InternalShare.query.filter_by(
+ recording_id=recording_id,
+ shared_with_user_id=membership.user_id
+ ).first()
+
+ if not existing_share:
+ # Create internal share with correct permissions
+ # Group admins get edit permission, regular members get read-only
+ share = InternalShare(
+ recording_id=recording_id,
+ owner_id=recording.user_id,
+ shared_with_user_id=membership.user_id,
+ can_edit=(membership.role == 'admin'),
+ can_reshare=False,
+ source_type='group_tag',
+ source_tag_id=tag.id
+ )
+ db.session.add(share)
+
+ # Create SharedRecordingState with default values for the recipient
+ state = SharedRecordingState(
+ recording_id=recording_id,
+ user_id=membership.user_id,
+ is_inbox=True, # New shares appear in inbox by default
+ is_highlighted=False # Not favorited by default
+ )
+ db.session.add(state)
+
+ shares_created += 1
+ current_app.logger.info(f"Auto-shared recording {recording_id} with user {membership.user_id} (role={membership.role}) via group tag '{tag.name}'")
+
+ if shares_created > 0:
+ db.session.commit()
+ current_app.logger.info(f"Created {shares_created} auto-shares for recording {recording_id} after processing completed")
+
+
+def format_transcription_for_llm(transcription_text):
+ """
+ Formats transcription for LLM. If it's our simplified JSON, convert it to plain text.
+ Otherwise, return as is.
+ """
+ try:
+ transcription_data = json.loads(transcription_text)
+ if isinstance(transcription_data, list):
+ # It's our simplified JSON format
+ formatted_lines = []
+ for segment in transcription_data:
+ speaker = segment.get('speaker', 'Unknown Speaker')
+ sentence = segment.get('sentence', '')
+ formatted_lines.append(f"[{speaker}]: {sentence}")
+ return "\n".join(formatted_lines)
+ except (json.JSONDecodeError, TypeError):
+ # Not a JSON, or not the format we expect, so return as is.
+ pass
+ return transcription_text
+
+
+def clean_llm_response(text):
+ """
+ Clean LLM responses by removing thinking tags and excessive whitespace.
+ This handles responses from reasoning models that include <think> tags.
+ """
+ if not text:
+ return ""
+
+ # Remove thinking tags and their content
+ # Handle both <think> and <thinking> tags with various closing formats
+ cleaned = re.sub(r'<think(?:ing)?>.*?</think(?:ing)?>', '', text, flags=re.DOTALL | re.IGNORECASE)
+
+ # Also handle unclosed thinking tags (in case the model doesn't close them)
+ cleaned = re.sub(r'<think(?:ing)?>.*$', '', cleaned, flags=re.DOTALL | re.IGNORECASE)
+
+ # Remove any remaining XML-like tags that might be related to thinking
+ # but preserve markdown formatting
+ cleaned = re.sub(r'<(?!/?(?:code|pre|blockquote|p|br|hr|ul|ol|li|h[1-6]|em|strong|b|i|a|img)(?:\s|>|/))[^>]+>', '', cleaned)
+
+ # Clean up excessive whitespace while preserving intentional formatting
+ # Remove leading/trailing whitespace from each line
+ lines = cleaned.split('\n')
+ cleaned_lines = []
+ for line in lines:
+ # Preserve lines that are part of code blocks or lists
+ if line.strip() or (len(cleaned_lines) > 0 and cleaned_lines[-1].strip().startswith(('```', '-', '*', '1.', '2.', '3.', '4.', '5.', '6.', '7.', '8.', '9.'))):
+ cleaned_lines.append(line.rstrip())
+
+ # Join lines and remove multiple consecutive blank lines
+ cleaned = '\n'.join(cleaned_lines)
+ cleaned = re.sub(r'\n{3,}', '\n\n', cleaned)
+
+ # Final strip to remove leading/trailing whitespace
+ return cleaned.strip()
+
+# Configuration from environment
+USE_ASR_ENDPOINT = os.environ.get('USE_ASR_ENDPOINT', 'false').lower() == 'true'
+ASR_ENDPOINT = os.environ.get('ASR_ENDPOINT', '')
+ASR_API_KEY = os.environ.get('ASR_API_KEY', '')
+OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY')
+ENABLE_INQUIRE_MODE = os.environ.get('ENABLE_INQUIRE_MODE', 'false').lower() == 'true'
+ENABLE_CHUNKING = os.environ.get('ENABLE_CHUNKING', 'true').lower() == 'true'
+
+# Chunking service will be passed in from app
+chunking_service = None
+
+# Import OpenAI client
+from openai import OpenAI
+
+if USE_ASR_ENDPOINT:
+ asr_client = OpenAI(base_url=ASR_ENDPOINT, api_key=ASR_API_KEY)
+else:
+ asr_client = OpenAI(api_key=OPENAI_API_KEY)
+
+
+def generate_title_task(app_context, recording_id, will_auto_summarize=False):
+ """Generates only a title for a recording based on transcription.
+
+ Args:
+ app_context: Flask app context
+ recording_id: ID of the recording
+ will_auto_summarize: If True, don't set status to COMPLETED (summary task will do it)
+ """
+ with app_context:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ current_app.logger.error(f"Error: Recording {recording_id} not found for title generation.")
+ return
+
+ if client is None:
+ current_app.logger.warning(f"Skipping title generation for {recording_id}: OpenRouter client not configured.")
+ # Only mark as completed if auto-summarization won't happen next
+ if not will_auto_summarize:
+ recording.status = 'COMPLETED'
+ recording.completed_at = datetime.utcnow()
+ db.session.commit()
+ return
+
+ if not recording.transcription or len(recording.transcription.strip()) < 10:
+ current_app.logger.warning(f"Transcription for recording {recording_id} is too short or empty. Skipping title generation.")
+ # Only mark as completed if auto-summarization won't happen next
+ if not will_auto_summarize:
+ recording.status = 'COMPLETED'
+ recording.completed_at = datetime.utcnow()
+ db.session.commit()
+ return
+
+ # Get configurable transcript length limit and format transcription for LLM
+ transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)
+ if transcript_limit == -1:
+ raw_transcription = recording.transcription
+ else:
+ raw_transcription = recording.transcription[:transcript_limit]
+
+ # Convert ASR JSON to clean text format
+ transcript_text = format_transcription_for_llm(raw_transcription)
+
+
+ # Get user language preference
+ user_output_language = None
+ if recording.owner:
+ user_output_language = recording.owner.output_language
+
+ language_directive = f"Please provide the title in {user_output_language}." if user_output_language else ""
+
+ prompt_text = f"""Create a short title for this conversation:
+
+{transcript_text}
+
+Requirements:
+- Maximum 8 words
+- No phrases like "Discussion about" or "Meeting on"
+- Just the main topic
+
+{language_directive}
+
+Title:"""
+
+ system_message_content = "You are an AI assistant that generates concise titles for audio transcriptions. Respond only with the title."
+ if user_output_language:
+ system_message_content += f" Ensure your response is in {user_output_language}."
+
+ try:
+ completion = call_llm_completion(
+ messages=[
+ {"role": "system", "content": system_message_content},
+ {"role": "user", "content": prompt_text}
+ ],
+ temperature=0.7,
+ max_tokens=5000
+ )
+
+ raw_response = completion.choices[0].message.content
+ reasoning = getattr(completion.choices[0].message, 'reasoning', None)
+
+ # Use reasoning content if main content is empty (fallback for reasoning models)
+ if not raw_response and reasoning:
+ current_app.logger.info(f"Title generation for recording {recording_id}: Using reasoning field as fallback")
+ # Try to extract a title from the reasoning field
+ lines = reasoning.strip().split('\n')
+ # Look for the last line that might be the title
+ for line in reversed(lines):
+ line = line.strip()
+ if line and not line.startswith('I') and len(line.split()) <= 8:
+ raw_response = line
+ break
+
+ title = clean_llm_response(raw_response) if raw_response else ""
+
+ if title:
+ recording.title = title
+ current_app.logger.info(f"Title generated for recording {recording_id}: {title}")
+ else:
+ current_app.logger.warning(f"Empty title generated for recording {recording_id}")
+
+ except Exception as e:
+ current_app.logger.error(f"Error generating title for recording {recording_id}: {str(e)}")
+ current_app.logger.error(f"Exception details:", exc_info=True)
+
+ # Only set status to COMPLETED if auto-summarization won't happen next
+ # If auto-summarization is enabled, the summary task will set COMPLETED
+ if not will_auto_summarize:
+ recording.status = 'COMPLETED'
+ recording.completed_at = datetime.utcnow()
+ db.session.commit()
+ current_app.logger.info(f"Title generation complete, status set to COMPLETED for recording {recording_id}")
+
+ # 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:
+ current_app.logger.error(f"Error processing chunks for completed recording {recording_id}: {e}")
+ else:
+ # Just commit the title without changing status
+ db.session.commit()
+ current_app.logger.info(f"Title generation complete, leaving status unchanged (auto-summarization will follow) for recording {recording_id}")
+
+
+def generate_summary_only_task(app_context, recording_id, custom_prompt_override=None, user_id=None):
+ """Generates only a summary for a recording (no title, no JSON response).
+
+ Args:
+ app_context: Flask app context
+ recording_id: ID of the recording
+ custom_prompt_override: Optional custom prompt that overrides all other prompts (for reprocessing)
+ user_id: Optional user ID to filter tag visibility (defaults to recording owner)
+ """
+ with app_context:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ current_app.logger.error(f"Error: Recording {recording_id} not found for summary generation.")
+ return
+
+ if client is None:
+ current_app.logger.warning(f"Skipping summary generation for {recording_id}: OpenRouter client not configured.")
+ recording.summary = "[Summary skipped: OpenRouter client not configured]"
+ db.session.commit()
+ return
+
+ recording.status = 'SUMMARIZING'
+ summarization_start_time = time.time()
+ db.session.commit()
+
+ current_app.logger.info(f"Requesting summary from OpenRouter for recording {recording_id} using model {TEXT_MODEL_NAME}...")
+
+ if not recording.transcription or len(recording.transcription.strip()) < 10:
+ current_app.logger.warning(f"Transcription for recording {recording_id} is too short or empty. Skipping summarization.")
+ recording.summary = "[Summary skipped due to short transcription]"
+ recording.status = 'COMPLETED'
+ db.session.commit()
+ return
+
+ # Get user preferences and tag custom prompts
+ user_summary_prompt = None
+ user_output_language = None
+ tag_custom_prompt = None
+
+ # Determine which user's perspective to use for tag visibility
+ # If user_id is provided (e.g., from reprocess), use that user
+ # Otherwise default to the recording owner
+ viewer_user = None
+ if user_id:
+ viewer_user = db.session.get(User, user_id)
+ if viewer_user:
+ current_app.logger.info(f"Using user {viewer_user.username} (ID: {user_id}) for tag visibility filtering")
+ else:
+ current_app.logger.warning(f"User ID {user_id} not found, falling back to recording owner")
+ viewer_user = recording.owner
+ else:
+ viewer_user = recording.owner
+ if viewer_user:
+ current_app.logger.info(f"Using recording owner {viewer_user.username} for tag visibility filtering")
+
+ # Collect custom prompts from tags visible to the viewer user
+ tag_custom_prompts = []
+ if viewer_user:
+ visible_tags = recording.get_visible_tags(viewer_user)
+ if visible_tags:
+ current_app.logger.info(f"Found {len(visible_tags)} visible tags for user {viewer_user.username} on recording {recording_id}")
+ # Tags are ordered by the order they were added to this recording
+ for tag in visible_tags:
+ if tag.custom_prompt and tag.custom_prompt.strip():
+ tag_custom_prompts.append({
+ 'name': tag.name,
+ 'prompt': tag.custom_prompt.strip()
+ })
+ current_app.logger.info(f"Found custom prompt from tag '{tag.name}' for recording {recording_id}")
+ else:
+ current_app.logger.warning(f"No viewer user available for tag filtering on recording {recording_id}")
+
+ # Create merged prompt if we have multiple tag prompts
+ if tag_custom_prompts:
+ if len(tag_custom_prompts) == 1:
+ tag_custom_prompt = tag_custom_prompts[0]['prompt']
+ current_app.logger.info(f"Using single custom prompt from tag '{tag_custom_prompts[0]['name']}' for recording {recording_id}")
+ else:
+ # Merge multiple prompts seamlessly as unified instructions
+ merged_parts = []
+ for tag_prompt in tag_custom_prompts:
+ merged_parts.append(tag_prompt['prompt'])
+ tag_custom_prompt = "\n\n".join(merged_parts)
+ tag_names = [tp['name'] for tp in tag_custom_prompts]
+ current_app.logger.info(f"Combined custom prompts from {len(tag_custom_prompts)} tags in order added ({', '.join(tag_names)}) for recording {recording_id}")
+ else:
+ tag_custom_prompt = None
+
+ if recording.owner:
+ user_summary_prompt = recording.owner.summary_prompt
+ user_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 limit
+ transcript_limit = SystemSetting.get_setting('transcript_length_limit', 30000)
+ if transcript_limit == -1:
+ transcript_text = formatted_transcription
+ else:
+ transcript_text = formatted_transcription[:transcript_limit]
+
+ language_directive = f"IMPORTANT: You MUST provide the summary in {user_output_language}. The entire response must be in {user_output_language}." if user_output_language else ""
+
+ # Determine which summarization instructions to use
+ # Priority order: custom_prompt_override > tag custom prompt > user summary prompt > admin default prompt > hardcoded fallback
+ summarization_instructions = ""
+ if custom_prompt_override:
+ current_app.logger.info(f"Using custom prompt override for recording {recording_id} (length: {len(custom_prompt_override)})")
+ summarization_instructions = custom_prompt_override
+ elif tag_custom_prompt:
+ current_app.logger.info(f"Using tag custom prompt for recording {recording_id}")
+ summarization_instructions = tag_custom_prompt
+ elif user_summary_prompt:
+ current_app.logger.info(f"Using user custom prompt for recording {recording_id}")
+ summarization_instructions = user_summary_prompt
+ else:
+ # Get admin default prompt from system settings
+ admin_default_prompt = SystemSetting.get_setting('admin_default_summary_prompt', None)
+ if admin_default_prompt:
+ current_app.logger.info(f"Using admin default prompt for recording {recording_id}")
+ summarization_instructions = admin_default_prompt
+ else:
+ # Fallback to hardcoded default if admin hasn't set one
+ summarization_instructions = """Generate a comprehensive summary that includes the following sections:
+- **Key Issues Discussed**: A bulleted list of the main topics
+- **Key Decisions Made**: A bulleted list of any decisions reached
+- **Action Items**: A bulleted list of tasks assigned, including who is responsible if mentioned"""
+ current_app.logger.info(f"Using hardcoded default prompt for recording {recording_id}")
+
+ # Build context information
+ current_date = datetime.now().strftime("%B %d, %Y")
+ context_parts = []
+ context_parts.append(f"Current date: {current_date}")
+
+ # Add selected tags information (only visible tags)
+ if viewer_user:
+ visible_tags = recording.get_visible_tags(viewer_user)
+ if visible_tags:
+ tag_names = [tag.name for tag in visible_tags]
+ context_parts.append(f"Tags applied to this transcript by the user: {', '.join(tag_names)}")
+
+ # Add user profile information if available
+ if recording.owner:
+ user_context_parts = []
+ if recording.owner.name:
+ user_context_parts.append(f"Name: {recording.owner.name}")
+ if recording.owner.job_title:
+ user_context_parts.append(f"Job title: {recording.owner.job_title}")
+ if recording.owner.company:
+ user_context_parts.append(f"Company: {recording.owner.company}")
+
+ if user_context_parts:
+ context_parts.append(f"Information about the user: {', '.join(user_context_parts)}")
+
+ context_section = "Context:\n" + "\n".join(f"- {part}" for part in context_parts)
+
+ # Build SYSTEM message: Initial instructions + Context + Language
+ system_message_content = "You are an AI assistant that generates comprehensive summaries for meeting transcripts. Respond only with the summary in Markdown format. Do NOT use markdown code blocks (```markdown). Provide raw markdown content directly."
+ system_message_content += f"\n\n{context_section}"
+ if user_output_language:
+ system_message_content += f"\n\nLanguage Requirement: You MUST generate the entire summary in {user_output_language}. This is mandatory."
+
+ # Build USER message: Transcription + Summarization Instructions + Language Directive
+ prompt_text = f"""Transcription:
+\"\"\"
+{transcript_text}
+\"\"\"
+
+Summarization Instructions:
+{summarization_instructions}
+
+{language_directive}"""
+
+ # Debug logging: Log the complete prompt being sent to the LLM
+ current_app.logger.info(f"Sending summarization prompt to LLM (length: {len(prompt_text)} chars). Set LOG_LEVEL=DEBUG to see full prompt details.")
+ current_app.logger.debug(f"=== SUMMARIZATION DEBUG for recording {recording_id} ===")
+ current_app.logger.debug(f"System message: {system_message_content}")
+ current_app.logger.debug(f"User prompt (length: {len(prompt_text)} chars):\n{prompt_text}")
+ current_app.logger.debug(f"=== END SUMMARIZATION DEBUG for recording {recording_id} ===")
+
+ try:
+ completion = call_llm_completion(
+ messages=[
+ {"role": "system", "content": system_message_content},
+ {"role": "user", "content": prompt_text}
+ ],
+ temperature=0.5,
+ max_tokens=int(os.environ.get("SUMMARY_MAX_TOKENS", "3000"))
+ )
+
+ raw_response = completion.choices[0].message.content
+ current_app.logger.info(f"Raw LLM response for recording {recording_id}: '{raw_response}'")
+
+ summary = clean_llm_response(raw_response) if raw_response else ""
+ current_app.logger.info(f"Processed summary length for recording {recording_id}: {len(summary)} characters")
+
+ if summary:
+ recording.summary = summary
+ db.session.commit()
+ current_app.logger.info(f"Summary generated successfully for recording {recording_id}")
+
+ # Extract events if enabled for this user BEFORE marking as completed
+ if recording.owner and recording.owner.extract_events:
+ extract_events_from_transcript(recording_id, formatted_transcription, summary)
+
+ # Mark as completed AFTER event extraction
+ recording.status = 'COMPLETED'
+ recording.completed_at = datetime.utcnow()
+ # Calculate and save summarization duration
+ summarization_end_time = time.time()
+ recording.summarization_duration_seconds = int(summarization_end_time - summarization_start_time)
+ db.session.commit()
+ current_app.logger.info(f"Summarization completed for recording {recording_id} in {recording.summarization_duration_seconds}s.")
+
+ # Apply auto-shares for group tags after processing completes
+ apply_team_tag_auto_shares(recording_id)
+
+ # Export to file if auto-export is enabled
+ if ENABLE_AUTO_EXPORT:
+ export_recording(recording_id)
+ else:
+ current_app.logger.warning(f"Empty summary generated for recording {recording_id}")
+ recording.summary = "[Summary not generated]"
+ recording.status = 'COMPLETED'
+ # Calculate and save summarization duration even for empty summary
+ summarization_end_time = time.time()
+ recording.summarization_duration_seconds = int(summarization_end_time - summarization_start_time)
+ db.session.commit()
+
+ # Apply auto-shares for group tags after processing completes
+ apply_team_tag_auto_shares(recording_id)
+
+ # Export to file if auto-export is enabled (even with empty summary, transcription may be useful)
+ if ENABLE_AUTO_EXPORT:
+ export_recording(recording_id)
+
+ except Exception as e:
+ error_msg = format_api_error_message(str(e))
+ current_app.logger.error(f"Error generating summary for recording {recording_id}: {str(e)}")
+ recording.summary = error_msg
+ recording.status = 'FAILED'
+ db.session.commit()
+
+
+def extract_events_from_transcript(recording_id, transcript_text, summary_text):
+ """Extract calendar events from transcript using LLM.
+
+ Args:
+ recording_id: ID of the recording
+ transcript_text: The formatted transcript text
+ summary_text: The generated summary text
+ """
+ try:
+ recording = db.session.get(Recording, recording_id)
+ if not recording or not recording.owner or not recording.owner.extract_events:
+ return # Event extraction not enabled for this user
+
+ current_app.logger.info(f"Extracting events for recording {recording_id}")
+
+ # Get user language preference
+ user_output_language = None
+ if recording.owner:
+ user_output_language = recording.owner.output_language
+
+ # Build comprehensive context information
+ current_date = datetime.now()
+ context_parts = []
+
+ # CRITICAL: Determine the reference date for relative date calculations
+ reference_date = None
+ reference_date_source = ""
+
+ if recording.meeting_date:
+ # Prefer meeting date if available
+ reference_date = recording.meeting_date
+ reference_date_source = "Meeting Date"
+ context_parts.append(f"**MEETING DATE (use this for relative date calculations): {recording.meeting_date.strftime('%A, %B %d, %Y')}**")
+ elif recording.created_at:
+ # Fall back to upload date
+ reference_date = recording.created_at.date()
+ reference_date_source = "Upload Date (no meeting date available)"
+ context_parts.append(f"**REFERENCE DATE (use this for relative date calculations): {recording.created_at.strftime('%A, %B %d, %Y')}**")
+
+ context_parts.append(f"Today's actual date: {current_date.strftime('%A, %B %d, %Y')}")
+ context_parts.append(f"Current time: {current_date.strftime('%I:%M %p')}")
+
+ # Add additional recording context
+ if recording.created_at:
+ context_parts.append(f"Recording uploaded on: {recording.created_at.strftime('%B %d, %Y at %I:%M %p')}")
+ if recording.meeting_date and reference_date_source == "Meeting Date":
+ # Calculate days between meeting and today for context
+ # Ensure both sides are date objects (meeting_date might be datetime or date)
+ meeting_date_obj = recording.meeting_date.date() if isinstance(recording.meeting_date, datetime) else recording.meeting_date
+ days_since = (current_date.date() - meeting_date_obj).days
+ if days_since == 0:
+ context_parts.append("This meeting happened today")
+ elif days_since == 1:
+ context_parts.append("This meeting happened yesterday")
+ else:
+ context_parts.append(f"This meeting happened {days_since} days ago")
+
+ # Add user context for better understanding
+ if recording.owner:
+ user_context = []
+ if recording.owner.name:
+ user_context.append(f"User's name: {recording.owner.name}")
+ if recording.owner.job_title:
+ user_context.append(f"Job title: {recording.owner.job_title}")
+ if recording.owner.company:
+ user_context.append(f"Company: {recording.owner.company}")
+ if user_context:
+ context_parts.append("User information: " + ", ".join(user_context))
+
+ # Add participants if available
+ if recording.participants:
+ context_parts.append(f"Participants in the meeting: {recording.participants}")
+
+ context_section = "\n".join(context_parts)
+
+ # Add language directive if user has a language preference
+ language_directive = ""
+ if user_output_language:
+ language_directive = f"\n\nLANGUAGE REQUIREMENT:\n**CRITICAL**: You MUST generate ALL event titles and descriptions in {user_output_language}. This is mandatory. The entire event content (title, description, location) must be in {user_output_language}."
+
+ # Prepare the prompt for event extraction
+ event_prompt = f"""You are analyzing a meeting transcript to extract calendar events. Use the context below to correctly interpret relative dates and times.
+
+IMPORTANT CONTEXT:
+{context_section}{language_directive}
+
+INSTRUCTIONS:
+1. **CRITICAL**: Use the MEETING DATE shown above as your reference point for ALL relative date calculations
+2. When people say "next Wednesday" or "tomorrow" or "next week", calculate from the MEETING DATE, not today's date
+3. Example: If the meeting date is September 13, 2025 and someone says "next Wednesday", that means September 17, 2025
+4. If no specific time is mentioned for an event, use 09:00:00 (9 AM) as the default start time
+5. Pay attention to time zones if mentioned
+6. Extract ONLY events that are explicitly discussed as future appointments, meetings, or deadlines
+7. Do NOT create events for past occurrences or general discussions
+
+STRICT QUALIFYING CRITERIA - Events MUST have:
+- Explicit action words indicating a scheduled event (meeting, appointment, call, deadline, interview, presentation, review, etc.)
+- A specific or calculable date/time
+- A reasonable duration (typically under 8 hours, unless explicitly specified for a multi-day event, trip, conference)
+- Clear purpose or agenda
+
+DO NOT EXTRACT (explicit exclusions):
+- Long-term plans or durations (study periods, job contracts, project timelines spanning weeks/months/years)
+- General statements about future intentions without specific scheduling ("I'm going to study here for a year", "I'll be working on this project")
+- Implied or inferred locations - only use locations explicitly stated in the conversation
+- Vague commitments without concrete times ("we should meet sometime", "let's catch up soon")
+- Personal life events not discussed as scheduled appointments
+- Events where you need to guess or infer critical details
+
+For each event found, extract:
+- Title: A clear, concise title for the event
+- Description: Brief description including context from the meeting
+- Start date/time: The calculated actual date/time (in ISO format YYYY-MM-DDTHH:MM:SS, use 09:00:00 if no time specified)
+- End date/time: When the event ends (if mentioned, in ISO format, default to 1 hour after start if not specified)
+- Location: Where the event will take place (if mentioned)
+- Attendees: List of people who should attend (if mentioned)
+- Reminder minutes: How how long before to remind (default 1 day)
+
+Transcript Summary:
+{summary_text}
+
+Transcript excerpt (for additional context):
+{transcript_text[:8000]}
+
+RESPONSE FORMAT:
+Respond with a JSON object containing an "events" array. If no events are found, return a JSON object with an empty events array.
+
+Example response:
+{{
+ "events": [
+ {{
+ "title": "Project Review Meeting",
+ "description": "Quarterly review to discuss project progress and next steps as discussed in the meeting",
+ "start_datetime": "2025-07-22T14:00:00",
+ "end_datetime": "2025-07-22T15:30:00",
+ "location": "Conference Room A",
+ "attendees": ["John Smith", "Jane Doe", "Bob Johnson"],
+ "reminder_minutes": 15
+ }}
+ ]
+}}
+
+NEGATIVE EXAMPLES - Do NOT extract events like these:
+
+❌ "I'm going to study here for one year" → NOT an event (long-term plan, no specific appointment)
+❌ "I'll be working on this project until March" → NOT an event (duration/timeline, not a meeting)
+❌ "We should get coffee sometime" → NOT an event (vague, no specific time)
+❌ "The semester starts in September" → NOT an event (general information, not a scheduled appointment)
+❌ "I moved here from California" → NOT an event (past occurrence)
+
+✅ "Let's meet next Tuesday at 2pm to review the proposal" → IS an event (specific time, action word, clear purpose)
+✅ "The deadline for submissions is Friday at 5pm" → IS an event (specific deadline)
+✅ "I have a doctor's appointment tomorrow at 10am" → IS an event (specific appointment)
+
+CRITICAL RULES:
+1. **BASE ALL DATE CALCULATIONS ON THE MEETING DATE PROVIDED IN THE CONTEXT ABOVE**
+2. Only extract events that are FUTURE relative to the MEETING DATE (not today's date)
+3. Convert all relative dates using the MEETING DATE as the reference point
+4. Example: If the meeting date is September 13, 2025 (Friday) and someone says:
+ - "next Wednesday" = September 17, 2025
+ - "tomorrow" = September 14, 2025
+ - "next week" = week of September 15-19, 2025
+5. IMPORTANT: If no time is mentioned, always use 09:00:00 (9 AM) as the start time, NOT midnight
+6. Include context from the discussion in the description
+7. Do NOT invent or assume events not explicitly discussed
+8. If unsure about a date/time, do not include that event"""
+
+ # Build system message with language requirement if applicable
+ system_message_content = """You are an expert at extracting calendar events from meeting transcripts. You excel at:
+1. Understanding relative date references ("next Tuesday", "tomorrow", "in two weeks") and converting them to absolute dates
+2. Identifying genuine future appointments, meetings, and deadlines from conversations
+3. Distinguishing between actual planned events vs. general discussions
+4. Extracting participant names and meeting details accurately
+
+You must respond with valid JSON format only."""
+
+ if user_output_language:
+ system_message_content += f"\n\nLanguage Requirement: You MUST generate ALL event titles, descriptions, and locations in {user_output_language}. This is mandatory."
+
+ completion = call_llm_completion(
+ messages=[
+ {"role": "system", "content": system_message_content},
+ {"role": "user", "content": event_prompt}
+ ],
+ temperature=0.2,
+ response_format={"type": "json_object"},
+ max_tokens=3000
+ )
+
+ response_content = completion.choices[0].message.content
+ events_data = safe_json_loads(response_content, {})
+
+ # Handle both {"events": [...]} and direct array format
+ if isinstance(events_data, dict) and 'events' in events_data:
+ events_list = events_data['events']
+ elif isinstance(events_data, list):
+ events_list = events_data
+ else:
+ events_list = []
+
+ current_app.logger.info(f"Found {len(events_list)} events for recording {recording_id}")
+
+ # Save events to database
+ for event_data in events_list:
+ try:
+ # Parse dates
+ start_dt = None
+ end_dt = None
+
+ if 'start_datetime' in event_data:
+ try:
+ # Try ISO format first
+ start_dt = datetime.fromisoformat(event_data['start_datetime'].replace('Z', '+00:00'))
+ except:
+ # Try other common formats
+ from dateutil import parser
+ try:
+ start_dt = parser.parse(event_data['start_datetime'])
+ except:
+ current_app.logger.warning(f"Could not parse start_datetime: {event_data['start_datetime']}")
+ continue # Skip this event if we can't parse the date
+
+ if 'end_datetime' in event_data and event_data['end_datetime']:
+ try:
+ end_dt = datetime.fromisoformat(event_data['end_datetime'].replace('Z', '+00:00'))
+ except:
+ from dateutil import parser
+ try:
+ end_dt = parser.parse(event_data['end_datetime'])
+ except:
+ pass # End time is optional
+
+ # Create event record
+ event = Event(
+ recording_id=recording_id,
+ title=event_data.get('title', 'Untitled Event')[:200],
+ description=event_data.get('description', ''),
+ start_datetime=start_dt,
+ end_datetime=end_dt,
+ location=event_data.get('location', '')[:500] if event_data.get('location') else None,
+ attendees=json.dumps(event_data.get('attendees', [])) if event_data.get('attendees') else None,
+ reminder_minutes=event_data.get('reminder_minutes', 15)
+ )
+
+ db.session.add(event)
+ current_app.logger.info(f"Added event '{event.title}' for recording {recording_id}")
+
+ except Exception as e:
+ current_app.logger.error(f"Error saving event for recording {recording_id}: {str(e)}")
+ continue
+
+ db.session.commit()
+
+ # Refresh the recording to ensure events relationship is loaded
+ recording = db.session.get(Recording, recording_id)
+ if recording:
+ db.session.refresh(recording)
+
+ except Exception as e:
+ current_app.logger.error(f"Error extracting events for recording {recording_id}: {str(e)}")
+ db.session.rollback()
+
+
+def extract_audio_from_video(video_filepath, output_format='mp3', cleanup_original=True):
+ """Extract audio from video containers using FFmpeg.
+
+ Uses MP3 codec for optimal compatibility and predictable file sizes.
+ 64kbps MP3 provides good speech quality at ~480KB per minute.
+ """
+ try:
+ # Generate output filename with audio extension
+ base_filepath, file_ext = os.path.splitext(video_filepath)
+ temp_audio_filepath = f"{base_filepath}_audio_temp.{output_format}"
+ final_audio_filepath = f"{base_filepath}_audio.{output_format}"
+
+ current_app.logger.info(f"Extracting audio from video: {video_filepath} -> {temp_audio_filepath}")
+
+ # Extract audio using FFmpeg - using high-quality MP3 for better transcription
+ subprocess.run([
+ 'ffmpeg', '-i', video_filepath, '-y',
+ '-vn', # No video
+ '-codec:a', 'libmp3lame', # Use LAME MP3 encoder explicitly
+ '-b:a', '128k', # 128kbps bitrate for high quality
+ '-ar', '44100', # 44.1kHz sample rate for better quality
+ '-ac', '1', # Mono (sufficient for speech, reduces file size)
+ '-compression_level', '2', # Better compression
+ temp_audio_filepath
+ ], check=True, capture_output=True, text=True)
+
+ current_app.logger.info(f"Successfully extracted audio to {temp_audio_filepath}")
+
+ # Optionally preserve temp file for debugging (set PRESERVE_TEMP_AUDIO=true in env)
+ if os.getenv('PRESERVE_TEMP_AUDIO', 'false').lower() == 'true':
+ import shutil
+ shutil.copy2(temp_audio_filepath, temp_audio_filepath.replace('_temp', '_debug'))
+ current_app.logger.info(f"Debug: Preserved temp audio file as {temp_audio_filepath.replace('_temp', '_debug')}")
+
+ # Rename temp file to final filename
+ os.rename(temp_audio_filepath, final_audio_filepath)
+
+ # Clean up original video file if requested
+ if cleanup_original:
+ try:
+ os.remove(video_filepath)
+ current_app.logger.info(f"Cleaned up original video file: {video_filepath}")
+ except Exception as e:
+ current_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:
+ current_app.logger.error(f"FFmpeg audio extraction failed for {video_filepath}: {e.stderr}")
+ raise Exception(f"Audio extraction failed: {e.stderr}")
+ except FileNotFoundError:
+ current_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:
+ current_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:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ current_app.logger.error(f"Error: Recording {recording_id} not found for ASR transcription.")
+ return
+
+ try:
+ current_app.logger.info(f"Starting ASR transcription for recording {recording_id}...")
+ recording.status = 'PROCESSING'
+ transcription_start_time = time.time()
+ db.session.commit()
+
+ # 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:
+ current_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, 'mp3')
+
+ # 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()
+
+ current_app.logger.info(f"Audio extracted successfully: {audio_filepath}")
+ except Exception as e:
+ current_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
+
+ # Keep track of whether we've already tried WAV conversion
+ wav_conversion_attempted = False
+ wav_converted_filepath = None
+
+ # Retry loop for handling 500 errors with WAV conversion
+ max_attempts = 2
+ for attempt in range(max_attempts):
+ try:
+ # Use converted MP3 if available from previous attempt
+ current_filepath = wav_converted_filepath if wav_converted_filepath else actual_filepath
+ current_content_type = 'audio/mpeg' if wav_converted_filepath else actual_content_type
+ current_filename = os.path.basename(current_filepath)
+
+ with open(current_filepath, 'rb') as audio_file:
+ url = f"{ASR_BASE_URL}/asr"
+ params = {
+ 'encode': True,
+ 'task': 'transcribe',
+ 'output': 'json'
+ }
+ if language:
+ params['language'] = language
+ if diarize:
+ params['enable_diarization'] = diarize
+ # Request speaker embeddings when diarization is enabled
+ params['return_speaker_embeddings'] = True
+ if min_speakers:
+ params['min_speakers'] = min_speakers
+ if max_speakers:
+ params['max_speakers'] = max_speakers
+
+ content_type = current_content_type
+ current_app.logger.info(f"Using MIME type {content_type} for ASR upload.")
+ files = {'audio_file': (current_filename, audio_file, content_type)}
+
+ with httpx.Client() as client:
+ # Get configurable ASR timeout from database (default 30 minutes)
+ asr_timeout_seconds = SystemSetting.get_setting('asr_timeout_seconds', 1800)
+ timeout = httpx.Timeout(None, connect=30.0, read=float(asr_timeout_seconds), write=30.0, pool=30.0)
+ current_app.logger.info(f"Sending ASR request to {url} with params: {params} (timeout: {asr_timeout_seconds}s)")
+ response = client.post(url, params=params, files=files, timeout=timeout)
+ current_app.logger.info(f"ASR request completed with status: {response.status_code}")
+ response.raise_for_status()
+
+ # Parse the JSON response from ASR (moved here so it's accessible)
+ asr_response_data = response.json()
+
+ # Extract speaker embeddings if present
+ if 'speaker_embeddings' in asr_response_data:
+ current_app.logger.info(f"Received speaker embeddings for speakers: {list(asr_response_data['speaker_embeddings'].keys())}")
+ # Store speaker embeddings in the recording
+ recording.speaker_embeddings = asr_response_data['speaker_embeddings']
+ db.session.commit()
+
+ # If we reach here, the request was successful
+ break
+
+ except httpx.HTTPStatusError as e:
+ # Check if it's a 500 error and we haven't tried WAV conversion yet
+ if e.response.status_code == 500 and attempt == 0 and not wav_conversion_attempted:
+ current_app.logger.warning(f"ASR returned 500 error for recording {recording_id}, attempting high-quality MP3 conversion and retry...")
+
+ # Convert to high-quality MP3 for better compatibility
+ filename_lower = actual_filename.lower()
+ if not filename_lower.endswith('.mp3'):
+ try:
+ base_filepath, file_ext = os.path.splitext(actual_filepath)
+ temp_mp3_filepath = f"{base_filepath}_temp.mp3"
+
+ current_app.logger.info(f"Converting {actual_filename} to high-quality MP3 format for retry...")
+ subprocess.run(
+ ['ffmpeg', '-i', actual_filepath, '-y', '-acodec', 'libmp3lame', '-b:a', '128k', '-ar', '44100', temp_mp3_filepath],
+ check=True, capture_output=True, text=True
+ )
+ current_app.logger.info(f"Successfully converted {actual_filepath} to {temp_mp3_filepath}")
+
+ wav_converted_filepath = temp_mp3_filepath # Keep variable name for compatibility
+ wav_conversion_attempted = True
+ # Continue to next iteration to retry with WAV
+ continue
+ except subprocess.CalledProcessError as conv_error:
+ current_app.logger.error(f"Failed to convert to WAV: {conv_error}")
+ # Re-raise the original HTTP error if conversion fails
+ raise e
+ else:
+ # Already a WAV file, can't convert further
+ current_app.logger.error(f"File is already WAV but still getting 500 error")
+ raise e
+ else:
+ # Not a 500 error or already tried conversion, propagate the error
+ raise e
+
+ # DEBUG: Preserve converted file for quality checking
+ if wav_converted_filepath and os.path.exists(wav_converted_filepath):
+ try:
+ # Get file size and basic info for debugging
+ converted_size = os.path.getsize(wav_converted_filepath)
+ converted_size_mb = converted_size / (1024 * 1024)
+
+ # Create a debug copy in a known location
+ debug_dir = os.path.join(current_app.config['UPLOAD_FOLDER'], 'debug_converted')
+ os.makedirs(debug_dir, exist_ok=True)
+
+ # Copy the converted file with a timestamp (MP3 now)
+ from shutil import copy2
+ file_ext = os.path.splitext(wav_converted_filepath)[1] or '.mp3'
+ debug_filename = f"debug_{recording_id}_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}{file_ext}"
+ debug_filepath = os.path.join(debug_dir, debug_filename)
+ copy2(wav_converted_filepath, debug_filepath)
+
+ current_app.logger.info(f"DEBUG: Converted file preserved at: {debug_filepath}")
+ current_app.logger.info(f"DEBUG: Converted file size: {converted_size_mb:.2f} MB ({converted_size} bytes)")
+ current_app.logger.info(f"DEBUG: Original file: {actual_filename}")
+ current_app.logger.info(f"DEBUG: Recording ID: {recording_id}")
+ current_app.logger.info(f"DEBUG: You can download this file from the container at: {debug_filepath}")
+
+ except Exception as debug_error:
+ current_app.logger.warning(f"DEBUG: Failed to preserve converted file: {debug_error}")
+
+ # Clean up the original temporary converted file (but keep debug copy)
+ try:
+ if wav_converted_filepath and os.path.exists(wav_converted_filepath):
+ os.remove(wav_converted_filepath)
+ current_app.logger.info(f"Cleaned up original temporary converted file: {wav_converted_filepath}")
+ except Exception as cleanup_error:
+ current_app.logger.warning(f"Failed to clean up temporary converted file: {cleanup_error}")
+
+ # Debug logging for ASR response
+ current_app.logger.info(f"ASR response keys: {list(asr_response_data.keys())}")
+
+ # Log the complete raw JSON response (truncated for readability)
+ import json as json_module
+ raw_json_str = json_module.dumps(asr_response_data, indent=2)
+ if len(raw_json_str) > 5000:
+ current_app.logger.info(f"Raw ASR response (first 5000 chars): {raw_json_str[:5000]}...")
+ else:
+ current_app.logger.info(f"Raw ASR response: {raw_json_str}")
+
+ if 'segments' in asr_response_data:
+ current_app.logger.info(f"Number of segments: {len(asr_response_data['segments'])}")
+
+ # Collect all unique speakers from the response
+ all_speakers = set()
+ segments_with_speakers = 0
+ segments_without_speakers = 0
+
+ for segment in asr_response_data['segments']:
+ if 'speaker' in segment and segment['speaker'] is not None:
+ all_speakers.add(segment['speaker'])
+ segments_with_speakers += 1
+ else:
+ segments_without_speakers += 1
+
+ current_app.logger.info(f"Unique speakers found in raw response: {sorted(list(all_speakers))}")
+ current_app.logger.info(f"Segments with speakers: {segments_with_speakers}, without speakers: {segments_without_speakers}")
+
+ # Log first few segments for debugging
+ for i, segment in enumerate(asr_response_data['segments'][:5]):
+ segment_keys = list(segment.keys())
+ current_app.logger.info(f"Segment {i} keys: {segment_keys}")
+ current_app.logger.info(f"Segment {i}: speaker='{segment.get('speaker')}', text='{segment.get('text', '')[:50]}...'")
+
+ # Simplify the JSON data
+ simplified_segments = []
+ if 'segments' in asr_response_data and isinstance(asr_response_data['segments'], list):
+ last_known_speaker = None
+
+ for i, segment in enumerate(asr_response_data['segments']):
+ speaker = segment.get('speaker')
+ text = segment.get('text', '').strip()
+
+ # If segment doesn't have a speaker, use the previous segment's speaker
+ if speaker is None:
+ if last_known_speaker is not None:
+ speaker = last_known_speaker
+ current_app.logger.info(f"Assigned speaker '{speaker}' to segment {i} from previous segment")
+ else:
+ speaker = 'UNKNOWN_SPEAKER'
+ current_app.logger.warning(f"No previous speaker available for segment {i}, using UNKNOWN_SPEAKER")
+ else:
+ # Update the last known speaker when we have a valid one
+ last_known_speaker = speaker
+
+ simplified_segments.append({
+ 'speaker': speaker,
+ 'sentence': text,
+ 'start_time': segment.get('start'),
+ 'end_time': segment.get('end')
+ })
+
+ # Log final simplified segments count
+ current_app.logger.info(f"Created {len(simplified_segments)} simplified segments")
+ null_speaker_count = sum(1 for seg in simplified_segments if seg['speaker'] is None)
+ if null_speaker_count > 0:
+ current_app.logger.warning(f"Found {null_speaker_count} segments with null speakers in final output")
+
+ # Store the simplified JSON as a string
+ recording.transcription = json.dumps(simplified_segments)
+
+ # Commit the transcription data
+ db.session.commit()
+
+ # Calculate and save transcription duration
+ transcription_end_time = time.time()
+ recording.transcription_duration_seconds = int(transcription_end_time - transcription_start_time)
+ db.session.commit()
+ current_app.logger.info(f"ASR transcription completed for recording {recording_id} in {recording.transcription_duration_seconds}s.")
+
+ # Check if auto-summarization is disabled
+ disable_auto_summarization = SystemSetting.get_setting('disable_auto_summarization', False)
+ will_auto_summarize = not disable_auto_summarization
+
+ # Generate title immediately (pass flag so it knows whether to set COMPLETED)
+ generate_title_task(app_context, recording_id, will_auto_summarize=will_auto_summarize)
+
+ if disable_auto_summarization:
+ current_app.logger.info(f"Auto-summarization disabled, skipping summary for recording {recording_id}")
+ recording = db.session.get(Recording, recording_id)
+ if recording:
+ recording.status = 'COMPLETED'
+ recording.completed_at = datetime.utcnow()
+ db.session.commit()
+
+ # Apply auto-shares for group tags after processing completes
+ apply_team_tag_auto_shares(recording_id)
+
+ # Export transcription-only if auto-export is enabled
+ if ENABLE_AUTO_EXPORT:
+ export_recording(recording_id)
+ else:
+ # Auto-generate summary for all recordings
+ current_app.logger.info(f"Auto-generating summary for recording {recording_id}")
+ generate_summary_only_task(app_context, recording_id)
+
+ except Exception as e:
+ db.session.rollback()
+
+ # Handle timeout errors specifically
+ error_msg = str(e)
+ if "timed out" in error_msg.lower() or "timeout" in error_msg.lower():
+ asr_timeout = SystemSetting.get_setting('asr_timeout_seconds', 1800)
+ current_app.logger.error(f"ASR processing TIMED OUT for recording {recording_id} after {asr_timeout} seconds. Consider increasing 'asr_timeout_seconds' in Admin Dashboard > System Settings.")
+ user_error_msg = f"ASR processing timed out after {asr_timeout} seconds. The file may be too long for the current timeout setting."
+ else:
+ # For non-timeout errors, include more detail
+ current_app.logger.error(f"ASR processing FAILED for recording {recording_id}: {error_msg}")
+ user_error_msg = f"ASR processing failed: {error_msg}"
+
+ recording = db.session.get(Recording, recording_id)
+ if recording:
+ recording.status = 'FAILED'
+ recording.transcription = user_error_msg
+ db.session.commit()
+
+
+
+def transcribe_audio_task(app_context, recording_id, filepath, filename_for_asr, start_time, language=None, min_speakers=None, max_speakers=None, tag_id=None):
+ """Runs the transcription and summarization in a background thread.
+
+ Args:
+ app_context: Flask app context
+ recording_id: ID of the recording to process
+ filepath: Path to the audio file
+ filename_for_asr: Filename to use for ASR
+ start_time: Processing start time
+ language: Optional language code override (from upload form)
+ min_speakers: Optional minimum speakers override (from upload form)
+ max_speakers: Optional maximum speakers override (from upload form)
+ tag_id: Optional tag ID to apply custom prompt from
+ """
+ if USE_ASR_ENDPOINT:
+ with app_context:
+ recording = db.session.get(Recording, recording_id)
+ # Environment variable ASR_DIARIZE overrides user setting
+ if '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_DIARIZE
+ else:
+ diarize_setting = recording.owner.diarize if recording.owner else False
+
+ # Use language from upload form if provided, otherwise use user's default
+ if language:
+ user_transcription_language = language
+ else:
+ user_transcription_language = recording.owner.transcription_language if recording.owner else None
+ # Use min/max speakers from upload form (already processed with precedence hierarchy)
+ # If None, ASR will auto-detect the number of speakers
+ final_min_speakers = min_speakers
+ final_max_speakers = max_speakers
+
+ transcribe_audio_asr(app_context, recording_id, filepath, filename_for_asr, start_time,
+ mime_type=recording.mime_type,
+ language=user_transcription_language,
+ diarize=diarize_setting,
+ min_speakers=final_min_speakers,
+ max_speakers=final_max_speakers,
+ tag_id=tag_id)
+
+ # After ASR task completes, calculate processing time
+ with app_context:
+ recording = db.session.get(Recording, recording_id)
+ if recording.status in ['COMPLETED', 'FAILED']:
+ end_time = datetime.utcnow()
+ recording.processing_time_seconds = (end_time - start_time).total_seconds()
+ db.session.commit()
+ return
+
+ with app_context: # Need app context for db operations in thread
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ current_app.logger.error(f"Error: Recording {recording_id} not found for transcription.")
+ return
+
+ try:
+ current_app.logger.info(f"Starting transcription for recording {recording_id} ({filename_for_asr})...")
+ recording.status = 'PROCESSING'
+ transcription_start_time = time.time()
+ db.session.commit()
+
+ # Check if chunking is needed for large files
+ needs_chunking = (chunking_service and
+ ENABLE_CHUNKING and
+ chunking_service.needs_chunking(filepath, USE_ASR_ENDPOINT))
+
+ if needs_chunking:
+ current_app.logger.info(f"File {filepath} is large ({os.path.getsize(filepath)/1024/1024:.1f}MB), using chunking for transcription")
+ transcription_text = transcribe_with_chunking(app_context, recording_id, filepath, filename_for_asr)
+ else:
+ # --- Standard transcription for smaller files ---
+ transcription_text = transcribe_single_file(filepath, recording)
+
+ recording.transcription = transcription_text
+
+ # Calculate and save transcription duration
+ transcription_end_time = time.time()
+ recording.transcription_duration_seconds = int(transcription_end_time - transcription_start_time)
+ db.session.commit()
+ current_app.logger.info(f"Transcription completed for recording {recording_id} in {recording.transcription_duration_seconds}s. Text length: {len(recording.transcription)}")
+
+ # Check if auto-summarization is disabled
+ disable_auto_summarization = SystemSetting.get_setting('disable_auto_summarization', False)
+ will_auto_summarize = not disable_auto_summarization
+
+ # Generate title immediately (pass flag so it knows whether to set COMPLETED)
+ generate_title_task(app_context, recording_id, will_auto_summarize=will_auto_summarize)
+
+ if disable_auto_summarization:
+ current_app.logger.info(f"Auto-summarization disabled, skipping summary for recording {recording_id}")
+ recording.status = 'COMPLETED'
+ recording.completed_at = datetime.utcnow()
+ db.session.commit()
+
+ # Apply auto-shares for group tags after processing completes
+ apply_team_tag_auto_shares(recording_id)
+
+ # Export transcription-only if auto-export is enabled
+ if ENABLE_AUTO_EXPORT:
+ export_recording(recording_id)
+ else:
+ # Auto-generate summary for all recordings
+ current_app.logger.info(f"Auto-generating summary for recording {recording_id}")
+ generate_summary_only_task(app_context, recording_id)
+
+ except Exception as e:
+ db.session.rollback() # Rollback if any step failed critically
+ current_app.logger.error(f"Processing FAILED for recording {recording_id}: {str(e)}", exc_info=True)
+ # Retrieve recording again in case session was rolled back
+ recording = db.session.get(Recording, recording_id)
+ if recording:
+ # Ensure status reflects failure even after rollback/retrieve attempt
+ if recording.status not in ['COMPLETED', 'FAILED']: # Avoid overwriting final state
+ recording.status = 'FAILED'
+ if not recording.transcription: # If transcription itself failed
+ recording.transcription = f"Processing failed: {str(e)}"
+ # Add error note to summary if appropriate stage was reached
+ if recording.status == 'SUMMARIZING' and not recording.summary:
+ recording.summary = f"[Processing failed during summarization: {str(e)}]"
+
+ end_time = datetime.utcnow()
+ recording.processing_time_seconds = (end_time - start_time).total_seconds()
+ db.session.commit()
+
+
+
+def transcribe_single_file(filepath, recording):
+ """Transcribe a single audio file using OpenAI Whisper API."""
+
+ # 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:
+ current_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()
+
+ current_app.logger.info(f"Audio extracted successfully for Whisper: {audio_filepath}")
+ except Exception as e:
+ current_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)}")
+
+ # List of formats supported by Whisper API
+ WHISPER_SUPPORTED_FORMATS = ['flac', 'm4a', 'mp3', 'mp4', 'mpeg', 'mpga', 'oga', 'ogg', 'wav', 'webm']
+
+ # Check if the file format needs conversion
+ file_ext = os.path.splitext(actual_filepath)[1].lower().lstrip('.')
+ converted_filepath = None
+
+ try:
+ with open(actual_filepath, 'rb') as audio_file:
+ transcription_client = OpenAI(
+ api_key=transcription_api_key,
+ base_url=transcription_base_url,
+ http_client=http_client_no_proxy
+ )
+ whisper_model = os.environ.get("WHISPER_MODEL", "Systran/faster-distil-whisper-large-v3")
+
+ user_transcription_language = None
+ if recording and recording.owner:
+ user_transcription_language = recording.owner.transcription_language
+
+ transcription_language = user_transcription_language
+
+ transcription_params = {
+ "model": whisper_model,
+ "file": audio_file
+ }
+
+ if transcription_language:
+ transcription_params["language"] = transcription_language
+ current_app.logger.info(f"Using transcription language: {transcription_language}")
+ else:
+ current_app.logger.info("Transcription language not set, using auto-detection or service default.")
+
+ transcript = transcription_client.audio.transcriptions.create(**transcription_params)
+ return transcript.text
+
+ except Exception as e:
+ # Check if it's a format error
+ error_message = str(e)
+ if "Invalid file format" in error_message or "Supported formats" in error_message:
+ current_app.logger.warning(f"Unsupported audio format '{file_ext}' detected, converting to MP3...")
+
+ # Convert to MP3
+ import tempfile
+ temp_mp3_filepath = None
+ try:
+ with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as temp_mp3:
+ temp_mp3_filepath = temp_mp3.name
+
+ # Use ffmpeg to convert to MP3 with consistent settings
+ subprocess.run(
+ ['ffmpeg', '-i', actual_filepath, '-y', '-acodec', 'libmp3lame', '-b:a', '128k', '-ar', '44100', temp_mp3_filepath],
+ check=True,
+ capture_output=True
+ )
+ current_app.logger.info(f"Successfully converted {actual_filepath} to MP3 format")
+ converted_filepath = temp_mp3_filepath
+
+ # Retry transcription with converted file
+ with open(converted_filepath, 'rb') as audio_file:
+ transcription_client = OpenAI(
+ api_key=transcription_api_key,
+ base_url=transcription_base_url,
+ http_client=http_client_no_proxy
+ )
+
+ transcription_params = {
+ "model": whisper_model,
+ "file": audio_file
+ }
+
+ if transcription_language:
+ transcription_params["language"] = transcription_language
+
+ transcript = transcription_client.audio.transcriptions.create(**transcription_params)
+ return transcript.text
+
+ finally:
+ # Clean up temporary converted file
+ if converted_filepath and os.path.exists(converted_filepath):
+ try:
+ os.unlink(converted_filepath)
+ current_app.logger.info(f"Cleaned up temporary converted file: {converted_filepath}")
+ except Exception as cleanup_error:
+ current_app.logger.warning(f"Failed to clean up temporary file {converted_filepath}: {cleanup_error}")
+ else:
+ # Re-raise if it's not a format error
+ raise
+
+
+
+def transcribe_with_chunking(app_context, recording_id, filepath, filename_for_asr):
+ """Transcribe a large audio file using chunking."""
+ import tempfile
+
+ with app_context:
+ recording = db.session.get(Recording, recording_id)
+ if not recording:
+ raise ValueError(f"Recording {recording_id} not found")
+
+ # Create temporary directory for chunks
+ with tempfile.TemporaryDirectory() as temp_dir:
+ try:
+ # Create chunks
+ current_app.logger.info(f"Creating chunks for large file: {filepath}")
+ chunks = chunking_service.create_chunks(filepath, temp_dir)
+
+ if not chunks:
+ raise ChunkProcessingError("No chunks were created from the audio file")
+
+ current_app.logger.info(f"Created {len(chunks)} chunks, processing each with Whisper API...")
+
+ # Process each chunk with proper timeout and retry handling
+ chunk_results = []
+
+ # Create HTTP client with proper timeouts
+ timeout_config = httpx.Timeout(
+ connect=30.0, # 30 seconds to establish connection
+ read=300.0, # 5 minutes to read response (for large audio files)
+ write=60.0, # 1 minute to write request
+ pool=10.0 # 10 seconds to get connection from pool
+ )
+
+ http_client_with_timeout = httpx.Client(
+ verify=True,
+ timeout=timeout_config,
+ limits=httpx.Limits(max_connections=5, max_keepalive_connections=2)
+ )
+
+ transcription_client = OpenAI(
+ api_key=transcription_api_key,
+ base_url=transcription_base_url,
+ http_client=http_client_with_timeout,
+ max_retries=3, # Increased retries for better reliability
+ timeout=300.0 # 5 minute timeout for API calls
+ )
+ whisper_model = os.environ.get("WHISPER_MODEL", "Systran/faster-distil-whisper-large-v3")
+
+ # Get user language preference
+ user_transcription_language = None
+ with app_context:
+ recording = db.session.get(Recording, recording_id)
+ if recording and recording.owner:
+ user_transcription_language = recording.owner.transcription_language
+
+ for i, chunk in enumerate(chunks):
+ max_chunk_retries = 3
+ chunk_retry_count = 0
+ chunk_success = False
+
+ while chunk_retry_count < max_chunk_retries and not chunk_success:
+ try:
+ retry_suffix = f" (retry {chunk_retry_count + 1}/{max_chunk_retries})" if chunk_retry_count > 0 else ""
+ current_app.logger.info(f"Processing chunk {i+1}/{len(chunks)}: {chunk['filename']} ({chunk['size_mb']:.1f}MB){retry_suffix}")
+
+ # Log detailed timing for each step
+ step_start_time = time.time()
+
+ # Step 1: File opening
+ file_open_start = time.time()
+ with open(chunk['path'], 'rb') as chunk_file:
+ file_open_time = time.time() - file_open_start
+ current_app.logger.info(f"Chunk {i+1}: File opened in {file_open_time:.2f}s")
+
+ # Step 2: Prepare transcription parameters
+ param_start = time.time()
+ transcription_params = {
+ "model": whisper_model,
+ "file": chunk_file
+ }
+
+ if user_transcription_language:
+ transcription_params["language"] = user_transcription_language
+
+ param_time = time.time() - param_start
+ current_app.logger.info(f"Chunk {i+1}: Parameters prepared in {param_time:.2f}s")
+
+ # Step 3: API call with detailed timing
+ api_start = time.time()
+ current_app.logger.info(f"Chunk {i+1}: Starting API call to {transcription_base_url}")
+
+ # Log connection details
+ current_app.logger.info(f"Chunk {i+1}: Using timeout config - connect: 30s, read: 300s, write: 60s")
+ current_app.logger.info(f"Chunk {i+1}: Max retries: 2, API timeout: 300s")
+
+ try:
+ transcript = transcription_client.audio.transcriptions.create(**transcription_params)
+ except Exception as chunk_error:
+ # Check if it's a format error (unlikely for chunks since they're MP3, but handle it)
+ error_msg = str(chunk_error)
+ if "Invalid file format" in error_msg or "Supported formats" in error_msg:
+ current_app.logger.warning(f"Chunk {i+1} format issue, attempting conversion...")
+ # Convert chunk to MP3 if needed
+ import tempfile
+ with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as temp_mp3:
+ temp_mp3_path = temp_mp3.name
+ try:
+ subprocess.run(
+ ['ffmpeg', '-i', chunk['path'], '-y', '-acodec', 'libmp3lame', '-b:a', '128k', '-ar', '44100', temp_mp3_path],
+ check=True,
+ capture_output=True
+ )
+ with open(temp_mp3_path, 'rb') as converted_chunk:
+ transcription_params['file'] = converted_chunk
+ transcript = transcription_client.audio.transcriptions.create(**transcription_params)
+ finally:
+ if os.path.exists(temp_mp3_path):
+ os.unlink(temp_mp3_path)
+ else:
+ raise
+
+ api_time = time.time() - api_start
+ current_app.logger.info(f"Chunk {i+1}: API call completed in {api_time:.2f}s")
+
+ # Step 4: Process response
+ response_start = time.time()
+ chunk_result = {
+ 'index': chunk['index'],
+ 'start_time': chunk['start_time'],
+ 'end_time': chunk['end_time'],
+ 'duration': chunk['duration'],
+ 'size_mb': chunk['size_mb'],
+ 'transcription': transcript.text,
+ 'filename': chunk['filename'],
+ 'processing_time': api_time # Store the actual API processing time
+ }
+ chunk_results.append(chunk_result)
+ response_time = time.time() - response_start
+
+ total_time = time.time() - step_start_time
+ current_app.logger.info(f"Chunk {i+1}: Response processed in {response_time:.2f}s")
+ current_app.logger.info(f"Chunk {i+1}: Total processing time: {total_time:.2f}s")
+ current_app.logger.info(f"Chunk {i+1} transcribed successfully: {len(transcript.text)} characters")
+ chunk_success = True
+
+ except Exception as chunk_error:
+ chunk_retry_count += 1
+ error_msg = str(chunk_error)
+
+ if chunk_retry_count < max_chunk_retries:
+ # Determine wait time based on error type
+ if "timeout" in error_msg.lower() or "timed out" in error_msg.lower():
+ wait_time = 30 # 30 seconds for timeout errors
+ elif "rate limit" in error_msg.lower():
+ wait_time = 60 # 1 minute for rate limit errors
+ else:
+ wait_time = 15 # 15 seconds for other errors
+
+ current_app.logger.warning(f"Chunk {i+1} failed (attempt {chunk_retry_count}/{max_chunk_retries}): {chunk_error}. Retrying in {wait_time} seconds...")
+ time.sleep(wait_time)
+ else:
+ current_app.logger.error(f"Chunk {i+1} failed after {max_chunk_retries} attempts: {chunk_error}")
+ # Add failed chunk to results
+ chunk_result = {
+ 'index': chunk['index'],
+ 'start_time': chunk['start_time'],
+ 'end_time': chunk['end_time'],
+ 'transcription': f"[Chunk {i+1} transcription failed after {max_chunk_retries} attempts: {str(chunk_error)}]",
+ 'filename': chunk['filename']
+ }
+ chunk_results.append(chunk_result)
+
+ # Add small delay between chunks to avoid overwhelming the API
+ if i < len(chunks) - 1: # Don't delay after the last chunk
+ time.sleep(2)
+
+ # Merge transcriptions
+ current_app.logger.info(f"Merging {len(chunk_results)} chunk transcriptions...")
+ merged_transcription = chunking_service.merge_transcriptions(chunk_results)
+
+ if not merged_transcription.strip():
+ raise ChunkProcessingError("Merged transcription is empty")
+
+ # Log detailed performance statistics and analysis
+ chunking_service.log_processing_statistics(chunk_results)
+
+ # Get performance recommendations
+ recommendations = chunking_service.get_performance_recommendations(chunk_results)
+ if recommendations:
+ current_app.logger.info("=== PERFORMANCE RECOMMENDATIONS ===")
+ for i, rec in enumerate(recommendations, 1):
+ current_app.logger.info(f"{i}. {rec}")
+ current_app.logger.info("=== END RECOMMENDATIONS ===")
+
+ current_app.logger.info(f"Chunked transcription completed. Final length: {len(merged_transcription)} characters")
+ return merged_transcription
+
+ except Exception as e:
+ current_app.logger.error(f"Chunking transcription failed for {filepath}: {e}")
+ # Clean up chunks if they exist
+ if 'chunks' in locals():
+ chunking_service.cleanup_chunks(chunks)
+ raise ChunkProcessingError(f"Chunked transcription failed: {str(e)}")
+ finally:
+ # Cleanup is handled by tempfile.TemporaryDirectory context manager
+ pass
+
+
+
diff --git a/src/utils/__init__.py b/src/utils/__init__.py
new file mode 100644
index 00000000..b4cf829c
--- /dev/null
+++ b/src/utils/__init__.py
@@ -0,0 +1,54 @@
+"""
+Utility functions package for the Speakr application.
+
+This package contains various utility modules for:
+- JSON parsing and handling
+- Markdown to HTML conversion
+- Datetime formatting and timezone handling
+- Security utilities
+"""
+
+from .json_parser import (
+ auto_close_json,
+ safe_json_loads,
+ preprocess_json_escapes,
+ extract_json_object
+)
+
+from .markdown import (
+ md_to_html,
+ sanitize_html
+)
+
+from .datetime import (
+ local_datetime_filter
+)
+
+from .security import (
+ password_check,
+ is_safe_url
+)
+
+from .database import (
+ add_column_if_not_exists,
+ migrate_column_type
+)
+
+__all__ = [
+ # JSON parsing
+ 'auto_close_json',
+ 'safe_json_loads',
+ 'preprocess_json_escapes',
+ 'extract_json_object',
+ # Markdown/HTML
+ 'md_to_html',
+ 'sanitize_html',
+ # Datetime
+ 'local_datetime_filter',
+ # Security
+ 'password_check',
+ 'is_safe_url',
+ # Database
+ 'add_column_if_not_exists',
+ 'migrate_column_type',
+]
diff --git a/src/utils/database.py b/src/utils/database.py
new file mode 100644
index 00000000..7bb824b5
--- /dev/null
+++ b/src/utils/database.py
@@ -0,0 +1,142 @@
+"""
+Database schema migration utilities.
+"""
+
+from sqlalchemy import inspect, text
+
+
+def add_column_if_not_exists(engine, table_name, column_name, column_type):
+ """
+ Add a column to a table if it doesn't already exist.
+
+ Args:
+ engine: SQLAlchemy engine
+ table_name: Name of the table
+ column_name: Name of the column to add
+ column_type: SQL type definition for the column
+
+ Returns:
+ bool: True if column was added, False if it already existed
+ """
+ inspector = inspect(engine)
+ columns = [col['name'] for col in inspector.get_columns(table_name)]
+
+ if column_name not in columns:
+ with engine.connect() as conn:
+ # Handle special case where column_type includes the column name
+ if column_name in column_type:
+ conn.execute(text(f'ALTER TABLE {table_name} ADD COLUMN {column_type}'))
+ else:
+ conn.execute(text(f'ALTER TABLE {table_name} ADD COLUMN {column_name} {column_type}'))
+ conn.commit()
+ return True
+ return False
+
+
+def migrate_column_type(engine, table_name, column_name, new_type, transform_sql=None):
+ """
+ Migrate a column to a new type if it exists.
+
+ For SQLite, this uses a temporary column approach since SQLite doesn't support ALTER COLUMN.
+
+ Args:
+ engine: SQLAlchemy engine
+ table_name: Name of the table
+ column_name: Name of the column to modify
+ new_type: New SQL type for the column
+ transform_sql: Optional SQL expression to transform existing data (e.g., "datetime(meeting_date || ' 12:00:00')")
+ If None, data is copied as-is
+
+ Returns:
+ bool: True if column was migrated, False if it didn't exist or migration wasn't needed
+ """
+ inspector = inspect(engine)
+
+ # Check if table exists
+ if table_name not in inspector.get_table_names():
+ return False
+
+ columns = {col['name']: col for col in inspector.get_columns(table_name)}
+
+ if column_name not in columns:
+ return False
+
+ engine_name = engine.name
+
+ with engine.connect() as conn:
+ if engine_name == 'sqlite':
+ # SQLite approach: use temporary column
+ temp_col = f"{column_name}_new"
+
+ # Check if temp column already exists (migration interrupted?)
+ if temp_col in columns:
+ try:
+ # Try to drop it and start over
+ conn.execute(text(f'ALTER TABLE {table_name} DROP COLUMN {temp_col}'))
+ conn.commit()
+ except Exception:
+ # If we can't drop it, the migration may have partially completed
+ # Check if old column still exists
+ if column_name not in columns:
+ # Old column is gone, temp exists - just rename temp to complete migration
+ try:
+ conn.execute(text(f'ALTER TABLE {table_name} RENAME COLUMN {temp_col} TO {column_name}'))
+ conn.commit()
+ return True
+ except Exception as e:
+ # Can't complete, leave as-is
+ return False
+ # Both columns exist - abort to avoid data issues
+ return False
+
+ # Add temporary column with new type
+ conn.execute(text(f'ALTER TABLE {table_name} ADD COLUMN {temp_col} {new_type}'))
+
+ # Copy data with optional transformation
+ if transform_sql:
+ conn.execute(text(f'UPDATE {table_name} SET {temp_col} = {transform_sql} WHERE {column_name} IS NOT NULL'))
+ else:
+ conn.execute(text(f'UPDATE {table_name} SET {temp_col} = {column_name}'))
+
+ # Drop old column (SQLite 3.35.0+ only)
+ try:
+ conn.execute(text(f'ALTER TABLE {table_name} DROP COLUMN {column_name}'))
+ # Drop succeeded, now rename temp to original name
+ conn.execute(text(f'ALTER TABLE {table_name} RENAME COLUMN {temp_col} TO {column_name}'))
+ conn.commit()
+ except Exception:
+ # Older SQLite - can't drop columns
+ # Rename temp column to original name (this will fail if original still exists)
+ try:
+ conn.execute(text(f'ALTER TABLE {table_name} RENAME COLUMN {temp_col} TO {column_name}'))
+ conn.commit()
+ except Exception:
+ # Can't rename because old column exists - this is OK for SQLite
+ # Just keep the new column and let the app use the old one
+ # The data in the old column is still valid
+ conn.rollback()
+ # Actually, let's just commit the temp column addition
+ # The model will use column_name which still exists with old data
+ # This is safe - new records will use the new model definition
+ return False
+
+ elif engine_name == 'postgresql':
+ # PostgreSQL can alter column type directly
+ if transform_sql:
+ conn.execute(text(f'ALTER TABLE {table_name} ALTER COLUMN {column_name} TYPE {new_type} USING {transform_sql}'))
+ else:
+ conn.execute(text(f'ALTER TABLE {table_name} ALTER COLUMN {column_name} TYPE {new_type}'))
+ conn.commit()
+
+ elif engine_name == 'mysql':
+ # MySQL can modify column type
+ conn.execute(text(f'ALTER TABLE {table_name} MODIFY COLUMN {column_name} {new_type}'))
+
+ # Apply transformation if provided
+ if transform_sql:
+ conn.execute(text(f'UPDATE {table_name} SET {column_name} = {transform_sql} WHERE {column_name} IS NOT NULL'))
+ conn.commit()
+
+ return True
+
+ return False
diff --git a/src/utils/datetime.py b/src/utils/datetime.py
new file mode 100644
index 00000000..28e21bc5
--- /dev/null
+++ b/src/utils/datetime.py
@@ -0,0 +1,46 @@
+"""
+Datetime utilities for timezone handling and formatting.
+
+This module provides functions for converting and formatting datetimes
+with timezone awareness.
+"""
+
+import os
+import logging
+import pytz
+from babel.dates import format_datetime
+
+# Module-level logger
+logger = logging.getLogger(__name__)
+
+
+def local_datetime_filter(dt):
+ """
+ Format a UTC datetime object to the user's local timezone.
+
+ Args:
+ dt: datetime object to format (assumed UTC if naive)
+
+ Returns:
+ str: Formatted datetime string in user's timezone
+ """
+ if dt is None:
+ return ""
+
+ # Get timezone from .env, default to UTC
+ user_tz_name = os.environ.get('TIMEZONE', 'UTC')
+ try:
+ user_tz = pytz.timezone(user_tz_name)
+ except pytz.UnknownTimeZoneError:
+ user_tz = pytz.utc
+ logger.warning(f"Invalid TIMEZONE '{user_tz_name}' in .env. Defaulting to UTC.")
+
+ # If the datetime object is naive, assume it's UTC
+ if dt.tzinfo is None:
+ dt = pytz.utc.localize(dt)
+
+ # Convert to the user's timezone
+ local_dt = dt.astimezone(user_tz)
+
+ # Format it nicely
+ return format_datetime(local_dt, format='medium', locale='en_US')
diff --git a/src/utils/json_parser.py b/src/utils/json_parser.py
new file mode 100644
index 00000000..f98533a6
--- /dev/null
+++ b/src/utils/json_parser.py
@@ -0,0 +1,215 @@
+"""
+JSON parsing utilities for handling LLM responses and malformed JSON.
+
+This module provides robust JSON parsing functions that can handle common
+issues with LLM-generated JSON, including:
+- Incomplete/unterminated JSON structures
+- Escape sequence problems
+- JSON embedded in markdown code blocks
+- Nested quotes and special characters
+"""
+
+import json
+import re
+import ast
+import logging
+
+# Module-level logger
+logger = logging.getLogger(__name__)
+
+
+def auto_close_json(json_string):
+ """
+ Attempts to close an incomplete JSON string by appending necessary brackets and braces.
+ This is a simplified parser and may not handle all edge cases, but is
+ designed to fix unterminated strings from API responses.
+ """
+ if not isinstance(json_string, str):
+ return json_string
+
+ stack = []
+ in_string = False
+ escape_next = False
+
+ for char in json_string:
+ if escape_next:
+ escape_next = False
+ continue
+
+ if char == '\\':
+ escape_next = True
+ continue
+
+ if char == '"':
+ # We don't handle escaped quotes inside strings perfectly,
+ # but this is a simple heuristic.
+ if not escape_next:
+ in_string = not in_string
+
+ if not in_string:
+ if char == '{':
+ stack.append('}')
+ elif char == '[':
+ stack.append(']')
+ elif char == '}':
+ if stack and stack[-1] == '}':
+ stack.pop()
+ elif char == ']':
+ if stack and stack[-1] == ']':
+ stack.pop()
+
+ # If we are inside a string at the end, close it.
+ if in_string:
+ json_string += '"'
+
+ # Close any remaining open structures
+ while stack:
+ json_string += stack.pop()
+
+ return json_string
+
+
+def preprocess_json_escapes(json_string):
+ """
+ Preprocess JSON string to fix common escape issues from LLM responses.
+ Uses a more sophisticated approach to handle nested quotes properly.
+ """
+ if not json_string:
+ return json_string
+
+ result = []
+ i = 0
+ in_string = False
+ escape_next = False
+ expecting_value = False # Track if we're expecting a value (after :)
+
+ while i < len(json_string):
+ char = json_string[i]
+
+ if escape_next:
+ # This character is escaped, add it as-is
+ result.append(char)
+ escape_next = False
+ elif char == '\\':
+ # This is an escape character
+ result.append(char)
+ escape_next = True
+ elif char == ':' and not in_string:
+ # We found a colon, next string will be a value
+ result.append(char)
+ expecting_value = True
+ elif char == ',' and not in_string:
+ # We found a comma, reset expecting_value
+ result.append(char)
+ expecting_value = False
+ elif char == '"':
+ if not in_string:
+ # Starting a string
+ in_string = True
+ result.append(char)
+ else:
+ # We're in a string, check if this quote should be escaped
+ # Look ahead to see if this is the end of the string value
+ j = i + 1
+ while j < len(json_string) and json_string[j].isspace():
+ j += 1
+
+ # For keys (not expecting_value), only end on colon
+ # For values (expecting_value), end on comma, closing brace, or closing bracket
+ if expecting_value:
+ end_chars = ',}]'
+ else:
+ end_chars = ':'
+
+ if j < len(json_string) and json_string[j] in end_chars:
+ # This is the end of the string
+ in_string = False
+ result.append(char)
+ if not expecting_value:
+ # We just finished a key, next will be expecting value
+ expecting_value = True
+ else:
+ # This is an inner quote that should be escaped
+ result.append('\\"')
+ else:
+ result.append(char)
+
+ i += 1
+
+ return ''.join(result)
+
+
+def extract_json_object(text):
+ """
+ Extract the first complete JSON object or array from text using regex.
+ """
+ # Look for JSON object
+ obj_match = re.search(r'\{.*\}', text, re.DOTALL)
+ if obj_match:
+ return obj_match.group(0)
+
+ # Look for JSON array
+ arr_match = re.search(r'\[.*\]', text, re.DOTALL)
+ if arr_match:
+ return arr_match.group(0)
+
+ # Return original if no JSON structure found
+ return text
+
+
+def safe_json_loads(json_string, fallback_value=None):
+ """
+ Safely parse JSON with preprocessing to handle common LLM JSON formatting issues.
+
+ Args:
+ json_string (str): The JSON string to parse
+ fallback_value: Value to return if parsing fails (default: None)
+
+ Returns:
+ Parsed JSON object or fallback_value if parsing fails
+ """
+ if not json_string or not isinstance(json_string, str):
+ logger.warning(f"Invalid JSON input: {type(json_string)} - {json_string}")
+ return fallback_value
+
+ # Step 1: Clean the input string
+ cleaned_json = json_string.strip()
+
+ # Step 2: Extract JSON from markdown code blocks if present
+ json_match = re.search(r'```(?:json)?\s*(.*?)\s*```', cleaned_json, re.DOTALL)
+ if json_match:
+ cleaned_json = json_match.group(1).strip()
+
+ # Step 3: Try multiple parsing strategies
+ parsing_strategies = [
+ # Strategy 1: Direct parsing (for well-formed JSON)
+ lambda x: json.loads(x),
+
+ # Strategy 2: Fix common escape issues
+ lambda x: json.loads(preprocess_json_escapes(x)),
+
+ # Strategy 3: Use ast.literal_eval as fallback for simple cases
+ lambda x: ast.literal_eval(x) if x.startswith(('{', '[')) else None,
+
+ # Strategy 4: Extract JSON object/array using regex
+ lambda x: json.loads(extract_json_object(x)),
+
+ # Strategy 5: Auto-close incomplete JSON and parse
+ lambda x: json.loads(auto_close_json(x)),
+ ]
+
+ for i, strategy in enumerate(parsing_strategies):
+ try:
+ result = strategy(cleaned_json)
+ if result is not None:
+ if i > 0: # Log if we had to use a fallback strategy
+ logger.info(f"JSON parsed successfully using strategy {i+1}")
+ return result
+ except (json.JSONDecodeError, ValueError, SyntaxError) as e:
+ if i == 0: # Only log the first failure to avoid spam
+ logger.debug(f"JSON parsing strategy {i+1} failed: {e}")
+ continue
+
+ # All strategies failed
+ logger.error(f"All JSON parsing strategies failed for: {cleaned_json[:200]}...")
+ return fallback_value
diff --git a/src/utils/markdown.py b/src/utils/markdown.py
new file mode 100644
index 00000000..8b55635e
--- /dev/null
+++ b/src/utils/markdown.py
@@ -0,0 +1,132 @@
+"""
+Markdown and HTML utilities for converting and sanitizing text content.
+
+This module provides functions for converting markdown to HTML and
+sanitizing HTML to prevent XSS and other security issues.
+"""
+
+import re
+import markdown
+import bleach
+
+# --- Initialize Markdown Once (Performance Optimization) ---
+# Create a single reusable Markdown instance to avoid reinitializing extensions on every call
+_markdown_instance = markdown.Markdown(extensions=[
+ 'fenced_code', # Fenced code blocks
+ 'tables', # Table support
+ 'attr_list', # Attribute lists
+ 'def_list', # Definition lists
+ 'footnotes', # Footnotes
+ 'abbr', # Abbreviations
+ 'codehilite', # Syntax highlighting for code blocks
+ 'smarty' # Smart quotes, dashes, etc.
+])
+
+
+def sanitize_html(text):
+ """
+ Sanitize HTML content to prevent XSS and other security issues.
+
+ Args:
+ text (str): HTML text to sanitize
+
+ Returns:
+ str: Sanitized HTML text
+ """
+ if not text:
+ return ""
+
+ # Remove any template-like syntax that could be exploited
+ # Remove {{ }} style template syntax
+ text = re.sub(r'\{\{.*?\}\}', '', text, flags=re.DOTALL)
+ text = re.sub(r'\{%.*?%\}', '', text, flags=re.DOTALL)
+
+ # Remove other template-like syntax
+ text = re.sub(r'<%.*?%>', '', text, flags=re.DOTALL)
+ text = re.sub(r'<\?.*?\?>', '', text, flags=re.DOTALL)
+
+ # Define allowed tags and attributes for safe HTML
+ allowed_tags = [
+ 'p', 'br', 'strong', 'b', 'em', 'i', 'u', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
+ 'ul', 'ol', 'li', 'blockquote', 'code', 'pre', 'a', 'img', 'table', 'thead',
+ 'tbody', 'tr', 'th', 'td', 'dl', 'dt', 'dd', 'div', 'span', 'hr', 'sup', 'sub'
+ ]
+
+ allowed_attributes = {
+ 'a': ['href', 'title'],
+ 'img': ['src', 'alt', 'title', 'width', 'height'],
+ 'code': ['class'], # For syntax highlighting
+ 'pre': ['class'], # For syntax highlighting
+ 'div': ['class'], # For code blocks
+ 'span': ['class'], # For syntax highlighting
+ 'th': ['align'],
+ 'td': ['align'],
+ 'table': ['class']
+ }
+
+ # Sanitize the HTML to remove dangerous content
+ sanitized_html = bleach.clean(
+ text,
+ tags=allowed_tags,
+ attributes=allowed_attributes,
+ protocols=['http', 'https', 'mailto'],
+ strip=True # Strip disallowed tags instead of escaping them
+ )
+
+ return sanitized_html
+
+
+def md_to_html(text):
+ """
+ Convert markdown text to sanitized HTML.
+
+ Args:
+ text (str): Markdown text to convert
+
+ Returns:
+ str: Sanitized HTML output
+ """
+ if not text:
+ return ""
+
+ # Fix list spacing
+ def fix_list_spacing(text):
+ lines = text.split('\n')
+ result = []
+ in_list = False
+
+ for line in lines:
+ stripped = line.strip()
+
+ # Check if this line is a list item (starts with -, *, +, or number.)
+ is_list_item = (
+ stripped.startswith(('- ', '* ', '+ ')) or
+ (stripped and stripped[0].isdigit() and '. ' in stripped[:10])
+ )
+
+ # If we're starting a new list or continuing a list, ensure proper spacing
+ if is_list_item:
+ if not in_list and result and result[-1].strip():
+ # Starting a new list - add blank line before
+ result.append('')
+ in_list = True
+ elif in_list and stripped and not is_list_item:
+ # Ending a list - add blank line after the list
+ if result and result[-1].strip():
+ result.append('')
+ in_list = False
+
+ result.append(line)
+
+ return '\n'.join(result)
+
+ # Fix list spacing
+ processed_text = fix_list_spacing(text)
+
+ # Convert markdown to HTML using the pre-configured singleton instance
+ # Reset the instance to clear any state from previous conversions
+ _markdown_instance.reset()
+ html = _markdown_instance.convert(processed_text)
+
+ # Apply sanitization to the generated HTML
+ return sanitize_html(html)
diff --git a/src/utils/security.py b/src/utils/security.py
new file mode 100644
index 00000000..e7178005
--- /dev/null
+++ b/src/utils/security.py
@@ -0,0 +1,50 @@
+"""
+Security utilities for password validation and other security functions.
+
+This module provides security-related utility functions for the application.
+"""
+
+import re
+from wtforms.validators import ValidationError
+from urllib.parse import urlparse, urljoin
+from flask import request
+
+
+def password_check(form, field):
+ """
+ Custom WTForms validator for password strength.
+
+ Validates that passwords meet security requirements:
+ - At least 8 characters long
+ - Contains at least one uppercase letter
+ - Contains at least one lowercase letter
+ - Contains at least one number
+ - Contains at least one special character
+
+ Args:
+ form: WTForms form object
+ field: WTForms field object containing the password
+
+ Raises:
+ ValidationError: If password doesn't meet requirements
+ """
+ password = field.data
+ if len(password) < 8:
+ raise ValidationError('Password must be at least 8 characters long.')
+ if not re.search(r'[A-Z]', password):
+ raise ValidationError('Password must contain at least one uppercase letter.')
+ if not re.search(r'[a-z]', password):
+ raise ValidationError('Password must contain at least one lowercase letter.')
+ if not re.search(r'[0-9]', password):
+ raise ValidationError('Password must contain at least one number.')
+ if not re.search(r'[!@#$%^&*(),.?":{}|<>]', password):
+ raise ValidationError('Password must contain at least one special character.')
+
+
+# --- URL Security ---
+
+def is_safe_url(target):
+ ref_url = urlparse(request.host_url)
+ test_url = urlparse(urljoin(request.host_url, target))
+ return test_url.scheme in ('http', 'https') and ref_url.netloc == test_url.netloc
+
diff --git a/static/css/styles.css b/static/css/styles.css
index 4c1f7a39..3d4ba9ea 100644
--- a/static/css/styles.css
+++ b/static/css/styles.css
@@ -429,20 +429,25 @@ main {
}
.summary-box,
.notes-box {
- flex: 1; /* Take up available space in content-box */
- min-height: 0; /* Critical for flex shrinking */
- max-height: 100%; /* Prevent expansion beyond parent */
- overflow-y: auto; /* Enable vertical scrolling */
- overflow-x: auto; /* Enable horizontal scrolling for wide content like tables */
- /* Keep existing styling */
+ flex: 1 1 auto !important;
+ width: 100% !important;
+ min-width: 100% !important;
+ max-width: 100% !important;
+ min-height: 0;
+ max-height: 100%;
+ overflow-y: auto;
+ overflow-x: hidden;
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);
+ word-wrap: break-word;
+ overflow-wrap: break-word;
+ white-space: normal;
+ display: block !important;
}
.transcription-box {
@@ -632,6 +637,25 @@ div[v-if="!editingNotes"] {
align-items: center;
justify-content: center;
}
+
+ /* Desktop only: match height of toggle buttons when icon-only */
+ @media (min-width: 1024px) {
+ #leftMainColumn .view-mode-toggle {
+ height: 1.75rem;
+ }
+ #leftMainColumn .toggle-button {
+ height: 1.75rem;
+ padding-top: 0;
+ padding-bottom: 0;
+ line-height: 1;
+ }
+ #leftMainColumn .copy-btn {
+ height: 1.75rem;
+ padding-top: 0;
+ padding-bottom: 0;
+ line-height: 1;
+ }
+ }
.copy-btn:hover {
background-color: var(--bg-accent-hover);
@@ -764,6 +788,16 @@ div[v-if="!editingNotes"] {
.ai-message p, .summary-box p, .notes-box p {
margin-bottom: 0.75rem;
+ width: 100% !important;
+ max-width: 100% !important;
+ word-wrap: break-word;
+ overflow-wrap: break-word;
+ }
+
+ .summary-box > *, .notes-box > * {
+ width: 100% !important;
+ max-width: 100% !important;
+ display: block;
}
.ai-message ul, .ai-message ol,
@@ -815,6 +849,13 @@ div[v-if="!editingNotes"] {
overflow-wrap: break-word;
}
+ /* Wrap tables in scrollable container */
+ .summary-box > table, .notes-box > table {
+ display: block;
+ width: 100%;
+ overflow-x: auto;
+ }
+
.ai-message table, .summary-box table, .notes-box table {
border-collapse: collapse;
width: 100%;
@@ -1292,6 +1333,7 @@ body {
padding: 0.5rem 0.75rem;
border-radius: 0.75rem;
max-width: fit-content;
+ transition: background-color 0.3s ease, box-shadow 0.3s ease;
min-width: fit-content;
width: auto;
word-wrap: break-word;
@@ -1424,6 +1466,125 @@ body {
.speaker-segment {
margin-bottom: 1rem;
+ transition: background-color 0.3s ease, box-shadow 0.3s ease;
+}
+
+/* Active segment highlighting - for currently playing transcript */
+.speaker-segment.active-playing-segment,
+.transcript-segment.active-playing-segment {
+ background-color: var(--bg-accent) !important;
+ box-shadow: 0 0 0 2px var(--border-accent) !important;
+ animation: pulse-highlight 0.5s ease-in-out;
+ padding: 0.75rem !important;
+ margin: 0.25rem 0 !important;
+ border-radius: 0.5rem !important;
+}
+
+.speaker-bubble.active-playing-segment {
+ background-color: var(--bg-accent) !important;
+ box-shadow: 0 0 0 2px var(--border-accent) !important;
+ animation: pulse-highlight 0.5s ease-in-out;
+ transform: scale(1.02);
+}
+
+@keyframes pulse-highlight {
+ 0% {
+ box-shadow: 0 0 0 0 var(--border-accent);
+ }
+ 50% {
+ box-shadow: 0 0 0 4px var(--border-accent);
+ }
+ 100% {
+ box-shadow: 0 0 0 2px var(--border-accent);
+ }
+}
+
+/* Follow Player Mode Checkbox Styling */
+.follow-player-control {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.375rem;
+ padding: 0.25rem 0.5rem;
+ border-radius: 0.375rem;
+ transition: all 0.2s ease;
+ cursor: pointer;
+ user-select: none;
+}
+
+.follow-player-control:hover {
+ background-color: var(--bg-accent-hover);
+}
+
+.follow-player-control input[type="checkbox"] {
+ appearance: none;
+ -webkit-appearance: none;
+ width: 14px;
+ height: 14px;
+ border: 1.5px solid var(--border-secondary);
+ border-radius: 0.25rem;
+ background-color: var(--bg-input);
+ cursor: pointer;
+ position: relative;
+ transition: all 0.2s ease;
+ flex-shrink: 0;
+}
+
+.follow-player-control input[type="checkbox"]:hover {
+ border-color: var(--border-accent);
+}
+
+.follow-player-control input[type="checkbox"]:checked {
+ background-color: var(--bg-button);
+ border-color: var(--bg-button);
+ animation: checkboxPop 0.2s ease-out;
+}
+
+.follow-player-control input[type="checkbox"]:checked::after {
+ content: '';
+ position: absolute;
+ left: 50%;
+ top: 50%;
+ width: 3.5px;
+ height: 7px;
+ border: solid var(--text-button);
+ border-width: 0 2px 2px 0;
+ transform: translate(-50%, -60%) rotate(45deg);
+ animation: checkmarkDraw 0.2s ease-out;
+}
+
+@keyframes checkboxPop {
+ 0% {
+ transform: scale(0.8);
+ }
+ 50% {
+ transform: scale(1.1);
+ }
+ 100% {
+ transform: scale(1);
+ }
+}
+
+@keyframes checkmarkDraw {
+ 0% {
+ width: 0;
+ height: 0;
+ opacity: 0;
+ }
+ 100% {
+ width: 3.5px;
+ height: 7px;
+ opacity: 1;
+ }
+}
+
+.follow-player-control .follow-icon {
+ font-size: 11px;
+ flex-shrink: 0;
+ opacity: 0.85;
+}
+
+.follow-player-control:hover .follow-icon {
+ opacity: 1;
}
.speaker-tablet {
@@ -1448,12 +1609,13 @@ body {
/* View mode toggle - compact tablet style */
.view-mode-toggle {
display: inline-flex;
- align-items: center;
+ align-items: stretch;
background-color: var(--bg-tertiary);
border: 1px solid var(--border-primary);
border-radius: 0.5rem;
padding: 0;
gap: 0;
+ box-shadow: 0 1px 2px rgba(0,0,0,0.05);
}
.toggle-button {
@@ -1471,13 +1633,12 @@ body {
display: inline-flex;
align-items: center;
justify-content: center;
- box-shadow: 0 1px 2px rgba(0,0,0,0.05);
+ height: 100%;
}
.toggle-button.active {
background-color: var(--bg-accent);
color: var(--text-accent);
- box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}
.toggle-button:hover:not(.active) {
@@ -1772,6 +1933,48 @@ body {
color: var(--text-secondary);
min-height: 0;
}
+
+ /* Remove inner box styling for summary and notes on mobile */
+ .mobile-content-box .summary-box,
+ .mobile-content-box .notes-box {
+ background-color: transparent;
+ border: none;
+ padding: 0;
+ border-radius: 0;
+ height: auto;
+ }
+
+ /* Remove padding from mobile-content-box when it contains markdown editor */
+ .mobile-content-box:has(.markdown-editor-container) {
+ padding: 0;
+ overflow: hidden; /* Ensure rounded corners are respected */
+ }
+
+ /* Make editor fill the rounded container properly */
+ .mobile-content-box .markdown-editor-container {
+ height: 100%;
+ }
+
+ .mobile-content-box .markdown-editor-container .EasyMDEContainer {
+ border: none !important;
+ border-radius: 0.75rem;
+ height: 100%;
+ }
+
+ .mobile-content-box .markdown-editor-container .EasyMDEContainer .editor-toolbar {
+ border: none !important;
+ border-radius: 0.75rem 0.75rem 0 0;
+ border-bottom: 1px solid var(--border-primary) !important;
+ }
+
+ .mobile-content-box .markdown-editor-container .EasyMDEContainer .CodeMirror {
+ border: none !important;
+ border-radius: 0 0 0.75rem 0.75rem;
+ }
+
+ .mobile-content-box .markdown-editor-container .EasyMDEContainer .CodeMirror-scroll {
+ border-radius: 0 0 0.75rem 0.75rem;
+ }
/* Mobile chat layout */
.mobile-chat-content {
@@ -2012,6 +2215,29 @@ body {
flex-shrink: 0;
}
+/* Toast message stacking with fly-in animation */
+.toast-message {
+ transition: transform 0.3s ease-in-out, opacity 0.3s ease-in-out;
+ pointer-events: auto;
+ transform: translateX(400px);
+ margin-bottom: 0.5rem;
+ display: block !important;
+ max-width: 450px;
+ word-wrap: break-word;
+ /* All other styles handled by Tailwind classes */
+}
+
+.toast-message.toast-show {
+ transform: translateX(0);
+}
+
+#toastContainer {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-end;
+ max-width: 450px;
+}
+
/* Discrete horizontal resize divider */
#mainColumnResizer {
width: 12px !important;
@@ -2568,9 +2794,43 @@ body {
}
.asr-editor-table td {
- padding: 0.25rem; /* Reduced padding */
+ padding: 0; /* No padding - let inputs fill the cell */
vertical-align: middle;
- border: 1px solid var(--border-primary);
+ border: 1px solid var(--border-secondary);
+}
+
+/* More visible borders in dark mode */
+.dark .asr-editor-table,
+.dark .asr-editor-table th,
+.dark .asr-editor-table td {
+ border-color: rgba(148, 163, 184, 0.3); /* slate-400 with opacity for visibility */
+}
+
+/* ASR Editor inputs - blend into table cells */
+.asr-editor-table input,
+.asr-editor-table textarea {
+ border-radius: 0 !important; /* Override global rounded corners */
+ margin: 0;
+ display: block;
+ min-height: 100%;
+}
+
+.asr-editor-table textarea {
+ vertical-align: top;
+ min-height: 2.5rem; /* Minimum height for single line */
+ line-height: 1.5;
+}
+
+/* Sticky header for ASR editor table */
+.asr-editor-table thead {
+ position: sticky;
+ top: 0;
+ z-index: 10;
+}
+
+.asr-editor-table thead th {
+ background-color: var(--bg-tertiary);
+ border-collapse: collapse;
}
/* Custom Number Input with Subtle Spinners */
diff --git a/static/js/app.js b/static/js/app.js
deleted file mode 100644
index 65ab140f..00000000
--- a/static/js/app.js
+++ /dev/null
@@ -1,6170 +0,0 @@
-const { createApp, ref, reactive, computed, onMounted, watch, nextTick } = Vue;
-
-// Wait for the DOM to be fully loaded before mounting the Vue app
-document.addEventListener('DOMContentLoaded', async () => {
- // Initialize i18n before creating Vue app
- if (window.i18n) {
- const appElement = document.getElementById('app');
- const userLang = appElement?.dataset.userLanguage || localStorage.getItem('preferredLanguage') || 'en';
- await window.i18n.init(userLang);
- console.log('i18n initialized with language:', userLang);
- }
-
- // CSRF Token Integration with Vue.js
- const csrfToken = ref(document.querySelector('meta[name="csrf-token"]')?.getAttribute('content'));
-
- // Register Service Worker
- if ('serviceWorker' in navigator) {
- window.addEventListener('load', () => {
- navigator.serviceWorker.register('/static/sw.js')
- .then(registration => {
- console.log('ServiceWorker registration successful with scope: ', registration.scope);
- })
- .catch(error => {
- console.log('ServiceWorker registration failed: ', error);
- });
- });
- }
-
- // Create a safe t function that's always available
- const safeT = (key, params = {}) => {
- if (!window.i18n || !window.i18n.t) {
- return key; // Return key as fallback without warning during initial render
- }
- return window.i18n.t(key, params);
- };
-
- const app = createApp({
- setup() {
- // --- Core State ---
- const currentView = ref('upload'); // 'upload' or 'recording'
- const dragover = ref(false);
- const recordings = ref([]);
- const selectedRecording = ref(null);
- const selectedTab = ref('summary'); // 'summary' or 'notes'
- const searchQuery = ref('');
- const isLoadingRecordings = ref(true);
- const globalError = ref(null);
-
- // Advanced filter state
- const showAdvancedFilters = ref(false);
- const filterTags = ref([]); // Selected tag IDs for filtering
- const filterDateRange = ref({ start: '', end: '' });
- const filterDatePreset = ref(''); // 'today', 'yesterday', 'week', 'month', etc.
- const filterTextQuery = ref('');
-
- // --- Pagination State ---
- const currentPage = ref(1);
- const perPage = ref(25);
- const totalRecordings = ref(0);
- const totalPages = ref(0);
- const hasNextPage = ref(false);
- const hasPrevPage = ref(false);
- const isLoadingMore = ref(false);
- const searchDebounceTimer = ref(null);
-
- // --- Enhanced Search & Organization State ---
- const sortBy = ref('created_at'); // 'created_at' or 'meeting_date'
- const selectedTagFilter = ref(null); // For filtering by clicked tag
-
- // --- UI State ---
- const browser = ref('unknown');
- const isSidebarCollapsed = ref(false);
- const searchTipsExpanded = ref(false);
- const isUserMenuOpen = ref(false);
- const isDarkMode = ref(false);
- const currentColorScheme = ref('blue');
- const showColorSchemeModal = ref(false);
- const windowWidth = ref(window.innerWidth);
- const mobileTab = ref('transcript');
- const isMetadataExpanded = ref(false);
-
- // --- i18n State ---
- const currentLanguage = ref('en');
- const currentLanguageName = ref('English');
- const availableLanguages = ref([]);
- const showLanguageMenu = ref(false);
-
- // --- Upload State ---
- const uploadQueue = ref([]);
- const currentlyProcessingFile = ref(null);
- const processingProgress = ref(0);
- const processingMessage = ref('');
- const isProcessingActive = ref(false);
- const pollInterval = ref(null);
- const progressPopupMinimized = ref(false);
- const progressPopupClosed = ref(false);
- const maxFileSizeMB = ref(250); // Default value, will be updated from API
- const chunkingEnabled = ref(true); // Default value, will be updated from API
- const chunkingMode = ref('size'); // 'size' or 'duration', will be updated from API
- const chunkingLimit = ref(20); // Value in MB or seconds, will be updated from API
- const chunkingLimitDisplay = ref('20MB'); // Human readable display, will be updated from API
- const recordingDisclaimer = ref(''); // Recording disclaimer text from admin settings
- const showRecordingDisclaimerModal = ref(false); // Controls disclaimer modal visibility
- const pendingRecordingMode = ref(null); // Stores the recording mode while showing disclaimer
-
- // --- Audio Recording State ---
- const isRecording = ref(false);
- const mediaRecorder = ref(null);
- const audioChunks = ref([]);
- const audioBlobURL = ref(null);
- const recordingTime = ref(0);
- const recordingInterval = ref(null);
- const canRecordAudio = ref(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);
- const canRecordSystemAudio = ref(false);
- const systemAudioSupported = ref(false);
- const systemAudioError = ref('');
- const recordingNotes = ref('');
- const showSystemAudioHelp = ref(false);
- // ASR options for recording view
- const asrLanguage = ref(''); // Empty string for auto-detect
- const asrMinSpeakers = ref(''); // Empty string for auto-detect
- const asrMaxSpeakers = ref(''); // Empty string for auto-detect
- const audioContext = ref(null);
- const analyser = ref(null);
- const micAnalyser = ref(null);
- const systemAnalyser = ref(null);
- const visualizer = ref(null);
- const micVisualizer = ref(null);
- const systemVisualizer = ref(null);
- const animationFrameId = ref(null);
- const recordingMode = ref('microphone'); // 'microphone', 'system', or 'both'
- const activeStreams = ref([]); // Track active streams for cleanup
-
- // --- Wake Lock and Background Recording ---
- const wakeLock = ref(null); // Screen wake lock to prevent screen from turning off
- const recordingNotification = ref(null); // Persistent notification during recording
- const isPageVisible = ref(true); // Track page visibility state
-
- // --- Recording Size Monitoring ---
- const estimatedFileSize = ref(0);
- const fileSizeWarningShown = ref(false);
- const recordingQuality = ref('optimized'); // 'optimized', 'standard', 'high'
- const actualBitrate = ref(0);
- const maxRecordingMB = ref(200); // Maximum recording size before auto-stop
- const sizeCheckInterval = ref(null);
-
- // Advanced Options for ASR
- const showAdvancedOptions = ref(false);
- const uploadLanguage = ref(''); // Empty string for auto-detect
- const uploadMinSpeakers = ref(''); // Empty string for auto-detect
- const uploadMaxSpeakers = ref(''); // Empty string for auto-detect
-
- // Tag Selection
- const availableTags = ref([]);
- const selectedTagIds = ref([]); // Changed to array for multiple selection
- const uploadTagSearchFilter = ref(''); // For filtering tags in upload view
- const selectedTags = computed(() => {
- return selectedTagIds.value.map(tagId =>
- availableTags.value.find(tag => tag.id == tagId)
- ).filter(Boolean); // Filter out undefined tags
- });
-
- // Computed property for filtered available tags in upload view
- const filteredAvailableTagsForUpload = computed(() => {
- const availableForSelection = availableTags.value.filter(tag => !selectedTagIds.value.includes(tag.id));
- if (!uploadTagSearchFilter.value) return availableForSelection;
-
- const filter = uploadTagSearchFilter.value.toLowerCase();
- return availableForSelection.filter(tag =>
- tag.name.toLowerCase().includes(filter)
- );
- });
-
- // --- Modal State ---
- const showEditModal = ref(false);
- const showDeleteModal = ref(false);
- const showEditTagsModal = ref(false);
- const selectedNewTagId = ref('');
- const tagSearchFilter = ref(''); // For filtering tags in the modal
- const showReprocessModal = ref(false);
- const showResetModal = ref(false);
- const showSpeakerModal = ref(false);
- const showShareModal = ref(false);
- const showSharesListModal = ref(false);
- const showTextEditorModal = ref(false);
- const showAsrEditorModal = ref(false);
- const editingRecording = ref(null);
- const editingTranscriptionContent = ref('');
- const editingSegments = ref([]);
- const availableSpeakers = ref([]);
- const recordingToShare = ref(null);
- const shareOptions = reactive({
- share_summary: true,
- share_notes: true,
- });
- const generatedShareLink = ref('');
- const existingShareDetected = ref(false);
- const userShares = ref([]);
- const isLoadingShares = ref(false);
- const shareToDelete = ref(null);
- const showShareDeleteModal = ref(false);
- const recordingToDelete = ref(null);
- const recordingToReset = ref(null);
- const reprocessType = ref(null); // 'transcription' or 'summary'
- const reprocessRecording = ref(null);
- const isAutoIdentifying = ref(false);
- const asrReprocessOptions = reactive({
- language: '',
- min_speakers: null,
- max_speakers: null
- });
- const summaryReprocessPromptSource = ref('default'); // 'default', 'tag', or 'custom'
- const summaryReprocessSelectedTagId = ref('');
- const summaryReprocessCustomPrompt = ref('');
- const speakerMap = ref({});
- const regenerateSummaryAfterSpeakerUpdate = ref(true);
- const speakerSuggestions = ref({});
- const loadingSuggestions = ref({});
- const activeSpeakerInput = ref(null);
-
- // --- Transcript Editing State ---
- const editingSegmentIndex = ref(null);
- const editingSpeakerIndex = ref(null);
- const showEditTextModal = ref(false);
- const editedText = ref('');
- const showAddSpeakerModal = ref(false);
- const newSpeakerName = ref('');
- const newSpeakerIsMe = ref(false);
- const editedTranscriptData = ref(null);
-
- // --- Inline Editing State ---
- const editingParticipants = ref(false);
- const editingMeetingDate = ref(false);
- const editingSummary = ref(false);
- const editingNotes = ref(false);
- const tempNotesContent = ref('');
- const tempSummaryContent = ref('');
- const autoSaveTimer = ref(null);
- const autoSaveDelay = 2000; // 2 seconds debounce
-
- // --- Markdown Editor State ---
- const notesMarkdownEditor = ref(null);
- const markdownEditorInstance = ref(null);
- const summaryMarkdownEditor = ref(null);
- const summaryMarkdownEditorInstance = ref(null);
- const recordingNotesEditor = ref(null);
- const recordingMarkdownEditorInstance = ref(null);
-
- // --- Transcription State ---
- const transcriptionViewMode = ref('simple'); // 'simple' or 'bubble'
- const legendExpanded = ref(false);
- const highlightedSpeaker = ref(null);
-
- // --- Chat State ---
- const showChat = ref(false);
- const isChatMaximized = ref(false);
- const chatMessages = ref([]);
- const chatInput = ref('');
- const isChatLoading = ref(false);
- const chatMessagesRef = ref(null);
-
- // --- Audio Player State ---
- const playerVolume = ref(1.0);
-
- // --- Column Resizing State ---
- const leftColumnWidth = ref(60); // 60% for left column (transcript)
- const rightColumnWidth = ref(40); // 40% for right column (summary/chat)
- const isResizing = ref(false);
-
- // --- App Configuration ---
- const useAsrEndpoint = ref(false);
- const currentUserName = ref('');
-
- // --- Computed Properties ---
- const isMobileScreen = computed(() => {
- return windowWidth.value < 1024;
- });
-
- const datePresetOptions = computed(() => {
- return [
- { value: 'today', label: t('sidebar.today') },
- { value: 'yesterday', label: t('sidebar.yesterday') },
- { value: 'thisweek', label: t('sidebar.thisWeek') },
- { value: 'lastweek', label: t('sidebar.lastWeek') },
- { value: 'thismonth', label: t('sidebar.thisMonth') },
- { value: 'lastmonth', label: t('sidebar.lastMonth') }
- ];
- });
-
- const languageOptions = computed(() => {
- return [
- { value: '', label: t('form.autoDetect') },
- { value: 'en', label: t('languages.en') },
- { value: 'es', label: t('languages.es') },
- { value: 'fr', label: t('languages.fr') },
- { value: 'de', label: t('languages.de') },
- { value: 'it', label: t('languages.it') },
- { value: 'pt', label: t('languages.pt') },
- { value: 'nl', label: t('languages.nl') },
- { value: 'ru', label: t('languages.ru') },
- { value: 'zh', label: t('languages.zh') },
- { value: 'ja', label: t('languages.ja') },
- { value: 'ko', label: t('languages.ko') }
- ];
- });
-
- const filteredRecordings = computed(() => {
- return recordings.value;
- });
-
- const highlightedTranscript = computed(() => {
- if (!selectedRecording.value?.transcription) return '';
- let html = selectedRecording.value.transcription;
- // Escape HTML to prevent injection, but keep it minimal
- html = html.replace(/</g, '<').replace(/>/g, '>');
-
- // 1. Replace newlines with <br> tags for proper line breaks in HTML
- html = html.replace(/\n/g, '<br>');
-
- // 2. Get speaker colors from the speakerMap if available
- const speakerColors = {};
- if (speakerMap.value) {
- Object.keys(speakerMap.value).forEach((speaker, index) => {
- speakerColors[speaker] = speakerMap.value[speaker].color || `speaker-color-${(index % 8) + 1}`;
- });
- }
-
- // 3. Wrap each speaker tag in a span for styling and interaction with colors
- html = html.replace(/\[([^\]]+)\]/g, (match, speakerId) => {
- const isHighlighted = speakerId === highlightedSpeaker.value;
- const colorClass = speakerColors[speakerId] || '';
- // Replace speaker ID with name if available
- const displayName = speakerMap.value[speakerId]?.name || speakerId;
- const displayText = `[${displayName}]`;
- // Use a more specific and stylish class structure with color
- return `<span class="speaker-tag ${colorClass} ${isHighlighted ? 'speaker-highlight' : ''}" data-speaker-id="${speakerId}">${displayText}</span>`;
- });
-
- return html;
- });
-
- const activeRecordingMetadata = computed(() => {
- if (!selectedRecording.value) return [];
-
- const recording = selectedRecording.value;
- const metadata = [];
-
- if (recording.created_at) {
- metadata.push({
- icon: 'fas fa-history',
- text: formatDisplayDate(recording.created_at)
- });
- }
-
- if (recording.file_size) {
- metadata.push({
- icon: 'fas fa-file-audio',
- text: formatFileSize(recording.file_size)
- });
- }
-
- if (recording.duration) {
- metadata.push({
- icon: 'fas fa-clock',
- text: formatDuration(recording.duration)
- });
- }
-
- if (recording.original_filename) {
- const maxLength = 30;
- const truncated = recording.original_filename.length > maxLength
- ? recording.original_filename.substring(0, maxLength) + '...'
- : recording.original_filename;
- metadata.push({
- icon: 'fas fa-file',
- text: truncated,
- fullText: recording.original_filename
- });
- }
-
- // Add tags to metadata
- if (recording.tags && recording.tags.length > 0) {
- metadata.push({
- icon: 'fas fa-tags',
- text: '', // Empty text since we'll render tags specially
- tags: recording.tags, // Pass the tags array
- isTagItem: true // Flag to identify this as a tag item
- });
- }
-
- return metadata;
- });
-
- const groupedRecordings = computed(() => {
- // Sort recordings based on the selected sort criteria
- const sortedRecordings = [...filteredRecordings.value].sort((a, b) => {
- const dateA = getDateForSorting(a);
- const dateB = getDateForSorting(b);
-
- // Handle null dates (put them at the end)
- if (!dateA && !dateB) return 0;
- if (!dateA) return 1;
- if (!dateB) return -1;
-
- return dateB - dateA; // Most recent first
- });
-
- const groups = {
- today: [],
- yesterday: [],
- thisWeek: [],
- lastWeek: [],
- thisMonth: [],
- lastMonth: [],
- older: []
- };
-
- sortedRecordings.forEach(recording => {
- const date = getDateForSorting(recording);
- if (!date) {
- groups.older.push(recording);
- return;
- }
-
- if (isToday(date)) {
- groups.today.push(recording);
- } else if (isYesterday(date)) {
- groups.yesterday.push(recording);
- } else if (isThisWeek(date)) {
- groups.thisWeek.push(recording);
- } else if (isLastWeek(date)) {
- groups.lastWeek.push(recording);
- } else if (isThisMonth(date)) {
- groups.thisMonth.push(recording);
- } else if (isLastMonth(date)) {
- groups.lastMonth.push(recording);
- } else {
- groups.older.push(recording);
- }
- });
-
- return [
- { title: t('sidebar.today'), items: groups.today },
- { title: t('sidebar.yesterday'), items: groups.yesterday },
- { title: t('sidebar.thisWeek'), items: groups.thisWeek },
- { title: t('sidebar.lastWeek'), items: groups.lastWeek },
- { title: t('sidebar.thisMonth'), items: groups.thisMonth },
- { title: t('sidebar.lastMonth'), items: groups.lastMonth },
- { title: t('sidebar.older'), items: groups.older }
- ].filter(g => g.items.length > 0);
- });
-
- const totalInQueue = computed(() => uploadQueue.value.length);
- const completedInQueue = computed(() => uploadQueue.value.filter(item => item.status === 'completed' || item.status === 'failed').length);
- const finishedFilesInQueue = computed(() => uploadQueue.value.filter(item => ['completed', 'failed'].includes(item.status)));
-
- const clearCompletedUploads = () => {
- uploadQueue.value = uploadQueue.value.filter(item => !['completed', 'failed'].includes(item.status));
- };
-
- const identifiedSpeakers = computed(() => {
- // Ensure we have a valid recording and transcription
- if (!selectedRecording.value?.transcription) {
- return [];
- }
-
- const transcription = selectedRecording.value.transcription;
- let transcriptionData;
-
- try {
- transcriptionData = JSON.parse(transcription);
- } catch (e) {
- transcriptionData = null;
- }
-
- // Updated to handle new simplified JSON format (array of segments)
- if (transcriptionData && Array.isArray(transcriptionData)) {
- // JSON format - extract speakers in order of appearance
- const speakersInOrder = [];
- const seenSpeakers = new Set();
- transcriptionData.forEach(segment => {
- if (segment.speaker && String(segment.speaker).trim() && !seenSpeakers.has(segment.speaker)) {
- seenSpeakers.add(segment.speaker);
- speakersInOrder.push(segment.speaker);
- }
- });
- return speakersInOrder; // Keep order of appearance, don't sort
- } else if (typeof transcription === 'string') {
- // Plain text format - find speakers in order of appearance
- const speakerRegex = /\[([^\]]+)\]:/g;
- const speakersInOrder = [];
- const seenSpeakers = new Set();
- let match;
- while ((match = speakerRegex.exec(transcription)) !== null) {
- const speaker = match[1].trim();
- if (speaker && !seenSpeakers.has(speaker)) {
- seenSpeakers.add(speaker);
- speakersInOrder.push(speaker);
- }
- }
- return speakersInOrder; // Keep order of appearance, don't sort
- }
- return [];
- });
-
- // identifiedSpeakersInOrder is now just an alias since identifiedSpeakers already preserves order
- const identifiedSpeakersInOrder = computed(() => {
- return identifiedSpeakers.value;
- });
-
- const hasSpeakerNames = computed(() => {
- // Check if any speaker has a non-empty name
- return Object.values(speakerMap.value).some(speakerData =>
- speakerData.name && speakerData.name.trim() !== ''
- );
- });
-
- const processedTranscription = computed(() => {
- if (!selectedRecording.value?.transcription) {
- return { hasDialogue: false, content: '', speakers: [], simpleSegments: [], bubbleRows: [] };
- }
-
- const transcription = selectedRecording.value.transcription;
- let transcriptionData;
-
- try {
- transcriptionData = JSON.parse(transcription);
- } catch (e) {
- transcriptionData = null;
- }
-
- // Handle new simplified JSON format (array of segments)
- if (transcriptionData && Array.isArray(transcriptionData)) {
- const wasDiarized = transcriptionData.some(segment => segment.speaker);
-
- if (!wasDiarized) {
- const segments = transcriptionData.map(segment => ({
- sentence: segment.sentence,
- startTime: segment.start_time,
- }));
- return {
- hasDialogue: false,
- isJson: true,
- content: segments.map(s => s.sentence).join('\n'),
- simpleSegments: segments,
- speakers: [],
- bubbleRows: []
- };
- }
-
- // Extract unique speakers
- const speakers = [...new Set(transcriptionData.map(segment => segment.speaker).filter(Boolean))];
- const speakerColors = {};
- speakers.forEach((speaker, index) => {
- speakerColors[speaker] = `speaker-color-${(index % 8) + 1}`;
- });
-
- const simpleSegments = transcriptionData.map(segment => ({
- speakerId: segment.speaker,
- speaker: speakerMap.value[segment.speaker]?.name || segment.speaker,
- sentence: segment.sentence,
- startTime: segment.start_time || segment.startTime,
- endTime: segment.end_time || segment.endTime,
- color: speakerColors[segment.speaker] || 'speaker-color-1'
- }));
-
- const processedSimpleSegments = [];
- let lastSpeakerId = null;
- simpleSegments.forEach(segment => {
- processedSimpleSegments.push({
- ...segment,
- showSpeaker: segment.speakerId !== lastSpeakerId
- });
- lastSpeakerId = segment.speakerId;
- });
-
- const bubbleRows = [];
- let lastBubbleSpeakerId = null;
- simpleSegments.forEach(segment => {
- if (bubbleRows.length === 0 || segment.speakerId !== lastBubbleSpeakerId) {
- bubbleRows.push({
- speaker: segment.speaker,
- color: segment.color,
- isMe: segment.speaker && (typeof segment.speaker === 'string') && segment.speaker.toLowerCase().includes('me'),
- bubbles: []
- });
- lastBubbleSpeakerId = segment.speakerId;
- }
- bubbleRows[bubbleRows.length - 1].bubbles.push({
- sentence: segment.sentence,
- startTime: segment.startTime || segment.start_time,
- color: segment.color
- });
- });
-
- return {
- hasDialogue: true,
- isJson: true,
- segments: simpleSegments,
- simpleSegments: processedSimpleSegments,
- bubbleRows: bubbleRows,
- speakers: speakers.map(speaker => ({
- name: speakerMap.value[speaker]?.name || speaker,
- color: speakerColors[speaker]
- }))
- };
-
- } else {
- // Fallback for plain text transcription
- const speakerRegex = /\[([^\]]+)\]:\s*/g;
- const hasDialogue = speakerRegex.test(transcription);
-
- if (!hasDialogue) {
- return {
- hasDialogue: false,
- isJson: false,
- content: transcription,
- speakers: [],
- simpleSegments: [],
- bubbleRows: []
- };
- }
-
- speakerRegex.lastIndex = 0;
- const speakers = new Set();
- let match;
- while ((match = speakerRegex.exec(transcription)) !== null) {
- speakers.add(match[1]);
- }
-
- const speakerList = Array.from(speakers);
- const speakerColors = {};
- speakerList.forEach((speaker, index) => {
- speakerColors[speaker] = `speaker-color-${(index % 8) + 1}`;
- });
-
- const segments = [];
- const lines = transcription.split('\n');
- let currentSpeakerId = null;
- let currentText = '';
-
- for (const line of lines) {
- const speakerMatch = line.match(/^\[([^\]]+)\]:\s*(.*)$/);
- if (speakerMatch) {
- if (currentSpeakerId && currentText.trim()) {
- segments.push({
- speakerId: currentSpeakerId,
- speaker: speakerMap.value[currentSpeakerId]?.name || currentSpeakerId,
- sentence: currentText.trim(),
- color: speakerColors[currentSpeakerId] || 'speaker-color-1'
- });
- }
- currentSpeakerId = speakerMatch[1];
- currentText = speakerMatch[2];
- } else if (currentSpeakerId && line.trim()) {
- currentText += ' ' + line.trim();
- } else if (!currentSpeakerId && line.trim()) {
- segments.push({
- speakerId: null,
- speaker: null,
- sentence: line.trim(),
- color: 'speaker-color-1'
- });
- }
- }
-
- if (currentSpeakerId && currentText.trim()) {
- segments.push({
- speakerId: currentSpeakerId,
- speaker: speakerMap.value[currentSpeakerId]?.name || currentSpeakerId,
- sentence: currentText.trim(),
- color: speakerColors[currentSpeakerId] || 'speaker-color-1'
- });
- }
-
- const simpleSegments = [];
- let lastSpeakerId = null;
- segments.forEach(segment => {
- simpleSegments.push({
- ...segment,
- showSpeaker: segment.speakerId !== lastSpeakerId,
- sentence: segment.sentence || segment.text
- });
- lastSpeakerId = segment.speakerId;
- });
-
- const bubbleRows = [];
- let currentRow = null;
- segments.forEach(segment => {
- if (!currentRow || currentRow.speakerId !== segment.speakerId) {
- if (currentRow) bubbleRows.push(currentRow);
- currentRow = {
- speakerId: segment.speakerId,
- speaker: segment.speaker,
- color: segment.color,
- bubbles: [],
- isMe: segment.speaker && segment.speaker.toLowerCase().includes('me')
- };
- }
- currentRow.bubbles.push({
- sentence: segment.sentence,
- color: segment.color
- });
- });
- if (currentRow) bubbleRows.push(currentRow);
-
- return {
- hasDialogue: true,
- isJson: false,
- segments: segments,
- simpleSegments: simpleSegments,
- bubbleRows: bubbleRows,
- speakers: speakerList.map(speaker => ({
- name: speakerMap.value[speaker]?.name || speaker,
- color: speakerColors[speaker] || 'speaker-color-1'
- }))
- };
- }
- });
-
- // --- Color Scheme Management ---
- const colorSchemes = {
- light: [
- { id: 'blue', name: 'Ocean Blue', description: 'Classic blue theme with professional appeal', class: '' },
- { id: 'emerald', name: 'Forest Emerald', description: 'Fresh green theme for a natural feel', class: 'theme-light-emerald' },
- { id: 'purple', name: 'Royal Purple', description: 'Elegant purple theme with sophistication', class: 'theme-light-purple' },
- { id: 'rose', name: 'Sunset Rose', description: 'Warm pink theme with gentle energy', class: 'theme-light-rose' },
- { id: 'amber', name: 'Golden Amber', description: 'Warm yellow theme for brightness', class: 'theme-light-amber' },
- { id: 'teal', name: 'Ocean Teal', description: 'Cool teal theme for tranquility', class: 'theme-light-teal' }
- ],
- dark: [
- { id: 'blue', name: 'Midnight Blue', description: 'Deep blue theme for focused work', class: '' },
- { id: 'emerald', name: 'Dark Forest', description: 'Rich green theme for comfortable viewing', class: 'theme-dark-emerald' },
- { id: 'purple', name: 'Deep Purple', description: 'Mysterious purple theme for creativity', class: 'theme-dark-purple' },
- { id: 'rose', name: 'Dark Rose', description: 'Muted pink theme with subtle warmth', class: 'theme-dark-rose' },
- { id: 'amber', name: 'Dark Amber', description: 'Warm brown theme for cozy sessions', class: 'theme-dark-amber' },
- { id: 'teal', name: 'Deep Teal', description: 'Dark teal theme for calm focus', class: 'theme-dark-teal' }
- ]
- };
-
- // --- Utility Methods ---
- const setGlobalError = (message, duration = 7000) => {
- globalError.value = message;
- if (duration > 0) {
- setTimeout(() => { if (globalError.value === message) globalError.value = null; }, duration);
- }
- };
-
- const formatFileSize = (bytes) => {
- if (bytes == null || bytes === 0) return '0 Bytes';
- const k = 1024;
- const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
- if (bytes < 0) bytes = 0;
- const i = bytes === 0 ? 0 : Math.max(0, Math.floor(Math.log(bytes) / Math.log(k)));
- const size = i === 0 ? bytes : parseFloat((bytes / Math.pow(k, i)).toFixed(2));
- return size + ' ' + sizes[i];
- };
-
- const formatDisplayDate = (dateString) => {
- if (!dateString) return '';
- try {
- // Try to parse the date string directly first (it might already be formatted)
- let date = new Date(dateString);
-
- // If that fails or results in invalid date, try different approaches
- if (isNaN(date.getTime())) {
- // Try appending time if it looks like a date-only string (YYYY-MM-DD format)
- if (/^\d{4}-\d{2}-\d{2}$/.test(dateString)) {
- date = new Date(dateString + 'T00:00:00');
- } else {
- // If it's already a formatted string, just return it
- return dateString;
- }
- }
-
- // If we still have an invalid date, return the original string
- if (isNaN(date.getTime())) {
- return dateString;
- }
-
- return date.toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' });
- } catch (e) {
- console.error("Error formatting date:", e);
- return dateString;
- }
- };
-
- const formatStatus = (status) => {
- if (!status || status === 'COMPLETED') return '';
- const statusMap = {
- 'PENDING': t('status.queued'),
- 'PROCESSING': t('status.processing'),
- 'TRANSCRIBING': t('status.transcribing'),
- 'SUMMARIZING': t('status.summarizing'),
- 'FAILED': t('status.failed'),
- 'UPLOADING': t('status.uploading')
- };
- return statusMap[status] || status.charAt(0).toUpperCase() + status.slice(1).toLowerCase();
- };
-
- const getStatusClass = (status) => {
- switch(status) {
- case 'PENDING': return 'status-pending';
- case 'PROCESSING': return 'status-processing';
- case 'SUMMARIZING': return 'status-summarizing';
- case 'COMPLETED': return '';
- case 'FAILED': return 'status-failed';
- default: return 'status-pending';
- }
- };
-
- const formatTime = (seconds) => {
- const minutes = Math.floor(seconds / 60);
- const secs = seconds % 60;
- return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
- };
-
- const formatDuration = (totalSeconds) => {
- if (totalSeconds == null || totalSeconds < 0) return 'N/A';
-
- if (totalSeconds < 1) {
- return `${totalSeconds.toFixed(2)} seconds`;
- }
-
- totalSeconds = Math.round(totalSeconds);
-
- if (totalSeconds < 60) {
- return `${totalSeconds} sec`;
- }
-
- const hours = Math.floor(totalSeconds / 3600);
- const minutes = Math.floor((totalSeconds % 3600) / 60);
- const seconds = totalSeconds % 60;
-
- let parts = [];
- if (hours > 0) {
- parts.push(`${hours} hr`);
- }
- if (minutes > 0) {
- parts.push(`${minutes} min`);
- }
- // Only show seconds if duration is less than an hour
- if (hours === 0 && seconds > 0) {
- parts.push(`${seconds} sec`);
- }
-
- return parts.join(' ');
- };
-
- // --- Recording Size Monitoring Functions ---
- const updateFileSizeEstimate = () => {
- if (!isRecording.value || !actualBitrate.value) return;
-
- // Calculate estimated size based on recording time and bitrate
- const recordingTimeSeconds = recordingTime.value;
- const estimatedBits = actualBitrate.value * recordingTimeSeconds;
- const estimatedBytes = estimatedBits / 8;
- estimatedFileSize.value = estimatedBytes;
-
- // Check if we're approaching the size limit
- const sizeMB = estimatedBytes / (1024 * 1024);
- const warningThresholdMB = maxRecordingMB.value * 0.8; // 80% of max size
-
- if (sizeMB > warningThresholdMB && !fileSizeWarningShown.value) {
- fileSizeWarningShown.value = true;
- showToast(`Recording size is ${formatFileSize(estimatedBytes)}. Consider stopping soon to avoid auto-stop at ${maxRecordingMB.value}MB.`, 'fa-exclamation-triangle', 5000);
- }
-
- // Auto-stop if we exceed the maximum size
- if (sizeMB > maxRecordingMB.value) {
- console.log(`Auto-stopping recording: size ${formatFileSize(estimatedBytes)} exceeds limit of ${maxRecordingMB.value}MB`);
- stopRecording();
- showToast(`Recording automatically stopped at ${formatFileSize(estimatedBytes)} to prevent excessive file size.`, 'fa-stop-circle', 7000);
- }
- };
-
- const startSizeMonitoring = () => {
- if (sizeCheckInterval.value) {
- clearInterval(sizeCheckInterval.value);
- }
-
- // Reset size monitoring state
- estimatedFileSize.value = 0;
- fileSizeWarningShown.value = false;
-
- // Start monitoring every 5 seconds
- sizeCheckInterval.value = setInterval(updateFileSizeEstimate, 5000);
- };
-
- const stopSizeMonitoring = () => {
- if (sizeCheckInterval.value) {
- clearInterval(sizeCheckInterval.value);
- sizeCheckInterval.value = null;
- }
- };
-
- // --- Enhanced Date Utility Functions ---
- const getDateForSorting = (recording) => {
- const dateStr = sortBy.value === 'meeting_date' ? recording.meeting_date : recording.created_at;
- if (!dateStr) return null;
- return new Date(dateStr);
- };
-
- const isToday = (date) => {
- const today = new Date();
- return isSameDay(date, today);
- };
-
- const isYesterday = (date) => {
- const yesterday = new Date();
- yesterday.setDate(yesterday.getDate() - 1);
- return isSameDay(date, yesterday);
- };
-
- const isThisWeek = (date) => {
- const now = new Date();
- const startOfWeek = new Date(now);
- const day = now.getDay();
- const diff = now.getDate() - day + (day === 0 ? -6 : 1); // Monday as start of week
- startOfWeek.setDate(diff);
- startOfWeek.setHours(0, 0, 0, 0);
-
- const endOfWeek = new Date(startOfWeek);
- endOfWeek.setDate(startOfWeek.getDate() + 6);
- endOfWeek.setHours(23, 59, 59, 999);
-
- return date >= startOfWeek && date <= endOfWeek;
- };
-
- const isLastWeek = (date) => {
- const now = new Date();
- const startOfLastWeek = new Date(now);
- const day = now.getDay();
- const diff = now.getDate() - day + (day === 0 ? -6 : 1) - 7; // Previous Monday
- startOfLastWeek.setDate(diff);
- startOfLastWeek.setHours(0, 0, 0, 0);
-
- const endOfLastWeek = new Date(startOfLastWeek);
- endOfLastWeek.setDate(startOfLastWeek.getDate() + 6);
- endOfLastWeek.setHours(23, 59, 59, 999);
-
- return date >= startOfLastWeek && date <= endOfLastWeek;
- };
-
- const isThisMonth = (date) => {
- const now = new Date();
- return date.getFullYear() === now.getFullYear() && date.getMonth() === now.getMonth();
- };
-
- const isLastMonth = (date) => {
- const now = new Date();
- const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
- return date.getFullYear() === lastMonth.getFullYear() && date.getMonth() === lastMonth.getMonth();
- };
-
- const isSameDay = (date1, date2) => {
- return date1.getFullYear() === date2.getFullYear() &&
- date1.getMonth() === date2.getMonth() &&
- date1.getDate() === date2.getDate();
- };
-
- const reprocessTranscription = (recordingId) => {
- const recording = recordings.value.find(r => r.id === recordingId) || selectedRecording.value;
- confirmReprocess('transcription', recording);
- };
-
- const reprocessSummary = (recordingId) => {
- const recording = recordings.value.find(r => r.id === recordingId) || selectedRecording.value;
- confirmReprocess('summary', recording);
- };
-
- const generateSummary = async () => {
- if (!selectedRecording.value) return;
-
- try {
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
-
- const response = await fetch(`/recording/${selectedRecording.value.id}/generate_summary`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': csrfToken
- }
- });
-
- const data = await response.json();
-
- if (!response.ok) {
- throw new Error(data.error || 'Failed to generate summary');
- }
-
- // Update the recording status to show it's being processed
- selectedRecording.value.status = 'SUMMARIZING';
-
- // Also update in recordings list if it exists
- const recordingInList = recordings.value.find(r => r.id === selectedRecording.value.id);
- if (recordingInList) {
- recordingInList.status = 'SUMMARIZING';
- }
-
- showToast('Summary generation started', 'success');
-
- } catch (error) {
- console.error('Error generating summary:', error);
- setGlobalError(`Failed to generate summary: ${error.message}`);
- }
- };
-
- const resetRecordingStatus = async (recordingId) => {
- const recording = recordings.value.find(r => r.id === recordingId);
- if (!recording) return;
-
- try {
- const response = await fetch(`/recording/${recording.id}/reset_status`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- });
- const data = await response.json();
- if (!response.ok) {
- throw new Error(data.error || 'Failed to reset status');
- }
- const index = recordings.value.findIndex(r => r.id === recording.id);
- if (index !== -1) {
- recordings.value[index] = data.recording;
- }
- if (selectedRecording.value?.id === recording.id) {
- selectedRecording.value = data.recording;
- }
- showToast('Recording status has been reset.', 'fa-check-circle');
- } catch (error) {
- setGlobalError(`Failed to reset status: ${error.message}`);
- }
- };
-
- const confirmReprocess = (type, recording) => {
- reprocessType.value = type;
- reprocessRecording.value = recording;
- showReprocessModal.value = true;
- };
-
- const openTranscriptionEditor = () => {
- if (processedTranscription.value.isJson) {
- openAsrEditorModal();
- } else {
- openTextEditorModal();
- }
- };
-
- const openTextEditorModal = () => {
- if (!selectedRecording.value) return;
- editingTranscriptionContent.value = selectedRecording.value.transcription;
- showTextEditorModal.value = true;
- };
-
- const closeTextEditorModal = () => {
- showTextEditorModal.value = false;
- editingTranscriptionContent.value = '';
- };
-
- const saveTranscription = async () => {
- if (!selectedRecording.value) return;
- await saveTranscriptionContent(editingTranscriptionContent.value);
- closeTextEditorModal();
- };
-
- const openAsrEditorModal = async () => {
- if (!selectedRecording.value) return;
- try {
- const segments = JSON.parse(selectedRecording.value.transcription);
- editingSegments.value = segments.map((s, i) => ({
- ...s,
- id: i,
- showSuggestions: false,
- filteredSpeakers: []
- }));
-
- // Populate available speakers
- const speakersInTranscript = [...new Set(segments.map(s => s.speaker))];
- const response = await fetch('/speakers');
- const speakersFromDb = await response.json();
- const speakerNamesFromDb = speakersFromDb.map(s => s.name);
- availableSpeakers.value = [...new Set([...speakersInTranscript, ...speakerNamesFromDb])].sort();
-
- showAsrEditorModal.value = true;
- } catch (e) {
- console.error("Could not parse transcription as JSON for ASR editor:", e);
- setGlobalError("This transcription is not in the correct format for the ASR editor.");
- }
- };
-
- const closeAsrEditorModal = () => {
- showAsrEditorModal.value = false;
- editingSegments.value = [];
- availableSpeakers.value = [];
- };
-
- const saveAsrTranscription = async () => {
- const contentToSave = JSON.stringify(editingSegments.value.map(({ id, showSuggestions, filteredSpeakers, ...rest }) => rest));
- await saveTranscriptionContent(contentToSave);
- closeAsrEditorModal();
- };
-
- const adjustTime = (index, field, amount) => {
- if (editingSegments.value[index]) {
- editingSegments.value[index][field] = parseFloat((editingSegments.value[index][field] + amount).toFixed(3));
- }
- };
-
- const filterSpeakers = (index) => {
- const segment = editingSegments.value[index];
- if (segment) {
- const query = segment.speaker.toLowerCase();
- segment.filteredSpeakers = availableSpeakers.value.filter(s => s.toLowerCase().includes(query));
- }
- };
-
- const openSpeakerSuggestions = (index) => {
- if (editingSegments.value[index]) {
- editingSegments.value[index].showSuggestions = true;
- filterSpeakers(index);
- }
- };
-
- const closeSpeakerSuggestions = (index) => {
- if (editingSegments.value[index]) {
- window.setTimeout(() => {
- if (editingSegments.value[index]) {
- editingSegments.value[index].showSuggestions = false;
- }
- }, 200); // Delay to allow click event to register
- }
- };
-
- const selectSpeaker = (index, speaker) => {
- if (editingSegments.value[index]) {
- editingSegments.value[index].speaker = speaker;
- editingSegments.value[index].showSuggestions = false;
- }
- };
-
- const addSegment = () => {
- const lastSegment = editingSegments.value[editingSegments.value.length - 1];
- editingSegments.value.push({
- id: Date.now(),
- speaker: lastSegment ? lastSegment.speaker : 'SPEAKER_00',
- start_time: lastSegment ? lastSegment.end_time : 0,
- end_time: lastSegment ? lastSegment.end_time + 1 : 1,
- sentence: ''
- });
- };
-
- const removeSegment = (index) => {
- editingSegments.value.splice(index, 1);
- };
-
- const saveTranscriptionContent = async (content) => {
- if (!selectedRecording.value) return;
- try {
- const response = await fetch(`/recording/${selectedRecording.value.id}/update_transcription`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ transcription: content })
- });
- const data = await response.json();
- if (!response.ok) throw new Error(data.error || 'Failed to update transcription');
- const index = recordings.value.findIndex(r => r.id === selectedRecording.value.id);
- if (index !== -1) {
- recordings.value[index] = data.recording;
- }
- selectedRecording.value = data.recording;
- showToast('Transcription updated successfully!', 'fa-check-circle');
- } catch (error) {
- console.error('Save Transcription Error:', error);
- setGlobalError(`Failed to save transcription: ${error.message}`);
- }
- };
-
- const cancelReprocess = () => {
- showReprocessModal.value = false;
- reprocessType.value = null;
- reprocessRecording.value = null;
- // Reset summary reprocess options
- summaryReprocessPromptSource.value = 'default';
- summaryReprocessSelectedTagId.value = '';
- summaryReprocessCustomPrompt.value = '';
- };
-
- const executeReprocess = async () => {
- if (!reprocessRecording.value || !reprocessType.value) return;
-
- const recordingId = reprocessRecording.value.id;
- const type = reprocessType.value;
-
- // Save values before closing the modal (cancelReprocess resets them)
- const savedAsrOptions = {
- language: asrReprocessOptions.language,
- min_speakers: asrReprocessOptions.min_speakers,
- max_speakers: asrReprocessOptions.max_speakers
- };
- const savedSummaryPromptSource = summaryReprocessPromptSource.value;
- const savedSummaryTagId = summaryReprocessSelectedTagId.value;
- const savedSummaryCustomPrompt = summaryReprocessCustomPrompt.value;
-
- // Close the modal
- cancelReprocess();
-
- if (type === 'transcription') {
- await performReprocessTranscription(
- recordingId,
- savedAsrOptions.language,
- savedAsrOptions.min_speakers,
- savedAsrOptions.max_speakers
- );
- } else if (type === 'summary') {
- await performReprocessSummary(
- recordingId,
- savedSummaryPromptSource,
- savedSummaryTagId,
- savedSummaryCustomPrompt
- );
- }
- };
-
- const performReprocessTranscription = async (recordingId, language, minSpeakers, maxSpeakers) => {
- if (!recordingId) {
- setGlobalError('No recording ID provided for reprocessing.');
- return;
- }
-
- try {
- const payload = {
- language: language,
- min_speakers: minSpeakers,
- max_speakers: maxSpeakers
- };
-
- const response = await fetch(`/recording/${recordingId}/reprocess_transcription`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
-
- const data = await response.json();
- if (!response.ok) throw new Error(data.error || 'Failed to start transcription reprocessing');
-
- // Ensure the recording status is properly set to PROCESSING
- if (data.recording && data.recording.status !== 'PROCESSING') {
- console.warn(`Warning: Reprocess transcription returned unexpected status: ${data.recording.status}`);
- data.recording.status = 'PROCESSING';
- }
-
- // Update the recording in the UI
- const index = recordings.value.findIndex(r => r.id === recordingId);
- if (index !== -1) {
- recordings.value[index] = data.recording;
- }
-
- // Update selected recording if it's the one being reprocessed
- if (selectedRecording.value?.id === recordingId) {
- selectedRecording.value = data.recording;
- }
-
- showToast('Transcription reprocessing started', 'fa-sync-alt');
-
- // Switch to Summary tab to show progress
- selectedTab.value = 'summary';
-
- // Show progress modal for reprocessing
- showProgressModalForReprocessing(recordingId, 'transcription');
-
- // Start polling for status updates
- startReprocessingPoll(recordingId);
-
- } catch (error) {
- console.error('Reprocess Transcription Error:', error);
- setGlobalError(`Failed to start transcription reprocessing: ${error.message}`);
- }
- };
-
- const performReprocessSummary = async (recordingId, promptSource, selectedTagId, customPrompt) => {
- if (!recordingId) {
- setGlobalError('No recording ID provided for reprocessing.');
- return;
- }
-
- try {
- // Prepare payload with custom prompt data
- const payload = {};
-
- console.log('[Reprocess Summary] Prompt source:', promptSource);
- console.log('[Reprocess Summary] Selected tag ID:', selectedTagId);
- console.log('[Reprocess Summary] Custom prompt:', customPrompt);
-
- if (promptSource === 'tag' && selectedTagId) {
- const selectedTag = availableTags.value.find(t => t.id == selectedTagId);
- if (selectedTag && selectedTag.custom_prompt) {
- payload.custom_prompt = selectedTag.custom_prompt;
- console.log('[Reprocess Summary] Using tag prompt:', selectedTag.name, 'Length:', selectedTag.custom_prompt.length);
- }
- } else if (promptSource === 'custom' && customPrompt && customPrompt.trim()) {
- payload.custom_prompt = customPrompt.trim();
- console.log('[Reprocess Summary] Using custom prompt, Length:', payload.custom_prompt.length);
- }
- // If 'default' is selected or no custom prompt, payload will be empty and backend will use default
-
- console.log('[Reprocess Summary] Final payload:', payload);
-
- const response = await fetch(`/recording/${recordingId}/reprocess_summary`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
-
- const data = await response.json();
- if (!response.ok) throw new Error(data.error || 'Failed to start summary reprocessing');
-
- // Ensure the recording status is properly set to SUMMARIZING
- if (data.recording && data.recording.status !== 'SUMMARIZING') {
- console.warn(`Warning: Reprocess summary returned unexpected status: ${data.recording.status}`);
- data.recording.status = 'SUMMARIZING';
- }
-
- // Update the recording in the UI
- const index = recordings.value.findIndex(r => r.id === recordingId);
- if (index !== -1) {
- recordings.value[index] = data.recording;
- }
-
- // Update selected recording if it's the one being reprocessed
- if (selectedRecording.value?.id === recordingId) {
- selectedRecording.value = data.recording;
- }
-
- showToast('Summary reprocessing started', 'fa-sync-alt');
-
- // Switch to Summary tab to show progress
- selectedTab.value = 'summary';
-
- // Show progress modal for reprocessing
- showProgressModalForReprocessing(recordingId, 'summary');
-
- // Start polling for status updates
- startReprocessingPoll(recordingId);
-
- } catch (error) {
- console.error('Reprocess Summary Error:', error);
- setGlobalError(`Failed to start summary reprocessing: ${error.message}`);
- }
- };
-
- // Show progress modal for reprocessing operations
- const showProgressModalForReprocessing = (recordingId, type) => {
- const recording = recordings.value.find(r => r.id === recordingId);
- if (!recording) return;
-
- // Create a mock file item for the progress modal
- const reprocessItem = {
- file: {
- name: recording.title || `Recording ${recordingId}`,
- size: recording.file_size || 0
- },
- status: 'pending',
- recordingId: recordingId,
- clientId: `reprocess-${type}-${recordingId}-${Date.now()}`,
- error: null,
- isReprocessing: true,
- reprocessType: type
- };
-
- // Add to upload queue for progress tracking
- uploadQueue.value.unshift(reprocessItem);
-
- // Show progress modal
- progressPopupMinimized.value = false;
- progressPopupClosed.value = false;
-
- // Set as currently processing file
- currentlyProcessingFile.value = reprocessItem;
- processingProgress.value = 10;
- processingMessage.value = type === 'transcription' ? 'Starting transcription reprocessing...' : 'Starting summary reprocessing...';
- };
-
- // Polling for reprocessing status updates
- const reprocessingPolls = ref(new Map()); // Track active polls by recording ID
-
- const startReprocessingPoll = (recordingId) => {
- // Clear any existing poll for this recording
- if (reprocessingPolls.value.has(recordingId)) {
- clearInterval(reprocessingPolls.value.get(recordingId));
- }
-
- console.log(`Starting reprocessing poll for recording ${recordingId}`);
-
- const pollInterval = setInterval(async () => {
- try {
- const response = await fetch(`/status/${recordingId}`);
- if (!response.ok) {
- console.error(`Status check failed for recording ${recordingId}`);
- stopReprocessingPoll(recordingId);
- return;
- }
-
- const data = await response.json();
-
- // Update the recording in the UI
- const index = recordings.value.findIndex(r => r.id === recordingId);
- if (index !== -1) {
- recordings.value[index] = data;
- }
-
- // Update selected recording if it's the one being reprocessed
- if (selectedRecording.value?.id === recordingId) {
- selectedRecording.value = data;
- }
-
- const queueItem = uploadQueue.value.find(item => item.recordingId === recordingId);
-
- // Update the item's status and name for intermediate states
- if (queueItem) {
- queueItem.status = data.status; // e.g., 'PROCESSING', 'SUMMARIZING'
- queueItem.file.name = data.title || data.original_filename;
- }
-
- // Update progress modal if this is the currently processing item
- if (queueItem && currentlyProcessingFile.value?.clientId === queueItem.clientId) {
- updateReprocessingProgress(data.status, queueItem);
- }
-
- // Stop polling if processing is complete
- if (data.status === 'COMPLETED' || data.status === 'FAILED') {
- console.log(`Reprocessing ${data.status.toLowerCase()} for recording ${recordingId}`);
- stopReprocessingPoll(recordingId);
-
- // Update queue item status to final lowercase state
- if (queueItem) {
- queueItem.status = data.status === 'COMPLETED' ? 'completed' : 'failed';
- if (data.status === 'FAILED') {
- queueItem.error = data.error_message || 'Reprocessing failed';
- }
- }
-
- // Clear current processing if this was the active item
- if (currentlyProcessingFile.value?.recordingId === recordingId) {
- resetCurrentFileProcessingState();
- }
-
- if (data.status === 'COMPLETED') {
- showToast('Reprocessing completed successfully', 'fa-check-circle');
- } else {
- showToast('Reprocessing failed', 'fa-exclamation-circle');
- }
- }
-
- } catch (error) {
- console.error(`Error polling status for recording ${recordingId}:`, error);
- stopReprocessingPoll(recordingId);
- }
- }, 3000); // Poll every 3 seconds
-
- reprocessingPolls.value.set(recordingId, pollInterval);
- };
-
- const updateReprocessingProgress = (status, queueItem) => {
- switch (status) {
- case 'PENDING':
- processingProgress.value = 20;
- processingMessage.value = `Waiting to start ${queueItem.reprocessType} reprocessing...`;
- break;
- case 'PROCESSING':
- processingProgress.value = Math.round(Math.min(70, processingProgress.value + Math.random() * 10));
- processingMessage.value = queueItem.reprocessType === 'transcription'
- ? 'Reprocessing transcription...'
- : 'Processing audio...';
- break;
- case 'SUMMARIZING':
- processingProgress.value = Math.round(Math.min(90, processingProgress.value + Math.random() * 10));
- processingMessage.value = queueItem.reprocessType === 'summary'
- ? 'Regenerating summary...'
- : 'Generating title and summary...';
- break;
- case 'COMPLETED':
- processingProgress.value = 100;
- processingMessage.value = 'Reprocessing completed!';
- break;
- case 'FAILED':
- processingProgress.value = 100;
- processingMessage.value = 'Reprocessing failed.';
- break;
- default:
- processingProgress.value = 15;
- processingMessage.value = 'Starting reprocessing...';
- }
- };
-
- const stopReprocessingPoll = (recordingId) => {
- if (reprocessingPolls.value.has(recordingId)) {
- clearInterval(reprocessingPolls.value.get(recordingId));
- reprocessingPolls.value.delete(recordingId);
- console.log(`Stopped reprocessing poll for recording ${recordingId}`);
- }
- };
-
- const confirmReset = (recording) => {
- recordingToReset.value = recording;
- showResetModal.value = true;
- };
-
- const cancelReset = () => {
- showResetModal.value = false;
- recordingToReset.value = null;
- };
-
- const executeReset = async () => {
- if (!recordingToReset.value) return;
- const recordingId = recordingToReset.value.id;
-
- // Close the modal first
- cancelReset();
-
- try {
- const response = await fetch(`/recording/${recordingId}/reset_status`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' }
- });
-
- const data = await response.json();
- if (!response.ok) throw new Error(data.error || 'Failed to reset status');
-
- // Update the recording in the UI
- const index = recordings.value.findIndex(r => r.id === recordingId);
- if (index !== -1) {
- recordings.value[index] = data.recording;
- }
-
- // Update selected recording if it's the one being reset
- if (selectedRecording.value?.id === recordingId) {
- selectedRecording.value = data.recording;
- }
-
- showToast('Recording status has been reset.', 'fa-check-circle');
-
- } catch (error) {
- console.error('Reset Status Error:', error);
- setGlobalError(`Failed to reset status: ${error.message}`);
- }
- };
-
- const searchSpeakers = async (query, speakerId) => {
- if (!query || query.length < 2) {
- speakerSuggestions.value[speakerId] = [];
- return;
- }
-
- loadingSuggestions.value[speakerId] = true;
-
- try {
- const response = await fetch(`/speakers/search?q=${encodeURIComponent(query)}`);
- if (!response.ok) throw new Error('Failed to search speakers');
-
- const speakers = await response.json();
- speakerSuggestions.value[speakerId] = speakers;
- } catch (error) {
- console.error('Error searching speakers:', error);
- speakerSuggestions.value[speakerId] = [];
- } finally {
- loadingSuggestions.value[speakerId] = false;
- }
- };
-
- const selectSpeakerSuggestion = (speakerId, suggestion) => {
- if (speakerMap.value[speakerId]) {
- speakerMap.value[speakerId].name = suggestion.name;
- speakerSuggestions.value[speakerId] = [];
- }
- };
-
- const closeSpeakerSuggestionsOnClick = (event) => {
- // Check if the click was on an input field or dropdown
- const clickedInput = event.target.closest('input[type="text"]');
- const clickedDropdown = event.target.closest('.absolute.z-10');
-
- // If not clicking on input or dropdown, close all suggestions
- if (!clickedInput && !clickedDropdown) {
- Object.keys(speakerSuggestions.value).forEach(speakerId => {
- speakerSuggestions.value[speakerId] = [];
- });
- }
- };
-
- // Create a mapping for display-friendly speaker IDs
- const speakerDisplayMap = ref({});
- const modalSpeakers = ref([]);
-
- const openSpeakerModal = () => {
- // Clear any existing speaker map data first
- speakerMap.value = {};
- speakerDisplayMap.value = {};
-
- // Get the same speaker order used in processedTranscription
- const transcription = selectedRecording.value?.transcription;
- let speakers = [];
-
- if (transcription) {
- try {
- const transcriptionData = JSON.parse(transcription);
- if (transcriptionData && Array.isArray(transcriptionData)) {
- // Use the exact same logic as processedTranscription to get speakers
- speakers = [...new Set(transcriptionData.map(segment => segment.speaker).filter(Boolean))];
- }
- } catch (e) {
- // Fall back to identifiedSpeakers if JSON parsing fails
- speakers = identifiedSpeakers.value;
- }
- }
-
- // Set modalSpeakers for the template to use
- modalSpeakers.value = speakers;
-
- // Initialize speaker map with the same order and colors as the transcript
- speakerMap.value = speakers.reduce((acc, speaker, index) => {
- acc[speaker] = {
- name: '',
- isMe: false,
- color: `speaker-color-${(index % 8) + 1}` // Same color assignment as processedTranscription
- };
- // Keep the original speaker ID for display
- speakerDisplayMap.value[speaker] = speaker;
- return acc;
- }, {});
-
- highlightedSpeaker.value = null;
- speakerSuggestions.value = {};
- loadingSuggestions.value = {};
- isAutoIdentifying.value = false;
- showSpeakerModal.value = true;
- };
-
- const closeSpeakerModal = () => {
- showSpeakerModal.value = false;
- highlightedSpeaker.value = null;
- // Clear the speaker map to prevent stale data from persisting
- speakerMap.value = {};
- speakerSuggestions.value = {};
- loadingSuggestions.value = {};
-
- // Clean up click handler if it exists
- if (window.speakerModalClickHandler) {
- const modalContent = document.querySelector('.modal-content');
- if (modalContent) {
- modalContent.removeEventListener('click', window.speakerModalClickHandler);
- }
- delete window.speakerModalClickHandler;
- }
- };
-
- const saveSpeakerNames = async () => {
- if (!selectedRecording.value) return;
-
- // If there are transcript edits, save those instead
- if (editedTranscriptData.value) {
- return saveTranscriptEdits();
- }
-
- // Create a filtered speaker map that excludes entries with blank names
- const filteredSpeakerMap = Object.entries(speakerMap.value).reduce((acc, [speakerId, speakerData]) => {
- if (speakerData.name && speakerData.name.trim() !== '') {
- acc[speakerId] = speakerData;
- }
- return acc;
- }, {});
-
- try {
- const response = await fetch(`/recording/${selectedRecording.value.id}/update_speakers`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- speaker_map: filteredSpeakerMap, // Send the filtered map
- regenerate_summary: regenerateSummaryAfterSpeakerUpdate.value
- })
- });
-
- const data = await response.json();
- if (!response.ok) throw new Error(data.error || 'Failed to update speakers');
-
- // On success, close the modal and clear the speakerMap state *before*
- // updating the recording data. This prevents a race condition where the
- // view could re-render using the new data but the old, lingering speakerMap.
- closeSpeakerModal();
-
- // The backend returns the fully updated recording object.
- // We can directly update our local state with this fresh data.
- const index = recordings.value.findIndex(r => r.id === selectedRecording.value.id);
- if (index !== -1) {
- recordings.value[index] = data.recording;
- }
- selectedRecording.value = data.recording;
-
- showToast('Speaker names updated successfully!', 'fa-check-circle');
-
- // If a summary regeneration was requested, start polling for its status.
- if (regenerateSummaryAfterSpeakerUpdate.value) {
- startReprocessingPoll(selectedRecording.value.id);
- }
-
- } catch (error) {
- console.error('Save Speaker Names Error:', error);
- setGlobalError(`Failed to save speaker names: ${error.message}`);
- }
- };
-
- // Speaker group navigation state
- const currentSpeakerGroupIndex = ref(-1);
- const speakerGroups = ref([]);
-
- const findSpeakerGroups = (speakerId) => {
- if (!speakerId) return [];
-
- const groups = [];
- const modalTranscript = document.querySelector('div.speaker-modal-transcript');
- const mainTranscript = document.querySelector('.transcription-simple-view, .transcription-with-speakers, .transcription-content');
- const transcriptContainer = modalTranscript || mainTranscript;
-
- if (!transcriptContainer) return [];
-
- // For JSON-based transcripts with segments
- const allSegments = transcriptContainer.querySelectorAll('.speaker-segment');
- if (allSegments.length > 0) {
- let currentGroup = null;
- let lastSpeakerId = null;
-
- allSegments.forEach(segment => {
- const speakerTag = segment.querySelector('[data-speaker-id]');
- const segmentSpeakerId = speakerTag?.dataset.speakerId;
-
- if (segmentSpeakerId === speakerId) {
- // If this is a new group (not consecutive with previous)
- if (lastSpeakerId !== speakerId) {
- currentGroup = {
- startElement: segment,
- elements: [segment]
- };
- groups.push(currentGroup);
- } else if (currentGroup) {
- // Add to existing group
- currentGroup.elements.push(segment);
- }
- }
- lastSpeakerId = segmentSpeakerId;
- });
- } else {
- // For plain text transcripts with speaker tags
- const allTags = transcriptContainer.querySelectorAll('[data-speaker-id]');
- let currentGroup = null;
-
- allTags.forEach(tag => {
- if (tag.dataset.speakerId === speakerId) {
- // Find the parent element that contains this speaker's content
- const parentSegment = tag.closest('.speaker-segment') || tag.parentElement;
-
- if (!currentGroup || !currentGroup.lastElement ||
- !parentSegment.previousElementSibling ||
- parentSegment.previousElementSibling !== currentGroup.lastElement) {
- // Start a new group
- currentGroup = {
- startElement: parentSegment,
- elements: [parentSegment],
- lastElement: parentSegment
- };
- groups.push(currentGroup);
- } else {
- // Continue the group
- currentGroup.elements.push(parentSegment);
- currentGroup.lastElement = parentSegment;
- }
- }
- });
- }
-
- return groups;
- };
-
- const highlightSpeakerInTranscript = (speakerId) => {
- highlightedSpeaker.value = speakerId;
-
- if (speakerId) {
- // Find all speaker groups for navigation
- speakerGroups.value = findSpeakerGroups(speakerId);
- currentSpeakerGroupIndex.value = 0;
-
- // Scroll to the first group
- if (speakerGroups.value.length > 0) {
- nextTick(() => {
- const firstGroup = speakerGroups.value[0];
- if (firstGroup && firstGroup.startElement) {
- firstGroup.startElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
- }
- });
- }
- } else {
- speakerGroups.value = [];
- currentSpeakerGroupIndex.value = -1;
- }
- };
-
- const navigateToNextSpeakerGroup = () => {
- if (speakerGroups.value.length === 0) return;
-
- // Don't reset the speaker groups, just update the index
- currentSpeakerGroupIndex.value = (currentSpeakerGroupIndex.value + 1) % speakerGroups.value.length;
- const group = speakerGroups.value[currentSpeakerGroupIndex.value];
- if (group && group.startElement) {
- group.startElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
- }
- };
-
- const navigateToPrevSpeakerGroup = () => {
- if (speakerGroups.value.length === 0) return;
-
- // Don't reset the speaker groups, just update the index
- currentSpeakerGroupIndex.value = currentSpeakerGroupIndex.value <= 0
- ? speakerGroups.value.length - 1
- : currentSpeakerGroupIndex.value - 1;
- const group = speakerGroups.value[currentSpeakerGroupIndex.value];
- if (group && group.startElement) {
- group.startElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
- }
- };
-
- // Enhanced speaker highlighting with focus/blur events for text inputs
- const focusSpeaker = (speakerId) => {
- // Set this as the active speaker input
- activeSpeakerInput.value = speakerId;
- // Only highlight if not already highlighted (to preserve navigation state)
- if (highlightedSpeaker.value !== speakerId) {
- highlightSpeakerInTranscript(speakerId);
- }
- };
-
- const blurSpeaker = () => {
- // Clear the active speaker input after a delay to allow clicking on suggestions
- setTimeout(() => {
- activeSpeakerInput.value = null;
- speakerSuggestions.value = {};
- }, 200);
- clearSpeakerHighlight();
- };
-
- const clearSpeakerHighlight = () => {
- highlightedSpeaker.value = null;
- };
-
- const autoIdentifySpeakers = async () => {
- if (!selectedRecording.value) {
- showToast('No recording selected.', 'fa-exclamation-circle');
- return;
- }
-
- isAutoIdentifying.value = true;
- showToast('Starting automatic speaker identification...', 'fa-magic');
-
- try {
- const response = await fetch(`/recording/${selectedRecording.value.id}/auto_identify_speakers`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- current_speaker_map: speakerMap.value
- })
- });
-
- const data = await response.json();
- if (!response.ok) {
- throw new Error(data.error || 'Unknown error occurred during auto-identification.');
- }
-
- // Check if there's a message (e.g., all speakers already identified)
- if (data.message) {
- showToast(data.message, 'fa-info-circle');
- return;
- }
-
- // Update speakerMap with the identified names (only for unidentified speakers)
- let identifiedCount = 0;
- for (const speakerId in data.speaker_map) {
- const identifiedName = data.speaker_map[speakerId];
- if (speakerMap.value[speakerId] && identifiedName && identifiedName.trim() !== '') {
- speakerMap.value[speakerId].name = identifiedName;
- identifiedCount++;
- }
- }
-
- if (identifiedCount > 0) {
- showToast(`${identifiedCount} speaker(s) identified successfully!`, 'fa-check-circle');
- } else {
- showToast('No speakers could be identified from the context.', 'fa-info-circle');
- }
-
- } catch (error) {
- console.error('Auto Identify Speakers Error:', error);
- showToast(`Error: ${error.message}`, 'fa-exclamation-circle', 5000);
- } finally {
- isAutoIdentifying.value = false;
- }
- };
-
- // --- Transcript Editing Functions ---
-
- const openAddSpeakerModal = () => {
- newSpeakerName.value = '';
- newSpeakerIsMe.value = false;
- showAddSpeakerModal.value = true;
- };
-
- const closeAddSpeakerModal = () => {
- showAddSpeakerModal.value = false;
- newSpeakerName.value = '';
- newSpeakerIsMe.value = false;
- };
-
- const addNewSpeaker = () => {
- const name = newSpeakerIsMe.value ? (currentUserName.value || 'Me') : newSpeakerName.value.trim();
-
- if (!newSpeakerIsMe.value && !name) {
- showToast('Please enter a speaker name', 'fa-exclamation-circle');
- return;
- }
-
- // Generate new speaker ID
- const existingSpeakerNumbers = modalSpeakers.value
- .map(s => {
- const match = s.match(/^SPEAKER_(\d+)$/);
- return match ? parseInt(match[1]) : -1;
- })
- .filter(n => n >= 0);
-
- const nextNumber = existingSpeakerNumbers.length > 0
- ? Math.max(...existingSpeakerNumbers) + 1
- : modalSpeakers.value.length;
-
- const newSpeakerId = `SPEAKER_${String(nextNumber).padStart(2, '0')}`;
-
- // Add to modalSpeakers
- modalSpeakers.value.push(newSpeakerId);
-
- // Add to speakerMap with next available color
- const colorIndex = modalSpeakers.value.length - 1;
- speakerMap.value[newSpeakerId] = {
- name: name,
- isMe: newSpeakerIsMe.value,
- color: `speaker-color-${(colorIndex % 8) + 1}`
- };
-
- // Add to speakerDisplayMap
- speakerDisplayMap.value[newSpeakerId] = newSpeakerId;
-
- closeAddSpeakerModal();
- showToast('Speaker added successfully', 'fa-check-circle');
- };
-
- const openSpeakerChangeDropdown = (segmentIndex) => {
- editingSpeakerIndex.value = editingSpeakerIndex.value === segmentIndex ? null : segmentIndex;
- };
-
- const changeSpeaker = (segmentIndex, newSpeakerId) => {
- if (!selectedRecording.value?.transcription) return;
-
- try {
- const transcriptionData = JSON.parse(selectedRecording.value.transcription);
- if (transcriptionData && Array.isArray(transcriptionData) && transcriptionData[segmentIndex]) {
- transcriptionData[segmentIndex].speaker = newSpeakerId;
- editedTranscriptData.value = transcriptionData;
-
- // Update the recording's transcription temporarily for UI update
- selectedRecording.value.transcription = JSON.stringify(transcriptionData);
-
- editingSpeakerIndex.value = null;
- showToast('Speaker changed. Click "Save Names" to persist changes.', 'fa-info-circle');
- }
- } catch (e) {
- console.error('Error changing speaker:', e);
- showToast('Error changing speaker', 'fa-exclamation-circle');
- }
- };
-
- const openEditTextModal = (segmentIndex) => {
- if (!selectedRecording.value?.transcription) return;
-
- try {
- const transcriptionData = JSON.parse(selectedRecording.value.transcription);
- if (transcriptionData && Array.isArray(transcriptionData) && transcriptionData[segmentIndex]) {
- editingSegmentIndex.value = segmentIndex;
- editedText.value = transcriptionData[segmentIndex].sentence || '';
- showEditTextModal.value = true;
- }
- } catch (e) {
- console.error('Error opening text editor:', e);
- showToast('Error opening text editor', 'fa-exclamation-circle');
- }
- };
-
- const closeEditTextModal = () => {
- showEditTextModal.value = false;
- editingSegmentIndex.value = null;
- editedText.value = '';
- };
-
- const saveEditedText = () => {
- if (editingSegmentIndex.value === null || !selectedRecording.value?.transcription) return;
-
- try {
- const transcriptionData = JSON.parse(selectedRecording.value.transcription);
- if (transcriptionData && Array.isArray(transcriptionData) && transcriptionData[editingSegmentIndex.value]) {
- transcriptionData[editingSegmentIndex.value].sentence = editedText.value;
- editedTranscriptData.value = transcriptionData;
-
- // Update the recording's transcription temporarily for UI update
- selectedRecording.value.transcription = JSON.stringify(transcriptionData);
-
- closeEditTextModal();
- showToast('Text updated. Click "Save Names" to persist changes.', 'fa-info-circle');
- }
- } catch (e) {
- console.error('Error saving text:', e);
- showToast('Error saving text', 'fa-exclamation-circle');
- }
- };
-
- const saveTranscriptEdits = async () => {
- if (!selectedRecording.value || !editedTranscriptData.value) {
- return saveSpeakerNames(); // Fall back to regular speaker name save
- }
-
- try {
- // Save both speaker names and transcript edits
- const filteredSpeakerMap = Object.entries(speakerMap.value).reduce((acc, [speakerId, speakerData]) => {
- if (speakerData.name && speakerData.name.trim() !== '') {
- acc[speakerId] = speakerData;
- }
- return acc;
- }, {});
-
- const response = await fetch(`/recording/${selectedRecording.value.id}/update_transcript`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- transcript_data: editedTranscriptData.value,
- speaker_map: filteredSpeakerMap,
- regenerate_summary: regenerateSummaryAfterSpeakerUpdate.value
- })
- });
-
- const data = await response.json();
- if (!response.ok) throw new Error(data.error || 'Failed to update transcript');
-
- closeSpeakerModal();
-
- const index = recordings.value.findIndex(r => r.id === selectedRecording.value.id);
- if (index !== -1) {
- recordings.value[index] = data.recording;
- }
- selectedRecording.value = data.recording;
- editedTranscriptData.value = null;
-
- showToast('Transcript updated successfully!', 'fa-check-circle');
- } catch (error) {
- console.error('Save Transcript Error:', error);
- showToast(`Error: ${error.message}`, 'fa-exclamation-circle');
- }
- };
-
- const toggleInbox = async (recording) => {
- if (!recording || !recording.id) return;
-
- try {
- const response = await fetch(`/recording/${recording.id}/toggle_inbox`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' }
- });
-
- const data = await response.json();
- if (!response.ok) throw new Error(data.error || 'Failed to toggle inbox status');
-
- // Update the recording in the UI
- recording.is_inbox = data.is_inbox;
-
- // Update in the recordings list
- const index = recordings.value.findIndex(r => r.id === recording.id);
- if (index !== -1) {
- recordings.value[index].is_inbox = data.is_inbox;
- }
-
- showToast(`Recording ${data.is_inbox ? 'moved to inbox' : 'marked as read'}`);
- } catch (error) {
- console.error('Toggle Inbox Error:', error);
- setGlobalError(`Failed to toggle inbox status: ${error.message}`);
- }
- };
-
- // Toggle highlighted status
- const toggleHighlight = async (recording) => {
- if (!recording || !recording.id) return;
-
- try {
- const response = await fetch(`/recording/${recording.id}/toggle_highlight`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' }
- });
-
- const data = await response.json();
- if (!response.ok) throw new Error(data.error || 'Failed to toggle highlighted status');
-
- // Update the recording in the UI
- recording.is_highlighted = data.is_highlighted;
-
- // Update in the recordings list
- const index = recordings.value.findIndex(r => r.id === recording.id);
- if (index !== -1) {
- recordings.value[index].is_highlighted = data.is_highlighted;
- }
-
- showToast(`Recording ${data.is_highlighted ? 'highlighted' : 'unhighlighted'}`);
- } catch (error) {
- console.error('Toggle Highlight Error:', error);
- setGlobalError(`Failed to toggle highlighted status: ${error.message}`);
- }
- };
-
- // --- Dark Mode ---
- const toggleDarkMode = () => {
- isDarkMode.value = !isDarkMode.value;
- if (isDarkMode.value) {
- document.documentElement.classList.add('dark');
- localStorage.setItem('darkMode', 'true');
- } else {
- document.documentElement.classList.remove('dark');
- localStorage.setItem('darkMode', 'false');
- }
- };
-
- const initializeDarkMode = () => {
- const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
- const savedMode = localStorage.getItem('darkMode');
- if (savedMode === 'true' || (savedMode === null && prefersDark)) {
- isDarkMode.value = true;
- document.documentElement.classList.add('dark');
- } else {
- isDarkMode.value = false;
- document.documentElement.classList.remove('dark');
- }
- };
-
- const applyColorScheme = (schemeId, mode = null) => {
- const targetMode = mode || (isDarkMode.value ? 'dark' : 'light');
- const scheme = colorSchemes[targetMode].find(s => s.id === schemeId);
-
- if (!scheme) {
- console.warn(`Color scheme '${schemeId}' not found for mode '${targetMode}'`);
- return;
- }
-
- const allThemeClasses = [
- ...colorSchemes.light.map(s => s.class),
- ...colorSchemes.dark.map(s => s.class)
- ].filter(c => c !== '');
-
- document.documentElement.classList.remove(...allThemeClasses);
-
- if (scheme.class) {
- document.documentElement.classList.add(scheme.class);
- }
-
- currentColorScheme.value = schemeId;
- localStorage.setItem('colorScheme', schemeId);
- };
-
- const initializeColorScheme = () => {
- const savedScheme = localStorage.getItem('colorScheme') || 'blue';
- currentColorScheme.value = savedScheme;
- applyColorScheme(savedScheme);
- };
-
- const openColorSchemeModal = () => {
- showColorSchemeModal.value = true;
- };
-
- const closeColorSchemeModal = () => {
- showColorSchemeModal.value = false;
- };
-
- const selectColorScheme = (schemeId) => {
- applyColorScheme(schemeId);
- showToast(`Applied ${colorSchemes[isDarkMode.value ? 'dark' : 'light'].find(s => s.id === schemeId)?.name} theme`, 'fa-palette');
- };
-
- const resetColorScheme = () => {
- applyColorScheme('blue');
- showToast('Reset to default Ocean Blue theme', 'fa-undo');
- };
-
- // Watch for dark mode changes to reapply color scheme
- watch(isDarkMode, () => {
- applyColorScheme(currentColorScheme.value);
- });
-
- // --- Sidebar Toggle ---
- const toggleSidebar = () => {
- isSidebarCollapsed.value = !isSidebarCollapsed.value;
- };
-
- // --- View Management ---
- const hasUnsavedRecording = () => {
- // Check if we have an active recording or a finished recording that hasn't been uploaded
- return currentView.value === 'recording' && (isRecording.value || audioBlobURL.value);
- };
-
- const confirmNavigationWithUnsavedRecording = () => {
- if (hasUnsavedRecording()) {
- const message = isRecording.value
- ? 'Recording in progress. Are you sure you want to leave? Your recording will be lost.'
- : 'You have an unsaved recording. Are you sure you want to leave? Your recording will be lost.';
- return confirm(message);
- }
- return true;
- };
-
- const switchToUploadView = () => {
- if (!confirmNavigationWithUnsavedRecording()) {
- return;
- }
- currentView.value = 'upload';
- selectedRecording.value = null;
- if (isMobileScreen.value) {
- isSidebarCollapsed.value = true;
- }
- // Clean up any active or unsaved recording
- if (isRecording.value) {
- stopRecording();
- }
- if (audioBlobURL.value) {
- discardRecording();
- }
- };
-
- const selectRecording = (recording) => {
- // Check for active or unsaved recording before switching
- if (!confirmNavigationWithUnsavedRecording()) {
- return;
- }
- selectedRecording.value = recording;
- currentView.value = 'detail';
- if (recording && recording.id) {
- localStorage.setItem('lastSelectedRecordingId', recording.id);
- } else {
- localStorage.removeItem('lastSelectedRecordingId');
- }
- if (isMobileScreen.value) {
- isSidebarCollapsed.value = true;
- }
- // Clean up any active or unsaved recording
- if (isRecording.value) {
- stopRecording();
- }
- if (audioBlobURL.value) {
- discardRecording();
- }
- };
-
- // --- File Upload ---
- const handleDragOver = (e) => {
- e.preventDefault();
- dragover.value = true;
- };
-
- const handleDragLeave = (e) => {
- if (e.relatedTarget && e.currentTarget.contains(e.relatedTarget)) {
- return;
- }
- dragover.value = false;
- };
-
- const handleDrop = (e) => {
- e.preventDefault();
- dragover.value = false;
- addFilesToQueue(e.dataTransfer.files);
- };
-
- const handleFileSelect = (e) => {
- addFilesToQueue(e.target.files);
- e.target.value = null;
- };
-
- const addFilesToQueue = (files) => {
- let filesAdded = 0;
- for (const file of files) {
- const fileObject = file.file ? file.file : file;
- const notes = file.notes || null;
- const tags = file.tags || selectedTags.value || [];
- const asrOptions = file.asrOptions || {
- language: asrLanguage.value,
- min_speakers: asrMinSpeakers.value,
- max_speakers: asrMaxSpeakers.value
- };
-
- // Check if it's an audio file or video container with audio
- const 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('.mp4') ||
- fileObject.name.toLowerCase().endsWith('.mov') ||
- fileObject.name.toLowerCase().endsWith('.avi') ||
- fileObject.name.toLowerCase().endsWith('.mkv') ||
- fileObject.name.toLowerCase().endsWith('.webm')
- );
-
- if (isAudioFile) {
- // Only check general file size limit (chunking handles OpenAI 25MB limit automatically)
- if (fileObject.size > maxFileSizeMB.value * 1024 * 1024) {
- setGlobalError(`File "${fileObject.name}" exceeds the maximum size of ${maxFileSizeMB.value} MB and was skipped.`);
- continue;
- }
-
- const clientId = `client-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
-
- // Auto-summarization will always occur for all uploads
- const willAutoSummarize = true;
-
- uploadQueue.value.push({
- file: fileObject,
- notes: notes,
- tags: tags,
- asrOptions: asrOptions,
- status: 'queued',
- recordingId: null,
- clientId: clientId,
- error: null,
- willAutoSummarize: willAutoSummarize
- });
- filesAdded++;
- } else if (fileObject) {
- 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) {
- console.log(`Added ${filesAdded} file(s) to the queue.`);
- progressPopupMinimized.value = false;
- progressPopupClosed.value = false;
- if (!isProcessingActive.value) {
- startProcessingQueue();
- }
- }
- };
-
- const resetCurrentFileProcessingState = () => {
- if (pollInterval.value) clearInterval(pollInterval.value);
- pollInterval.value = null;
- currentlyProcessingFile.value = null;
- processingProgress.value = 0;
- processingMessage.value = '';
- };
-
- const startProcessingQueue = async () => {
- console.log("Attempting to start processing queue...");
- if (isProcessingActive.value) {
- console.log("Queue processor already active.");
- return;
- }
-
- isProcessingActive.value = true;
- resetCurrentFileProcessingState();
-
- const nextFileItem = uploadQueue.value.find(item => item.status === 'queued');
-
- if (nextFileItem) {
- console.log(`Processing next file: ${nextFileItem.file.name} (Client ID: ${nextFileItem.clientId})`);
- currentlyProcessingFile.value = nextFileItem;
-
- // Check if this is a "reload" item (existing recording being tracked)
- if (nextFileItem.clientId.startsWith('reload-')) {
- // Skip upload, go directly to polling existing recording
- console.log(`Skipping upload for existing recording: ${nextFileItem.recordingId}`);
- nextFileItem.status = 'processing';
- startStatusPolling(nextFileItem, nextFileItem.recordingId);
- return;
- }
-
- nextFileItem.status = 'uploading';
- processingMessage.value = 'Preparing upload...';
- processingProgress.value = 5;
-
- try {
- const formData = new FormData();
- formData.append('file', nextFileItem.file);
- if (nextFileItem.notes) {
- formData.append('notes', nextFileItem.notes);
- }
-
- // Add tags if selected (multiple tags)
- // Use tags from the queue item if available, otherwise use global selectedTagIds
- const tagsToUse = nextFileItem.tags || selectedTags.value || [];
- tagsToUse.forEach((tag, index) => {
- const tagId = tag.id || tag; // Handle both tag objects and tag IDs
- formData.append(`tag_ids[${index}]`, tagId);
- });
-
- // Add ASR advanced options if ASR endpoint is enabled
- if (useAsrEndpoint.value) {
- // Use ASR options from the queue item if available, otherwise use global values
- const asrOpts = nextFileItem.asrOptions || {};
- const language = asrOpts.language || uploadLanguage.value;
- const minSpeakers = asrOpts.min_speakers || uploadMinSpeakers.value;
- const maxSpeakers = asrOpts.max_speakers || uploadMaxSpeakers.value;
-
- if (language) {
- formData.append('language', language);
- }
- // Only send speaker limits if they're actually set
- if (minSpeakers && minSpeakers !== '') {
- formData.append('min_speakers', minSpeakers.toString());
- }
- if (maxSpeakers && maxSpeakers !== '') {
- formData.append('max_speakers', maxSpeakers.toString());
- }
- }
-
- processingMessage.value = 'Uploading file...';
- processingProgress.value = 10;
-
- const response = await fetch('/upload', { method: 'POST', body: formData });
- const data = await response.json();
-
- if (!response.ok) {
- let errorMsg = data.error || `Upload failed with status ${response.status}`;
- if (response.status === 413) errorMsg = data.error || `File too large. Max: ${data.max_size_mb?.toFixed(0) || maxFileSizeMB.value} MB.`;
- throw new Error(errorMsg);
- }
-
- if (response.status === 202 && data.id) {
- console.log(`File ${nextFileItem.file.name} uploaded. Recording ID: ${data.id}. Starting status poll.`);
- nextFileItem.status = 'pending';
- nextFileItem.recordingId = data.id;
- processingMessage.value = 'Upload complete. Waiting for processing...';
- processingProgress.value = 30;
-
- recordings.value.unshift(data);
- totalRecordings.value++; // Update total count
- pollProcessingStatus(nextFileItem);
-
- } else {
- throw new Error('Unexpected success response from server after upload.');
- }
-
- } catch (error) {
- console.error(`Upload/Processing Error for ${nextFileItem.file.name} (Client ID: ${nextFileItem.clientId}):`, error);
- nextFileItem.status = 'failed';
- nextFileItem.error = error.message;
- const failedRecordIndex = recordings.value.findIndex(r => r.id === nextFileItem.recordingId);
- if(failedRecordIndex !== -1) {
- recordings.value[failedRecordIndex].status = 'FAILED';
- recordings.value[failedRecordIndex].transcription = `Upload/Processing failed: ${error.message}`;
- } else {
- setGlobalError(`Failed to process "${nextFileItem.file.name}": ${error.message}`);
- }
-
- resetCurrentFileProcessingState();
- isProcessingActive.value = false;
- await nextTick();
- startProcessingQueue();
- }
- } else {
- console.log("Upload queue is empty or no files are queued.");
- isProcessingActive.value = false;
- }
- };
-
- const startStatusPolling = (fileItem, recordingId) => {
- fileItem.recordingId = recordingId;
- pollProcessingStatus(fileItem);
- };
-
- const pollProcessingStatus = (fileItem) => {
- if (pollInterval.value) clearInterval(pollInterval.value);
-
- const recordingId = fileItem.recordingId;
- if (!recordingId) {
- console.error("Cannot poll status without recording ID for", fileItem.file.name);
- fileItem.status = 'failed';
- fileItem.error = 'Internal error: Missing recording ID for polling.';
- resetCurrentFileProcessingState();
- isProcessingActive.value = false;
- nextTick(startProcessingQueue);
- return;
- }
-
- processingMessage.value = 'Waiting for transcription...';
- processingProgress.value = 40;
-
- pollInterval.value = setInterval(async () => {
- // Check if we should stop polling
- const shouldStopPolling = !currentlyProcessingFile.value ||
- currentlyProcessingFile.value.clientId !== fileItem.clientId ||
- fileItem.status === 'failed' ||
- (fileItem.status === 'completed' && (!fileItem.willAutoSummarize || fileItem.summaryCompleted));
-
- if (shouldStopPolling) {
- console.log(`Polling stopped for ${fileItem.clientId} as it's no longer active or finished.`);
- clearInterval(pollInterval.value);
- pollInterval.value = null;
- if (currentlyProcessingFile.value && currentlyProcessingFile.value.clientId === fileItem.clientId) {
- resetCurrentFileProcessingState();
- isProcessingActive.value = false;
- await nextTick();
- startProcessingQueue();
- }
- return;
- }
-
- try {
- console.log(`Polling status for recording ID: ${recordingId} (${fileItem.file.name})`);
- const response = await fetch(`/status/${recordingId}`);
- if (!response.ok) throw new Error(`Status check failed with status ${response.status}`);
-
- const data = await response.json();
- const galleryIndex = recordings.value.findIndex(r => r.id === recordingId);
-
- if (galleryIndex !== -1) {
- recordings.value[galleryIndex] = data;
- if(selectedRecording.value?.id === recordingId) {
- selectedRecording.value = data;
- }
- }
-
- const previousStatus = fileItem.status;
- fileItem.status = data.status;
- fileItem.file.name = data.title || data.original_filename;
-
- if (data.status === 'COMPLETED') {
- console.log(`Processing COMPLETED for ${fileItem.file.name} (ID: ${recordingId})`);
-
- // If this was previously summarizing, it's now fully complete
- if (previousStatus === 'summarizing') {
- console.log(`Auto-summary completed for ${fileItem.file.name}`);
- processingMessage.value = 'Processing complete!';
- processingProgress.value = 100;
- fileItem.status = 'completed';
- fileItem.summaryCompleted = true;
-
- // This is final completion - clean up immediately and synchronously
- clearInterval(pollInterval.value);
- pollInterval.value = null;
- resetCurrentFileProcessingState();
- isProcessingActive.value = false;
-
- // Keep completed items visible in the modal - don't remove them
- console.log(`Completed item ${fileItem.clientId} will remain visible in queue`);
-
- // Use immediate startProcessingQueue instead of nextTick to avoid duplication
- startProcessingQueue();
- return; // Exit early to prevent further processing
- }
- // If auto-summarization will occur and hasn't started yet, wait for it
- else if (fileItem.willAutoSummarize && !fileItem.hasCheckedForAutoSummary) {
- processingMessage.value = 'Transcription complete!';
- processingProgress.value = 85;
- fileItem.status = 'awaiting_summary'; // Use intermediate status to keep it in upload queue
- // Don't mark as summaryCompleted yet, continue polling
- }
- // No auto-summarization expected, complete normally
- else {
- processingMessage.value = 'Processing complete!';
- processingProgress.value = 100;
- fileItem.status = 'completed';
- fileItem.summaryCompleted = true; // No summary expected, so consider it complete
-
- // Complete immediately for files without auto-summarization
- clearInterval(pollInterval.value);
- pollInterval.value = null;
- resetCurrentFileProcessingState();
- isProcessingActive.value = false;
-
- // Keep completed items visible in the modal - don't remove them
- console.log(`Completed item ${fileItem.clientId} will remain visible in queue`);
-
- startProcessingQueue();
- return; // Exit early to prevent further processing
- }
-
- // For files with auto-summarization, mark that they've been checked and continue polling
- if (fileItem.willAutoSummarize && !fileItem.hasCheckedForAutoSummary) {
- fileItem.hasCheckedForAutoSummary = true;
- fileItem.autoSummaryStartTime = Date.now();
- console.log(`Auto-summary expected for ${fileItem.file.name}, continuing to poll...`);
- // Don't complete yet, continue polling
- return;
- }
-
- // If we have auto-summarization and we've been waiting, check if we should timeout
- if (fileItem.willAutoSummarize && fileItem.hasCheckedForAutoSummary) {
- const waitTime = Date.now() - fileItem.autoSummaryStartTime;
- const maxWaitTime = 60000; // 60 seconds
-
- if (waitTime > maxWaitTime) {
- // Timeout - complete the process
- console.log(`Auto-summary timeout for ${fileItem.file.name}, completing...`);
- processingMessage.value = 'Processing complete!';
- processingProgress.value = 100;
- fileItem.status = 'completed';
- fileItem.summaryCompleted = true; // Mark as complete due to timeout
- clearInterval(pollInterval.value);
- pollInterval.value = null;
- resetCurrentFileProcessingState();
- isProcessingActive.value = false;
-
- // Keep completed items visible in the modal - don't remove them
- console.log(`Timed-out item ${fileItem.clientId} will remain visible in queue`);
-
- startProcessingQueue();
- } else {
- // Still waiting for auto-summary, continue polling
- return;
- }
- }
-
- // Normal completion path (no auto-summary check needed)
- clearInterval(pollInterval.value);
- pollInterval.value = null;
- resetCurrentFileProcessingState();
- isProcessingActive.value = false;
-
- // Remove this item from uploadQueue immediately to prevent duplication
- const queueIndex = uploadQueue.value.findIndex(item => item.clientId === fileItem.clientId);
- if (queueIndex !== -1) {
- uploadQueue.value.splice(queueIndex, 1);
- console.log(`Removed completed item ${fileItem.clientId} from queue immediately`);
- }
-
- startProcessingQueue();
-
- } else if (data.status === 'FAILED') {
- console.log(`Processing FAILED for ${fileItem.file.name} (ID: ${recordingId})`);
- processingMessage.value = 'Processing failed.';
- processingProgress.value = 100;
- fileItem.status = 'failed';
- fileItem.error = data.transcription || data.summary || 'Processing failed on server.';
- setGlobalError(`Processing failed for "${data.title || fileItem.file.name}".`);
- clearInterval(pollInterval.value);
- pollInterval.value = null;
- resetCurrentFileProcessingState();
- isProcessingActive.value = false;
- await nextTick();
- startProcessingQueue();
-
- } else if (data.status === 'PROCESSING') {
- // Check if this file will actually use chunking based on all conditions:
- // 1. Chunking must be enabled in config
- // 2. Must NOT be using ASR endpoint (ASR handles large files natively)
- // 3. For size-based: File size must exceed the limit (can determine immediately)
- // 4. For time-based: Can't determine client-side, but backend logs show it gets duration
-
- const couldUseChunking = chunkingEnabled.value && !useAsrEndpoint.value;
-
- if (couldUseChunking) {
- if (chunkingMode.value === 'size') {
- // Size-based chunking: we can determine definitively
- const chunkThresholdBytes = chunkingLimit.value * 1024 * 1024;
- const willUseChunking = fileItem.file.size > chunkThresholdBytes;
-
- if (willUseChunking) {
- processingMessage.value = 'Processing large file (chunking in progress)...';
- // If auto-summarization will occur, cap at 70%, otherwise 80%
- const maxProgress = fileItem.willAutoSummarize ? 70 : 80;
- processingProgress.value = Math.round(Math.min(maxProgress, processingProgress.value + Math.random() * 3));
- } else {
- processingMessage.value = 'Transcription in progress...';
- // If auto-summarization will occur, cap at 65%, otherwise 75%
- const maxProgress = fileItem.willAutoSummarize ? 65 : 75;
- processingProgress.value = Math.round(Math.min(maxProgress, processingProgress.value + Math.random() * 5));
- }
- } else {
- // Duration-based chunking: Backend determines this after getting duration
- // Show a neutral processing message since we can't know client-side
- processingMessage.value = 'Processing file (chunking determined server-side)...';
- const maxProgress = fileItem.willAutoSummarize ? 70 : 80;
- processingProgress.value = Math.round(Math.min(maxProgress, processingProgress.value + Math.random() * 3));
- }
- } else {
- processingMessage.value = 'Transcription in progress...';
- const maxProgress = fileItem.willAutoSummarize ? 65 : 75;
- processingProgress.value = Math.round(Math.min(maxProgress, processingProgress.value + Math.random() * 5));
- }
- } else if (data.status === 'SUMMARIZING') {
- console.log(`Auto-summary started for ${fileItem.file.name}`);
- processingMessage.value = 'Generating summary...';
- processingProgress.value = 90;
- fileItem.status = 'summarizing';
- } else {
- processingMessage.value = 'Waiting in queue...';
- processingProgress.value = 45;
- }
- } catch (error) {
- console.error(`Polling Error for ${fileItem.file.name} (ID: ${recordingId}):`, error);
- fileItem.status = 'failed';
- fileItem.error = `Error checking status: ${error.message}`;
- setGlobalError(`Error checking status for "${fileItem.file.name}": ${error.message}.`);
- const galleryIndex = recordings.value.findIndex(r => r.id === recordingId);
- if (galleryIndex !== -1) recordings.value[galleryIndex].status = 'FAILED';
-
- clearInterval(pollInterval.value);
- pollInterval.value = null;
- resetCurrentFileProcessingState();
- isProcessingActive.value = false;
- await nextTick();
- startProcessingQueue();
- }
- }, 5000);
- };
-
- // --- Data Loading ---
- const loadRecordings = async (page = 1, append = false, searchQuery = '') => {
- globalError.value = null;
- if (!append) {
- isLoadingRecordings.value = true;
- } else {
- isLoadingMore.value = true;
- }
-
- try {
- const params = new URLSearchParams({
- page: page.toString(),
- per_page: perPage.value.toString()
- });
-
- if (searchQuery.trim()) {
- params.set('q', searchQuery.trim());
- }
-
- const response = await fetch(`/api/recordings?${params}`);
- const data = await response.json();
- if (!response.ok) throw new Error(data.error || 'Failed to load recordings');
-
- // Update pagination state
- currentPage.value = data.pagination.page;
- totalRecordings.value = data.pagination.total;
- totalPages.value = data.pagination.total_pages;
- hasNextPage.value = data.pagination.has_next;
- hasPrevPage.value = data.pagination.has_prev;
-
- // Update recordings data
- if (append) {
- // Append to existing recordings (infinite scroll)
- recordings.value = [...recordings.value, ...data.recordings];
- } else {
- // Replace recordings (fresh load or search)
- recordings.value = data.recordings;
-
- // Try to restore last selected recording
- const lastRecordingId = localStorage.getItem('lastSelectedRecordingId');
- if (lastRecordingId && data.recordings.length > 0) {
- const recordingToSelect = data.recordings.find(r => r.id == lastRecordingId);
- if (recordingToSelect) {
- selectRecording(recordingToSelect);
- }
- }
- }
-
- // Handle incomplete recordings for processing queue
- const incompleteRecordings = data.recordings.filter(r => ['PENDING', 'PROCESSING', 'SUMMARIZING'].includes(r.status));
- if (incompleteRecordings.length > 0 && !isProcessingActive.value) {
- console.warn(`Found ${incompleteRecordings.length} incomplete recording(s) on load.`);
- for (const recording of incompleteRecordings) {
- let queueItem = uploadQueue.value.find(item => item.recordingId === recording.id);
- if (!queueItem) {
- queueItem = {
- file: { name: recording.title || `Recording ${recording.id}`, size: recording.file_size },
- status: 'queued',
- recordingId: recording.id,
- clientId: `reload-${recording.id}`,
- error: null
- };
- uploadQueue.value.unshift(queueItem);
- if (!isProcessingActive.value) {
- startProcessingQueue();
- }
- }
- }
- }
-
- } catch (error) {
- console.error('Load Recordings Error:', error);
- setGlobalError(`Failed to load recordings: ${error.message}`);
- if (!append) {
- recordings.value = [];
- }
- } finally {
- isLoadingRecordings.value = false;
- isLoadingMore.value = false;
- }
- };
-
- // Load more recordings (infinite scroll)
- const loadMoreRecordings = async () => {
- if (!hasNextPage.value || isLoadingMore.value) return;
- await loadRecordings(currentPage.value + 1, true, searchQuery.value);
- };
-
- // Search with debouncing
- const performSearch = async (query = '') => {
- currentPage.value = 1;
- await loadRecordings(1, false, query);
- };
-
- // Debounced search function
- const debouncedSearch = (query) => {
- if (searchDebounceTimer.value) {
- clearTimeout(searchDebounceTimer.value);
- }
- searchDebounceTimer.value = setTimeout(() => {
- performSearch(query);
- }, 300); // 300ms debounce
- };
-
- const loadTags = async () => {
- try {
- const response = await fetch('/api/tags');
- if (response.ok) {
- availableTags.value = await response.json();
- } else {
- console.warn('Failed to load tags:', response.status);
- availableTags.value = [];
- }
- } catch (error) {
- console.warn('Error loading tags:', error);
- availableTags.value = [];
- }
- };
-
- const addTagToSelection = (tagId) => {
- if (!selectedTagIds.value.includes(tagId)) {
- selectedTagIds.value.push(tagId);
- applyTagDefaults();
- }
- };
-
- const removeTagFromSelection = (tagId) => {
- const index = selectedTagIds.value.indexOf(tagId);
- if (index > -1) {
- selectedTagIds.value.splice(index, 1);
- applyTagDefaults();
- }
- };
-
- const applyTagDefaults = () => {
- // Apply defaults from the first selected tag (highest priority)
- const firstTag = selectedTags.value[0];
- if (firstTag && useAsrEndpoint.value) {
- if (firstTag.default_language) {
- uploadLanguage.value = firstTag.default_language;
- }
- if (firstTag.default_min_speakers) {
- uploadMinSpeakers.value = firstTag.default_min_speakers;
- }
- if (firstTag.default_max_speakers) {
- uploadMaxSpeakers.value = firstTag.default_max_speakers;
- }
- }
- };
-
- // Legacy function for backward compatibility
- const onTagSelected = applyTagDefaults;
-
- // Tag helper functions
- const getRecordingTags = (recording) => {
- if (!recording || !recording.tags) return [];
- return recording.tags || [];
- };
-
- const getAvailableTagsForRecording = (recording) => {
- if (!recording || !availableTags.value) return [];
- const recordingTagIds = getRecordingTags(recording).map(tag => tag.id);
- return availableTags.value.filter(tag => !recordingTagIds.includes(tag.id));
- };
-
- // Computed property for filtered available tags in the modal
- const filteredAvailableTagsForModal = computed(() => {
- if (!editingRecording.value) return [];
- const availableTags = getAvailableTagsForRecording(editingRecording.value);
- if (!tagSearchFilter.value) return availableTags;
-
- const filter = tagSearchFilter.value.toLowerCase();
- return availableTags.filter(tag =>
- tag.name.toLowerCase().includes(filter)
- );
- });
- const filterByTag = (tag) => {
- // Use advanced filter instead of text-based
- filterTags.value = [tag.id];
- applyAdvancedFilters();
- };
-
- // Computed property for tags with custom prompts (for reprocess modal)
- const tagsWithCustomPrompts = computed(() => {
- return availableTags.value.filter(tag => tag.custom_prompt && tag.custom_prompt.trim());
- });
-
- // Helper function to get tag prompt preview
- const getTagPromptPreview = (tagId) => {
- const tag = availableTags.value.find(t => t.id == tagId);
- if (!tag || !tag.custom_prompt) return '';
- // Return first 100 characters
- return tag.custom_prompt.length > 100
- ? tag.custom_prompt.substring(0, 100) + '...'
- : tag.custom_prompt;
- };
- const clearTagFilter = () => {
- searchQuery.value = '';
- clearAllFilters();
- };
-
- // Build search query from advanced filters
- const buildSearchQuery = () => {
- let query = [];
-
- // Add text search
- if (filterTextQuery.value.trim()) {
- query.push(filterTextQuery.value.trim());
- }
-
- // Add tag filters
- if (filterTags.value.length > 0) {
- const tagNames = filterTags.value.map(tagId => {
- const tag = availableTags.value.find(t => t.id === tagId);
- return tag ? `tag:${tag.name.replace(/\s+/g, '_')}` : '';
- }).filter(Boolean);
- query.push(...tagNames);
- }
-
- // Add date filter
- if (filterDatePreset.value) {
- query.push(`date:${filterDatePreset.value}`);
- } else if (filterDateRange.value.start || filterDateRange.value.end) {
- // Custom date range - send as separate parameters
- // Will be handled differently in the backend
- if (filterDateRange.value.start) {
- query.push(`date_from:${filterDateRange.value.start}`);
- }
- if (filterDateRange.value.end) {
- query.push(`date_to:${filterDateRange.value.end}`);
- }
- }
-
- return query.join(' ');
- };
-
- const applyAdvancedFilters = () => {
- searchQuery.value = buildSearchQuery();
- };
-
- const clearAllFilters = () => {
- filterTags.value = [];
- filterDateRange.value = { start: '', end: '' };
- filterDatePreset.value = '';
- filterTextQuery.value = '';
- searchQuery.value = '';
- };
-
- const editRecordingTags = (recording) => {
- editingRecording.value = recording;
- selectedNewTagId.value = '';
- showEditTagsModal.value = true;
- };
-
- const closeEditTagsModal = () => {
- showEditTagsModal.value = false;
- editingRecording.value = null;
- selectedNewTagId.value = '';
- tagSearchFilter.value = ''; // Clear the filter when closing
- };
-
- const addTagToRecording = async (tagId = null) => {
- // Use provided tagId or fall back to selectedNewTagId
- const tagToAddId = tagId || selectedNewTagId.value;
- if (!tagToAddId || !editingRecording.value) return;
-
- try {
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
-
- const response = await fetch(`/api/recordings/${editingRecording.value.id}/tags`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': csrfToken
- },
- body: JSON.stringify({ tag_id: tagToAddId })
- });
-
- if (!response.ok) {
- const errorData = await response.json();
- throw new Error(errorData.error || 'Failed to add tag');
- }
-
- // Update local recording data
- const tagToAdd = availableTags.value.find(tag => tag.id == tagToAddId);
- if (tagToAdd) {
- if (!editingRecording.value.tags) {
- editingRecording.value.tags = [];
- }
- editingRecording.value.tags.push(tagToAdd);
-
- // Also update in recordings list if it's a different object
- const recordingInList = recordings.value.find(r => r.id === editingRecording.value.id);
- if (recordingInList && recordingInList !== editingRecording.value) {
- if (!recordingInList.tags) {
- recordingInList.tags = [];
- }
- recordingInList.tags.push(tagToAdd);
- }
- }
-
- selectedNewTagId.value = '';
-
- } catch (error) {
- console.error('Error adding tag to recording:', error);
- setGlobalError(`Failed to add tag: ${error.message}`);
- }
- };
-
- const removeTagFromRecording = async (tagId) => {
- if (!editingRecording.value) return;
-
- try {
- const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
-
- const response = await fetch(`/api/recordings/${editingRecording.value.id}/tags/${tagId}`, {
- method: 'DELETE',
- headers: {
- 'X-CSRFToken': csrfToken
- }
- });
-
- if (!response.ok) {
- const errorData = await response.json();
- throw new Error(errorData.error || 'Failed to remove tag');
- }
-
- // Update local recording data
- editingRecording.value.tags = editingRecording.value.tags.filter(tag => tag.id !== tagId);
-
- // Also update in recordings list if it's a different object
- const recordingInList = recordings.value.find(r => r.id === editingRecording.value.id);
- if (recordingInList && recordingInList !== editingRecording.value && recordingInList.tags) {
- recordingInList.tags = recordingInList.tags.filter(tag => tag.id !== tagId);
- }
-
- } catch (error) {
- console.error('Error removing tag from recording:', error);
- setGlobalError(`Failed to remove tag: ${error.message}`);
- }
- };
-
- // --- Wake Lock and Background Recording Support ---
-
- // Request screen wake lock to prevent screen from turning off during recording
- const requestWakeLock = async () => {
- if ('wakeLock' in navigator) {
- try {
- wakeLock.value = await navigator.wakeLock.request('screen');
- console.log('[Wake Lock] Screen wake lock acquired');
-
- wakeLock.value.addEventListener('release', () => {
- console.log('[Wake Lock] Screen wake lock was released');
- wakeLock.value = null;
-
- // Auto re-acquire if still recording and page is visible
- if (isRecording.value && document.visibilityState === 'visible') {
- console.log('[Wake Lock] Attempting to re-acquire wake lock...');
- setTimeout(() => {
- if (isRecording.value) {
- requestWakeLock();
- }
- }, 100);
- }
- });
-
- return true;
- } catch (err) {
- console.error('[Wake Lock] Failed to acquire wake lock:', err);
- // Not a critical error - recording can continue without wake lock
- return false;
- }
- } else {
- console.warn('[Wake Lock] Wake Lock API not supported');
- return false;
- }
- };
-
- // Release screen wake lock
- const releaseWakeLock = async () => {
- if (wakeLock.value !== null) {
- try {
- await wakeLock.value.release();
- wakeLock.value = null;
- console.log('[Wake Lock] Wake lock released successfully');
- } catch (err) {
- console.error('[Wake Lock] Error releasing wake lock:', err);
- }
- }
- };
-
- // Detect if running on mobile device
- const isMobileDevice = computed(() => {
- return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
- });
-
- // Show persistent notification during recording (mobile only)
- const showRecordingNotification = async () => {
- // Only show notifications on mobile devices
- if (!isMobileDevice.value) {
- console.log('[Notification] Skipping notification on desktop');
- return false;
- }
-
- if ('Notification' in window && 'serviceWorker' in navigator) {
- try {
- // Request notification permission if not already granted
- let permission = Notification.permission;
- if (permission === 'default') {
- permission = await Notification.requestPermission();
- }
-
- if (permission === 'granted') {
- // Use service worker to show notification (keeps it persistent)
- const registration = await navigator.serviceWorker.ready;
-
- await registration.showNotification('Speakr Recording', {
- body: 'Recording in progress...',
- icon: '/static/img/icon-192x192.png',
- badge: '/static/img/icon-192x192.png',
- tag: 'recording',
- requireInteraction: true, // Keep notification visible
- silent: true, // Don't make sound
- data: {
- type: 'recording'
- }
- });
-
- console.log('[Notification] Recording notification shown');
- return true;
- } else {
- console.warn('[Notification] Permission denied');
- return false;
- }
- } catch (err) {
- console.error('[Notification] Failed to show notification:', err);
- return false;
- }
- } else {
- console.warn('[Notification] Notifications not supported');
- return false;
- }
- };
-
- // Hide recording notification
- const hideRecordingNotification = async () => {
- if ('serviceWorker' in navigator) {
- try {
- const registration = await navigator.serviceWorker.ready;
- const notifications = await registration.getNotifications({ tag: 'recording' });
- notifications.forEach(notification => notification.close());
- console.log('[Notification] Recording notification hidden');
- } catch (err) {
- console.error('[Notification] Error hiding notification:', err);
- }
- }
- };
-
- // Handle page visibility changes to maintain recording state
- const handleVisibilityChange = async () => {
- const wasVisible = isPageVisible.value;
- isPageVisible.value = !document.hidden;
-
- if (isRecording.value) {
- if (isPageVisible.value && !wasVisible) {
- // Page became visible again
- console.log('[Visibility] Page visible - resuming recording if needed');
-
- // Resume audio context if suspended
- if (audioContext.value && audioContext.value.state === 'suspended') {
- try {
- await audioContext.value.resume();
- console.log('[Visibility] Audio context resumed');
- } catch (err) {
- console.error('[Visibility] Failed to resume audio context:', err);
- }
- }
-
- // Resume MediaRecorder if paused
- if (mediaRecorder.value && mediaRecorder.value.state === 'paused') {
- try {
- mediaRecorder.value.resume();
- console.log('[Visibility] MediaRecorder resumed');
- } catch (err) {
- console.error('[Visibility] Failed to resume MediaRecorder:', err);
- }
- }
-
- // Re-acquire wake lock if it was lost
- if (wakeLock.value === null) {
- requestWakeLock();
- }
-
- // Hide notification when returning to foreground
- hideRecordingNotification();
- } else if (!isPageVisible.value && wasVisible) {
- // Page became hidden
- console.log('[Visibility] Page hidden - keeping recording active');
-
- // Keep audio context running
- if (audioContext.value && audioContext.value.state === 'suspended') {
- try {
- await audioContext.value.resume();
- console.log('[Visibility] Audio context resumed in background');
- } catch (err) {
- console.error('[Visibility] Failed to resume audio context:', err);
- }
- }
-
- // Ensure MediaRecorder is still recording
- if (mediaRecorder.value) {
- console.log('[Visibility] MediaRecorder state:', mediaRecorder.value.state);
-
- // If paused, try to resume
- if (mediaRecorder.value.state === 'paused') {
- try {
- mediaRecorder.value.resume();
- console.log('[Visibility] MediaRecorder resumed from paused state');
- } catch (err) {
- console.error('[Visibility] Failed to resume MediaRecorder:', err);
- }
- }
- }
-
- // Show notification to keep process alive
- showRecordingNotification();
-
- // Notify service worker that recording is active
- if ('serviceWorker' in navigator && navigator.serviceWorker.controller) {
- navigator.serviceWorker.controller.postMessage({
- type: 'RECORDING_STATE',
- isRecording: true,
- duration: recordingTime.value
- });
- }
- }
- }
- };
-
- // Handle wake lock release (e.g., when screen turns off despite wake lock)
- const handleWakeLockRelease = async () => {
- console.log('[Wake Lock] Wake lock was released, attempting to re-acquire...');
-
- // If still recording and page is visible, try to re-acquire
- if (isRecording.value && isPageVisible.value) {
- await requestWakeLock();
- }
- };
-
- // --- Audio Recording ---
- const startRecordingWithDisclaimer = async (mode = 'microphone') => {
- // Check if disclaimer needs to be shown
- if (recordingDisclaimer.value && recordingDisclaimer.value.trim()) {
- pendingRecordingMode.value = mode;
- showRecordingDisclaimerModal.value = true;
- } else {
- // No disclaimer configured, proceed directly
- await startRecordingActual(mode);
- }
- };
-
- const acceptRecordingDisclaimer = async () => {
- showRecordingDisclaimerModal.value = false;
- if (pendingRecordingMode.value) {
- await startRecordingActual(pendingRecordingMode.value);
- pendingRecordingMode.value = null;
- }
- };
-
- const cancelRecordingDisclaimer = () => {
- showRecordingDisclaimerModal.value = false;
- pendingRecordingMode.value = null;
- };
-
- const startRecording = startRecordingWithDisclaimer; // Maintain backward compatibility
-
- const startRecordingActual = async (mode = 'microphone') => {
- recordingMode.value = mode;
-
- try {
- // Load tags if not already loaded
- if (availableTags.value.length === 0) {
- await loadTags();
- }
-
- // Reset state
- audioChunks.value = [];
- audioBlobURL.value = null;
- recordingNotes.value = '';
- activeStreams.value = [];
- // Clear previous tag selection and ASR options for fresh recording
- selectedTagIds.value = [];
- asrLanguage.value = '';
- asrMinSpeakers.value = '';
- asrMaxSpeakers.value = '';
-
- let combinedStream = null;
- let micStream = null;
- let systemStream = null;
-
- // Get microphone stream if needed
- if (mode === 'microphone' || mode === 'both') {
- if (!canRecordAudio.value) {
- throw new Error('Microphone recording is not supported by your browser or permission was denied.');
- }
- micStream = await navigator.mediaDevices.getUserMedia({ audio: true });
- activeStreams.value.push(micStream);
- showToast('Microphone access granted', 'fa-microphone');
- }
-
- // Get system audio stream if needed
- if (mode === 'system' || mode === 'both') {
- if (!canRecordSystemAudio.value) {
- throw new Error('System audio recording is not supported by your browser.');
- }
- try {
- systemStream = await navigator.mediaDevices.getDisplayMedia({
- audio: true,
- video: true // Request video to enable system audio sharing prompt
- });
-
- // Check if the user actually granted audio permission
- if (systemStream.getAudioTracks().length === 0) {
- // Stop the video track if it exists, since we didn't get audio
- systemStream.getVideoTracks().forEach(track => track.stop());
- throw new Error('System audio permission was not granted. Please ensure you check the "Share system audio" box.');
- }
-
- activeStreams.value.push(systemStream);
- showToast('System audio access granted', 'fa-desktop');
- } catch (err) {
- if (mode === 'system') {
- throw err; // Re-throw the original error to be caught by the outer handler
- } else {
- // For 'both' mode, fall back to microphone only
- showToast('System audio denied, using microphone only', 'fa-exclamation-triangle');
- mode = 'microphone';
- systemStream = null; // Make sure systemStream is null so it's not used later
- }
- }
- }
-
- // Combine streams if we have both
- if (micStream && systemStream) {
- try {
- audioContext.value = new (window.AudioContext || window.webkitAudioContext)();
-
- const micSource = audioContext.value.createMediaStreamSource(micStream);
- const systemSource = audioContext.value.createMediaStreamSource(systemStream);
- const destination = audioContext.value.createMediaStreamDestination();
-
- micSource.connect(destination);
- systemSource.connect(destination);
-
- // Create a new MediaStream with only the audio track from the destination
- const mixedAudioTrack = destination.stream.getAudioTracks()[0];
- if (!mixedAudioTrack) {
- throw new Error('Failed to create mixed audio track');
- }
-
- combinedStream = new MediaStream([mixedAudioTrack]);
-
- // Verify the stream has audio tracks
- if (combinedStream.getAudioTracks().length === 0) {
- throw new Error('Combined stream has no audio tracks');
- }
-
- console.log('Successfully created combined audio stream with', combinedStream.getAudioTracks().length, 'audio tracks');
- showToast('Recording both microphone and system audio', 'fa-microphone');
-
- } catch (error) {
- console.error('Failed to combine audio streams:', error);
- // Fallback to system audio only
- if (audioContext.value) {
- audioContext.value.close().catch(e => console.error("Error closing AudioContext:", e));
- audioContext.value = null;
- }
- combinedStream = systemStream;
- showToast('Failed to combine audio, using system audio only', 'fa-exclamation-triangle');
- }
- } else if (systemStream) {
- // For system audio only, create a new stream with just the audio tracks
- const audioTracks = systemStream.getAudioTracks();
- if (audioTracks.length > 0) {
- combinedStream = new MediaStream(audioTracks);
- console.log('Created system audio stream with', audioTracks.length, 'audio tracks');
- showToast('Recording system audio only', 'fa-desktop');
- } else {
- throw new Error('System stream has no audio tracks');
- }
- } else if (micStream) {
- combinedStream = micStream;
- showToast('Recording microphone only', 'fa-microphone');
- } else {
- throw new Error('No audio streams available for recording.');
- }
-
- // Setup MediaRecorder with optimized settings for transcription
- const getOptimizedRecorderOptions = () => {
- // Define transcription-optimized options in order of preference
- const optionsList = [
- // Best option: Opus codec at 32kbps (excellent compression for speech)
- {
- mimeType: 'audio/webm;codecs=opus',
- audioBitsPerSecond: 32000,
- description: 'Optimized (32kbps Opus)'
- },
- // Good option: Opus at 64kbps (slightly higher quality)
- {
- mimeType: 'audio/webm;codecs=opus',
- audioBitsPerSecond: 64000,
- description: 'Good quality (64kbps Opus)'
- },
- // Fallback 1: WebM with reduced bitrate
- {
- mimeType: 'audio/webm',
- audioBitsPerSecond: 64000,
- description: 'Standard WebM (64kbps)'
- },
- // Fallback 2: MP4 with reduced bitrate
- {
- mimeType: 'audio/mp4',
- audioBitsPerSecond: 64000,
- description: 'Standard MP4 (64kbps)'
- },
- // Fallback 3: Just the codec without bitrate
- {
- mimeType: 'audio/webm;codecs=opus',
- description: 'Opus codec (default bitrate)'
- },
- // Fallback 4: Just WebM without bitrate
- {
- mimeType: 'audio/webm',
- description: 'WebM (default bitrate)'
- }
- ];
-
- // Test each option to find the first supported one
- for (const options of optionsList) {
- if (MediaRecorder.isTypeSupported(options.mimeType)) {
- console.log(`Testing audio recording option: ${options.description} - ${options.mimeType}`);
- return options;
- }
- }
-
- // Final fallback: no options (browser default)
- console.log('Using browser default audio recording settings');
- return null;
- };
-
- // Try to create MediaRecorder with progressive fallbacks
- let mediaRecorderCreated = false;
- let recorderOptions = getOptimizedRecorderOptions();
- let attemptCount = 0;
-
- while (!mediaRecorderCreated && attemptCount < 5) {
- try {
- attemptCount++;
-
- if (recorderOptions && attemptCount === 1) {
- // First attempt: try with full options
- console.log(`Attempt ${attemptCount}: Trying ${recorderOptions.description}`);
- mediaRecorder.value = new MediaRecorder(combinedStream, recorderOptions);
- actualBitrate.value = recorderOptions.audioBitsPerSecond || 64000;
- showToast(`Recording: ${recorderOptions.description}`, 'fa-compress-alt', 3000);
- } else if (recorderOptions && attemptCount === 2 && recorderOptions.audioBitsPerSecond) {
- // Second attempt: try same mime type without bitrate constraint
- console.log(`Attempt ${attemptCount}: Trying ${recorderOptions.mimeType} without bitrate`);
- mediaRecorder.value = new MediaRecorder(combinedStream, { mimeType: recorderOptions.mimeType });
- actualBitrate.value = 128000; // Estimate
- showToast(`Recording: ${recorderOptions.mimeType} (default bitrate)`, 'fa-compress-alt', 3000);
- } else {
- // Final attempt: browser default
- console.log(`Attempt ${attemptCount}: Using browser default`);
- mediaRecorder.value = new MediaRecorder(combinedStream);
- actualBitrate.value = 128000; // Estimate browser default
- showToast('Recording with browser default settings', 'fa-microphone', 3000);
- }
-
- mediaRecorderCreated = true;
- console.log(`MediaRecorder created successfully on attempt ${attemptCount}`);
-
- } catch (error) {
- console.warn(`MediaRecorder creation attempt ${attemptCount} failed:`, error);
- mediaRecorder.value = null;
-
- if (attemptCount >= 5) {
- throw new Error(`Failed to create MediaRecorder after ${attemptCount} attempts. Last error: ${error.message}`);
- }
- }
- }
-
- if (!mediaRecorder.value) {
- throw new Error('Failed to create MediaRecorder with any configuration');
- }
-
- console.log(`Recording with estimated bitrate: ${actualBitrate.value} bps`);
-
- // Add state change monitoring
- mediaRecorder.value.onpause = () => {
- console.warn('[MediaRecorder] Recording PAUSED - attempting to resume');
- // Automatically resume if paused (shouldn't happen in normal operation)
- setTimeout(() => {
- if (mediaRecorder.value && mediaRecorder.value.state === 'paused' && isRecording.value) {
- try {
- mediaRecorder.value.resume();
- console.log('[MediaRecorder] Auto-resumed from paused state');
- } catch (err) {
- console.error('[MediaRecorder] Failed to auto-resume:', err);
- }
- }
- }, 100);
- };
-
- mediaRecorder.value.onresume = () => {
- console.log('[MediaRecorder] Recording RESUMED');
- };
-
- mediaRecorder.value.onerror = (event) => {
- console.error('[MediaRecorder] Error occurred:', event.error);
- };
-
- mediaRecorder.value.ondataavailable = event => {
- if (event.data && event.data.size > 0) {
- audioChunks.value.push(event.data);
- // Only log every 10th chunk to reduce console noise
- if (audioChunks.value.length % 10 === 0) {
- console.log(`[MediaRecorder] ${audioChunks.value.length} chunks received (${(audioChunks.value.reduce((sum, chunk) => sum + chunk.size, 0) / 1024).toFixed(1)} KB total)`);
- }
- } else {
- console.warn('[MediaRecorder] Received empty data chunk');
- }
- };
- mediaRecorder.value.onstop = () => {
- const audioBlob = new Blob(audioChunks.value, { type: 'audio/webm' });
- audioBlobURL.value = URL.createObjectURL(audioBlob);
-
- // Stop size monitoring
- stopSizeMonitoring();
-
- // Stop all active streams
- activeStreams.value.forEach(stream => {
- stream.getTracks().forEach(track => track.stop());
- });
- activeStreams.value = [];
-
- if (audioContext.value) {
- audioContext.value.close().catch(e => console.error("Error closing AudioContext:", e));
- audioContext.value = null;
- }
- cancelAnimationFrame(animationFrameId.value);
- clearInterval(recordingInterval.value);
- };
-
- // --- Visualizer Setup ---
- if (!audioContext.value) {
- audioContext.value = new (window.AudioContext || window.webkitAudioContext)();
- }
-
- if (mode === 'both' && micStream && systemStream) {
- // Dual visualizer setup
- micAnalyser.value = audioContext.value.createAnalyser();
- micAnalyser.value.fftSize = 256;
- const micSource = audioContext.value.createMediaStreamSource(micStream);
- micSource.connect(micAnalyser.value);
-
- systemAnalyser.value = audioContext.value.createAnalyser();
- systemAnalyser.value.fftSize = 256;
- const systemSource = audioContext.value.createMediaStreamSource(systemStream);
- systemSource.connect(systemAnalyser.value);
-
- } else {
- // Single visualizer setup
- const visualizerStream = micStream || systemStream;
- if (visualizerStream) {
- analyser.value = audioContext.value.createAnalyser();
- analyser.value.fftSize = 256;
- const source = audioContext.value.createMediaStreamSource(visualizerStream);
- source.connect(analyser.value);
- }
- }
-
- // Start recording and timer
- // Use timeslice to force regular data emission - helps prevent pausing in background
- // Request data every 1 second (1000ms)
- mediaRecorder.value.start(1000);
- console.log('[MediaRecorder] Started with 1-second timeslice for background resilience');
- isRecording.value = true;
- recordingTime.value = 0;
- recordingInterval.value = setInterval(() => {
- recordingTime.value++;
-
- // Keep audio context alive (check every second)
- if (audioContext.value && audioContext.value.state === 'suspended') {
- audioContext.value.resume().then(() => {
- console.log('[Audio Context] Resumed from suspended state');
- }).catch(err => {
- console.error('[Audio Context] Failed to resume:', err);
- });
- }
-
- // Check MediaRecorder state
- if (mediaRecorder.value) {
- if (mediaRecorder.value.state === 'paused') {
- console.warn('[MediaRecorder] Detected paused state during recording');
- mediaRecorder.value.resume();
- }
-
- // Every 30 seconds, check if we're still receiving audio
- if (recordingTime.value % 30 === 0) {
- console.log(`[Recording] ${recordingTime.value}s - State: ${mediaRecorder.value.state}, Chunks: ${audioChunks.value.length}`);
-
- // Check if audio tracks are still active
- activeStreams.value.forEach((stream, idx) => {
- const audioTracks = stream.getAudioTracks();
- audioTracks.forEach((track, trackIdx) => {
- console.log(`[Stream ${idx}] Track ${trackIdx}: ${track.label} - enabled: ${track.enabled}, muted: ${track.muted}, readyState: ${track.readyState}`);
- });
- });
- }
- }
- }, 1000);
-
- // Switch to recording view FIRST (immediately show UI)
- currentView.value = 'recording';
-
- // Start size monitoring
- startSizeMonitoring();
-
- // Start visualizer(s)
- drawVisualizers();
-
- // Acquire wake lock to prevent screen from turning off (non-blocking)
- requestWakeLock().catch(err => {
- console.warn('[Wake Lock] Failed to acquire, recording continues:', err);
- });
-
- // Show notification for background recording support (non-blocking)
- // This helps keep the app active when screen is locked
- showRecordingNotification().catch(err => {
- console.warn('[Notification] Failed to show, recording continues:', err);
- });
-
- // Notify service worker that recording has started (non-blocking)
- if ('serviceWorker' in navigator && navigator.serviceWorker.controller) {
- navigator.serviceWorker.controller.postMessage({
- type: 'RECORDING_STATE',
- isRecording: true,
- duration: 0
- });
- }
-
- setGlobalError(null);
- } catch (err) {
- console.error("Error starting recording:", err);
- setGlobalError(`Could not start recording: ${err.message}`);
- isRecording.value = false;
-
- // Clean up any streams that were created
- activeStreams.value.forEach(stream => {
- stream.getTracks().forEach(track => track.stop());
- });
- activeStreams.value = [];
- }
- };
-
- const stopRecording = async () => {
- if (mediaRecorder.value && isRecording.value) {
- mediaRecorder.value.stop();
- isRecording.value = false;
- stopSizeMonitoring();
- cancelAnimationFrame(animationFrameId.value);
- animationFrameId.value = null;
-
- // Release wake lock
- await releaseWakeLock();
-
- // Hide recording notification
- await hideRecordingNotification();
-
- // Notify service worker that recording has stopped
- if ('serviceWorker' in navigator && navigator.serviceWorker.controller) {
- navigator.serviceWorker.controller.postMessage({
- type: 'RECORDING_STATE',
- isRecording: false,
- duration: recordingTime.value
- });
- }
- }
- };
-
- const uploadRecordedAudio = () => {
- if (!audioBlobURL.value) {
- setGlobalError("No recorded audio to upload.");
- return;
- }
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
- const recordedFile = new File(audioChunks.value, `recording-${timestamp}.webm`, { type: 'audio/webm' });
-
- // Pass notes, tags, and ASR options along with the file
- addFilesToQueue([{
- file: recordedFile,
- notes: recordingNotes.value,
- tags: selectedTags.value,
- asrOptions: {
- language: asrLanguage.value,
- min_speakers: asrMinSpeakers.value,
- max_speakers: asrMaxSpeakers.value
- }
- }]);
- discardRecording();
-
- // Switch back to upload view
- currentView.value = 'upload';
- };
-
- const discardRecording = async () => {
- if (audioBlobURL.value) {
- URL.revokeObjectURL(audioBlobURL.value);
- }
- audioBlobURL.value = null;
- audioChunks.value = [];
- isRecording.value = false;
- recordingTime.value = 0;
- if (recordingInterval.value) clearInterval(recordingInterval.value);
- recordingNotes.value = '';
- // Clear tags and ASR options for fresh start
- selectedTagIds.value = [];
- asrLanguage.value = '';
- asrMinSpeakers.value = '';
- asrMaxSpeakers.value = '';
-
- // Clean up wake lock and notification
- await releaseWakeLock();
- await hideRecordingNotification();
- };
-
- const drawSingleVisualizer = (analyserNode, canvasElement) => {
- if (!analyserNode || !canvasElement) return;
-
- const bufferLength = analyserNode.frequencyBinCount;
- const dataArray = new Uint8Array(bufferLength);
- analyserNode.getByteFrequencyData(dataArray);
-
- const canvasCtx = canvasElement.getContext('2d');
- const WIDTH = canvasElement.width;
- const HEIGHT = canvasElement.height;
-
- canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
-
- const barWidth = (WIDTH / bufferLength) * 1.5;
- let barHeight;
- let x = 0;
-
- // Use theme-specific colors that work with all color schemes
- const buttonColor = getComputedStyle(document.documentElement).getPropertyValue('--bg-button').trim();
- const buttonHoverColor = getComputedStyle(document.documentElement).getPropertyValue('--bg-button-hover').trim();
-
- // Create gradient that works in both light and dark modes
- const gradient = canvasCtx.createLinearGradient(0, 0, 0, HEIGHT);
- if (isDarkMode.value) {
- // Dark mode: use button colors with transparency
- gradient.addColorStop(0, buttonColor);
- gradient.addColorStop(0.6, buttonHoverColor);
- gradient.addColorStop(1, 'rgba(0, 0, 0, 0.2)');
- } else {
- // Light mode: use more saturated colors for visibility
- gradient.addColorStop(0, buttonColor);
- gradient.addColorStop(0.5, buttonHoverColor);
- gradient.addColorStop(1, 'rgba(0, 0, 0, 0.1)');
- }
-
- for (let i = 0; i < bufferLength; i++) {
- barHeight = dataArray[i] / 2.5;
- canvasCtx.fillStyle = gradient;
- canvasCtx.fillRect(x, HEIGHT - barHeight, barWidth, barHeight);
- x += barWidth + 2;
- }
- };
-
- const drawVisualizers = () => {
- if (!isRecording.value) {
- if (animationFrameId.value) {
- cancelAnimationFrame(animationFrameId.value);
- animationFrameId.value = null;
- }
- return;
- }
-
- animationFrameId.value = requestAnimationFrame(drawVisualizers);
-
- if (recordingMode.value === 'both') {
- drawSingleVisualizer(micAnalyser.value, micVisualizer.value);
- drawSingleVisualizer(systemAnalyser.value, systemVisualizer.value);
- } else {
- drawSingleVisualizer(analyser.value, visualizer.value);
- }
- };
-
- // --- Recording Management ---
- const saveMetadata = async (recordingDataToSave) => {
- globalError.value = null;
- if (!recordingDataToSave || !recordingDataToSave.id) return null;
- console.log('Saving metadata for:', recordingDataToSave.id);
- try {
- const payload = {
- id: recordingDataToSave.id,
- title: recordingDataToSave.title,
- participants: recordingDataToSave.participants,
- notes: recordingDataToSave.notes,
- summary: recordingDataToSave.summary,
- meeting_date: recordingDataToSave.meeting_date
- };
- const response = await fetch('/save', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- const data = await response.json();
- if (!response.ok) throw new Error(data.error || 'Failed to save metadata');
-
- console.log('Save successful:', data.recording.id);
- const index = recordings.value.findIndex(r => r.id === data.recording.id);
- if (index !== -1) {
- recordings.value[index].title = payload.title;
- recordings.value[index].participants = payload.participants;
- recordings.value[index].notes = payload.notes;
- recordings.value[index].notes_html = data.recording.notes_html;
- recordings.value[index].summary = payload.summary;
- recordings.value[index].summary_html = data.recording.summary_html;
- recordings.value[index].meeting_date = payload.meeting_date;
- }
- if (selectedRecording.value?.id === data.recording.id) {
- selectedRecording.value.title = payload.title;
- selectedRecording.value.participants = payload.participants;
- selectedRecording.value.notes = payload.notes;
- selectedRecording.value.notes_html = data.recording.notes_html;
- selectedRecording.value.summary = payload.summary;
- selectedRecording.value.summary_html = data.recording.summary_html;
- selectedRecording.value.meeting_date = payload.meeting_date;
- }
- return data.recording;
- } catch (error) {
- console.error('Save Metadata Error:', error);
- setGlobalError(`Save failed: ${error.message}`);
- return null;
- }
- };
-
- const editRecording = (recording) => {
- editingRecording.value = JSON.parse(JSON.stringify(recording));
- showEditModal.value = true;
- };
-
- const cancelEdit = () => {
- showEditModal.value = false;
- editingRecording.value = null;
- };
-
- const saveEdit = async () => {
- const success = await saveMetadata(editingRecording.value);
- if (success) {
- cancelEdit();
- }
- };
-
- const confirmDelete = (recording) => {
- recordingToDelete.value = recording;
- showDeleteModal.value = true;
- };
-
- const cancelDelete = () => {
- showDeleteModal.value = false;
- recordingToDelete.value = null;
- };
-
- const deleteRecording = async () => {
- globalError.value = null;
- if (!recordingToDelete.value) return;
- const idToDelete = recordingToDelete.value.id;
- const titleToDelete = recordingToDelete.value.title;
- try {
- const response = await fetch(`/recording/${idToDelete}`, { method: 'DELETE' });
- const data = await response.json();
- if (!response.ok) throw new Error(data.error || 'Failed to delete recording');
-
- recordings.value = recordings.value.filter(r => r.id !== idToDelete);
- totalRecordings.value--; // Update total count
-
- const queueIndex = uploadQueue.value.findIndex(item => item.recordingId === idToDelete);
- if (queueIndex !== -1) {
- const deletedItem = uploadQueue.value.splice(queueIndex, 1)[0];
- console.log(`Removed item ${deletedItem.clientId} from queue.`);
- if (currentlyProcessingFile.value?.clientId === deletedItem.clientId) {
- console.log(`Deleting currently processing file: ${titleToDelete}. Stopping poll and moving to next.`);
- clearInterval(pollInterval.value);
- pollInterval.value = null;
- resetCurrentFileProcessingState();
- isProcessingActive.value = false;
- await nextTick();
- startProcessingQueue();
- }
- }
-
- if (selectedRecording.value?.id === idToDelete) selectedRecording.value = null;
- cancelDelete();
- console.log(`Successfully deleted recording ${idToDelete} (${titleToDelete})`);
-
- } catch (error) {
- console.error('Delete Error:', error);
- setGlobalError(`Failed to delete recording "${titleToDelete}": ${error.message}`);
- cancelDelete();
- }
- };
-
- // --- Inline Editing ---
- const toggleEditParticipants = () => {
- editingParticipants.value = !editingParticipants.value;
- if (!editingParticipants.value) {
- saveInlineEdit('participants');
- }
- };
-
- const toggleEditMeetingDate = () => {
- editingMeetingDate.value = !editingMeetingDate.value;
- if (!editingMeetingDate.value) {
- saveInlineEdit('meeting_date');
- }
- };
-
- const toggleEditSummary = () => {
- editingSummary.value = !editingSummary.value;
- if (editingSummary.value) {
- // Store current content in temp variable
- tempSummaryContent.value = selectedRecording.value.summary || '';
- nextTick(() => {
- initializeSummaryMarkdownEditor();
- });
- }
- };
-
- const cancelEditSummary = () => {
- if (summaryMarkdownEditorInstance.value) {
- summaryMarkdownEditorInstance.value.toTextArea();
- summaryMarkdownEditorInstance.value = null;
- }
- editingSummary.value = false;
- // Restore original content
- if (selectedRecording.value) {
- selectedRecording.value.summary = tempSummaryContent.value;
- }
- };
-
- const saveEditSummary = async () => {
- if (summaryMarkdownEditorInstance.value) {
- selectedRecording.value.summary = summaryMarkdownEditorInstance.value.value();
- summaryMarkdownEditorInstance.value.toTextArea();
- summaryMarkdownEditorInstance.value = null;
- }
- editingSummary.value = false;
- await saveInlineEdit('summary');
- };
-
- const toggleEditNotes = () => {
- editingNotes.value = !editingNotes.value;
- if (editingNotes.value) {
- // Store current content in temp variable
- tempNotesContent.value = selectedRecording.value.notes || '';
- // Initialize markdown editor when entering edit mode
- nextTick(() => {
- initializeMarkdownEditor();
- });
- }
- };
-
- const cancelEditNotes = () => {
- if (markdownEditorInstance.value) {
- markdownEditorInstance.value.toTextArea();
- markdownEditorInstance.value = null;
- }
- editingNotes.value = false;
- // Restore original content
- if (selectedRecording.value) {
- selectedRecording.value.notes = tempNotesContent.value;
- }
- };
-
- const saveEditNotes = async () => {
- if (markdownEditorInstance.value) {
- // Get the markdown content from the editor
- selectedRecording.value.notes = markdownEditorInstance.value.value();
- markdownEditorInstance.value.toTextArea();
- markdownEditorInstance.value = null;
- }
- editingNotes.value = false;
- await saveInlineEdit('notes');
- };
-
- const clickToEditNotes = () => {
- // Allow clicking on empty notes area to start editing
- if (!editingNotes.value && (!selectedRecording.value?.notes || selectedRecording.value.notes.trim() === '')) {
- toggleEditNotes();
- }
- };
-
- const clickToEditSummary = () => {
- // Allow clicking on empty summary area to start editing
- if (!editingSummary.value && (!selectedRecording.value?.summary || selectedRecording.value.summary.trim() === '')) {
- toggleEditSummary();
- }
- };
-
- const autoSaveNotes = async () => {
- if (markdownEditorInstance.value && editingNotes.value) {
- // Just save the content to the model, don't exit edit mode
- selectedRecording.value.notes = markdownEditorInstance.value.value();
- // Silently save to backend without changing UI state
- try {
- const payload = {
- id: selectedRecording.value.id,
- title: selectedRecording.value.title,
- participants: selectedRecording.value.participants,
- notes: selectedRecording.value.notes,
- summary: selectedRecording.value.summary,
- meeting_date: selectedRecording.value.meeting_date
- };
- const response = await fetch('/save', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify(payload)
- });
- const data = await response.json();
- if (response.ok && data.recording) {
- // Update the HTML rendered versions if they exist
- if (data.recording.notes_html) {
- selectedRecording.value.notes_html = data.recording.notes_html;
- }
- } else {
- console.error('Failed to auto-save notes');
- }
- } catch (error) {
- console.error('Error auto-saving notes:', error);
- }
- }
- };
-
- const autoSaveSummary = async () => {
- if (summaryMarkdownEditorInstance.value && editingSummary.value) {
- // Just save the content to the model, don't exit edit mode
- selectedRecording.value.summary = summaryMarkdownEditorInstance.value.value();
- // Silently save to backend without changing UI state
- try {
- const payload = {
- id: selectedRecording.value.id,
- title: selectedRecording.value.title,
- participants: selectedRecording.value.participants,
- notes: selectedRecording.value.notes,
- summary: selectedRecording.value.summary,
- meeting_date: selectedRecording.value.meeting_date
- };
- const response = await fetch('/save', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify(payload)
- });
- const data = await response.json();
- if (response.ok && data.recording) {
- // Update the HTML rendered versions if they exist
- if (data.recording.summary_html) {
- selectedRecording.value.summary_html = data.recording.summary_html;
- }
- } else {
- console.error('Failed to auto-save summary');
- }
- } catch (error) {
- console.error('Error auto-saving summary:', error);
- }
- }
- };
-
- const initializeMarkdownEditor = () => {
- if (!notesMarkdownEditor.value) return;
-
- try {
- markdownEditorInstance.value = new EasyMDE({
- element: notesMarkdownEditor.value,
- spellChecker: false,
- autofocus: true,
- placeholder: "Enter notes in Markdown format...",
- initialValue: selectedRecording.value?.notes || '',
- status: false,
- toolbar: [
- "bold", "italic", "heading", "|",
- "quote", "unordered-list", "ordered-list", "|",
- "link", "image", "|",
- "preview", "side-by-side", "fullscreen", "|",
- "guide"
- ],
- previewClass: ["editor-preview", "notes-preview"],
- theme: isDarkMode.value ? "dark" : "light"
- });
-
- // Add auto-save functionality
- markdownEditorInstance.value.codemirror.on('change', () => {
- if (autoSaveTimer.value) {
- clearTimeout(autoSaveTimer.value);
- }
- autoSaveTimer.value = setTimeout(() => {
- autoSaveNotes();
- }, autoSaveDelay);
- });
- } catch (error) {
- console.error('Failed to initialize markdown editor:', error);
- // Fallback to regular textarea editing
- editingNotes.value = true;
- }
- };
-
- const initializeRecordingMarkdownEditor = () => {
- if (!recordingNotesEditor.value) {
- console.log('Recording notes editor ref not found');
- return;
- }
-
- // Check if EasyMDE is available
- if (typeof EasyMDE === 'undefined') {
- console.error('EasyMDE is not loaded');
- return;
- }
-
- // Clean up existing instance if any
- if (recordingMarkdownEditorInstance.value) {
- recordingMarkdownEditorInstance.value.toTextArea();
- recordingMarkdownEditorInstance.value = null;
- }
-
- try {
- console.log('Initializing recording markdown editor');
- recordingMarkdownEditorInstance.value = new EasyMDE({
- element: recordingNotesEditor.value,
- spellChecker: false,
- autofocus: false,
- placeholder: "Type your notes in Markdown format...",
- status: false,
- toolbar: [
- "bold", "italic", "heading", "|",
- "quote", "unordered-list", "ordered-list", "|",
- "link", "|",
- "preview", "guide"
- ],
- previewClass: ["editor-preview", "notes-preview"],
- theme: isDarkMode.value ? "dark" : "light",
- initialValue: recordingNotes.value || "",
- maxHeight: "300px", // Add height constraint to prevent unlimited growth
- minHeight: "150px" // Minimum height for usability
- });
-
- // Sync changes back to the reactive variable
- recordingMarkdownEditorInstance.value.codemirror.on('change', () => {
- recordingNotes.value = recordingMarkdownEditorInstance.value.value();
- });
-
- console.log('Recording markdown editor initialized successfully');
- } catch (error) {
- console.error('Failed to initialize recording markdown editor:', error);
- // Keep as regular textarea if EasyMDE fails
- }
- };
-
- const toggleTranscriptionViewMode = () => {
- transcriptionViewMode.value = transcriptionViewMode.value === 'simple' ? 'bubble' : 'simple';
- localStorage.setItem('transcriptionViewMode', transcriptionViewMode.value);
- };
-
- const toggleChatMaximize = () => {
- if (isChatMaximized.value) {
- // If maximized, restore to normal state
- isChatMaximized.value = false;
- } else {
- // If not maximized, maximize and ensure chat is open
- isChatMaximized.value = true;
- if (!showChat.value) {
- showChat.value = true;
- }
- }
- };
-
- const saveInlineEdit = async (field) => {
- if (!selectedRecording.value) return;
-
- const fullPayload = {
- id: selectedRecording.value.id,
- title: selectedRecording.value.title,
- participants: selectedRecording.value.participants,
- notes: selectedRecording.value.notes,
- summary: selectedRecording.value.summary,
- meeting_date: selectedRecording.value.meeting_date
- };
-
- try {
- const updatedRecording = await saveMetadata(fullPayload);
- if (updatedRecording) {
- if (field === 'notes') {
- selectedRecording.value.notes_html = updatedRecording.notes_html;
- } else if (field === 'summary') {
- selectedRecording.value.summary_html = updatedRecording.summary_html;
- }
-
- switch(field) {
- case 'participants':
- editingParticipants.value = false;
- break;
- case 'meeting_date':
- editingMeetingDate.value = false;
- break;
- case 'summary':
- editingSummary.value = false;
- break;
- case 'notes':
- editingNotes.value = false;
- break;
- }
- showToast(`${field.charAt(0).toUpperCase() + field.slice(1).replace('_', ' ')} updated successfully`);
- }
- } catch (error) {
- console.error(`Save ${field} Error:`, error);
- setGlobalError(`Failed to save ${field}: ${error.message}`);
- }
- };
-
- // --- Chat Functionality ---
- // Helper function to check if chat is scrolled to bottom (within bottom 5%)
- const isChatScrolledToBottom = () => {
- if (!chatMessagesRef.value) return true;
- const { scrollTop, scrollHeight, clientHeight } = chatMessagesRef.value;
- const scrollableHeight = scrollHeight - clientHeight;
- if (scrollableHeight <= 0) return true; // No scrolling possible
- const scrollPercentage = scrollTop / scrollableHeight;
- return scrollPercentage >= 0.95; // Within bottom 5%
- };
-
- // Helper function to scroll chat to bottom with smooth behavior
- const scrollChatToBottom = () => {
- if (chatMessagesRef.value) {
- requestAnimationFrame(() => {
- if (chatMessagesRef.value) {
- chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;
- }
- });
- }
- };
-
- const sendChatMessage = async () => {
- if (!chatInput.value.trim() || isChatLoading.value || !selectedRecording.value || selectedRecording.value.status !== 'COMPLETED') {
- return;
- }
-
- const message = chatInput.value.trim();
-
- if (!Array.isArray(chatMessages.value)) {
- chatMessages.value = [];
- }
-
- chatMessages.value.push({ role: 'user', content: message });
- chatInput.value = '';
- isChatLoading.value = true;
-
- await nextTick();
- // Always scroll to bottom when user sends a new message
- scrollChatToBottom();
-
- let assistantMessage = null;
-
- try {
- const messageHistory = chatMessages.value
- .slice(0, -1)
- .map(msg => ({ role: msg.role, content: msg.content }));
-
- const response = await fetch('/chat', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- recording_id: selectedRecording.value.id,
- message: message,
- message_history: messageHistory
- })
- });
-
- if (!response.ok) {
- const errorData = await response.json();
- throw new Error(errorData.error || 'Failed to get chat response');
- }
-
- const reader = response.body.getReader();
- const decoder = new TextDecoder();
- let buffer = '';
-
- const processStream = async () => {
- let isFirstChunk = true;
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
-
- buffer += decoder.decode(value, { stream: true });
- const lines = buffer.split('\n');
- buffer = lines.pop();
-
- for (const line of lines) {
- if (line.startsWith('data: ')) {
- const jsonStr = line.substring(6);
- if (jsonStr) {
- try {
- const data = JSON.parse(jsonStr);
- if (data.thinking) {
- // Check scroll position BEFORE updating content
- const shouldScroll = isChatScrolledToBottom();
-
- if (isFirstChunk) {
- isChatLoading.value = false;
- assistantMessage = reactive({
- role: 'assistant',
- content: '',
- html: '',
- thinking: data.thinking,
- thinkingExpanded: false
- });
- chatMessages.value.push(assistantMessage);
- isFirstChunk = false;
- } else if (assistantMessage) {
- // Append to existing thinking content
- if (assistantMessage.thinking) {
- assistantMessage.thinking += '\n\n' + data.thinking;
- } else {
- assistantMessage.thinking = data.thinking;
- }
- }
-
- // Scroll if we were at bottom before the update
- if (shouldScroll) {
- await nextTick();
- scrollChatToBottom();
- }
- }
- if (data.delta) {
- // Check scroll position BEFORE updating content
- const shouldScroll = isChatScrolledToBottom();
-
- if (isFirstChunk) {
- isChatLoading.value = false;
- assistantMessage = reactive({
- role: 'assistant',
- content: '',
- html: '',
- thinking: '',
- thinkingExpanded: false
- });
- chatMessages.value.push(assistantMessage);
- isFirstChunk = false;
- }
-
- assistantMessage.content += data.delta;
- assistantMessage.html = marked.parse(assistantMessage.content);
-
- // Scroll if we were at bottom before the update
- if (shouldScroll) {
- await nextTick();
- scrollChatToBottom();
- }
- }
- if (data.end_of_stream) {
- return;
- }
- if (data.error) {
- throw new Error(data.error);
- }
- } catch (e) {
- console.error('Error parsing stream data:', e);
- }
- }
- }
- }
- }
- };
-
- await processStream();
-
- } catch (error) {
- console.error('Chat Error:', error);
- if (assistantMessage) {
- assistantMessage.content = `Error: ${error.message}`;
- assistantMessage.html = `<span class="text-red-500">Error: ${error.message}</span>`;
- } else {
- chatMessages.value.push({ role: 'assistant', content: `Error: ${error.message}`, html: `<span class="text-red-500">Error: ${error.message}</span>` });
- }
- } finally {
- isChatLoading.value = false;
- await nextTick();
- // Final scroll only if user is at bottom
- if (isChatScrolledToBottom()) {
- scrollChatToBottom();
- }
- }
- };
-
- // --- Column Resizing ---
- const startColumnResize = (event) => {
- isResizing.value = true;
- const startX = event.clientX;
- const startLeftWidth = leftColumnWidth.value;
-
- const handleMouseMove = (e) => {
- if (!isResizing.value) return;
-
- const container = document.getElementById('mainContentColumns');
- if (!container) return;
-
- const containerRect = container.getBoundingClientRect();
- const deltaX = e.clientX - startX;
- const containerWidth = containerRect.width;
- const deltaPercent = (deltaX / containerWidth) * 100;
-
- let newLeftWidth = startLeftWidth + deltaPercent;
- newLeftWidth = Math.max(20, Math.min(80, newLeftWidth)); // Constrain between 20% and 80%
-
- leftColumnWidth.value = newLeftWidth;
- rightColumnWidth.value = 100 - newLeftWidth;
- };
-
- const handleMouseUp = () => {
- isResizing.value = false;
- document.removeEventListener('mousemove', handleMouseMove);
- document.removeEventListener('mouseup', handleMouseUp);
-
- // Save to localStorage
- localStorage.setItem('transcriptColumnWidth', leftColumnWidth.value);
- localStorage.setItem('summaryColumnWidth', rightColumnWidth.value);
- };
-
- document.addEventListener('mousemove', handleMouseMove);
- document.addEventListener('mouseup', handleMouseUp);
- event.preventDefault();
- };
-
- // --- Chat Input Handling ---
- const handleChatKeydown = (event) => {
- if (event.key === 'Enter') {
- if (event.ctrlKey || event.shiftKey) {
- // Ctrl+Enter or Shift+Enter: add new line (default behavior)
- return;
- } else {
- // Enter: send message
- event.preventDefault();
- sendChatMessage();
- }
- }
- };
-
- // --- Audio Player ---
- const seekAudio = (time, context = 'main') => {
- let audioPlayer = null;
- if (context === 'modal') {
- // The audio player in the modal has the class directly on the audio element
- audioPlayer = document.querySelector('audio.speaker-modal-transcript');
- } else {
- audioPlayer = document.querySelector('.main-content-area audio');
- }
-
- if (audioPlayer) {
- const wasPlaying = !audioPlayer.paused;
- audioPlayer.currentTime = time;
- if (wasPlaying) {
- audioPlayer.play();
- }
- } else {
- console.warn(`Audio player not found for context: ${context}`);
- // Fallback to old method if new one fails
- const oldPlayer = document.querySelector('audio');
- if(oldPlayer) {
- const wasPlaying = !oldPlayer.paused;
- oldPlayer.currentTime = time;
- if (wasPlaying) {
- oldPlayer.play();
- }
- }
- }
- };
-
- const seekAudioFromEvent = (event) => {
- const segmentElement = event.target.closest('[data-start-time]');
- if (!segmentElement) return;
-
- const time = parseFloat(segmentElement.dataset.startTime);
- if (isNaN(time)) return;
-
- // Determine context by checking if we're inside the speaker modal
- const isInSpeakerModal = event.target.closest('.speaker-modal-transcript') !== null;
- const context = isInSpeakerModal ? 'modal' : 'main';
-
- seekAudio(time, context);
- };
-
- const onPlayerVolumeChange = (event) => {
- const newVolume = event.target.volume;
- playerVolume.value = newVolume;
- localStorage.setItem('playerVolume', newVolume);
- };
-
- // --- i18n Helper Functions ---
- // Use the same safeT function that's globally available
- const t = safeT;
-
- const tc = (key, count, params = {}) => {
- return window.i18n ? window.i18n.tc(key, count, params) : key;
- };
-
- const changeLanguage = async (langCode) => {
- if (window.i18n) {
- await window.i18n.setLocale(langCode);
- currentLanguage.value = langCode;
- const lang = availableLanguages.value.find(l => l.code === langCode);
- currentLanguageName.value = lang ? lang.nativeName : 'English';
- showLanguageMenu.value = false;
- isUserMenuOpen.value = false;
-
- // Save preference to backend
- try {
- await fetch('/api/user/preferences', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRF-Token': csrfToken.value
- },
- body: JSON.stringify({ language: langCode })
- });
- } catch (error) {
- console.error('Failed to save language preference:', error);
- }
- }
- };
-
- // --- Toast Notifications ---
- const showToast = (message, icon = 'fa-check-circle', duration = 2000) => {
- const toastContainer = document.getElementById('toastContainer');
-
- const toast = document.createElement('div');
- toast.className = 'toast';
- toast.innerHTML = `<i class="fas ${icon}"></i> ${message}`;
-
- toastContainer.appendChild(toast);
-
- setTimeout(() => {
- toast.classList.add('show');
- }, 10);
-
- setTimeout(() => {
- toast.classList.remove('show');
- setTimeout(() => {
- toastContainer.removeChild(toast);
- }, 300);
- }, duration);
- };
-
- const animateCopyButton = (button) => {
- button.classList.add('copy-success');
-
- const originalContent = button.innerHTML;
- button.innerHTML = '<i class="fas fa-check"></i>';
-
- setTimeout(() => {
- button.classList.remove('copy-success');
- button.innerHTML = originalContent;
- }, 1500);
- };
-
- const copyMessage = (text, event) => {
- const button = event.currentTarget;
-
- if (navigator.clipboard && window.isSecureContext) {
- navigator.clipboard.writeText(text)
- .then(() => {
- showToast('Copied to clipboard!');
- animateCopyButton(button);
- })
- .catch(err => {
- console.error('Copy failed:', err);
- showToast('Failed to copy: ' + err.message, 'fa-exclamation-circle');
- fallbackCopyTextToClipboard(text, button);
- });
- } else {
- fallbackCopyTextToClipboard(text, button);
- }
- };
-
- const fallbackCopyTextToClipboard = (text, button = null) => {
- try {
- const textArea = document.createElement("textarea");
- textArea.value = text;
-
- textArea.style.position = "fixed";
- textArea.style.left = "-999999px";
- textArea.style.top = "-999999px";
- document.body.appendChild(textArea);
-
- textArea.focus();
- textArea.select();
- const successful = document.execCommand('copy');
-
- document.body.removeChild(textArea);
-
- if (successful) {
- showToast('Copied to clipboard!');
- if (button) animateCopyButton(button);
- } else {
- showToast('Copy failed. Your browser may not support this feature.', 'fa-exclamation-circle');
- }
- } catch (err) {
- console.error('Fallback copy failed:', err);
- showToast('Unable to copy: ' + err.message, 'fa-exclamation-circle');
- }
- };
-
- const copyTranscription = (event) => {
- if (!selectedRecording.value || !selectedRecording.value.transcription) {
- showToast('No transcription available to copy.', 'fa-exclamation-circle');
- return;
- }
-
- const button = event.currentTarget;
- let textToCopy = '';
-
- try {
- const transcriptionData = JSON.parse(selectedRecording.value.transcription);
- if (Array.isArray(transcriptionData)) {
- const wasDiarized = transcriptionData.some(segment => segment.speaker);
- if (wasDiarized) {
- textToCopy = transcriptionData.map(segment => {
- const speakerName = segment.speaker;
- return `[${speakerName}]: ${segment.sentence}`;
- }).join('\n');
- } else {
- textToCopy = transcriptionData.map(segment => segment.sentence).join('\n');
- }
- } else {
- textToCopy = selectedRecording.value.transcription;
- }
- } catch (e) {
- textToCopy = selectedRecording.value.transcription;
- }
-
- animateCopyButton(button);
-
- if (navigator.clipboard && window.isSecureContext) {
- navigator.clipboard.writeText(textToCopy)
- .then(() => {
- showToast('Transcription copied to clipboard!');
- })
- .catch(err => {
- console.error('Copy failed:', err);
- showToast('Failed to copy: ' + err.message, 'fa-exclamation-circle');
- fallbackCopyTextToClipboard(textToCopy);
- });
- } else {
- fallbackCopyTextToClipboard(textToCopy);
- }
- };
-
- const copySummary = (event) => {
- if (!selectedRecording.value || !selectedRecording.value.summary) {
- showToast('No summary available to copy.', 'fa-exclamation-circle');
- return;
- }
- const button = event.currentTarget;
- const textToCopy = selectedRecording.value.summary;
- animateCopyButton(button);
- if (navigator.clipboard && window.isSecureContext) {
- navigator.clipboard.writeText(textToCopy)
- .then(() => {
- showToast('Summary copied to clipboard!');
- })
- .catch(err => {
- console.error('Copy failed:', err);
- showToast('Failed to copy: ' + err.message, 'fa-exclamation-circle');
- fallbackCopyTextToClipboard(textToCopy);
- });
- } else {
- fallbackCopyTextToClipboard(textToCopy);
- }
- };
-
- const copyNotes = (event) => {
- if (!selectedRecording.value || !selectedRecording.value.notes) {
- showToast('No notes available to copy.', 'fa-exclamation-circle');
- return;
- }
- const button = event.currentTarget;
- const textToCopy = selectedRecording.value.notes;
- animateCopyButton(button);
- if (navigator.clipboard && window.isSecureContext) {
- navigator.clipboard.writeText(textToCopy)
- .then(() => {
- showToast('Notes copied to clipboard!');
- })
- .catch(err => {
- console.error('Copy failed:', err);
- showToast('Failed to copy: ' + err.message, 'fa-exclamation-circle');
- fallbackCopyTextToClipboard(textToCopy);
- });
- } else {
- fallbackCopyTextToClipboard(textToCopy);
- }
- };
-
- const downloadSummary = async () => {
- if (!selectedRecording.value || !selectedRecording.value.summary) {
- showToast('No summary available to download.', 'fa-exclamation-circle');
- return;
- }
-
- try {
- const response = await fetch(`/recording/${selectedRecording.value.id}/download/summary`);
- if (!response.ok) {
- const error = await response.json();
- showToast(error.error || 'Failed to download summary', 'fa-exclamation-circle');
- return;
- }
-
- // Create blob and download
- const blob = await response.blob();
- const url = window.URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.style.display = 'none';
- a.href = url;
-
- // Get filename from response headers or use default
- const contentDisposition = response.headers.get('Content-Disposition');
- let filename = 'summary.docx';
- if (contentDisposition) {
- console.log('DEBUG: Content-Disposition header:', contentDisposition);
-
- // Try UTF-8 encoded filename first (for Chinese characters)
- const utf8Match = /filename\*=utf-8''(.+)/.exec(contentDisposition);
- if (utf8Match) {
- filename = decodeURIComponent(utf8Match[1]);
- console.log('DEBUG: Using UTF-8 filename:', filename);
- } else {
- // Fallback to regular filename
- const regularMatch = /filename="(.+)"/.exec(contentDisposition);
- if (regularMatch) {
- filename = regularMatch[1];
- console.log('DEBUG: Using regular filename:', filename);
- }
- }
- }
- a.download = filename;
-
- document.body.appendChild(a);
- a.click();
- window.URL.revokeObjectURL(url);
- document.body.removeChild(a);
-
- showToast('Summary downloaded successfully!');
- } catch (error) {
- console.error('Download failed:', error);
- showToast('Failed to download summary', 'fa-exclamation-circle');
- }
- };
-
- const downloadTranscript = async () => {
- if (!selectedRecording.value || !selectedRecording.value.transcription) {
- showToast('No transcription available to download.', 'fa-exclamation-circle');
- return;
- }
-
- try {
- // First, fetch available templates
- const templatesResponse = await fetch('/api/transcript-templates');
- let templates = [];
- if (templatesResponse.ok) {
- templates = await templatesResponse.json();
- }
-
- // If there are templates, show a selection dialog
- let templateId = null;
- if (templates.length > 0) {
- // Create a simple modal for template selection
- const modal = document.createElement('div');
- modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
- modal.innerHTML = `
- <div class="bg-[var(--bg-secondary)] rounded-lg p-6 max-w-md w-full mx-4">
- <h3 class="text-lg font-semibold mb-4">${t('transcriptTemplates.selectTemplate')}</h3>
- <div class="space-y-2 max-h-60 overflow-y-auto">
- ${templates.map(tmpl => `
- <button class="template-option w-full text-left p-3 rounded border border-[var(--border-primary)] hover:bg-[var(--bg-tertiary)] ${tmpl.is_default ? 'ring-2 ring-[var(--ring-focus)]' : ''}" data-template-id="${tmpl.id}">
- <div class="font-medium">${tmpl.name}</div>
- ${tmpl.description ? `<div class="text-sm text-[var(--text-muted)]">${tmpl.description}</div>` : ''}
- ${tmpl.is_default ? `<div class="text-xs text-[var(--text-accent)] mt-1"><i class="fas fa-star mr-1"></i>${t('transcriptTemplates.default')}</div>` : ''}
- </button>
- `).join('')}
- </div>
- <div class="mt-4 flex gap-2">
- <button class="cancel-btn px-4 py-2 bg-[var(--bg-tertiary)] text-[var(--text-secondary)] rounded hover:bg-[var(--bg-accent-light)]">${t('transcriptTemplates.cancel')}</button>
- <button class="download-without-template-btn px-4 py-2 bg-[var(--bg-accent)] text-white rounded hover:bg-[var(--bg-accent-hover)]">${t('transcriptTemplates.downloadWithoutTemplate')}</button>
- </div>
- </div>
- `;
- document.body.appendChild(modal);
-
- // Wait for user selection
- await new Promise((resolve) => {
- modal.querySelectorAll('.template-option').forEach(btn => {
- btn.addEventListener('click', () => {
- templateId = btn.dataset.templateId;
- modal.remove();
- resolve();
- });
- });
-
- modal.querySelector('.cancel-btn').addEventListener('click', () => {
- templateId = 'cancelled'; // Mark as cancelled
- modal.remove();
- resolve();
- });
-
- modal.querySelector('.download-without-template-btn').addEventListener('click', () => {
- templateId = 'none'; // Use 'none' to indicate no template
- modal.remove();
- resolve();
- });
-
- modal.addEventListener('click', (e) => {
- if (e.target === modal) {
- templateId = 'cancelled'; // Mark as cancelled when clicking outside
- modal.remove();
- resolve();
- }
- });
- });
-
- if (templateId === null || templateId === undefined || templateId === 'cancelled') {
- // User cancelled
- return;
- }
- }
-
- // If templateId is 'none', download raw transcript without any template
- if (templateId === 'none') {
- // Create raw transcript text
- let rawText = '';
- try {
- const transcriptionData = JSON.parse(selectedRecording.value.transcription);
- if (Array.isArray(transcriptionData)) {
- rawText = transcriptionData.map(segment => {
- const speaker = segment.speaker || 'Unknown';
- const text = segment.sentence || '';
- return `${speaker}: ${text}`;
- }).join('\n');
- } else {
- rawText = selectedRecording.value.transcription;
- }
- } catch (e) {
- rawText = selectedRecording.value.transcription;
- }
-
- // Create and download the file directly
- const blob = new Blob([rawText], { type: 'text/plain;charset=utf-8' });
- const downloadUrl = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = downloadUrl;
- a.download = `${selectedRecording.value.title || 'transcript'}_raw.txt`;
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- URL.revokeObjectURL(downloadUrl);
-
- showToast('Transcript downloaded successfully!');
- return;
- }
-
- // Download the transcript with the selected template
- const url = templateId
- ? `/recording/${selectedRecording.value.id}/download/transcript?template_id=${templateId}`
- : `/recording/${selectedRecording.value.id}/download/transcript`;
-
- const response = await fetch(url);
- if (!response.ok) {
- throw new Error('Failed to download transcript');
- }
-
- const blob = await response.blob();
- const contentDisposition = response.headers.get('content-disposition');
- let filename = 'transcript.txt';
- if (contentDisposition) {
- const matches = contentDisposition.match(/filename="([^"]+)"/);
- if (matches && matches[1]) {
- filename = matches[1];
- }
- }
-
- // Create download link
- const downloadUrl = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = downloadUrl;
- a.download = filename;
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- URL.revokeObjectURL(downloadUrl);
-
- showToast('Transcript downloaded successfully!');
- } catch (error) {
- console.error('Error downloading transcript:', error);
- showToast('Failed to download transcript', 'fa-exclamation-circle');
- }
- };
-
- const downloadNotes = async () => {
- if (!selectedRecording.value || !selectedRecording.value.notes) {
- showToast('No notes available to download.', 'fa-exclamation-circle');
- return;
- }
-
- try {
- const response = await fetch(`/recording/${selectedRecording.value.id}/download/notes`);
- if (!response.ok) {
- const error = await response.json();
- showToast(error.error || 'Failed to download notes', 'fa-exclamation-circle');
- return;
- }
-
- // Create blob and download
- const blob = await response.blob();
- const url = window.URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.style.display = 'none';
- a.href = url;
-
- // Get filename from response headers or use default
- const contentDisposition = response.headers.get('Content-Disposition');
- let filename = 'notes.docx';
- if (contentDisposition) {
- console.log('DEBUG: Content-Disposition header:', contentDisposition);
-
- // Try UTF-8 encoded filename first (for Chinese characters)
- const utf8Match = /filename\*=utf-8''(.+)/.exec(contentDisposition);
- if (utf8Match) {
- filename = decodeURIComponent(utf8Match[1]);
- console.log('DEBUG: Using UTF-8 filename:', filename);
- } else {
- // Fallback to regular filename
- const regularMatch = /filename="(.+)"/.exec(contentDisposition);
- if (regularMatch) {
- filename = regularMatch[1];
- console.log('DEBUG: Using regular filename:', filename);
- }
- }
- }
- a.download = filename;
-
- document.body.appendChild(a);
- a.click();
- window.URL.revokeObjectURL(url);
- document.body.removeChild(a);
-
- showToast('Notes downloaded successfully!', 'fa-check-circle');
- } catch (error) {
- console.error('Download failed:', error);
- showToast('Failed to download notes', 'fa-exclamation-circle');
- }
- };
-
- const downloadEventICS = async (event) => {
- if (!event || !event.id) {
- showToast('Invalid event data', 'fa-exclamation-circle');
- return;
- }
-
- try {
- const response = await fetch(`/api/event/${event.id}/ics`);
- if (!response.ok) {
- const error = await response.json();
- showToast(error.error || 'Failed to download event', 'fa-exclamation-circle');
- return;
- }
-
- // Create blob and download
- const blob = await response.blob();
- const url = window.URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.style.display = 'none';
- a.href = url;
- a.download = `${event.title || 'event'}.ics`;
- document.body.appendChild(a);
- a.click();
- window.URL.revokeObjectURL(url);
- document.body.removeChild(a);
-
- showToast(`Event "${event.title}" downloaded. Open the file to add to your calendar.`, 'fa-calendar-check', 3000);
- } catch (error) {
- console.error('Download failed:', error);
- showToast('Failed to download event', 'fa-exclamation-circle');
- }
- };
-
- const downloadICS = async () => {
- if (!selectedRecording.value || !selectedRecording.value.events || selectedRecording.value.events.length === 0) {
- showToast('No events to export', 'fa-exclamation-circle');
- return;
- }
-
- try {
- const response = await fetch(`/api/recording/${selectedRecording.value.id}/events/ics`);
- if (!response.ok) {
- const error = await response.json();
- showToast(error.error || 'Failed to export events', 'fa-exclamation-circle');
- return;
- }
-
- // Create blob and download
- const blob = await response.blob();
- const url = window.URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.style.display = 'none';
- a.href = url;
- a.download = `events-${selectedRecording.value.title || selectedRecording.value.id}.ics`;
- document.body.appendChild(a);
- a.click();
- window.URL.revokeObjectURL(url);
- document.body.removeChild(a);
-
- showToast(`Exported ${selectedRecording.value.events.length} events`, 'fa-calendar-check');
- } catch (error) {
- console.error('Download all events ICS error:', error);
- showToast('Failed to export events', 'fa-exclamation-circle');
- }
- };
-
- const formatEventDateTime = (dateTimeStr) => {
- if (!dateTimeStr) return '';
- try {
- const date = new Date(dateTimeStr);
- const options = {
- weekday: 'short',
- year: 'numeric',
- month: 'short',
- day: 'numeric',
- hour: '2-digit',
- minute: '2-digit'
- };
- return date.toLocaleString(undefined, options);
- } catch (e) {
- return dateTimeStr;
- }
- };
-
- const downloadChat = async () => {
- if (!selectedRecording.value || chatMessages.value.length === 0) {
- showToast('No chat messages to download.', 'fa-exclamation-circle');
- return;
- }
-
- try {
- const response = await fetch(`/recording/${selectedRecording.value.id}/download/chat`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': csrfToken.value
- },
- body: JSON.stringify({
- messages: chatMessages.value
- })
- });
-
- if (!response.ok) {
- const error = await response.json();
- showToast(error.error || 'Failed to download chat', 'fa-exclamation-circle');
- return;
- }
-
- // Create blob and download
- const blob = await response.blob();
- const url = window.URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.style.display = 'none';
- a.href = url;
-
- // Get filename from response headers or use default
- const contentDisposition = response.headers.get('Content-Disposition');
- let filename = 'chat.docx';
- if (contentDisposition) {
- console.log('DEBUG: Content-Disposition header:', contentDisposition);
-
- // Try UTF-8 encoded filename first (for Chinese characters)
- const utf8Match = /filename\*=utf-8''(.+)/.exec(contentDisposition);
- if (utf8Match) {
- filename = decodeURIComponent(utf8Match[1]);
- console.log('DEBUG: Using UTF-8 filename:', filename);
- } else {
- // Fallback to regular filename
- const regularMatch = /filename="(.+)"/.exec(contentDisposition);
- if (regularMatch) {
- filename = regularMatch[1];
- console.log('DEBUG: Using regular filename:', filename);
- }
- }
- }
- a.download = filename;
-
- document.body.appendChild(a);
- a.click();
- window.URL.revokeObjectURL(url);
- document.body.removeChild(a);
-
- showToast('Notes downloaded successfully!');
- } catch (error) {
- console.error('Download failed:', error);
- showToast('Failed to download notes', 'fa-exclamation-circle');
- }
- };
-
- const clearChat = () => {
- if (chatMessages.value.length > 0) {
- chatMessages.value = [];
- showToast('Chat cleared', 'fa-broom');
- }
- };
-
- const openShareModal = async (recording) => {
- recordingToShare.value = recording;
- shareOptions.share_summary = true;
- shareOptions.share_notes = true;
- generatedShareLink.value = '';
- existingShareDetected.value = false;
- showShareModal.value = true;
-
- // Check for existing share
- try {
- const response = await fetch(`/api/recording/${recording.id}/share`, {
- method: 'GET'
- });
- const data = await response.json();
- if (response.ok && data.exists) {
- generatedShareLink.value = data.share_url;
- existingShareDetected.value = true;
- shareOptions.share_summary = data.share.share_summary;
- shareOptions.share_notes = data.share.share_notes;
- }
- } catch (error) {
- console.error('Error checking for existing share:', error);
- }
- };
-
- const closeShareModal = () => {
- showShareModal.value = false;
- recordingToShare.value = null;
- existingShareDetected.value = false;
- };
-
- const createShare = async (forceNew = false) => {
- if (!recordingToShare.value) return;
- try {
- const response = await fetch(`/api/recording/${recordingToShare.value.id}/share`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- ...shareOptions,
- force_new: forceNew
- })
- });
- const data = await response.json();
- if (!response.ok) throw new Error(data.error || 'Failed to create share link');
-
- generatedShareLink.value = data.share_url;
- existingShareDetected.value = data.existing && !forceNew;
-
- if (data.existing && !forceNew) {
- // Show that we're using an existing share
- showToast('Using existing share link', 'fa-link');
- } else {
- showToast('Share link created successfully!', 'fa-check-circle');
- }
- } catch (error) {
- setGlobalError(`Failed to create share link: ${error.message}`);
- }
- };
-
- const copyShareLink = () => {
- if (!generatedShareLink.value) return;
- navigator.clipboard.writeText(generatedShareLink.value).then(() => {
- showToast('Share link copied to clipboard!');
- });
- };
-
- const openSharesList = async () => {
- isLoadingShares.value = true;
- showSharesListModal.value = true;
- try {
- const response = await fetch('/api/shares');
- const data = await response.json();
- if (!response.ok) throw new Error(data.error || 'Failed to load shared items');
- userShares.value = data;
- } catch (error) {
- setGlobalError(`Failed to load shared items: ${error.message}`);
- } finally {
- isLoadingShares.value = false;
- }
- };
-
- const closeSharesList = () => {
- showSharesListModal.value = false;
- userShares.value = [];
- };
-
- const updateShare = async (share) => {
- try {
- const response = await fetch(`/api/share/${share.id}`, {
- method: 'PUT',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- share_summary: share.share_summary,
- share_notes: share.share_notes
- })
- });
- const data = await response.json();
- if (!response.ok) throw new Error(data.error || 'Failed to update share');
- showToast('Share permissions updated.', 'fa-check-circle');
- } catch (error) {
- setGlobalError(`Failed to update share: ${error.message}`);
- }
- };
-
- const confirmDeleteShare = (share) => {
- shareToDelete.value = share;
- showShareDeleteModal.value = true;
- };
-
- const cancelDeleteShare = () => {
- shareToDelete.value = null;
- showShareDeleteModal.value = false;
- };
-
- const deleteShare = async () => {
- if (!shareToDelete.value) return;
- const shareId = shareToDelete.value.id;
- try {
- const response = await fetch(`/api/share/${shareId}`, { method: 'DELETE' });
- const data = await response.json();
- if (!response.ok) throw new Error(data.error || 'Failed to delete share');
- userShares.value = userShares.value.filter(s => s.id !== shareId);
- showToast('Share link deleted successfully.', 'fa-check-circle');
- showShareDeleteModal.value = false;
- shareToDelete.value = null;
- } catch (error) {
- setGlobalError(`Failed to delete share: ${error.message}`);
- }
- };
-
- // --- Watchers ---
- watch(uploadQueue, (newQueue, oldQueue) => {
- if (newQueue.length === 0 && oldQueue.length > 0 && !isProcessingActive.value) {
- console.log("Upload queue processing finished.");
- setTimeout(() => progressPopupMinimized.value = true, 500);
- setTimeout(() => {
- if (completedInQueue.value === totalInQueue.value && !isProcessingActive.value) {
- progressPopupClosed.value = true;
- }
- }, 2000);
- }
- }, { deep: true });
-
- // Watch for changes to speakerMap to handle "This is Me" functionality
- watch(speakerMap, (newSpeakerMap) => {
- if (!newSpeakerMap) return;
-
- Object.keys(newSpeakerMap).forEach(speakerId => {
- const speakerData = newSpeakerMap[speakerId];
- if (speakerData.isMe && currentUserName.value && !speakerData.name) {
- // Automatically fill in the user's name when "This is Me" is checked
- speakerData.name = currentUserName.value;
- } else if (!speakerData.isMe && speakerData.name === currentUserName.value) {
- // Clear the name if "This is Me" is unchecked and the name matches the current user
- speakerData.name = '';
- }
- });
- }, { deep: true });
-
- // Watch for tab changes to save content properly
- watch(selectedTab, (newTab, oldTab) => {
- // Save content when switching away from notes tab but keep editor open
- if (oldTab === 'notes' && editingNotes.value && markdownEditorInstance.value) {
- // Save the current content from the editor
- const currentContent = markdownEditorInstance.value.value();
- selectedRecording.value.notes = currentContent;
- // Call auto-save instead of saveInlineEdit to keep editor open
- autoSaveNotes();
- // Store that we need to recreate the editor when coming back
- tempNotesContent.value = currentContent;
- }
- // Save content when switching away from summary tab but keep editor open
- if (oldTab === 'summary' && editingSummary.value && summaryMarkdownEditorInstance.value) {
- // Save the current content from the editor
- const currentContent = summaryMarkdownEditorInstance.value.value();
- selectedRecording.value.summary = currentContent;
- // Call auto-save instead of saveInlineEdit to keep editor open
- autoSaveSummary();
- // Store that we need to recreate the editor when coming back
- tempSummaryContent.value = currentContent;
- }
-
- // Re-initialize editors when switching back to tabs
- if (newTab === 'notes' && editingNotes.value) {
- // Destroy old instance if exists
- if (markdownEditorInstance.value) {
- markdownEditorInstance.value.toTextArea();
- markdownEditorInstance.value = null;
- }
- // Re-initialize the editor in next tick
- nextTick(() => {
- initializeMarkdownEditor();
- });
- }
- if (newTab === 'summary' && editingSummary.value) {
- // Destroy old instance if exists
- if (summaryMarkdownEditorInstance.value) {
- summaryMarkdownEditorInstance.value.toTextArea();
- summaryMarkdownEditorInstance.value = null;
- }
- // Re-initialize the editor in next tick
- nextTick(() => {
- initializeSummaryMarkdownEditor();
- });
- }
- });
-
- // Watch for mobile tab changes similarly
- watch(mobileTab, (newTab, oldTab) => {
- // Save content when switching away from notes tab but keep editor open
- if (oldTab === 'notes' && editingNotes.value && markdownEditorInstance.value) {
- const currentContent = markdownEditorInstance.value.value();
- selectedRecording.value.notes = currentContent;
- autoSaveNotes(); // Use auto-save instead
- tempNotesContent.value = currentContent;
- }
- // Save content when switching away from summary tab but keep editor open
- if (oldTab === 'summary' && editingSummary.value && summaryMarkdownEditorInstance.value) {
- const currentContent = summaryMarkdownEditorInstance.value.value();
- selectedRecording.value.summary = currentContent;
- autoSaveSummary(); // Use auto-save instead
- tempSummaryContent.value = currentContent;
- }
-
- // Re-initialize editors when switching back to tabs on mobile
- if (newTab === 'notes' && editingNotes.value) {
- if (markdownEditorInstance.value) {
- markdownEditorInstance.value.toTextArea();
- markdownEditorInstance.value = null;
- }
- nextTick(() => {
- initializeMarkdownEditor();
- });
- }
- if (newTab === 'summary' && editingSummary.value) {
- if (summaryMarkdownEditorInstance.value) {
- summaryMarkdownEditorInstance.value.toTextArea();
- summaryMarkdownEditorInstance.value = null;
- }
- nextTick(() => {
- initializeSummaryMarkdownEditor();
- });
- }
- });
-
- watch(selectedRecording, (newVal, oldVal) => {
- if (newVal?.id !== oldVal?.id) {
- // Save any pending edits before switching recordings
- if (editingNotes.value && markdownEditorInstance.value && oldVal?.id) {
- selectedRecording.value = oldVal; // Temporarily restore old recording
- saveEditNotes(); // This will save and cleanup
- selectedRecording.value = newVal; // Switch back to new recording
- }
- if (editingSummary.value && summaryMarkdownEditorInstance.value && oldVal?.id) {
- selectedRecording.value = oldVal; // Temporarily restore old recording
- saveEditSummary(); // This will save and cleanup
- selectedRecording.value = newVal; // Switch back to new recording
- }
-
- // Preserve chat maximized state when switching recordings
- // Don't reset chat visibility or maximized state if chat is currently maximized
- if (!isChatMaximized.value) {
- showChat.value = false;
- selectedTab.value = 'summary';
- }
- // Clear messages for the new recording
- chatMessages.value = [];
-
- editingParticipants.value = false;
- 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();
- }
- }
- });
- });
- }
- }
- });
-
- watch(currentView, (newView) => {
- if (newView === 'recording') {
- // Initialize recording markdown editor when switching to recording view
- nextTick(() => {
- initializeRecordingMarkdownEditor();
- // Fix audio duration for recorded files
- if (audioBlobURL.value) {
- const recordingAudio = document.querySelector('audio[src*="blob:"]');
- if (recordingAudio) {
- const fixDuration = () => {
- if (!isFinite(recordingAudio.duration) || recordingAudio.duration === 0) {
- const originalTime = recordingAudio.currentTime;
- recordingAudio.currentTime = 1e101;
- recordingAudio.addEventListener('timeupdate', function resetTime() {
- recordingAudio.currentTime = originalTime;
- recordingAudio.removeEventListener('timeupdate', resetTime);
- }, { once: true });
- }
- };
- recordingAudio.addEventListener('loadedmetadata', fixDuration, { once: true });
- recordingAudio.addEventListener('canplay', fixDuration, { once: true });
- if (recordingAudio.readyState >= 1) {
- setTimeout(fixDuration, 100);
- }
- }
- }
- });
- } else {
- // Clean up recording markdown editor when leaving recording view
- if (recordingMarkdownEditorInstance.value) {
- recordingMarkdownEditorInstance.value.toTextArea();
- recordingMarkdownEditorInstance.value = null;
- }
- }
- });
-
- watch(audioBlobURL, (newURL) => {
- if (newURL) {
- nextTick(() => {
- const recordingAudio = document.querySelector('audio[src*="blob:"]');
- if (recordingAudio) {
- const fixDuration = () => {
- if (!isFinite(recordingAudio.duration) || recordingAudio.duration === 0) {
- const originalTime = recordingAudio.currentTime;
- recordingAudio.currentTime = 1e101;
- recordingAudio.addEventListener('timeupdate', function resetTime() {
- if (Number.isFinite(originalTime)) {
- recordingAudio.currentTime = originalTime;
- }
- recordingAudio.removeEventListener('timeupdate', resetTime);
- }, { once: true });
- }
- };
-
- // Multiple events to ensure we catch the duration
- recordingAudio.addEventListener('loadedmetadata', fixDuration, { once: true });
- recordingAudio.addEventListener('loadeddata', fixDuration, { once: true });
- recordingAudio.addEventListener('canplay', fixDuration, { once: true });
-
- // Also try after a delay
- if (recordingAudio.readyState >= 1) {
- setTimeout(fixDuration, 100);
- }
- }
- });
- }
- });
-
- watch(playerVolume, (newVolume) => {
- const audioElements = document.querySelectorAll('audio');
- audioElements.forEach(audio => {
- if (audio.volume !== newVolume) {
- audio.volume = newVolume;
- }
- });
- });
-
- // Watch for search query changes
- watch(searchQuery, (newQuery) => {
- debouncedSearch(newQuery);
- });
-
- // Auto-apply filters when they change (except text query which is debounced)
- watch(filterTags, () => {
- applyAdvancedFilters();
- }, { deep: true });
-
- watch(filterDatePreset, () => {
- applyAdvancedFilters();
- });
-
- watch(filterDateRange, () => {
- applyAdvancedFilters();
- }, { deep: true });
-
- // Debounce text query changes
- watch(filterTextQuery, (newValue) => {
- clearTimeout(searchDebounceTimer.value);
- searchDebounceTimer.value = setTimeout(() => {
- applyAdvancedFilters();
- }, 300);
- });
-
- // --- Configuration Loading ---
- const loadConfiguration = async () => {
- try {
- const response = await fetch('/api/config');
- if (response.ok) {
- const config = await response.json();
- maxFileSizeMB.value = config.max_file_size_mb || 250;
- chunkingEnabled.value = config.chunking_enabled !== undefined ? config.chunking_enabled : true;
- chunkingMode.value = config.chunking_mode || 'size';
- chunkingLimit.value = config.chunking_limit || 20;
- chunkingLimitDisplay.value = config.chunking_limit_display || '20MB';
- recordingDisclaimer.value = config.recording_disclaimer || '';
- console.log(`Loaded configuration: max size ${maxFileSizeMB.value}MB, chunking ${chunkingEnabled.value ? 'enabled' : 'disabled'} (${chunkingLimitDisplay.value})`);
- } else {
- console.warn('Failed to load configuration, using default values');
- }
- } catch (error) {
- console.error('Error loading configuration:', error);
- // Keep default values on error
- }
- };
-
- const initializeSummaryMarkdownEditor = () => {
- if (!summaryMarkdownEditor.value) return;
-
- try {
- summaryMarkdownEditorInstance.value = new EasyMDE({
- element: summaryMarkdownEditor.value,
- spellChecker: false,
- autofocus: true,
- placeholder: "Enter summary in Markdown format...",
- initialValue: selectedRecording.value?.summary || '',
- status: false,
- toolbar: [
- "bold", "italic", "heading", "|",
- "quote", "unordered-list", "ordered-list", "|",
- "link", "image", "|",
- "preview", "side-by-side", "fullscreen", "|",
- "guide"
- ],
- previewClass: ["editor-preview", "notes-preview"],
- theme: isDarkMode.value ? "dark" : "light"
- });
-
- // Add auto-save functionality
- summaryMarkdownEditorInstance.value.codemirror.on('change', () => {
- if (autoSaveTimer.value) {
- clearTimeout(autoSaveTimer.value);
- }
- autoSaveTimer.value = setTimeout(() => {
- autoSaveSummary();
- }, autoSaveDelay);
- });
- } catch (error) {
- console.error('Failed to initialize summary markdown editor:', error);
- editingSummary.value = true;
- }
- };
-
- const pollInboxRecordings = async () => {
- try {
- const response = await fetch('/api/inbox_recordings');
- if (!response.ok) {
- // Silently fail, as this is a background task
- return;
- }
- const inboxRecordings = await response.json();
-
- if (inboxRecordings && inboxRecordings.length > 0) {
- inboxRecordings.forEach(recording => {
- // Add to main recordings list if it's not there already
- const existingRecording = recordings.value.find(r => r.id === recording.id);
- if (!existingRecording) {
- recordings.value.unshift(recording);
- totalRecordings.value++; // Update total count
- }
-
- // Check if this recording is already in the upload queue or currently being processed
- const existingItem = uploadQueue.value.find(item => item.recordingId === recording.id);
- const isCurrentlyProcessing = currentlyProcessingFile.value && currentlyProcessingFile.value.recordingId === recording.id;
-
- // Don't add if it's already in queue or being processed
- if (existingItem || isCurrentlyProcessing) {
- // Update status if the existing item status has changed
- if (existingItem && existingItem.status !== recording.status) {
- console.log(`Updating status for existing recording ${recording.original_filename}: ${existingItem.status} -> ${recording.status}`);
- }
- return;
- }
-
- // Only add recordings that are still processing (not completed)
- if (recording.status === 'COMPLETED') {
- console.log(`Skipping completed inbox recording: ${recording.original_filename}`);
- return;
- }
-
- console.log(`Found new inbox recording: ${recording.original_filename} (status: ${recording.status})`);
-
- // Don't add recordings that are already being handled by main processing
- if (recording.status === 'SUMMARIZING' && isProcessingActive.value) {
- console.log(`Skipping ${recording.original_filename} - already in summarization phase of main processing`);
- return;
- }
-
- // Add it to the queue to be displayed in the progress modal
- const inboxItem = {
- file: {
- name: recording.original_filename || `Recording ${recording.id}`,
- size: recording.file_size || 0
- },
- status: 'pending', // It's already being processed on backend
- recordingId: recording.id,
- clientId: `inbox-${recording.id}-${Date.now()}`,
- error: null,
- isReprocessing: true, // Use reprocessing logic to poll for status
- reprocessType: 'transcription'
- };
- uploadQueue.value.unshift(inboxItem);
-
- // If nothing is currently being processed, make this the active item for the main progress bar
- if (!isProcessingActive.value && !currentlyProcessingFile.value) {
- currentlyProcessingFile.value = inboxItem;
- }
-
- // Show progress modal if it's hidden
- progressPopupMinimized.value = false;
- progressPopupClosed.value = false;
-
- // Start polling its status
- startReprocessingPoll(recording.id);
- });
- }
- } catch (error) {
- console.error('Error polling for inbox recordings:', error);
- }
- };
-
- // --- Audio Format Detection ---
- const detectSupportedAudioFormats = () => {
- const formats = [
- 'audio/webm;codecs=opus',
- 'audio/webm;codecs=vp9',
- 'audio/webm',
- 'audio/mp4;codecs=mp4a.40.2',
- 'audio/mp4',
- 'audio/ogg;codecs=opus',
- 'audio/wav'
- ];
-
- const supportedFormats = formats.filter(format => MediaRecorder.isTypeSupported(format));
- console.log('Supported audio recording formats:', supportedFormats);
-
- if (supportedFormats.length === 0) {
- console.warn('No optimized audio formats supported, will use browser default');
- }
-
- return supportedFormats;
- };
-
- // --- System Audio Detection ---
- const detectSystemAudioCapabilities = async () => {
- systemAudioSupported.value = false;
- canRecordSystemAudio.value = false;
- systemAudioError.value = '';
-
- // Check if getDisplayMedia is available
- if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {
- systemAudioError.value = 'getDisplayMedia API not supported';
- return;
- }
-
- try {
- // Test if we can request system audio (this will prompt user)
- // We'll do this only when user actually tries to record
- systemAudioSupported.value = true;
- canRecordSystemAudio.value = true;
- systemAudioError.value = '';
- } catch (error) {
- systemAudioError.value = error.message;
- console.warn('System audio detection failed:', error);
- }
- };
-
- const detectBrowser = () => {
- const userAgent = navigator.userAgent;
- if (userAgent.includes("Firefox")) {
- browser.value = "firefox";
- } else if (userAgent.includes("Chrome")) {
- browser.value = "chrome";
- } else if (userAgent.includes("Safari")) {
- browser.value = "safari";
- } else if (userAgent.includes("MSIE") || userAgent.includes("Trident/")) {
- browser.value = "ie";
- } else {
- browser.value = "unknown";
- }
- };
-
- // --- Lifecycle ---
- onMounted(async () => {
- const loader = document.getElementById('loader');
- const app = document.getElementById('app');
- if (loader) {
- loader.style.opacity = '0';
- setTimeout(() => {
- loader.style.display = 'none';
- }, 500);
- }
- if (app) {
- app.style.opacity = '1';
- }
- const appDiv = document.getElementById('app');
- if (appDiv) {
- const asrFlag = appDiv.dataset.useAsrEndpoint;
- useAsrEndpoint.value = asrFlag === 'True' || asrFlag === 'true';
- currentUserName.value = appDiv.dataset.currentUserName || '';
- }
-
- // Load configuration first
- await loadConfiguration();
-
- // Detect system audio capabilities
- await detectSystemAudioCapabilities();
-
- detectBrowser();
-
- // Check if language was changed in account settings
- if (localStorage.getItem('ui_language_changed') === 'true') {
- localStorage.removeItem('ui_language_changed');
- // Force reload to apply new language
- window.location.reload();
- return;
- }
-
- // i18n is already initialized before Vue app creation
- if (window.i18n) {
- currentLanguage.value = window.i18n.getLocale();
- availableLanguages.value = window.i18n.getAvailableLocales();
- const lang = availableLanguages.value.find(l => l.code === currentLanguage.value);
- currentLanguageName.value = lang ? lang.nativeName : 'English';
-
- // Listen for locale changes
- window.addEventListener('localeChanged', (event) => {
- currentLanguage.value = event.detail.locale;
- const lang = availableLanguages.value.find(l => l.code === currentLanguage.value);
- currentLanguageName.value = lang ? lang.nativeName : 'English';
- });
- }
-
- loadRecordings();
- loadTags();
- initializeDarkMode();
- initializeColorScheme();
-
- const savedVolume = localStorage.getItem('playerVolume');
- if (savedVolume !== null) {
- playerVolume.value = parseFloat(savedVolume);
- }
-
- const savedTranscriptionViewMode = localStorage.getItem('transcriptionViewMode');
- if (savedTranscriptionViewMode) {
- transcriptionViewMode.value = savedTranscriptionViewMode;
- }
-
- // Load saved column widths
- const savedLeftWidth = localStorage.getItem('transcriptColumnWidth');
- const savedRightWidth = localStorage.getItem('summaryColumnWidth');
- if (savedLeftWidth && savedRightWidth) {
- leftColumnWidth.value = parseFloat(savedLeftWidth);
- rightColumnWidth.value = parseFloat(savedRightWidth);
- }
-
- const updateMobileStatus = () => {
- windowWidth.value = window.innerWidth;
- };
-
- window.addEventListener('resize', updateMobileStatus);
- updateMobileStatus();
-
- // Add Page Visibility API listener to handle screen lock/background
- document.addEventListener('visibilitychange', handleVisibilityChange);
- console.log('[Visibility] Page visibility change listener registered');
-
- // Add beforeunload event listener to warn about unsaved recordings
- window.addEventListener('beforeunload', (e) => {
- if (hasUnsavedRecording()) {
- e.preventDefault();
- e.returnValue = 'You have an unsaved recording. Are you sure you want to leave?';
- return e.returnValue;
- }
- });
-
- // Intercept navigation clicks when there's an unsaved recording
- document.addEventListener('click', (e) => {
- // Check if click is on an anchor tag or inside one
- const link = e.target.closest('a[href]');
- if (link && hasUnsavedRecording()) {
- // Check if it's an external navigation (not just a hash change within the same page)
- const href = link.getAttribute('href');
- if (href && href !== '#' && !href.startsWith('javascript:')) {
- if (!confirmNavigationWithUnsavedRecording()) {
- e.preventDefault();
- return false;
- } else {
- // User confirmed, clean up the recording
- if (isRecording.value) {
- stopRecording();
- }
- if (audioBlobURL.value) {
- discardRecording();
- }
- }
- }
- }
- });
-
- // Start polling for inbox recordings
- setInterval(pollInboxRecordings, 10000); // Poll every 10 seconds
-
- const handleEsc = (e) => {
- if (e.key === 'Escape') {
- if (showColorSchemeModal.value) {
- closeColorSchemeModal();
- }
- if (showEditModal.value) {
- cancelEdit();
- }
- if (showDeleteModal.value) {
- cancelDelete();
- }
- if (showSortOptions.value) {
- showSortOptions.value = false;
- }
- }
- };
- document.addEventListener('keydown', handleEsc);
-
- // Click away handler for dropdowns
- const handleClickAway = (e) => {
- // Close user menu if clicking outside
- if (isUserMenuOpen.value) {
- // Check if we clicked within the user menu area (button or dropdown)
- const userMenuButton = e.target.closest('button[class*="flex items-center gap"]');
- const userMenuDropdown = e.target.closest('div[class*="absolute right-0"]');
-
- // Check if the click was on the user menu button specifically
- const isUserMenuButtonClick = userMenuButton && userMenuButton.querySelector('i.fa-user-circle');
-
- // If we didn't click on the user menu button or dropdown, close it
- if (!isUserMenuButtonClick && !userMenuDropdown) {
- isUserMenuOpen.value = false;
- }
- }
-
- // Close speaker suggestions if clicking outside in the modal
- if (showSpeakerModal.value) {
- // If not clicking on an input field or suggestion dropdown
- const clickedOnInput = e.target.closest('input[type="text"]');
- const clickedOnSuggestion = e.target.closest('[class*="absolute z-10"]');
-
- if (!clickedOnInput && !clickedOnSuggestion) {
- // Close all suggestion dropdowns
- Object.keys(speakerSuggestions.value).forEach(speakerId => {
- speakerSuggestions.value[speakerId] = [];
- });
- }
- }
- };
- document.addEventListener('click', handleClickAway);
- });
-
- return {
- // Core State
- currentView, dragover, recordings, selectedRecording, selectedTab, searchQuery,
- isLoadingRecordings, globalError, maxFileSizeMB, chunkingEnabled, chunkingMode, chunkingLimit, chunkingLimitDisplay, sortBy,
- showAdvancedFilters, filterTags, filterDateRange, filterDatePreset, filterTextQuery,
-
- // Pagination State
- currentPage, perPage, totalRecordings, totalPages, hasNextPage, hasPrevPage, isLoadingMore,
-
- // UI State
- browser,
- isSidebarCollapsed, searchTipsExpanded, isUserMenuOpen, isDarkMode, currentColorScheme,
- showColorSchemeModal, windowWidth, isMobileScreen, isMobileDevice,
- mobileTab, isMetadataExpanded,
-
- // i18n State
- currentLanguage, currentLanguageName, availableLanguages, showLanguageMenu,
-
- // Upload State
- uploadQueue, currentlyProcessingFile, processingProgress, processingMessage,
- isProcessingActive, progressPopupMinimized, progressPopupClosed,
- totalInQueue, completedInQueue, finishedFilesInQueue, clearCompletedUploads,
-
- // Audio Recording
- isRecording, canRecordAudio, canRecordSystemAudio, systemAudioSupported, systemAudioError, audioBlobURL, recordingTime, recordingNotes, visualizer, micVisualizer, systemVisualizer, recordingMode,
- recordingDisclaimer, showRecordingDisclaimerModal, acceptRecordingDisclaimer, cancelRecordingDisclaimer,
- showAdvancedOptions, uploadLanguage, uploadMinSpeakers, uploadMaxSpeakers,
- asrLanguage, asrMinSpeakers, asrMaxSpeakers,
- availableTags, selectedTagIds, selectedTags, uploadTagSearchFilter, filteredAvailableTagsForUpload, onTagSelected, addTagToSelection, removeTagFromSelection,
- showSystemAudioHelp,
-
- // Modal State
- showEditModal, showDeleteModal, showResetModal, editingRecording, recordingToDelete,
- showEditTagsModal, selectedNewTagId, tagSearchFilter, filteredAvailableTagsForModal, editRecordingTags, closeEditTagsModal, addTagToRecording, removeTagFromRecording,
- getRecordingTags, getAvailableTagsForRecording, filterByTag, clearTagFilter,
- applyAdvancedFilters, clearAllFilters,
- showTextEditorModal, showAsrEditorModal, editingTranscriptionContent, editingSegments, availableSpeakers,
-
- // Inline Editing
- editingParticipants, editingMeetingDate, editingSummary, editingNotes,
-
- // Markdown Editor
- notesMarkdownEditor, markdownEditorInstance, summaryMarkdownEditor, summaryMarkdownEditorInstance, recordingNotesEditor,
-
- // Transcription
- transcriptionViewMode, legendExpanded, highlightedSpeaker, processedTranscription,
-
- // Chat
- showChat, isChatMaximized, toggleChatMaximize, chatMessages, chatInput, isChatLoading, chatMessagesRef,
-
- // Audio Player
- playerVolume,
-
- // Column Resizing
- leftColumnWidth, rightColumnWidth, isResizing,
-
- // App Configuration
- useAsrEndpoint, currentUserName,
-
- // Computed
- filteredRecordings, groupedRecordings, activeRecordingMetadata, datePresetOptions, languageOptions,
-
- // Color Schemes
- colorSchemes,
-
- // Methods
- setGlobalError, formatFileSize, formatDisplayDate, formatStatus, getStatusClass, formatTime,
- t, tc, changeLanguage,
- toggleDarkMode, applyColorScheme, initializeColorScheme, openColorSchemeModal,
- closeColorSchemeModal, selectColorScheme, resetColorScheme,
- toggleSidebar, switchToUploadView, selectRecording,
- handleDragOver, handleDragLeave, handleDrop, handleFileSelect, addFilesToQueue,
- startRecording, stopRecording, uploadRecordedAudio, discardRecording,
- loadRecordings, loadMoreRecordings, performSearch, debouncedSearch, saveMetadata, editRecording, cancelEdit, saveEdit,
- confirmDelete, cancelDelete, deleteRecording,
- toggleEditParticipants, toggleEditMeetingDate, toggleEditSummary, cancelEditSummary, saveEditSummary, toggleEditNotes,
- cancelEditNotes, saveEditNotes, initializeMarkdownEditor, saveInlineEdit, clickToEditNotes, clickToEditSummary,
- autoSaveNotes, autoSaveSummary,
- sendChatMessage, isChatScrolledToBottom, scrollChatToBottom, startColumnResize, handleChatKeydown, seekAudio, seekAudioFromEvent, onPlayerVolumeChange,
- showToast, copyMessage, copyTranscription, copySummary, copyNotes,
- downloadSummary, downloadTranscript, downloadNotes, downloadChat, clearChat, downloadEventICS, downloadICS, formatEventDateTime,
- toggleInbox, toggleHighlight,
- toggleTranscriptionViewMode,
- reprocessTranscription,
- reprocessSummary,
- generateSummary,
- resetRecordingStatus,
- confirmReset,
- cancelReset,
- executeReset,
- openTranscriptionEditor,
- openTextEditorModal,
- closeTextEditorModal,
- saveTranscription,
- openAsrEditorModal,
- closeAsrEditorModal,
- saveAsrTranscription,
- adjustTime,
- filterSpeakers,
- openSpeakerSuggestions,
- closeSpeakerSuggestions,
- selectSpeaker,
- addSegment,
- removeSegment,
- showReprocessModal,
- reprocessType,
- reprocessRecording,
- cancelReprocess,
- executeReprocess,
- asrReprocessOptions,
- summaryReprocessPromptSource,
- summaryReprocessSelectedTagId,
- summaryReprocessCustomPrompt,
- tagsWithCustomPrompts,
- getTagPromptPreview,
- showSpeakerModal,
- showShareModal,
- recordingToShare,
- shareOptions,
- generatedShareLink,
- existingShareDetected,
- userShares,
- isLoadingShares,
- showSharesListModal,
- shareToDelete,
- showShareDeleteModal,
- confirmDeleteShare,
- cancelDeleteShare,
- speakerMap,
- speakerDisplayMap,
- modalSpeakers,
- regenerateSummaryAfterSpeakerUpdate,
- identifiedSpeakers,
- identifiedSpeakersInOrder,
- hasSpeakerNames,
- openSpeakerModal,
- closeSpeakerModal,
- saveSpeakerNames,
- highlightedTranscript,
- highlightedSpeaker,
- highlightSpeakerInTranscript,
- focusSpeaker,
- blurSpeaker,
- clearSpeakerHighlight,
- currentSpeakerGroupIndex,
- speakerGroups,
- navigateToNextSpeakerGroup,
- navigateToPrevSpeakerGroup,
- speakerSuggestions,
- loadingSuggestions,
- activeSpeakerInput,
- searchSpeakers,
- selectSpeakerSuggestion,
- closeSpeakerSuggestionsOnClick,
- autoIdentifySpeakers,
- isAutoIdentifying,
-
- // Transcript Editing
- editingSegmentIndex,
- editingSpeakerIndex,
- showEditTextModal,
- editedText,
- showAddSpeakerModal,
- newSpeakerName,
- newSpeakerIsMe,
- editedTranscriptData,
- openAddSpeakerModal,
- closeAddSpeakerModal,
- addNewSpeaker,
- openSpeakerChangeDropdown,
- changeSpeaker,
- openEditTextModal,
- closeEditTextModal,
- saveEditedText,
- saveTranscriptEdits,
-
- formatDuration,
- openShareModal,
- closeShareModal,
- createShare,
- openSharesList,
- closeSharesList,
- updateShare,
- deleteShare,
- copyShareLink,
-
- // Recording Size Monitoring
- estimatedFileSize,
- fileSizeWarningShown,
- recordingQuality,
- actualBitrate,
- maxRecordingMB,
- sizeCheckInterval,
- updateFileSizeEstimate,
- startSizeMonitoring,
- stopSizeMonitoring
- }
- },
- delimiters: ['${', '}']
- });
-
- // Add t function as a global property BEFORE mounting so it's available in templates immediately
- app.config.globalProperties.t = safeT;
-
- // Also add tc for pluralization
- app.config.globalProperties.tc = (key, count, params = {}) => {
- if (!window.i18n || !window.i18n.tc) {
- return key;
- }
- return window.i18n.tc(key, count, params);
- };
-
- // Provide t and tc to the app
- app.provide('t', safeT);
- app.provide('tc', (key, count, params = {}) => {
- if (!window.i18n || !window.i18n.tc) {
- return key;
- }
- return window.i18n.tc(key, count, params);
- });
-
- // Mount the app
- app.mount('#app');
-
- // Hide loading overlay after Vue is mounted and ready
- Vue.nextTick(() => {
- const overlay = document.querySelector('.app-loading-overlay');
- if (overlay) {
- // Small delay to ensure everything is rendered
- setTimeout(() => {
- overlay.classList.add('fade-out');
- setTimeout(() => {
- overlay.remove();
- document.body.classList.remove('app-loading');
- }, 300);
- }, 100);
- } else {
- document.body.classList.remove('app-loading');
- }
- });
-});
diff --git a/static/js/app.modular.js b/static/js/app.modular.js
new file mode 100644
index 00000000..93580201
--- /dev/null
+++ b/static/js/app.modular.js
@@ -0,0 +1,1372 @@
+const { createApp, ref, reactive, computed, onMounted, watch, nextTick } = Vue;
+
+// Import composables
+import { useRecordings } from './modules/composables/recordings.js';
+import { useUpload } from './modules/composables/upload.js';
+import { useAudio } from './modules/composables/audio.js';
+import { useUI } from './modules/composables/ui.js';
+import { useModals } from './modules/composables/modals.js';
+import { useSharing } from './modules/composables/sharing.js';
+import { useReprocess } from './modules/composables/reprocess.js';
+import { useTranscription } from './modules/composables/transcription.js';
+import { useSpeakers } from './modules/composables/speakers.js';
+import { useChat } from './modules/composables/chat.js';
+import { useTags } from './modules/composables/tags.js';
+
+// Import utilities
+import { showToast } from './modules/utils/toast.js';
+import { getContrastTextColor } from './modules/utils/colors.js';
+
+// Wait for the DOM to be fully loaded before mounting the Vue app
+document.addEventListener('DOMContentLoaded', async () => {
+ // Initialize i18n before creating Vue app (if not already initialized)
+ try {
+ if (window.i18n && !window.i18n.currentLocale) {
+ const appElement = document.getElementById('app');
+ const userLang = appElement?.dataset.userLanguage || localStorage.getItem('preferredLanguage') || 'en';
+
+ // Add timeout to prevent indefinite waiting
+ await Promise.race([
+ window.i18n.init(userLang),
+ new Promise((resolve) => setTimeout(resolve, 3000))
+ ]);
+
+ console.log('i18n initialized with language:', userLang);
+ } else if (window.i18n && window.i18n.currentLocale) {
+ console.log('i18n already initialized with language:', window.i18n.currentLocale);
+ }
+ } catch (error) {
+ console.error('Error initializing i18n:', error);
+ // Continue anyway with fallback translations
+ }
+
+ // CSRF Token Integration with Vue.js
+ const csrfToken = ref(document.querySelector('meta[name="csrf-token"]')?.getAttribute('content'));
+
+ // Register Service Worker (non-blocking)
+ if ('serviceWorker' in navigator) {
+ // Delay registration to not block page load
+ setTimeout(() => {
+ navigator.serviceWorker.register('/static/sw.js')
+ .then(registration => {
+ console.log('ServiceWorker registration successful with scope:', registration.scope);
+ })
+ .catch(error => {
+ console.warn('ServiceWorker registration failed (non-critical):', error);
+ });
+ }, 1000);
+ }
+
+ // Create a safe t function that's always available
+ const safeT = (key, params = {}) => {
+ if (!window.i18n || !window.i18n.t) {
+ return key;
+ }
+ return window.i18n.t(key, params);
+ };
+
+ const app = createApp({
+ setup() {
+ // =========================================================================
+ // STATE DECLARATIONS - All reactive state stays here for proper reactivity
+ // =========================================================================
+
+ // --- Core State ---
+ const currentView = ref('upload');
+ const dragover = ref(false);
+ const recordings = ref([]);
+ const selectedRecording = ref(null);
+ const selectedTab = ref('summary');
+ const searchQuery = ref('');
+ const isLoadingRecordings = ref(true);
+ const globalError = ref(null);
+
+ // Advanced filter state
+ const showAdvancedFilters = ref(false);
+ const filterTags = ref([]);
+ const filterDateRange = ref({ start: '', end: '' });
+ const filterDatePreset = ref('');
+ const filterTextQuery = ref('');
+ const showArchivedRecordings = ref(false);
+ const showSharedWithMe = ref(false);
+
+ // --- Pagination State ---
+ const currentPage = ref(1);
+ const perPage = ref(25);
+ const totalRecordings = ref(0);
+ const totalPages = ref(0);
+ const hasNextPage = ref(false);
+ const hasPrevPage = ref(false);
+ const isLoadingMore = ref(false);
+ const searchDebounceTimer = ref(null);
+
+ // --- Enhanced Search & Organization State ---
+ const sortBy = ref('created_at');
+ const selectedTagFilter = ref(null);
+
+ // --- UI State ---
+ const browser = ref('unknown');
+ const isSidebarCollapsed = ref(false);
+ const searchTipsExpanded = ref(false);
+ const isUserMenuOpen = ref(false);
+ const isDarkMode = ref(false);
+ const currentColorScheme = ref('blue');
+ const showColorSchemeModal = ref(false);
+ const windowWidth = ref(window.innerWidth);
+ const mobileTab = ref('transcript');
+ const isMetadataExpanded = ref(false);
+ const showSortOptions = ref(false);
+
+ // --- i18n State ---
+ const currentLanguage = ref('en');
+ const currentLanguageName = ref('English');
+ const availableLanguages = ref([]);
+ const showLanguageMenu = ref(false);
+
+ // --- Upload State ---
+ const uploadQueue = ref([]);
+ const currentlyProcessingFile = ref(null);
+ const processingProgress = ref(0);
+ const processingMessage = ref('');
+ const isProcessingActive = ref(false);
+ const pollInterval = ref(null);
+ const progressPopupMinimized = ref(false);
+ const progressPopupClosed = ref(false);
+ const maxFileSizeMB = ref(250);
+ const chunkingEnabled = ref(true);
+ const chunkingMode = ref('size');
+ const chunkingLimit = ref(20);
+ const chunkingLimitDisplay = ref('20MB');
+ const recordingDisclaimer = ref('');
+ const showRecordingDisclaimerModal = ref(false);
+ const pendingRecordingMode = ref(null);
+
+ // --- Audio Recording State ---
+ const isRecording = ref(false);
+ const mediaRecorder = ref(null);
+ const audioChunks = ref([]);
+ const audioBlobURL = ref(null);
+ const recordingTime = ref(0);
+ const recordingInterval = ref(null);
+ const canRecordAudio = ref(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);
+ const canRecordSystemAudio = ref(false);
+ const systemAudioSupported = ref(false);
+ const systemAudioError = ref('');
+ const recordingNotes = ref('');
+ const showSystemAudioHelp = ref(false);
+ const showSystemAudioHelpModal = ref(false);
+ const asrLanguage = ref('');
+ const asrMinSpeakers = ref('');
+ const asrMaxSpeakers = ref('');
+ const audioContext = ref(null);
+ const analyser = ref(null);
+ const micAnalyser = ref(null);
+ const systemAnalyser = ref(null);
+ const visualizer = ref(null);
+ const micVisualizer = ref(null);
+ const systemVisualizer = ref(null);
+ const animationFrameId = ref(null);
+ const recordingMode = ref('microphone');
+ const activeStreams = ref([]);
+
+ // --- Wake Lock and Background Recording ---
+ const wakeLock = ref(null);
+ const recordingNotification = ref(null);
+ const isPageVisible = ref(true);
+
+ // --- Recording Size Monitoring ---
+ const estimatedFileSize = ref(0);
+ const fileSizeWarningShown = ref(false);
+ const recordingQuality = ref('optimized');
+ const actualBitrate = ref(0);
+ const maxRecordingMB = ref(200);
+ const sizeCheckInterval = ref(null);
+
+ // Advanced Options for ASR
+ const showAdvancedOptions = ref(false);
+ const uploadLanguage = ref('');
+ const uploadMinSpeakers = ref('');
+ const uploadMaxSpeakers = ref('');
+
+ // Tag Selection
+ const availableTags = ref([]);
+ const selectedTagIds = ref([]);
+ const uploadTagSearchFilter = ref('');
+
+ // --- Modal State ---
+ const showEditModal = ref(false);
+ const showDeleteModal = ref(false);
+ const showEditTagsModal = ref(false);
+ const selectedNewTagId = ref('');
+ const tagSearchFilter = ref('');
+ const showReprocessModal = ref(false);
+ const showResetModal = ref(false);
+ const showSpeakerModal = ref(false);
+ const showShareModal = ref(false);
+ const showSharesListModal = ref(false);
+ const showTextEditorModal = ref(false);
+ const showAsrEditorModal = ref(false);
+ const editingRecording = ref(null);
+ const editingTranscriptionContent = ref('');
+ const editingSegments = ref([]);
+ const availableSpeakers = ref([]);
+ const showEditSpeakersModal = ref(false);
+ const editingSpeakersList = ref([]);
+ const databaseSpeakers = ref([]);
+ const editingSpeakerSuggestions = ref({});
+ const showEditParticipantsModal = ref(false);
+ const editingParticipantsList = ref([]);
+ const editingParticipantSuggestions = ref({});
+ const allParticipants = ref([]);
+ const recordingToShare = ref(null);
+ const shareOptions = reactive({
+ share_summary: true,
+ share_notes: true,
+ });
+ const generatedShareLink = ref('');
+ const existingShareDetected = ref(false);
+ const recordingPublicShares = ref([]); // All public shares for current recording
+ const isLoadingPublicShares = ref(false);
+ const userShares = ref([]);
+ const isLoadingShares = ref(false);
+ const copiedShareId = ref(null);
+ const shareToDelete = ref(null);
+ const showShareDeleteModal = ref(false);
+ const recordingToDelete = ref(null);
+ const recordingToReset = ref(null);
+ const reprocessType = ref(null);
+ const reprocessRecording = ref(null);
+ const isAutoIdentifying = ref(false);
+ const asrReprocessOptions = reactive({
+ language: '',
+ min_speakers: null,
+ max_speakers: null
+ });
+ const summaryReprocessPromptSource = ref('default');
+ const summaryReprocessSelectedTagId = ref('');
+ const summaryReprocessCustomPrompt = ref('');
+ const speakerMap = ref({});
+ const modalSpeakers = ref([]);
+ const speakerDisplayMap = ref({});
+ const regenerateSummaryAfterSpeakerUpdate = ref(true);
+ const speakerSuggestions = ref({});
+ const loadingSuggestions = ref({});
+ const activeSpeakerInput = ref(null);
+ const voiceSuggestions = ref({});
+ const loadingVoiceSuggestions = ref(false);
+
+ // --- Transcript Editing State ---
+ const editingSegmentIndex = ref(null);
+ const editingSpeakerIndex = ref(null);
+ const showEditTextModal = ref(false);
+ const editedText = ref('');
+ const showAddSpeakerModal = ref(false);
+ const newSpeakerName = ref('');
+ const newSpeakerIsMe = ref(false);
+ const newSpeakerSuggestions = ref([]);
+ const loadingNewSpeakerSuggestions = ref(false);
+ const showNewSpeakerSuggestions = ref(false);
+ const editedTranscriptData = ref(null);
+
+ // --- Inline Editing State ---
+ const editingTitle = ref(false);
+ const originalTitle = ref('');
+ const editingParticipants = ref(false);
+ const editingMeetingDate = ref(false);
+ const editingSummary = ref(false);
+ const editingNotes = ref(false);
+ const tempNotesContent = ref('');
+ const tempSummaryContent = ref('');
+ const autoSaveTimer = ref(null);
+ const autoSaveDelay = 2000;
+
+ // --- Markdown Editor State ---
+ const notesMarkdownEditor = ref(null);
+ const markdownEditorInstance = ref(null);
+ const summaryMarkdownEditor = ref(null);
+ const summaryMarkdownEditorInstance = ref(null);
+ const recordingNotesEditor = ref(null);
+ const recordingMarkdownEditorInstance = ref(null);
+
+ // --- Transcription State ---
+ const transcriptionViewMode = ref('simple');
+ const legendExpanded = ref(false);
+ const highlightedSpeaker = ref(null);
+ const showDownloadMenu = ref(false);
+ const currentPlayingSegmentIndex = ref(null);
+ const followPlayerMode = ref(false);
+
+ // --- Chat State ---
+ const showChat = ref(false);
+ const isChatMaximized = ref(false);
+ const chatMessages = ref([]);
+ const chatInput = ref('');
+ const isChatLoading = ref(false);
+ const chatMessagesRef = ref(null);
+
+ // --- Audio Player State ---
+ const playerVolume = ref(1.0);
+ const asrEditorAudio = ref(null);
+
+ // --- Column Resizing State ---
+ const leftColumnWidth = ref(60);
+ const rightColumnWidth = ref(40);
+ const isResizing = ref(false);
+
+ // --- Dropdown Positioning ---
+ const dropdownPositions = ref({});
+
+ // --- App Configuration ---
+ const useAsrEndpoint = ref(false);
+ const currentUserName = ref('');
+ const canDeleteRecordings = ref(true);
+ const enableInternalSharing = ref(false);
+ const enableArchiveToggle = ref(false);
+ const showUsernamesInUI = ref(false);
+
+ // --- Internal Sharing State ---
+ const showUnifiedShareModal = ref(false);
+ const internalShareUserSearch = ref('');
+ const internalShareSearchResults = ref([]);
+ const internalShareRecording = ref(null);
+ const internalSharePermissions = ref({ can_edit: false, can_reshare: false });
+ const internalShareMaxPermissions = ref({ can_edit: true, can_reshare: true }); // Permission ceiling for current user
+ const recordingInternalShares = ref([]);
+ const isLoadingInternalShares = ref(false);
+ const isSearchingUsers = ref(false);
+ const allUsers = ref([]);
+ const isLoadingAllUsers = ref(false);
+
+ // --- Reprocessing Polls ---
+ const reprocessingPolls = ref(new Map());
+
+ // --- Speaker Groups State ---
+ const currentSpeakerGroupIndex = ref(0);
+ const speakerGroups = ref([]);
+
+ // --- Computed properties needed by composables ---
+ const isMobileScreen = computed(() => windowWidth.value < 1024);
+ const isMobileDevice = computed(() => {
+ return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ||
+ ('ontouchstart' in window) ||
+ (navigator.maxTouchPoints > 0);
+ });
+
+ const colorSchemes = {
+ light: [
+ { id: 'blue', name: 'Ocean Blue', description: 'Classic blue theme with professional appeal', class: '' },
+ { id: 'emerald', name: 'Forest Emerald', description: 'Fresh green theme for a natural feel', class: 'theme-light-emerald' },
+ { id: 'purple', name: 'Royal Purple', description: 'Elegant purple theme with sophistication', class: 'theme-light-purple' },
+ { id: 'rose', name: 'Sunset Rose', description: 'Warm pink theme with gentle energy', class: 'theme-light-rose' },
+ { id: 'amber', name: 'Golden Amber', description: 'Warm yellow theme for brightness', class: 'theme-light-amber' },
+ { id: 'teal', name: 'Ocean Teal', description: 'Cool teal theme for tranquility', class: 'theme-light-teal' }
+ ],
+ dark: [
+ { id: 'blue', name: 'Midnight Blue', description: 'Deep blue theme for focused work', class: '' },
+ { id: 'emerald', name: 'Dark Forest', description: 'Rich green theme for comfortable viewing', class: 'theme-dark-emerald' },
+ { id: 'purple', name: 'Deep Purple', description: 'Mysterious purple theme for creativity', class: 'theme-dark-purple' },
+ { id: 'rose', name: 'Dark Rose', description: 'Muted pink theme with subtle warmth', class: 'theme-dark-rose' },
+ { id: 'amber', name: 'Dark Amber', description: 'Warm brown theme for cozy sessions', class: 'theme-dark-amber' },
+ { id: 'teal', name: 'Deep Teal', description: 'Dark teal theme for calm focus', class: 'theme-dark-teal' }
+ ]
+ };
+
+ // =========================================================================
+ // COLLECT ALL STATE INTO SINGLE OBJECT FOR COMPOSABLES
+ // =========================================================================
+ const state = {
+ // Core
+ currentView, dragover, recordings, selectedRecording, selectedTab, searchQuery,
+ isLoadingRecordings, globalError, csrfToken,
+
+ // Filters
+ showAdvancedFilters, filterTags, filterDateRange, filterDatePreset, filterTextQuery,
+ showArchivedRecordings, showSharedWithMe, sortBy, selectedTagFilter,
+
+ // Pagination
+ currentPage, perPage, totalRecordings, totalPages, hasNextPage, hasPrevPage,
+ isLoadingMore, searchDebounceTimer,
+
+ // UI
+ browser, isSidebarCollapsed, searchTipsExpanded, isUserMenuOpen, isDarkMode,
+ currentColorScheme, showColorSchemeModal, windowWidth, mobileTab, isMetadataExpanded,
+ showSortOptions, currentLanguage, currentLanguageName, availableLanguages, showLanguageMenu,
+ colorSchemes, isMobileScreen, isMobileDevice,
+
+ // Upload
+ uploadQueue, currentlyProcessingFile, processingProgress, processingMessage,
+ isProcessingActive, pollInterval, progressPopupMinimized, progressPopupClosed,
+ maxFileSizeMB, chunkingEnabled, chunkingMode, chunkingLimit, chunkingLimitDisplay,
+ recordingDisclaimer, showRecordingDisclaimerModal, pendingRecordingMode,
+ showAdvancedOptions, uploadLanguage, uploadMinSpeakers, uploadMaxSpeakers,
+ availableTags, selectedTagIds, uploadTagSearchFilter,
+
+ // Audio Recording
+ isRecording, mediaRecorder, audioChunks, audioBlobURL, recordingTime, recordingInterval,
+ canRecordAudio, canRecordSystemAudio, systemAudioSupported, systemAudioError,
+ recordingNotes, showSystemAudioHelp, showSystemAudioHelpModal, asrLanguage, asrMinSpeakers, asrMaxSpeakers,
+ audioContext, analyser, micAnalyser, systemAnalyser, visualizer, micVisualizer,
+ systemVisualizer, animationFrameId, recordingMode, activeStreams,
+ wakeLock, recordingNotification, isPageVisible,
+ estimatedFileSize, fileSizeWarningShown, recordingQuality, actualBitrate,
+ maxRecordingMB, sizeCheckInterval,
+
+ // Modals
+ showEditModal, showDeleteModal, showEditTagsModal, selectedNewTagId, tagSearchFilter,
+ showReprocessModal, showResetModal, showSpeakerModal, showShareModal, showSharesListModal,
+ showTextEditorModal, showAsrEditorModal, editingRecording, editingTranscriptionContent,
+ editingSegments, availableSpeakers, showEditSpeakersModal, editingSpeakersList,
+ databaseSpeakers, editingSpeakerSuggestions,
+ showEditParticipantsModal, editingParticipantsList, editingParticipantSuggestions, allParticipants,
+ recordingToShare, shareOptions,
+ generatedShareLink, existingShareDetected, recordingPublicShares, isLoadingPublicShares,
+ userShares, isLoadingShares, copiedShareId,
+ shareToDelete, showShareDeleteModal, recordingToDelete, recordingToReset,
+ reprocessType, reprocessRecording, isAutoIdentifying, asrReprocessOptions,
+ summaryReprocessPromptSource, summaryReprocessSelectedTagId, summaryReprocessCustomPrompt,
+ speakerMap, modalSpeakers, speakerDisplayMap, regenerateSummaryAfterSpeakerUpdate, speakerSuggestions,
+ loadingSuggestions, activeSpeakerInput, voiceSuggestions, loadingVoiceSuggestions,
+
+ // Transcript Editing
+ editingSegmentIndex, editingSpeakerIndex, showEditTextModal, editedText,
+ showAddSpeakerModal, newSpeakerName, newSpeakerIsMe, newSpeakerSuggestions,
+ loadingNewSpeakerSuggestions, showNewSpeakerSuggestions, editedTranscriptData,
+
+ // Inline Editing
+ editingTitle, originalTitle,
+ editingParticipants, editingMeetingDate, editingSummary, editingNotes,
+ tempNotesContent, tempSummaryContent, autoSaveTimer, autoSaveDelay,
+
+ // Markdown
+ notesMarkdownEditor, markdownEditorInstance, summaryMarkdownEditor,
+ summaryMarkdownEditorInstance, recordingNotesEditor, recordingMarkdownEditorInstance,
+
+ // Transcription
+ transcriptionViewMode, legendExpanded, highlightedSpeaker, showDownloadMenu,
+ currentPlayingSegmentIndex, followPlayerMode,
+
+ // Chat
+ showChat, isChatMaximized, chatMessages, chatInput, isChatLoading, chatMessagesRef,
+
+ // Audio Player
+ playerVolume, asrEditorAudio,
+
+ // Column Resizing
+ leftColumnWidth, rightColumnWidth, isResizing,
+
+ // Dropdown Positioning
+ dropdownPositions,
+
+ // App Config
+ useAsrEndpoint, currentUserName, canDeleteRecordings, enableInternalSharing, enableArchiveToggle, showUsernamesInUI,
+
+ // Internal Sharing
+ showUnifiedShareModal, internalShareUserSearch, internalShareSearchResults,
+ internalShareRecording, internalSharePermissions, internalShareMaxPermissions, recordingInternalShares,
+ isLoadingInternalShares, isSearchingUsers, allUsers, isLoadingAllUsers,
+
+ // Reprocessing
+ reprocessingPolls,
+
+ // Speaker Groups
+ currentSpeakerGroupIndex, speakerGroups
+ };
+
+ // =========================================================================
+ // TRANSLATION FUNCTION
+ // =========================================================================
+ const t = safeT;
+ const tc = (key, count, params = {}) => {
+ if (!window.i18n || !window.i18n.tc) {
+ return key;
+ }
+ return window.i18n.tc(key, count, params);
+ };
+
+ // =========================================================================
+ // UTILITY FUNCTIONS
+ // =========================================================================
+ // showToast is now imported from modules/utils/toast.js
+
+ const setGlobalError = (message, duration = 5000) => {
+ // Use toast system for all errors instead of the old global error banner
+ showToast(message, 'fa-exclamation-circle', duration, 'error');
+ };
+
+ // Helper function to calculate global segment index in bubble view
+ const getBubbleGlobalIndex = (rowIndex, bubbleIndex) => {
+ if (!processedTranscription.value.bubbleRows) return 0;
+
+ let globalIndex = 0;
+ for (let i = 0; i < rowIndex; i++) {
+ globalIndex += processedTranscription.value.bubbleRows[i].bubbles.length;
+ }
+ globalIndex += bubbleIndex;
+ return globalIndex;
+ };
+
+ const formatFileSize = (bytes) => {
+ if (!bytes) return '0 B';
+ const k = 1024;
+ const sizes = ['B', 'KB', 'MB', 'GB'];
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
+ };
+
+ const formatDisplayDate = (dateString) => {
+ if (!dateString) return '';
+ try {
+ let date = new Date(dateString);
+ if (isNaN(date.getTime())) {
+ if (/^\d{4}-\d{2}-\d{2}$/.test(dateString)) {
+ const [year, month, day] = dateString.split('-').map(Number);
+ date = new Date(year, month - 1, day);
+ } else {
+ return dateString;
+ }
+ }
+ if (isNaN(date.getTime())) {
+ return dateString;
+ }
+ return date.toLocaleDateString(undefined, {
+ year: 'numeric', month: 'short', day: 'numeric',
+ hour: '2-digit', minute: '2-digit'
+ });
+ } catch (e) {
+ return dateString;
+ }
+ };
+
+ const formatShortDate = (dateString) => {
+ if (!dateString) return '';
+ try {
+ let date = new Date(dateString);
+ if (isNaN(date.getTime())) {
+ if (/^\d{4}-\d{2}-\d{2}$/.test(dateString)) {
+ const [year, month, day] = dateString.split('-').map(Number);
+ date = new Date(year, month - 1, day);
+ }
+ }
+ if (isNaN(date.getTime())) {
+ return dateString;
+ }
+ const now = new Date();
+ const isCurrentYear = date.getFullYear() === now.getFullYear();
+ if (isCurrentYear) {
+ return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
+ }
+ return date.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
+ } catch (e) {
+ return dateString;
+ }
+ };
+
+ const formatStatus = (status) => {
+ const statusMap = {
+ 'PENDING': t('status.pending'),
+ 'PROCESSING': t('status.processing'),
+ 'SUMMARIZING': t('status.summarizing'),
+ 'COMPLETED': t('status.completed'),
+ 'FAILED': t('status.failed')
+ };
+ return statusMap[status] || status;
+ };
+
+ const getStatusClass = (status) => {
+ switch(status) {
+ case 'COMPLETED': return 'status-completed';
+ case 'PROCESSING': return 'status-processing';
+ case 'SUMMARIZING': return 'status-summarizing';
+ case 'PENDING': return 'status-pending';
+ case 'FAILED': return 'status-failed';
+ default: return '';
+ }
+ };
+
+ const formatTime = (seconds) => {
+ const mins = Math.floor(seconds / 60);
+ const secs = Math.floor(seconds % 60);
+ return `${mins}:${secs.toString().padStart(2, '0')}`;
+ };
+
+ const formatDuration = (totalSeconds) => {
+ if (!totalSeconds && totalSeconds !== 0) return '';
+ totalSeconds = Math.round(totalSeconds);
+ if (totalSeconds < 1) {
+ return '< 1s';
+ }
+ const hours = Math.floor(totalSeconds / 3600);
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
+ const seconds = totalSeconds % 60;
+ if (totalSeconds < 60) {
+ return `${seconds}s`;
+ }
+ let parts = [];
+ if (hours > 0) {
+ parts.push(`${hours}h`);
+ }
+ if (minutes > 0) {
+ parts.push(`${minutes}m`);
+ }
+ if (hours === 0 && seconds > 0) {
+ parts.push(`${seconds}s`);
+ }
+ return parts.join(' ');
+ };
+
+ const formatEventDateTime = (dateString, timeOnly = false) => {
+ if (!dateString) return '';
+ const date = new Date(dateString);
+ if (timeOnly) {
+ return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
+ }
+ return date.toLocaleString([], {
+ weekday: 'short', month: 'short', day: 'numeric',
+ hour: '2-digit', minute: '2-digit'
+ });
+ };
+
+ // Date helper functions
+ const getDateForSorting = (recording) => {
+ const dateStr = sortBy.value === 'meeting_date'
+ ? (recording.meeting_date || recording.created_at)
+ : recording.created_at;
+ return dateStr ? new Date(dateStr) : null;
+ };
+
+ const isToday = (date) => {
+ const today = new Date();
+ return date.getDate() === today.getDate() &&
+ date.getMonth() === today.getMonth() &&
+ date.getFullYear() === today.getFullYear();
+ };
+
+ const isYesterday = (date) => {
+ const yesterday = new Date();
+ yesterday.setDate(yesterday.getDate() - 1);
+ return date.getDate() === yesterday.getDate() &&
+ date.getMonth() === yesterday.getMonth() &&
+ date.getFullYear() === yesterday.getFullYear();
+ };
+
+ const isThisWeek = (date) => {
+ const now = new Date();
+ const startOfWeek = new Date(now);
+ startOfWeek.setDate(now.getDate() - now.getDay());
+ startOfWeek.setHours(0, 0, 0, 0);
+ const endOfWeek = new Date(startOfWeek);
+ endOfWeek.setDate(startOfWeek.getDate() + 7);
+ return date >= startOfWeek && date < endOfWeek && !isToday(date) && !isYesterday(date);
+ };
+
+ const isLastWeek = (date) => {
+ const now = new Date();
+ const startOfLastWeek = new Date(now);
+ startOfLastWeek.setDate(now.getDate() - now.getDay() - 7);
+ startOfLastWeek.setHours(0, 0, 0, 0);
+ const endOfLastWeek = new Date(startOfLastWeek);
+ endOfLastWeek.setDate(startOfLastWeek.getDate() + 7);
+ return date >= startOfLastWeek && date < endOfLastWeek;
+ };
+
+ const isThisMonth = (date) => {
+ const now = new Date();
+ return date.getMonth() === now.getMonth() &&
+ date.getFullYear() === now.getFullYear() &&
+ !isToday(date) && !isYesterday(date) && !isThisWeek(date) && !isLastWeek(date);
+ };
+
+ const isLastMonth = (date) => {
+ const now = new Date();
+ const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
+ return date.getMonth() === lastMonth.getMonth() &&
+ date.getFullYear() === lastMonth.getFullYear();
+ };
+
+ const isSameDay = (date1, date2) => {
+ return date1.getDate() === date2.getDate() &&
+ date1.getMonth() === date2.getMonth() &&
+ date1.getFullYear() === date2.getFullYear();
+ };
+
+ // Bundle utilities for composables
+ const utils = {
+ t, tc, setGlobalError, showToast, formatFileSize, formatDisplayDate, formatShortDate,
+ formatStatus, getStatusClass, formatTime, formatDuration, formatEventDateTime,
+ getDateForSorting, isToday, isYesterday, isThisWeek, isLastWeek, isThisMonth, isLastMonth, isSameDay,
+ nextTick
+ };
+
+ // =========================================================================
+ // COMPUTED PROPERTIES (define before composables that need them)
+ // =========================================================================
+ const processedTranscription = computed(() => {
+ if (!selectedRecording.value?.transcription) {
+ return { hasDialogue: false, content: '', speakers: [], simpleSegments: [], bubbleRows: [] };
+ }
+
+ const transcription = selectedRecording.value.transcription;
+ let transcriptionData;
+
+ try {
+ transcriptionData = JSON.parse(transcription);
+ } catch (e) {
+ transcriptionData = null;
+ }
+
+ // Handle new simplified JSON format (array of segments)
+ if (transcriptionData && Array.isArray(transcriptionData)) {
+ const wasDiarized = transcriptionData.some(segment => segment.speaker);
+
+ if (!wasDiarized) {
+ const segments = transcriptionData.map(segment => ({
+ sentence: segment.sentence,
+ startTime: segment.start_time,
+ }));
+ return {
+ hasDialogue: false,
+ isJson: true,
+ content: segments.map(s => s.sentence).join('\n'),
+ simpleSegments: segments,
+ speakers: [],
+ bubbleRows: []
+ };
+ }
+
+ // Extract unique speakers
+ const speakers = [...new Set(transcriptionData.map(segment => segment.speaker).filter(Boolean))];
+ const speakerColors = {};
+ speakers.forEach((speaker, index) => {
+ speakerColors[speaker] = `speaker-color-${(index % 8) + 1}`;
+ });
+
+ const simpleSegments = transcriptionData.map(segment => ({
+ speakerId: segment.speaker,
+ speaker: speakerMap.value[segment.speaker]?.name || segment.speaker,
+ sentence: segment.sentence,
+ startTime: segment.start_time || segment.startTime,
+ endTime: segment.end_time || segment.endTime,
+ color: speakerColors[segment.speaker] || 'speaker-color-1'
+ }));
+
+ const processedSimpleSegments = [];
+ let lastSpeakerId = null;
+ simpleSegments.forEach(segment => {
+ processedSimpleSegments.push({
+ ...segment,
+ showSpeaker: segment.speakerId !== lastSpeakerId
+ });
+ lastSpeakerId = segment.speakerId;
+ });
+
+ const bubbleRows = [];
+ let lastBubbleSpeakerId = null;
+ simpleSegments.forEach(segment => {
+ if (bubbleRows.length === 0 || segment.speakerId !== lastBubbleSpeakerId) {
+ bubbleRows.push({
+ speaker: segment.speaker,
+ color: segment.color,
+ isMe: segment.speaker && (typeof segment.speaker === 'string') && segment.speaker.toLowerCase().includes('me'),
+ bubbles: []
+ });
+ lastBubbleSpeakerId = segment.speakerId;
+ }
+ bubbleRows[bubbleRows.length - 1].bubbles.push({
+ sentence: segment.sentence,
+ startTime: segment.startTime || segment.start_time,
+ color: segment.color
+ });
+ });
+
+ return {
+ hasDialogue: true,
+ isJson: true,
+ segments: simpleSegments,
+ simpleSegments: processedSimpleSegments,
+ bubbleRows: bubbleRows,
+ speakers: speakers.map(speaker => ({
+ name: speakerMap.value[speaker]?.name || speaker,
+ color: speakerColors[speaker]
+ }))
+ };
+
+ } else {
+ // Fallback for plain text transcription
+ const speakerRegex = /\[([^\]]+)\]:\s*/g;
+ const hasDialogue = speakerRegex.test(transcription);
+
+ if (!hasDialogue) {
+ return {
+ hasDialogue: false,
+ isJson: false,
+ content: transcription,
+ speakers: [],
+ simpleSegments: [],
+ bubbleRows: []
+ };
+ }
+
+ speakerRegex.lastIndex = 0;
+ const speakers = new Set();
+ let match;
+ while ((match = speakerRegex.exec(transcription)) !== null) {
+ speakers.add(match[1]);
+ }
+
+ const speakerList = Array.from(speakers);
+ const speakerColors = {};
+ speakerList.forEach((speaker, index) => {
+ speakerColors[speaker] = `speaker-color-${(index % 8) + 1}`;
+ });
+
+ const segments = [];
+ const lines = transcription.split('\n');
+ let currentSpeakerId = null;
+ let currentText = '';
+
+ for (const line of lines) {
+ const speakerMatch = line.match(/^\[([^\]]+)\]:\s*(.*)$/);
+ if (speakerMatch) {
+ if (currentSpeakerId && currentText.trim()) {
+ segments.push({
+ speakerId: currentSpeakerId,
+ speaker: speakerMap.value[currentSpeakerId]?.name || currentSpeakerId,
+ sentence: currentText.trim(),
+ color: speakerColors[currentSpeakerId] || 'speaker-color-1'
+ });
+ }
+ currentSpeakerId = speakerMatch[1];
+ currentText = speakerMatch[2];
+ } else if (currentSpeakerId && line.trim()) {
+ currentText += ' ' + line.trim();
+ } else if (!currentSpeakerId && line.trim()) {
+ segments.push({
+ speakerId: null,
+ speaker: null,
+ sentence: line.trim(),
+ color: 'speaker-color-1'
+ });
+ }
+ }
+
+ if (currentSpeakerId && currentText.trim()) {
+ segments.push({
+ speakerId: currentSpeakerId,
+ speaker: speakerMap.value[currentSpeakerId]?.name || currentSpeakerId,
+ sentence: currentText.trim(),
+ color: speakerColors[currentSpeakerId] || 'speaker-color-1'
+ });
+ }
+
+ const simpleSegments = [];
+ let lastSpeakerId = null;
+ segments.forEach(segment => {
+ simpleSegments.push({
+ ...segment,
+ showSpeaker: segment.speakerId !== lastSpeakerId,
+ sentence: segment.sentence || segment.text
+ });
+ lastSpeakerId = segment.speakerId;
+ });
+
+ const bubbleRows = [];
+ let currentRow = null;
+ segments.forEach(segment => {
+ if (!currentRow || currentRow.speakerId !== segment.speakerId) {
+ if (currentRow) bubbleRows.push(currentRow);
+ currentRow = {
+ speakerId: segment.speakerId,
+ speaker: segment.speaker,
+ color: segment.color,
+ bubbles: [],
+ isMe: segment.speaker && segment.speaker.toLowerCase().includes('me')
+ };
+ }
+ currentRow.bubbles.push({
+ sentence: segment.sentence,
+ color: segment.color
+ });
+ });
+ if (currentRow) bubbleRows.push(currentRow);
+
+ return {
+ hasDialogue: true,
+ isJson: false,
+ segments: segments,
+ simpleSegments: simpleSegments,
+ bubbleRows: bubbleRows,
+ speakers: speakerList.map(speaker => ({
+ name: speakerMap.value[speaker]?.name || speaker,
+ color: speakerColors[speaker] || 'speaker-color-1'
+ }))
+ };
+ }
+ });
+
+ // =========================================================================
+ // INITIALIZE COMPOSABLES (after processedTranscription is defined)
+ // =========================================================================
+ // Create reprocess composable first so it can be passed to recordings
+ const reprocessComposable = useReprocess(state, utils);
+ const recordingsComposable = useRecordings(state, utils, reprocessComposable);
+ const uploadComposable = useUpload(state, utils);
+
+ // Add startUpload to utils for audio composable to use
+ utils.startUploadQueue = uploadComposable.startUpload;
+
+ const audioComposable = useAudio(state, utils);
+ const uiComposable = useUI(state, utils, processedTranscription);
+ const modalsComposable = useModals(state, utils);
+ const sharingComposable = useSharing(state, utils);
+ const transcriptionComposable = useTranscription(state, utils);
+ const chatComposable = useChat(state, utils);
+ const tagsComposable = useTags({
+ recordings,
+ availableTags,
+ selectedRecording,
+ showEditTagsModal,
+ editingRecording,
+ tagSearchFilter,
+ showToast,
+ setGlobalError
+ });
+
+ // Speakers composable needs processedTranscription, so initialize it after
+ const speakersComposable = useSpeakers(state, utils, processedTranscription);
+
+ // DEBUG: Check if handleAudioTimeUpdate exists
+ console.log('handleAudioTimeUpdate from uiComposable:', typeof uiComposable.handleAudioTimeUpdate);
+ console.log('toggleFollowPlayerMode from uiComposable:', typeof uiComposable.toggleFollowPlayerMode);
+
+ // DEBUG: Watch for when recording changes and check audio element
+ watch(selectedRecording, () => {
+ nextTick(() => {
+ const audioElements = document.querySelectorAll('audio');
+ console.log('Audio elements found:', audioElements.length);
+ audioElements.forEach((audio, index) => {
+ console.log(`Audio ${index}:`, audio);
+ console.log(`Audio ${index} has timeupdate listener:`, audio.ontimeupdate);
+ // Manually add a test listener
+ audio.addEventListener('timeupdate', (e) => {
+ console.log('MANUAL timeupdate listener fired!', e.target.currentTime);
+ }, { once: true });
+ });
+ });
+ });
+
+ const groupedRecordings = computed(() => {
+ const groups = {};
+ recordings.value.forEach(recording => {
+ const date = getDateForSorting(recording);
+ if (!date) return;
+ let group;
+ if (isToday(date)) group = t('sidebar.today');
+ else if (isYesterday(date)) group = t('sidebar.yesterday');
+ else if (isThisWeek(date)) group = t('sidebar.thisWeek');
+ else if (isLastWeek(date)) group = t('sidebar.lastWeek');
+ else if (isThisMonth(date)) group = t('sidebar.thisMonth');
+ else if (isLastMonth(date)) group = t('sidebar.lastMonth');
+ else group = t('sidebar.older');
+ if (!groups[group]) groups[group] = [];
+ groups[group].push(recording);
+ });
+ return Object.entries(groups).map(([title, items]) => ({ title, items }));
+ });
+
+ const filteredAvailableTags = computed(() => {
+ return availableTags.value.filter(tag =>
+ !selectedTagIds.value.includes(tag.id) &&
+ (!tagSearchFilter.value || tag.name.toLowerCase().includes(tagSearchFilter.value.toLowerCase()))
+ );
+ });
+
+ const selectedTags = computed(() => {
+ return selectedTagIds.value.map(id =>
+ availableTags.value.find(t => t.id === id)
+ ).filter(Boolean);
+ });
+
+ const toasts = ref([]);
+
+ // Date preset options for filters
+ const datePresetOptions = computed(() => {
+ return [
+ { value: 'today', label: t('sidebar.today') },
+ { value: 'yesterday', label: t('sidebar.yesterday') },
+ { value: 'thisweek', label: t('sidebar.thisWeek') },
+ { value: 'lastweek', label: t('sidebar.lastWeek') },
+ { value: 'thismonth', label: t('sidebar.thisMonth') },
+ { value: 'lastmonth', label: t('sidebar.lastMonth') }
+ ];
+ });
+
+ // Language options for ASR
+ const languageOptions = computed(() => {
+ return [
+ { value: '', label: t('form.autoDetect') },
+ { value: 'en', label: t('languages.en') },
+ { value: 'es', label: t('languages.es') },
+ { value: 'fr', label: t('languages.fr') },
+ { value: 'de', label: t('languages.de') },
+ { value: 'it', label: t('languages.it') },
+ { value: 'pt', label: t('languages.pt') },
+ { value: 'nl', label: t('languages.nl') },
+ { value: 'ru', label: t('languages.ru') },
+ { value: 'zh', label: t('languages.zh') },
+ { value: 'ja', label: t('languages.ja') },
+ { value: 'ko', label: t('languages.ko') }
+ ];
+ });
+
+ // Recording metadata for sidebar
+ const activeRecordingMetadata = computed(() => {
+ if (!selectedRecording.value) return [];
+
+ const recording = selectedRecording.value;
+ const metadata = [];
+
+ if (recording.created_at) {
+ // Format duration in human-readable format (e.g., "2m 30s")
+ const formatProcessingDuration = (seconds) => {
+ if (!seconds && seconds !== 0) return null;
+ if (seconds < 60) return `${seconds}s`;
+ const mins = Math.floor(seconds / 60);
+ const secs = seconds % 60;
+ return secs > 0 ? `${mins}m ${secs}s` : `${mins}m`;
+ };
+
+ // Build tooltip with processing breakdown
+ let tooltipParts = [`Processed: ${formatDisplayDate(recording.completed_at || recording.created_at)}`];
+
+ if (recording.transcription_duration_seconds) {
+ tooltipParts.push(`Transcription: ${formatProcessingDuration(recording.transcription_duration_seconds)}`);
+ }
+ if (recording.summarization_duration_seconds) {
+ tooltipParts.push(`Summarization: ${formatProcessingDuration(recording.summarization_duration_seconds)}`);
+ }
+
+ const tooltipText = tooltipParts.length > 1 ? tooltipParts.join('\n') : null;
+
+ metadata.push({
+ icon: 'fas fa-history',
+ text: formatDisplayDate(recording.created_at),
+ fullText: tooltipText
+ });
+ }
+
+ if (recording.file_size) {
+ metadata.push({
+ icon: 'fas fa-file-audio',
+ text: formatFileSize(recording.file_size)
+ });
+ }
+
+ if (recording.duration) {
+ metadata.push({
+ icon: 'fas fa-clock',
+ text: formatDuration(recording.duration)
+ });
+ }
+
+ if (recording.original_filename) {
+ const maxLength = 30;
+ const truncated = recording.original_filename.length > maxLength
+ ? recording.original_filename.substring(0, maxLength) + '...'
+ : recording.original_filename;
+ metadata.push({
+ icon: 'fas fa-file',
+ text: truncated,
+ fullText: recording.original_filename
+ });
+ }
+
+ return metadata;
+ });
+
+ // Upload queue computed properties
+ const totalInQueue = computed(() => uploadQueue.value.length);
+ const completedInQueue = computed(() => uploadQueue.value.filter(item => item.status === 'completed' || item.status === 'failed').length);
+ const finishedFilesInQueue = computed(() => uploadQueue.value.filter(item => ['completed', 'failed'].includes(item.status)));
+ const waitingFilesInQueue = computed(() => uploadQueue.value.filter(item => item.status === 'ready'));
+ const pendingQueueFiles = computed(() => uploadQueue.value.filter(item => item.status === 'queued'));
+
+ // Speaker computed properties
+ const hasSpeakerNames = computed(() => {
+ // Check if any speaker has a non-empty name
+ return Object.values(speakerMap.value).some(speakerData =>
+ speakerData && speakerData.name && speakerData.name.trim() !== ''
+ );
+ });
+
+ // Tags with custom prompts for reprocess modal
+ const tagsWithCustomPrompts = computed(() => {
+ return availableTags.value.filter(tag => tag.custom_prompt && tag.custom_prompt.trim() !== '');
+ });
+
+ // Get tag prompt preview
+ const getTagPromptPreview = (tagId) => {
+ const tag = availableTags.value.find(t => t.id == tagId);
+ if (tag && tag.custom_prompt) {
+ // Return first 100 characters of the custom prompt
+ return tag.custom_prompt.length > 100
+ ? tag.custom_prompt.substring(0, 100) + '...'
+ : tag.custom_prompt;
+ }
+ return '';
+ };
+
+ // Tag functions from composable (using composable's implementations)
+
+ // =========================================================================
+ // WATCHERS
+ // =========================================================================
+ // Watch for search query changes
+ watch(searchQuery, (newQuery) => {
+ recordingsComposable.debouncedSearch(newQuery);
+ });
+
+ // Auto-apply filters when they change
+ watch(filterTags, () => {
+ recordingsComposable.applyAdvancedFilters();
+ }, { deep: true });
+
+ watch(filterDatePreset, () => {
+ recordingsComposable.applyAdvancedFilters();
+ });
+
+ watch(filterDateRange, () => {
+ recordingsComposable.applyAdvancedFilters();
+ }, { deep: true });
+
+ watch(filterTextQuery, (newValue) => {
+ clearTimeout(searchDebounceTimer.value);
+ searchDebounceTimer.value = setTimeout(() => {
+ recordingsComposable.applyAdvancedFilters();
+ }, 300);
+ });
+
+ watch(showArchivedRecordings, () => {
+ // Reload recordings when switching between archived/normal view
+ if (showArchivedRecordings.value) {
+ showSharedWithMe.value = false; // Can't show both at once
+ }
+ recordingsComposable.loadRecordings(1, false, searchQuery.value);
+ });
+
+ watch(showSharedWithMe, () => {
+ // Reload recordings when switching to/from shared view
+ if (showSharedWithMe.value) {
+ showArchivedRecordings.value = false; // Can't show both at once
+ }
+ recordingsComposable.loadRecordings(1, false, searchQuery.value);
+ });
+
+ // Watch for view changes to initialize recording notes editor
+ watch(currentView, async (newView, oldView) => {
+ if (newView === 'recording') {
+ // Initialize recording notes editor when entering recording view
+ await nextTick();
+ uiComposable.initializeRecordingNotesEditor();
+ } else if (oldView === 'recording') {
+ // Destroy editor when leaving recording view
+ uiComposable.destroyRecordingNotesEditor();
+ }
+ });
+
+ // Watch for mobile tab changes to reinitialize editors if still in edit mode
+ watch(mobileTab, async (newTab) => {
+ // Wait for DOM to update
+ await nextTick();
+
+ // If switching to summary tab and still in edit mode, reinitialize editor
+ if (newTab === 'summary' && editingSummary.value) {
+ uiComposable.initializeSummaryMarkdownEditor();
+ }
+
+ // If switching to notes tab and still in edit mode, reinitialize editor
+ if (newTab === 'notes' && editingNotes.value) {
+ uiComposable.initializeMarkdownEditor();
+ }
+ });
+
+ // Watch for desktop tab changes to reinitialize editors if still in edit mode
+ watch(selectedTab, async (newTab) => {
+ // Wait for DOM to update
+ await nextTick();
+
+ // If switching to summary tab and still in edit mode, reinitialize editor
+ if (newTab === 'summary' && editingSummary.value) {
+ uiComposable.initializeSummaryMarkdownEditor();
+ }
+
+ // If switching to notes tab and still in edit mode, reinitialize editor
+ if (newTab === 'notes' && editingNotes.value) {
+ uiComposable.initializeMarkdownEditor();
+ }
+ });
+
+ // Watch for selectedRecording changes to reset chat
+ watch(selectedRecording, (newRecording, oldRecording) => {
+ // Only clear if we're actually switching to a different recording
+ if (oldRecording && newRecording && oldRecording.id !== newRecording.id) {
+ chatMessages.value = [];
+ chatInput.value = '';
+ }
+ });
+
+ // =========================================================================
+ // LIFECYCLE
+ // =========================================================================
+ onMounted(async () => {
+ // Get config from data attributes
+ const appElement = document.getElementById('app');
+ if (appElement) {
+ useAsrEndpoint.value = appElement.dataset.useAsrEndpoint === 'True';
+ currentUserName.value = appElement.dataset.currentUserName || '';
+ }
+
+ // Initialize UI
+ uiComposable.initializeDarkMode();
+ uiComposable.initializeColorScheme();
+ uiComposable.initializeSidebar();
+
+ // Load initial data
+ await Promise.all([
+ recordingsComposable.loadRecordings(),
+ recordingsComposable.loadTags()
+ ]);
+
+ // Load config
+ try {
+ const response = await fetch('/api/config');
+ if (response.ok) {
+ const config = await response.json();
+ maxFileSizeMB.value = config.max_file_size_mb || 250;
+ chunkingEnabled.value = config.chunking_enabled !== false;
+ chunkingMode.value = config.chunking_mode || 'size';
+ chunkingLimit.value = config.chunking_limit || 20;
+ recordingDisclaimer.value = config.recording_disclaimer || '';
+ canDeleteRecordings.value = config.can_delete_recordings !== false;
+ enableInternalSharing.value = config.enable_internal_sharing === true;
+ enableArchiveToggle.value = config.enable_archive_toggle === true;
+ showUsernamesInUI.value = config.show_usernames_in_ui === true;
+ }
+ } catch (error) {
+ console.error('Failed to load config:', error);
+ }
+
+ // Initialize UI settings from localStorage
+ uiComposable.initializeUI();
+
+ // Initialize audio capabilities
+ await audioComposable.initializeAudio();
+
+ // Show app - hide loader and show main content
+ const loader = document.getElementById('loader');
+ const appEl = document.getElementById('app');
+ if (loader) {
+ loader.style.opacity = '0';
+ setTimeout(() => {
+ loader.style.display = 'none';
+ }, 500);
+ }
+ if (appEl) {
+ appEl.style.opacity = '1';
+ appEl.classList.remove('opacity-0');
+ }
+
+ // Also hide AppLoader overlay if it exists
+ if (window.AppLoader) {
+ window.AppLoader.hide();
+ }
+
+ // Window resize handler
+ window.addEventListener('resize', () => {
+ windowWidth.value = window.innerWidth;
+ });
+
+ // Visibility change handler for wake lock
+ document.addEventListener('visibilitychange', audioComposable.handleVisibilityChange);
+ });
+
+ // =========================================================================
+ // RETURN ALL STATE AND METHODS
+ // =========================================================================
+ return {
+ // Translation
+ t, tc,
+
+ // State
+ ...state,
+
+ // Computed
+ isMobileScreen,
+ isMobileDevice,
+ processedTranscription,
+ groupedRecordings,
+ filteredAvailableTags,
+ selectedTags,
+ colorSchemes,
+ dropdownPositions,
+ toasts,
+ datePresetOptions,
+ languageOptions,
+ activeRecordingMetadata,
+ totalInQueue,
+ completedInQueue,
+ finishedFilesInQueue,
+ waitingFilesInQueue,
+ pendingQueueFiles,
+ hasSpeakerNames,
+ tagsWithCustomPrompts,
+ getTagPromptPreview,
+
+ // Utilities
+ formatFileSize,
+ formatDisplayDate,
+ formatShortDate,
+ formatStatus,
+ getStatusClass,
+ formatTime,
+ formatDuration,
+ formatEventDateTime,
+ setGlobalError,
+ showToast,
+ getContrastTextColor,
+ getBubbleGlobalIndex,
+
+ // Composable methods
+ ...recordingsComposable,
+ ...uploadComposable,
+ ...audioComposable,
+ ...uiComposable,
+ ...modalsComposable,
+ ...sharingComposable,
+ ...reprocessComposable,
+ ...transcriptionComposable,
+ ...speakersComposable,
+ ...chatComposable,
+ ...tagsComposable
+ };
+ },
+ delimiters: ['${', '}']
+ });
+
+ app.config.globalProperties.t = safeT;
+ app.config.globalProperties.tc = (key, count, params = {}) => {
+ if (!window.i18n || !window.i18n.tc) {
+ return key;
+ }
+ return window.i18n.tc(key, count, params);
+ };
+
+ app.provide('t', safeT);
+ app.provide('tc', (key, count, params = {}) => {
+ if (!window.i18n || !window.i18n.tc) {
+ return key;
+ }
+ return window.i18n.tc(key, count, params);
+ });
+
+ app.mount('#app');
+});
diff --git a/static/js/composables/index.js b/static/js/composables/index.js
new file mode 100644
index 00000000..d18b2769
--- /dev/null
+++ b/static/js/composables/index.js
@@ -0,0 +1,17 @@
+/**
+ * Composables index - export all composables for easy importing
+ *
+ * Usage (with ES modules/build system):
+ * import { useRecordings, useUpload, useUI } from './composables';
+ */
+
+export { usePagination } from './usePagination.js';
+export { useUI } from './useUI.js';
+export { useFilters } from './useFilters.js';
+export { usePlayer } from './usePlayer.js';
+export { useSharing } from './useSharing.js';
+export { useTranscript } from './useTranscript.js';
+export { useChat } from './useChat.js';
+export { useAudioRecorder } from './useAudioRecorder.js';
+export { useUpload } from './useUpload.js';
+export { useRecordings } from './useRecordings.js';
diff --git a/static/js/composables/useAudioRecorder.js b/static/js/composables/useAudioRecorder.js
new file mode 100644
index 00000000..fa35d700
--- /dev/null
+++ b/static/js/composables/useAudioRecorder.js
@@ -0,0 +1,217 @@
+/**
+ * Audio Recorder composable
+ * Handles audio recording from microphone and/or system audio
+ */
+
+import { ref, computed } from 'vue';
+
+export function useAudioRecorder() {
+ // State
+ const isRecording = ref(false);
+ const isPaused = ref(false);
+ const audioChunks = ref([]);
+ const audioBlobURL = ref(null);
+ const recordingMode = ref('microphone');
+ const mediaRecorder = ref(null);
+ const audioContext = ref(null);
+ const activeStreams = ref([]);
+ const recordingDuration = ref(0);
+ const recordingSize = ref(0);
+ const actualBitrate = ref(128000);
+ const recordingTimer = ref(null);
+ const recordingNotes = ref('');
+ const showRecordingDisclaimerModal = ref(false);
+ const pendingRecordingMode = ref(null);
+ const recordingDisclaimer = ref('');
+
+ // Computed
+ const canRecordAudio = computed(() => navigator.mediaDevices && navigator.mediaDevices.getUserMedia);
+ const canRecordSystemAudio = computed(() => navigator.mediaDevices && navigator.mediaDevices.getDisplayMedia);
+
+ const recordingTimeFormatted = computed(() => {
+ const hours = Math.floor(recordingDuration.value / 3600);
+ const mins = Math.floor((recordingDuration.value % 3600) / 60);
+ const secs = recordingDuration.value % 60;
+ if (hours > 0) {
+ return hours + ':' + String(mins).padStart(2, '0') + ':' + String(secs).padStart(2, '0');
+ }
+ return mins + ':' + String(secs).padStart(2, '0');
+ });
+
+ // Methods
+ const startRecording = async (mode = 'microphone') => {
+ if (recordingDisclaimer.value && recordingDisclaimer.value.trim()) {
+ pendingRecordingMode.value = mode;
+ showRecordingDisclaimerModal.value = true;
+ return;
+ }
+ await startRecordingActual(mode);
+ };
+
+ const acceptDisclaimer = async () => {
+ showRecordingDisclaimerModal.value = false;
+ if (pendingRecordingMode.value) {
+ await startRecordingActual(pendingRecordingMode.value);
+ pendingRecordingMode.value = null;
+ }
+ };
+
+ const cancelDisclaimer = () => {
+ showRecordingDisclaimerModal.value = false;
+ pendingRecordingMode.value = null;
+ };
+
+ const startRecordingActual = async (mode = 'microphone') => {
+ recordingMode.value = mode;
+ audioChunks.value = [];
+ audioBlobURL.value = null;
+ recordingNotes.value = '';
+ activeStreams.value = [];
+ recordingDuration.value = 0;
+ recordingSize.value = 0;
+
+ try {
+ let combinedStream = null;
+ let micStream = null;
+ let systemStream = null;
+
+ if (mode === 'microphone' || mode === 'both') {
+ if (!canRecordAudio.value) throw new Error('Microphone not supported');
+ micStream = await navigator.mediaDevices.getUserMedia({ audio: true });
+ activeStreams.value.push(micStream);
+ }
+
+ if (mode === 'system' || mode === 'both') {
+ if (!canRecordSystemAudio.value) throw new Error('System audio not supported');
+ try {
+ systemStream = await navigator.mediaDevices.getDisplayMedia({ audio: true, video: true });
+ if (systemStream.getAudioTracks().length === 0) {
+ systemStream.getVideoTracks().forEach(track => track.stop());
+ throw new Error('System audio permission not granted');
+ }
+ activeStreams.value.push(systemStream);
+ } catch (err) {
+ if (mode === 'system') throw err;
+ systemStream = null;
+ }
+ }
+
+ // Combine streams
+ if (micStream && systemStream) {
+ audioContext.value = new (window.AudioContext || window.webkitAudioContext)();
+ const micSource = audioContext.value.createMediaStreamSource(micStream);
+ const systemSource = audioContext.value.createMediaStreamSource(systemStream);
+ const destination = audioContext.value.createMediaStreamDestination();
+ micSource.connect(destination);
+ systemSource.connect(destination);
+ combinedStream = new MediaStream([destination.stream.getAudioTracks()[0]]);
+ } else if (systemStream) {
+ combinedStream = new MediaStream(systemStream.getAudioTracks());
+ } else if (micStream) {
+ combinedStream = micStream;
+ }
+
+ if (!combinedStream) throw new Error('No audio streams available');
+
+ // Create MediaRecorder
+ const options = { mimeType: 'audio/webm;codecs=opus', audioBitsPerSecond: 32000 };
+ if (MediaRecorder.isTypeSupported(options.mimeType)) {
+ mediaRecorder.value = new MediaRecorder(combinedStream, options);
+ actualBitrate.value = 32000;
+ } else {
+ mediaRecorder.value = new MediaRecorder(combinedStream);
+ actualBitrate.value = 128000;
+ }
+
+ mediaRecorder.value.ondataavailable = (event) => {
+ if (event.data && event.data.size > 0) {
+ audioChunks.value.push(event.data);
+ recordingSize.value += event.data.size;
+ }
+ };
+
+ mediaRecorder.value.onstop = () => {
+ const audioBlob = new Blob(audioChunks.value, { type: mediaRecorder.value.mimeType });
+ audioBlobURL.value = URL.createObjectURL(audioBlob);
+ };
+
+ mediaRecorder.value.start(1000);
+ isRecording.value = true;
+
+ recordingTimer.value = setInterval(() => {
+ recordingDuration.value++;
+ }, 1000);
+
+ } catch (error) {
+ stopAllStreams();
+ throw error;
+ }
+ };
+
+ const stopRecording = () => {
+ if (mediaRecorder.value && isRecording.value) {
+ mediaRecorder.value.stop();
+ isRecording.value = false;
+ isPaused.value = false;
+
+ if (recordingTimer.value) {
+ clearInterval(recordingTimer.value);
+ recordingTimer.value = null;
+ }
+ stopAllStreams();
+ }
+ };
+
+ const pauseRecording = () => {
+ if (mediaRecorder.value && isRecording.value && !isPaused.value) {
+ mediaRecorder.value.pause();
+ isPaused.value = true;
+ if (recordingTimer.value) {
+ clearInterval(recordingTimer.value);
+ recordingTimer.value = null;
+ }
+ }
+ };
+
+ const resumeRecording = () => {
+ if (mediaRecorder.value && isRecording.value && isPaused.value) {
+ mediaRecorder.value.resume();
+ isPaused.value = false;
+ recordingTimer.value = setInterval(() => {
+ recordingDuration.value++;
+ }, 1000);
+ }
+ };
+
+ const stopAllStreams = () => {
+ activeStreams.value.forEach(stream => {
+ stream.getTracks().forEach(track => track.stop());
+ });
+ activeStreams.value = [];
+
+ if (audioContext.value) {
+ audioContext.value.close().catch(e => console.error("Error closing AudioContext:", e));
+ audioContext.value = null;
+ }
+ };
+
+ const resetRecording = () => {
+ stopRecording();
+ audioChunks.value = [];
+ audioBlobURL.value = null;
+ recordingDuration.value = 0;
+ recordingSize.value = 0;
+ recordingNotes.value = '';
+ };
+
+ const getRecordingBlob = () => {
+ if (audioChunks.value.length === 0) return null;
+ return new Blob(audioChunks.value, { type: 'audio/webm' });
+ };
+
+ return {
+ isRecording, isPaused, audioBlobURL, recordingMode, recordingDuration, recordingSize, recordingNotes,
+ showRecordingDisclaimerModal, recordingDisclaimer, canRecordAudio, canRecordSystemAudio, recordingTimeFormatted,
+ startRecording, stopRecording, pauseRecording, resumeRecording, resetRecording, acceptDisclaimer, cancelDisclaimer, getRecordingBlob
+ };
+}
diff --git a/static/js/composables/useChat.js b/static/js/composables/useChat.js
new file mode 100644
index 00000000..fcfe3aa6
--- /dev/null
+++ b/static/js/composables/useChat.js
@@ -0,0 +1,234 @@
+/**
+ * Chat composable
+ * Handles chat/inquire functionality with streaming responses
+ */
+
+import { ref, reactive, nextTick } from 'vue';
+
+export function useChat() {
+ // State
+ const chatMessages = ref([]);
+ const chatInput = ref('');
+ const isChatLoading = ref(false);
+ const chatMessagesRef = ref(null);
+ const isChatExpanded = ref(false);
+
+ // Methods
+ const isChatScrolledToBottom = () => {
+ if (!chatMessagesRef.value) return true;
+ const { scrollTop, scrollHeight, clientHeight } = chatMessagesRef.value;
+ const scrollableHeight = scrollHeight - clientHeight;
+ if (scrollableHeight <= 0) return true;
+ const scrollPercentage = scrollTop / scrollableHeight;
+ return scrollPercentage >= 0.95; // Within bottom 5%
+ };
+
+ const scrollChatToBottom = () => {
+ if (chatMessagesRef.value) {
+ requestAnimationFrame(() => {
+ if (chatMessagesRef.value) {
+ chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;
+ }
+ });
+ }
+ };
+
+ const sendMessage = async (recordingId) => {
+ if (!chatInput.value.trim() || isChatLoading.value) {
+ return;
+ }
+
+ const message = chatInput.value.trim();
+
+ if (!Array.isArray(chatMessages.value)) {
+ chatMessages.value = [];
+ }
+
+ chatMessages.value.push({ role: 'user', content: message });
+ chatInput.value = '';
+ isChatLoading.value = true;
+
+ await nextTick();
+ scrollChatToBottom();
+
+ let assistantMessage = null;
+
+ try {
+ const messageHistory = chatMessages.value
+ .slice(0, -1)
+ .map(msg => ({ role: msg.role, content: msg.content }));
+
+ const response = await fetch('/chat', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ recording_id: recordingId,
+ message: message,
+ message_history: messageHistory
+ })
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(errorData.error || 'Failed to get chat response');
+ }
+
+ const reader = response.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = '';
+
+ const processStream = async () => {
+ let isFirstChunk = true;
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+
+ buffer += decoder.decode(value, { stream: true });
+ const lines = buffer.split('\n');
+ buffer = lines.pop();
+
+ for (const line of lines) {
+ if (line.startsWith('data: ')) {
+ const jsonStr = line.substring(6);
+ if (jsonStr) {
+ try {
+ const data = JSON.parse(jsonStr);
+
+ if (data.thinking) {
+ const shouldScroll = isChatScrolledToBottom();
+
+ if (isFirstChunk) {
+ isChatLoading.value = false;
+ assistantMessage = reactive({
+ role: 'assistant',
+ content: '',
+ html: '',
+ thinking: data.thinking,
+ thinkingExpanded: false
+ });
+ chatMessages.value.push(assistantMessage);
+ isFirstChunk = false;
+ } else if (assistantMessage) {
+ if (assistantMessage.thinking) {
+ assistantMessage.thinking += '\n\n' + data.thinking;
+ } else {
+ assistantMessage.thinking = data.thinking;
+ }
+ }
+
+ if (shouldScroll) {
+ await nextTick();
+ scrollChatToBottom();
+ }
+ }
+
+ if (data.delta) {
+ const shouldScroll = isChatScrolledToBottom();
+
+ if (isFirstChunk) {
+ isChatLoading.value = false;
+ assistantMessage = reactive({
+ role: 'assistant',
+ content: '',
+ html: '',
+ thinking: '',
+ thinkingExpanded: false
+ });
+ chatMessages.value.push(assistantMessage);
+ isFirstChunk = false;
+ }
+
+ assistantMessage.content += data.delta;
+ if (window.marked) {
+ assistantMessage.html = window.marked.parse(assistantMessage.content);
+ } else {
+ assistantMessage.html = assistantMessage.content;
+ }
+
+ if (shouldScroll) {
+ await nextTick();
+ scrollChatToBottom();
+ }
+ }
+
+ if (data.end_of_stream) {
+ return;
+ }
+
+ if (data.error) {
+ throw new Error(data.error);
+ }
+ } catch (e) {
+ console.error('Error parsing stream data:', e);
+ }
+ }
+ }
+ }
+ }
+ };
+
+ await processStream();
+
+ } catch (error) {
+ console.error('Chat Error:', error);
+ if (assistantMessage) {
+ assistantMessage.content = `Error: ${error.message}`;
+ assistantMessage.html = `<span class="text-red-500">Error: ${error.message}</span>`;
+ } else {
+ chatMessages.value.push({
+ role: 'assistant',
+ content: `Error: ${error.message}`,
+ html: `<span class="text-red-500">Error: ${error.message}</span>`
+ });
+ }
+ } finally {
+ isChatLoading.value = false;
+ await nextTick();
+ if (isChatScrolledToBottom()) {
+ scrollChatToBottom();
+ }
+ }
+ };
+
+ const clearChat = () => {
+ chatMessages.value = [];
+ chatInput.value = '';
+ isChatLoading.value = false;
+ };
+
+ const toggleThinking = (message) => {
+ if (message.thinking) {
+ message.thinkingExpanded = !message.thinkingExpanded;
+ }
+ };
+
+ const setChatRef = (el) => {
+ chatMessagesRef.value = el;
+ };
+
+ const handleChatInput = (event) => {
+ if (event.key === 'Enter' && !event.shiftKey) {
+ event.preventDefault();
+ // Trigger send message (caller should provide recordingId)
+ return true;
+ }
+ return false;
+ };
+
+ return {
+ // State
+ chatMessages,
+ chatInput,
+ isChatLoading,
+ chatMessagesRef,
+ isChatExpanded,
+
+ // Methods
+ sendMessage,
+ clearChat,
+ toggleThinking,
+ setChatRef,
+ scrollChatToBottom,
+ handleChatInput
+ };
+}
diff --git a/static/js/composables/useFilters.js b/static/js/composables/useFilters.js
new file mode 100644
index 00000000..8705e4bc
--- /dev/null
+++ b/static/js/composables/useFilters.js
@@ -0,0 +1,119 @@
+/**
+ * Filters composable
+ * Handles search, filtering, and sorting functionality
+ */
+
+import { ref, computed } from 'vue';
+import { parseDateRange } from '../utils/dateUtils.js';
+
+export function useFilters() {
+ // State
+ const searchQuery = ref('');
+ const showAdvancedFilters = ref(false);
+ const filterTags = ref([]);
+ const filterDateRange = ref({ start: '', end: '' });
+ const filterDatePreset = ref('');
+ const filterTextQuery = ref('');
+ const showArchivedRecordings = ref(false);
+ const showSharedWithMe = ref(false);
+ const sortBy = ref('created_at');
+ const selectedTagFilter = ref(null);
+ const searchDebounceTimer = ref(null);
+
+ // Methods
+ const toggleAdvancedFilters = () => {
+ showAdvancedFilters.value = !showAdvancedFilters.value;
+ };
+
+ const setDatePreset = (preset) => {
+ filterDatePreset.value = preset;
+ const range = parseDateRange(preset);
+ filterDateRange.value = {
+ start: range.start ? range.start.toISOString().split('T')[0] : '',
+ end: range.end ? range.end.toISOString().split('T')[0] : ''
+ };
+ };
+
+ const clearDateFilter = () => {
+ filterDatePreset.value = '';
+ filterDateRange.value = { start: '', end: '' };
+ };
+
+ const toggleTagFilter = (tagId) => {
+ const index = filterTags.value.indexOf(tagId);
+ if (index > -1) {
+ filterTags.value.splice(index, 1);
+ } else {
+ filterTags.value.push(tagId);
+ }
+ };
+
+ const clearTagFilters = () => {
+ filterTags.value = [];
+ selectedTagFilter.value = null;
+ };
+
+ const clearAllFilters = () => {
+ filterTags.value = [];
+ filterDateRange.value = { start: '', end: '' };
+ filterDatePreset.value = '';
+ filterTextQuery.value = '';
+ selectedTagFilter.value = null;
+ searchQuery.value = '';
+ };
+
+ const toggleArchivedView = () => {
+ showArchivedRecordings.value = !showArchivedRecordings.value;
+ if (showArchivedRecordings.value) {
+ showSharedWithMe.value = false;
+ }
+ };
+
+ const toggleSharedView = () => {
+ showSharedWithMe.value = !showSharedWithMe.value;
+ if (showSharedWithMe.value) {
+ showArchivedRecordings.value = false;
+ }
+ };
+
+ const setSortBy = (field) => {
+ sortBy.value = field;
+ };
+
+ const hasActiveFilters = computed(() => {
+ return filterTags.value.length > 0 ||
+ filterDateRange.value.start ||
+ filterDateRange.value.end ||
+ filterTextQuery.value ||
+ searchQuery.value;
+ });
+
+ return {
+ // State
+ searchQuery,
+ showAdvancedFilters,
+ filterTags,
+ filterDateRange,
+ filterDatePreset,
+ filterTextQuery,
+ showArchivedRecordings,
+ showSharedWithMe,
+ sortBy,
+ selectedTagFilter,
+ searchDebounceTimer,
+
+ // Computed
+ hasActiveFilters,
+
+ // Methods
+ toggleAdvancedFilters,
+ setDatePreset,
+ clearDateFilter,
+ toggleTagFilter,
+ clearTagFilters,
+ clearAllFilters,
+ toggleArchivedView,
+ toggleSharedView,
+ setSortBy
+ };
+}
diff --git a/static/js/composables/usePagination.js b/static/js/composables/usePagination.js
new file mode 100644
index 00000000..f23e7c67
--- /dev/null
+++ b/static/js/composables/usePagination.js
@@ -0,0 +1,95 @@
+/**
+ * Pagination composable
+ * Handles pagination state and navigation
+ */
+
+import { ref, computed } from 'vue';
+
+export function usePagination() {
+ // State
+ const currentPage = ref(1);
+ const perPage = ref(25);
+ const totalRecordings = ref(0);
+ const totalPages = ref(0);
+ const hasNextPage = ref(false);
+ const hasPrevPage = ref(false);
+ const isLoadingMore = ref(false);
+
+ // Computed
+ const paginationInfo = computed(() => {
+ const start = (currentPage.value - 1) * perPage.value + 1;
+ const end = Math.min(currentPage.value * perPage.value, totalRecordings.value);
+ return {
+ start,
+ end,
+ total: totalRecordings.value,
+ currentPage: currentPage.value,
+ totalPages: totalPages.value
+ };
+ });
+
+ // Methods
+ const updatePagination = (pagination) => {
+ if (!pagination) {
+ // Reset pagination for non-paginated views
+ currentPage.value = 1;
+ totalPages.value = 1;
+ hasNextPage.value = false;
+ hasPrevPage.value = false;
+ return;
+ }
+
+ currentPage.value = pagination.page;
+ totalRecordings.value = pagination.total;
+ totalPages.value = pagination.total_pages;
+ hasNextPage.value = pagination.has_next;
+ hasPrevPage.value = pagination.has_prev;
+ };
+
+ const goToPage = (page) => {
+ if (page < 1 || page > totalPages.value) return;
+ currentPage.value = page;
+ };
+
+ const nextPage = () => {
+ if (hasNextPage.value) {
+ currentPage.value++;
+ }
+ };
+
+ const prevPage = () => {
+ if (hasPrevPage.value) {
+ currentPage.value--;
+ }
+ };
+
+ const reset = () => {
+ currentPage.value = 1;
+ totalRecordings.value = 0;
+ totalPages.value = 0;
+ hasNextPage.value = false;
+ hasPrevPage.value = false;
+ isLoadingMore.value = false;
+ };
+
+ return {
+ // State
+ currentPage,
+ perPage,
+ totalRecordings,
+ totalPages,
+ hasNextPage,
+ hasPrevPage,
+ isLoadingMore,
+
+ // Computed
+ paginationInfo,
+
+ // Methods
+ updatePagination,
+ goToPage,
+ nextPage,
+ prevPage,
+ reset
+ };
+}
diff --git a/static/js/composables/usePlayer.js b/static/js/composables/usePlayer.js
new file mode 100644
index 00000000..caef9720
--- /dev/null
+++ b/static/js/composables/usePlayer.js
@@ -0,0 +1,147 @@
+/**
+ * Audio Player composable
+ * Handles audio playback functionality
+ */
+
+import { ref, computed, watch } from 'vue';
+
+export function usePlayer() {
+ // State
+ const isPlaying = ref(false);
+ const currentTime = ref(0);
+ const duration = ref(0);
+ const playbackRate = ref(1.0);
+ const audioElement = ref(null);
+
+ // Computed
+ const progress = computed(() => {
+ if (!duration.value) return 0;
+ return (currentTime.value / duration.value) * 100;
+ });
+
+ const formattedCurrentTime = computed(() => {
+ return formatTime(currentTime.value);
+ });
+
+ const formattedDuration = computed(() => {
+ return formatTime(duration.value);
+ });
+
+ // Methods
+ const formatTime = (seconds) => {
+ if (!seconds || isNaN(seconds)) return '0:00';
+ const mins = Math.floor(seconds / 60);
+ const secs = Math.floor(seconds % 60);
+ return `${mins}:${secs.toString().padStart(2, '0')}`;
+ };
+
+ const initPlayer = (audio) => {
+ audioElement.value = audio;
+
+ if (!audio) return;
+
+ audio.addEventListener('loadedmetadata', () => {
+ duration.value = audio.duration;
+ });
+
+ audio.addEventListener('timeupdate', () => {
+ currentTime.value = audio.currentTime;
+ });
+
+ audio.addEventListener('play', () => {
+ isPlaying.value = true;
+ });
+
+ audio.addEventListener('pause', () => {
+ isPlaying.value = false;
+ });
+
+ audio.addEventListener('ended', () => {
+ isPlaying.value = false;
+ currentTime.value = 0;
+ });
+ };
+
+ const play = () => {
+ if (audioElement.value) {
+ audioElement.value.play();
+ }
+ };
+
+ const pause = () => {
+ if (audioElement.value) {
+ audioElement.value.pause();
+ }
+ };
+
+ const togglePlayPause = () => {
+ if (isPlaying.value) {
+ pause();
+ } else {
+ play();
+ }
+ };
+
+ const seek = (time) => {
+ if (audioElement.value) {
+ audioElement.value.currentTime = time;
+ currentTime.value = time;
+ }
+ };
+
+ const seekPercent = (percent) => {
+ if (audioElement.value && duration.value) {
+ const time = (percent / 100) * duration.value;
+ seek(time);
+ }
+ };
+
+ const skip = (seconds) => {
+ if (audioElement.value) {
+ const newTime = Math.max(0, Math.min(duration.value, currentTime.value + seconds));
+ seek(newTime);
+ }
+ };
+
+ const setPlaybackRate = (rate) => {
+ playbackRate.value = rate;
+ if (audioElement.value) {
+ audioElement.value.playbackRate = rate;
+ }
+ };
+
+ const reset = () => {
+ if (audioElement.value) {
+ audioElement.value.pause();
+ audioElement.value.currentTime = 0;
+ }
+ isPlaying.value = false;
+ currentTime.value = 0;
+ duration.value = 0;
+ };
+
+ return {
+ // State
+ isPlaying,
+ currentTime,
+ duration,
+ playbackRate,
+ audioElement,
+
+ // Computed
+ progress,
+ formattedCurrentTime,
+ formattedDuration,
+
+ // Methods
+ initPlayer,
+ play,
+ pause,
+ togglePlayPause,
+ seek,
+ seekPercent,
+ skip,
+ setPlaybackRate,
+ reset
+ };
+}
diff --git a/static/js/composables/useRecordings.js b/static/js/composables/useRecordings.js
new file mode 100644
index 00000000..67fc6321
--- /dev/null
+++ b/static/js/composables/useRecordings.js
@@ -0,0 +1,327 @@
+/**
+ * Recordings composable
+ * Handles recordings list, selection, and CRUD operations
+ */
+
+import { ref, computed } from 'vue';
+import { apiRequest } from '../utils/apiClient.js';
+
+export function useRecordings() {
+ // State
+ const recordings = ref([]);
+ const selectedRecording = ref(null);
+ const isLoadingRecordings = ref(true);
+ const globalError = ref(null);
+ const currentView = ref('upload');
+ const availableTags = ref([]);
+ const selectedTagIds = ref([]);
+ const showTagModal = ref(false);
+ const showDeleteModal = ref(false);
+ const recordingToDelete = ref(null);
+
+ // Computed
+ const completedRecordings = computed(() => {
+ return recordings.value.filter(r => r.status === 'COMPLETED');
+ });
+
+ const processingRecordings = computed(() => {
+ return recordings.value.filter(r => ['PENDING', 'PROCESSING', 'SUMMARIZING'].includes(r.status));
+ });
+
+ const hasRecordings = computed(() => recordings.value.length > 0);
+
+ // Methods
+ const loadRecordings = async (page = 1, filters = {}) => {
+ globalError.value = null;
+ isLoadingRecordings.value = true;
+
+ try {
+ let endpoint = '/api/recordings';
+ if (filters.archived) {
+ endpoint = '/api/recordings/archived';
+ } else if (filters.sharedWithMe) {
+ endpoint = '/api/recordings/shared-with-me';
+ }
+
+ const params = new URLSearchParams({
+ page: page.toString(),
+ per_page: '25'
+ });
+
+ if (filters.query) {
+ params.set('q', filters.query.trim());
+ }
+
+ const response = await fetch(`${endpoint}?${params}`);
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error(data.error || 'Failed to load recordings');
+ }
+
+ const recordingsList = filters.archived || filters.sharedWithMe ? data : data.recordings;
+
+ if (!Array.isArray(recordingsList)) {
+ throw new Error('Invalid response format');
+ }
+
+ recordings.value = recordingsList;
+
+ // Restore last selected recording
+ const lastRecordingId = localStorage.getItem('lastSelectedRecordingId');
+ if (lastRecordingId && recordingsList.length > 0) {
+ const recordingToSelect = recordingsList.find(r => r.id == lastRecordingId);
+ if (recordingToSelect) {
+ selectRecording(recordingToSelect);
+ }
+ }
+
+ return filters.archived || filters.sharedWithMe ? null : data.pagination;
+
+ } catch (error) {
+ globalError.value = error.message;
+ throw error;
+ } finally {
+ isLoadingRecordings.value = false;
+ }
+ };
+
+ const selectRecording = async (recording) => {
+ if (!recording) return;
+
+ selectedRecording.value = recording;
+ currentView.value = 'recording';
+ localStorage.setItem('lastSelectedRecordingId', recording.id);
+
+ // Load full recording details if needed
+ if (!recording.transcription && recording.status === 'COMPLETED') {
+ try {
+ const data = await apiRequest(`/api/recordings/${recording.id}`);
+ Object.assign(selectedRecording.value, data);
+ } catch (error) {
+ console.error('Error loading recording details:', error);
+ }
+ }
+ };
+
+ const deselectRecording = () => {
+ selectedRecording.value = null;
+ currentView.value = 'upload';
+ localStorage.removeItem('lastSelectedRecordingId');
+ };
+
+ const deleteRecording = async (recordingId) => {
+ try {
+ await apiRequest(`/api/recordings/${recordingId}`, {
+ method: 'DELETE'
+ });
+
+ recordings.value = recordings.value.filter(r => r.id !== recordingId);
+
+ if (selectedRecording.value && selectedRecording.value.id === recordingId) {
+ deselectRecording();
+ }
+
+ return true;
+ } catch (error) {
+ globalError.value = error.message;
+ throw error;
+ }
+ };
+
+ const archiveRecording = async (recordingId) => {
+ try {
+ await apiRequest(`/api/recordings/${recordingId}/archive`, {
+ method: 'POST'
+ });
+
+ recordings.value = recordings.value.filter(r => r.id !== recordingId);
+
+ if (selectedRecording.value && selectedRecording.value.id === recordingId) {
+ deselectRecording();
+ }
+
+ return true;
+ } catch (error) {
+ globalError.value = error.message;
+ throw error;
+ }
+ };
+
+ const unarchiveRecording = async (recordingId) => {
+ try {
+ await apiRequest(`/api/recordings/${recordingId}/unarchive`, {
+ method: 'POST'
+ });
+
+ recordings.value = recordings.value.filter(r => r.id !== recordingId);
+
+ return true;
+ } catch (error) {
+ globalError.value = error.message;
+ throw error;
+ }
+ };
+
+ const updateRecording = async (recordingId, updates) => {
+ try {
+ const data = await apiRequest(`/api/recordings/${recordingId}`, {
+ method: 'PUT',
+ body: JSON.stringify(updates)
+ });
+
+ const index = recordings.value.findIndex(r => r.id === recordingId);
+ if (index > -1) {
+ Object.assign(recordings.value[index], data.recording || data);
+ }
+
+ if (selectedRecording.value && selectedRecording.value.id === recordingId) {
+ Object.assign(selectedRecording.value, data.recording || data);
+ }
+
+ return data.recording || data;
+ } catch (error) {
+ globalError.value = error.message;
+ throw error;
+ }
+ };
+
+ const regenerateSummary = async (recordingId, customPrompt = null) => {
+ try {
+ const body = customPrompt ? { custom_prompt: customPrompt } : {};
+ const data = await apiRequest(`/api/recordings/${recordingId}/regenerate-summary`, {
+ method: 'POST',
+ body: JSON.stringify(body)
+ });
+
+ if (selectedRecording.value && selectedRecording.value.id === recordingId) {
+ selectedRecording.value.status = 'SUMMARIZING';
+ }
+
+ return data;
+ } catch (error) {
+ globalError.value = error.message;
+ throw error;
+ }
+ };
+
+ const loadTags = async () => {
+ try {
+ const data = await apiRequest('/api/tags');
+ availableTags.value = data;
+ } catch (error) {
+ console.error('Error loading tags:', error);
+ }
+ };
+
+ const addTagToRecording = async (recordingId, tagId) => {
+ try {
+ const data = await apiRequest(`/api/recordings/${recordingId}/tags`, {
+ method: 'POST',
+ body: JSON.stringify({ tag_id: tagId })
+ });
+
+ if (selectedRecording.value && selectedRecording.value.id === recordingId) {
+ selectedRecording.value.tags = data.tags || [];
+ }
+
+ return data;
+ } catch (error) {
+ globalError.value = error.message;
+ throw error;
+ }
+ };
+
+ const removeTagFromRecording = async (recordingId, tagId) => {
+ try {
+ await apiRequest(`/api/recordings/${recordingId}/tags/${tagId}`, {
+ method: 'DELETE'
+ });
+
+ if (selectedRecording.value && selectedRecording.value.id === recordingId) {
+ selectedRecording.value.tags = selectedRecording.value.tags.filter(t => t.id !== tagId);
+ }
+
+ return true;
+ } catch (error) {
+ globalError.value = error.message;
+ throw error;
+ }
+ };
+
+ const toggleHighlight = async (recordingId) => {
+ const recording = recordings.value.find(r => r.id === recordingId);
+ if (!recording) return;
+
+ const newValue = !recording.is_highlighted;
+
+ try {
+ await updateRecording(recordingId, { is_highlighted: newValue });
+ } catch (error) {
+ throw error;
+ }
+ };
+
+ const setGlobalError = (message) => {
+ globalError.value = message;
+ };
+
+ const clearGlobalError = () => {
+ globalError.value = null;
+ };
+
+ const confirmDelete = (recording) => {
+ recordingToDelete.value = recording;
+ showDeleteModal.value = true;
+ };
+
+ const cancelDelete = () => {
+ recordingToDelete.value = null;
+ showDeleteModal.value = false;
+ };
+
+ const executeDelete = async () => {
+ if (recordingToDelete.value) {
+ await deleteRecording(recordingToDelete.value.id);
+ cancelDelete();
+ }
+ };
+
+ return {
+ // State
+ recordings,
+ selectedRecording,
+ isLoadingRecordings,
+ globalError,
+ currentView,
+ availableTags,
+ selectedTagIds,
+ showTagModal,
+ showDeleteModal,
+ recordingToDelete,
+
+ // Computed
+ completedRecordings,
+ processingRecordings,
+ hasRecordings,
+
+ // Methods
+ loadRecordings,
+ selectRecording,
+ deselectRecording,
+ deleteRecording,
+ archiveRecording,
+ unarchiveRecording,
+ updateRecording,
+ regenerateSummary,
+ loadTags,
+ addTagToRecording,
+ removeTagFromRecording,
+ toggleHighlight,
+ setGlobalError,
+ clearGlobalError,
+ confirmDelete,
+ cancelDelete,
+ executeDelete
+ };
+}
diff --git a/static/js/composables/useSharing.js b/static/js/composables/useSharing.js
new file mode 100644
index 00000000..60706c4a
--- /dev/null
+++ b/static/js/composables/useSharing.js
@@ -0,0 +1,195 @@
+/**
+ * Sharing composable
+ * Handles public and internal sharing functionality
+ */
+
+import { ref } from 'vue';
+import { apiRequest } from '../utils/apiClient.js';
+
+export function useSharing() {
+ // State
+ const showShareModal = ref(false);
+ const showInternalShareModal = ref(false);
+ const shareUrl = ref('');
+ const shareSettings = ref({
+ shareSummary: true,
+ shareNotes: true
+ });
+ const internalShareSettings = ref({
+ userId: null,
+ canEdit: false,
+ canReshare: false
+ });
+ const isLoadingShare = ref(false);
+ const shareError = ref(null);
+
+ // Methods
+ const openShareModal = async (recording) => {
+ showShareModal.value = true;
+ shareError.value = null;
+ isLoadingShare.value = true;
+
+ try {
+ const data = await apiRequest(`/api/recording/${recording.id}/share`);
+
+ if (data.exists) {
+ shareUrl.value = data.share_url;
+ shareSettings.value = {
+ shareSummary: data.share.share_summary,
+ shareNotes: data.share.share_notes
+ };
+ } else {
+ shareUrl.value = '';
+ }
+ } catch (error) {
+ shareError.value = error.message;
+ } finally {
+ isLoadingShare.value = false;
+ }
+ };
+
+ const createShare = async (recordingId) => {
+ isLoadingShare.value = true;
+ shareError.value = null;
+
+ try {
+ const data = await apiRequest(`/api/recording/${recordingId}/share`, {
+ method: 'POST',
+ body: JSON.stringify(shareSettings.value)
+ });
+
+ shareUrl.value = data.share_url;
+ return data;
+ } catch (error) {
+ shareError.value = error.message;
+ throw error;
+ } finally {
+ isLoadingShare.value = false;
+ }
+ };
+
+ const updateShare = async (shareId) => {
+ isLoadingShare.value = true;
+ shareError.value = null;
+
+ try {
+ const data = await apiRequest(`/api/share/${shareId}`, {
+ method: 'PUT',
+ body: JSON.stringify(shareSettings.value)
+ });
+
+ return data;
+ } catch (error) {
+ shareError.value = error.message;
+ throw error;
+ } finally {
+ isLoadingShare.value = false;
+ }
+ };
+
+ const deleteShare = async (shareId) => {
+ isLoadingShare.value = true;
+ shareError.value = null;
+
+ try {
+ await apiRequest(`/api/share/${shareId}`, {
+ method: 'DELETE'
+ });
+
+ shareUrl.value = '';
+ } catch (error) {
+ shareError.value = error.message;
+ throw error;
+ } finally {
+ isLoadingShare.value = false;
+ }
+ };
+
+ const copyShareUrl = async () => {
+ try {
+ await navigator.clipboard.writeText(shareUrl.value);
+ return true;
+ } catch (error) {
+ console.error('Failed to copy:', error);
+ return false;
+ }
+ };
+
+ const openInternalShareModal = (recording) => {
+ showInternalShareModal.value = true;
+ shareError.value = null;
+ internalShareSettings.value = {
+ userId: null,
+ canEdit: false,
+ canReshare: false
+ };
+ };
+
+ const shareInternally = async (recordingId) => {
+ isLoadingShare.value = true;
+ shareError.value = null;
+
+ try {
+ const data = await apiRequest(`/api/recordings/${recordingId}/share-internal`, {
+ method: 'POST',
+ body: JSON.stringify({
+ user_id: internalShareSettings.value.userId,
+ can_edit: internalShareSettings.value.canEdit,
+ can_reshare: internalShareSettings.value.canReshare
+ })
+ });
+
+ return data;
+ } catch (error) {
+ shareError.value = error.message;
+ throw error;
+ } finally {
+ isLoadingShare.value = false;
+ }
+ };
+
+ const revokeInternalShare = async (shareId) => {
+ isLoadingShare.value = true;
+ shareError.value = null;
+
+ try {
+ await apiRequest(`/api/internal-shares/${shareId}`, {
+ method: 'DELETE'
+ });
+ } catch (error) {
+ shareError.value = error.message;
+ throw error;
+ } finally {
+ isLoadingShare.value = false;
+ }
+ };
+
+ const closeShareModal = () => {
+ showShareModal.value = false;
+ showInternalShareModal.value = false;
+ shareUrl.value = '';
+ shareError.value = null;
+ };
+
+ return {
+ // State
+ showShareModal,
+ showInternalShareModal,
+ shareUrl,
+ shareSettings,
+ internalShareSettings,
+ isLoadingShare,
+ shareError,
+
+ // Methods
+ openShareModal,
+ createShare,
+ updateShare,
+ deleteShare,
+ copyShareUrl,
+ openInternalShareModal,
+ shareInternally,
+ revokeInternalShare,
+ closeShareModal
+ };
+}
diff --git a/static/js/composables/useTranscript.js b/static/js/composables/useTranscript.js
new file mode 100644
index 00000000..0c2032e9
--- /dev/null
+++ b/static/js/composables/useTranscript.js
@@ -0,0 +1,209 @@
+/**
+ * Transcript composable
+ * Handles transcript viewing and editing functionality
+ */
+
+import { ref, computed } from 'vue';
+import { apiRequest } from '../utils/apiClient.js';
+
+export function useTranscript() {
+ // State
+ const selectedTab = ref('summary');
+ const isEditingTranscript = ref(false);
+ const editedTranscription = ref('');
+ const isEditingSummary = ref(false);
+ const editedSummary = ref('');
+ const isEditingNotes = ref(false);
+ const editedNotes = ref('');
+ const isInlineEditingTitle = ref(false);
+ const editedTitle = ref('');
+ const isSavingChanges = ref(false);
+ const transcriptSearchQuery = ref('');
+ const highlightedText = ref('');
+
+ // Methods
+ const setTab = (tab) => {
+ selectedTab.value = tab;
+ };
+
+ const startEditingTranscript = (recording) => {
+ isEditingTranscript.value = true;
+ editedTranscription.value = recording.transcription || '';
+ };
+
+ const cancelEditingTranscript = () => {
+ isEditingTranscript.value = false;
+ editedTranscription.value = '';
+ };
+
+ const saveTranscript = async (recordingId) => {
+ isSavingChanges.value = true;
+
+ try {
+ const data = await apiRequest(`/api/recordings/${recordingId}/transcript`, {
+ method: 'PUT',
+ body: JSON.stringify({
+ transcription: editedTranscription.value
+ })
+ });
+
+ isEditingTranscript.value = false;
+ return data.recording;
+ } catch (error) {
+ throw error;
+ } finally {
+ isSavingChanges.value = false;
+ }
+ };
+
+ const startEditingSummary = (recording) => {
+ isEditingSummary.value = true;
+ editedSummary.value = recording.summary || '';
+ };
+
+ const cancelEditingSummary = () => {
+ isEditingSummary.value = false;
+ editedSummary.value = '';
+ };
+
+ const saveSummary = async (recordingId) => {
+ isSavingChanges.value = true;
+
+ try {
+ const data = await apiRequest(`/api/recordings/${recordingId}/summary`, {
+ method: 'PUT',
+ body: JSON.stringify({
+ summary: editedSummary.value
+ })
+ });
+
+ isEditingSummary.value = false;
+ return data.recording;
+ } catch (error) {
+ throw error;
+ } finally {
+ isSavingChanges.value = false;
+ }
+ };
+
+ const startEditingNotes = (recording) => {
+ isEditingNotes.value = true;
+ editedNotes.value = recording.notes || '';
+ };
+
+ const cancelEditingNotes = () => {
+ isEditingNotes.value = false;
+ editedNotes.value = '';
+ };
+
+ const saveNotes = async (recordingId) => {
+ isSavingChanges.value = true;
+
+ try {
+ const data = await apiRequest(`/api/recordings/${recordingId}/notes`, {
+ method: 'PUT',
+ body: JSON.stringify({
+ notes: editedNotes.value
+ })
+ });
+
+ isEditingNotes.value = false;
+ return data.recording;
+ } catch (error) {
+ throw error;
+ } finally {
+ isSavingChanges.value = false;
+ }
+ };
+
+ const startEditingTitle = (recording) => {
+ isInlineEditingTitle.value = true;
+ editedTitle.value = recording.title || '';
+ };
+
+ const cancelEditingTitle = () => {
+ isInlineEditingTitle.value = false;
+ editedTitle.value = '';
+ };
+
+ const saveTitle = async (recordingId) => {
+ isSavingChanges.value = true;
+
+ try {
+ const data = await apiRequest(`/api/recordings/${recordingId}`, {
+ method: 'PUT',
+ body: JSON.stringify({
+ title: editedTitle.value
+ })
+ });
+
+ isInlineEditingTitle.value = false;
+ return data.recording;
+ } catch (error) {
+ throw error;
+ } finally {
+ isSavingChanges.value = false;
+ }
+ };
+
+ const searchInTranscript = (text, query) => {
+ if (!query) {
+ highlightedText.value = text;
+ return text;
+ }
+
+ const regex = new RegExp(`(${query})`, 'gi');
+ highlightedText.value = text.replace(regex, '<mark>$1</mark>');
+ return highlightedText.value;
+ };
+
+ const exportTranscript = async (recordingId, format) => {
+ try {
+ const response = await fetch(`/api/recordings/${recordingId}/export/${format}`);
+ const blob = await response.blob();
+ const url = window.URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `transcript.${format}`;
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ window.URL.revokeObjectURL(url);
+ } catch (error) {
+ throw error;
+ }
+ };
+
+ return {
+ // State
+ selectedTab,
+ isEditingTranscript,
+ editedTranscription,
+ isEditingSummary,
+ editedSummary,
+ isEditingNotes,
+ editedNotes,
+ isInlineEditingTitle,
+ editedTitle,
+ isSavingChanges,
+ transcriptSearchQuery,
+ highlightedText,
+
+ // Methods
+ setTab,
+ startEditingTranscript,
+ cancelEditingTranscript,
+ saveTranscript,
+ startEditingSummary,
+ cancelEditingSummary,
+ saveSummary,
+ startEditingNotes,
+ cancelEditingNotes,
+ saveNotes,
+ startEditingTitle,
+ cancelEditingTitle,
+ saveTitle,
+ searchInTranscript,
+ exportTranscript
+ };
+}
diff --git a/static/js/composables/useUI.js b/static/js/composables/useUI.js
new file mode 100644
index 00000000..f5d9dce2
--- /dev/null
+++ b/static/js/composables/useUI.js
@@ -0,0 +1,147 @@
+/**
+ * UI State composable
+ * Handles all UI-related state (theme, sidebar, modals, etc.)
+ */
+
+import { ref, computed, watch, onMounted } from 'vue';
+
+export function useUI() {
+ // State
+ const browser = ref('unknown');
+ const isSidebarCollapsed = ref(false);
+ const searchTipsExpanded = ref(false);
+ const isUserMenuOpen = ref(false);
+ const isDarkMode = ref(false);
+ const currentColorScheme = ref('blue');
+ const showColorSchemeModal = ref(false);
+ const windowWidth = ref(window.innerWidth);
+ const mobileTab = ref('transcript');
+ const isMetadataExpanded = ref(false);
+ const currentLanguage = ref('en');
+ const currentLanguageName = ref('English');
+ const availableLanguages = ref([]);
+ const showLanguageMenu = ref(false);
+
+ // Computed
+ const isMobile = computed(() => windowWidth.value < 768);
+ const isTablet = computed(() => windowWidth.value >= 768 && windowWidth.value < 1024);
+ const isDesktop = computed(() => windowWidth.value >= 1024);
+
+ const colorSchemes = [
+ { name: 'blue', label: 'Blue', primary: '#3b82f6', hover: '#2563eb' },
+ { name: 'purple', label: 'Purple', primary: '#8b5cf6', hover: '#7c3aed' },
+ { name: 'green', label: 'Green', primary: '#10b981', hover: '#059669' },
+ { name: 'orange', label: 'Orange', primary: '#f59e0b', hover: '#d97706' },
+ { name: 'pink', label: 'Pink', primary: '#ec4899', hover: '#db2777' },
+ { name: 'red', label: 'Red', primary: '#ef4444', hover: '#dc2626' }
+ ];
+
+ // Methods
+ const detectBrowser = () => {
+ const userAgent = navigator.userAgent.toLowerCase();
+ if (userAgent.indexOf('firefox') > -1) browser.value = 'firefox';
+ else if (userAgent.indexOf('chrome') > -1 && userAgent.indexOf('edge') === -1) browser.value = 'chrome';
+ else if (userAgent.indexOf('safari') > -1 && userAgent.indexOf('chrome') === -1) browser.value = 'safari';
+ else if (userAgent.indexOf('edge') > -1) browser.value = 'edge';
+ else browser.value = 'unknown';
+ };
+
+ const toggleSidebar = () => {
+ isSidebarCollapsed.value = !isSidebarCollapsed.value;
+ localStorage.setItem('sidebarCollapsed', isSidebarCollapsed.value.toString());
+ };
+
+ const toggleDarkMode = () => {
+ isDarkMode.value = !isDarkMode.value;
+ document.documentElement.classList.toggle('dark', isDarkMode.value);
+ localStorage.setItem('darkMode', isDarkMode.value ? 'enabled' : 'disabled');
+ };
+
+ const setColorScheme = (scheme) => {
+ currentColorScheme.value = scheme;
+ document.documentElement.setAttribute('data-color-scheme', scheme);
+ localStorage.setItem('colorScheme', scheme);
+ };
+
+ const loadUIPreferences = () => {
+ // Load dark mode
+ const savedDarkMode = localStorage.getItem('darkMode');
+ if (savedDarkMode === 'enabled') {
+ isDarkMode.value = true;
+ document.documentElement.classList.add('dark');
+ }
+
+ // Load color scheme
+ const savedScheme = localStorage.getItem('colorScheme');
+ if (savedScheme && colorSchemes.find(s => s.name === savedScheme)) {
+ setColorScheme(savedScheme);
+ }
+
+ // Load sidebar state
+ const savedSidebar = localStorage.getItem('sidebarCollapsed');
+ if (savedSidebar === 'true') {
+ isSidebarCollapsed.value = true;
+ }
+ };
+
+ const handleResize = () => {
+ windowWidth.value = window.innerWidth;
+ };
+
+ const toggleUserMenu = () => {
+ isUserMenuOpen.value = !isUserMenuOpen.value;
+ };
+
+ const closeUserMenu = () => {
+ isUserMenuOpen.value = false;
+ };
+
+ const setMobileTab = (tab) => {
+ mobileTab.value = tab;
+ };
+
+ const toggleMetadata = () => {
+ isMetadataExpanded.value = !isMetadataExpanded.value;
+ };
+
+ // Initialize
+ onMounted(() => {
+ detectBrowser();
+ loadUIPreferences();
+ window.addEventListener('resize', handleResize);
+ });
+
+ return {
+ // State
+ browser,
+ isSidebarCollapsed,
+ searchTipsExpanded,
+ isUserMenuOpen,
+ isDarkMode,
+ currentColorScheme,
+ showColorSchemeModal,
+ windowWidth,
+ mobileTab,
+ isMetadataExpanded,
+ currentLanguage,
+ currentLanguageName,
+ availableLanguages,
+ showLanguageMenu,
+
+ // Computed
+ isMobile,
+ isTablet,
+ isDesktop,
+ colorSchemes,
+
+ // Methods
+ toggleSidebar,
+ toggleDarkMode,
+ setColorScheme,
+ loadUIPreferences,
+ toggleUserMenu,
+ closeUserMenu,
+ setMobileTab,
+ toggleMetadata
+ };
+}
diff --git a/static/js/composables/useUpload.js b/static/js/composables/useUpload.js
new file mode 100644
index 00000000..4ca05c74
--- /dev/null
+++ b/static/js/composables/useUpload.js
@@ -0,0 +1,280 @@
+/**
+ * Upload composable
+ * Handles file upload queue and processing
+ */
+
+import { ref, computed, nextTick } from 'vue';
+import { uploadFile } from '../utils/apiClient.js';
+
+export function useUpload() {
+ // State
+ const uploadQueue = ref([]);
+ const currentlyProcessingFile = ref(null);
+ const processingProgress = ref(0);
+ const processingMessage = ref('');
+ const isProcessingActive = ref(false);
+ const pollInterval = ref(null);
+ const progressPopupMinimized = ref(false);
+ const progressPopupClosed = ref(false);
+ const maxFileSizeMB = ref(250);
+ const chunkingEnabled = ref(true);
+ const dragover = ref(false);
+
+ // Computed
+ const hasQueuedFiles = computed(() => {
+ return uploadQueue.value.some(item => item.status === 'queued');
+ });
+
+ const processingCount = computed(() => {
+ return uploadQueue.value.filter(item => item.status === 'processing' || item.status === 'queued').length;
+ });
+
+ const completedCount = computed(() => {
+ return uploadQueue.value.filter(item => item.status === 'completed').length;
+ });
+
+ const errorCount = computed(() => {
+ return uploadQueue.value.filter(item => item.status === 'error').length;
+ });
+
+ // Methods
+ const addFilesToQueue = (files) => {
+ const maxFileSize = maxFileSizeMB.value * 1024 * 1024;
+
+ for (const file of files) {
+ if (file.size > maxFileSize) {
+ uploadQueue.value.push({
+ file,
+ status: 'error',
+ error: `File exceeds maximum size of ${maxFileSizeMB.value}MB`,
+ clientId: Date.now() + Math.random()
+ });
+ continue;
+ }
+
+ const isAudio = file.type.startsWith('audio/') ||
+ file.type.startsWith('video/') ||
+ /\.(mp3|wav|ogg|m4a|flac|webm|mp4|mov|avi|mkv)$/i.test(file.name);
+
+ if (!isAudio) {
+ uploadQueue.value.push({
+ file,
+ status: 'error',
+ error: 'File type not supported',
+ clientId: Date.now() + Math.random()
+ });
+ continue;
+ }
+
+ uploadQueue.value.push({
+ file,
+ status: 'queued',
+ recordingId: null,
+ clientId: Date.now() + Math.random(),
+ error: null
+ });
+ }
+
+ if (!isProcessingActive.value && hasQueuedFiles.value) {
+ startProcessingQueue();
+ }
+ };
+
+ const startProcessingQueue = async () => {
+ if (isProcessingActive.value) return;
+
+ const nextItem = uploadQueue.value.find(item => item.status === 'queued');
+ if (!nextItem) {
+ isProcessingActive.value = false;
+ return;
+ }
+
+ isProcessingActive.value = true;
+ currentlyProcessingFile.value = nextItem;
+ nextItem.status = 'uploading';
+ processingProgress.value = 0;
+ processingMessage.value = 'Uploading...';
+
+ try {
+ const data = await uploadFile('/api/recordings/upload', nextItem.file, (progress) => {
+ processingProgress.value = progress;
+ processingMessage.value = `Uploading... ${Math.round(progress)}%`;
+ });
+
+ nextItem.recordingId = data.recording_id;
+ nextItem.status = 'processing';
+ processingMessage.value = 'Processing...';
+
+ // Start polling for status
+ pollProcessingStatus(nextItem);
+
+ } catch (error) {
+ nextItem.status = 'error';
+ nextItem.error = error.message;
+ currentlyProcessingFile.value = null;
+ isProcessingActive.value = false;
+
+ // Continue with next file
+ if (hasQueuedFiles.value) {
+ await nextTick();
+ startProcessingQueue();
+ }
+ }
+ };
+
+ const pollProcessingStatus = (queueItem) => {
+ if (pollInterval.value) {
+ clearInterval(pollInterval.value);
+ }
+
+ pollInterval.value = setInterval(async () => {
+ try {
+ const response = await fetch(`/api/recordings/${queueItem.recordingId}/status`);
+ const data = await response.json();
+
+ if (data.status === 'COMPLETED') {
+ clearInterval(pollInterval.value);
+ pollInterval.value = null;
+
+ queueItem.status = 'completed';
+ currentlyProcessingFile.value = null;
+ isProcessingActive.value = false;
+ processingProgress.value = 100;
+ processingMessage.value = 'Complete!';
+
+ // Continue with next file
+ if (hasQueuedFiles.value) {
+ await nextTick();
+ startProcessingQueue();
+ }
+
+ } else if (data.status === 'ERROR') {
+ clearInterval(pollInterval.value);
+ pollInterval.value = null;
+
+ queueItem.status = 'error';
+ queueItem.error = data.error_message || 'Processing failed';
+ currentlyProcessingFile.value = null;
+ isProcessingActive.value = false;
+
+ // Continue with next file
+ if (hasQueuedFiles.value) {
+ await nextTick();
+ startProcessingQueue();
+ }
+
+ } else {
+ // Still processing
+ if (data.status === 'SUMMARIZING') {
+ processingMessage.value = 'Generating summary...';
+ processingProgress.value = 80;
+ } else {
+ processingMessage.value = 'Transcribing...';
+ processingProgress.value = 50;
+ }
+ }
+
+ } catch (error) {
+ console.error('Error polling status:', error);
+ }
+ }, 3000);
+ };
+
+ const removeFromQueue = (clientId) => {
+ const index = uploadQueue.value.findIndex(item => item.clientId === clientId);
+ if (index > -1) {
+ uploadQueue.value.splice(index, 1);
+ }
+ };
+
+ const clearCompletedFromQueue = () => {
+ uploadQueue.value = uploadQueue.value.filter(item =>
+ item.status !== 'completed' && item.status !== 'error'
+ );
+ };
+
+ const handleDragEnter = (event) => {
+ event.preventDefault();
+ dragover.value = true;
+ };
+
+ const handleDragLeave = (event) => {
+ event.preventDefault();
+ dragover.value = false;
+ };
+
+ const handleDrop = (event) => {
+ event.preventDefault();
+ dragover.value = false;
+
+ const files = Array.from(event.dataTransfer.files);
+ if (files.length > 0) {
+ addFilesToQueue(files);
+ }
+ };
+
+ const handleFileSelect = (event) => {
+ const files = Array.from(event.target.files);
+ if (files.length > 0) {
+ addFilesToQueue(files);
+ }
+ event.target.value = '';
+ };
+
+ const minimizeProgressPopup = () => {
+ progressPopupMinimized.value = true;
+ };
+
+ const maximizeProgressPopup = () => {
+ progressPopupMinimized.value = false;
+ };
+
+ const closeProgressPopup = () => {
+ progressPopupClosed.value = true;
+ };
+
+ const loadConfig = async () => {
+ try {
+ const response = await fetch('/api/config');
+ const data = await response.json();
+ maxFileSizeMB.value = data.max_file_size_mb || 250;
+ chunkingEnabled.value = data.chunking_enabled !== false;
+ } catch (error) {
+ console.error('Error loading config:', error);
+ }
+ };
+
+ return {
+ // State
+ uploadQueue,
+ currentlyProcessingFile,
+ processingProgress,
+ processingMessage,
+ isProcessingActive,
+ progressPopupMinimized,
+ progressPopupClosed,
+ maxFileSizeMB,
+ chunkingEnabled,
+ dragover,
+
+ // Computed
+ hasQueuedFiles,
+ processingCount,
+ completedCount,
+ errorCount,
+
+ // Methods
+ addFilesToQueue,
+ startProcessingQueue,
+ removeFromQueue,
+ clearCompletedFromQueue,
+ handleDragEnter,
+ handleDragLeave,
+ handleDrop,
+ handleFileSelect,
+ minimizeProgressPopup,
+ maximizeProgressPopup,
+ closeProgressPopup,
+ loadConfig
+ };
+}
diff --git a/static/js/loading.js b/static/js/loading.js
index c1fd2dc4..630a59ad 100644
--- a/static/js/loading.js
+++ b/static/js/loading.js
@@ -6,6 +6,7 @@
window.AppLoader = {
initialized: false,
readyChecks: [],
+ initTime: Date.now(),
/**
* Initialize the loading system
@@ -13,6 +14,7 @@ window.AppLoader = {
init() {
if (this.initialized) return;
this.initialized = true;
+ this.initTime = Date.now();
// Add loading class to body
document.body.classList.add('app-loading');
@@ -53,18 +55,33 @@ window.AppLoader = {
*/
setupReadyChecks() {
// Check if DOM is ready
- this.addReadyCheck(() => document.readyState === 'complete');
+ this.addReadyCheck(() => {
+ return document.readyState === 'complete' || document.readyState === 'interactive';
+ });
- // Check if styles are loaded
+ // Check if styles are loaded (optional - don't block on this)
this.addReadyCheck(() => {
- const styles = document.querySelector('link[href*="styles.css"]');
- return !styles || styles.sheet;
+ try {
+ const styles = document.querySelector('link[href*="styles.css"]');
+ // If stylesheet isn't found or loaded, continue anyway after 2 seconds
+ return !styles || styles.sheet || (Date.now() - this.initTime) > 2000;
+ } catch (e) {
+ console.warn('Error checking stylesheet:', e);
+ return true; // Don't block on stylesheet errors
+ }
});
- // Check if theme is initialized
+ // Check if theme is initialized (optional - don't block on this)
this.addReadyCheck(() => {
- const computed = window.getComputedStyle(document.documentElement);
- return computed.getPropertyValue('--bg-primary').trim() !== '';
+ try {
+ const computed = window.getComputedStyle(document.documentElement);
+ const bgPrimary = computed.getPropertyValue('--bg-primary').trim();
+ // Accept if property exists or if 2 seconds have passed
+ return bgPrimary !== '' || (Date.now() - this.initTime) > 2000;
+ } catch (e) {
+ console.warn('Error checking CSS variables:', e);
+ return true; // Don't block on CSS variable errors
+ }
});
},
@@ -86,15 +103,40 @@ window.AppLoader = {
* Hide the loading overlay
*/
hide() {
- const overlay = document.querySelector('.app-loading-overlay');
- if (overlay) {
- overlay.classList.add('fade-out');
- setTimeout(() => {
- overlay.remove();
- document.body.classList.remove('app-loading');
- }, 300);
- } else {
+ try {
+ // Remove app-loading class immediately to show content
document.body.classList.remove('app-loading');
+
+ // Find all loading overlays (might be multiple)
+ const overlays = document.querySelectorAll('.app-loading-overlay');
+
+ if (overlays.length > 0) {
+ overlays.forEach(overlay => {
+ // Force display none immediately in Firefox
+ overlay.style.display = 'none';
+
+ // Then do graceful removal
+ overlay.classList.add('fade-out');
+ setTimeout(() => {
+ try {
+ overlay.remove();
+ } catch (e) {
+ console.warn('Could not remove overlay:', e);
+ }
+ }, 100);
+ });
+ }
+
+ console.log('Loader hidden successfully');
+ } catch (error) {
+ console.error('Error hiding loader:', error);
+ // Force hide everything as last resort
+ document.body.classList.remove('app-loading');
+ const overlays = document.querySelectorAll('.app-loading-overlay');
+ overlays.forEach(o => {
+ o.style.display = 'none';
+ try { o.remove(); } catch (e) {}
+ });
}
},
@@ -103,15 +145,49 @@ window.AppLoader = {
*/
async waitForReady(timeout = 5000) {
const startTime = Date.now();
+ let hideExecuted = false;
+
+ const safeHide = () => {
+ if (!hideExecuted) {
+ hideExecuted = true;
+ try {
+ this.hide();
+ } catch (error) {
+ console.error('Error hiding loader:', error);
+ // Force hide even if error occurs
+ const overlay = document.querySelector('.app-loading-overlay');
+ if (overlay) overlay.remove();
+ document.body.classList.remove('app-loading');
+ }
+ }
+ };
const checkReady = () => {
- if (this.isReady() || Date.now() - startTime > timeout) {
- this.hide();
- } else {
- requestAnimationFrame(checkReady);
+ try {
+ const elapsed = Date.now() - startTime;
+ if (this.isReady()) {
+ console.log('App ready, hiding loader');
+ safeHide();
+ } else if (elapsed > timeout) {
+ console.warn('Loader timeout reached, forcing hide');
+ safeHide();
+ } else {
+ requestAnimationFrame(checkReady);
+ }
+ } catch (error) {
+ console.error('Error in checkReady:', error);
+ safeHide();
}
};
+ // Hard timeout as absolute failsafe - hide after 10 seconds no matter what
+ setTimeout(() => {
+ if (!hideExecuted) {
+ console.warn('Hard timeout reached (10s), forcing loader hide');
+ safeHide();
+ }
+ }, 10000);
+
// Start checking after a minimum display time
setTimeout(checkReady, 300);
}
diff --git a/static/js/modules/composables/audio.js b/static/js/modules/composables/audio.js
new file mode 100644
index 00000000..d25557dc
--- /dev/null
+++ b/static/js/modules/composables/audio.js
@@ -0,0 +1,535 @@
+/**
+ * Audio recording composable
+ * Handles microphone/system audio recording with visualizers and wake lock
+ */
+
+export function useAudio(state, utils) {
+ const {
+ isRecording, mediaRecorder, audioContext, analyser, micAnalyser, systemAnalyser,
+ audioChunks, recordingTime, recordingInterval, recordingMode, audioBlobURL,
+ estimatedFileSize, actualBitrate, recordingNotes, recordingQuality,
+ maxRecordingMB, fileSizeWarningShown, sizeCheckInterval, recordingDisclaimer,
+ showRecordingDisclaimerModal, currentView, isDarkMode, wakeLock, animationFrameId,
+ activeStreams, visualizer, micVisualizer, systemVisualizer, canRecordAudio,
+ canRecordSystemAudio, systemAudioSupported, systemAudioError, globalError,
+ selectedTagIds, asrLanguage, asrMinSpeakers, asrMaxSpeakers, uploadQueue,
+ progressPopupMinimized, progressPopupClosed
+ } = state;
+
+ const { showToast, setGlobalError, formatFileSize, startUploadQueue } = utils;
+
+ // Acquire wake lock to prevent screen from sleeping during recording
+ const acquireWakeLock = async () => {
+ try {
+ if ('wakeLock' in navigator) {
+ wakeLock.value = await navigator.wakeLock.request('screen');
+ console.log('[WakeLock] Acquired');
+ }
+ } catch (err) {
+ console.warn('[WakeLock] Could not acquire:', err.message);
+ }
+ };
+
+ // Release wake lock
+ const releaseWakeLock = async () => {
+ if (wakeLock.value) {
+ try {
+ await wakeLock.value.release();
+ wakeLock.value = null;
+ console.log('[WakeLock] Released');
+ } catch (err) {
+ console.warn('[WakeLock] Could not release:', err.message);
+ }
+ }
+ };
+
+ // Show recording notification
+ const showRecordingNotification = async () => {
+ if ('Notification' in window && Notification.permission === 'granted') {
+ // Notifications handled by service worker
+ }
+ };
+
+ // Detect system audio capabilities
+ const detectSystemAudioCapabilities = async () => {
+ systemAudioSupported.value = false;
+ canRecordSystemAudio.value = false;
+ systemAudioError.value = '';
+
+ // Check if getDisplayMedia is available
+ if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {
+ systemAudioError.value = 'getDisplayMedia API not supported';
+ return;
+ }
+
+ try {
+ // Test if we can request system audio (this will prompt user)
+ // We'll do this only when user actually tries to record
+ systemAudioSupported.value = true;
+ canRecordSystemAudio.value = true;
+ systemAudioError.value = '';
+ } catch (error) {
+ systemAudioError.value = error.message;
+ console.warn('System audio detection failed:', error);
+ }
+ };
+
+ // Hide recording notification
+ const hideRecordingNotification = async () => {
+ // Notifications cleared when recording stops
+ };
+
+ // Handle visibility change (for wake lock re-acquisition)
+ const handleVisibilityChange = async () => {
+ if (document.visibilityState === 'visible' && isRecording.value) {
+ console.log('[Visibility] Page visible, re-acquiring wake lock');
+ await acquireWakeLock();
+ }
+ };
+
+ // Start recording
+ const startRecording = async (mode = 'microphone') => {
+ // Check if there's a disclaimer to show
+ if (recordingDisclaimer.value && recordingDisclaimer.value.trim() !== '') {
+ showRecordingDisclaimerModal.value = true;
+ state.pendingRecordingMode = mode;
+ return;
+ }
+
+ await startRecordingInternal(mode);
+ };
+
+ // Accept recording disclaimer and start recording
+ const acceptRecordingDisclaimer = async () => {
+ showRecordingDisclaimerModal.value = false;
+ await startRecordingInternal(state.pendingRecordingMode || 'microphone');
+ };
+
+ // Cancel recording disclaimer
+ const cancelRecordingDisclaimer = () => {
+ showRecordingDisclaimerModal.value = false;
+ state.pendingRecordingMode = null;
+ };
+
+ // Internal start recording function
+ const startRecordingInternal = async (mode) => {
+ try {
+ recordingMode.value = mode;
+ audioChunks.value = [];
+ recordingTime.value = 0;
+ estimatedFileSize.value = 0;
+ fileSizeWarningShown.value = false;
+
+ let stream;
+ let combinedStream;
+
+ if (mode === 'microphone') {
+ stream = await navigator.mediaDevices.getUserMedia({
+ audio: {
+ echoCancellation: true,
+ noiseSuppression: true,
+ sampleRate: 48000
+ }
+ });
+ activeStreams.value = [stream];
+
+ audioContext.value = new (window.AudioContext || window.webkitAudioContext)();
+ const source = audioContext.value.createMediaStreamSource(stream);
+ analyser.value = audioContext.value.createAnalyser();
+ analyser.value.fftSize = 256;
+ source.connect(analyser.value);
+
+ } else if (mode === 'system') {
+ stream = await navigator.mediaDevices.getDisplayMedia({
+ video: true,
+ audio: {
+ echoCancellation: false,
+ noiseSuppression: false,
+ autoGainControl: false
+ }
+ });
+
+ const audioTrack = stream.getAudioTracks()[0];
+ if (!audioTrack) {
+ stream.getTracks().forEach(track => track.stop());
+ throw new Error('No system audio track available. Please share a tab or window with audio.');
+ }
+
+ // Stop video track
+ stream.getVideoTracks().forEach(track => track.stop());
+ stream = new MediaStream([audioTrack]);
+ activeStreams.value = [stream];
+
+ audioContext.value = new (window.AudioContext || window.webkitAudioContext)();
+ const source = audioContext.value.createMediaStreamSource(stream);
+ analyser.value = audioContext.value.createAnalyser();
+ analyser.value.fftSize = 256;
+ source.connect(analyser.value);
+
+ } else if (mode === 'both') {
+ const micStream = await navigator.mediaDevices.getUserMedia({
+ audio: {
+ echoCancellation: true,
+ noiseSuppression: true,
+ sampleRate: 48000
+ }
+ });
+
+ const displayStream = await navigator.mediaDevices.getDisplayMedia({
+ video: true,
+ audio: {
+ echoCancellation: false,
+ noiseSuppression: false,
+ autoGainControl: false
+ }
+ });
+
+ const systemAudioTrack = displayStream.getAudioTracks()[0];
+ if (!systemAudioTrack) {
+ micStream.getTracks().forEach(track => track.stop());
+ displayStream.getTracks().forEach(track => track.stop());
+ throw new Error('No system audio track available.');
+ }
+
+ // Stop video tracks
+ displayStream.getVideoTracks().forEach(track => track.stop());
+
+ // Create audio context and combine streams
+ audioContext.value = new (window.AudioContext || window.webkitAudioContext)();
+ const destination = audioContext.value.createMediaStreamDestination();
+
+ const micSource = audioContext.value.createMediaStreamSource(micStream);
+ const systemSource = audioContext.value.createMediaStreamSource(new MediaStream([systemAudioTrack]));
+
+ // Create analysers for each source
+ micAnalyser.value = audioContext.value.createAnalyser();
+ micAnalyser.value.fftSize = 256;
+ systemAnalyser.value = audioContext.value.createAnalyser();
+ systemAnalyser.value.fftSize = 256;
+
+ micSource.connect(micAnalyser.value);
+ micSource.connect(destination);
+ systemSource.connect(systemAnalyser.value);
+ systemSource.connect(destination);
+
+ combinedStream = destination.stream;
+ activeStreams.value = [micStream, displayStream];
+ stream = combinedStream;
+ }
+
+ // Determine best mime type
+ const mimeType = MediaRecorder.isTypeSupported('audio/webm;codecs=opus')
+ ? 'audio/webm;codecs=opus'
+ : 'audio/webm';
+
+ const recorder = new MediaRecorder(stream, { mimeType });
+
+ recorder.ondataavailable = (event) => {
+ if (event.data.size > 0) {
+ audioChunks.value.push(event.data);
+ }
+ };
+
+ recorder.onstop = () => {
+ const blob = new Blob(audioChunks.value, { type: mimeType });
+ audioBlobURL.value = URL.createObjectURL(blob);
+ stopSizeMonitoring();
+ };
+
+ mediaRecorder.value = recorder;
+ recorder.start(1000);
+ isRecording.value = true;
+
+ // Start timer
+ recordingInterval.value = setInterval(() => {
+ recordingTime.value++;
+ }, 1000);
+
+ // Start size monitoring
+ startSizeMonitoring();
+
+ // Acquire wake lock
+ await acquireWakeLock();
+
+ // Show notification
+ await showRecordingNotification();
+
+ // Start visualizers
+ drawVisualizers();
+
+ // Notify service worker
+ if ('serviceWorker' in navigator && navigator.serviceWorker.controller) {
+ navigator.serviceWorker.controller.postMessage({
+ type: 'RECORDING_STATE',
+ isRecording: true
+ });
+ }
+
+ // Switch to recording view
+ currentView.value = 'recording';
+
+ } catch (error) {
+ console.error('Recording error:', error);
+ setGlobalError(`Failed to start recording: ${error.message}`);
+
+ // Clean up any started streams
+ if (activeStreams.value.length > 0) {
+ activeStreams.value.forEach(stream => {
+ stream.getTracks().forEach(track => track.stop());
+ });
+ activeStreams.value = [];
+ }
+ }
+ };
+
+ // Stop recording
+ const stopRecording = async () => {
+ if (mediaRecorder.value && isRecording.value) {
+ mediaRecorder.value.stop();
+ isRecording.value = false;
+
+ // Clear the recording timer
+ if (recordingInterval.value) {
+ clearInterval(recordingInterval.value);
+ recordingInterval.value = null;
+ }
+
+ stopSizeMonitoring();
+ cancelAnimationFrame(animationFrameId.value);
+ animationFrameId.value = null;
+
+ // Stop all active media streams (mic, screen share, etc.)
+ if (activeStreams.value.length > 0) {
+ activeStreams.value.forEach(stream => {
+ stream.getTracks().forEach(track => track.stop());
+ });
+ activeStreams.value = [];
+ }
+
+ // Release wake lock
+ await releaseWakeLock();
+
+ // Hide recording notification
+ await hideRecordingNotification();
+
+ // Notify service worker
+ if ('serviceWorker' in navigator && navigator.serviceWorker.controller) {
+ navigator.serviceWorker.controller.postMessage({
+ type: 'RECORDING_STATE',
+ isRecording: false,
+ duration: recordingTime.value
+ });
+ }
+ }
+ };
+
+ // Upload recorded audio
+ const uploadRecordedAudio = () => {
+ if (!audioBlobURL.value) {
+ setGlobalError("No recorded audio to upload.");
+ return;
+ }
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
+ const recordedFile = new File(audioChunks.value, `recording-${timestamp}.webm`, { type: 'audio/webm' });
+
+ // Get selected tags as objects and create a DEEP copy to prevent reactivity issues
+ const selectedTagsTemp = selectedTagIds.value.map(tagId => {
+ const tag = state.availableTags.value.find(t => t.id == tagId);
+ return tag || null;
+ }).filter(Boolean);
+
+ // Deep clone to completely break reactivity chain - JSON parse/stringify removes all proxies
+ const selectedTags = JSON.parse(JSON.stringify(selectedTagsTemp));
+
+ // Add to upload queue
+ uploadQueue.value.push({
+ file: recordedFile,
+ notes: recordingNotes.value,
+ tags: selectedTags, // Completely non-reactive deep copy
+ asrOptions: {
+ language: asrLanguage.value,
+ min_speakers: asrMinSpeakers.value,
+ max_speakers: asrMaxSpeakers.value
+ },
+ status: 'queued',
+ recordingId: null,
+ clientId: `client-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`,
+ error: null,
+ willAutoSummarize: false // Server will tell us via SUMMARIZING status
+ });
+
+ discardRecording();
+
+ // Return to upload view (main UI)
+ currentView.value = 'upload';
+
+ // Start upload immediately
+ progressPopupMinimized.value = false;
+ progressPopupClosed.value = false;
+
+ if (startUploadQueue) {
+ startUploadQueue();
+ }
+ };
+
+ // Discard recording
+ const discardRecording = async () => {
+ if (audioBlobURL.value) {
+ URL.revokeObjectURL(audioBlobURL.value);
+ }
+ audioBlobURL.value = null;
+ audioChunks.value = [];
+ isRecording.value = false;
+ recordingTime.value = 0;
+ if (recordingInterval.value) clearInterval(recordingInterval.value);
+ recordingNotes.value = '';
+ selectedTagIds.value = [];
+ asrLanguage.value = '';
+ asrMinSpeakers.value = '';
+ asrMaxSpeakers.value = '';
+
+ await releaseWakeLock();
+ await hideRecordingNotification();
+ };
+
+ // Draw single visualizer
+ const drawSingleVisualizer = (analyserNode, canvasElement) => {
+ if (!analyserNode || !canvasElement) return;
+
+ const bufferLength = analyserNode.frequencyBinCount;
+ const dataArray = new Uint8Array(bufferLength);
+ analyserNode.getByteFrequencyData(dataArray);
+
+ const canvasCtx = canvasElement.getContext('2d');
+ const WIDTH = canvasElement.width;
+ const HEIGHT = canvasElement.height;
+
+ canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
+
+ const barWidth = (WIDTH / bufferLength) * 1.5;
+ let barHeight;
+ let x = 0;
+
+ const buttonColor = getComputedStyle(document.documentElement).getPropertyValue('--bg-button').trim();
+ const buttonHoverColor = getComputedStyle(document.documentElement).getPropertyValue('--bg-button-hover').trim();
+
+ const gradient = canvasCtx.createLinearGradient(0, 0, 0, HEIGHT);
+ if (isDarkMode.value) {
+ gradient.addColorStop(0, buttonColor);
+ gradient.addColorStop(0.6, buttonHoverColor);
+ gradient.addColorStop(1, 'rgba(0, 0, 0, 0.2)');
+ } else {
+ gradient.addColorStop(0, buttonColor);
+ gradient.addColorStop(0.5, buttonHoverColor);
+ gradient.addColorStop(1, 'rgba(0, 0, 0, 0.1)');
+ }
+
+ for (let i = 0; i < bufferLength; i++) {
+ barHeight = dataArray[i] / 2.5;
+ canvasCtx.fillStyle = gradient;
+ canvasCtx.fillRect(x, HEIGHT - barHeight, barWidth, barHeight);
+ x += barWidth + 2;
+ }
+ };
+
+ // Draw visualizers
+ const drawVisualizers = () => {
+ if (!isRecording.value) {
+ if (animationFrameId.value) {
+ cancelAnimationFrame(animationFrameId.value);
+ animationFrameId.value = null;
+ }
+ return;
+ }
+
+ animationFrameId.value = requestAnimationFrame(drawVisualizers);
+
+ if (recordingMode.value === 'both') {
+ drawSingleVisualizer(micAnalyser.value, micVisualizer.value);
+ drawSingleVisualizer(systemAnalyser.value, systemVisualizer.value);
+ } else {
+ drawSingleVisualizer(analyser.value, visualizer.value);
+ }
+ };
+
+ // Update file size estimate
+ const updateFileSizeEstimate = () => {
+ if (!isRecording.value || !audioChunks.value.length) return;
+
+ const totalSize = audioChunks.value.reduce((sum, chunk) => sum + chunk.size, 0);
+ estimatedFileSize.value = totalSize;
+
+ if (recordingTime.value > 0) {
+ actualBitrate.value = (totalSize * 8) / recordingTime.value;
+ }
+
+ // Check for size warning
+ const sizeMB = totalSize / (1024 * 1024);
+ const warningThresholdMB = maxRecordingMB.value * 0.8;
+
+ if (sizeMB > warningThresholdMB && !fileSizeWarningShown.value) {
+ fileSizeWarningShown.value = true;
+ showToast(
+ `Recording size is ${formatFileSize(totalSize)}. Consider stopping soon.`,
+ 'fa-exclamation-triangle',
+ 5000
+ );
+ }
+
+ // Auto-stop if max size reached
+ if (sizeMB > maxRecordingMB.value) {
+ stopRecording();
+ showToast(
+ `Recording automatically stopped at ${formatFileSize(totalSize)}`,
+ 'fa-stop-circle',
+ 7000
+ );
+ }
+ };
+
+ // Start size monitoring
+ const startSizeMonitoring = () => {
+ if (sizeCheckInterval.value) {
+ clearInterval(sizeCheckInterval.value);
+ }
+ sizeCheckInterval.value = setInterval(updateFileSizeEstimate, 2000);
+ };
+
+ // Stop size monitoring
+ const stopSizeMonitoring = () => {
+ if (sizeCheckInterval.value) {
+ clearInterval(sizeCheckInterval.value);
+ sizeCheckInterval.value = null;
+ }
+ };
+
+ // Check if there's an unsaved recording
+ const hasUnsavedRecording = () => {
+ return isRecording.value || audioBlobURL.value;
+ };
+
+ // Initialize audio capabilities
+ const initializeAudio = async () => {
+ await detectSystemAudioCapabilities();
+ };
+
+ return {
+ startRecording,
+ stopRecording,
+ discardRecording,
+ uploadRecordedAudio,
+ acceptRecordingDisclaimer,
+ cancelRecordingDisclaimer,
+ updateFileSizeEstimate,
+ startSizeMonitoring,
+ stopSizeMonitoring,
+ drawVisualizers,
+ drawSingleVisualizer,
+ handleVisibilityChange,
+ hasUnsavedRecording,
+ acquireWakeLock,
+ releaseWakeLock,
+ detectSystemAudioCapabilities,
+ initializeAudio
+ };
+}
diff --git a/static/js/modules/composables/chat.js b/static/js/modules/composables/chat.js
new file mode 100644
index 00000000..33bef7a2
--- /dev/null
+++ b/static/js/modules/composables/chat.js
@@ -0,0 +1,337 @@
+/**
+ * Chat composable
+ * Handles AI chat functionality with streaming responses
+ */
+
+export function useChat(state, utils) {
+ const {
+ showChat, isChatMaximized, chatMessages, chatInput,
+ isChatLoading, chatMessagesRef, selectedRecording, csrfToken
+ } = state;
+
+ const { showToast, setGlobalError } = utils;
+
+ // Helper function to check if chat is scrolled to bottom (within bottom 5%)
+ const isChatScrolledToBottom = () => {
+ if (!chatMessagesRef.value) return true;
+ const { scrollTop, scrollHeight, clientHeight } = chatMessagesRef.value;
+ const scrollableHeight = scrollHeight - clientHeight;
+ if (scrollableHeight <= 0) return true;
+ const scrollPercentage = scrollTop / scrollableHeight;
+ return scrollPercentage >= 0.95;
+ };
+
+ // Helper function to scroll chat to bottom
+ const scrollChatToBottom = () => {
+ if (chatMessagesRef.value) {
+ requestAnimationFrame(() => {
+ if (chatMessagesRef.value) {
+ chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight;
+ }
+ });
+ }
+ };
+
+ const toggleChatMaximize = () => {
+ if (isChatMaximized.value) {
+ isChatMaximized.value = false;
+ } else {
+ isChatMaximized.value = true;
+ if (!showChat.value) {
+ showChat.value = true;
+ }
+ }
+ };
+
+ const sendChatMessage = async () => {
+ if (!chatInput.value.trim() || isChatLoading.value || !selectedRecording.value || selectedRecording.value.status !== 'COMPLETED') {
+ return;
+ }
+
+ const message = chatInput.value.trim();
+
+ if (!Array.isArray(chatMessages.value)) {
+ chatMessages.value = [];
+ }
+
+ chatMessages.value.push({ role: 'user', content: message });
+ chatInput.value = '';
+ isChatLoading.value = true;
+
+ await Vue.nextTick();
+ scrollChatToBottom();
+
+ let assistantMessage = null;
+
+ try {
+ const messageHistory = chatMessages.value
+ .slice(0, -1)
+ .map(msg => ({ role: msg.role, content: msg.content }));
+
+ const response = await fetch('/chat', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ recording_id: selectedRecording.value.id,
+ message: message,
+ message_history: messageHistory
+ })
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(errorData.error || 'Failed to get chat response');
+ }
+
+ const reader = response.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = '';
+
+ const processStream = async () => {
+ let isFirstChunk = true;
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+
+ buffer += decoder.decode(value, { stream: true });
+ const lines = buffer.split('\n');
+ buffer = lines.pop();
+
+ for (const line of lines) {
+ if (line.startsWith('data: ')) {
+ const jsonStr = line.substring(6);
+ if (jsonStr) {
+ try {
+ const data = JSON.parse(jsonStr);
+ if (data.thinking) {
+ const shouldScroll = isChatScrolledToBottom();
+
+ if (isFirstChunk) {
+ isChatLoading.value = false;
+ assistantMessage = Vue.reactive({
+ role: 'assistant',
+ content: '',
+ html: '',
+ thinking: data.thinking,
+ thinkingExpanded: false
+ });
+ chatMessages.value.push(assistantMessage);
+ isFirstChunk = false;
+ } else if (assistantMessage) {
+ if (assistantMessage.thinking) {
+ assistantMessage.thinking += '\n\n' + data.thinking;
+ } else {
+ assistantMessage.thinking = data.thinking;
+ }
+ }
+
+ if (shouldScroll) {
+ await Vue.nextTick();
+ scrollChatToBottom();
+ }
+ }
+ if (data.delta) {
+ const shouldScroll = isChatScrolledToBottom();
+
+ if (isFirstChunk) {
+ isChatLoading.value = false;
+ assistantMessage = Vue.reactive({
+ role: 'assistant',
+ content: '',
+ html: '',
+ thinking: '',
+ thinkingExpanded: false
+ });
+ chatMessages.value.push(assistantMessage);
+ isFirstChunk = false;
+ }
+
+ assistantMessage.content += data.delta;
+ assistantMessage.html = marked.parse(assistantMessage.content);
+
+ if (shouldScroll) {
+ await Vue.nextTick();
+ scrollChatToBottom();
+ }
+ }
+ if (data.end_of_stream) {
+ return;
+ }
+ if (data.error) {
+ throw new Error(data.error);
+ }
+ } catch (e) {
+ console.error('Error parsing stream data:', e);
+ }
+ }
+ }
+ }
+ }
+ };
+
+ await processStream();
+
+ } catch (error) {
+ console.error('Chat Error:', error);
+ if (assistantMessage) {
+ assistantMessage.content = `Error: ${error.message}`;
+ assistantMessage.html = `<span class="text-red-500">Error: ${error.message}</span>`;
+ } else {
+ chatMessages.value.push({
+ role: 'assistant',
+ content: `Error: ${error.message}`,
+ html: `<span class="text-red-500">Error: ${error.message}</span>`
+ });
+ }
+ } finally {
+ isChatLoading.value = false;
+ await Vue.nextTick();
+ if (isChatScrolledToBottom()) {
+ scrollChatToBottom();
+ }
+ }
+ };
+
+ const handleChatKeydown = (event) => {
+ if (event.key === 'Enter') {
+ if (event.ctrlKey || event.shiftKey) {
+ return;
+ } else {
+ event.preventDefault();
+ sendChatMessage();
+ }
+ }
+ };
+
+ const clearChat = () => {
+ if (chatMessages.value.length > 0) {
+ chatMessages.value = [];
+ showToast('Chat cleared', 'fa-broom');
+ }
+ };
+
+ const downloadChat = async () => {
+ if (!selectedRecording.value || chatMessages.value.length === 0) {
+ showToast('No chat messages to download.', 'fa-exclamation-circle');
+ return;
+ }
+
+ try {
+ const csrfTokenValue = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await fetch(`/recording/${selectedRecording.value.id}/download/chat`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfTokenValue
+ },
+ body: JSON.stringify({
+ messages: chatMessages.value
+ })
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ showToast(error.error || 'Failed to download chat', 'fa-exclamation-circle');
+ return;
+ }
+
+ const blob = await response.blob();
+ const url = window.URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.style.display = 'none';
+ a.href = url;
+
+ const contentDisposition = response.headers.get('Content-Disposition');
+ let filename = 'chat.docx';
+ if (contentDisposition) {
+ const utf8Match = /filename\*=utf-8''(.+)/.exec(contentDisposition);
+ if (utf8Match) {
+ filename = decodeURIComponent(utf8Match[1]);
+ } else {
+ const regularMatch = /filename="(.+)"/.exec(contentDisposition);
+ if (regularMatch) {
+ filename = regularMatch[1];
+ }
+ }
+ }
+ a.download = filename;
+
+ document.body.appendChild(a);
+ a.click();
+ window.URL.revokeObjectURL(url);
+ document.body.removeChild(a);
+
+ showToast('Chat downloaded successfully!');
+ } catch (error) {
+ console.error('Download failed:', error);
+ showToast('Failed to download chat', 'fa-exclamation-circle');
+ }
+ };
+
+ const copyMessage = (text, event) => {
+ const button = event.currentTarget;
+
+ if (navigator.clipboard && window.isSecureContext) {
+ navigator.clipboard.writeText(text)
+ .then(() => {
+ showToast('Copied to clipboard!');
+ animateCopyButton(button);
+ })
+ .catch(err => {
+ console.error('Copy failed:', err);
+ showToast('Failed to copy: ' + err.message, 'fa-exclamation-circle');
+ fallbackCopyTextToClipboard(text, button);
+ });
+ } else {
+ fallbackCopyTextToClipboard(text, button);
+ }
+ };
+
+ const animateCopyButton = (button) => {
+ button.classList.add('copy-success');
+ const originalContent = button.innerHTML;
+ button.innerHTML = '<i class="fas fa-check"></i>';
+ setTimeout(() => {
+ button.classList.remove('copy-success');
+ button.innerHTML = originalContent;
+ }, 1500);
+ };
+
+ const fallbackCopyTextToClipboard = (text, button = null) => {
+ try {
+ const textArea = document.createElement("textarea");
+ textArea.value = text;
+ textArea.style.position = "fixed";
+ textArea.style.left = "-999999px";
+ textArea.style.top = "-999999px";
+ document.body.appendChild(textArea);
+ textArea.focus();
+ textArea.select();
+ const successful = document.execCommand('copy');
+ document.body.removeChild(textArea);
+
+ if (successful) {
+ showToast('Copied to clipboard!');
+ if (button) animateCopyButton(button);
+ } else {
+ showToast('Copy failed. Your browser may not support this feature.', 'fa-exclamation-circle');
+ }
+ } catch (err) {
+ console.error('Fallback copy failed:', err);
+ showToast('Unable to copy: ' + err.message, 'fa-exclamation-circle');
+ }
+ };
+
+ return {
+ isChatScrolledToBottom,
+ scrollChatToBottom,
+ toggleChatMaximize,
+ sendChatMessage,
+ handleChatKeydown,
+ clearChat,
+ downloadChat,
+ copyMessage,
+ animateCopyButton,
+ fallbackCopyTextToClipboard
+ };
+}
diff --git a/static/js/modules/composables/index.js b/static/js/modules/composables/index.js
new file mode 100644
index 00000000..c7249ff5
--- /dev/null
+++ b/static/js/modules/composables/index.js
@@ -0,0 +1,26 @@
+/**
+ * Composables module exports
+ *
+ * Each composable encapsulates related functionality:
+ * - recordings: Loading, selecting, filtering recordings
+ * - upload: File upload queue management
+ * - audio: Microphone/system audio recording
+ * - ui: Dark mode, color schemes, sidebar
+ * - transcription: Transcription editing (ASR editor, text editor)
+ * - speakers: Speaker identification and management
+ * - reprocess: Reprocessing transcription/summary
+ * - sharing: Public/internal sharing
+ * - modals: Modal dialog management
+ * - chat: AI chat functionality
+ */
+
+export { useRecordings } from './recordings.js';
+export { useUpload } from './upload.js';
+export { useAudio } from './audio.js';
+export { useUI } from './ui.js';
+export { useModals } from './modals.js';
+export { useSharing } from './sharing.js';
+export { useReprocess } from './reprocess.js';
+export { useTranscription } from './transcription.js';
+export { useSpeakers } from './speakers.js';
+export { useChat } from './chat.js';
diff --git a/static/js/modules/composables/modals.js b/static/js/modules/composables/modals.js
new file mode 100644
index 00000000..9f8b0d4f
--- /dev/null
+++ b/static/js/modules/composables/modals.js
@@ -0,0 +1,330 @@
+/**
+ * Modal management composable
+ * Handles opening, closing, and saving modal dialogs
+ */
+
+export function useModals(state, utils) {
+ const {
+ showEditModal, showDeleteModal, showEditTagsModal,
+ showReprocessModal, showResetModal, showShareModal,
+ showSharesListModal, showTextEditorModal, showAsrEditorModal,
+ showEditSpeakersModal, showAddSpeakerModal, showEditTextModal,
+ showShareDeleteModal, showUnifiedShareModal, showColorSchemeModal,
+ showSystemAudioHelpModal, editingRecording, recordingToDelete, recordingToReset,
+ selectedRecording, recordings, selectedNewTagId, tagSearchFilter,
+ availableTags, currentView, totalRecordings, toasts
+ } = state;
+
+ const { showToast, setGlobalError } = utils;
+
+ // =========================================
+ // Edit Recording Modal
+ // =========================================
+
+ const openEditModal = (recording) => {
+ editingRecording.value = { ...recording };
+ showEditModal.value = true;
+ };
+
+ const cancelEdit = () => {
+ showEditModal.value = false;
+ editingRecording.value = null;
+ };
+
+ const saveEdit = async () => {
+ if (!editingRecording.value) return;
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await fetch(`/api/recordings/${editingRecording.value.id}`, {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({
+ title: editingRecording.value.title,
+ participants: editingRecording.value.participants,
+ meeting_date: editingRecording.value.meeting_date,
+ notes: editingRecording.value.notes
+ })
+ });
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to save changes');
+
+ // Update local data
+ const index = recordings.value.findIndex(r => r.id === editingRecording.value.id);
+ if (index !== -1) {
+ recordings.value[index] = { ...recordings.value[index], ...editingRecording.value };
+ }
+ if (selectedRecording.value && selectedRecording.value.id === editingRecording.value.id) {
+ selectedRecording.value = { ...selectedRecording.value, ...editingRecording.value };
+ }
+
+ showToast('Recording updated!', 'fa-check-circle');
+ showEditModal.value = false;
+ editingRecording.value = null;
+ } catch (error) {
+ setGlobalError(`Failed to save changes: ${error.message}`);
+ }
+ };
+
+ // =========================================
+ // Delete Recording Modal
+ // =========================================
+
+ const confirmDelete = (recording) => {
+ recordingToDelete.value = recording;
+ showDeleteModal.value = true;
+ };
+
+ const cancelDelete = () => {
+ showDeleteModal.value = false;
+ recordingToDelete.value = null;
+ };
+
+ const deleteRecording = async () => {
+ if (!recordingToDelete.value) return;
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await fetch(`/recording/${recordingToDelete.value.id}`, {
+ method: 'DELETE',
+ headers: { 'X-CSRFToken': csrfToken }
+ });
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to delete recording');
+
+ recordings.value = recordings.value.filter(r => r.id !== recordingToDelete.value.id);
+ totalRecordings.value--;
+
+ if (selectedRecording.value?.id === recordingToDelete.value.id) {
+ selectedRecording.value = null;
+ currentView.value = 'upload';
+ }
+
+ showToast('Recording deleted.', 'fa-trash');
+ showDeleteModal.value = false;
+ recordingToDelete.value = null;
+ } catch (error) {
+ setGlobalError(`Failed to delete recording: ${error.message}`);
+ }
+ };
+
+ // =========================================
+ // Archive Recording
+ // =========================================
+
+ const archiveRecording = async (recording) => {
+ if (!recording) return;
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await fetch(`/api/recordings/${recording.id}/archive`, {
+ method: 'POST',
+ headers: { 'X-CSRFToken': csrfToken }
+ });
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to archive recording');
+
+ recording.is_archived = true;
+ recording.audio_deleted_at = data.audio_deleted_at;
+
+ // Update in recordings list
+ const index = recordings.value.findIndex(r => r.id === recording.id);
+ if (index !== -1) {
+ recordings.value[index].is_archived = true;
+ recordings.value[index].audio_deleted_at = data.audio_deleted_at;
+ }
+
+ showToast('Recording archived (audio deleted)', 'fa-archive');
+ } catch (error) {
+ setGlobalError(`Failed to archive recording: ${error.message}`);
+ }
+ };
+
+ // =========================================
+ // Edit Tags Modal
+ // =========================================
+
+ const openEditTagsModal = () => {
+ selectedNewTagId.value = '';
+ tagSearchFilter.value = '';
+ showEditTagsModal.value = true;
+ };
+
+ const closeEditTagsModal = () => {
+ showEditTagsModal.value = false;
+ };
+
+ const addTagToRecording = async (tagId) => {
+ if (!selectedRecording.value || !tagId) return;
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await fetch(`/api/recordings/${selectedRecording.value.id}/tags`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({ tag_id: tagId })
+ });
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to add tag');
+
+ // Find the tag object
+ const tag = availableTags.value.find(t => t.id === tagId);
+ if (tag) {
+ if (!selectedRecording.value.tags) {
+ selectedRecording.value.tags = [];
+ }
+ selectedRecording.value.tags.push(tag);
+ }
+
+ // Update in recordings list
+ const index = recordings.value.findIndex(r => r.id === selectedRecording.value.id);
+ if (index !== -1 && tag) {
+ if (!recordings.value[index].tags) {
+ recordings.value[index].tags = [];
+ }
+ recordings.value[index].tags.push(tag);
+ }
+
+ selectedNewTagId.value = '';
+ showToast('Tag added!', 'fa-tag');
+ } catch (error) {
+ setGlobalError(`Failed to add tag: ${error.message}`);
+ }
+ };
+
+ const removeTagFromRecording = async (tagId) => {
+ if (!selectedRecording.value || !tagId) return;
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await fetch(`/api/recordings/${selectedRecording.value.id}/tags/${tagId}`, {
+ method: 'DELETE',
+ headers: { 'X-CSRFToken': csrfToken }
+ });
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to remove tag');
+
+ // Remove from selected recording
+ if (selectedRecording.value.tags) {
+ selectedRecording.value.tags = selectedRecording.value.tags.filter(t => t.id !== tagId);
+ }
+
+ // Update in recordings list
+ const index = recordings.value.findIndex(r => r.id === selectedRecording.value.id);
+ if (index !== -1 && recordings.value[index].tags) {
+ recordings.value[index].tags = recordings.value[index].tags.filter(t => t.id !== tagId);
+ }
+
+ showToast('Tag removed!', 'fa-tag');
+ } catch (error) {
+ setGlobalError(`Failed to remove tag: ${error.message}`);
+ }
+ };
+
+ // =========================================
+ // Reset Modal
+ // =========================================
+
+ const openResetModal = (recording) => {
+ recordingToReset.value = recording;
+ showResetModal.value = true;
+ };
+
+ const cancelReset = () => {
+ showResetModal.value = false;
+ recordingToReset.value = null;
+ };
+
+ const resetRecording = async () => {
+ if (!recordingToReset.value) return;
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await fetch(`/recording/${recordingToReset.value.id}/reset_status`, {
+ method: 'POST',
+ headers: { 'X-CSRFToken': csrfToken }
+ });
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to reset recording');
+
+ // Update recording status
+ const index = recordings.value.findIndex(r => r.id === recordingToReset.value.id);
+ if (index !== -1) {
+ recordings.value[index].status = 'PENDING';
+ recordings.value[index].transcription = '';
+ recordings.value[index].summary = '';
+ }
+
+ if (selectedRecording.value?.id === recordingToReset.value.id) {
+ selectedRecording.value.status = 'PENDING';
+ selectedRecording.value.transcription = '';
+ selectedRecording.value.summary = '';
+ }
+
+ showToast('Recording reset for reprocessing.', 'fa-redo');
+ showResetModal.value = false;
+ recordingToReset.value = null;
+ } catch (error) {
+ setGlobalError(`Failed to reset recording: ${error.message}`);
+ }
+ };
+
+ // =========================================
+ // System Audio Help Modal
+ // =========================================
+
+ const openSystemAudioHelpModal = () => {
+ showSystemAudioHelpModal.value = true;
+ };
+
+ const closeSystemAudioHelpModal = () => {
+ showSystemAudioHelpModal.value = false;
+ };
+
+ // =========================================
+ // Toast Management
+ // =========================================
+
+ const dismissToast = (id) => {
+ toasts.value = toasts.value.filter(t => t.id !== id);
+ };
+
+ // Aliases for template compatibility
+ const editRecording = openEditModal;
+ const editRecordingTags = openEditTagsModal;
+
+ return {
+ // Edit modal
+ openEditModal,
+ editRecording,
+ cancelEdit,
+ saveEdit,
+
+ // Delete modal
+ confirmDelete,
+ cancelDelete,
+ deleteRecording,
+
+ // Archive
+ archiveRecording,
+
+ // Tags modal
+ openEditTagsModal,
+ editRecordingTags,
+ closeEditTagsModal,
+ addTagToRecording,
+ removeTagFromRecording,
+
+ // Reset modal
+ openResetModal,
+ cancelReset,
+ resetRecording,
+
+ // System audio help
+ openSystemAudioHelpModal,
+ closeSystemAudioHelpModal,
+
+ // Toast
+ dismissToast
+ };
+}
diff --git a/static/js/modules/composables/recordings.js b/static/js/modules/composables/recordings.js
new file mode 100644
index 00000000..75efc197
--- /dev/null
+++ b/static/js/modules/composables/recordings.js
@@ -0,0 +1,391 @@
+/**
+ * Recording management composable
+ * Handles loading, selecting, filtering, and managing recordings
+ */
+
+export function useRecordings(state, utils, reprocessComposable) {
+ const {
+ recordings, selectedRecording, isLoadingRecordings, isLoadingMore,
+ currentPage, perPage, totalRecordings, totalPages, hasNextPage, hasPrevPage,
+ showSharedWithMe, showArchivedRecordings, searchQuery, searchDebounceTimer,
+ filterTags, filterDatePreset, filterDateRange, filterTextQuery,
+ availableTags, selectedTagIds, uploadLanguage, uploadMinSpeakers, uploadMaxSpeakers,
+ useAsrEndpoint, globalError, uploadQueue, isProcessingActive, currentView,
+ isMobileScreen, isSidebarCollapsed, isRecording, audioBlobURL
+ } = state;
+
+ const { setGlobalError, showToast } = utils;
+
+ // Load recordings from API
+ const loadRecordings = async (page = 1, append = false, searchQueryParam = '') => {
+ globalError.value = null;
+ if (!append) {
+ isLoadingRecordings.value = true;
+ } else {
+ isLoadingMore.value = true;
+ }
+
+ try {
+ let endpoint = '/api/recordings';
+ if (showArchivedRecordings.value) {
+ endpoint = '/api/recordings/archived';
+ } else if (showSharedWithMe.value) {
+ endpoint = '/api/recordings/shared-with-me';
+ }
+
+ const params = new URLSearchParams({
+ page: page.toString(),
+ per_page: perPage.value.toString()
+ });
+
+ if (searchQueryParam.trim()) {
+ params.set('q', searchQueryParam.trim());
+ }
+
+ const response = await fetch(`${endpoint}?${params}`);
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to load recordings');
+
+ const recordingsList = (showArchivedRecordings.value || showSharedWithMe.value) ? data : data.recordings;
+ const pagination = (showArchivedRecordings.value || showSharedWithMe.value) ? null : data.pagination;
+
+ if (!Array.isArray(recordingsList)) {
+ console.error('Unexpected response format:', data);
+ throw new Error('Invalid response format from server');
+ }
+
+ if (pagination) {
+ currentPage.value = pagination.page;
+ totalRecordings.value = pagination.total;
+ totalPages.value = pagination.total_pages;
+ hasNextPage.value = pagination.has_next;
+ hasPrevPage.value = pagination.has_prev;
+ } else {
+ currentPage.value = 1;
+ totalRecordings.value = recordingsList.length;
+ totalPages.value = 1;
+ hasNextPage.value = false;
+ hasPrevPage.value = false;
+ }
+
+ if (append && !showArchivedRecordings.value) {
+ recordings.value = [...recordings.value, ...recordingsList];
+ } else {
+ recordings.value = recordingsList;
+ const lastRecordingId = localStorage.getItem('lastSelectedRecordingId');
+ if (lastRecordingId && recordingsList.length > 0) {
+ const recordingToSelect = recordingsList.find(r => r.id == lastRecordingId);
+ if (recordingToSelect) {
+ selectRecording(recordingToSelect);
+ }
+ }
+ }
+
+ // Handle incomplete recordings
+ const incompleteRecordings = recordingsList.filter(r =>
+ ['PENDING', 'PROCESSING', 'SUMMARIZING'].includes(r.status)
+ );
+ if (incompleteRecordings.length > 0 && !isProcessingActive.value) {
+ for (const recording of incompleteRecordings) {
+ let queueItem = uploadQueue.value.find(item => item.recordingId === recording.id);
+ if (!queueItem) {
+ queueItem = {
+ file: { name: recording.title || `Recording ${recording.id}`, size: recording.file_size },
+ status: 'queued',
+ recordingId: recording.id,
+ clientId: `reload-${recording.id}`,
+ error: null
+ };
+ uploadQueue.value.unshift(queueItem);
+ }
+ }
+ }
+
+ } catch (error) {
+ console.error('Load Recordings Error:', error);
+ setGlobalError(`Failed to load recordings: ${error.message}`);
+ if (!append) {
+ recordings.value = [];
+ }
+ } finally {
+ isLoadingRecordings.value = false;
+ isLoadingMore.value = false;
+ }
+ };
+
+ const loadMoreRecordings = async () => {
+ if (!hasNextPage.value || isLoadingMore.value) return;
+ await loadRecordings(currentPage.value + 1, true, searchQuery.value);
+ };
+
+ const performSearch = async (query = '') => {
+ currentPage.value = 1;
+ await loadRecordings(1, false, query);
+ };
+
+ const debouncedSearch = (query) => {
+ if (searchDebounceTimer.value) {
+ clearTimeout(searchDebounceTimer.value);
+ }
+ searchDebounceTimer.value = setTimeout(() => {
+ performSearch(query);
+ }, 300);
+ };
+
+ const loadTags = async () => {
+ try {
+ const response = await fetch('/api/tags');
+ if (response.ok) {
+ availableTags.value = await response.json();
+ } else {
+ availableTags.value = [];
+ }
+ } catch (error) {
+ console.warn('Error loading tags:', error);
+ availableTags.value = [];
+ }
+ };
+
+ const selectRecording = async (recording) => {
+ if (hasUnsavedRecording()) {
+ if (!confirm('You have an unsaved recording. Are you sure you want to leave?')) {
+ return;
+ }
+ }
+
+ selectedRecording.value = recording;
+
+ if (recording && recording.id) {
+ localStorage.setItem('lastSelectedRecordingId', recording.id);
+
+ try {
+ const response = await fetch(`/api/recordings/${recording.id}`);
+ if (response.ok) {
+ const fullRecording = await response.json();
+ selectedRecording.value = fullRecording;
+
+ const index = recordings.value.findIndex(r => r.id === recording.id);
+ if (index !== -1) {
+ recordings.value[index] = fullRecording;
+ }
+
+ // Auto-start polling if recording is still processing or summarizing
+ if (['PROCESSING', 'SUMMARIZING'].includes(fullRecording.status)) {
+ console.log(`[AUTO-POLL] Recording ${fullRecording.id} is in ${fullRecording.status} state, starting auto-polling`);
+ if (reprocessComposable && reprocessComposable.startReprocessingPoll) {
+ reprocessComposable.startReprocessingPoll(fullRecording.id);
+ } else {
+ console.warn('[AUTO-POLL] reprocessComposable.startReprocessingPoll not available');
+ }
+ }
+ }
+ } catch (error) {
+ console.error('Error loading full recording:', error);
+ }
+ }
+
+ if (isMobileScreen.value) {
+ isSidebarCollapsed.value = true;
+ }
+
+ currentView.value = 'detail';
+
+ if (isRecording.value) {
+ // Don't interrupt recording
+ }
+ if (audioBlobURL.value) {
+ // Don't discard recorded audio
+ }
+ };
+
+ const hasUnsavedRecording = () => {
+ return isRecording.value || audioBlobURL.value;
+ };
+
+ const toggleInbox = async (recording) => {
+ if (!recording || !recording.id) return;
+
+ try {
+ const response = await fetch(`/recording/${recording.id}/toggle_inbox`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' }
+ });
+
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to toggle inbox status');
+
+ // Update the recording in the UI
+ recording.is_inbox = data.is_inbox;
+
+ // Update in the recordings list
+ const index = recordings.value.findIndex(r => r.id === recording.id);
+ if (index !== -1) {
+ recordings.value[index].is_inbox = data.is_inbox;
+ }
+
+ showToast(`Recording ${data.is_inbox ? 'moved to inbox' : 'marked as read'}`);
+ } catch (error) {
+ console.error('Toggle Inbox Error:', error);
+ setGlobalError(`Failed to toggle inbox status: ${error.message}`);
+ }
+ };
+
+ const toggleHighlight = async (recording) => {
+ if (!recording || !recording.id) return;
+
+ try {
+ const response = await fetch(`/recording/${recording.id}/toggle_highlight`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' }
+ });
+
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to toggle highlighted status');
+
+ // Update the recording in the UI
+ recording.is_highlighted = data.is_highlighted;
+
+ // Update in the recordings list
+ const index = recordings.value.findIndex(r => r.id === recording.id);
+ if (index !== -1) {
+ recordings.value[index].is_highlighted = data.is_highlighted;
+ }
+
+ showToast(`Recording ${data.is_highlighted ? 'highlighted' : 'unhighlighted'}`);
+ } catch (error) {
+ console.error('Toggle Highlight Error:', error);
+ setGlobalError(`Failed to toggle highlighted status: ${error.message}`);
+ }
+ };
+
+ const getRecordingTags = (recording) => {
+ if (!recording || !recording.tags) return [];
+ return recording.tags || [];
+ };
+
+ const getAvailableTagsForRecording = (recording) => {
+ if (!recording || !availableTags.value) return [];
+ const recordingTagIds = getRecordingTags(recording).map(tag => tag.id);
+ return availableTags.value.filter(tag => !recordingTagIds.includes(tag.id));
+ };
+
+ const filterByTag = (tag) => {
+ filterTags.value = [tag.id];
+ applyAdvancedFilters();
+ };
+
+ const buildSearchQuery = () => {
+ let query = [];
+
+ if (filterTextQuery.value.trim()) {
+ query.push(filterTextQuery.value.trim());
+ }
+
+ if (filterTags.value.length > 0) {
+ const tagNames = filterTags.value.map(tagId => {
+ const tag = availableTags.value.find(t => t.id === tagId);
+ return tag ? `tag:${tag.name.replace(/\s+/g, '_')}` : '';
+ }).filter(Boolean);
+ query.push(...tagNames);
+ }
+
+ if (filterDatePreset.value) {
+ query.push(`date:${filterDatePreset.value}`);
+ } else if (filterDateRange.value.start || filterDateRange.value.end) {
+ if (filterDateRange.value.start) {
+ query.push(`date_from:${filterDateRange.value.start}`);
+ }
+ if (filterDateRange.value.end) {
+ query.push(`date_to:${filterDateRange.value.end}`);
+ }
+ }
+
+ return query.join(' ');
+ };
+
+ const applyAdvancedFilters = () => {
+ searchQuery.value = buildSearchQuery();
+ };
+
+ const clearAllFilters = () => {
+ filterTags.value = [];
+ filterDateRange.value = { start: '', end: '' };
+ filterDatePreset.value = '';
+ filterTextQuery.value = '';
+ searchQuery.value = '';
+ };
+
+ const clearTagFilter = () => {
+ searchQuery.value = '';
+ clearAllFilters();
+ };
+
+ const addTagToSelection = (tagId) => {
+ if (!selectedTagIds.value.includes(tagId)) {
+ selectedTagIds.value.push(tagId);
+ applyTagDefaults();
+ }
+ };
+
+ const removeTagFromSelection = (tagId) => {
+ const index = selectedTagIds.value.indexOf(tagId);
+ if (index > -1) {
+ selectedTagIds.value.splice(index, 1);
+ applyTagDefaults();
+ }
+ };
+
+ const applyTagDefaults = () => {
+ const selectedTags = selectedTagIds.value.map(tagId =>
+ availableTags.value.find(tag => tag.id == tagId)
+ ).filter(Boolean);
+
+ const firstTag = selectedTags[0];
+ if (firstTag && useAsrEndpoint.value) {
+ if (firstTag.default_language) {
+ uploadLanguage.value = firstTag.default_language;
+ }
+ if (firstTag.default_min_speakers) {
+ uploadMinSpeakers.value = firstTag.default_min_speakers;
+ }
+ if (firstTag.default_max_speakers) {
+ uploadMaxSpeakers.value = firstTag.default_max_speakers;
+ }
+ }
+ };
+
+ const pollInboxRecordings = async () => {
+ try {
+ const response = await fetch('/api/recordings/inbox-count');
+ if (response.ok) {
+ const data = await response.json();
+ // Update inbox count in UI if needed
+ }
+ } catch (error) {
+ // Silent fail for polling
+ }
+ };
+
+ return {
+ loadRecordings,
+ loadMoreRecordings,
+ performSearch,
+ debouncedSearch,
+ loadTags,
+ selectRecording,
+ hasUnsavedRecording,
+ toggleInbox,
+ toggleHighlight,
+ getRecordingTags,
+ getAvailableTagsForRecording,
+ filterByTag,
+ buildSearchQuery,
+ applyAdvancedFilters,
+ clearAllFilters,
+ clearTagFilter,
+ addTagToSelection,
+ removeTagFromSelection,
+ applyTagDefaults,
+ pollInboxRecordings
+ };
+}
diff --git a/static/js/modules/composables/reprocess.js b/static/js/modules/composables/reprocess.js
new file mode 100644
index 00000000..28d34291
--- /dev/null
+++ b/static/js/modules/composables/reprocess.js
@@ -0,0 +1,406 @@
+/**
+ * Reprocessing composable
+ * Handles reprocessing transcription and summary
+ */
+
+export function useReprocess(state, utils) {
+ const { nextTick } = Vue;
+
+ const {
+ showReprocessModal, showResetModal, reprocessType,
+ reprocessRecording, recordingToReset, selectedRecording,
+ recordings, asrReprocessOptions, summaryReprocessPromptSource,
+ summaryReprocessSelectedTagId, summaryReprocessCustomPrompt,
+ availableTags, processingProgress, processingMessage,
+ currentlyProcessingFile, uploadQueue
+ } = state;
+
+ const { showToast, setGlobalError } = utils;
+
+ // Store for active polling intervals
+ const reprocessingPolls = new Map();
+
+ // =========================================
+ // Reprocess Modal
+ // =========================================
+
+ const openReprocessModal = (type, recording = null) => {
+ reprocessType.value = type;
+ reprocessRecording.value = recording || selectedRecording.value;
+ showReprocessModal.value = true;
+
+ // Reset options
+ if (type === 'transcription') {
+ asrReprocessOptions.language = '';
+ asrReprocessOptions.min_speakers = '';
+ asrReprocessOptions.max_speakers = '';
+ } else {
+ summaryReprocessPromptSource.value = 'default';
+ summaryReprocessSelectedTagId.value = '';
+ summaryReprocessCustomPrompt.value = '';
+ }
+ };
+
+ const closeReprocessModal = () => {
+ showReprocessModal.value = false;
+ reprocessRecording.value = null;
+ reprocessType.value = null;
+ };
+
+ const confirmReprocess = openReprocessModal;
+ const cancelReprocess = closeReprocessModal;
+
+ // =========================================
+ // Reset Status
+ // =========================================
+
+ const confirmReset = (recording) => {
+ recordingToReset.value = recording;
+ showResetModal.value = true;
+ };
+
+ const cancelReset = () => {
+ showResetModal.value = false;
+ recordingToReset.value = null;
+ };
+
+ const executeReset = async () => {
+ if (!recordingToReset.value) return;
+
+ const recordingId = recordingToReset.value.id;
+
+ // Close the modal first
+ cancelReset();
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await fetch(`/recording/${recordingId}/reset_status`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ }
+ });
+
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to reset recording status');
+
+ // Update recording status in list
+ const index = recordings.value.findIndex(r => r.id === recordingId);
+ if (index !== -1) {
+ recordings.value[index].status = 'FAILED';
+ }
+
+ if (selectedRecording.value?.id === recordingId) {
+ selectedRecording.value.status = 'FAILED';
+ }
+
+ showToast('Recording status reset to FAILED', 'fa-undo');
+ } catch (error) {
+ setGlobalError(`Failed to reset status: ${error.message}`);
+ }
+ };
+
+ const executeReprocess = async () => {
+ if (!reprocessRecording.value || !reprocessType.value) return;
+
+ const recordingId = reprocessRecording.value.id;
+ const type = reprocessType.value;
+
+ closeReprocessModal();
+
+ if (type === 'transcription') {
+ await reprocessTranscription(
+ recordingId,
+ asrReprocessOptions.language,
+ asrReprocessOptions.min_speakers,
+ asrReprocessOptions.max_speakers
+ );
+ } else {
+ await reprocessSummary(
+ recordingId,
+ summaryReprocessPromptSource.value,
+ summaryReprocessSelectedTagId.value,
+ summaryReprocessCustomPrompt.value
+ );
+ }
+ };
+
+ // =========================================
+ // Transcription Reprocessing
+ // =========================================
+
+ const reprocessTranscription = async (recordingId, language, minSpeakers, maxSpeakers) => {
+ if (!recordingId) {
+ setGlobalError('No recording ID provided for reprocessing.');
+ return;
+ }
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const requestBody = {};
+ if (language) requestBody.language = language;
+ if (minSpeakers && minSpeakers !== '') requestBody.min_speakers = parseInt(minSpeakers);
+ if (maxSpeakers && maxSpeakers !== '') requestBody.max_speakers = parseInt(maxSpeakers);
+
+ const response = await fetch(`/recording/${recordingId}/reprocess_transcription`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify(requestBody)
+ });
+
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to start transcription reprocessing');
+
+ // Update recording status in list
+ const index = recordings.value.findIndex(r => r.id === recordingId);
+ if (index !== -1) {
+ recordings.value[index].status = 'PROCESSING';
+ }
+
+ if (selectedRecording.value?.id === recordingId) {
+ selectedRecording.value.status = 'PROCESSING';
+ }
+
+ showToast('Transcription reprocessing started', 'fa-sync-alt');
+
+ // Start polling for progress
+ startReprocessingPoll(recordingId);
+ } catch (error) {
+ setGlobalError(`Failed to start transcription reprocessing: ${error.message}`);
+ }
+ };
+
+ // =========================================
+ // Summary Reprocessing
+ // =========================================
+
+ const reprocessSummary = async (recordingId, promptSource, selectedTagId, customPrompt) => {
+ if (!recordingId) {
+ setGlobalError('No recording ID provided for reprocessing.');
+ return;
+ }
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const requestBody = { reprocess_summary: true };
+
+ if (promptSource === 'tag' && selectedTagId) {
+ const selectedTag = availableTags.value.find(t => t.id == selectedTagId);
+ if (selectedTag && selectedTag.custom_prompt) {
+ requestBody.custom_prompt = selectedTag.custom_prompt;
+ }
+ } else if (promptSource === 'custom' && customPrompt) {
+ requestBody.custom_prompt = customPrompt;
+ }
+
+ const response = await fetch(`/recording/${recordingId}/reprocess_summary`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify(requestBody)
+ });
+
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to start summary reprocessing');
+
+ // Update recording status in list
+ const index = recordings.value.findIndex(r => r.id === recordingId);
+ if (index !== -1) {
+ recordings.value[index].status = 'SUMMARIZING';
+ }
+
+ if (selectedRecording.value?.id === recordingId) {
+ selectedRecording.value.status = 'SUMMARIZING';
+ }
+
+ showToast('Summary reprocessing started', 'fa-sync-alt');
+
+ // Start polling for progress
+ startReprocessingPoll(recordingId);
+ } catch (error) {
+ setGlobalError(`Failed to start summary reprocessing: ${error.message}`);
+ }
+ };
+
+ // =========================================
+ // Generate Summary
+ // =========================================
+
+ const generateSummary = async () => {
+ if (!selectedRecording.value) return;
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await fetch(`/recording/${selectedRecording.value.id}/generate_summary`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ }
+ });
+
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to start summary generation');
+
+ selectedRecording.value.status = 'SUMMARIZING';
+
+ const recordingInList = recordings.value.find(r => r.id === selectedRecording.value.id);
+ if (recordingInList) {
+ recordingInList.status = 'SUMMARIZING';
+ }
+
+ showToast('Summary generation started', 'fa-file-alt');
+
+ // Start polling for progress
+ startReprocessingPoll(selectedRecording.value.id);
+ } catch (error) {
+ setGlobalError(`Failed to generate summary: ${error.message}`);
+ }
+ };
+
+ // =========================================
+ // Progress Polling
+ // =========================================
+
+ const startReprocessingPoll = (recordingId) => {
+ // Stop existing poll if any
+ stopReprocessingPoll(recordingId);
+
+ // Track if we've already fetched full data for SUMMARIZING status
+ let hasFetchedForSummarizing = false;
+
+ const pollInterval = setInterval(async () => {
+ try {
+ // Use lightweight status-only endpoint
+ const response = await fetch(`/recording/${recordingId}/status`);
+ if (!response.ok) throw new Error('Status check failed');
+
+ const statusData = await response.json();
+
+ // Update status in recordings list
+ const index = recordings.value.findIndex(r => r.id === recordingId);
+ console.log(`[REPROCESS] Status update: ${statusData.status} for recording ${recordingId}`);
+
+ if (index !== -1) {
+ // Create new object to ensure Vue reactivity
+ recordings.value[index] = {
+ ...recordings.value[index],
+ status: statusData.status
+ };
+ }
+
+ // Update selectedRecording with new object reference for reactivity
+ if (selectedRecording.value?.id === recordingId) {
+ console.log(`[REPROCESS] Updating selectedRecording status to: ${statusData.status}`);
+ selectedRecording.value = {
+ ...selectedRecording.value,
+ status: statusData.status
+ };
+ }
+
+ // Check if summarization has started (fetch transcript) or processing is complete
+ if (statusData.status === 'SUMMARIZING' || statusData.status === 'COMPLETED') {
+ // Only fetch once when status first becomes SUMMARIZING
+ const shouldFetch = (statusData.status === 'SUMMARIZING' && !hasFetchedForSummarizing) ||
+ statusData.status === 'COMPLETED';
+
+ if (shouldFetch) {
+ const statusLabel = statusData.status === 'SUMMARIZING' ? 'SUMMARIZING (fetching transcript)' : 'COMPLETED';
+ console.log(`[REPROCESS] Status ${statusLabel} detected for recording ${recordingId}`);
+
+ // Mark that we've fetched for SUMMARIZING
+ if (statusData.status === 'SUMMARIZING') {
+ hasFetchedForSummarizing = true;
+ }
+
+ // Only stop polling if COMPLETED, keep polling during SUMMARIZING
+ if (statusData.status === 'COMPLETED') {
+ stopReprocessingPoll(recordingId);
+ }
+
+ // Fetch the full recording with updated data
+ console.log(`[REPROCESS] Fetching full recording data from /api/recordings/${recordingId}`);
+ const fullResponse = await fetch(`/api/recordings/${recordingId}`);
+ console.log(`[REPROCESS] Full recording fetch response OK:`, fullResponse.ok, 'Status:', fullResponse.status);
+
+ if (fullResponse.ok) {
+ const fullData = await fullResponse.json();
+ console.log(`[REPROCESS] Full recording data received. Has transcript:`, !!fullData.transcription, 'Has summary:', !!fullData.summary);
+ console.log(`[REPROCESS] Full data status:`, fullData.status);
+
+ // Update in recordings list first
+ const currentIndex = recordings.value.findIndex(r => r.id === recordingId);
+ if (currentIndex !== -1) {
+ console.log(`[REPROCESS] Updating recording in list at index ${currentIndex}`);
+ recordings.value[currentIndex] = fullData;
+ }
+
+ // Always update selectedRecording if it's the current recording
+ if (selectedRecording.value?.id === recordingId) {
+ console.log(`[REPROCESS] Updating selectedRecording. Has transcript:`, !!fullData.transcription, 'Has summary:', !!fullData.summary);
+ selectedRecording.value = fullData;
+ // Force Vue to detect the change
+ await nextTick();
+ console.log(`[REPROCESS] After nextTick. Has transcript:`, !!selectedRecording.value.transcription, 'Has summary:', !!selectedRecording.value.summary);
+ } else {
+ console.log(`[REPROCESS] NOT updating selectedRecording. Current ID:`, selectedRecording.value?.id, 'Target ID:', recordingId);
+ }
+ } else {
+ console.error(`[REPROCESS] Failed to fetch full recording data. Status: ${fullResponse.status}`);
+ }
+
+ if (statusData.status === 'COMPLETED') {
+ showToast('Processing completed!', 'fa-check-circle');
+ }
+ }
+ } else if (statusData.status === 'FAILED') {
+ stopReprocessingPoll(recordingId);
+ showToast('Processing failed', 'fa-exclamation-circle');
+ }
+ } catch (error) {
+ console.error('Polling error:', error);
+ stopReprocessingPoll(recordingId);
+ }
+ }, 3000);
+
+ reprocessingPolls.set(recordingId, pollInterval);
+ };
+
+ const stopReprocessingPoll = (recordingId) => {
+ if (reprocessingPolls.has(recordingId)) {
+ clearInterval(reprocessingPolls.get(recordingId));
+ reprocessingPolls.delete(recordingId);
+ }
+ };
+
+ return {
+ // Reprocess modal
+ openReprocessModal,
+ closeReprocessModal,
+ confirmReprocess,
+ cancelReprocess,
+ executeReprocess,
+
+ // Reset status
+ confirmReset,
+ cancelReset,
+ executeReset,
+
+ // Transcription
+ reprocessTranscription,
+
+ // Summary
+ reprocessSummary,
+ generateSummary,
+
+ // Polling
+ startReprocessingPoll,
+ stopReprocessingPoll
+ };
+}
diff --git a/static/js/modules/composables/sharing.js b/static/js/modules/composables/sharing.js
new file mode 100644
index 00000000..abc55f2b
--- /dev/null
+++ b/static/js/modules/composables/sharing.js
@@ -0,0 +1,659 @@
+/**
+ * Sharing composable
+ * Handles public and internal sharing of recordings
+ */
+
+export function useSharing(state, utils) {
+ const {
+ showShareModal, showSharesListModal, showShareDeleteModal,
+ showUnifiedShareModal, recordingToShare, shareOptions,
+ generatedShareLink, existingShareDetected, recordingPublicShares, isLoadingPublicShares,
+ userShares, isLoadingShares, copiedShareId, shareToDelete, selectedRecording, recordings,
+ internalShareUserSearch, internalShareSearchResults,
+ internalShareRecording, internalSharePermissions, internalShareMaxPermissions,
+ recordingInternalShares, isLoadingInternalShares,
+ isSearchingUsers, allUsers, isLoadingAllUsers,
+ enableInternalSharing, showUsernamesInUI
+ } = state;
+
+ const { showToast, setGlobalError } = utils;
+
+ let userSearchTimeout = null;
+
+ // Helper function to format share dates
+ const formatShareDate = (dateString) => {
+ if (!dateString) return 'Unknown date';
+
+ try {
+ const date = new Date(dateString);
+ const now = new Date();
+ const diffMs = now - date;
+ const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
+
+ // If today
+ if (diffDays === 0) {
+ return 'Today at ' + date.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true });
+ }
+ // If yesterday
+ else if (diffDays === 1) {
+ return 'Yesterday at ' + date.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true });
+ }
+ // If within last week
+ else if (diffDays < 7) {
+ return date.toLocaleDateString('en-US', { weekday: 'long', hour: 'numeric', minute: '2-digit', hour12: true });
+ }
+ // Otherwise show full date
+ else {
+ return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: '2-digit', hour12: true });
+ }
+ } catch (e) {
+ console.error('Error formatting date:', e);
+ return dateString;
+ }
+ };
+
+ // Helper function to get color class for username (like speaker colors)
+ const getUserColorClass = (username) => {
+ if (!username) return 'speaker-color-1';
+
+ // Simple hash function to generate consistent color from username
+ let hash = 0;
+ for (let i = 0; i < username.length; i++) {
+ hash = ((hash << 5) - hash) + username.charCodeAt(i);
+ hash = hash & hash; // Convert to 32bit integer
+ }
+
+ // Map to color classes 1-8
+ const colorNum = (Math.abs(hash) % 8) + 1;
+ return `speaker-color-${colorNum}`;
+ };
+
+ // =========================================
+ // Public Sharing
+ // =========================================
+
+ const openShareModal = async (recording) => {
+ recordingToShare.value = recording;
+ shareOptions.share_summary = true;
+ shareOptions.share_notes = true;
+ generatedShareLink.value = '';
+ existingShareDetected.value = false;
+ recordingPublicShares.value = [];
+ showShareModal.value = true;
+
+ // Load all public shares for this recording
+ isLoadingPublicShares.value = true;
+ try {
+ const response = await fetch(`/api/shares`);
+ if (response.ok) {
+ const allShares = await response.json();
+ // Filter to only shares for this recording and add share_url
+ recordingPublicShares.value = allShares
+ .filter(share => share.recording_id === recording.id)
+ .map(share => ({
+ ...share,
+ share_url: `${window.location.origin}/share/${share.public_id}`
+ }));
+ }
+ } catch (error) {
+ console.error('Error loading public shares:', error);
+ recordingPublicShares.value = [];
+ } finally {
+ isLoadingPublicShares.value = false;
+ }
+ };
+
+ const closeShareModal = () => {
+ showShareModal.value = false;
+ recordingToShare.value = null;
+ existingShareDetected.value = false;
+ recordingPublicShares.value = [];
+ };
+
+ const createShare = async (forceNew = false) => {
+ const recording = recordingToShare.value || internalShareRecording.value;
+ if (!recording) return;
+
+ try {
+ const response = await fetch(`/api/recording/${recording.id}/share`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ ...shareOptions,
+ force_new: forceNew
+ })
+ });
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to create share link');
+
+ generatedShareLink.value = data.share_url;
+ existingShareDetected.value = data.existing && !forceNew;
+
+ // Add to the shares list (works for both share modal and unified modal)
+ if (!data.existing) {
+ recordingPublicShares.value.push({
+ ...data.share,
+ share_url: `${window.location.origin}/share/${data.share.public_id}`
+ });
+ // Update the recording's share count in the UI
+ await refreshRecordingShareCounts();
+ } else if (data.existing && !recordingPublicShares.value.find(s => s.id === data.share.id)) {
+ // If existing but not in list, add it
+ recordingPublicShares.value.push({
+ ...data.share,
+ share_url: `${window.location.origin}/share/${data.share.public_id}`
+ });
+ }
+
+ if (data.existing && !forceNew) {
+ showToast('Using existing share link', 'fa-link');
+ } else {
+ showToast('Share link created successfully!', 'fa-check-circle');
+ }
+ } catch (error) {
+ setGlobalError(`Failed to create share link: ${error.message}`);
+ }
+ };
+
+ const confirmDeletePublicShare = (share) => {
+ shareToDelete.value = share;
+ showShareDeleteModal.value = true;
+ };
+
+ const deletePublicShare = async () => {
+ if (!shareToDelete.value) return;
+ const shareId = shareToDelete.value.id;
+
+ try {
+ const response = await fetch(`/api/share/${shareId}`, { method: 'DELETE' });
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to delete share');
+
+ // Remove from the shares list (both modals use different arrays)
+ recordingPublicShares.value = recordingPublicShares.value.filter(s => s.id !== shareId);
+ userShares.value = userShares.value.filter(s => s.id !== shareId);
+
+ // Update the recording's share count in the UI
+ await refreshRecordingShareCounts();
+
+ showToast('Share link deleted successfully.', 'fa-check-circle');
+ showShareDeleteModal.value = false;
+ shareToDelete.value = null;
+ } catch (error) {
+ setGlobalError(`Failed to delete share: ${error.message}`);
+ }
+ };
+
+ const copyPublicShareLink = (shareUrl) => {
+ navigator.clipboard.writeText(shareUrl).then(() => {
+ showToast('Share link copied to clipboard!', 'fa-check-circle');
+ }).catch(() => {
+ setGlobalError('Failed to copy link to clipboard');
+ });
+ };
+
+ const copyPublicShareLinkWithFeedback = (shareUrl, shareId) => {
+ navigator.clipboard.writeText(shareUrl).then(() => {
+ copiedShareId.value = shareId;
+ showToast('Share link copied to clipboard!', 'fa-check-circle');
+
+ // Reset after delay
+ setTimeout(() => {
+ copiedShareId.value = null;
+ }, 1500);
+ }).catch(() => {
+ setGlobalError('Failed to copy link to clipboard');
+ });
+ };
+
+ const refreshRecordingShareCounts = async () => {
+ // Refresh the current recording if one is selected
+ const recording = recordingToShare.value || internalShareRecording.value || selectedRecording.value;
+ if (!recording) return;
+
+ try {
+ const response = await fetch(`/api/recordings/${recording.id}`);
+ if (response.ok) {
+ const updatedRecording = await response.json();
+
+ // Update in recordings list
+ const index = recordings.value.findIndex(r => r.id === recording.id);
+ if (index !== -1) {
+ // Preserve reactivity by updating specific fields
+ recordings.value[index].public_share_count = updatedRecording.public_share_count || 0;
+ recordings.value[index].shared_with_count = updatedRecording.shared_with_count || 0;
+ }
+
+ // Update selected recording if it's the same one
+ if (selectedRecording.value && selectedRecording.value.id === recording.id) {
+ selectedRecording.value.public_share_count = updatedRecording.public_share_count || 0;
+ selectedRecording.value.shared_with_count = updatedRecording.shared_with_count || 0;
+ }
+
+ // Update internal share recording if it's the same one
+ if (internalShareRecording.value && internalShareRecording.value.id === recording.id) {
+ internalShareRecording.value.public_share_count = updatedRecording.public_share_count || 0;
+ internalShareRecording.value.shared_with_count = updatedRecording.shared_with_count || 0;
+ }
+
+ // Update recording to share if it's the same one
+ if (recordingToShare.value && recordingToShare.value.id === recording.id) {
+ recordingToShare.value.public_share_count = updatedRecording.public_share_count || 0;
+ recordingToShare.value.shared_with_count = updatedRecording.shared_with_count || 0;
+ }
+ }
+ } catch (error) {
+ console.error('Failed to refresh recording share counts:', error);
+ }
+ };
+
+ const copyShareLink = () => {
+ if (!generatedShareLink.value) return;
+ navigator.clipboard.writeText(generatedShareLink.value).then(() => {
+ showToast('Share link copied to clipboard!');
+ });
+ };
+
+ const copyIndividualShareLink = (shareId) => {
+ const input = document.getElementById(`share-link-${shareId}`);
+ if (!input) return;
+
+ const button = input.nextElementSibling;
+ if (!button) return;
+
+ navigator.clipboard.writeText(input.value).then(() => {
+ copiedShareId.value = shareId;
+ showToast('Share link copied to clipboard!', 'fa-check');
+
+ // Apply success state
+ button.style.transition = 'background-color 0.2s ease';
+ button.style.backgroundColor = 'var(--bg-success, #10b981)';
+
+ // Revert after delay
+ setTimeout(() => {
+ button.style.backgroundColor = '';
+ copiedShareId.value = null;
+ setTimeout(() => {
+ button.style.transition = '';
+ }, 200);
+ }, 1500);
+ }).catch(err => {
+ console.error('Failed to copy share link:', err);
+ });
+ };
+
+ // =========================================
+ // Shares List
+ // =========================================
+
+ const openSharesList = async () => {
+ isLoadingShares.value = true;
+ showSharesListModal.value = true;
+ try {
+ const response = await fetch('/api/shares');
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to load shared items');
+ userShares.value = data;
+ } catch (error) {
+ setGlobalError(`Failed to load shared items: ${error.message}`);
+ } finally {
+ isLoadingShares.value = false;
+ }
+ };
+
+ const closeSharesList = () => {
+ showSharesListModal.value = false;
+ userShares.value = [];
+ };
+
+ const updateShare = async (share) => {
+ try {
+ const response = await fetch(`/api/share/${share.id}`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ share_summary: share.share_summary,
+ share_notes: share.share_notes
+ })
+ });
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to update share');
+ showToast('Share permissions updated.', 'fa-check-circle');
+ } catch (error) {
+ setGlobalError(`Failed to update share: ${error.message}`);
+ }
+ };
+
+ const confirmDeleteShare = (share) => {
+ shareToDelete.value = share;
+ showShareDeleteModal.value = true;
+ };
+
+ const cancelDeleteShare = () => {
+ shareToDelete.value = null;
+ showShareDeleteModal.value = false;
+ };
+
+ // =========================================
+ // Internal Sharing
+ // =========================================
+
+ const loadAllUsers = async () => {
+ if (!showUsernamesInUI.value) return;
+
+ isLoadingAllUsers.value = true;
+ try {
+ const response = await fetch('/api/users/search?q=');
+ if (!response.ok) {
+ if (response.status === 403) {
+ throw new Error('Internal sharing is not enabled');
+ }
+ throw new Error('Failed to load users');
+ }
+ const data = await response.json();
+ allUsers.value = data;
+ } catch (error) {
+ setGlobalError(`Failed to load users: ${error.message}`);
+ allUsers.value = [];
+ } finally {
+ isLoadingAllUsers.value = false;
+ }
+ };
+
+ const searchInternalShareUsers = async () => {
+ const query = internalShareUserSearch.value.trim();
+
+ // If SHOW_USERNAMES_IN_UI is enabled, filter allUsers locally
+ if (showUsernamesInUI.value) {
+ // Get list of user IDs that already have access
+ const sharedUserIds = new Set(recordingInternalShares.value.map(share => share.user_id));
+
+ // Filter out already-shared users
+ const availableUsers = allUsers.value.filter(user => !sharedUserIds.has(user.id));
+
+ if (query.length === 0) {
+ internalShareSearchResults.value = availableUsers;
+ } else {
+ internalShareSearchResults.value = availableUsers.filter(user =>
+ user.username.toLowerCase().includes(query.toLowerCase()) ||
+ (user.email && user.email.toLowerCase().includes(query.toLowerCase()))
+ );
+ }
+ return;
+ }
+
+ // Otherwise, use server-side search
+ if (query.length < 2) {
+ internalShareSearchResults.value = [];
+ return;
+ }
+
+ clearTimeout(userSearchTimeout);
+ userSearchTimeout = setTimeout(async () => {
+ isSearchingUsers.value = true;
+ try {
+ const response = await fetch(`/api/users/search?q=${encodeURIComponent(query)}`);
+ if (!response.ok) {
+ if (response.status === 403) {
+ throw new Error('Internal sharing is not enabled');
+ }
+ throw new Error('Failed to search users');
+ }
+ const data = await response.json();
+ internalShareSearchResults.value = data;
+ } catch (error) {
+ setGlobalError(`Failed to search users: ${error.message}`);
+ internalShareSearchResults.value = [];
+ } finally {
+ isSearchingUsers.value = false;
+ }
+ }, 300);
+ };
+
+ const openUnifiedShareModal = async (recording) => {
+ internalShareRecording.value = recording;
+ internalShareUserSearch.value = '';
+ internalShareSearchResults.value = [];
+ internalSharePermissions.value = { can_edit: false, can_reshare: false };
+ recordingPublicShares.value = [];
+ shareOptions.share_summary = true;
+ shareOptions.share_notes = true;
+
+ // PERMISSION CEILING: Calculate maximum permissions current user can grant
+ // If viewing a shared recording (not owner), constrain to their permissions
+ if (recording.is_shared && recording.share_info) {
+ internalShareMaxPermissions.value = {
+ can_edit: recording.share_info.can_edit || false,
+ can_reshare: recording.share_info.can_reshare || false
+ };
+ } else {
+ // Owner has unlimited permissions
+ internalShareMaxPermissions.value = {
+ can_edit: true,
+ can_reshare: true
+ };
+ }
+
+ showUnifiedShareModal.value = true;
+
+ // Load all public shares for this recording
+ isLoadingPublicShares.value = true;
+ try {
+ const response = await fetch(`/api/shares`);
+ if (response.ok) {
+ const allShares = await response.json();
+ // Filter to only shares for this recording and add share_url
+ recordingPublicShares.value = allShares
+ .filter(share => share.recording_id === recording.id)
+ .map(share => ({
+ ...share,
+ share_url: `${window.location.origin}/share/${share.public_id}`
+ }));
+ }
+ } catch (error) {
+ console.error('Error loading public shares:', error);
+ recordingPublicShares.value = [];
+ } finally {
+ isLoadingPublicShares.value = false;
+ }
+
+ // Load existing internal shares
+ isLoadingInternalShares.value = true;
+ try {
+ const response = await fetch(`/api/recordings/${recording.id}/shares-internal`);
+ if (!response.ok) {
+ if (response.status === 403) {
+ throw new Error('Internal sharing is not enabled');
+ }
+ throw new Error('Failed to load shares');
+ }
+ const data = await response.json();
+ recordingInternalShares.value = data.shares || [];
+ } catch (error) {
+ setGlobalError(`Failed to load shares: ${error.message}`);
+ recordingInternalShares.value = [];
+ } finally {
+ isLoadingInternalShares.value = false;
+ }
+
+ // If SHOW_USERNAMES_IN_UI is enabled, load all users
+ if (showUsernamesInUI.value) {
+ await loadAllUsers();
+ internalShareSearchResults.value = allUsers.value;
+ }
+ };
+
+ const closeUnifiedShareModal = () => {
+ showUnifiedShareModal.value = false;
+ internalShareRecording.value = null;
+ internalShareUserSearch.value = '';
+ internalShareSearchResults.value = [];
+ recordingInternalShares.value = [];
+ recordingPublicShares.value = [];
+ allUsers.value = [];
+ };
+
+ // Legacy function names for backward compatibility
+ const openInternalShareModal = openUnifiedShareModal;
+ const openManageInternalSharesModal = openUnifiedShareModal;
+ const closeInternalShareModal = closeUnifiedShareModal;
+ const closeManageInternalSharesModal = closeUnifiedShareModal;
+
+ const reloadInternalShares = async () => {
+ if (!internalShareRecording.value) return;
+
+ isLoadingInternalShares.value = true;
+ try {
+ const response = await fetch(`/api/recordings/${internalShareRecording.value.id}/shares-internal`);
+ if (!response.ok) {
+ throw new Error('Failed to load shares');
+ }
+ const data = await response.json();
+ recordingInternalShares.value = data.shares || [];
+ } catch (error) {
+ setGlobalError(`Failed to reload shares: ${error.message}`);
+ } finally {
+ isLoadingInternalShares.value = false;
+ }
+ };
+
+ const shareWithUsername = async () => {
+ if (!internalShareRecording.value) return;
+
+ const username = internalShareUserSearch.value.trim();
+ if (!username) {
+ setGlobalError('Please enter a username');
+ return;
+ }
+
+ isSearchingUsers.value = true;
+ try {
+ // Search for the exact username
+ const searchResponse = await fetch(`/api/users/search?q=${encodeURIComponent(username)}`);
+ if (!searchResponse.ok) {
+ if (searchResponse.status === 403) {
+ throw new Error('Internal sharing is not enabled');
+ }
+ throw new Error('Failed to find user');
+ }
+
+ const users = await searchResponse.json();
+
+ if (users.length === 0) {
+ setGlobalError(`User "${username}" not found`);
+ return;
+ }
+
+ // Use the first matching user (should be exact match from backend)
+ const user = users[0];
+ await createInternalShare(user.id, user.username);
+
+ // Clear input on success
+ internalShareUserSearch.value = '';
+ } catch (error) {
+ setGlobalError(error.message || 'Failed to share with user');
+ } finally {
+ isSearchingUsers.value = false;
+ }
+ };
+
+ const createInternalShare = async (userId, username) => {
+ if (!internalShareRecording.value) return;
+
+ try {
+ const response = await fetch(`/api/recordings/${internalShareRecording.value.id}/share-internal`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ user_id: userId,
+ can_edit: internalSharePermissions.value.can_edit,
+ can_reshare: internalSharePermissions.value.can_reshare
+ })
+ });
+
+ const data = await response.json();
+ if (!response.ok) {
+ throw new Error(data.error || 'Failed to share recording');
+ }
+
+ const displayName = showUsernamesInUI.value ? username : `User #${userId}`;
+ showToast(`Recording shared with ${displayName}`, 'fa-share-alt');
+
+ // Reset permissions for next share
+ internalSharePermissions.value = { can_edit: false, can_reshare: false };
+
+ // Reload shares to show the new share in the list
+ await reloadInternalShares();
+
+ // Update the recording's share count in the UI
+ await refreshRecordingShareCounts();
+ } catch (error) {
+ setGlobalError(`Failed to share recording: ${error.message}`);
+ }
+ };
+
+ const revokeInternalShare = async (shareId, username) => {
+ if (!internalShareRecording.value) return;
+
+ try {
+ const response = await fetch(`/api/internal-shares/${shareId}`, {
+ method: 'DELETE'
+ });
+
+ if (!response.ok) {
+ const data = await response.json();
+ throw new Error(data.error || 'Failed to revoke share');
+ }
+
+ recordingInternalShares.value = recordingInternalShares.value.filter(s => s.id !== shareId);
+ const displayName = showUsernamesInUI.value ? username : 'User';
+ showToast(`Access revoked for ${displayName}`, 'fa-user-times');
+
+ // Update the recording's share count in the UI
+ await refreshRecordingShareCounts();
+ } catch (error) {
+ setGlobalError(`Failed to revoke share: ${error.message}`);
+ }
+ };
+
+ return {
+ // Utilities
+ formatShareDate,
+ getUserColorClass,
+
+ // Public sharing
+ openShareModal,
+ closeShareModal,
+ createShare,
+ copyShareLink,
+ copyPublicShareLink,
+ copyPublicShareLinkWithFeedback,
+ copyIndividualShareLink,
+ confirmDeletePublicShare,
+ deletePublicShare,
+ refreshRecordingShareCounts,
+
+ // Shares list
+ openSharesList,
+ closeSharesList,
+ updateShare,
+ confirmDeleteShare,
+ cancelDeleteShare,
+ deleteShare: deletePublicShare, // Alias for template compatibility
+ copiedShareId,
+
+ // Internal sharing
+ loadAllUsers,
+ searchInternalShareUsers,
+ openUnifiedShareModal,
+ closeUnifiedShareModal,
+ openInternalShareModal,
+ closeInternalShareModal,
+ openManageInternalSharesModal,
+ closeManageInternalSharesModal,
+ reloadInternalShares,
+ shareWithUsername,
+ createInternalShare,
+ revokeInternalShare
+ };
+}
diff --git a/static/js/modules/composables/speakers.js b/static/js/modules/composables/speakers.js
new file mode 100644
index 00000000..60380020
--- /dev/null
+++ b/static/js/modules/composables/speakers.js
@@ -0,0 +1,1069 @@
+/**
+ * Speaker management composable
+ * Handles speaker identification, naming, and navigation
+ */
+
+export function useSpeakers(state, utils, processedTranscription) {
+ const { nextTick } = Vue;
+ const {
+ showSpeakerModal, showAddSpeakerModal, showEditSpeakersModal,
+ showEditTextModal, selectedRecording, recordings,
+ speakerMap, modalSpeakers, speakerDisplayMap, speakerSuggestions, loadingSuggestions,
+ activeSpeakerInput, regenerateSummaryAfterSpeakerUpdate,
+ editingSpeakersList, databaseSpeakers, editingSpeakerSuggestions,
+ editSpeakerDropdownPositions, newSpeakerName, newSpeakerIsMe,
+ newSpeakerSuggestions, loadingNewSpeakerSuggestions, showNewSpeakerSuggestions,
+ editingSegmentIndex, editingSpeakerIndex, editedText, editedTranscriptData, highlightedSpeaker,
+ isAutoIdentifying, availableSpeakers, editingSegments,
+ currentSpeakerGroupIndex, speakerGroups, currentUserName,
+ voiceSuggestions, loadingVoiceSuggestions
+ } = state;
+
+ const { showToast, setGlobalError } = utils;
+
+ // Current speaker highlight state
+ let currentSpeakerId = null;
+
+ // =========================================
+ // Speaker Identification Modal
+ // =========================================
+
+ const openSpeakerModal = () => {
+ if (!selectedRecording.value) return;
+
+ // Clear any existing speaker map data first
+ speakerMap.value = {};
+ speakerDisplayMap.value = {};
+
+ // Get the same speaker order used in processedTranscription
+ const transcription = selectedRecording.value?.transcription;
+ let speakers = [];
+
+ if (transcription) {
+ try {
+ const transcriptionData = JSON.parse(transcription);
+ if (transcriptionData && Array.isArray(transcriptionData)) {
+ // Use the exact same logic as processedTranscription to get speakers
+ speakers = [...new Set(transcriptionData.map(segment => segment.speaker).filter(Boolean))];
+ }
+ } catch (e) {
+ // Fall back to getIdentifiedSpeakers if JSON parsing fails
+ speakers = getIdentifiedSpeakers();
+ }
+ }
+
+ // Set modalSpeakers for the template to use
+ modalSpeakers.value = speakers;
+
+ // Initialize speaker map with the same order and colors as the transcript
+ speakerMap.value = speakers.reduce((acc, speaker, index) => {
+ acc[speaker] = {
+ name: '',
+ isMe: false,
+ color: `speaker-color-${(index % 8) + 1}` // Same color assignment as processedTranscription
+ };
+ // Keep the original speaker ID for display
+ speakerDisplayMap.value[speaker] = speaker;
+ return acc;
+ }, {});
+
+ highlightedSpeaker.value = null;
+ speakerSuggestions.value = {};
+ loadingSuggestions.value = {};
+ activeSpeakerInput.value = null;
+ isAutoIdentifying.value = false;
+ regenerateSummaryAfterSpeakerUpdate.value = true;
+ voiceSuggestions.value = {};
+
+ showSpeakerModal.value = true;
+
+ // Load voice-based suggestions if embeddings are available
+ loadVoiceSuggestions();
+ };
+
+ const getIdentifiedSpeakers = () => {
+ // Ensure we have a valid recording and transcription
+ if (!selectedRecording.value?.transcription) {
+ return [];
+ }
+
+ const transcription = selectedRecording.value.transcription;
+ let transcriptionData;
+
+ try {
+ transcriptionData = JSON.parse(transcription);
+ } catch (e) {
+ transcriptionData = null;
+ }
+
+ // Handle new simplified JSON format (array of segments)
+ if (transcriptionData && Array.isArray(transcriptionData)) {
+ // JSON format - extract speakers in order of appearance
+ const speakersInOrder = [];
+ const seenSpeakers = new Set();
+ transcriptionData.forEach(segment => {
+ if (segment.speaker && !seenSpeakers.has(segment.speaker)) {
+ seenSpeakers.add(segment.speaker);
+ speakersInOrder.push(segment.speaker);
+ }
+ });
+ return speakersInOrder;
+ } else if (typeof transcription === 'string') {
+ // Plain text format - find speakers in order of appearance
+ const speakerRegex = /\[([^\]]+)\]:/g;
+ const speakersInOrder = [];
+ const seenSpeakers = new Set();
+ let match;
+ while ((match = speakerRegex.exec(transcription)) !== null) {
+ const speaker = match[1].trim();
+ if (speaker && !seenSpeakers.has(speaker)) {
+ seenSpeakers.add(speaker);
+ speakersInOrder.push(speaker);
+ }
+ }
+ return speakersInOrder;
+ }
+ return [];
+ };
+
+ const closeSpeakerModal = () => {
+ showSpeakerModal.value = false;
+ highlightedSpeaker.value = null;
+ // Clear the speaker map to prevent stale data from persisting
+ speakerMap.value = {};
+ speakerSuggestions.value = {};
+ loadingSuggestions.value = {};
+ clearSpeakerHighlight();
+ };
+
+ const saveTranscriptImmediately = async (transcriptData) => {
+ if (!selectedRecording.value) return;
+
+ try {
+ // Save transcript without closing modal
+ const filteredSpeakerMap = Object.entries(speakerMap.value).reduce((acc, [speakerId, speakerData]) => {
+ if (speakerData.name && speakerData.name.trim() !== '') {
+ acc[speakerId] = speakerData;
+ }
+ return acc;
+ }, {});
+
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await fetch(`/recording/${selectedRecording.value.id}/update_transcript`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({
+ transcript_data: transcriptData,
+ speaker_map: filteredSpeakerMap,
+ regenerate_summary: false // Don't regenerate on immediate saves
+ })
+ });
+
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to update transcript');
+
+ // Update recordings list and selected recording without closing modal
+ const index = recordings.value.findIndex(r => r.id === selectedRecording.value.id);
+ if (index !== -1) {
+ recordings.value[index] = data.recording;
+ }
+ selectedRecording.value = data.recording;
+ editedTranscriptData.value = null;
+
+ showToast('Saved!', 'fa-check-circle', 2000, 'success');
+ } catch (error) {
+ console.error('Save Transcript Error:', error);
+ showToast(`Error: ${error.message}`, 'fa-exclamation-circle', 3000, 'error');
+ }
+ };
+
+ const saveTranscriptEdits = async () => {
+ if (!selectedRecording.value || !editedTranscriptData.value) {
+ return saveSpeakerNames(); // Fall back to regular speaker name save
+ }
+
+ try {
+ // Save both speaker names and transcript edits
+ const filteredSpeakerMap = Object.entries(speakerMap.value).reduce((acc, [speakerId, speakerData]) => {
+ if (speakerData.name && speakerData.name.trim() !== '') {
+ acc[speakerId] = speakerData;
+ }
+ return acc;
+ }, {});
+
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await fetch(`/recording/${selectedRecording.value.id}/update_transcript`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({
+ transcript_data: editedTranscriptData.value,
+ speaker_map: filteredSpeakerMap,
+ regenerate_summary: regenerateSummaryAfterSpeakerUpdate.value
+ })
+ });
+
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to update transcript');
+
+ closeSpeakerModal();
+
+ // If summary regeneration was requested, update status immediately
+ if (regenerateSummaryAfterSpeakerUpdate.value && data.summary_queued) {
+ // Update recording status to SUMMARIZING immediately for UI feedback
+ const summarizingRecording = { ...data.recording, status: 'SUMMARIZING' };
+
+ const index = recordings.value.findIndex(r => r.id === selectedRecording.value.id);
+ if (index !== -1) {
+ recordings.value[index] = summarizingRecording;
+ }
+ selectedRecording.value = summarizingRecording;
+ editedTranscriptData.value = null;
+
+ showToast('Transcript updated successfully!', 'fa-check-circle');
+ showToast('Summary regeneration started', 'fa-sync-alt');
+
+ // Poll for summary completion
+ pollForSummaryCompletion(selectedRecording.value.id);
+ } else {
+ const index = recordings.value.findIndex(r => r.id === selectedRecording.value.id);
+ if (index !== -1) {
+ recordings.value[index] = data.recording;
+ }
+ selectedRecording.value = data.recording;
+ editedTranscriptData.value = null;
+
+ showToast('Transcript updated successfully!', 'fa-check-circle');
+ }
+ } catch (error) {
+ console.error('Save Transcript Error:', error);
+ showToast(`Error: ${error.message}`, 'fa-exclamation-circle', 3000, 'error');
+ }
+ };
+
+ const saveSpeakerNames = async () => {
+ if (!selectedRecording.value) return;
+
+ // If there are transcript edits, save those instead
+ if (editedTranscriptData.value) {
+ return saveTranscriptEdits();
+ }
+
+ // Create a filtered speaker map that excludes entries with blank names
+ const filteredSpeakerMap = Object.entries(speakerMap.value).reduce((acc, [speakerId, speakerData]) => {
+ if (speakerData.name && speakerData.name.trim() !== '') {
+ acc[speakerId] = speakerData;
+ }
+ return acc;
+ }, {});
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await fetch(`/recording/${selectedRecording.value.id}/update_speakers`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({
+ speaker_map: filteredSpeakerMap,
+ regenerate_summary: regenerateSummaryAfterSpeakerUpdate.value
+ })
+ });
+
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to update speaker names');
+
+ closeSpeakerModal();
+
+ // If summary regeneration was requested, update status immediately
+ if (regenerateSummaryAfterSpeakerUpdate.value && data.summary_queued) {
+ // Update recording status to SUMMARIZING immediately for UI feedback
+ const summarizingRecording = { ...data.recording, status: 'SUMMARIZING' };
+
+ const index = recordings.value.findIndex(r => r.id === selectedRecording.value.id);
+ if (index !== -1) {
+ recordings.value[index] = summarizingRecording;
+ }
+ selectedRecording.value = summarizingRecording;
+
+ showToast('Speaker names updated successfully!', 'fa-check-circle');
+ showToast('Summary regeneration started', 'fa-sync-alt');
+
+ // Poll for summary completion
+ pollForSummaryCompletion(selectedRecording.value.id);
+ } else {
+ // The backend returns the fully updated recording object
+ const index = recordings.value.findIndex(r => r.id === selectedRecording.value.id);
+ if (index !== -1) {
+ recordings.value[index] = data.recording;
+ }
+ selectedRecording.value = data.recording;
+
+ showToast('Speaker names updated successfully!', 'fa-check-circle');
+ }
+ } catch (error) {
+ setGlobalError(`Failed to save speaker names: ${error.message}`);
+ }
+ };
+
+ // Poll for summary completion after regeneration
+ const pollForSummaryCompletion = async (recordingId) => {
+ const maxAttempts = 40; // Poll for up to 2 minutes (40 * 3 seconds)
+ let attempts = 0;
+
+ const pollInterval = setInterval(async () => {
+ attempts++;
+
+ try {
+ // Use lightweight status-only endpoint for polling
+ const response = await fetch(`/recording/${recordingId}/status`);
+ if (!response.ok) {
+ clearInterval(pollInterval);
+ return;
+ }
+
+ const statusData = await response.json();
+
+ // Update status in recordings list
+ const index = recordings.value.findIndex(r => r.id === recordingId);
+ if (index !== -1) {
+ // Create new object to ensure Vue reactivity
+ recordings.value[index] = {
+ ...recordings.value[index],
+ status: statusData.status
+ };
+ }
+
+ // Update selectedRecording with new object reference for reactivity
+ if (selectedRecording.value && selectedRecording.value.id === recordingId) {
+ selectedRecording.value = {
+ ...selectedRecording.value,
+ status: statusData.status
+ };
+ }
+
+ // Check if summarization is complete
+ if (statusData.status === 'COMPLETED') {
+ clearInterval(pollInterval);
+
+ // Now fetch the full recording with the new summary
+ const fullResponse = await fetch(`/api/recordings/${recordingId}`);
+ if (fullResponse.ok) {
+ const fullData = await fullResponse.json();
+
+ // Update in recordings list first
+ const currentIndex = recordings.value.findIndex(r => r.id === recordingId);
+ if (currentIndex !== -1) {
+ recordings.value[currentIndex] = fullData;
+ }
+
+ // Always update selectedRecording if it's the current recording
+ if (selectedRecording.value && selectedRecording.value.id === recordingId) {
+ selectedRecording.value = fullData;
+ // Force Vue to detect the change
+ await nextTick();
+ }
+ }
+
+ showToast('Summary updated!', 'fa-check-circle');
+ } else if (statusData.status === 'FAILED' || statusData.status === 'ERROR') {
+ // Stop polling if it failed
+ clearInterval(pollInterval);
+ showToast('Summary generation failed', 'fa-exclamation-circle', 3000, 'error');
+ } else if (attempts >= maxAttempts) {
+ // Stop polling after max attempts
+ clearInterval(pollInterval);
+ showToast('Summary generation timed out', 'fa-clock', 3000, 'warning');
+ }
+ } catch (error) {
+ console.error('Error polling for summary:', error);
+ clearInterval(pollInterval);
+ }
+ }, 3000); // Poll every 3 seconds
+ };
+
+ // =========================================
+ // Speaker Suggestions
+ // =========================================
+
+ const loadVoiceSuggestions = async () => {
+ if (!selectedRecording.value?.id) return;
+
+ loadingVoiceSuggestions.value = true;
+ voiceSuggestions.value = {};
+
+ try {
+ const response = await fetch(`/speakers/suggestions/${selectedRecording.value.id}`);
+ if (!response.ok) throw new Error('Failed to load voice suggestions');
+
+ const data = await response.json();
+
+ if (data.success && data.suggestions) {
+ // Only keep suggestions that have matches
+ voiceSuggestions.value = Object.fromEntries(
+ Object.entries(data.suggestions).filter(([_, matches]) => matches && matches.length > 0)
+ );
+ }
+ } catch (error) {
+ console.error('Error loading voice suggestions:', error);
+ voiceSuggestions.value = {};
+ } finally {
+ loadingVoiceSuggestions.value = false;
+ }
+ };
+
+ const applyVoiceSuggestion = (speakerId, suggestion) => {
+ if (speakerMap.value[speakerId]) {
+ speakerMap.value[speakerId].name = suggestion.name;
+ // Don't delete the suggestion - let it reappear if user clears the field
+ }
+ };
+
+ // Handle "This is Me" checkbox changes
+ const handleIsMeChange = (speakerId) => {
+ if (!speakerMap.value[speakerId]) return;
+
+ if (speakerMap.value[speakerId].isMe) {
+ // Checkbox is now checked - set the name to current user's name
+ speakerMap.value[speakerId].name = currentUserName.value || 'Me';
+ } else {
+ // Checkbox is now unchecked - clear the name
+ speakerMap.value[speakerId].name = '';
+ }
+ };
+
+ // Determine if voice suggestion pill should be shown inside the input field
+ const shouldShowVoiceSuggestionPill = (speakerId) => {
+ // Don't show if no suggestions available
+ if (!voiceSuggestions.value[speakerId] || voiceSuggestions.value[speakerId].length === 0) {
+ return false;
+ }
+
+ // Don't show if "This is Me" is checked
+ if (speakerMap.value[speakerId]?.isMe) {
+ return false;
+ }
+
+ // Only show when the input field is empty
+ const typedName = speakerMap.value[speakerId]?.name?.trim();
+ if (typedName && typedName.length > 0) {
+ return false;
+ }
+
+ return true;
+ };
+
+ const searchSpeakers = async (query, speakerId) => {
+ if (!query || query.length < 2) {
+ speakerSuggestions.value[speakerId] = [];
+ return;
+ }
+
+ loadingSuggestions.value[speakerId] = true;
+
+ try {
+ const response = await fetch(`/speakers/search?q=${encodeURIComponent(query)}`);
+ if (!response.ok) throw new Error('Failed to search speakers');
+
+ const speakers = await response.json();
+ speakerSuggestions.value[speakerId] = speakers;
+ } catch (error) {
+ console.error('Error searching speakers:', error);
+ speakerSuggestions.value[speakerId] = [];
+ } finally {
+ loadingSuggestions.value[speakerId] = false;
+ }
+ };
+
+ const selectSpeakerSuggestion = (speakerId, suggestion) => {
+ if (speakerMap.value[speakerId]) {
+ speakerMap.value[speakerId].name = suggestion.name;
+ speakerSuggestions.value[speakerId] = [];
+ activeSpeakerInput.value = null;
+ }
+ };
+
+ const closeSpeakerSuggestionsOnClick = (event) => {
+ // Check if the click was on an input field or dropdown
+ const clickedInput = event.target.closest('input[type="text"]');
+ const clickedDropdown = event.target.closest('.absolute.z-10');
+
+ // If not clicking on input or dropdown, close all suggestions
+ if (!clickedInput && !clickedDropdown) {
+ Object.keys(speakerSuggestions.value).forEach(speakerId => {
+ speakerSuggestions.value[speakerId] = [];
+ });
+ }
+ };
+
+ // =========================================
+ // Speaker Navigation
+ // =========================================
+
+ const findSpeakerGroups = (speakerId) => {
+ if (!speakerId) return [];
+
+ const groups = [];
+ const modalTranscript = document.querySelector('div.speaker-modal-transcript');
+ const mainTranscript = document.querySelector('.transcription-simple-view, .transcription-with-speakers, .transcription-content');
+ const transcriptContainer = modalTranscript || mainTranscript;
+
+ if (!transcriptContainer) return [];
+
+ // For JSON-based transcripts with segments
+ const allSegments = transcriptContainer.querySelectorAll('.speaker-segment');
+ if (allSegments.length > 0) {
+ let currentGroup = null;
+ let lastSpeakerId = null;
+
+ allSegments.forEach(segment => {
+ const speakerTag = segment.querySelector('[data-speaker-id]');
+ const segmentSpeakerId = speakerTag?.dataset.speakerId;
+
+ if (segmentSpeakerId === speakerId) {
+ // If this is a new group (not consecutive with previous)
+ if (lastSpeakerId !== speakerId) {
+ currentGroup = {
+ startElement: segment,
+ elements: [segment]
+ };
+ groups.push(currentGroup);
+ } else if (currentGroup) {
+ // Add to existing group
+ currentGroup.elements.push(segment);
+ }
+ }
+ lastSpeakerId = segmentSpeakerId;
+ });
+ } else {
+ // For plain text transcripts with speaker tags
+ const allTags = transcriptContainer.querySelectorAll('[data-speaker-id]');
+ let currentGroup = null;
+
+ allTags.forEach(tag => {
+ if (tag.dataset.speakerId === speakerId) {
+ // Find the parent element that contains this speaker's content
+ const parentSegment = tag.closest('.speaker-segment') || tag.parentElement;
+
+ if (!currentGroup || !currentGroup.lastElement ||
+ !parentSegment.previousElementSibling ||
+ parentSegment.previousElementSibling !== currentGroup.lastElement) {
+ // Start a new group
+ currentGroup = {
+ startElement: parentSegment,
+ elements: [parentSegment],
+ lastElement: parentSegment
+ };
+ groups.push(currentGroup);
+ } else {
+ // Continue the group
+ currentGroup.elements.push(parentSegment);
+ currentGroup.lastElement = parentSegment;
+ }
+ }
+ });
+ }
+
+ return groups;
+ };
+
+ const highlightSpeakerInTranscript = (speakerId) => {
+ highlightedSpeaker.value = speakerId;
+
+ if (speakerId) {
+ // Find all speaker groups for navigation
+ speakerGroups.value = findSpeakerGroups(speakerId);
+ currentSpeakerGroupIndex.value = 0;
+
+ // Scroll to the first group
+ if (speakerGroups.value.length > 0) {
+ nextTick(() => {
+ const firstGroup = speakerGroups.value[0];
+ if (firstGroup && firstGroup.startElement) {
+ firstGroup.startElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ }
+ });
+ }
+ } else {
+ speakerGroups.value = [];
+ currentSpeakerGroupIndex.value = -1;
+ }
+ };
+
+ const navigateToNextSpeakerGroup = () => {
+ if (speakerGroups.value.length === 0) return;
+
+ // Don't reset the speaker groups, just update the index
+ currentSpeakerGroupIndex.value = (currentSpeakerGroupIndex.value + 1) % speakerGroups.value.length;
+ const group = speakerGroups.value[currentSpeakerGroupIndex.value];
+ if (group && group.startElement) {
+ group.startElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ }
+ };
+
+ const navigateToPrevSpeakerGroup = () => {
+ if (speakerGroups.value.length === 0) return;
+
+ // Don't reset the speaker groups, just update the index
+ currentSpeakerGroupIndex.value = currentSpeakerGroupIndex.value <= 0
+ ? speakerGroups.value.length - 1
+ : currentSpeakerGroupIndex.value - 1;
+ const group = speakerGroups.value[currentSpeakerGroupIndex.value];
+ if (group && group.startElement) {
+ group.startElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ }
+ };
+
+ const focusSpeaker = (speakerId) => {
+ // Set this as the active speaker input
+ activeSpeakerInput.value = speakerId;
+ // Only highlight if not already highlighted (to preserve navigation state)
+ if (highlightedSpeaker.value !== speakerId) {
+ highlightSpeakerInTranscript(speakerId);
+ }
+ };
+
+ const blurSpeaker = () => {
+ // Clear the active speaker input after a delay to allow clicking on suggestions
+ setTimeout(() => {
+ activeSpeakerInput.value = null;
+ speakerSuggestions.value = {};
+ }, 200);
+ clearSpeakerHighlight();
+ };
+
+ const clearSpeakerHighlight = () => {
+ highlightedSpeaker.value = null;
+ };
+
+ // =========================================
+ // Auto-Identify Speakers
+ // =========================================
+
+ const autoIdentifySpeakers = async () => {
+ if (!selectedRecording.value) {
+ showToast('No recording selected.', 'fa-exclamation-circle');
+ return;
+ }
+
+ isAutoIdentifying.value = true;
+ showToast('Starting automatic speaker identification...', 'fa-magic');
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await fetch(`/recording/${selectedRecording.value.id}/auto_identify_speakers`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({
+ current_speaker_map: speakerMap.value
+ })
+ });
+
+ const data = await response.json();
+ if (!response.ok) {
+ throw new Error(data.error || 'Unknown error occurred during auto-identification.');
+ }
+
+ // Check if there's a message (e.g., all speakers already identified)
+ if (data.message) {
+ showToast(data.message, 'fa-info-circle');
+ return;
+ }
+
+ // Update speakerMap with the identified names
+ let identifiedCount = 0;
+ for (const speakerId in data.speaker_map) {
+ const identifiedName = data.speaker_map[speakerId];
+ if (speakerMap.value[speakerId] && identifiedName && identifiedName.trim() !== '') {
+ speakerMap.value[speakerId].name = identifiedName;
+ identifiedCount++;
+ }
+ }
+
+ if (identifiedCount > 0) {
+ showToast(`${identifiedCount} speaker(s) identified successfully!`, 'fa-check-circle');
+ } else {
+ showToast('No speakers could be identified from the context.', 'fa-info-circle');
+ }
+
+ } catch (error) {
+ console.error('Auto Identify Speakers Error:', error);
+ showToast(`Error: ${error.message}`, 'fa-exclamation-circle', 5000, 'error');
+ } finally {
+ isAutoIdentifying.value = false;
+ }
+ };
+
+ // =========================================
+ // Add Speaker Modal
+ // =========================================
+
+ const searchNewSpeaker = async () => {
+ const query = newSpeakerName.value;
+ if (!query || query.length < 2) {
+ newSpeakerSuggestions.value = [];
+ return;
+ }
+
+ loadingNewSpeakerSuggestions.value = true;
+ try {
+ const response = await fetch(`/speakers/search?q=${encodeURIComponent(query)}`);
+ if (!response.ok) throw new Error('Failed to search speakers');
+
+ const speakers = await response.json();
+ newSpeakerSuggestions.value = speakers;
+ } catch (error) {
+ console.error('Error searching speakers:', error);
+ newSpeakerSuggestions.value = [];
+ } finally {
+ loadingNewSpeakerSuggestions.value = false;
+ }
+ };
+
+ const selectNewSpeakerSuggestion = (suggestion) => {
+ newSpeakerName.value = suggestion.name;
+ newSpeakerSuggestions.value = [];
+ showNewSpeakerSuggestions.value = false;
+ };
+
+ const hideNewSpeakerSuggestionsDelayed = () => {
+ setTimeout(() => {
+ showNewSpeakerSuggestions.value = false;
+ newSpeakerSuggestions.value = [];
+ }, 200);
+ };
+
+ const openAddSpeakerModal = () => {
+ newSpeakerName.value = '';
+ newSpeakerIsMe.value = false;
+ newSpeakerSuggestions.value = [];
+ loadingNewSpeakerSuggestions.value = false;
+ showNewSpeakerSuggestions.value = false;
+ showAddSpeakerModal.value = true;
+ };
+
+ const closeAddSpeakerModal = () => {
+ showAddSpeakerModal.value = false;
+ newSpeakerName.value = '';
+ newSpeakerIsMe.value = false;
+ newSpeakerSuggestions.value = [];
+ loadingNewSpeakerSuggestions.value = false;
+ showNewSpeakerSuggestions.value = false;
+ };
+
+ const addNewSpeaker = () => {
+ const name = newSpeakerIsMe.value ? (currentUserName.value || 'Me') : newSpeakerName.value.trim();
+
+ if (!newSpeakerIsMe.value && !name) {
+ showToast('Please enter a speaker name', 'fa-exclamation-circle');
+ return;
+ }
+
+ // Generate new speaker ID
+ const existingSpeakerNumbers = modalSpeakers.value
+ .map(s => {
+ const match = s.match(/^SPEAKER_(\d+)$/);
+ return match ? parseInt(match[1]) : -1;
+ })
+ .filter(n => n >= 0);
+
+ const nextNumber = existingSpeakerNumbers.length > 0
+ ? Math.max(...existingSpeakerNumbers) + 1
+ : modalSpeakers.value.length;
+
+ const newSpeakerId = `SPEAKER_${String(nextNumber).padStart(2, '0')}`;
+
+ // Add to modalSpeakers
+ modalSpeakers.value.push(newSpeakerId);
+
+ // Add to speakerMap with next available color
+ const colorIndex = modalSpeakers.value.length - 1;
+ speakerMap.value[newSpeakerId] = {
+ name: name,
+ isMe: newSpeakerIsMe.value,
+ color: `speaker-color-${(colorIndex % 8) + 1}`
+ };
+
+ // Add to speakerDisplayMap
+ speakerDisplayMap.value[newSpeakerId] = newSpeakerId;
+
+ closeAddSpeakerModal();
+ showToast('Speaker added successfully', 'fa-check-circle');
+ };
+
+ // =========================================
+ // Edit Speakers Modal
+ // =========================================
+
+ const openEditSpeakersModal = async () => {
+ // Close any open suggestions
+ editingSegments.value.forEach(seg => seg.showSuggestions = false);
+ // Copy current speakers to editing list with original and current properties
+ editingSpeakersList.value = availableSpeakers.value.map(s => ({
+ original: s,
+ current: s
+ }));
+ // Fetch speakers from database for autocomplete
+ try {
+ const response = await fetch('/speakers');
+ const speakers = await response.json();
+ // Keep full objects with id and name for autocomplete dropdown
+ databaseSpeakers.value = speakers;
+ } catch (e) {
+ console.error('Failed to fetch speakers:', e);
+ databaseSpeakers.value = [];
+ }
+ editingSpeakerSuggestions.value = {};
+ showEditSpeakersModal.value = true;
+ };
+
+ const closeEditSpeakersModal = () => {
+ showEditSpeakersModal.value = false;
+ editingSpeakersList.value = [];
+ };
+
+ const addEditingSpeaker = () => {
+ editingSpeakersList.value.push({ original: '', current: '' });
+ };
+
+ const removeEditingSpeaker = (index) => {
+ editingSpeakersList.value.splice(index, 1);
+ };
+
+ const filterEditingSpeakerSuggestions = (index) => {
+ const query = editingSpeakersList.value[index]?.current?.toLowerCase().trim() || '';
+ if (query === '') {
+ // Show all speakers when field is empty/focused
+ editingSpeakerSuggestions.value[index] = [...databaseSpeakers.value];
+ } else {
+ editingSpeakerSuggestions.value[index] = databaseSpeakers.value.filter(
+ s => s.name.toLowerCase().includes(query)
+ );
+ }
+ };
+
+ const selectEditingSpeakerSuggestion = (index, name) => {
+ editingSpeakersList.value[index].current = name;
+ editingSpeakerSuggestions.value[index] = [];
+ };
+
+ const closeEditingSpeakerSuggestions = (index) => {
+ editingSpeakerSuggestions.value[index] = [];
+ };
+
+ const onEditSpeakerBlur = (index) => {
+ // Delay closing to allow clicking on suggestions
+ setTimeout(() => {
+ closeEditingSpeakerSuggestions(index);
+ }, 200);
+ };
+
+ const getEditSpeakerDropdownPosition = (index) => {
+ // Find the input element for this index and calculate position
+ const inputs = document.querySelectorAll('[class*="edit-speakers-modal"] input[placeholder="New name..."], .max-w-md input[placeholder="New name..."]');
+ if (inputs[index]) {
+ const rect = inputs[index].getBoundingClientRect();
+ return {
+ top: rect.bottom + 2 + 'px',
+ left: rect.left + 'px',
+ width: rect.width + 'px'
+ };
+ }
+ return { top: '0px', left: '0px', width: '200px' };
+ };
+
+ const saveEditingSpeakers = async () => {
+ const map = {};
+ editingSpeakersList.value.forEach(item => {
+ if (item.original && item.current) {
+ map[item.original] = item.current;
+ }
+ });
+
+ // Update ASR editor state if it's open
+ if (editingSegments.value.length > 0) {
+ // Build new list of available speakers
+ const newSpeakers = new Set();
+
+ // Apply renames to all segments
+ editingSegments.value.forEach(segment => {
+ if (map[segment.speaker]) {
+ segment.speaker = map[segment.speaker];
+ }
+ newSpeakers.add(segment.speaker);
+ });
+
+ // Add any newly added speakers from the modal
+ editingSpeakersList.value.forEach(item => {
+ if (!item.original && item.current) {
+ // This is a new speaker (no original)
+ newSpeakers.add(item.current);
+ }
+ });
+
+ // Update available speakers list
+ availableSpeakers.value = [...newSpeakers].sort();
+
+ // Update filtered speakers for all segments
+ editingSegments.value.forEach(segment => {
+ segment.filteredSpeakers = [...availableSpeakers.value];
+ });
+
+ closeEditSpeakersModal();
+ showToast('Speakers updated! Save the transcript to apply changes.', 'fa-check-circle');
+ } else {
+ // Regular flow for non-ASR editor context
+ speakerMap.value = map;
+ closeEditSpeakersModal();
+ await saveSpeakerNames();
+ }
+ };
+
+ // =========================================
+ // Edit Text Modal
+ // =========================================
+
+ const openEditTextModal = (segmentIndex) => {
+ if (!selectedRecording.value?.transcription) return;
+
+ try {
+ const transcriptionData = JSON.parse(selectedRecording.value.transcription);
+ if (transcriptionData && Array.isArray(transcriptionData) && transcriptionData[segmentIndex]) {
+ editingSegmentIndex.value = segmentIndex;
+ editedText.value = transcriptionData[segmentIndex].sentence || '';
+ showEditTextModal.value = true;
+ }
+ } catch (e) {
+ console.error('Error opening text editor:', e);
+ showToast('Error opening text editor', 'fa-exclamation-circle', 3000, 'error');
+ }
+ };
+
+ const closeEditTextModal = () => {
+ showEditTextModal.value = false;
+ editingSegmentIndex.value = null;
+ editedText.value = '';
+ };
+
+ const saveEditedText = async () => {
+ if (editingSegmentIndex.value === null || !selectedRecording.value?.transcription) return;
+
+ try {
+ const transcriptionData = JSON.parse(selectedRecording.value.transcription);
+ if (transcriptionData && Array.isArray(transcriptionData) && transcriptionData[editingSegmentIndex.value]) {
+ transcriptionData[editingSegmentIndex.value].sentence = editedText.value;
+ editedTranscriptData.value = transcriptionData;
+
+ // Update the recording's transcription temporarily for UI update
+ selectedRecording.value.transcription = JSON.stringify(transcriptionData);
+
+ closeEditTextModal();
+
+ // Immediately persist the change
+ showToast('Saving...', 'fa-spinner fa-spin');
+ await saveTranscriptImmediately(transcriptionData);
+ }
+ } catch (e) {
+ console.error('Error saving text:', e);
+ showToast('Error saving text', 'fa-exclamation-circle', 3000, 'error');
+ }
+ };
+
+ // =========================================
+ // Change Speaker in Segment
+ // =========================================
+
+ const openSpeakerChangeDropdown = (segmentIndex) => {
+ editingSpeakerIndex.value = editingSpeakerIndex.value === segmentIndex ? null : segmentIndex;
+ };
+
+ const changeSpeaker = async (segmentIndex, newSpeakerId) => {
+ if (!selectedRecording.value?.transcription) return;
+
+ try {
+ const transcriptionData = JSON.parse(selectedRecording.value.transcription);
+ if (transcriptionData && Array.isArray(transcriptionData) && transcriptionData[segmentIndex]) {
+ transcriptionData[segmentIndex].speaker = newSpeakerId;
+ editedTranscriptData.value = transcriptionData;
+
+ // Update the recording's transcription temporarily for UI update
+ selectedRecording.value.transcription = JSON.stringify(transcriptionData);
+
+ editingSpeakerIndex.value = null;
+
+ // Immediately persist the change
+ showToast('Saving...', 'fa-spinner fa-spin');
+ await saveTranscriptImmediately(transcriptionData);
+ }
+ } catch (e) {
+ console.error('Error changing speaker:', e);
+ showToast('Error changing speaker', 'fa-exclamation-circle', 3000, 'error');
+ }
+ };
+
+ return {
+ // Speaker modal
+ openSpeakerModal,
+ closeSpeakerModal,
+ saveSpeakerNames,
+
+ // Suggestions
+ loadVoiceSuggestions,
+ applyVoiceSuggestion,
+ handleIsMeChange,
+ shouldShowVoiceSuggestionPill,
+ searchSpeakers,
+ selectSpeakerSuggestion,
+ closeSpeakerSuggestionsOnClick,
+
+ // Navigation
+ findSpeakerGroups,
+ highlightSpeakerInTranscript,
+ navigateToNextSpeakerGroup,
+ navigateToPrevSpeakerGroup,
+ focusSpeaker,
+ blurSpeaker,
+ clearSpeakerHighlight,
+
+ // Auto-identify
+ autoIdentifySpeakers,
+
+ // Add speaker
+ openAddSpeakerModal,
+ closeAddSpeakerModal,
+ addNewSpeaker,
+ searchNewSpeaker,
+ selectNewSpeakerSuggestion,
+ hideNewSpeakerSuggestionsDelayed,
+
+ // Edit speakers modal
+ openEditSpeakersModal,
+ closeEditSpeakersModal,
+ addEditingSpeaker,
+ removeEditingSpeaker,
+ filterEditingSpeakerSuggestions,
+ selectEditingSpeakerSuggestion,
+ closeEditingSpeakerSuggestions,
+ onEditSpeakerBlur,
+ getEditSpeakerDropdownPosition,
+ saveEditingSpeakers,
+
+ // Edit text
+ openEditTextModal,
+ closeEditTextModal,
+ saveEditedText,
+
+ // Change speaker
+ openSpeakerChangeDropdown,
+ changeSpeaker
+ };
+}
diff --git a/static/js/modules/composables/tags.js b/static/js/modules/composables/tags.js
new file mode 100644
index 00000000..c8cb16f9
--- /dev/null
+++ b/static/js/modules/composables/tags.js
@@ -0,0 +1,174 @@
+/**
+ * Tags Management Composable
+ * Handles tag operations for recordings
+ */
+
+const { computed } = Vue;
+
+export function useTags({
+ recordings,
+ availableTags,
+ selectedRecording,
+ showEditTagsModal,
+ editingRecording,
+ tagSearchFilter,
+ showToast,
+ setGlobalError
+}) {
+ // State (using passed refs from parent)
+
+ // Computed
+ const getRecordingTags = (recording) => {
+ if (!recording || !recording.tags) return [];
+ return recording.tags;
+ };
+
+ const getAvailableTagsForRecording = (recording) => {
+ if (!recording || !availableTags.value) return [];
+ const recordingTagIds = getRecordingTags(recording).map(tag => tag.id);
+ return availableTags.value.filter(tag => !recordingTagIds.includes(tag.id));
+ };
+
+ const filteredAvailableTagsForModal = computed(() => {
+ if (!editingRecording.value) return [];
+ const availableTagsForRec = getAvailableTagsForRecording(editingRecording.value);
+ if (!tagSearchFilter.value) return availableTagsForRec;
+
+ const filter = tagSearchFilter.value.toLowerCase();
+ return availableTagsForRec.filter(tag =>
+ tag.name.toLowerCase().includes(filter)
+ );
+ });
+
+ // Methods
+ const editRecordingTags = (recording) => {
+ editingRecording.value = recording;
+ tagSearchFilter.value = '';
+ showEditTagsModal.value = true;
+ };
+
+ const closeEditTagsModal = () => {
+ showEditTagsModal.value = false;
+ editingRecording.value = null;
+ tagSearchFilter.value = '';
+ };
+
+ const addTagToRecording = async (tagId) => {
+ if (!tagId || !editingRecording.value) return;
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+
+ const response = await fetch(`/api/recordings/${editingRecording.value.id}/tags`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({ tag_id: tagId })
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(errorData.error || 'Failed to add tag');
+ }
+
+ // Update local recording data
+ const tagToAdd = availableTags.value.find(tag => tag.id == tagId);
+ if (tagToAdd) {
+ // Check if tag already exists to prevent duplicates
+ const tagExists = editingRecording.value.tags?.some(t => t.id === tagToAdd.id);
+ if (!tagExists) {
+ if (!editingRecording.value.tags) {
+ editingRecording.value.tags = [];
+ }
+ editingRecording.value.tags.push(tagToAdd);
+ }
+
+ // Also update in recordings list (only if different object)
+ const recordingInList = recordings.value.find(r => r.id === editingRecording.value.id);
+ if (recordingInList && recordingInList !== editingRecording.value) {
+ const tagExistsInList = recordingInList.tags?.some(t => t.id === tagToAdd.id);
+ if (!tagExistsInList) {
+ if (!recordingInList.tags) {
+ recordingInList.tags = [];
+ }
+ recordingInList.tags.push(tagToAdd);
+ }
+ }
+
+ // Update selectedRecording if it matches (only if different object)
+ if (selectedRecording.value &&
+ selectedRecording.value.id === editingRecording.value.id &&
+ selectedRecording.value !== editingRecording.value) {
+ const tagExistsInSelected = selectedRecording.value.tags?.some(t => t.id === tagToAdd.id);
+ if (!tagExistsInSelected) {
+ if (!selectedRecording.value.tags) {
+ selectedRecording.value.tags = [];
+ }
+ selectedRecording.value.tags.push(tagToAdd);
+ }
+ }
+ }
+
+ showToast('Tag added successfully', 'fa-check-circle', 2000, 'success');
+
+ } catch (error) {
+ console.error('Error adding tag to recording:', error);
+ setGlobalError(`Failed to add tag: ${error.message}`);
+ }
+ };
+
+ const removeTagFromRecording = async (tagId) => {
+ if (!editingRecording.value) return;
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+
+ const response = await fetch(`/api/recordings/${editingRecording.value.id}/tags/${tagId}`, {
+ method: 'DELETE',
+ headers: {
+ 'X-CSRFToken': csrfToken
+ }
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(errorData.error || 'Failed to remove tag');
+ }
+
+ // Update local recording data
+ editingRecording.value.tags = editingRecording.value.tags.filter(tag => tag.id !== tagId);
+
+ // Also update in recordings list
+ const recordingInList = recordings.value.find(r => r.id === editingRecording.value.id);
+ if (recordingInList && recordingInList !== editingRecording.value && recordingInList.tags) {
+ recordingInList.tags = recordingInList.tags.filter(tag => tag.id !== tagId);
+ }
+
+ // Update selectedRecording if it matches
+ if (selectedRecording.value && selectedRecording.value.id === editingRecording.value.id && selectedRecording.value.tags) {
+ selectedRecording.value.tags = selectedRecording.value.tags.filter(tag => tag.id !== tagId);
+ }
+
+ showToast('Tag removed successfully', 'fa-check-circle', 2000, 'success');
+
+ } catch (error) {
+ console.error('Error removing tag from recording:', error);
+ setGlobalError(`Failed to remove tag: ${error.message}`);
+ }
+ };
+
+ return {
+ // Computed
+ filteredAvailableTagsForModal,
+
+ // Methods
+ getRecordingTags,
+ getAvailableTagsForRecording,
+ editRecordingTags,
+ closeEditTagsModal,
+ addTagToRecording,
+ removeTagFromRecording
+ };
+}
diff --git a/static/js/modules/composables/transcription.js b/static/js/modules/composables/transcription.js
new file mode 100644
index 00000000..f594918b
--- /dev/null
+++ b/static/js/modules/composables/transcription.js
@@ -0,0 +1,434 @@
+/**
+ * Transcription editing composable
+ * Handles ASR editor, text editor, and segment management
+ */
+
+export function useTranscription(state, utils) {
+ const {
+ showTextEditorModal, showAsrEditorModal, selectedRecording,
+ editingTranscriptionContent, editingSegments, availableSpeakers,
+ recordings, dropdownPositions
+ } = state;
+
+ const { showToast, setGlobalError, nextTick } = utils;
+
+ // =========================================
+ // Text Editor Modal
+ // =========================================
+
+ const openTranscriptionEditor = () => {
+ if (!selectedRecording.value || !selectedRecording.value.transcription) {
+ return;
+ }
+
+ // Check if transcription is JSON (ASR format)
+ try {
+ const parsed = JSON.parse(selectedRecording.value.transcription);
+ if (Array.isArray(parsed)) {
+ openAsrEditorModal();
+ } else {
+ openTextEditorModal();
+ }
+ } catch (e) {
+ // Not JSON, use text editor
+ openTextEditorModal();
+ }
+ };
+
+ const openTextEditorModal = () => {
+ if (!selectedRecording.value) return;
+ editingTranscriptionContent.value = selectedRecording.value.transcription || '';
+ showTextEditorModal.value = true;
+ };
+
+ const closeTextEditorModal = () => {
+ showTextEditorModal.value = false;
+ editingTranscriptionContent.value = '';
+ };
+
+ const saveTranscription = async () => {
+ if (!selectedRecording.value) return;
+ await saveTranscriptionContent(editingTranscriptionContent.value);
+ closeTextEditorModal();
+ };
+
+ // =========================================
+ // ASR Editor Modal
+ // =========================================
+
+ const openAsrEditorModal = async () => {
+ if (!selectedRecording.value) return;
+ try {
+ const segments = JSON.parse(selectedRecording.value.transcription);
+
+ // Populate available speakers from THIS recording only
+ const speakersInTranscript = [...new Set(segments.map(s => s.speaker))].sort();
+ availableSpeakers.value = speakersInTranscript;
+
+ editingSegments.value = segments.map((s, i) => ({
+ ...s,
+ id: i,
+ showSuggestions: false,
+ filteredSpeakers: [...speakersInTranscript]
+ }));
+
+ showAsrEditorModal.value = true;
+ } catch (e) {
+ console.error("Could not parse transcription as JSON for ASR editor:", e);
+ setGlobalError("This transcription is not in the correct format for the ASR editor.");
+ }
+ };
+
+ const closeAsrEditorModal = () => {
+ showAsrEditorModal.value = false;
+ editingSegments.value = [];
+ };
+
+ const saveAsrTranscription = async () => {
+ if (!selectedRecording.value) return;
+
+ // Remove extra UI fields and save the rest
+ const contentToSave = JSON.stringify(editingSegments.value.map(({ id, showSuggestions, filteredSpeakers, ...rest }) => rest));
+
+ await saveTranscriptionContent(contentToSave);
+ closeAsrEditorModal();
+ };
+
+ // =========================================
+ // Segment Management
+ // =========================================
+
+ const adjustTime = (index, field, amount) => {
+ if (editingSegments.value[index]) {
+ editingSegments.value[index][field] = Math.max(0,
+ editingSegments.value[index][field] + amount
+ );
+ }
+ };
+
+ const filterSpeakers = (index) => {
+ const segment = editingSegments.value[index];
+ if (segment) {
+ const query = segment.speaker?.toLowerCase() || '';
+ if (query === '') {
+ segment.filteredSpeakers = [...availableSpeakers.value];
+ } else {
+ segment.filteredSpeakers = availableSpeakers.value.filter(
+ speaker => speaker.toLowerCase().includes(query)
+ );
+ }
+ }
+ };
+
+ const openSpeakerSuggestions = (index) => {
+ if (editingSegments.value[index]) {
+ // Close other dropdowns
+ editingSegments.value.forEach((seg, i) => {
+ if (i !== index) seg.showSuggestions = false;
+ });
+
+ editingSegments.value[index].showSuggestions = true;
+ filterSpeakers(index);
+ updateDropdownPosition(index);
+ }
+ };
+
+ const closeSpeakerSuggestions = (index) => {
+ if (editingSegments.value[index]) {
+ editingSegments.value[index].showSuggestions = false;
+ }
+ };
+
+ const closeAllSpeakerSuggestions = () => {
+ editingSegments.value.forEach(seg => {
+ seg.showSuggestions = false;
+ });
+ };
+
+ const getDropdownPosition = (index) => {
+ const pos = dropdownPositions.value[index];
+ if (pos) {
+ const style = {
+ left: pos.left + 'px',
+ width: pos.width + 'px'
+ };
+
+ // When opening upward, anchor from bottom so dropdown grows upward
+ if (pos.openUpward) {
+ style.bottom = pos.bottom + 'px';
+ style.top = 'auto';
+ } else {
+ style.top = pos.top + 'px';
+ style.bottom = 'auto';
+ }
+
+ // Apply calculated max height
+ if (pos.maxHeight) {
+ style.maxHeight = pos.maxHeight + 'px';
+ }
+ return style;
+ }
+ return { top: '0px', left: '0px' };
+ };
+
+ const updateDropdownPosition = (index) => {
+ nextTick(() => {
+ const rows = document.querySelectorAll('.asr-editor-table tbody tr');
+ if (rows[index]) {
+ const cell = rows[index].querySelector('td:first-child');
+ if (cell) {
+ const rect = cell.getBoundingClientRect();
+ const viewportHeight = window.innerHeight;
+
+ // Calculate available space above and below
+ const spaceBelow = viewportHeight - rect.bottom - 10;
+ const spaceAbove = rect.top - 10;
+
+ // Determine max height based on available space (cap at 192px which is max-h-48)
+ const maxDropdownHeight = 192;
+
+ let top, bottom, openUpward, maxHeight;
+
+ if (spaceBelow >= maxDropdownHeight || spaceBelow >= spaceAbove) {
+ // Open downward
+ top = rect.bottom + 2;
+ bottom = null;
+ openUpward = false;
+ maxHeight = Math.min(spaceBelow, maxDropdownHeight);
+ } else {
+ // Open upward - anchor from bottom so dropdown grows upward
+ openUpward = true;
+ maxHeight = Math.min(spaceAbove, maxDropdownHeight);
+ // Bottom is distance from viewport bottom to the top of the cell
+ bottom = viewportHeight - rect.top + 2;
+ top = null;
+ }
+
+ dropdownPositions.value[index] = {
+ top: top,
+ bottom: bottom,
+ left: rect.left,
+ width: rect.width,
+ openUpward: openUpward,
+ maxHeight: maxHeight
+ };
+ }
+ }
+ });
+ };
+
+ const selectSpeaker = (index, speaker) => {
+ if (editingSegments.value[index]) {
+ editingSegments.value[index].speaker = speaker;
+ closeSpeakerSuggestions(index);
+ }
+ };
+
+ const addSegment = () => {
+ const lastSegment = editingSegments.value[editingSegments.value.length - 1];
+ const newStart = lastSegment ? lastSegment.end_time : 0;
+
+ editingSegments.value.push({
+ speaker: availableSpeakers.value[0] || 'Speaker 1',
+ start_time: newStart,
+ end_time: newStart + 5,
+ sentence: '',
+ id: editingSegments.value.length,
+ showSuggestions: false,
+ filteredSpeakers: [...availableSpeakers.value]
+ });
+ };
+
+ const removeSegment = (index) => {
+ editingSegments.value.splice(index, 1);
+ // Re-index segments
+ editingSegments.value.forEach((seg, i) => {
+ seg.id = i;
+ });
+ };
+
+ const addSegmentBelow = (index) => {
+ const currentSegment = editingSegments.value[index];
+ const nextSegment = editingSegments.value[index + 1];
+
+ const newStart = currentSegment.end_time;
+ const newEnd = nextSegment ? nextSegment.start_time : newStart + 5;
+
+ editingSegments.value.splice(index + 1, 0, {
+ speaker: currentSegment.speaker,
+ start_time: newStart,
+ end_time: newEnd,
+ sentence: '',
+ id: index + 1,
+ showSuggestions: false,
+ filteredSpeakers: [...availableSpeakers.value]
+ });
+
+ // Re-index segments
+ editingSegments.value.forEach((seg, i) => {
+ seg.id = i;
+ });
+ };
+
+ const seekToSegmentTime = (time) => {
+ // Find audio elements and use the one in a visible modal (z-50)
+ const audioElements = document.querySelectorAll('.fixed.z-50 audio');
+ const audioElement = audioElements.length > 0 ? audioElements[audioElements.length - 1] : null;
+ if (audioElement) {
+ audioElement.currentTime = time;
+ audioElement.play();
+ }
+ };
+
+ const autoResizeTextarea = (event) => {
+ const textarea = event.target;
+ textarea.style.height = 'auto';
+ textarea.style.height = textarea.scrollHeight + 'px';
+ };
+
+ // =========================================
+ // Save Transcription Content
+ // =========================================
+
+ const saveTranscriptionContent = async (content) => {
+ if (!selectedRecording.value) return;
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await fetch(`/recording/${selectedRecording.value.id}/update_transcription`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({ transcription: content })
+ });
+
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to update transcription');
+
+ // Update recording
+ selectedRecording.value.transcription = content;
+
+ const index = recordings.value.findIndex(r => r.id === selectedRecording.value.id);
+ if (index !== -1) {
+ recordings.value[index].transcription = content;
+ }
+
+ showToast('Transcription updated successfully!', 'fa-check-circle');
+ } catch (error) {
+ setGlobalError(`Failed to save transcription: ${error.message}`);
+ }
+ };
+
+ // =========================================
+ // Save Summary
+ // =========================================
+
+ const saveSummary = async (summary) => {
+ if (!selectedRecording.value) return;
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const payload = {
+ id: selectedRecording.value.id,
+ title: selectedRecording.value.title,
+ participants: selectedRecording.value.participants,
+ notes: selectedRecording.value.notes,
+ summary: summary,
+ meeting_date: selectedRecording.value.meeting_date
+ };
+ const response = await fetch('/save', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify(payload)
+ });
+
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to update summary');
+
+ // Update recording
+ selectedRecording.value.summary = summary;
+
+ const index = recordings.value.findIndex(r => r.id === selectedRecording.value.id);
+ if (index !== -1) {
+ recordings.value[index].summary = summary;
+ }
+
+ showToast('Summary saved!', 'fa-check-circle');
+ } catch (error) {
+ setGlobalError(`Failed to save summary: ${error.message}`);
+ }
+ };
+
+ // =========================================
+ // Save Notes
+ // =========================================
+
+ const saveNotes = async (notes) => {
+ if (!selectedRecording.value) return;
+
+ try {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await fetch(`/api/recordings/${selectedRecording.value.id}`, {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({ notes })
+ });
+
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to update notes');
+
+ // Update recording
+ selectedRecording.value.notes = notes;
+
+ const index = recordings.value.findIndex(r => r.id === selectedRecording.value.id);
+ if (index !== -1) {
+ recordings.value[index].notes = notes;
+ }
+
+ showToast('Notes saved!', 'fa-check-circle');
+ } catch (error) {
+ setGlobalError(`Failed to save notes: ${error.message}`);
+ }
+ };
+
+ return {
+ // Text editor
+ openTranscriptionEditor,
+ openTextEditorModal,
+ closeTextEditorModal,
+ saveTranscription,
+
+ // ASR editor
+ openAsrEditorModal,
+ closeAsrEditorModal,
+ saveAsrTranscription,
+
+ // Segment management
+ adjustTime,
+ filterSpeakers,
+ openSpeakerSuggestions,
+ closeSpeakerSuggestions,
+ closeAllSpeakerSuggestions,
+ getDropdownPosition,
+ updateDropdownPosition,
+ selectSpeaker,
+ addSegment,
+ removeSegment,
+ addSegmentBelow,
+ seekToSegmentTime,
+ autoResizeTextarea,
+
+ // Save
+ saveTranscriptionContent,
+ saveSummary,
+ saveNotes
+ };
+}
diff --git a/static/js/modules/composables/ui.js b/static/js/modules/composables/ui.js
new file mode 100644
index 00000000..9eba3558
--- /dev/null
+++ b/static/js/modules/composables/ui.js
@@ -0,0 +1,1537 @@
+/**
+ * UI management composable
+ * Handles dark mode, color schemes, sidebar, and other UI state
+ */
+
+export function useUI(state, utils, processedTranscription) {
+ const {
+ isDarkMode, currentColorScheme, colorSchemes, isSidebarCollapsed,
+ showColorSchemeModal, isUserMenuOpen, currentView, selectedRecording,
+ windowWidth, isMobileScreen, showAdvancedFilters, showSortOptions,
+ searchTipsExpanded, isMetadataExpanded, editingParticipants, editingMeetingDate,
+ editingSummary, tempSummaryContent, summaryMarkdownEditorInstance,
+ leftColumnWidth, rightColumnWidth, isResizing, playerVolume,
+ editingNotes, tempNotesContent, transcriptionViewMode,
+ notesMarkdownEditor, markdownEditorInstance, autoSaveTimer, csrfToken,
+ summaryMarkdownEditor, recordingNotesEditor, recordingMarkdownEditorInstance,
+ recordingNotes, showDownloadMenu, currentPlayingSegmentIndex, followPlayerMode
+ } = state;
+
+ const autoSaveDelay = 2000; // 2 seconds
+
+ const { showToast, nextTick, t } = utils;
+ const { computed, watch } = Vue;
+
+ // isMobile computed
+ const isMobile = computed(() => windowWidth.value < 768);
+
+ // Toggle dark mode
+ const toggleDarkMode = () => {
+ isDarkMode.value = !isDarkMode.value;
+ localStorage.setItem('darkMode', isDarkMode.value);
+
+ if (isDarkMode.value) {
+ document.documentElement.classList.add('dark');
+ } else {
+ document.documentElement.classList.remove('dark');
+ }
+
+ // Re-apply current color scheme for new mode
+ applyColorScheme(currentColorScheme.value);
+ };
+
+ // Initialize dark mode from storage
+ const initializeDarkMode = () => {
+ const savedMode = localStorage.getItem('darkMode');
+ if (savedMode !== null) {
+ isDarkMode.value = savedMode === 'true';
+ } else {
+ // Check system preference
+ isDarkMode.value = window.matchMedia('(prefers-color-scheme: dark)').matches;
+ }
+
+ if (isDarkMode.value) {
+ document.documentElement.classList.add('dark');
+ } else {
+ document.documentElement.classList.remove('dark');
+ }
+ };
+
+ // Apply a color scheme
+ const applyColorScheme = (schemeId, mode = null) => {
+ const targetMode = mode || (isDarkMode.value ? 'dark' : 'light');
+ const scheme = colorSchemes[targetMode].find(s => s.id === schemeId);
+
+ if (!scheme) {
+ console.warn(`Color scheme '${schemeId}' not found for mode '${targetMode}'`);
+ return;
+ }
+
+ // Remove all theme classes
+ const allThemeClasses = [
+ ...colorSchemes.light.map(s => s.class),
+ ...colorSchemes.dark.map(s => s.class)
+ ].filter(c => c !== '');
+
+ document.documentElement.classList.remove(...allThemeClasses);
+
+ // Add new theme class if not default
+ if (scheme.class) {
+ document.documentElement.classList.add(scheme.class);
+ }
+
+ currentColorScheme.value = schemeId;
+ localStorage.setItem('colorScheme', schemeId);
+ };
+
+ // Initialize color scheme from storage
+ const initializeColorScheme = () => {
+ const savedScheme = localStorage.getItem('colorScheme');
+ if (savedScheme) {
+ applyColorScheme(savedScheme);
+ } else {
+ // Apply default scheme
+ applyColorScheme('blue');
+ }
+ };
+
+ // Open color scheme modal
+ const openColorSchemeModal = () => {
+ showColorSchemeModal.value = true;
+ isUserMenuOpen.value = false;
+ };
+
+ // Close color scheme modal
+ const closeColorSchemeModal = () => {
+ showColorSchemeModal.value = false;
+ };
+
+ // Select a color scheme
+ const selectColorScheme = (schemeId) => {
+ applyColorScheme(schemeId);
+ showToast('Color scheme applied', 'fa-palette');
+ };
+
+ // Reset to default color scheme
+ const resetColorScheme = () => {
+ applyColorScheme('blue');
+ showToast('Color scheme reset to default', 'fa-undo');
+ };
+
+ // Toggle sidebar
+ const toggleSidebar = () => {
+ isSidebarCollapsed.value = !isSidebarCollapsed.value;
+ localStorage.setItem('sidebarCollapsed', isSidebarCollapsed.value);
+ };
+
+ // Initialize sidebar state
+ const initializeSidebar = () => {
+ const saved = localStorage.getItem('sidebarCollapsed');
+ if (saved !== null) {
+ isSidebarCollapsed.value = saved === 'true';
+ }
+ };
+
+ // Switch to upload view
+ const switchToUploadView = () => {
+ currentView.value = 'upload';
+ if (isMobileScreen.value) {
+ isSidebarCollapsed.value = true;
+ }
+ };
+
+ // Switch to detail view
+ const switchToDetailView = () => {
+ currentView.value = 'detail';
+ };
+
+ // Switch to recording view
+ const switchToRecordingView = () => {
+ currentView.value = 'recording';
+ if (isMobileScreen.value) {
+ isSidebarCollapsed.value = true;
+ }
+ };
+
+ // Set global error
+ const setGlobalError = (message, duration = 7000) => {
+ if (state.globalError) {
+ state.globalError.value = message;
+ if (duration > 0) {
+ setTimeout(() => {
+ if (state.globalError.value === message) {
+ state.globalError.value = null;
+ }
+ }, duration);
+ }
+ }
+ };
+
+ // Format file size
+ const formatFileSize = (bytes) => {
+ if (!bytes) return '0 B';
+ const k = 1024;
+ const sizes = ['B', 'KB', 'MB', 'GB'];
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
+ };
+
+ // Format display date
+ const formatDisplayDate = (dateString) => {
+ if (!dateString) return '';
+ const date = new Date(dateString);
+ return date.toLocaleDateString(undefined, {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
+ hour: '2-digit',
+ minute: '2-digit'
+ });
+ };
+
+ // Format short date
+ const formatShortDate = (dateString) => {
+ if (!dateString) return '';
+ const date = new Date(dateString);
+ const now = new Date();
+ const diff = now - date;
+ const oneDay = 24 * 60 * 60 * 1000;
+
+ if (diff < oneDay) {
+ return date.toLocaleTimeString(undefined, {
+ hour: '2-digit',
+ minute: '2-digit'
+ });
+ } else if (diff < 7 * oneDay) {
+ return date.toLocaleDateString(undefined, {
+ weekday: 'short'
+ });
+ } else {
+ return date.toLocaleDateString(undefined, {
+ month: 'short',
+ day: 'numeric'
+ });
+ }
+ };
+
+ // Format status
+ const formatStatus = (status) => {
+ if (!status || status === 'COMPLETED') return '';
+ const statusMap = {
+ 'PENDING': t('status.queued'),
+ 'PROCESSING': t('status.processing'),
+ 'TRANSCRIBING': t('status.transcribing'),
+ 'SUMMARIZING': t('status.summarizing'),
+ 'FAILED': t('status.failed'),
+ 'UPLOADING': t('status.uploading')
+ };
+ return statusMap[status] || status.charAt(0).toUpperCase() + status.slice(1).toLowerCase();
+ };
+
+ // Get status class
+ const getStatusClass = (status) => {
+ switch(status) {
+ case 'PENDING': return 'status-pending';
+ case 'PROCESSING': return 'status-processing';
+ case 'SUMMARIZING': return 'status-summarizing';
+ case 'COMPLETED': return '';
+ case 'FAILED': return 'status-failed';
+ default: return 'status-pending';
+ }
+ };
+
+ // Format time (seconds to HH:MM:SS)
+ const formatTime = (seconds) => {
+ if (!seconds && seconds !== 0) return '00:00';
+ const h = Math.floor(seconds / 3600);
+ const m = Math.floor((seconds % 3600) / 60);
+ const s = Math.floor(seconds % 60);
+
+ if (h > 0) {
+ return `${h}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
+ }
+ return `${m}:${s.toString().padStart(2, '0')}`;
+ };
+
+ // Format duration in seconds to human readable
+ const formatDuration = (seconds) => {
+ if (!seconds && seconds !== 0) return '';
+
+ const h = Math.floor(seconds / 3600);
+ const m = Math.floor((seconds % 3600) / 60);
+ const s = Math.floor(seconds % 60);
+
+ const parts = [];
+ if (h > 0) parts.push(`${h}h`);
+ if (m > 0) parts.push(`${m}m`);
+ if (s > 0 || parts.length === 0) parts.push(`${s}s`);
+
+ return parts.join(' ');
+ };
+
+ // Format processing duration
+ const formatProcessingDuration = (seconds) => {
+ if (!seconds) return '';
+ if (seconds < 60) {
+ return `${Math.round(seconds)}s`;
+ } else if (seconds < 3600) {
+ const m = Math.floor(seconds / 60);
+ const s = Math.round(seconds % 60);
+ return `${m}m ${s}s`;
+ } else {
+ const h = Math.floor(seconds / 3600);
+ const m = Math.round((seconds % 3600) / 60);
+ return `${h}h ${m}m`;
+ }
+ };
+
+ // --- Inline Editing ---
+ const saveInlineEdit = async (field) => {
+ if (!selectedRecording.value) return;
+
+ const fullPayload = {
+ id: selectedRecording.value.id,
+ title: selectedRecording.value.title,
+ participants: selectedRecording.value.participants,
+ notes: selectedRecording.value.notes,
+ summary: selectedRecording.value.summary,
+ meeting_date: selectedRecording.value.meeting_date
+ };
+
+ try {
+ const csrfTokenValue = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const response = await fetch('/save', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfTokenValue
+ },
+ body: JSON.stringify(fullPayload)
+ });
+
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to save metadata');
+
+ // Update the recording with returned HTML
+ if (data.recording) {
+ if (field === 'notes' && data.recording.notes_html) {
+ selectedRecording.value.notes_html = data.recording.notes_html;
+ } else if (field === 'summary' && data.recording.summary_html) {
+ selectedRecording.value.summary_html = data.recording.summary_html;
+ }
+ }
+ } catch (error) {
+ showToast(`Failed to save: ${error.message}`, 'fa-exclamation-circle', 3000, 'error');
+ }
+ };
+
+ const toggleEditParticipants = () => {
+ editingParticipants.value = !editingParticipants.value;
+ if (!editingParticipants.value) {
+ saveInlineEdit('participants');
+ }
+ };
+
+ const toggleEditMeetingDate = () => {
+ editingMeetingDate.value = !editingMeetingDate.value;
+ if (!editingMeetingDate.value) {
+ saveInlineEdit('meeting_date');
+ }
+ };
+
+ const toggleEditTitle = () => {
+ if (!selectedRecording.value) return;
+
+ // Check if user has permission to edit
+ if (selectedRecording.value.can_edit === false) {
+ showToast('You do not have permission to edit this recording', 'fa-exclamation-circle', 3000, 'error');
+ return;
+ }
+
+ if (!state.editingTitle.value) {
+ // Start editing
+ state.originalTitle.value = selectedRecording.value.title || '';
+ state.editingTitle.value = true;
+ nextTick(() => {
+ // Focus the input field
+ const titleInput = document.querySelector('input[ref="titleInput"]');
+ if (titleInput) {
+ titleInput.focus();
+ titleInput.select();
+ }
+ });
+ }
+ };
+
+ const saveTitle = async () => {
+ if (!selectedRecording.value) return;
+
+ state.editingTitle.value = false;
+
+ // Only save if title changed
+ if (selectedRecording.value.title !== state.originalTitle.value) {
+ await saveInlineEdit('title');
+ }
+ };
+
+ const cancelEditTitle = () => {
+ if (!selectedRecording.value) return;
+
+ // Restore original title
+ selectedRecording.value.title = state.originalTitle.value;
+ state.editingTitle.value = false;
+ };
+
+ const toggleEditSummary = () => {
+ editingSummary.value = !editingSummary.value;
+ if (editingSummary.value) {
+ tempSummaryContent.value = selectedRecording.value?.summary || '';
+ nextTick(() => {
+ initializeSummaryMarkdownEditor();
+ });
+ }
+ };
+
+ const cancelEditSummary = () => {
+ if (summaryMarkdownEditorInstance.value) {
+ summaryMarkdownEditorInstance.value.toTextArea();
+ summaryMarkdownEditorInstance.value = null;
+ }
+ editingSummary.value = false;
+ // Restore original content
+ if (selectedRecording.value) {
+ selectedRecording.value.summary = tempSummaryContent.value;
+ }
+ };
+
+ const saveEditSummary = async () => {
+ if (summaryMarkdownEditorInstance.value) {
+ selectedRecording.value.summary = summaryMarkdownEditorInstance.value.value();
+ summaryMarkdownEditorInstance.value.toTextArea();
+ summaryMarkdownEditorInstance.value = null;
+ }
+ editingSummary.value = false;
+ await saveInlineEdit('summary');
+ };
+
+ const initializeSummaryMarkdownEditor = () => {
+ if (!summaryMarkdownEditor.value) return;
+
+ try {
+ summaryMarkdownEditorInstance.value = new EasyMDE({
+ element: summaryMarkdownEditor.value,
+ spellChecker: false,
+ autofocus: true,
+ placeholder: "Enter summary in Markdown format...",
+ initialValue: selectedRecording.value?.summary || '',
+ status: false,
+ toolbar: [
+ "bold", "italic", "heading", "|",
+ "quote", "unordered-list", "ordered-list", "|",
+ "link", "image", "|",
+ "preview", "side-by-side", "fullscreen"
+ ],
+ previewClass: ["editor-preview", "notes-preview"],
+ theme: isDarkMode.value ? "dark" : "light"
+ });
+
+ // Add auto-save functionality
+ summaryMarkdownEditorInstance.value.codemirror.on('change', () => {
+ if (autoSaveTimer.value) {
+ clearTimeout(autoSaveTimer.value);
+ }
+ autoSaveTimer.value = setTimeout(() => {
+ autoSaveSummary();
+ }, autoSaveDelay);
+ });
+ } catch (error) {
+ console.error('Failed to initialize summary markdown editor:', error);
+ editingSummary.value = true;
+ }
+ };
+
+ const autoSaveSummary = async () => {
+ if (summaryMarkdownEditorInstance.value && editingSummary.value) {
+ // Just save the content to the model, don't exit edit mode
+ selectedRecording.value.summary = summaryMarkdownEditorInstance.value.value();
+ // Silently save to backend without changing UI state
+ try {
+ const payload = {
+ id: selectedRecording.value.id,
+ title: selectedRecording.value.title,
+ participants: selectedRecording.value.participants,
+ notes: selectedRecording.value.notes,
+ summary: selectedRecording.value.summary,
+ meeting_date: selectedRecording.value.meeting_date
+ };
+ const response = await fetch('/save', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken.value
+ },
+ body: JSON.stringify(payload)
+ });
+ const data = await response.json();
+ if (response.ok && data.recording) {
+ // Update the HTML rendered versions if they exist
+ if (data.recording.summary_html) {
+ selectedRecording.value.summary_html = data.recording.summary_html;
+ }
+ } else {
+ console.error('Failed to auto-save summary');
+ }
+ } catch (error) {
+ console.error('Error auto-saving summary:', error);
+ }
+ }
+ };
+
+ const toggleTranscriptionViewMode = () => {
+ transcriptionViewMode.value = transcriptionViewMode.value === 'simple' ? 'bubble' : 'simple';
+ localStorage.setItem('transcriptionViewMode', transcriptionViewMode.value);
+ };
+
+ const toggleEditNotes = () => {
+ editingNotes.value = !editingNotes.value;
+ if (editingNotes.value) {
+ tempNotesContent.value = selectedRecording.value?.notes || '';
+ // Initialize markdown editor when entering edit mode
+ nextTick(() => {
+ initializeMarkdownEditor();
+ });
+ }
+ };
+
+ const cancelEditNotes = () => {
+ if (markdownEditorInstance.value) {
+ markdownEditorInstance.value.toTextArea();
+ markdownEditorInstance.value = null;
+ }
+ editingNotes.value = false;
+ // Restore original content
+ if (selectedRecording.value) {
+ selectedRecording.value.notes = tempNotesContent.value;
+ }
+ };
+
+ const saveEditNotes = async () => {
+ if (markdownEditorInstance.value) {
+ // Get the markdown content from the editor
+ selectedRecording.value.notes = markdownEditorInstance.value.value();
+ markdownEditorInstance.value.toTextArea();
+ markdownEditorInstance.value = null;
+ }
+ editingNotes.value = false;
+ await saveInlineEdit('notes');
+ };
+
+ const initializeMarkdownEditor = () => {
+ if (!notesMarkdownEditor.value) return;
+
+ try {
+ markdownEditorInstance.value = new EasyMDE({
+ element: notesMarkdownEditor.value,
+ spellChecker: false,
+ autofocus: true,
+ placeholder: "Enter notes in Markdown format...",
+ initialValue: selectedRecording.value?.notes || '',
+ status: false,
+ toolbar: [
+ "bold", "italic", "heading", "|",
+ "quote", "unordered-list", "ordered-list", "|",
+ "link", "image", "|",
+ "preview", "side-by-side", "fullscreen"
+ ],
+ previewClass: ["editor-preview", "notes-preview"],
+ theme: isDarkMode.value ? "dark" : "light"
+ });
+
+ // Add auto-save functionality
+ markdownEditorInstance.value.codemirror.on('change', () => {
+ if (autoSaveTimer.value) {
+ clearTimeout(autoSaveTimer.value);
+ }
+ autoSaveTimer.value = setTimeout(() => {
+ autoSaveNotes();
+ }, autoSaveDelay);
+ });
+ } catch (error) {
+ console.error('Failed to initialize markdown editor:', error);
+ // Fallback to regular textarea editing
+ editingNotes.value = true;
+ }
+ };
+
+ const autoSaveNotes = async () => {
+ if (markdownEditorInstance.value && editingNotes.value) {
+ // Just save the content to the model, don't exit edit mode
+ selectedRecording.value.notes = markdownEditorInstance.value.value();
+ // Silently save to backend without changing UI state
+ try {
+ const payload = {
+ id: selectedRecording.value.id,
+ title: selectedRecording.value.title,
+ participants: selectedRecording.value.participants,
+ notes: selectedRecording.value.notes,
+ summary: selectedRecording.value.summary,
+ meeting_date: selectedRecording.value.meeting_date
+ };
+ const response = await fetch('/save', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken.value
+ },
+ body: JSON.stringify(payload)
+ });
+ const data = await response.json();
+ if (response.ok && data.recording) {
+ // Update the HTML rendered versions if they exist
+ if (data.recording.notes_html) {
+ selectedRecording.value.notes_html = data.recording.notes_html;
+ }
+ } else {
+ console.error('Failed to auto-save notes');
+ }
+ } catch (error) {
+ console.error('Error auto-saving notes:', error);
+ }
+ }
+ };
+
+ const clickToEditNotes = () => {
+ // Allow clicking on empty notes area to start editing
+ if (!editingNotes.value && (!selectedRecording.value?.notes || selectedRecording.value.notes.trim() === '')) {
+ toggleEditNotes();
+ }
+ };
+
+ const clickToEditSummary = () => {
+ // Allow clicking on empty summary area to start editing
+ if (!editingSummary.value && (!selectedRecording.value?.summary || selectedRecording.value.summary.trim() === '')) {
+ toggleEditSummary();
+ }
+ };
+
+ const downloadNotes = async () => {
+ if (!selectedRecording.value || !selectedRecording.value.notes) {
+ showToast('No notes available to download.', 'fa-exclamation-circle');
+ return;
+ }
+
+ try {
+ const response = await fetch(`/recording/${selectedRecording.value.id}/download/notes`);
+ if (!response.ok) {
+ const error = await response.json();
+ showToast(error.error || 'Failed to download notes', 'fa-exclamation-circle');
+ return;
+ }
+
+ // Create blob and download
+ const blob = await response.blob();
+ const url = window.URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `${selectedRecording.value.title || 'notes'}.md`;
+ document.body.appendChild(a);
+ a.click();
+ window.URL.revokeObjectURL(url);
+ document.body.removeChild(a);
+
+ showToast('Notes downloaded successfully!');
+ } catch (error) {
+ showToast('Failed to download notes', 'fa-exclamation-circle');
+ }
+ };
+
+ const downloadEventICS = async (event) => {
+ if (!event || !event.id) {
+ showToast('Invalid event data', 'fa-exclamation-circle');
+ return;
+ }
+
+ try {
+ const response = await fetch(`/api/event/${event.id}/ics`);
+ if (!response.ok) {
+ const error = await response.json();
+ showToast(error.error || 'Failed to download event', 'fa-exclamation-circle');
+ return;
+ }
+
+ // Create blob and download
+ const blob = await response.blob();
+ const url = window.URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.style.display = 'none';
+ a.href = url;
+ a.download = `${event.title || 'event'}.ics`;
+ document.body.appendChild(a);
+ a.click();
+ window.URL.revokeObjectURL(url);
+ document.body.removeChild(a);
+
+ showToast(`Event "${event.title}" downloaded. Open the file to add to your calendar.`, 'fa-calendar-check', 3000);
+ } catch (error) {
+ console.error('Download failed:', error);
+ showToast('Failed to download event', 'fa-exclamation-circle');
+ }
+ };
+
+ const downloadICS = async () => {
+ if (!selectedRecording.value || !selectedRecording.value.events || selectedRecording.value.events.length === 0) {
+ showToast('No events to export', 'fa-exclamation-circle');
+ return;
+ }
+
+ try {
+ const response = await fetch(`/api/recording/${selectedRecording.value.id}/events/ics`);
+ if (!response.ok) {
+ const error = await response.json();
+ showToast(error.error || 'Failed to export events', 'fa-exclamation-circle');
+ return;
+ }
+
+ // Create blob and download
+ const blob = await response.blob();
+ const url = window.URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.style.display = 'none';
+ a.href = url;
+ a.download = `events-${selectedRecording.value.title || selectedRecording.value.id}.ics`;
+ document.body.appendChild(a);
+ a.click();
+ window.URL.revokeObjectURL(url);
+ document.body.removeChild(a);
+
+ showToast(`Exported ${selectedRecording.value.events.length} events`, 'fa-calendar-check');
+ } catch (error) {
+ console.error('Download all events ICS error:', error);
+ showToast('Failed to export events', 'fa-exclamation-circle');
+ }
+ };
+
+ const formatEventDateTime = (dateTimeStr) => {
+ if (!dateTimeStr) return '';
+ try {
+ const date = new Date(dateTimeStr);
+ const options = {
+ weekday: 'short',
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
+ hour: '2-digit',
+ minute: '2-digit'
+ };
+ return date.toLocaleString(undefined, options);
+ } catch (e) {
+ return dateTimeStr;
+ }
+ };
+
+ // --- Column Resizing ---
+ const startColumnResize = (event) => {
+ isResizing.value = true;
+ const startX = event.clientX;
+ const startLeftWidth = leftColumnWidth.value;
+
+ const handleMouseMove = (e) => {
+ if (!isResizing.value) return;
+
+ const container = document.getElementById('mainContentColumns');
+ if (!container) return;
+
+ const containerRect = container.getBoundingClientRect();
+ const deltaX = e.clientX - startX;
+ const containerWidth = containerRect.width;
+ const deltaPercent = (deltaX / containerWidth) * 100;
+
+ let newLeftWidth = startLeftWidth + deltaPercent;
+ newLeftWidth = Math.max(20, Math.min(80, newLeftWidth));
+
+ leftColumnWidth.value = newLeftWidth;
+ rightColumnWidth.value = 100 - newLeftWidth;
+ };
+
+ const handleMouseUp = () => {
+ isResizing.value = false;
+ document.removeEventListener('mousemove', handleMouseMove);
+ document.removeEventListener('mouseup', handleMouseUp);
+
+ localStorage.setItem('transcriptColumnWidth', leftColumnWidth.value);
+ localStorage.setItem('summaryColumnWidth', rightColumnWidth.value);
+ };
+
+ document.addEventListener('mousemove', handleMouseMove);
+ document.addEventListener('mouseup', handleMouseUp);
+ event.preventDefault();
+ };
+
+ // --- Audio Player ---
+ const seekAudio = (time, context = 'main') => {
+ let audioPlayer = null;
+ if (context === 'modal') {
+ audioPlayer = document.querySelector('audio.speaker-modal-transcript');
+ } else {
+ audioPlayer = document.querySelector('.main-content-area audio');
+ }
+
+ if (audioPlayer) {
+ const wasPlaying = !audioPlayer.paused;
+ audioPlayer.currentTime = time;
+ if (wasPlaying) {
+ audioPlayer.play();
+ }
+ } else {
+ const oldPlayer = document.querySelector('audio');
+ if (oldPlayer) {
+ const wasPlaying = !oldPlayer.paused;
+ oldPlayer.currentTime = time;
+ if (wasPlaying) {
+ oldPlayer.play();
+ }
+ }
+ }
+ };
+
+ const seekAudioFromEvent = (event) => {
+ const segmentElement = event.target.closest('[data-start-time]');
+ if (!segmentElement) return;
+
+ const time = parseFloat(segmentElement.dataset.startTime);
+ if (isNaN(time)) return;
+
+ const isInSpeakerModal = event.target.closest('.speaker-modal-transcript') !== null;
+ const context = isInSpeakerModal ? 'modal' : 'main';
+
+ seekAudio(time, context);
+ };
+
+ const onPlayerVolumeChange = (event) => {
+ const newVolume = event.target.volume;
+ playerVolume.value = newVolume;
+ localStorage.setItem('playerVolume', newVolume);
+ };
+
+ // --- Active Segment Tracking ---
+ const handleAudioTimeUpdate = (event) => {
+ console.log('!!! handleAudioTimeUpdate FIRED !!!', event.target.currentTime);
+
+ const transcription = processedTranscription.value;
+
+ console.log('handleAudioTimeUpdate called', {
+ hasTranscription: !!transcription,
+ isJson: transcription?.isJson,
+ hasDialogue: transcription?.hasDialogue,
+ segmentCount: transcription?.simpleSegments?.length
+ });
+
+ if (!transcription || !transcription.isJson) {
+ console.log('Exiting early - no valid transcription');
+ return;
+ }
+
+ const audioElement = event.target;
+ const currentTime = audioElement.currentTime;
+
+ // Find the segment that contains the current time
+ let segments = transcription.simpleSegments || [];
+
+ if (segments.length === 0) {
+ return;
+ }
+
+ // Find the active segment index using a more robust algorithm
+ let activeIndex = null;
+
+ for (let i = segments.length - 1; i >= 0; i--) {
+ const segment = segments[i];
+ const startTime = segment.startTime || segment.start_time;
+
+ if (startTime !== undefined && currentTime >= startTime) {
+ activeIndex = i;
+ break;
+ }
+ }
+
+ // Only update if changed
+ if (activeIndex !== currentPlayingSegmentIndex.value) {
+ console.log('Active segment changed:', activeIndex, 'Time:', currentTime);
+ currentPlayingSegmentIndex.value = activeIndex;
+
+ // Scroll to active segment if follow mode is enabled
+ if (followPlayerMode.value && activeIndex !== null) {
+ scrollToActiveSegment(activeIndex);
+ }
+ }
+ };
+
+ const scrollToActiveSegment = (segmentIndex) => {
+ console.log('Scrolling to segment:', segmentIndex);
+ // Find the active segment element
+ const segments = document.querySelectorAll('.transcript-segment[data-segment-index], .speaker-segment[data-segment-index], .speaker-bubble[data-segment-index]');
+ console.log('Found segments:', segments.length);
+ if (segments[segmentIndex]) {
+ console.log('Scrolling element into view');
+ segments[segmentIndex].scrollIntoView({
+ behavior: 'smooth',
+ block: 'center'
+ });
+ } else {
+ console.log('Segment element not found at index:', segmentIndex);
+ }
+ };
+
+ const toggleFollowPlayerMode = () => {
+ followPlayerMode.value = !followPlayerMode.value;
+ localStorage.setItem('followPlayerMode', followPlayerMode.value);
+
+ if (followPlayerMode.value) {
+ showToast('Follow player mode enabled', 'fa-link');
+ // Scroll to current position if we have an active segment
+ if (currentPlayingSegmentIndex.value !== null) {
+ scrollToActiveSegment(currentPlayingSegmentIndex.value);
+ }
+ } else {
+ showToast('Follow player mode disabled', 'fa-unlink');
+ }
+ };
+
+ // --- Copy Functions ---
+ const animateCopyButton = (button) => {
+ if (!button) return;
+ const icon = button.querySelector('i');
+ if (icon) {
+ const originalClass = icon.className;
+ icon.className = 'fas fa-check';
+ setTimeout(() => {
+ icon.className = originalClass;
+ }, 2000);
+ }
+ };
+
+ const fallbackCopyTextToClipboard = (text) => {
+ const textArea = document.createElement('textarea');
+ textArea.value = text;
+ textArea.style.position = 'fixed';
+ textArea.style.left = '-999999px';
+ document.body.appendChild(textArea);
+ textArea.select();
+ try {
+ document.execCommand('copy');
+ showToast('Copied to clipboard!');
+ } catch (err) {
+ showToast('Failed to copy', 'fa-exclamation-circle');
+ }
+ document.body.removeChild(textArea);
+ };
+
+ const copyTranscription = (event) => {
+ if (!selectedRecording.value || !selectedRecording.value.transcription) {
+ showToast('No transcription available to copy.', 'fa-exclamation-circle');
+ return;
+ }
+
+ const button = event?.currentTarget;
+ let textToCopy = '';
+
+ try {
+ const transcriptionData = JSON.parse(selectedRecording.value.transcription);
+ if (Array.isArray(transcriptionData)) {
+ const wasDiarized = transcriptionData.some(segment => segment.speaker);
+ if (wasDiarized) {
+ textToCopy = transcriptionData.map(segment => {
+ return `[${segment.speaker}]: ${segment.text || segment.sentence}`;
+ }).join('\n');
+ } else {
+ textToCopy = transcriptionData.map(segment => segment.text || segment.sentence).join('\n');
+ }
+ } else {
+ textToCopy = selectedRecording.value.transcription;
+ }
+ } catch (e) {
+ textToCopy = selectedRecording.value.transcription;
+ }
+
+ animateCopyButton(button);
+
+ if (navigator.clipboard && window.isSecureContext) {
+ navigator.clipboard.writeText(textToCopy)
+ .then(() => showToast('Transcription copied to clipboard!'))
+ .catch(() => fallbackCopyTextToClipboard(textToCopy));
+ } else {
+ fallbackCopyTextToClipboard(textToCopy);
+ }
+ };
+
+ const copySummary = (event) => {
+ if (!selectedRecording.value || !selectedRecording.value.summary) {
+ showToast('No summary available to copy.', 'fa-exclamation-circle');
+ return;
+ }
+ const button = event?.currentTarget;
+ animateCopyButton(button);
+
+ if (navigator.clipboard && window.isSecureContext) {
+ navigator.clipboard.writeText(selectedRecording.value.summary)
+ .then(() => showToast('Summary copied to clipboard!'))
+ .catch(() => fallbackCopyTextToClipboard(selectedRecording.value.summary));
+ } else {
+ fallbackCopyTextToClipboard(selectedRecording.value.summary);
+ }
+ };
+
+ const copyNotes = (event) => {
+ if (!selectedRecording.value || !selectedRecording.value.notes) {
+ showToast('No notes available to copy.', 'fa-exclamation-circle');
+ return;
+ }
+ const button = event?.currentTarget;
+ animateCopyButton(button);
+
+ if (navigator.clipboard && window.isSecureContext) {
+ navigator.clipboard.writeText(selectedRecording.value.notes)
+ .then(() => showToast('Notes copied to clipboard!'))
+ .catch(() => fallbackCopyTextToClipboard(selectedRecording.value.notes));
+ } else {
+ fallbackCopyTextToClipboard(selectedRecording.value.notes);
+ }
+ };
+
+ // --- Download Functions ---
+ const downloadSummary = async () => {
+ if (!selectedRecording.value || !selectedRecording.value.summary) {
+ showToast('No summary available to download.', 'fa-exclamation-circle');
+ return;
+ }
+
+ try {
+ const response = await fetch(`/recording/${selectedRecording.value.id}/download/summary`);
+ if (!response.ok) {
+ const error = await response.json();
+ showToast(error.error || 'Failed to download summary', 'fa-exclamation-circle');
+ return;
+ }
+
+ const blob = await response.blob();
+ const url = window.URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.style.display = 'none';
+ a.href = url;
+
+ const contentDisposition = response.headers.get('Content-Disposition');
+ let filename = 'summary.docx';
+ if (contentDisposition) {
+ const utf8Match = /filename\*=utf-8''(.+)/.exec(contentDisposition);
+ if (utf8Match) {
+ filename = decodeURIComponent(utf8Match[1]);
+ } else {
+ const regularMatch = /filename="(.+)"/.exec(contentDisposition);
+ if (regularMatch) {
+ filename = regularMatch[1];
+ }
+ }
+ }
+ a.download = filename;
+
+ document.body.appendChild(a);
+ a.click();
+ window.URL.revokeObjectURL(url);
+ document.body.removeChild(a);
+
+ showToast('Summary downloaded successfully!');
+ } catch (error) {
+ showToast('Failed to download summary', 'fa-exclamation-circle');
+ }
+ };
+
+ const downloadTranscript = async () => {
+ if (!selectedRecording.value || !selectedRecording.value.transcription) {
+ showToast('No transcription available to download.', 'fa-exclamation-circle');
+ return;
+ }
+
+ try {
+ // First, fetch available templates
+ const templatesResponse = await fetch('/api/transcript-templates');
+ let templates = [];
+ if (templatesResponse.ok) {
+ templates = await templatesResponse.json();
+ }
+
+ // If there are templates, show a selection dialog
+ let templateId = null;
+ if (templates.length > 0) {
+ // Create a simple modal for template selection
+ const modal = document.createElement('div');
+ modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
+ modal.innerHTML = `
+ <div class="bg-[var(--bg-secondary)] rounded-lg p-6 max-w-md w-full mx-4">
+ <h3 class="text-lg font-semibold mb-4">${t('transcriptTemplates.selectTemplate')}</h3>
+ <div class="space-y-2 max-h-60 overflow-y-auto">
+ ${templates.map(tmpl => `
+ <button class="template-option w-full text-left p-3 rounded border border-[var(--border-primary)] hover:bg-[var(--bg-tertiary)] ${tmpl.is_default ? 'ring-2 ring-[var(--ring-focus)]' : ''}" data-template-id="${tmpl.id}">
+ <div class="font-medium">${tmpl.name}</div>
+ ${tmpl.description ? `<div class="text-sm text-[var(--text-muted)]">${tmpl.description}</div>` : ''}
+ ${tmpl.is_default ? `<div class="text-xs text-[var(--text-accent)] mt-1"><i class="fas fa-star mr-1"></i>${t('transcriptTemplates.default')}</div>` : ''}
+ </button>
+ `).join('')}
+ </div>
+ <div class="mt-4 flex gap-2">
+ <button class="cancel-btn px-4 py-2 bg-[var(--bg-tertiary)] text-[var(--text-secondary)] rounded hover:bg-[var(--bg-accent-light)]">${t('transcriptTemplates.cancel')}</button>
+ <button class="download-without-template-btn px-4 py-2 bg-[var(--bg-accent)] text-white rounded hover:bg-[var(--bg-accent-hover)]">${t('transcriptTemplates.downloadWithoutTemplate')}</button>
+ </div>
+ </div>
+ `;
+ document.body.appendChild(modal);
+
+ // Wait for user selection
+ await new Promise((resolve) => {
+ modal.querySelectorAll('.template-option').forEach(btn => {
+ btn.addEventListener('click', () => {
+ templateId = btn.dataset.templateId;
+ modal.remove();
+ resolve();
+ });
+ });
+
+ modal.querySelector('.cancel-btn').addEventListener('click', () => {
+ templateId = 'cancelled';
+ modal.remove();
+ resolve();
+ });
+
+ modal.querySelector('.download-without-template-btn').addEventListener('click', () => {
+ templateId = 'none';
+ modal.remove();
+ resolve();
+ });
+
+ modal.addEventListener('click', (e) => {
+ if (e.target === modal) {
+ templateId = 'cancelled';
+ modal.remove();
+ resolve();
+ }
+ });
+ });
+
+ if (templateId === null || templateId === undefined || templateId === 'cancelled') {
+ return;
+ }
+ }
+
+ // If templateId is 'none', download raw transcript without any template
+ if (templateId === 'none') {
+ let rawText = '';
+ try {
+ const transcriptionData = JSON.parse(selectedRecording.value.transcription);
+ if (Array.isArray(transcriptionData)) {
+ rawText = transcriptionData.map(segment => {
+ const speaker = segment.speaker || 'Unknown';
+ const text = segment.sentence || '';
+ return `${speaker}: ${text}`;
+ }).join('\n');
+ } else {
+ rawText = selectedRecording.value.transcription;
+ }
+ } catch (e) {
+ rawText = selectedRecording.value.transcription;
+ }
+
+ const blob = new Blob([rawText], { type: 'text/plain;charset=utf-8' });
+ const downloadUrl = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = downloadUrl;
+ a.download = `${selectedRecording.value.title || 'transcript'}_raw.txt`;
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ URL.revokeObjectURL(downloadUrl);
+
+ showToast('Transcript downloaded successfully!');
+ return;
+ }
+
+ // Download the transcript with the selected template
+ const url = templateId
+ ? `/recording/${selectedRecording.value.id}/download/transcript?template_id=${templateId}`
+ : `/recording/${selectedRecording.value.id}/download/transcript`;
+
+ const response = await fetch(url);
+ if (!response.ok) {
+ throw new Error('Failed to download transcript');
+ }
+
+ const blob = await response.blob();
+ const contentDisposition = response.headers.get('content-disposition');
+ let filename = 'transcript.txt';
+ if (contentDisposition) {
+ const matches = contentDisposition.match(/filename="([^"]+)"/);
+ if (matches && matches[1]) {
+ filename = matches[1];
+ }
+ }
+
+ const downloadUrl = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = downloadUrl;
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ URL.revokeObjectURL(downloadUrl);
+
+ showToast('Transcript downloaded successfully!');
+ } catch (error) {
+ console.error('Error downloading transcript:', error);
+ showToast('Failed to download transcript', 'fa-exclamation-circle');
+ }
+ };
+
+ // Download with default template (no modal)
+ const downloadWithDefaultTemplate = async () => {
+ if (!selectedRecording.value || !selectedRecording.value.transcription) {
+ showToast('No transcription available to download.', 'fa-exclamation-circle');
+ return;
+ }
+
+ try {
+ // Download using the default template (server will use user's default)
+ const response = await fetch(`/recording/${selectedRecording.value.id}/download/transcript`);
+ if (!response.ok) {
+ throw new Error('Failed to download transcript');
+ }
+
+ const blob = await response.blob();
+ const contentDisposition = response.headers.get('content-disposition');
+ let filename = 'transcript.txt';
+ if (contentDisposition) {
+ const matches = contentDisposition.match(/filename="([^"]+)"/);
+ if (matches && matches[1]) {
+ filename = matches[1];
+ }
+ }
+
+ const downloadUrl = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = downloadUrl;
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ URL.revokeObjectURL(downloadUrl);
+
+ showToast('Transcript downloaded successfully!');
+ } catch (error) {
+ console.error('Error downloading transcript:', error);
+ showToast('Failed to download transcript', 'fa-exclamation-circle');
+ }
+ };
+
+ // Show template selector modal (reuses the modal from downloadTranscript)
+ const showTemplateSelector = async () => {
+ // This calls the full downloadTranscript which shows the modal
+ await downloadTranscript();
+ };
+
+ // Initialize UI settings from localStorage
+ const initializeUI = () => {
+ // Load saved column widths
+ const savedLeftWidth = localStorage.getItem('transcriptColumnWidth');
+ const savedRightWidth = localStorage.getItem('summaryColumnWidth');
+ if (savedLeftWidth && savedRightWidth) {
+ leftColumnWidth.value = parseFloat(savedLeftWidth);
+ rightColumnWidth.value = parseFloat(savedRightWidth);
+ }
+
+ // Load saved transcription view mode
+ const savedViewMode = localStorage.getItem('transcriptionViewMode');
+ if (savedViewMode) {
+ transcriptionViewMode.value = savedViewMode;
+ }
+
+ // Load saved player volume
+ const savedVolume = localStorage.getItem('playerVolume');
+ if (savedVolume) {
+ playerVolume.value = parseFloat(savedVolume);
+ }
+
+ // Load saved follow player mode
+ const savedFollowMode = localStorage.getItem('followPlayerMode');
+ if (savedFollowMode !== null) {
+ followPlayerMode.value = savedFollowMode === 'true';
+ }
+
+ // Watch for recording changes to reset active segment
+ watch(selectedRecording, () => {
+ currentPlayingSegmentIndex.value = null;
+ });
+ };
+
+ // Initialize recording notes markdown editor
+ const initializeRecordingNotesEditor = () => {
+ if (!recordingNotesEditor.value) return;
+
+ // Destroy existing instance if any
+ if (recordingMarkdownEditorInstance.value) {
+ recordingMarkdownEditorInstance.value.toTextArea();
+ recordingMarkdownEditorInstance.value = null;
+ }
+
+ try {
+ recordingMarkdownEditorInstance.value = new EasyMDE({
+ element: recordingNotesEditor.value,
+ spellChecker: false,
+ autofocus: false,
+ placeholder: "Enter notes in Markdown format...",
+ initialValue: recordingNotes.value || '',
+ status: false,
+ toolbar: [
+ "bold", "italic", "heading", "|",
+ "quote", "unordered-list", "ordered-list", "|",
+ "link", "|",
+ "preview", "side-by-side", "fullscreen"
+ ],
+ previewClass: ["editor-preview", "notes-preview"],
+ theme: isDarkMode.value ? "dark" : "light"
+ });
+
+ // Sync changes back to recordingNotes
+ recordingMarkdownEditorInstance.value.codemirror.on('change', () => {
+ recordingNotes.value = recordingMarkdownEditorInstance.value.value();
+ });
+ } catch (error) {
+ console.error('Failed to initialize recording notes markdown editor:', error);
+ }
+ };
+
+ // Destroy recording notes markdown editor
+ const destroyRecordingNotesEditor = () => {
+ if (recordingMarkdownEditorInstance.value) {
+ // Save current value before destroying
+ recordingNotes.value = recordingMarkdownEditorInstance.value.value();
+ recordingMarkdownEditorInstance.value.toTextArea();
+ recordingMarkdownEditorInstance.value = null;
+ }
+ };
+
+ // =========================================
+ // Participants Modal
+ // =========================================
+
+ const openParticipantsModal = async () => {
+ if (!selectedRecording.value) return;
+
+ // Parse current participants into array
+ const participants = selectedRecording.value.participants
+ ? selectedRecording.value.participants.split(',').map(p => p.trim()).filter(Boolean)
+ : [];
+
+ state.editingParticipantsList.value = participants.map(name => ({ name }));
+
+ // Fetch speakers from database for autocomplete
+ try {
+ const response = await fetch('/speakers');
+ if (response.ok) {
+ const speakers = await response.json();
+ state.allParticipants.value = speakers.map(s => s.name).sort();
+ }
+ } catch (e) {
+ console.error('Failed to fetch speakers:', e);
+ state.allParticipants.value = [];
+ }
+
+ state.editingParticipantSuggestions.value = {};
+ state.showEditParticipantsModal.value = true;
+ };
+
+ const closeEditParticipantsModal = () => {
+ state.showEditParticipantsModal.value = false;
+ state.editingParticipantsList.value = [];
+ };
+
+ const addParticipant = () => {
+ state.editingParticipantsList.value.push({ name: '' });
+ };
+
+ const removeParticipant = (index) => {
+ state.editingParticipantsList.value.splice(index, 1);
+ delete state.editingParticipantSuggestions.value[index];
+ };
+
+ const filterParticipantSuggestions = (index) => {
+ // Close all other dropdowns first
+ closeAllParticipantSuggestions();
+
+ const query = state.editingParticipantsList.value[index]?.name?.toLowerCase().trim() || '';
+ if (query === '') {
+ // Show all participants when field is empty/focused
+ state.editingParticipantSuggestions.value[index] = [...state.allParticipants.value];
+ } else {
+ state.editingParticipantSuggestions.value[index] = state.allParticipants.value.filter(
+ p => p.toLowerCase().includes(query)
+ );
+ }
+ };
+
+ const selectParticipantSuggestion = (index, name) => {
+ state.editingParticipantsList.value[index].name = name;
+ state.editingParticipantSuggestions.value[index] = [];
+ };
+
+ const closeParticipantSuggestions = (index) => {
+ state.editingParticipantSuggestions.value[index] = [];
+ };
+
+ const closeParticipantSuggestionsDelayed = (index) => {
+ setTimeout(() => closeParticipantSuggestions(index), 200);
+ };
+
+ const closeAllParticipantSuggestions = () => {
+ state.editingParticipantSuggestions.value = {};
+ };
+
+ const getParticipantDropdownPosition = (index) => {
+ // Find the input element for this index and calculate position
+ const inputs = document.querySelectorAll('.max-w-md input[placeholder="Participant name..."]');
+ if (inputs[index]) {
+ const rect = inputs[index].getBoundingClientRect();
+ return {
+ top: rect.bottom + 2 + 'px',
+ left: rect.left + 'px',
+ width: rect.width + 'px'
+ };
+ }
+ return { top: '0px', left: '0px', width: '200px' };
+ };
+
+ const saveParticipants = async () => {
+ if (!selectedRecording.value) return;
+
+ // Join participant names with comma
+ const participantsString = state.editingParticipantsList.value
+ .map(p => p.name.trim())
+ .filter(Boolean)
+ .join(', ');
+
+ // Update the recording
+ selectedRecording.value.participants = participantsString;
+
+ // Use the same save endpoint as inline editing
+ const fullPayload = {
+ id: selectedRecording.value.id,
+ title: selectedRecording.value.title,
+ participants: selectedRecording.value.participants,
+ notes: selectedRecording.value.notes,
+ summary: selectedRecording.value.summary,
+ meeting_date: selectedRecording.value.meeting_date
+ };
+
+ try {
+ const response = await fetch('/save', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken.value
+ },
+ body: JSON.stringify(fullPayload)
+ });
+
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Failed to save participants');
+
+ showToast(t('common.changesSaved'), 'fa-check-circle');
+ closeEditParticipantsModal();
+ } catch (error) {
+ console.error('Save error:', error);
+ utils.setGlobalError(`Save failed: ${error.message}`);
+ }
+ };
+
+ return {
+ // Initialization
+ initializeUI,
+ toggleDarkMode,
+ initializeDarkMode,
+ applyColorScheme,
+ initializeColorScheme,
+ openColorSchemeModal,
+ closeColorSchemeModal,
+ selectColorScheme,
+ resetColorScheme,
+ toggleSidebar,
+ initializeSidebar,
+ switchToUploadView,
+ switchToDetailView,
+ switchToRecordingView,
+ setGlobalError,
+ formatFileSize,
+ formatDisplayDate,
+ formatShortDate,
+ formatStatus,
+ getStatusClass,
+ formatTime,
+ formatDuration,
+ formatProcessingDuration,
+ // Inline editing
+ toggleEditTitle,
+ saveTitle,
+ cancelEditTitle,
+ toggleEditParticipants,
+ toggleEditMeetingDate,
+ toggleEditSummary,
+ cancelEditSummary,
+ saveEditSummary,
+ initializeSummaryMarkdownEditor,
+ autoSaveSummary,
+ toggleEditNotes,
+ cancelEditNotes,
+ saveEditNotes,
+ initializeMarkdownEditor,
+ autoSaveNotes,
+ clickToEditNotes,
+ clickToEditSummary,
+ // Recording notes editor
+ initializeRecordingNotesEditor,
+ destroyRecordingNotesEditor,
+ downloadNotes,
+ downloadEventICS,
+ downloadICS,
+ formatEventDateTime,
+ // View mode
+ toggleTranscriptionViewMode,
+ // Column resizing
+ startColumnResize,
+ // Audio player
+ seekAudio,
+ seekAudioFromEvent,
+ onPlayerVolumeChange,
+ handleAudioTimeUpdate,
+ toggleFollowPlayerMode,
+ scrollToActiveSegment,
+ // Copy functions
+ copyTranscription,
+ copySummary,
+ copyNotes,
+ // Download functions
+ downloadSummary,
+ downloadTranscript,
+ downloadWithDefaultTemplate,
+ showTemplateSelector,
+ // Participants modal
+ openParticipantsModal,
+ closeEditParticipantsModal,
+ addParticipant,
+ removeParticipant,
+ filterParticipantSuggestions,
+ selectParticipantSuggestion,
+ closeParticipantSuggestions,
+ closeParticipantSuggestionsDelayed,
+ closeAllParticipantSuggestions,
+ getParticipantDropdownPosition,
+ saveParticipants,
+ // Computed
+ isMobile
+ };
+}
diff --git a/static/js/modules/composables/upload.js b/static/js/modules/composables/upload.js
new file mode 100644
index 00000000..fa42f464
--- /dev/null
+++ b/static/js/modules/composables/upload.js
@@ -0,0 +1,581 @@
+/**
+ * Upload management composable
+ * Handles file uploads, queue processing, and progress tracking
+ */
+
+export function useUpload(state, utils) {
+ const {
+ uploadQueue, currentlyProcessingFile, processingProgress, processingMessage,
+ isProcessingActive, pollInterval, progressPopupMinimized, progressPopupClosed,
+ maxFileSizeMB, chunkingEnabled, chunkingMode, chunkingLimit,
+ recordings, selectedRecording, totalRecordings, globalError,
+ selectedTagIds, uploadLanguage, uploadMinSpeakers, uploadMaxSpeakers,
+ useAsrEndpoint, asrLanguage, asrMinSpeakers, asrMaxSpeakers,
+ dragover, availableTags, uploadTagSearchFilter
+ } = state;
+
+ const { computed, nextTick } = Vue;
+
+ const { setGlobalError, showToast, formatFileSize } = utils;
+
+ // Compute selected tags from IDs
+ const selectedTags = computed(() => {
+ return selectedTagIds.value.map(id =>
+ availableTags.value.find(t => t.id === id)
+ ).filter(Boolean);
+ });
+
+ // Handle drag events
+ const handleDragOver = (e) => {
+ e.preventDefault();
+ dragover.value = true;
+ };
+
+ const handleDragLeave = (e) => {
+ if (e.relatedTarget && e.currentTarget.contains(e.relatedTarget)) {
+ return;
+ }
+ dragover.value = false;
+ };
+
+ const handleDrop = (e) => {
+ e.preventDefault();
+ dragover.value = false;
+ addFilesToQueue(e.dataTransfer.files);
+ };
+
+ const handleFileSelect = (e) => {
+ addFilesToQueue(e.target.files);
+ e.target.value = null;
+ };
+
+ // Add files to the upload queue
+ const addFilesToQueue = (files) => {
+ let filesAdded = 0;
+ for (const file of files) {
+ const fileObject = file.file ? file.file : file;
+ const notes = file.notes || null;
+ const tags = file.tags || selectedTags.value || [];
+ const asrOptions = file.asrOptions || {
+ language: asrLanguage.value,
+ min_speakers: asrMinSpeakers.value,
+ max_speakers: asrMaxSpeakers.value
+ };
+
+ // Check if it's an audio file or video container with audio
+ const 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('.mp4') ||
+ fileObject.name.toLowerCase().endsWith('.mov') ||
+ fileObject.name.toLowerCase().endsWith('.avi') ||
+ fileObject.name.toLowerCase().endsWith('.mkv') ||
+ fileObject.name.toLowerCase().endsWith('.webm')
+ );
+
+ if (isAudioFile) {
+ // Only check general file size limit
+ if (fileObject.size > maxFileSizeMB.value * 1024 * 1024) {
+ setGlobalError(`File "${fileObject.name}" exceeds the maximum size of ${maxFileSizeMB.value} MB and was skipped.`);
+ continue;
+ }
+
+ const clientId = `client-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
+
+ uploadQueue.value.push({
+ file: fileObject,
+ notes: notes,
+ tags: tags,
+ asrOptions: asrOptions,
+ status: 'queued',
+ recordingId: null,
+ clientId: clientId,
+ error: null,
+ willAutoSummarize: false // Server will tell us via SUMMARIZING status
+ });
+ filesAdded++;
+ } else if (fileObject) {
+ 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) {
+ console.log(`Added ${filesAdded} file(s) to the queue.`);
+ }
+ };
+
+ // Remove a file from the queue before processing starts
+ const removeFromQueue = (clientId) => {
+ const index = uploadQueue.value.findIndex(item => item.clientId === clientId);
+ if (index !== -1 && (uploadQueue.value[index].status === 'queued' || uploadQueue.value[index].status === 'ready')) {
+ uploadQueue.value.splice(index, 1);
+ console.log(`Removed file from queue: ${clientId}`);
+ }
+ };
+
+ // Cancel a waiting file from the upload progress queue
+ const cancelWaitingFile = (clientId) => {
+ const index = uploadQueue.value.findIndex(item => item.clientId === clientId);
+ if (index !== -1 && uploadQueue.value[index].status === 'ready') {
+ uploadQueue.value.splice(index, 1);
+ console.log(`Cancelled waiting file: ${clientId}`);
+ showToast('File removed from queue', 'fa-trash');
+ }
+ };
+
+ // Clear completed uploads from queue
+ const clearCompletedUploads = () => {
+ uploadQueue.value = uploadQueue.value.filter(item => !['completed', 'failed'].includes(item.status));
+ };
+
+ // Start processing all queued files
+ const startUpload = () => {
+ const pendingFiles = uploadQueue.value.filter(item => item.status === 'queued');
+ if (pendingFiles.length === 0) {
+ return;
+ }
+ // Update all queued files with current tags and ASR options
+ // AND change their status to 'ready' so they move to upload progress immediately
+ for (const item of uploadQueue.value) {
+ if (item.status === 'queued') {
+ // Only update tags if not already set
+ if (!item.tags || item.tags.length === 0) {
+ item.tags = [...selectedTags.value];
+ }
+ // Only update ASR options if not already set
+ if (!item.asrOptions || !item.asrOptions.language) {
+ item.asrOptions = {
+ language: asrLanguage.value,
+ min_speakers: asrMinSpeakers.value,
+ max_speakers: asrMaxSpeakers.value
+ };
+ }
+ // Change status to 'ready' to remove from upload view but keep in queue
+ item.status = 'ready';
+ }
+ }
+ progressPopupMinimized.value = false;
+ progressPopupClosed.value = false;
+ if (!isProcessingActive.value) {
+ startProcessingQueue();
+ }
+ };
+
+ const resetCurrentFileProcessingState = () => {
+ if (pollInterval.value) clearInterval(pollInterval.value);
+ pollInterval.value = null;
+ currentlyProcessingFile.value = null;
+ processingProgress.value = 0;
+ processingMessage.value = '';
+ };
+
+ const startProcessingQueue = async () => {
+ console.log("Attempting to start processing queue...");
+ if (isProcessingActive.value) {
+ console.log("Queue processor already active.");
+ return;
+ }
+
+ isProcessingActive.value = true;
+ resetCurrentFileProcessingState();
+
+ const nextFileItem = uploadQueue.value.find(item => item.status === 'ready' || item.status === 'queued');
+
+ if (nextFileItem) {
+ console.log(`Processing next file: ${nextFileItem.file.name} (Client ID: ${nextFileItem.clientId})`);
+ currentlyProcessingFile.value = nextFileItem;
+
+ // Check if this is a "reload" item (existing recording being tracked)
+ if (nextFileItem.clientId.startsWith('reload-')) {
+ console.log(`Skipping upload for existing recording: ${nextFileItem.recordingId}`);
+ nextFileItem.status = 'processing';
+ startStatusPolling(nextFileItem, nextFileItem.recordingId);
+ return;
+ }
+
+ nextFileItem.status = 'uploading';
+ processingMessage.value = 'Preparing upload...';
+ processingProgress.value = 5;
+
+ try {
+ const formData = new FormData();
+ formData.append('file', nextFileItem.file);
+ if (nextFileItem.notes) {
+ formData.append('notes', nextFileItem.notes);
+ }
+
+ // Add tags if selected
+ const tagsToUse = nextFileItem.tags || selectedTags.value || [];
+ tagsToUse.forEach((tag, index) => {
+ const tagId = tag.id || tag;
+ formData.append(`tag_ids[${index}]`, tagId);
+ });
+
+ // Add ASR advanced options if ASR endpoint is enabled
+ if (useAsrEndpoint.value) {
+ const asrOpts = nextFileItem.asrOptions || {};
+ const language = asrOpts.language || uploadLanguage.value;
+ const minSpeakers = asrOpts.min_speakers || uploadMinSpeakers.value;
+ const maxSpeakers = asrOpts.max_speakers || uploadMaxSpeakers.value;
+
+ if (language) {
+ formData.append('language', language);
+ }
+ if (minSpeakers && minSpeakers !== '') {
+ formData.append('min_speakers', minSpeakers.toString());
+ }
+ if (maxSpeakers && maxSpeakers !== '') {
+ formData.append('max_speakers', maxSpeakers.toString());
+ }
+ }
+
+ processingMessage.value = 'Uploading file...';
+ processingProgress.value = 10;
+
+ const response = await fetch('/upload', { method: 'POST', body: formData });
+ const data = await response.json();
+
+ if (!response.ok) {
+ let errorMsg = data.error || `Upload failed with status ${response.status}`;
+ if (response.status === 413) errorMsg = data.error || `File too large. Max: ${data.max_size_mb?.toFixed(0) || maxFileSizeMB.value} MB.`;
+ throw new Error(errorMsg);
+ }
+
+ if (response.status === 202 && data.id) {
+ console.log(`File ${nextFileItem.file.name} uploaded. Recording ID: ${data.id}. Starting status poll.`);
+ nextFileItem.status = 'pending';
+ nextFileItem.recordingId = data.id;
+ processingMessage.value = 'Upload complete. Waiting for processing...';
+ processingProgress.value = 30;
+
+ recordings.value.unshift(data);
+ totalRecordings.value++;
+ pollProcessingStatus(nextFileItem);
+
+ } else {
+ throw new Error('Unexpected success response from server after upload.');
+ }
+
+ } catch (error) {
+ console.error(`Upload/Processing Error for ${nextFileItem.file.name} (Client ID: ${nextFileItem.clientId}):`, error);
+ nextFileItem.status = 'failed';
+ nextFileItem.error = error.message;
+ const failedRecordIndex = recordings.value.findIndex(r => r.id === nextFileItem.recordingId);
+ if (failedRecordIndex !== -1) {
+ recordings.value[failedRecordIndex].status = 'FAILED';
+ recordings.value[failedRecordIndex].transcription = `Upload/Processing failed: ${error.message}`;
+ } else {
+ setGlobalError(`Failed to process "${nextFileItem.file.name}": ${error.message}`);
+ }
+
+ resetCurrentFileProcessingState();
+ isProcessingActive.value = false;
+ await Vue.nextTick();
+ startProcessingQueue();
+ }
+ } else {
+ console.log("Upload queue is empty or no files are queued.");
+ isProcessingActive.value = false;
+ }
+ };
+
+ const startStatusPolling = (fileItem, recordingId) => {
+ fileItem.recordingId = recordingId;
+ pollProcessingStatus(fileItem);
+ };
+
+ const pollProcessingStatus = (fileItem) => {
+ if (pollInterval.value) clearInterval(pollInterval.value);
+
+ const recordingId = fileItem.recordingId;
+ if (!recordingId) {
+ console.error("Cannot poll status without recording ID for", fileItem.file.name);
+ fileItem.status = 'failed';
+ fileItem.error = 'Internal error: Missing recording ID for polling.';
+ resetCurrentFileProcessingState();
+ isProcessingActive.value = false;
+ Vue.nextTick(startProcessingQueue);
+ return;
+ }
+
+ processingMessage.value = 'Waiting for transcription...';
+ processingProgress.value = 40;
+
+ pollInterval.value = setInterval(async () => {
+ const shouldStopPolling = !currentlyProcessingFile.value ||
+ currentlyProcessingFile.value.clientId !== fileItem.clientId ||
+ fileItem.status === 'failed' ||
+ (fileItem.status === 'completed' && (!fileItem.willAutoSummarize || fileItem.summaryCompleted));
+
+ if (shouldStopPolling) {
+ console.log(`Polling stopped for ${fileItem.clientId} as it's no longer active or finished.`);
+ clearInterval(pollInterval.value);
+ pollInterval.value = null;
+ if (currentlyProcessingFile.value && currentlyProcessingFile.value.clientId === fileItem.clientId) {
+ resetCurrentFileProcessingState();
+ isProcessingActive.value = false;
+ await Vue.nextTick();
+ startProcessingQueue();
+ }
+ return;
+ }
+
+ try {
+ console.log(`Polling status for recording ID: ${recordingId} (${fileItem.file.name})`);
+ // Use lightweight status-only endpoint
+ const response = await fetch(`/recording/${recordingId}/status`);
+ if (!response.ok) throw new Error(`Status check failed with status ${response.status}`);
+
+ const statusData = await response.json();
+ const galleryIndex = recordings.value.findIndex(r => r.id === recordingId);
+
+ // Update status in recordings list
+ if (galleryIndex !== -1) {
+ // Create new object to ensure Vue reactivity
+ recordings.value[galleryIndex] = {
+ ...recordings.value[galleryIndex],
+ status: statusData.status
+ };
+
+ // Update selectedRecording with new object reference for reactivity
+ if (selectedRecording.value?.id === recordingId) {
+ selectedRecording.value = {
+ ...selectedRecording.value,
+ status: statusData.status
+ };
+ }
+ }
+
+ const previousStatus = fileItem.status;
+ fileItem.status = statusData.status;
+
+ if (statusData.status === 'COMPLETED') {
+ // Fetch full recording data when complete
+ const fullResponse = await fetch(`/api/recordings/${recordingId}`);
+ if (fullResponse.ok) {
+ const data = await fullResponse.json();
+
+ // Update recordings list first
+ if (galleryIndex !== -1) {
+ recordings.value[galleryIndex] = data;
+ }
+
+ // Always update selectedRecording if it's the current recording,
+ // even if it's not in the current recordings list (e.g., filtered out)
+ if (selectedRecording.value?.id === recordingId) {
+ selectedRecording.value = data;
+ // Force Vue to detect the change
+ await nextTick();
+ }
+
+ // Store display name separately since File.name is read-only
+ fileItem.displayName = data.title || data.original_filename || fileItem.file.name;
+ }
+
+ console.log(`Processing COMPLETED for ${fileItem.displayName} (ID: ${recordingId})`);
+
+ if (previousStatus === 'summarizing') {
+ console.log(`Auto-summary completed for ${fileItem.displayName}`);
+ processingMessage.value = 'Processing complete!';
+ processingProgress.value = 100;
+ fileItem.status = 'completed';
+ fileItem.summaryCompleted = true;
+
+ clearInterval(pollInterval.value);
+ pollInterval.value = null;
+ resetCurrentFileProcessingState();
+ isProcessingActive.value = false;
+
+ startProcessingQueue();
+ return;
+ } else if (fileItem.willAutoSummarize && !fileItem.hasCheckedForAutoSummary) {
+ processingMessage.value = 'Transcription complete!';
+ processingProgress.value = 85;
+ fileItem.status = 'awaiting_summary';
+ fileItem.hasCheckedForAutoSummary = true;
+ fileItem.autoSummaryStartTime = Date.now();
+ return;
+ } else if (fileItem.willAutoSummarize && fileItem.hasCheckedForAutoSummary) {
+ const waitTime = Date.now() - fileItem.autoSummaryStartTime;
+ const maxWaitTime = 5000; // 5 seconds - if no summarization starts, complete
+
+ if (waitTime > maxWaitTime) {
+ console.log(`Auto-summary did not start within ${maxWaitTime}ms, completing`);
+ processingMessage.value = 'Processing complete!';
+ processingProgress.value = 100;
+ fileItem.status = 'completed';
+ fileItem.summaryCompleted = false; // Summary didn't happen
+ clearInterval(pollInterval.value);
+ pollInterval.value = null;
+ resetCurrentFileProcessingState();
+ isProcessingActive.value = false;
+ startProcessingQueue();
+ return;
+ }
+ return;
+ } else {
+ processingMessage.value = 'Processing complete!';
+ processingProgress.value = 100;
+ fileItem.status = 'completed';
+ fileItem.summaryCompleted = true;
+
+ clearInterval(pollInterval.value);
+ pollInterval.value = null;
+ resetCurrentFileProcessingState();
+ isProcessingActive.value = false;
+ startProcessingQueue();
+ return;
+ }
+
+ } else if (statusData.status === 'FAILED') {
+ console.log(`Processing FAILED for ${fileItem.displayName || fileItem.file.name} (ID: ${recordingId})`);
+ processingMessage.value = 'Processing failed.';
+ processingProgress.value = 100;
+ fileItem.status = 'failed';
+
+ // Fetch full data to get error details
+ try {
+ const failedResponse = await fetch(`/api/recordings/${recordingId}`);
+ if (failedResponse.ok) {
+ const failedData = await failedResponse.json();
+ fileItem.error = failedData.error_message || 'Processing failed on server.';
+ } else {
+ fileItem.error = 'Processing failed on server.';
+ }
+ } catch (err) {
+ fileItem.error = 'Processing failed on server.';
+ }
+
+ setGlobalError(`Processing failed for "${fileItem.displayName || fileItem.file.name}".`);
+ clearInterval(pollInterval.value);
+ pollInterval.value = null;
+ resetCurrentFileProcessingState();
+ isProcessingActive.value = false;
+ await Vue.nextTick();
+ startProcessingQueue();
+
+ } else if (statusData.status === 'PROCESSING') {
+ const couldUseChunking = chunkingEnabled.value && !useAsrEndpoint.value;
+
+ if (couldUseChunking) {
+ if (chunkingMode.value === 'size') {
+ const chunkThresholdBytes = chunkingLimit.value * 1024 * 1024;
+ const willUseChunking = fileItem.file.size > chunkThresholdBytes;
+
+ if (willUseChunking) {
+ processingMessage.value = 'Processing large file (chunking in progress)...';
+ const maxProgress = fileItem.willAutoSummarize ? 70 : 80;
+ processingProgress.value = Math.round(Math.min(maxProgress, processingProgress.value + Math.random() * 3));
+ } else {
+ processingMessage.value = 'Transcription in progress...';
+ const maxProgress = fileItem.willAutoSummarize ? 65 : 75;
+ processingProgress.value = Math.round(Math.min(maxProgress, processingProgress.value + Math.random() * 5));
+ }
+ } else {
+ processingMessage.value = 'Processing file (chunking determined server-side)...';
+ const maxProgress = fileItem.willAutoSummarize ? 70 : 80;
+ processingProgress.value = Math.round(Math.min(maxProgress, processingProgress.value + Math.random() * 3));
+ }
+ } else {
+ processingMessage.value = 'Transcription in progress...';
+ const maxProgress = fileItem.willAutoSummarize ? 65 : 75;
+ processingProgress.value = Math.round(Math.min(maxProgress, processingProgress.value + Math.random() * 5));
+ }
+ } else if (statusData.status === 'SUMMARIZING') {
+ console.log(`Auto-summary started for ${fileItem.displayName || fileItem.file.name}`);
+ processingMessage.value = 'Generating summary...';
+ processingProgress.value = 90;
+ fileItem.status = 'summarizing';
+ } else {
+ processingMessage.value = 'Waiting in queue...';
+ processingProgress.value = 45;
+ }
+ } catch (error) {
+ console.error(`Polling Error for ${fileItem.displayName || fileItem.file.name} (ID: ${recordingId}):`, error);
+ fileItem.status = 'failed';
+ fileItem.error = `Error checking status: ${error.message}`;
+ setGlobalError(`Error checking status for "${fileItem.displayName || fileItem.file.name}": ${error.message}.`);
+ const galleryIndex = recordings.value.findIndex(r => r.id === recordingId);
+ if (galleryIndex !== -1) recordings.value[galleryIndex].status = 'FAILED';
+
+ clearInterval(pollInterval.value);
+ pollInterval.value = null;
+ resetCurrentFileProcessingState();
+ isProcessingActive.value = false;
+ await Vue.nextTick();
+ startProcessingQueue();
+ }
+ }, 5000);
+ };
+
+ // Tag selection helpers
+ const addTagToSelection = (tagId) => {
+ if (!selectedTagIds.value.includes(tagId)) {
+ selectedTagIds.value.push(tagId);
+ applyTagDefaults();
+ }
+ };
+
+ const removeTagFromSelection = (tagId) => {
+ const index = selectedTagIds.value.indexOf(tagId);
+ if (index > -1) {
+ selectedTagIds.value.splice(index, 1);
+ applyTagDefaults();
+ }
+ };
+
+ const applyTagDefaults = () => {
+ const selectedTagsObjects = selectedTagIds.value.map(tagId =>
+ availableTags.value.find(tag => tag.id == tagId)
+ ).filter(Boolean);
+
+ const firstTag = selectedTagsObjects[0];
+ if (firstTag && useAsrEndpoint.value) {
+ if (firstTag.default_language) {
+ uploadLanguage.value = firstTag.default_language;
+ }
+ if (firstTag.default_min_speakers) {
+ uploadMinSpeakers.value = firstTag.default_min_speakers;
+ }
+ if (firstTag.default_max_speakers) {
+ uploadMaxSpeakers.value = firstTag.default_max_speakers;
+ }
+ }
+ };
+
+ // Computed property for filtered available tags in upload view
+ const filteredAvailableTagsForUpload = computed(() => {
+ const availableForSelection = availableTags.value.filter(tag => !selectedTagIds.value.includes(tag.id));
+ if (!uploadTagSearchFilter.value) return availableForSelection;
+
+ const filter = uploadTagSearchFilter.value.toLowerCase();
+ return availableForSelection.filter(tag =>
+ tag.name.toLowerCase().includes(filter)
+ );
+ });
+
+ return {
+ handleDragOver,
+ handleDragLeave,
+ handleDrop,
+ handleFileSelect,
+ addFilesToQueue,
+ removeFromQueue,
+ cancelWaitingFile,
+ clearCompletedUploads,
+ startUpload,
+ startProcessingQueue,
+ resetCurrentFileProcessingState,
+ startStatusPolling,
+ pollProcessingStatus,
+ addTagToSelection,
+ removeTagFromSelection,
+ applyTagDefaults,
+ filteredAvailableTagsForUpload
+ };
+}
diff --git a/static/js/modules/computed/index.js b/static/js/modules/computed/index.js
new file mode 100644
index 00000000..f9464da2
--- /dev/null
+++ b/static/js/modules/computed/index.js
@@ -0,0 +1,26 @@
+/**
+ * Computed properties module exports
+ *
+ * Note: These computed properties are defined inline in the main app.js
+ * due to their tight coupling with reactive state. This module serves as
+ * a placeholder for future extraction if needed.
+ */
+
+// Computed properties that could be extracted:
+// - filteredRecordings
+// - groupedRecordings
+// - highlightedTranscript
+// - activeRecordingMetadata
+// - identifiedSpeakers
+// - processedTranscription
+// - totalInQueue
+// - completedInQueue
+// - finishedFilesInQueue
+// - isMobileScreen
+// - datePresetOptions
+// - languageOptions
+// - tagsWithCustomPrompts
+// - filteredAvailableTagsForModal
+// - isMobileDevice
+
+export default {};
diff --git a/static/js/modules/state/audio.js b/static/js/modules/state/audio.js
new file mode 100644
index 00000000..0c9f7f4b
--- /dev/null
+++ b/static/js/modules/state/audio.js
@@ -0,0 +1,95 @@
+/**
+ * Audio recording state management
+ */
+
+export function createAudioState(ref) {
+ // --- Audio Recording State ---
+ const isRecording = ref(false);
+ const mediaRecorder = ref(null);
+ const audioChunks = ref([]);
+ const audioBlobURL = ref(null);
+ const recordingTime = ref(0);
+ const recordingInterval = ref(null);
+ const canRecordAudio = ref(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);
+ const canRecordSystemAudio = ref(false);
+ const systemAudioSupported = ref(false);
+ const systemAudioError = ref('');
+ const recordingNotes = ref('');
+ const showSystemAudioHelp = ref(false);
+
+ // ASR options for recording view
+ const asrLanguage = ref('');
+ const asrMinSpeakers = ref('');
+ const asrMaxSpeakers = ref('');
+
+ // Audio context and analyzers
+ const audioContext = ref(null);
+ const analyser = ref(null);
+ const micAnalyser = ref(null);
+ const systemAnalyser = ref(null);
+ const visualizer = ref(null);
+ const micVisualizer = ref(null);
+ const systemVisualizer = ref(null);
+ const animationFrameId = ref(null);
+ const recordingMode = ref('microphone');
+ const activeStreams = ref([]);
+
+ // --- Wake Lock and Background Recording ---
+ const wakeLock = ref(null);
+ const recordingNotification = ref(null);
+ const isPageVisible = ref(true);
+
+ // --- Recording Size Monitoring ---
+ const estimatedFileSize = ref(0);
+ const fileSizeWarningShown = ref(false);
+ const recordingQuality = ref('optimized');
+ const actualBitrate = ref(0);
+ const maxRecordingMB = ref(200);
+ const sizeCheckInterval = ref(null);
+
+ return {
+ // Recording state
+ isRecording,
+ mediaRecorder,
+ audioChunks,
+ audioBlobURL,
+ recordingTime,
+ recordingInterval,
+ canRecordAudio,
+ canRecordSystemAudio,
+ systemAudioSupported,
+ systemAudioError,
+ recordingNotes,
+ showSystemAudioHelp,
+
+ // ASR options
+ asrLanguage,
+ asrMinSpeakers,
+ asrMaxSpeakers,
+
+ // Audio context
+ audioContext,
+ analyser,
+ micAnalyser,
+ systemAnalyser,
+ visualizer,
+ micVisualizer,
+ systemVisualizer,
+ animationFrameId,
+ recordingMode,
+ activeStreams,
+
+ // Wake lock
+ wakeLock,
+ recordingNotification,
+ isPageVisible,
+
+ // Size monitoring
+ estimatedFileSize,
+ fileSizeWarningShown,
+ recordingQuality,
+ actualBitrate,
+ maxRecordingMB,
+ sizeCheckInterval
+ };
+}
diff --git a/static/js/modules/state/chat.js b/static/js/modules/state/chat.js
new file mode 100644
index 00000000..dc58cbda
--- /dev/null
+++ b/static/js/modules/state/chat.js
@@ -0,0 +1,21 @@
+/**
+ * Chat state management
+ */
+
+export function createChatState(ref) {
+ const showChat = ref(false);
+ const isChatMaximized = ref(false);
+ const chatMessages = ref([]);
+ const chatInput = ref('');
+ const isChatLoading = ref(false);
+ const chatMessagesRef = ref(null);
+
+ return {
+ showChat,
+ isChatMaximized,
+ chatMessages,
+ chatInput,
+ isChatLoading,
+ chatMessagesRef
+ };
+}
diff --git a/static/js/modules/state/core.js b/static/js/modules/state/core.js
new file mode 100644
index 00000000..407501f1
--- /dev/null
+++ b/static/js/modules/state/core.js
@@ -0,0 +1,128 @@
+/**
+ * Core application state
+ */
+
+export function createCoreState(ref, computed) {
+ // --- Core State ---
+ const currentView = ref('upload');
+ const dragover = ref(false);
+ const recordings = ref([]);
+ const selectedRecording = ref(null);
+ const selectedTab = ref('summary');
+ const searchQuery = ref('');
+ const isLoadingRecordings = ref(true);
+ const globalError = ref(null);
+
+ // --- Pagination State ---
+ const currentPage = ref(1);
+ const perPage = ref(25);
+ const totalRecordings = ref(0);
+ const totalPages = ref(0);
+ const hasNextPage = ref(false);
+ const hasPrevPage = ref(false);
+ const isLoadingMore = ref(false);
+ const searchDebounceTimer = ref(null);
+
+ // --- Enhanced Search & Organization State ---
+ const sortBy = ref('created_at');
+ const selectedTagFilter = ref(null);
+
+ // Advanced filter state
+ const showAdvancedFilters = ref(false);
+ const filterTags = ref([]);
+ const filterDateRange = ref({ start: '', end: '' });
+ const filterDatePreset = ref('');
+ const filterTextQuery = ref('');
+ const showArchivedRecordings = ref(false);
+ const showSharedWithMe = ref(false);
+
+ // --- App Configuration ---
+ const useAsrEndpoint = ref(false);
+ const currentUserName = ref('');
+ const canDeleteRecordings = ref(true);
+ const enableInternalSharing = ref(false);
+ const enableArchiveToggle = ref(false);
+ const showUsernamesInUI = ref(false);
+
+ // Tag Selection
+ const availableTags = ref([]);
+ const selectedTagIds = ref([]);
+ const uploadTagSearchFilter = ref('');
+
+ const selectedTags = computed(() => {
+ return selectedTagIds.value.map(tagId =>
+ availableTags.value.find(tag => tag.id == tagId)
+ ).filter(Boolean);
+ });
+
+ const filteredAvailableTagsForUpload = computed(() => {
+ const availableForSelection = availableTags.value.filter(tag => !selectedTagIds.value.includes(tag.id));
+ if (!uploadTagSearchFilter.value) return availableForSelection;
+
+ const filter = uploadTagSearchFilter.value.toLowerCase();
+ return availableForSelection.filter(tag =>
+ tag.name.toLowerCase().includes(filter)
+ );
+ });
+
+ const filteredRecordings = computed(() => {
+ return recordings.value;
+ });
+
+ const setGlobalError = (message, duration = 7000) => {
+ globalError.value = message;
+ if (duration > 0) {
+ setTimeout(() => { if (globalError.value === message) globalError.value = null; }, duration);
+ }
+ };
+
+ return {
+ // Core
+ currentView,
+ dragover,
+ recordings,
+ selectedRecording,
+ selectedTab,
+ searchQuery,
+ isLoadingRecordings,
+ globalError,
+ setGlobalError,
+
+ // Pagination
+ currentPage,
+ perPage,
+ totalRecordings,
+ totalPages,
+ hasNextPage,
+ hasPrevPage,
+ isLoadingMore,
+ searchDebounceTimer,
+
+ // Search & Organization
+ sortBy,
+ selectedTagFilter,
+ showAdvancedFilters,
+ filterTags,
+ filterDateRange,
+ filterDatePreset,
+ filterTextQuery,
+ showArchivedRecordings,
+ showSharedWithMe,
+
+ // App Configuration
+ useAsrEndpoint,
+ currentUserName,
+ canDeleteRecordings,
+ enableInternalSharing,
+ enableArchiveToggle,
+ showUsernamesInUI,
+
+ // Tags
+ availableTags,
+ selectedTagIds,
+ uploadTagSearchFilter,
+ selectedTags,
+ filteredAvailableTagsForUpload,
+ filteredRecordings
+ };
+}
diff --git a/static/js/modules/state/index.js b/static/js/modules/state/index.js
new file mode 100644
index 00000000..fe5d0b40
--- /dev/null
+++ b/static/js/modules/state/index.js
@@ -0,0 +1,11 @@
+/**
+ * State module exports
+ */
+
+export { createCoreState } from './core.js';
+export { createUIState } from './ui.js';
+export { createUploadState } from './upload.js';
+export { createAudioState } from './audio.js';
+export { createModalState } from './modals.js';
+export { createChatState } from './chat.js';
+export { createSharingState } from './sharing.js';
diff --git a/static/js/modules/state/modals.js b/static/js/modules/state/modals.js
new file mode 100644
index 00000000..5a102a0b
--- /dev/null
+++ b/static/js/modules/state/modals.js
@@ -0,0 +1,161 @@
+/**
+ * Modal state management
+ */
+
+export function createModalState(ref, reactive) {
+ // --- Modal Visibility State ---
+ const showEditModal = ref(false);
+ const showDeleteModal = ref(false);
+ const showEditTagsModal = ref(false);
+ const showReprocessModal = ref(false);
+ const showResetModal = ref(false);
+ const showSpeakerModal = ref(false);
+ const showShareModal = ref(false);
+ const showSharesListModal = ref(false);
+ const showTextEditorModal = ref(false);
+ const showAsrEditorModal = ref(false);
+ const showEditSpeakersModal = ref(false);
+ const showEditTextModal = ref(false);
+ const showAddSpeakerModal = ref(false);
+ const showShareDeleteModal = ref(false);
+ const showUnifiedShareModal = ref(false);
+
+ // --- Modal Data State ---
+ const selectedNewTagId = ref('');
+ const tagSearchFilter = ref('');
+ const editingRecording = ref(null);
+ const editingTranscriptionContent = ref('');
+ const editingSegments = ref([]);
+ const availableSpeakers = ref([]);
+ const editingSpeakersList = ref([]);
+ const databaseSpeakers = ref([]);
+ const editingSpeakerSuggestions = ref({});
+ const recordingToDelete = ref(null);
+ const recordingToReset = ref(null);
+ const reprocessType = ref(null);
+ const reprocessRecording = ref(null);
+ const isAutoIdentifying = ref(false);
+
+ const asrReprocessOptions = reactive({
+ language: '',
+ min_speakers: null,
+ max_speakers: null
+ });
+
+ const summaryReprocessPromptSource = ref('default');
+ const summaryReprocessSelectedTagId = ref('');
+ const summaryReprocessCustomPrompt = ref('');
+ const speakerMap = ref({});
+ const regenerateSummaryAfterSpeakerUpdate = ref(true);
+ const speakerSuggestions = ref({});
+ const loadingSuggestions = ref({});
+ const activeSpeakerInput = ref(null);
+ const voiceSuggestions = ref({});
+ const loadingVoiceSuggestions = ref(false);
+
+ // --- Transcript Editing State ---
+ const editingSegmentIndex = ref(null);
+ const editingSpeakerIndex = ref(null);
+ const editedText = ref('');
+ const newSpeakerName = ref('');
+ const newSpeakerIsMe = ref(false);
+ const editedTranscriptData = ref(null);
+
+ // --- Inline Editing State ---
+ const editingParticipants = ref(false);
+ const editingMeetingDate = ref(false);
+ const editingSummary = ref(false);
+ const editingNotes = ref(false);
+ const tempNotesContent = ref('');
+ const tempSummaryContent = ref('');
+ const autoSaveTimer = ref(null);
+ const autoSaveDelay = 2000;
+
+ // --- Markdown Editor State ---
+ const notesMarkdownEditor = ref(null);
+ const markdownEditorInstance = ref(null);
+ const summaryMarkdownEditor = ref(null);
+ const summaryMarkdownEditorInstance = ref(null);
+ const recordingNotesEditor = ref(null);
+ const recordingMarkdownEditorInstance = ref(null);
+
+ // --- Dropdown Positions ---
+ const dropdownPositions = ref({});
+ const editSpeakerDropdownPositions = ref({});
+
+ return {
+ // Modal visibility
+ showEditModal,
+ showDeleteModal,
+ showEditTagsModal,
+ showReprocessModal,
+ showResetModal,
+ showSpeakerModal,
+ showShareModal,
+ showSharesListModal,
+ showTextEditorModal,
+ showAsrEditorModal,
+ showEditSpeakersModal,
+ showEditTextModal,
+ showAddSpeakerModal,
+ showShareDeleteModal,
+ showUnifiedShareModal,
+
+ // Modal data
+ selectedNewTagId,
+ tagSearchFilter,
+ editingRecording,
+ editingTranscriptionContent,
+ editingSegments,
+ availableSpeakers,
+ editingSpeakersList,
+ databaseSpeakers,
+ editingSpeakerSuggestions,
+ recordingToDelete,
+ recordingToReset,
+ reprocessType,
+ reprocessRecording,
+ isAutoIdentifying,
+ asrReprocessOptions,
+ summaryReprocessPromptSource,
+ summaryReprocessSelectedTagId,
+ summaryReprocessCustomPrompt,
+ speakerMap,
+ regenerateSummaryAfterSpeakerUpdate,
+ speakerSuggestions,
+ loadingSuggestions,
+ activeSpeakerInput,
+ voiceSuggestions,
+ loadingVoiceSuggestions,
+
+ // Transcript editing
+ editingSegmentIndex,
+ editingSpeakerIndex,
+ editedText,
+ newSpeakerName,
+ newSpeakerIsMe,
+ editedTranscriptData,
+
+ // Inline editing
+ editingParticipants,
+ editingMeetingDate,
+ editingSummary,
+ editingNotes,
+ tempNotesContent,
+ tempSummaryContent,
+ autoSaveTimer,
+ autoSaveDelay,
+
+ // Markdown editors
+ notesMarkdownEditor,
+ markdownEditorInstance,
+ summaryMarkdownEditor,
+ summaryMarkdownEditorInstance,
+ recordingNotesEditor,
+ recordingMarkdownEditorInstance,
+
+ // Dropdown positions
+ dropdownPositions,
+ editSpeakerDropdownPositions
+ };
+}
diff --git a/static/js/modules/state/sharing.js b/static/js/modules/state/sharing.js
new file mode 100644
index 00000000..6f3b1b30
--- /dev/null
+++ b/static/js/modules/state/sharing.js
@@ -0,0 +1,56 @@
+/**
+ * Sharing state management
+ */
+
+export function createSharingState(ref, reactive) {
+ // --- Public Sharing State ---
+ const recordingToShare = ref(null);
+ const shareOptions = reactive({
+ share_summary: true,
+ share_notes: true,
+ });
+ const generatedShareLink = ref('');
+ const existingShareDetected = ref(false);
+ const userShares = ref([]);
+ const isLoadingShares = ref(false);
+ const shareToDelete = ref(null);
+
+ // --- Internal Sharing State ---
+ const internalShareUserSearch = ref('');
+ const internalShareSearchResults = ref([]);
+ const internalShareRecording = ref(null);
+ const internalSharePermissions = ref({ can_edit: false, can_reshare: false });
+ const recordingInternalShares = ref([]);
+ const isLoadingInternalShares = ref(false);
+ const isSearchingUsers = ref(false);
+ const allUsers = ref([]);
+ const isLoadingAllUsers = ref(false);
+
+ // --- Audio Player State ---
+ const playerVolume = ref(1.0);
+
+ return {
+ // Public sharing
+ recordingToShare,
+ shareOptions,
+ generatedShareLink,
+ existingShareDetected,
+ userShares,
+ isLoadingShares,
+ shareToDelete,
+
+ // Internal sharing
+ internalShareUserSearch,
+ internalShareSearchResults,
+ internalShareRecording,
+ internalSharePermissions,
+ recordingInternalShares,
+ isLoadingInternalShares,
+ isSearchingUsers,
+ allUsers,
+ isLoadingAllUsers,
+
+ // Audio player
+ playerVolume
+ };
+}
diff --git a/static/js/modules/state/ui.js b/static/js/modules/state/ui.js
new file mode 100644
index 00000000..7ac6689e
--- /dev/null
+++ b/static/js/modules/state/ui.js
@@ -0,0 +1,94 @@
+/**
+ * UI state management
+ */
+
+export function createUIState(ref, computed) {
+ // --- UI State ---
+ const browser = ref('unknown');
+ const isSidebarCollapsed = ref(false);
+ const searchTipsExpanded = ref(false);
+ const isUserMenuOpen = ref(false);
+ const isDarkMode = ref(false);
+ const currentColorScheme = ref('blue');
+ const showColorSchemeModal = ref(false);
+ const windowWidth = ref(window.innerWidth);
+ const mobileTab = ref('transcript');
+ const isMetadataExpanded = ref(false);
+
+ // --- i18n State ---
+ const currentLanguage = ref('en');
+ const currentLanguageName = ref('English');
+ const availableLanguages = ref([]);
+ const showLanguageMenu = ref(false);
+
+ // --- Column Resizing State ---
+ const leftColumnWidth = ref(60);
+ const rightColumnWidth = ref(40);
+ const isResizing = ref(false);
+
+ // --- Transcription State ---
+ const transcriptionViewMode = ref('simple');
+ const legendExpanded = ref(false);
+ const highlightedSpeaker = ref(null);
+
+ // --- Computed Properties ---
+ const isMobileScreen = computed(() => {
+ return windowWidth.value < 1024;
+ });
+
+ // --- Color Scheme Definitions ---
+ const colorSchemes = {
+ light: [
+ { id: 'blue', name: 'Ocean Blue', description: 'Classic blue theme with professional appeal', class: '' },
+ { id: 'emerald', name: 'Forest Emerald', description: 'Fresh green theme for a natural feel', class: 'theme-light-emerald' },
+ { id: 'purple', name: 'Royal Purple', description: 'Elegant purple theme with sophistication', class: 'theme-light-purple' },
+ { id: 'rose', name: 'Sunset Rose', description: 'Warm pink theme with gentle energy', class: 'theme-light-rose' },
+ { id: 'amber', name: 'Golden Amber', description: 'Warm yellow theme for brightness', class: 'theme-light-amber' },
+ { id: 'teal', name: 'Ocean Teal', description: 'Cool teal theme for tranquility', class: 'theme-light-teal' }
+ ],
+ dark: [
+ { id: 'blue', name: 'Midnight Blue', description: 'Deep blue theme for focused work', class: '' },
+ { id: 'emerald', name: 'Dark Forest', description: 'Rich green theme for comfortable viewing', class: 'theme-dark-emerald' },
+ { id: 'purple', name: 'Deep Purple', description: 'Mysterious purple theme for creativity', class: 'theme-dark-purple' },
+ { id: 'rose', name: 'Dark Rose', description: 'Muted pink theme with subtle warmth', class: 'theme-dark-rose' },
+ { id: 'amber', name: 'Dark Amber', description: 'Warm brown theme for cozy sessions', class: 'theme-dark-amber' },
+ { id: 'teal', name: 'Deep Teal', description: 'Dark teal theme for calm focus', class: 'theme-dark-teal' }
+ ]
+ };
+
+ return {
+ // UI
+ browser,
+ isSidebarCollapsed,
+ searchTipsExpanded,
+ isUserMenuOpen,
+ isDarkMode,
+ currentColorScheme,
+ showColorSchemeModal,
+ windowWidth,
+ mobileTab,
+ isMetadataExpanded,
+
+ // i18n
+ currentLanguage,
+ currentLanguageName,
+ availableLanguages,
+ showLanguageMenu,
+
+ // Column Resizing
+ leftColumnWidth,
+ rightColumnWidth,
+ isResizing,
+
+ // Transcription
+ transcriptionViewMode,
+ legendExpanded,
+ highlightedSpeaker,
+
+ // Computed
+ isMobileScreen,
+
+ // Constants
+ colorSchemes
+ };
+}
diff --git a/static/js/modules/state/upload.js b/static/js/modules/state/upload.js
new file mode 100644
index 00000000..e4633e02
--- /dev/null
+++ b/static/js/modules/state/upload.js
@@ -0,0 +1,71 @@
+/**
+ * Upload state management
+ */
+
+export function createUploadState(ref, computed) {
+ // --- Upload State ---
+ const uploadQueue = ref([]);
+ const currentlyProcessingFile = ref(null);
+ const processingProgress = ref(0);
+ const processingMessage = ref('');
+ const isProcessingActive = ref(false);
+ const pollInterval = ref(null);
+ const progressPopupMinimized = ref(false);
+ const progressPopupClosed = ref(false);
+ const maxFileSizeMB = ref(250);
+ const chunkingEnabled = ref(true);
+ const chunkingMode = ref('size');
+ const chunkingLimit = ref(20);
+ const chunkingLimitDisplay = ref('20MB');
+ const recordingDisclaimer = ref('');
+ const showRecordingDisclaimerModal = ref(false);
+ const pendingRecordingMode = ref(null);
+
+ // Advanced Options for ASR
+ const showAdvancedOptions = ref(false);
+ const uploadLanguage = ref('');
+ const uploadMinSpeakers = ref('');
+ const uploadMaxSpeakers = ref('');
+
+ // --- Computed Properties ---
+ const totalInQueue = computed(() => uploadQueue.value.length);
+ const completedInQueue = computed(() => uploadQueue.value.filter(item => item.status === 'completed' || item.status === 'failed').length);
+ const finishedFilesInQueue = computed(() => uploadQueue.value.filter(item => ['completed', 'failed'].includes(item.status)));
+
+ const clearCompletedUploads = () => {
+ uploadQueue.value = uploadQueue.value.filter(item => !['completed', 'failed'].includes(item.status));
+ };
+
+ return {
+ uploadQueue,
+ currentlyProcessingFile,
+ processingProgress,
+ processingMessage,
+ isProcessingActive,
+ pollInterval,
+ progressPopupMinimized,
+ progressPopupClosed,
+ maxFileSizeMB,
+ chunkingEnabled,
+ chunkingMode,
+ chunkingLimit,
+ chunkingLimitDisplay,
+ recordingDisclaimer,
+ showRecordingDisclaimerModal,
+ pendingRecordingMode,
+
+ // Advanced Options
+ showAdvancedOptions,
+ uploadLanguage,
+ uploadMinSpeakers,
+ uploadMaxSpeakers,
+
+ // Computed
+ totalInQueue,
+ completedInQueue,
+ finishedFilesInQueue,
+
+ // Methods
+ clearCompletedUploads
+ };
+}
diff --git a/static/js/modules/utils/api.js b/static/js/modules/utils/api.js
new file mode 100644
index 00000000..1976f1ad
--- /dev/null
+++ b/static/js/modules/utils/api.js
@@ -0,0 +1,61 @@
+/**
+ * API utility functions with CSRF token handling
+ */
+
+export const createApiClient = (csrfToken) => {
+ const getHeaders = (contentType = 'application/json') => {
+ const headers = {
+ 'X-CSRFToken': csrfToken.value
+ };
+ if (contentType) {
+ headers['Content-Type'] = contentType;
+ }
+ return headers;
+ };
+
+ return {
+ get: async (url) => {
+ const response = await fetch(url, {
+ headers: getHeaders()
+ });
+ return response;
+ },
+
+ post: async (url, data = {}) => {
+ const response = await fetch(url, {
+ method: 'POST',
+ headers: getHeaders(),
+ body: JSON.stringify(data)
+ });
+ return response;
+ },
+
+ postFormData: async (url, formData) => {
+ const response = await fetch(url, {
+ method: 'POST',
+ headers: {
+ 'X-CSRFToken': csrfToken.value
+ },
+ body: formData
+ });
+ return response;
+ },
+
+ delete: async (url) => {
+ const response = await fetch(url, {
+ method: 'DELETE',
+ headers: getHeaders()
+ });
+ return response;
+ },
+
+ put: async (url, data = {}) => {
+ const response = await fetch(url, {
+ method: 'PUT',
+ headers: getHeaders(),
+ body: JSON.stringify(data)
+ });
+ return response;
+ }
+ };
+};
diff --git a/static/js/modules/utils/colors.js b/static/js/modules/utils/colors.js
new file mode 100644
index 00000000..14ac47f4
--- /dev/null
+++ b/static/js/modules/utils/colors.js
@@ -0,0 +1,50 @@
+/**
+ * Color utility functions
+ */
+
+/**
+ * Calculate the relative luminance of a color
+ * Based on WCAG contrast ratio formula
+ * @param {string} hexColor - Hex color code (e.g., "#RRGGBB" or "#RGB")
+ * @returns {number} Luminance value between 0 and 1
+ */
+function calculateLuminance(hexColor) {
+ // Remove # if present
+ const hex = hexColor.replace('#', '');
+
+ // Convert 3-digit hex to 6-digit
+ const fullHex = hex.length === 3
+ ? hex.split('').map(char => char + char).join('')
+ : hex;
+
+ // Parse RGB values
+ const r = parseInt(fullHex.substr(0, 2), 16) / 255;
+ const g = parseInt(fullHex.substr(2, 2), 16) / 255;
+ const b = parseInt(fullHex.substr(4, 2), 16) / 255;
+
+ // Calculate relative luminance using simplified formula
+ // (More accurate would use gamma correction, but this is sufficient)
+ return 0.299 * r + 0.587 * g + 0.114 * b;
+}
+
+/**
+ * Get the appropriate text color (black or white) for a given background color
+ * Ensures readable contrast based on background luminance
+ * @param {string} bgColor - Background color in hex format
+ * @returns {string} Either 'white' or 'black'
+ */
+export function getContrastTextColor(bgColor) {
+ if (!bgColor) {
+ return 'white'; // Default to white for undefined colors
+ }
+
+ try {
+ const luminance = calculateLuminance(bgColor);
+ // Threshold of 0.65: only very light backgrounds get black text
+ // This ensures medium/dark colors like greens, blues still get white text
+ return luminance > 0.65 ? 'black' : 'white';
+ } catch (e) {
+ console.warn('Failed to calculate contrast color for:', bgColor, e);
+ return 'white'; // Fallback to white
+ }
+}
diff --git a/static/js/modules/utils/dates.js b/static/js/modules/utils/dates.js
new file mode 100644
index 00000000..768e93da
--- /dev/null
+++ b/static/js/modules/utils/dates.js
@@ -0,0 +1,67 @@
+/**
+ * Date comparison utility functions
+ */
+
+export const isSameDay = (date1, date2) => {
+ return date1.getFullYear() === date2.getFullYear() &&
+ date1.getMonth() === date2.getMonth() &&
+ date1.getDate() === date2.getDate();
+};
+
+export const isToday = (date) => {
+ const today = new Date();
+ return isSameDay(date, today);
+};
+
+export const isYesterday = (date) => {
+ const yesterday = new Date();
+ yesterday.setDate(yesterday.getDate() - 1);
+ return isSameDay(date, yesterday);
+};
+
+export const isThisWeek = (date) => {
+ const now = new Date();
+ const startOfWeek = new Date(now);
+ const day = now.getDay();
+ const diff = now.getDate() - day + (day === 0 ? -6 : 1); // Monday as start of week
+ startOfWeek.setDate(diff);
+ startOfWeek.setHours(0, 0, 0, 0);
+
+ const endOfWeek = new Date(startOfWeek);
+ endOfWeek.setDate(startOfWeek.getDate() + 6);
+ endOfWeek.setHours(23, 59, 59, 999);
+
+ return date >= startOfWeek && date <= endOfWeek;
+};
+
+export const isLastWeek = (date) => {
+ const now = new Date();
+ const startOfLastWeek = new Date(now);
+ const day = now.getDay();
+ const diff = now.getDate() - day + (day === 0 ? -6 : 1) - 7; // Previous Monday
+ startOfLastWeek.setDate(diff);
+ startOfLastWeek.setHours(0, 0, 0, 0);
+
+ const endOfLastWeek = new Date(startOfLastWeek);
+ endOfLastWeek.setDate(startOfLastWeek.getDate() + 6);
+ endOfLastWeek.setHours(23, 59, 59, 999);
+
+ return date >= startOfLastWeek && date <= endOfLastWeek;
+};
+
+export const isThisMonth = (date) => {
+ const now = new Date();
+ return date.getFullYear() === now.getFullYear() && date.getMonth() === now.getMonth();
+};
+
+export const isLastMonth = (date) => {
+ const now = new Date();
+ const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
+ return date.getFullYear() === lastMonth.getFullYear() && date.getMonth() === lastMonth.getMonth();
+};
+
+export const getDateForSorting = (recording, sortBy) => {
+ const dateStr = sortBy === 'meeting_date' ? recording.meeting_date : recording.created_at;
+ if (!dateStr) return null;
+ return new Date(dateStr);
+};
diff --git a/static/js/modules/utils/formatters.js b/static/js/modules/utils/formatters.js
new file mode 100644
index 00000000..db19f014
--- /dev/null
+++ b/static/js/modules/utils/formatters.js
@@ -0,0 +1,137 @@
+/**
+ * Formatting utility functions
+ */
+
+export const formatFileSize = (bytes) => {
+ if (bytes == null || bytes === 0) return '0 Bytes';
+ const k = 1024;
+ const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
+ if (bytes < 0) bytes = 0;
+ const i = bytes === 0 ? 0 : Math.max(0, Math.floor(Math.log(bytes) / Math.log(k)));
+ const size = i === 0 ? bytes : parseFloat((bytes / Math.pow(k, i)).toFixed(2));
+ return size + ' ' + sizes[i];
+};
+
+export const formatDisplayDate = (dateString) => {
+ if (!dateString) return '';
+ try {
+ let date = new Date(dateString);
+
+ if (isNaN(date.getTime())) {
+ if (/^\d{4}-\d{2}-\d{2}$/.test(dateString)) {
+ date = new Date(dateString + 'T00:00:00');
+ } else {
+ return dateString;
+ }
+ }
+
+ if (isNaN(date.getTime())) {
+ return dateString;
+ }
+
+ return date.toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric' });
+ } catch (e) {
+ console.error("Error formatting date:", e);
+ return dateString;
+ }
+};
+
+export const formatShortDate = (dateString) => {
+ if (!dateString) return '';
+ try {
+ let date = new Date(dateString);
+
+ if (isNaN(date.getTime())) {
+ if (/^\d{4}-\d{2}-\d{2}$/.test(dateString)) {
+ date = new Date(dateString + 'T00:00:00');
+ } else {
+ return dateString;
+ }
+ }
+
+ if (isNaN(date.getTime())) {
+ return dateString;
+ }
+
+ const now = new Date();
+ const isCurrentYear = date.getFullYear() === now.getFullYear();
+
+ if (isCurrentYear) {
+ return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
+ } else {
+ return date.toLocaleDateString(undefined, { year: '2-digit', month: 'short', day: 'numeric' });
+ }
+ } catch (e) {
+ console.error("Error formatting short date:", e);
+ return dateString;
+ }
+};
+
+export const formatStatus = (status, t) => {
+ if (!status || status === 'COMPLETED') return '';
+ const statusMap = {
+ 'PENDING': t('status.queued'),
+ 'PROCESSING': t('status.processing'),
+ 'TRANSCRIBING': t('status.transcribing'),
+ 'SUMMARIZING': t('status.summarizing'),
+ 'FAILED': t('status.failed'),
+ 'UPLOADING': t('status.uploading')
+ };
+ return statusMap[status] || status.charAt(0).toUpperCase() + status.slice(1).toLowerCase();
+};
+
+export const getStatusClass = (status) => {
+ switch(status) {
+ case 'PENDING': return 'status-pending';
+ case 'PROCESSING': return 'status-processing';
+ case 'SUMMARIZING': return 'status-summarizing';
+ case 'COMPLETED': return '';
+ case 'FAILED': return 'status-failed';
+ default: return 'status-pending';
+ }
+};
+
+export const formatTime = (seconds) => {
+ const minutes = Math.floor(seconds / 60);
+ const secs = seconds % 60;
+ return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
+};
+
+export const formatDuration = (totalSeconds) => {
+ if (totalSeconds == null || totalSeconds < 0) return 'N/A';
+
+ if (totalSeconds < 1) {
+ return `${totalSeconds.toFixed(2)} seconds`;
+ }
+
+ totalSeconds = Math.round(totalSeconds);
+
+ if (totalSeconds < 60) {
+ return `${totalSeconds} sec`;
+ }
+
+ const hours = Math.floor(totalSeconds / 3600);
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
+ const seconds = totalSeconds % 60;
+
+ let parts = [];
+ if (hours > 0) {
+ parts.push(`${hours} hr`);
+ }
+ if (minutes > 0) {
+ parts.push(`${minutes} min`);
+ }
+ if (hours === 0 && seconds > 0) {
+ parts.push(`${seconds} sec`);
+ }
+
+ return parts.join(' ');
+};
+
+export const formatProcessingDuration = (seconds) => {
+ if (!seconds && seconds !== 0) return null;
+ if (seconds < 60) return `${seconds}s`;
+ const mins = Math.floor(seconds / 60);
+ const secs = seconds % 60;
+ return secs > 0 ? `${mins}m ${secs}s` : `${mins}m`;
+};
diff --git a/static/js/modules/utils/index.js b/static/js/modules/utils/index.js
new file mode 100644
index 00000000..ae213188
--- /dev/null
+++ b/static/js/modules/utils/index.js
@@ -0,0 +1,9 @@
+/**
+ * Utils module exports
+ */
+
+export * from './formatters.js';
+export * from './dates.js';
+export { createApiClient } from './api.js';
+export { showToast } from './toast.js';
+export { getContrastTextColor } from './colors.js';
diff --git a/static/js/modules/utils/toast.js b/static/js/modules/utils/toast.js
new file mode 100644
index 00000000..9c4ab606
--- /dev/null
+++ b/static/js/modules/utils/toast.js
@@ -0,0 +1,91 @@
+/**
+ * Toast notification utility
+ */
+
+export const showToast = (message, iconClass = 'fa-info-circle', duration = 3000, type = 'info') => {
+ const container = document.getElementById('toastContainer');
+ if (!container) {
+ console.warn('Toast container not found');
+ return;
+ }
+
+ // Determine colors and styles based on type
+ let bgColor, textColor, iconColor, borderColor;
+
+ switch (type) {
+ case 'success':
+ bgColor = '#10b981'; // green-500
+ textColor = '#ffffff';
+ iconColor = '#ffffff';
+ borderColor = '#059669'; // green-600
+ break;
+ case 'error':
+ bgColor = '#ef4444'; // red-500
+ textColor = '#ffffff';
+ iconColor = '#ffffff';
+ borderColor = '#dc2626'; // red-600
+ break;
+ case 'warning':
+ bgColor = '#f59e0b'; // amber-500
+ textColor = '#ffffff';
+ iconColor = '#ffffff';
+ borderColor = '#d97706'; // amber-600
+ break;
+ case 'info':
+ default:
+ bgColor = '#3b82f6'; // blue-500
+ textColor = '#ffffff';
+ iconColor = '#ffffff';
+ borderColor = '#2563eb'; // blue-600
+ break;
+ }
+
+ const toast = document.createElement('div');
+ toast.className = 'toast-message px-4 py-3 rounded-lg shadow-lg flex items-center gap-3 opacity-0 min-w-[300px]';
+ toast.style.backgroundColor = bgColor;
+ toast.style.color = textColor;
+ toast.style.border = `1px solid ${borderColor}`;
+
+ // Handle icon class - support both old format (just icon name) and new format (full class)
+ let fullIconClass = iconClass;
+ if (!iconClass.includes(' ')) {
+ // Old format: just the icon name like 'fa-check-circle'
+ fullIconClass = `fas ${iconClass}`;
+ }
+
+ toast.innerHTML = `
+ <i class="${fullIconClass}" style="color: ${iconColor}"></i>
+ <span class="flex-1">${message}</span>
+ `;
+
+ // Make toast clickable to dismiss
+ toast.style.cursor = 'pointer';
+
+ container.appendChild(toast);
+
+ // Trigger fly-in animation
+ requestAnimationFrame(() => {
+ toast.classList.remove('opacity-0');
+ toast.classList.add('opacity-100', 'toast-show');
+ });
+
+ // Function to dismiss the toast
+ const dismissToast = () => {
+ toast.classList.remove('opacity-100', 'toast-show');
+ toast.classList.add('opacity-0');
+ setTimeout(() => {
+ if (toast.parentNode) {
+ toast.parentNode.removeChild(toast);
+ }
+ }, 300);
+ };
+
+ // Add click handler to dismiss toast
+ toast.addEventListener('click', () => {
+ clearTimeout(timeoutId);
+ dismissToast();
+ });
+
+ // Auto-dismiss after duration
+ const timeoutId = setTimeout(dismissToast, duration);
+};
diff --git a/static/js/utils/apiClient.js b/static/js/utils/apiClient.js
new file mode 100644
index 00000000..39b5783f
--- /dev/null
+++ b/static/js/utils/apiClient.js
@@ -0,0 +1,99 @@
+/**
+ * API client utilities for making HTTP requests
+ */
+
+class APIError extends Error {
+ constructor(message, status, data) {
+ super(message);
+ this.name = 'APIError';
+ this.status = status;
+ this.data = data;
+ }
+}
+
+export async function apiRequest(url, options = {}) {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+
+ const defaultOptions = {
+ headers: {
+ 'Content-Type': 'application/json',
+ ...(csrfToken && { 'X-CSRFToken': csrfToken })
+ }
+ };
+
+ const mergedOptions = {
+ ...defaultOptions,
+ ...options,
+ headers: {
+ ...defaultOptions.headers,
+ ...options.headers
+ }
+ };
+
+ try {
+ const response = await fetch(url, mergedOptions);
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new APIError(
+ data.error || 'Request failed',
+ response.status,
+ data
+ );
+ }
+
+ return data;
+ } catch (error) {
+ if (error instanceof APIError) {
+ throw error;
+ }
+ throw new APIError(error.message, 0, null);
+ }
+}
+
+export async function uploadFile(url, file, onProgress = null) {
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
+ const formData = new FormData();
+ formData.append('audio_file', file);
+
+ return new Promise((resolve, reject) => {
+ const xhr = new XMLHttpRequest();
+
+ if (onProgress) {
+ xhr.upload.addEventListener('progress', (e) => {
+ if (e.lengthComputable) {
+ const percentComplete = (e.loaded / e.total) * 100;
+ onProgress(percentComplete);
+ }
+ });
+ }
+
+ xhr.addEventListener('load', () => {
+ if (xhr.status >= 200 && xhr.status < 300) {
+ try {
+ const data = JSON.parse(xhr.responseText);
+ resolve(data);
+ } catch (e) {
+ reject(new Error('Invalid response format'));
+ }
+ } else {
+ try {
+ const error = JSON.parse(xhr.responseText);
+ reject(new APIError(error.error || 'Upload failed', xhr.status, error));
+ } catch (e) {
+ reject(new APIError('Upload failed', xhr.status, null));
+ }
+ }
+ });
+
+ xhr.addEventListener('error', () => {
+ reject(new Error('Network error'));
+ });
+
+ xhr.open('POST', url);
+ if (csrfToken) {
+ xhr.setRequestHeader('X-CSRFToken', csrfToken);
+ }
+ xhr.send(formData);
+ });
+}
diff --git a/static/js/utils/audioUtils.js b/static/js/utils/audioUtils.js
new file mode 100644
index 00000000..ce613c2f
--- /dev/null
+++ b/static/js/utils/audioUtils.js
@@ -0,0 +1,61 @@
+/**
+ * Audio processing and visualization utilities
+ */
+
+export function formatFileSize(bytes) {
+ if (bytes === 0) return '0 Bytes';
+ const k = 1024;
+ const sizes = ['Bytes', 'KB', 'MB', 'GB'];
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
+ return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i];
+}
+
+export function createAudioVisualizer(canvas, stream, color = '#3b82f6') {
+ if (!canvas || !stream) return null;
+
+ const audioContext = new (window.AudioContext || window.webkitAudioContext)();
+ const analyser = audioContext.createAnalyser();
+ const microphone = audioContext.createMediaStreamSource(stream);
+
+ analyser.fftSize = 256;
+ const bufferLength = analyser.frequencyBinCount;
+ const dataArray = new Uint8Array(bufferLength);
+
+ microphone.connect(analyser);
+
+ const canvasCtx = canvas.getContext('2d');
+ const WIDTH = canvas.width;
+ const HEIGHT = canvas.height;
+
+ function draw() {
+ requestAnimationFrame(draw);
+ analyser.getByteFrequencyData(dataArray);
+
+ canvasCtx.fillStyle = 'rgb(17, 24, 39)';
+ canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
+
+ const barWidth = (WIDTH / bufferLength) * 2.5;
+ let barHeight;
+ let x = 0;
+
+ for (let i = 0; i < bufferLength; i++) {
+ barHeight = (dataArray[i] / 255) * HEIGHT;
+ canvasCtx.fillStyle = color;
+ canvasCtx.fillRect(x, HEIGHT - barHeight, barWidth, barHeight);
+ x += barWidth + 1;
+ }
+ }
+
+ draw();
+
+ return { audioContext, analyser, stop: () => audioContext.close() };
+}
+
+export function detectBrowser() {
+ const userAgent = navigator.userAgent.toLowerCase();
+ if (userAgent.indexOf('firefox') > -1) return 'firefox';
+ if (userAgent.indexOf('chrome') > -1 && userAgent.indexOf('edge') === -1) return 'chrome';
+ if (userAgent.indexOf('safari') > -1 && userAgent.indexOf('chrome') === -1) return 'safari';
+ if (userAgent.indexOf('edge') > -1) return 'edge';
+ return 'unknown';
+}
diff --git a/static/js/utils/dateUtils.js b/static/js/utils/dateUtils.js
new file mode 100644
index 00000000..ec8cd8c2
--- /dev/null
+++ b/static/js/utils/dateUtils.js
@@ -0,0 +1,83 @@
+/**
+ * Date utility functions for formatting and parsing dates
+ */
+
+export function formatDateTime(dateString) {
+ if (!dateString) return '';
+ const date = new Date(dateString);
+ const now = new Date();
+ const diffMs = now - date;
+ const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
+
+ if (diffDays === 0) {
+ return 'Today at ' + date.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true });
+ } else if (diffDays === 1) {
+ return 'Yesterday at ' + date.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true });
+ } else if (diffDays < 7) {
+ const dayName = date.toLocaleDateString('en-US', { weekday: 'long' });
+ return dayName + ' at ' + date.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true });
+ } else {
+ return date.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
+ }
+}
+
+export function formatTimeAgo(dateString) {
+ if (!dateString) return '';
+ const date = new Date(dateString);
+ const now = new Date();
+ const diffMs = now - date;
+ const diffMins = Math.floor(diffMs / 60000);
+ const diffHours = Math.floor(diffMs / 3600000);
+ const diffDays = Math.floor(diffMs / 86400000);
+
+ if (diffMins < 1) return 'Just now';
+ if (diffMins < 60) return `${diffMins} minute${diffMins > 1 ? 's' : ''} ago`;
+ if (diffHours < 24) return `${diffHours} hour${diffHours > 1 ? 's' : ''} ago`;
+ if (diffDays < 30) return `${diffDays} day${diffDays > 1 ? 's' : ''} ago`;
+
+ const diffMonths = Math.floor(diffDays / 30);
+ if (diffMonths < 12) return `${diffMonths} month${diffMonths > 1 ? 's' : ''} ago`;
+
+ const diffYears = Math.floor(diffDays / 365);
+ return `${diffYears} year${diffYears > 1 ? 's' : ''} ago`;
+}
+
+export function formatDuration(seconds) {
+ if (!seconds || seconds < 0) return '0:00';
+ const hrs = Math.floor(seconds / 3600);
+ const mins = Math.floor((seconds % 3600) / 60);
+ const secs = Math.floor(seconds % 60);
+
+ if (hrs > 0) {
+ return `${hrs}:${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
+ }
+ return `${mins}:${secs.toString().padStart(2, '0')}`;
+}
+
+export function parseDateRange(preset) {
+ const now = new Date();
+ const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
+
+ switch (preset) {
+ case 'today':
+ return { start: today, end: new Date() };
+ case 'yesterday':
+ const yesterday = new Date(today);
+ yesterday.setDate(yesterday.getDate() - 1);
+ return { start: yesterday, end: today };
+ case 'week':
+ const weekStart = new Date(today);
+ weekStart.setDate(weekStart.getDate() - 7);
+ return { start: weekStart, end: new Date() };
+ case 'month':
+ const monthStart = new Date(today);
+ monthStart.setMonth(monthStart.getMonth() - 1);
+ return { start: monthStart, end: new Date() };
+ case 'year':
+ const yearStart = new Date(today);
+ yearStart.setFullYear(yearStart.getFullYear() - 1);
+ return { start: yearStart, end: new Date() };
+ default:
+ return { start: null, end: null };
+ }
+}
diff --git a/static/locales/de.json b/static/locales/de.json
index b92fa624..91b6ab0e 100644
--- a/static/locales/de.json
+++ b/static/locales/de.json
@@ -96,6 +96,12 @@
"transcriptTemplates": "Transkript-Vorlagen",
"promptOptions": "Prompt-Optionen"
},
+ "eventExtraction": {
+ "title": "Ereignisextraktion",
+ "enableLabel": "Automatische Ereignisextraktion aus Transkripten aktivieren",
+ "description": "Wenn aktiviert, identifiziert die KI Meetings, Termine und Fristen in Ihren Aufnahmen und erstellt herunterladbare Kalenderereignisse.",
+ "info": "Extrahierte Ereignisse erscheinen im 'Ereignisse'-Tab bei Aufnahmen, in denen Kalenderelemente erkannt werden."
+ },
"transcriptTemplates": {
"title": "Transkript-Vorlagen",
"description": "Anpassen, wie Transkripte für Download und Export formatiert werden.",
@@ -114,7 +120,9 @@
"viewGuide": "Vorlagen-Leitfaden Anzeigen",
"selectTemplate": "Vorlage Auswählen",
"default": "Standard",
- "downloadWithoutTemplate": "Ohne Vorlage Herunterladen"
+ "downloadWithoutTemplate": "Ohne Vorlage Herunterladen",
+ "downloadDefault": "Standard herunterladen",
+ "chooseTemplate": "Vorlage wählen..."
},
"admin": {
"title": "Administration",
@@ -268,10 +276,16 @@
"editTag": "Tag bearbeiten",
"editTags": "Tags bearbeiten",
"editTranscription": "Transkription bearbeiten",
+ "editSpeakers": "Sprecher bearbeiten...",
"editUser": "Benutzer bearbeiten",
"help": "Hilfe",
"identifySpeakers": "Sprecher identifizieren",
+ "next": "Weiter",
+ "previous": "Zurück",
"refresh": "Refresh",
+ "addSpeaker": "Sprecher hinzufügen",
+ "addSegment": "Segment Hinzufügen",
+ "saveNames": "Namen speichern",
"reprocessSummary": "Zusammenfassung neu verarbeiten",
"reprocessTranscription": "Transkription neu verarbeiten",
"reprocessWithAsr": "Mit ASR neu verarbeiten",
@@ -309,13 +323,35 @@
},
"colorScheme": {
"chooseRecording": "Wählen Sie eine Aufnahme aus der Seitenleiste, um ihre Transkription und Zusammenfassung zu sehen",
+ "darkThemes": "Dunkle Themen",
+ "lightThemes": "Helle Themen",
+ "resetToDefault": "Auf Standard zurücksetzen",
"selectRecording": "Eine Aufnahme auswählen",
"subtitle": "Passen Sie Ihre Benutzeroberfläche mit schönen Farbthemen an",
- "title": "Farbschema"
+ "title": "Farbschema wählen",
+ "themes": {
+ "light": {
+ "blue": { "name": "Ozeanblau", "description": "Klassisches Blau-Thema mit professioneller Anmutung" },
+ "emerald": { "name": "Waldsmaragd", "description": "Frisches grünes Thema für natürliches Gefühl" },
+ "purple": { "name": "Königslila", "description": "Elegantes Lila-Thema mit Raffinesse" },
+ "rose": { "name": "Sonnenuntergang-Rose", "description": "Warmes Rosa-Thema mit sanfter Energie" },
+ "amber": { "name": "Goldenes Bernstein", "description": "Warmes Gelb-Thema für Helligkeit" },
+ "teal": { "name": "Ozean-Türkis", "description": "Kühles Türkis-Thema für Ruhe" }
+ },
+ "dark": {
+ "blue": { "name": "Mitternachtsblau", "description": "Tiefes Blau-Thema für konzentriertes Arbeiten" },
+ "emerald": { "name": "Dunkler Wald", "description": "Sattes grünes Thema für angenehmes Betrachten" },
+ "purple": { "name": "Tiefes Lila", "description": "Mysteriöses Lila-Thema für Kreativität" },
+ "rose": { "name": "Dunkle Rose", "description": "Gedämpftes Rosa-Thema mit subtiler Wärme" },
+ "amber": { "name": "Dunkles Bernstein", "description": "Warmes Braun-Thema für gemütliche Sitzungen" },
+ "teal": { "name": "Tiefes Türkis", "description": "Dunkles Türkis-Thema für ruhigen Fokus" }
+ }
+ }
},
"common": {
"back": "Zurück",
"cancel": "Abbrechen",
+ "changesSaved": "Änderungen gespeichert",
"close": "Schließen",
"confirm": "Bestätigen",
"delete": "Löschen",
@@ -477,6 +513,9 @@
"approachingLimit": "Nähert sich {{limit}}MB-Limit",
"askAboutTranscription": "Fragen zu dieser Transkription stellen",
"audioPlayer": "Audio-Player",
+ "audioDeletedMessage": "Audiodatei wurde archiviert und ist nicht mehr zur Wiedergabe verfügbar.",
+ "audioDeletedTitle": "Audiodatei gelöscht",
+ "audioDeletedDescription": "Die Audiodatei für diese Aufnahme wurde gelöscht, aber die Transkription ist weiterhin verfügbar.",
"autoIdentify": "Automatisch identifizieren",
"bothAudioDesc": "Nimmt Ihre Stimme + Meeting-Teilnehmer auf (empfohlen für Online-Meetings)",
"clearFilters": "Filter löschen",
@@ -490,9 +529,12 @@
"discard": "Verwerfen",
"endTime": "Ende",
"enterNameFor": "Namen eingeben für",
+ "enterSpeakerName": "Sprechername eingeben...",
"entireScreen": "Gesamter Bildschirm",
"estimatedSize": "Geschätzte Größe",
"generatingSummary": "Generiere Zusammenfassung...",
+ "groups": "Gruppen",
+ "identifying": "Identifiziere...",
"howToRecordSystemAudio": "Wie man System-Audio aufnimmt",
"importantNote": "Wichtiger Hinweis",
"lines": "{{count}} Zeilen",
@@ -502,9 +544,14 @@
"microphoneDesc": "Nimmt nur Ihre Stimme auf",
"modelReasoning": "Modell-Begründung",
"moreSpeakersThanColors": "Mehr Sprecher als verfügbare Farben",
+ "navigate": "Navigiere",
"noDateSet": "Kein Datum gesetzt",
"noParticipants": "Keine Teilnehmer",
"noTagsCreated": "Noch keine Tags erstellt.",
+ "of": "von",
+ "playFromHere": "Von hier abspielen",
+ "addSegmentBelow": "Segment darunter hinzufügen",
+ "deleteSegment": "Segment löschen",
"processingTime": "Verarbeitungszeit",
"processingTimeDescription": "Dies kann einige Minuten dauern. Sie können die App während der Verarbeitung weiter verwenden.",
"processingTranscription": "Verarbeite Transkription...",
@@ -519,6 +566,7 @@
"shareTabAudio": "Tab-Audio teilen",
"sharedOn": "Geteilt am",
"sharingWindowNoAudio": "Das Teilen eines \"Fensters\" nimmt kein Audio auf.",
+ "speakerName": "Sprechername",
"speakerCount": "Sprecher",
"specificBrowserTab": "spezifischen Browser-Tab",
"startTime": "Start",
@@ -533,7 +581,10 @@
"uploadRecordingNotes": "Aufnahme und Notizen hochladen",
"whatWillHappen": "Was wird passieren?",
"whyNotWorking": "Warum funktioniert es nicht?",
- "speakers": "Sprecher"
+ "youHaveXSpeakers": "Sie haben {{count}} Sprecher, aber nur 8 eindeutige Farben sind verfügbar. Die Farben wiederholen sich nach dem 8. Sprecher.",
+ "speakers": "Sprecher",
+ "publicLinkDesc": "Jeder mit diesem Link kann auf die Aufnahme zugreifen",
+ "internalSharingDesc": "Mit bestimmten Benutzern in Ihrer Organisation teilen"
},
"inquire": {
"title": "Nachfragen",
@@ -576,6 +627,43 @@
"ru": "Russisch",
"zh": "Chinesisch"
},
+ "speakersManagement": {
+ "description": "Verwalten Sie Ihre gespeicherten Sprecher. Diese werden automatisch gespeichert, wenn Sie Sprechernamen in Ihren Aufnahmen verwenden.",
+ "loadingSpeakers": "Sprecher werden geladen...",
+ "failedToLoad": "Fehler beim Laden der Sprecher",
+ "noSpeakersYet": "Noch keine Sprecher gespeichert",
+ "speakersWillAppear": "Sprecher erscheinen hier, wenn Sie Sprechernamen in Ihren Aufnahmen verwenden",
+ "totalSpeakers": "Sprecher gespeichert",
+ "usedTimes": "Verwendet",
+ "lastUsed": "Zuletzt verwendet",
+ "created": "Erstellt",
+ "used": "Verwendet",
+ "time": "Mal",
+ "times": "Mal",
+ "last": "Zuletzt",
+ "added": "Hinzugefügt",
+ "voiceProfile": "Stimmprofil",
+ "voiceMatchSuggestions": "Stimmübereinstimmungs-Vorschläge",
+ "match": "Übereinstimmung",
+ "confidence": "Zuverlässigkeit",
+ "confidenceHigh": "hoch",
+ "confidenceMedium": "mittel",
+ "confidenceLow": "niedrig",
+ "samples": "Proben",
+ "sample": "Probe",
+ "viewSnippets": "Ausschnitte Anzeigen",
+ "noSnippetsAvailable": "Keine Ausschnitte verfügbar",
+ "failedToLoadSnippets": "Fehler beim Laden der Ausschnitte",
+ "mergeSpeakers": "Sprecher Zusammenführen",
+ "selectToMerge": "Wählen Sie 2+ zum Zusammenführen",
+ "mergeNSpeakers": "{{count}} Sprecher Zusammenführen",
+ "speakersToMerge": "Zusammenzuführende Sprecher:",
+ "keepThisSpeaker": "Diesen Sprecher behalten (andere werden damit zusammengeführt):",
+ "mergeDescription": "Kombinieren Sie mehrere Sprecherprofile zu einem. Alle Einbettungen, Ausschnitte und Nutzungsdaten werden zusammengeführt.",
+ "targetWillReceive": "Der ausgewählte Sprecher erhält alle Stimmdaten und Ausschnitte der anderen.",
+ "mergeSuccess": "Sprecher erfolgreich zusammengeführt",
+ "mergeFailed": "Fehler beim Zusammenführen der Sprecher"
+ },
"manageSpeakersModal": {
"created": "Erstellt",
"description": "Verwalten Sie Ihre gespeicherten Sprecher. Diese werden automatisch gespeichert, wenn Sie Sprechernamen in Ihren Aufnahmen verwenden.",
@@ -620,10 +708,13 @@
"wordCount": "Wortanzahl"
},
"modal": {
+ "addSpeaker": "Neuen Sprecher Hinzufügen",
"colorScheme": "Farbschema",
"deleteRecording": "Aufnahme löschen",
"editAsrTranscription": "ASR-Transkription bearbeiten",
"editRecording": "Aufnahme bearbeiten",
+ "editSpeakers": "Sprecher Bearbeiten",
+ "editParticipants": "Teilnehmer Bearbeiten",
"editTags": "Aufnahme-Tags bearbeiten",
"editTranscription": "Transkription bearbeiten",
"identifySpeakers": "Sprecher identifizieren",
@@ -648,6 +739,12 @@
"recording": "Aufnahme",
"settings": "Einstellungen",
"signOut": "Abmelden",
+ "teamManagement": "Gruppenverwaltung",
+ "groupManagement": "Gruppenverwaltung",
+ "groupManagement": "Gruppenverwaltung",
+ "groupManagement": "Gruppenverwaltung",
+ "groupManagement": "Gruppenverwaltung",
+ "groupManagement": "Gruppenverwaltung",
"upload": "Hochladen",
"userProfile": "Benutzerprofil"
},
@@ -708,13 +805,6 @@
"title": "Einstellungen",
"twoFactorAuth": "Zwei-Faktor-Authentifizierung"
},
- "speakersManagement": {
- "used": "Verwendet",
- "time": "Mal",
- "times": "Mal",
- "last": "Zuletzt",
- "added": "Hinzugefügt"
- },
"sharedTranscripts": {
"noSharedTranscripts": "Sie haben noch keine Transkripte geteilt.",
"sharedOn": "Geteilt am",
@@ -724,8 +814,28 @@
"sharedTranscriptsPage": {
"noSharedTranscripts": "Sie haben noch keine Transkripte geteilt."
},
+ "sharing": {
+ "publicLink": "Öffentlicher Link",
+ "publicLinks": "öffentliche(r) Link(s)",
+ "publicLinksGenerated": "öffentliche(r) Link(s) generiert",
+ "internalSharing": "Interne Freigabe",
+ "searchUsers": "Benutzer suchen...",
+ "canEdit": "Kann bearbeiten",
+ "canReshare": "Kann weitergeben",
+ "notSharedYet": "Noch nicht geteilt",
+ "sharedBy": "Geteilt von",
+ "sharedWith": "Geteilt mit",
+ "sharedBadge": "Geteilt",
+ "publicBadge": "Öffentlich",
+ "teamBadge": "Group",
+ "teamRecording": "Team-Aufnahme",
+ "users": "Benutzer",
+ "unknown": "Unbekannt"
+ },
"sidebar": {
"advancedSearch": "Erweiterte Suche",
+ "archived": "Archiviert",
+ "archivedRecordings": "Archivierte Aufnahmen",
"dateRange": "Datumsbereich",
"filters": "Filter",
"highlighted": "Hervorgehoben",
@@ -739,6 +849,7 @@
"older": "Älter",
"removeFromHighlighted": "Von Favoriten entfernen",
"searchRecordings": "Aufnahmen suchen...",
+ "sharedWithMe": "Mit mir geteilt",
"sortBy": "Sortieren nach",
"sortByDate": "Erstellungsdatum",
"sortByMeetingDate": "Meeting-Datum",
@@ -788,8 +899,10 @@
"addTag": "Tag hinzufügen",
"clearTagFilter": "Filter löschen",
"createTag": "Tag erstellen",
+ "currentTags": "Aktuelle Tags",
"filterByTag": "Nach Tag filtern",
"manageAllTags": "Alle Tags verwalten",
+ "noAvailableTags": "Keine verfügbaren Tags",
"noTags": "Keine Tags",
"removeTag": "Tag entfernen",
"tagColor": "Tag-Farbe",
@@ -803,6 +916,43 @@
"noTagsAssigned": "Dieser Aufnahme sind keine Tags zugewiesen",
"searchTags": "Tags suchen..."
},
+ "groups": {
+ "title": "Gruppenverwaltung",
+ "createTeam": "Team erstellen",
+ "editTeam": "Team bearbeiten",
+ "deleteTeam": "Team löschen",
+ "updateTeam": "Team aktualisieren",
+ "teamName": "Team-Name",
+ "teamNamePlaceholder": "Team-Name eingeben",
+ "teamLead": "Teamleiter",
+ "selectTeamLead": "Teamleiter auswählen...",
+ "members": "Mitglieder",
+ "noMembers": "Keine Mitglieder in diesem Team",
+ "addMembers": "Mitglieder hinzufügen...",
+ "searchUsers": "Benutzer suchen...",
+ "syncTeamShares": "Team-Freigaben synchronisieren",
+ "syncTeamSharesDescription": "Dadurch werden alle Aufnahmen mit Team-Tags rückwirkend mit den entsprechenden Team-Mitgliedern gemäß den Freigabeeinstellungen des Tags geteilt.",
+ "syncComplete": "Team-Freigaben erfolgreich synchronisiert",
+ "confirmDelete": "Sind Sie sicher, dass Sie dieses Team löschen möchten? Diese Aktion kann nicht rückgängig gemacht werden.",
+ "teamTags": "Team-Tags",
+ "createTeamTag": "Neuen Team-Tag erstellen",
+ "editTeamTag": "Team-Tag bearbeiten",
+ "retentionPeriod": "Aufbewahrungsdauer (Tage)",
+ "retentionPlaceholder": "Leer lassen für globale Aufbewahrung",
+ "retentionHelp": "Aufnahmen mit diesem Tag werden nach dieser Anzahl von Tagen gelöscht. Leer lassen für globale Aufbewahrung ({{days}} Tage).",
+ "dayRetention": "Tage Aufbewahrung",
+ "globalRetention": "Globale Aufbewahrung",
+ "autoShare": "Automatisch teilen",
+ "autoShareTeam": "Aufnahmen automatisch mit allen Team-Mitgliedern teilen, wenn dieser Tag angewendet wird",
+ "shareWithAdmins": "Aufnahmen mit Team-Administratoren teilen, wenn dieser Tag angewendet wird",
+ "autoShareNote": "Hinweis: Wenn beide aktiviert sind, haben alle Team-Mitglieder Zugriff. Wenn nur \"Team-Administratoren\" aktiviert ist, haben nur Teamleiter Zugriff.",
+ "deletionExempt": "Von Löschung ausgenommen",
+ "deletionExemptHelp": "Aufnahmen mit diesem Tag werden von der automatischen Löschung ausgenommen, auch wenn sie die Aufbewahrungsdauer überschreiten.",
+ "autoSharesWithTeam": "Teilt automatisch mit allen Team-Mitgliedern",
+ "sharesWithAdminsOnly": "Teilt nur mit Team-Administratoren",
+ "noTeams": "Noch keine Teams erstellt",
+ "noTeamTags": "Noch keine Team-Tags erstellt"
+ },
"time": {
"dayAgo": "Vor 1 Tag",
"daysAgo": "Vor {{count}} Tagen",
@@ -859,12 +1009,6 @@
"uploadProgress": {
"title": "Upload-Fortschritt"
},
- "eventExtraction": {
- "title": "Ereignisextraktion",
- "enableLabel": "Automatische Ereignisextraktion aus Transkripten aktivieren",
- "description": "Wenn aktiviert, identifiziert die KI Meetings, Termine und Fristen in Ihren Aufnahmen und erstellt herunterladbare Kalenderereignisse.",
- "info": "Extrahierte Ereignisse erscheinen im 'Ereignisse'-Tab bei Aufnahmen, in denen Kalenderelemente erkannt werden."
- },
"events": {
"title": "Ereignisse",
"add": "Hinzufügen",
@@ -874,5 +1018,38 @@
"end": "Ende",
"location": "Ort",
"attendees": "Teilnehmer"
+ },
+ "tooltips": {
+ "copyTranscript": "Transkript kopieren",
+ "downloadTranscriptWithTemplate": "Transkript mit Vorlage herunterladen",
+ "editTranscript": "Transkript bearbeiten",
+ "doubleClickToEdit": "Doppelklicken zum Bearbeiten",
+ "editTitle": "Titel bearbeiten",
+ "markAsRead": "Als gelesen markieren",
+ "moveToInbox": "In Posteingang verschieben",
+ "removeHighlight": "Hervorhebung entfernen",
+ "highlight": "Hervorheben",
+ "reprocessWithAsr": "Mit ASR neu verarbeiten",
+ "reprocessTranscription": "Transkript neu verarbeiten",
+ "shareWithUsers": "Mit Benutzern teilen",
+ "removeFromQueue": "Aus Warteschlange entfernen",
+ "changeSpeaker": "Sprecher ändern",
+ "editText": "Text bearbeiten",
+ "clearChat": "Chat leeren",
+ "restoreChat": "Chat wiederherstellen",
+ "maximizeChat": "Chat maximieren",
+ "switchToLightMode": "Zum Hellmodus Wechseln",
+ "switchToDarkMode": "Zum Dunkelmodus Wechseln",
+ "revokePublicSharing": "Öffentliche Freigabeberechtigung widerrufen",
+ "grantPublicSharing": "Öffentliche Freigabeberechtigung erteilen",
+ "removeAdmin": "Admin Entfernen",
+ "makeAdmin": "Zum Admin Machen",
+ "manageMembers": "Mitglieder Verwalten",
+ "manageTeamTags": "Gruppen-Tags Verwalten",
+ "editTeam": "Gruppe Bearbeiten",
+ "deleteTeam": "Gruppe Löschen",
+ "removeFromTeam": "Aus Team entfernen",
+ "followPlayerDisabled": "Automatisches Scrollen aktivieren - Transkript folgt der Audiowiedergabe",
+ "followPlayerEnabled": "Automatisches Scrollen deaktivieren - Transkript bleibt an Ort und Stelle"
}
-}
\ No newline at end of file
+}
diff --git a/static/locales/en.json b/static/locales/en.json
index 8866488b..b4f1aba2 100644
--- a/static/locales/en.json
+++ b/static/locales/en.json
@@ -120,7 +120,9 @@
"viewGuide": "View Template Guide",
"selectTemplate": "Select Template",
"default": "Default",
- "downloadWithoutTemplate": "Download without template"
+ "downloadWithoutTemplate": "Download without template",
+ "downloadDefault": "Download default",
+ "chooseTemplate": "Choose template..."
},
"admin": {
"title": "Admin",
@@ -249,11 +251,13 @@
"yes": "Yes"
},
"buttons": {
+ "addSpeaker": "Add Speaker",
"cancel": "Cancel",
"clearAllFilters": "Clear all filters",
"clearCompleted": "Clear completed uploads",
"clearSearchText": "Clear search text",
"close": "Close",
+ "copy": "Copy",
"copyMessage": "Copy message",
"copyNotes": "Copy notes",
"copySummary": "Copy summary",
@@ -274,10 +278,15 @@
"editTag": "Edit tag",
"editTags": "Edit Tags",
"editTranscription": "Edit transcription",
+ "editSpeakers": "Edit Speakers...",
"editUser": "Edit User",
"help": "Help",
"identifySpeakers": "Identify speakers",
+ "next": "Next",
+ "previous": "Previous",
"refresh": "Refresh",
+ "addSegment": "Add Segment",
+ "saveNames": "Save Names",
"reprocessSummary": "Reprocess summary",
"reprocessTranscription": "Reprocess transcription",
"reprocessWithAsr": "Reprocess with ASR",
@@ -315,13 +324,35 @@
},
"colorScheme": {
"chooseRecording": "Choose a recording from the sidebar to view its transcription and summary",
+ "darkThemes": "Dark Themes",
+ "lightThemes": "Light Themes",
+ "resetToDefault": "Reset to Default",
"selectRecording": "Select a Recording",
"subtitle": "Customize your interface with beautiful color themes",
- "title": "Color Scheme"
+ "title": "Choose Color Scheme",
+ "themes": {
+ "light": {
+ "blue": { "name": "Ocean Blue", "description": "Classic blue theme with professional appeal" },
+ "emerald": { "name": "Forest Emerald", "description": "Fresh green theme for a natural feel" },
+ "purple": { "name": "Royal Purple", "description": "Elegant purple theme with sophistication" },
+ "rose": { "name": "Sunset Rose", "description": "Warm pink theme with gentle energy" },
+ "amber": { "name": "Golden Amber", "description": "Warm yellow theme for brightness" },
+ "teal": { "name": "Ocean Teal", "description": "Cool teal theme for tranquility" }
+ },
+ "dark": {
+ "blue": { "name": "Midnight Blue", "description": "Deep blue theme for focused work" },
+ "emerald": { "name": "Dark Forest", "description": "Rich green theme for comfortable viewing" },
+ "purple": { "name": "Deep Purple", "description": "Mysterious purple theme for creativity" },
+ "rose": { "name": "Dark Rose", "description": "Muted pink theme with subtle warmth" },
+ "amber": { "name": "Dark Amber", "description": "Warm brown theme for cozy sessions" },
+ "teal": { "name": "Deep Teal", "description": "Dark teal theme for calm focus" }
+ }
+ }
},
"common": {
"back": "Back",
"cancel": "Cancel",
+ "changesSaved": "Changes saved",
"close": "Close",
"confirm": "Confirm",
"delete": "Delete",
@@ -483,6 +514,9 @@
"approachingLimit": "Approaching {{limit}}MB limit",
"askAboutTranscription": "Ask questions about this transcription",
"audioPlayer": "Audio Player",
+ "audioDeletedMessage": "Audio file has been archived and is no longer available for playback.",
+ "audioDeletedTitle": "Audio file deleted",
+ "audioDeletedDescription": "The audio file for this recording has been deleted, but the transcription remains available.",
"autoIdentify": "Auto Identify",
"bothAudioDesc": "Records your voice + meeting participants (recommended for online meetings)",
"clearFilters": "clear filters",
@@ -496,9 +530,12 @@
"discard": "Discard",
"endTime": "End",
"enterNameFor": "Enter name for",
+ "enterSpeakerName": "Enter speaker name...",
"entireScreen": "Entire Screen",
"estimatedSize": "Estimated size",
"generatingSummary": "Generating summary...",
+ "groups": "groups",
+ "identifying": "Identifying...",
"howToRecordSystemAudio": "How to Record System Audio",
"importantNote": "Important note",
"lines": "{{count}} lines",
@@ -508,9 +545,14 @@
"microphoneDesc": "Records your voice only",
"modelReasoning": "Model Reasoning",
"moreSpeakersThanColors": "More speakers than available colors",
+ "navigate": "Navigate",
"noDateSet": "No date set",
"noParticipants": "No participants",
"noTagsCreated": "No tags created yet.",
+ "of": "of",
+ "playFromHere": "Play from here",
+ "addSegmentBelow": "Add segment below",
+ "deleteSegment": "Delete segment",
"processingTime": "Processing time",
"processingTimeDescription": "This may take a few minutes to complete. You can continue using the app while processing.",
"processingTranscription": "Processing transcription...",
@@ -525,6 +567,7 @@
"shareTabAudio": "Share tab audio",
"sharedOn": "Shared on",
"sharingWindowNoAudio": "Sharing a \"Window\" will not capture audio.",
+ "speakerName": "Speaker Name",
"speakerCount": "Speaker",
"specificBrowserTab": "specific browser tab",
"startTime": "Start",
@@ -540,7 +583,9 @@
"whatWillHappen": "What will happen?",
"whyNotWorking": "Why isn't it working?",
"youHaveXSpeakers": "You have {{count}} speakers, but only 8 unique colors are available. Colors will repeat after the 8th speaker.",
- "speakers": "Speakers"
+ "speakers": "Speakers",
+ "publicLinkDesc": "Anyone with this link can access the recording",
+ "internalSharingDesc": "Share with specific users in your organization"
},
"inquire": {
"title": "Inquire",
@@ -597,7 +642,28 @@
"time": "time",
"times": "times",
"last": "Last",
- "added": "Added"
+ "added": "Added",
+ "voiceProfile": "Voice Profile",
+ "voiceMatchSuggestions": "Voice Match Suggestions",
+ "match": "match",
+ "confidence": "Confidence",
+ "confidenceHigh": "high",
+ "confidenceMedium": "medium",
+ "confidenceLow": "low",
+ "samples": "samples",
+ "sample": "sample",
+ "viewSnippets": "View Snippets",
+ "noSnippetsAvailable": "No snippets available",
+ "failedToLoadSnippets": "Failed to load snippets",
+ "mergeSpeakers": "Merge Speakers",
+ "selectToMerge": "Select 2+ to Merge",
+ "mergeNSpeakers": "Merge {{count}} Speakers",
+ "speakersToMerge": "Speakers to merge:",
+ "keepThisSpeaker": "Keep this speaker (others will be merged into it):",
+ "mergeDescription": "Combine multiple speaker profiles into one. All embeddings, snippets, and usage data will be merged.",
+ "targetWillReceive": "The selected speaker will receive all voice data and snippets from the others.",
+ "mergeSuccess": "Speakers merged successfully",
+ "mergeFailed": "Failed to merge speakers"
},
"manageSpeakersModal": {
"created": "Created",
@@ -643,10 +709,13 @@
"wordCount": "Word Count"
},
"modal": {
+ "addSpeaker": "Add New Speaker",
"colorScheme": "Color Scheme",
"deleteRecording": "Delete Recording",
"editAsrTranscription": "Edit ASR Transcription",
"editRecording": "Edit Recording",
+ "editSpeakers": "Edit Speakers",
+ "editParticipants": "Edit Participants",
"editTags": "Edit Recording Tags",
"editTranscription": "Edit Transcription",
"identifySpeakers": "Identify Speakers",
@@ -655,12 +724,12 @@
"reprocessTranscription": "Reprocess Transcription",
"resetStatus": "Reset Recording Status?",
"shareRecording": "Share Recording",
- "sharedTranscripts": "My Shared Transcripts",
+ "sharedTranscripts": "Shared Transcripts",
"systemAudioHelp": "System Audio Help"
},
"nav": {
"account": "Account",
- "accountSettings": "Account Settings",
+ "accountSettings": "Account Settings",
"admin": "Admin",
"adminDashboard": "Admin Dashboard",
"darkMode": "Dark Mode",
@@ -671,6 +740,8 @@
"recording": "Recording",
"settings": "Settings",
"signOut": "Sign Out",
+ "teamManagement": "Group Management",
+ "groupManagement": "Group Management",
"upload": "Upload",
"userProfile": "User Profile"
},
@@ -737,11 +808,31 @@
"shareSummary": "Share Summary",
"shareNotes": "Share Notes"
},
+ "sharing": {
+ "publicLink": "Public Link",
+ "publicLinks": "public link(s)",
+ "publicLinksGenerated": "public link(s) generated",
+ "internalSharing": "Internal Sharing",
+ "searchUsers": "Search users...",
+ "canEdit": "Can edit",
+ "canReshare": "Can reshare",
+ "notSharedYet": "Not shared yet",
+ "sharedBy": "Shared by",
+ "sharedWith": "Shared with",
+ "sharedBadge": "Shared",
+ "publicBadge": "Public",
+ "teamBadge": "Group",
+ "teamRecording": "Group recording",
+ "users": "user(s)",
+ "unknown": "Unknown"
+ },
"sharedTranscriptsPage": {
"noSharedTranscripts": "You have not shared any transcripts yet."
},
"sidebar": {
"advancedSearch": "Advanced Search",
+ "archived": "Archived",
+ "archivedRecordings": "Archived Recordings",
"dateRange": "Date Range",
"filters": "Filters",
"highlighted": "Highlighted",
@@ -755,6 +846,7 @@
"older": "Older",
"removeFromHighlighted": "Remove from starred",
"searchRecordings": "Search recordings...",
+ "sharedWithMe": "Shared with Me",
"sortBy": "Sort By",
"sortByDate": "Created Date",
"sortByMeetingDate": "Meeting Date",
@@ -804,8 +896,10 @@
"addTag": "Add Tag",
"clearTagFilter": "Clear filter",
"createTag": "Create Tag",
+ "currentTags": "Current Tags",
"filterByTag": "Filter by tag",
"manageAllTags": "Manage All Tags",
+ "noAvailableTags": "No available tags",
"noTags": "No tags",
"removeTag": "Remove Tag",
"tagColor": "Tag Color",
@@ -819,6 +913,43 @@
"noTagsAssigned": "No tags assigned to this recording",
"searchTags": "Search tags..."
},
+ "groups": {
+ "title": "Group Management",
+ "createTeam": "Create Group",
+ "editTeam": "Edit Group",
+ "deleteTeam": "Delete Group",
+ "updateTeam": "Update Group",
+ "teamName": "Group Name",
+ "teamNamePlaceholder": "Enter group name",
+ "teamLead": "Group Lead",
+ "selectTeamLead": "Select group lead...",
+ "members": "Members",
+ "noMembers": "No members in this group",
+ "addMembers": "Add members...",
+ "searchUsers": "Search users...",
+ "syncTeamShares": "Sync Group Shares",
+ "syncTeamSharesDescription": "This will retroactively share all recordings that have group tags with the appropriate group members based on the tag's sharing settings.",
+ "syncComplete": "Group shares synchronized successfully",
+ "confirmDelete": "Are you sure you want to delete this group? This action cannot be undone.",
+ "teamTags": "Group Tags",
+ "createTeamTag": "Create New Group Tag",
+ "editTeamTag": "Edit Group Tag",
+ "retentionPeriod": "Retention Period (days)",
+ "retentionPlaceholder": "Leave empty to use global retention",
+ "retentionHelp": "Recordings with this tag will be deleted after this many days. Leave empty to use global retention ({{days}} days).",
+ "dayRetention": "day retention",
+ "globalRetention": "Global retention",
+ "autoShare": "Auto-share",
+ "autoShareTeam": "Auto-share recordings with all team members when this tag is applied",
+ "shareWithAdmins": "Share recordings with team admins when this tag is applied",
+ "autoShareNote": "Note: If both are enabled, all team members will have access. If only \"team admins\" is enabled, only group leads will have access.",
+ "deletionExempt": "Exempt from deletion",
+ "deletionExemptHelp": "Recordings with this tag will be exempt from automatic deletion, even if they exceed the retention period.",
+ "autoSharesWithTeam": "Auto-shares with all team members",
+ "sharesWithAdminsOnly": "Shares with team admins only",
+ "noTeams": "No teams created yet",
+ "noTeamTags": "No group tags created yet"
+ },
"time": {
"dayAgo": "1 day ago",
"daysAgo": "{{count}} days ago",
@@ -884,5 +1015,38 @@
"end": "End",
"location": "Location",
"attendees": "Attendees"
+ },
+ "tooltips": {
+ "copyTranscript": "Copy transcript",
+ "downloadTranscriptWithTemplate": "Download transcript with template",
+ "editTranscript": "Edit transcript",
+ "doubleClickToEdit": "Double-click to edit",
+ "editTitle": "Edit title",
+ "markAsRead": "Mark as read",
+ "moveToInbox": "Move to inbox",
+ "removeHighlight": "Remove highlight",
+ "highlight": "Highlight",
+ "reprocessWithAsr": "Reprocess with ASR",
+ "reprocessTranscription": "Reprocess transcription",
+ "shareWithUsers": "Share with users",
+ "removeFromQueue": "Remove from queue",
+ "changeSpeaker": "Change speaker",
+ "editText": "Edit text",
+ "clearChat": "Clear chat",
+ "restoreChat": "Restore chat",
+ "maximizeChat": "Maximize chat",
+ "switchToLightMode": "Switch to Light Mode",
+ "switchToDarkMode": "Switch to Dark Mode",
+ "revokePublicSharing": "Revoke public sharing permission",
+ "grantPublicSharing": "Grant public sharing permission",
+ "removeAdmin": "Remove Admin",
+ "makeAdmin": "Make Admin",
+ "manageMembers": "Manage Members",
+ "manageTeamTags": "Manage Group Tags",
+ "editTeam": "Edit Group",
+ "deleteTeam": "Delete Group",
+ "removeFromTeam": "Remove from team",
+ "followPlayerDisabled": "Enable auto-scroll - transcript follows audio playback",
+ "followPlayerEnabled": "Disable auto-scroll - transcript stays in place"
}
}
\ No newline at end of file
diff --git a/static/locales/es.json b/static/locales/es.json
index d732a970..f396455b 100644
--- a/static/locales/es.json
+++ b/static/locales/es.json
@@ -120,7 +120,9 @@
"viewGuide": "Ver Guía de Plantillas",
"selectTemplate": "Seleccionar Plantilla",
"default": "Predeterminado",
- "downloadWithoutTemplate": "Descargar sin plantilla"
+ "downloadWithoutTemplate": "Descargar sin plantilla",
+ "downloadDefault": "Descargar predeterminado",
+ "chooseTemplate": "Elegir plantilla..."
},
"admin": {
"title": "Administración",
@@ -249,6 +251,7 @@
"yes": "Sí"
},
"buttons": {
+ "addSegment": "Agregar Segmento",
"cancel": "Cancel",
"clearAllFilters": "Limpiar todos los filtros",
"clearCompleted": "Limpiar cargas completadas",
@@ -274,10 +277,15 @@
"editTag": "Editar etiqueta",
"editTags": "Editar etiquetas",
"editTranscription": "Editar Transcripción",
+ "editSpeakers": "Editar Hablantes...",
"editUser": "Editar usuario",
"help": "Ayuda",
"identifySpeakers": "Identificar Hablantes",
+ "next": "Siguiente",
+ "previous": "Anterior",
"refresh": "Refresh",
+ "addSpeaker": "Añadir Hablante",
+ "saveNames": "Guardar Nombres",
"reprocessSummary": "Reprocesar resumen",
"reprocessTranscription": "Reprocesar transcripción",
"reprocessWithAsr": "Reprocesar con ASR",
@@ -315,13 +323,35 @@
},
"colorScheme": {
"chooseRecording": "Elige una grabación de la barra lateral para ver su transcripción y resumen",
+ "darkThemes": "Temas Oscuros",
+ "lightThemes": "Temas Claros",
+ "resetToDefault": "Restablecer por Defecto",
"selectRecording": "Seleccionar una Grabación",
"subtitle": "Personaliza tu interfaz con hermosos temas de color",
- "title": "Esquema de Color"
+ "title": "Elegir Esquema de Color",
+ "themes": {
+ "light": {
+ "blue": { "name": "Azul Océano", "description": "Tema azul clásico con atractivo profesional" },
+ "emerald": { "name": "Esmeralda Bosque", "description": "Tema verde fresco para sensación natural" },
+ "purple": { "name": "Púrpura Real", "description": "Tema púrpura elegante con sofisticación" },
+ "rose": { "name": "Rosa Atardecer", "description": "Tema rosa cálido con energía suave" },
+ "amber": { "name": "Ámbar Dorado", "description": "Tema amarillo cálido para luminosidad" },
+ "teal": { "name": "Turquesa Océano", "description": "Tema turquesa fresco para tranquilidad" }
+ },
+ "dark": {
+ "blue": { "name": "Azul Medianoche", "description": "Tema azul profundo para trabajo enfocado" },
+ "emerald": { "name": "Bosque Oscuro", "description": "Tema verde rico para visualización cómoda" },
+ "purple": { "name": "Púrpura Profundo", "description": "Tema púrpura misterioso para creatividad" },
+ "rose": { "name": "Rosa Oscuro", "description": "Tema rosa tenue con calidez sutil" },
+ "amber": { "name": "Ámbar Oscuro", "description": "Tema marrón cálido para sesiones acogedoras" },
+ "teal": { "name": "Turquesa Profundo", "description": "Tema turquesa oscuro para enfoque tranquilo" }
+ }
+ }
},
"common": {
"back": "Atrás",
"cancel": "Cancelar",
+ "changesSaved": "Cambios guardados",
"close": "Cerrar",
"confirm": "Confirmar",
"delete": "Eliminar",
@@ -483,6 +513,9 @@
"approachingLimit": "Acercándose al límite de {{limit}}MB",
"askAboutTranscription": "Haz preguntas sobre esta transcripción",
"audioPlayer": "Reproductor de Audio",
+ "audioDeletedMessage": "El archivo de audio ha sido archivado y ya no está disponible para reproducción.",
+ "audioDeletedTitle": "Archivo de audio eliminado",
+ "audioDeletedDescription": "El archivo de audio de esta grabación ha sido eliminado, pero la transcripción sigue disponible.",
"autoIdentify": "Identificar Automáticamente",
"bothAudioDesc": "Graba tu voz + participantes de reunión (recomendado para reuniones en línea)",
"clearFilters": "limpiar filtros",
@@ -499,6 +532,8 @@
"entireScreen": "Pantalla Completa",
"estimatedSize": "Tamaño estimado",
"generatingSummary": "Generando resumen...",
+ "groups": "grupos",
+ "identifying": "Identificando...",
"howToRecordSystemAudio": "Cómo Grabar Audio del Sistema",
"importantNote": "Nota importante",
"lines": "{{count}} líneas",
@@ -508,9 +543,14 @@
"microphoneDesc": "Graba solo tu voz",
"modelReasoning": "Razonamiento del Modelo",
"moreSpeakersThanColors": "Más hablantes que colores disponibles",
+ "navigate": "Navegar",
"noDateSet": "Sin fecha establecida",
"noParticipants": "Sin participantes",
"noTagsCreated": "Aún no se han creado etiquetas.",
+ "of": "de",
+ "playFromHere": "Reproducir desde aquí",
+ "addSegmentBelow": "Añadir segmento debajo",
+ "deleteSegment": "Eliminar segmento",
"processingTime": "Tiempo de procesamiento",
"processingTimeDescription": "Esto puede tardar unos minutos en completarse. Puedes continuar usando la aplicación mientras se procesa.",
"processingTranscription": "Procesando transcripción...",
@@ -539,7 +579,11 @@
"uploadRecordingNotes": "Subir Grabación y Notas",
"whatWillHappen": "¿Qué pasará?",
"whyNotWorking": "¿Por qué no funciona?",
- "speakers": "Hablantes"
+ "youHaveXSpeakers": "Tiene {{count}} oradores, pero solo hay 8 colores únicos disponibles. Los colores se repetirán después del octavo orador.",
+ "speakers": "Hablantes",
+ "publicLinkDesc": "Cualquiera con este enlace puede acceder a la grabación",
+ "internalSharingDesc": "Compartir con usuarios específicos de su organización",
+ "enterSpeakerName": "Ingrese nombre del orador..."
},
"inquire": {
"title": "Consultar",
@@ -582,6 +626,43 @@
"ru": "Ruso",
"zh": "Chino"
},
+ "speakersManagement": {
+ "description": "Administre sus oradores guardados. Estos se guardan automáticamente cuando usa nombres de oradores en sus grabaciones.",
+ "loadingSpeakers": "Cargando oradores...",
+ "failedToLoad": "Error al cargar oradores",
+ "noSpeakersYet": "Aún no hay oradores guardados",
+ "speakersWillAppear": "Los oradores aparecerán aquí cuando use nombres de oradores en sus grabaciones",
+ "totalSpeakers": "oradores guardados",
+ "usedTimes": "Usado",
+ "lastUsed": "Último uso",
+ "created": "Creado",
+ "used": "Usado",
+ "time": "vez",
+ "times": "veces",
+ "last": "Último",
+ "added": "Agregado",
+ "voiceProfile": "Perfil de Voz",
+ "voiceMatchSuggestions": "Sugerencias de Coincidencia de Voz",
+ "match": "coincidencia",
+ "confidence": "Confianza",
+ "confidenceHigh": "alta",
+ "confidenceMedium": "media",
+ "confidenceLow": "baja",
+ "samples": "muestras",
+ "sample": "muestra",
+ "viewSnippets": "Ver Fragmentos",
+ "noSnippetsAvailable": "No hay fragmentos disponibles",
+ "failedToLoadSnippets": "Error al cargar fragmentos",
+ "mergeSpeakers": "Combinar Oradores",
+ "selectToMerge": "Seleccione 2+ para Combinar",
+ "mergeNSpeakers": "Combinar {{count}} Oradores",
+ "speakersToMerge": "Oradores para combinar:",
+ "keepThisSpeaker": "Mantener este orador (los otros se combinarán en él):",
+ "mergeDescription": "Combine múltiples perfiles de oradores en uno. Todas las incrustaciones, fragmentos y datos de uso se combinarán.",
+ "targetWillReceive": "El orador seleccionado recibirá todos los datos de voz y fragmentos de los demás.",
+ "mergeSuccess": "Oradores combinados exitosamente",
+ "mergeFailed": "Error al combinar oradores"
+ },
"manageSpeakersModal": {
"created": "Creado",
"description": "Gestiona tus oradores guardados. Estos se guardan automáticamente cuando usas nombres de oradores en tus grabaciones.",
@@ -626,10 +707,13 @@
"wordCount": "Recuento de Palabras"
},
"modal": {
+ "addSpeaker": "Agregar Nuevo Orador",
"colorScheme": "Esquema de Color",
"deleteRecording": "Eliminar Grabación",
"editAsrTranscription": "Editar Transcripción ASR",
"editRecording": "Editar Grabación",
+ "editSpeakers": "Editar Oradores",
+ "editParticipants": "Editar Participantes",
"editTags": "Editar Etiquetas de Grabación",
"editTranscription": "Editar Transcripción",
"identifySpeakers": "Identificar Hablantes",
@@ -654,6 +738,12 @@
"recording": "Grabación",
"settings": "Configuración",
"signOut": "Cerrar Sesión",
+ "teamManagement": "Gestión de Grupos",
+ "groupManagement": "Gestión de Grupos",
+ "groupManagement": "Gestión de Grupos",
+ "groupManagement": "Gestión de Grupos",
+ "groupManagement": "Gestión de Grupos",
+ "groupManagement": "Gestión de Grupos",
"upload": "Subir",
"userProfile": "Perfil de Usuario"
},
@@ -730,8 +820,28 @@
"sharedTranscriptsPage": {
"noSharedTranscripts": "Aún no has compartido ninguna transcripción."
},
+ "sharing": {
+ "publicLink": "Enlace Público",
+ "publicLinks": "enlace(s) público(s)",
+ "publicLinksGenerated": "enlace(s) público(s) generado(s)",
+ "internalSharing": "Compartir Interno",
+ "searchUsers": "Buscar usuarios...",
+ "canEdit": "Puede editar",
+ "canReshare": "Puede recompartir",
+ "notSharedYet": "Aún no compartido",
+ "sharedBy": "Compartido por",
+ "sharedWith": "Compartido con",
+ "sharedBadge": "Compartido",
+ "publicBadge": "Público",
+ "teamBadge": "Equipo",
+ "teamRecording": "Grabación del equipo",
+ "users": "usuario(s)",
+ "unknown": "Desconocido"
+ },
"sidebar": {
"advancedSearch": "Búsqueda Avanzada",
+ "archived": "Archivado",
+ "archivedRecordings": "Grabaciones Archivadas",
"dateRange": "Rango de Fechas",
"filters": "Filtros",
"highlighted": "Destacado",
@@ -745,6 +855,7 @@
"older": "Más Antiguo",
"removeFromHighlighted": "Quitar de destacados",
"searchRecordings": "Buscar grabaciones...",
+ "sharedWithMe": "Compartido Conmigo",
"sortBy": "Ordenar Por",
"sortByDate": "Fecha de Creación",
"sortByMeetingDate": "Fecha de Reunión",
@@ -794,8 +905,10 @@
"addTag": "Añadir Etiqueta",
"clearTagFilter": "Limpiar filtro",
"createTag": "Crear Etiqueta",
+ "currentTags": "Etiquetas Actuales",
"filterByTag": "Filtrar por etiqueta",
"manageAllTags": "Gestionar Todas las Etiquetas",
+ "noAvailableTags": "No hay etiquetas disponibles",
"noTags": "Sin etiquetas",
"removeTag": "Eliminar Etiqueta",
"tagColor": "Color de Etiqueta",
@@ -809,6 +922,43 @@
"noTagsAssigned": "No hay etiquetas asignadas a esta grabación",
"searchTags": "Buscar etiquetas..."
},
+ "groups": {
+ "title": "Gestión de Grupos",
+ "createTeam": "Crear Equipo",
+ "editTeam": "Editar Equipo",
+ "deleteTeam": "Eliminar Equipo",
+ "updateTeam": "Actualizar Equipo",
+ "teamName": "Nombre del Equipo",
+ "teamNamePlaceholder": "Ingrese nombre del equipo",
+ "teamLead": "Líder del Equipo",
+ "selectTeamLead": "Seleccionar líder del equipo...",
+ "members": "Miembros",
+ "noMembers": "No hay miembros en este equipo",
+ "addMembers": "Añadir miembros...",
+ "searchUsers": "Buscar usuarios...",
+ "syncTeamShares": "Sincronizar Compartidos del Equipo",
+ "syncTeamSharesDescription": "Esto compartirá retroactivamente todas las grabaciones con etiquetas de equipo con los miembros apropiados según la configuración de compartición de la etiqueta.",
+ "syncComplete": "Compartidos del equipo sincronizados exitosamente",
+ "confirmDelete": "¿Estás seguro de que quieres eliminar este equipo? Esta acción no se puede deshacer.",
+ "teamTags": "Etiquetas del Equipo",
+ "createTeamTag": "Crear Nueva Etiqueta de Equipo",
+ "editTeamTag": "Editar Etiqueta de Equipo",
+ "retentionPeriod": "Período de Retención (días)",
+ "retentionPlaceholder": "Dejar vacío para usar retención global",
+ "retentionHelp": "Las grabaciones con esta etiqueta serán eliminadas después de estos días. Dejar vacío para usar retención global ({{days}} días).",
+ "dayRetention": "días de retención",
+ "globalRetention": "Retención global",
+ "autoShare": "Compartir automáticamente",
+ "autoShareTeam": "Compartir automáticamente grabaciones con todos los miembros del equipo cuando se aplique esta etiqueta",
+ "shareWithAdmins": "Compartir grabaciones con administradores del equipo cuando se aplique esta etiqueta",
+ "autoShareNote": "Nota: Si ambos están habilitados, todos los miembros del equipo tendrán acceso. Si solo \"administradores del equipo\" está habilitado, solo los líderes del equipo tendrán acceso.",
+ "deletionExempt": "Exento de eliminación",
+ "deletionExemptHelp": "Las grabaciones con esta etiqueta estarán exentas de eliminación automática, incluso si exceden el período de retención.",
+ "autoSharesWithTeam": "Comparte automáticamente con todos los miembros del equipo",
+ "sharesWithAdminsOnly": "Comparte solo con administradores del equipo",
+ "noTeams": "Aún no se han creado equipos",
+ "noTeamTags": "Aún no se han creado etiquetas de equipo"
+ },
"time": {
"dayAgo": "Hace 1 día",
"daysAgo": "Hace {{count}} días",
@@ -855,10 +1005,10 @@
"queued": "En cola",
"selectFiles": "Seleccionar Archivos",
"summarizing": "Resumiendo...",
- "supportedFormats": "Formatos compatibles",
+ "supportedFormats": "Soporta MP3, WAV, M4A, MP4, MOV, AVI, AMR, y más",
"title": "Subir Audio",
"transcribing": "Transcribiendo...",
- "untitled": "Untitled Recording",
+ "untitled": "Grabación Sin Título",
"uploadProgress": "Progreso de Carga",
"willAutoSummarize": "Se resumirá automáticamente después de la transcripción"
},
@@ -874,5 +1024,38 @@
"end": "Fin",
"location": "Ubicación",
"attendees": "Asistentes"
+ },
+ "tooltips": {
+ "copyTranscript": "Copiar transcripción",
+ "downloadTranscriptWithTemplate": "Descargar transcripción con plantilla",
+ "editTranscript": "Editar transcripción",
+ "doubleClickToEdit": "Doble clic para editar",
+ "editTitle": "Editar título",
+ "markAsRead": "Marcar como leído",
+ "moveToInbox": "Mover a la bandeja de entrada",
+ "removeHighlight": "Quitar resaltado",
+ "highlight": "Resaltar",
+ "reprocessWithAsr": "Reprocesar con ASR",
+ "reprocessTranscription": "Reprocesar transcripción",
+ "shareWithUsers": "Compartir con usuarios",
+ "removeFromQueue": "Eliminar de la cola",
+ "changeSpeaker": "Cambiar orador",
+ "editText": "Editar texto",
+ "clearChat": "Limpiar chat",
+ "restoreChat": "Restaurar chat",
+ "maximizeChat": "Maximizar chat",
+ "switchToLightMode": "Cambiar a Modo Claro",
+ "switchToDarkMode": "Cambiar a Modo Oscuro",
+ "revokePublicSharing": "Revocar permiso para compartir públicamente",
+ "grantPublicSharing": "Otorgar permiso para compartir públicamente",
+ "removeAdmin": "Remover Administrador",
+ "makeAdmin": "Hacer Administrador",
+ "manageMembers": "Administrar Miembros",
+ "manageTeamTags": "Administrar Etiquetas de Grupo",
+ "editTeam": "Editar Grupo",
+ "deleteTeam": "Eliminar Grupo",
+ "removeFromTeam": "Eliminar del equipo",
+ "followPlayerDisabled": "Activar desplazamiento automático - la transcripción sigue la reproducción de audio",
+ "followPlayerEnabled": "Desactivar desplazamiento automático - la transcripción permanece en su lugar"
}
}
\ No newline at end of file
diff --git a/static/locales/fr.json b/static/locales/fr.json
index 1e4acefa..af275828 100644
--- a/static/locales/fr.json
+++ b/static/locales/fr.json
@@ -114,7 +114,9 @@
"viewGuide": "Voir le Guide des Modèles",
"selectTemplate": "Sélectionner un Modèle",
"default": "Par Défaut",
- "downloadWithoutTemplate": "Télécharger sans modèle"
+ "downloadWithoutTemplate": "Télécharger sans modèle",
+ "downloadDefault": "Télécharger par défaut",
+ "chooseTemplate": "Choisir un modèle..."
},
"admin": {
"title": "Administration",
@@ -243,6 +245,7 @@
"yes": "Oui"
},
"buttons": {
+ "addSegment": "Ajouter un Segment",
"cancel": "Cancel",
"clearAllFilters": "Effacer tous les filtres",
"clearCompleted": "Effacer les téléchargements terminés",
@@ -268,10 +271,15 @@
"editTag": "Éditer l'étiquette",
"editTags": "Éditer les étiquettes",
"editTranscription": "Modifier la Transcription",
+ "editSpeakers": "Éditer les orateurs...",
"editUser": "Éditer l'utilisateur",
"help": "Aide",
"identifySpeakers": "Identifier les Orateurs",
+ "next": "Suivant",
+ "previous": "Précédent",
"refresh": "Refresh",
+ "addSpeaker": "Ajouter un orateur",
+ "saveNames": "Enregistrer les noms",
"reprocessSummary": "Retraiter le résumé",
"reprocessTranscription": "Retraiter la transcription",
"reprocessWithAsr": "Retraiter avec ASR",
@@ -309,13 +317,35 @@
},
"colorScheme": {
"chooseRecording": "Choisissez un enregistrement dans la barre latérale pour voir sa transcription et son résumé",
+ "darkThemes": "Thèmes Sombres",
+ "lightThemes": "Thèmes Clairs",
+ "resetToDefault": "Réinitialiser par Défaut",
"selectRecording": "Sélectionner un Enregistrement",
"subtitle": "Personnalisez votre interface avec de magnifiques thèmes de couleur",
- "title": "Schéma de Couleurs"
+ "title": "Choisir le Schéma de Couleurs",
+ "themes": {
+ "light": {
+ "blue": { "name": "Bleu Océan", "description": "Thème bleu classique avec attrait professionnel" },
+ "emerald": { "name": "Émeraude Forêt", "description": "Thème vert frais pour une sensation naturelle" },
+ "purple": { "name": "Violet Royal", "description": "Thème violet élégant avec sophistication" },
+ "rose": { "name": "Rose Coucher de Soleil", "description": "Thème rose chaud avec énergie douce" },
+ "amber": { "name": "Ambre Doré", "description": "Thème jaune chaud pour la luminosité" },
+ "teal": { "name": "Turquoise Océan", "description": "Thème turquoise frais pour la tranquillité" }
+ },
+ "dark": {
+ "blue": { "name": "Bleu Minuit", "description": "Thème bleu profond pour travail concentré" },
+ "emerald": { "name": "Forêt Sombre", "description": "Thème vert riche pour visualisation confortable" },
+ "purple": { "name": "Violet Profond", "description": "Thème violet mystérieux pour la créativité" },
+ "rose": { "name": "Rose Sombre", "description": "Thème rose atténué avec chaleur subtile" },
+ "amber": { "name": "Ambre Sombre", "description": "Thème marron chaud pour sessions confortables" },
+ "teal": { "name": "Turquoise Profond", "description": "Thème turquoise sombre pour concentration calme" }
+ }
+ }
},
"common": {
"back": "Retour",
"cancel": "Annuler",
+ "changesSaved": "Modifications enregistrées",
"close": "Fermer",
"confirm": "Confirmer",
"delete": "Supprimer",
@@ -477,6 +507,9 @@
"approachingLimit": "Approche de la limite de {{limit}}MB",
"askAboutTranscription": "Posez des questions sur cette transcription",
"audioPlayer": "Lecteur Audio",
+ "audioDeletedMessage": "Le fichier audio a été archivé et n'est plus disponible pour la lecture.",
+ "audioDeletedTitle": "Fichier audio supprimé",
+ "audioDeletedDescription": "Le fichier audio de cet enregistrement a été supprimé, mais la transcription reste disponible.",
"autoIdentify": "Identifier Automatiquement",
"bothAudioDesc": "Enregistre votre voix + les participants à la réunion (recommandé pour les réunions en ligne)",
"clearFilters": "effacer les filtres",
@@ -493,6 +526,8 @@
"entireScreen": "Écran Entier",
"estimatedSize": "Taille estimée",
"generatingSummary": "Génération du résumé...",
+ "groups": "groupes",
+ "identifying": "Identification...",
"howToRecordSystemAudio": "Comment Enregistrer l'Audio Système",
"importantNote": "Note importante",
"lines": "{{count}} lignes",
@@ -502,9 +537,14 @@
"microphoneDesc": "Enregistre uniquement votre voix",
"modelReasoning": "Raisonnement du Modèle",
"moreSpeakersThanColors": "Plus d'orateurs que de couleurs disponibles",
+ "navigate": "Naviguer",
"noDateSet": "Aucune date définie",
"noParticipants": "Aucun participant",
"noTagsCreated": "Aucune étiquette créée pour le moment.",
+ "of": "sur",
+ "playFromHere": "Lire à partir d'ici",
+ "addSegmentBelow": "Ajouter un segment en dessous",
+ "deleteSegment": "Supprimer le segment",
"processingTime": "Temps de traitement",
"processingTimeDescription": "Cela peut prendre quelques minutes. Vous pouvez continuer à utiliser l'application pendant le traitement.",
"processingTranscription": "Traitement de la transcription...",
@@ -533,7 +573,11 @@
"uploadRecordingNotes": "Télécharger l'Enregistrement et les Notes",
"whatWillHappen": "Que va-t-il se passer?",
"whyNotWorking": "Pourquoi ça ne marche pas?",
- "speakers": "Orateurs"
+ "youHaveXSpeakers": "Vous avez {{count}} locuteurs, mais seulement 8 couleurs uniques sont disponibles. Les couleurs se répéteront après le 8ème locuteur.",
+ "speakers": "Orateurs",
+ "publicLinkDesc": "Toute personne disposant de ce lien peut accéder à l'enregistrement",
+ "internalSharingDesc": "Partager avec des utilisateurs spécifiques de votre organisation",
+ "enterSpeakerName": "Entrez le nom du locuteur..."
},
"inquire": {
"title": "Enquêter",
@@ -576,6 +620,43 @@
"ru": "Russe",
"zh": "Chinois"
},
+ "speakersManagement": {
+ "description": "Gérez vos locuteurs enregistrés. Ceux-ci sont automatiquement sauvegardés lorsque vous utilisez des noms de locuteurs dans vos enregistrements.",
+ "loadingSpeakers": "Chargement des locuteurs...",
+ "failedToLoad": "Échec du chargement des locuteurs",
+ "noSpeakersYet": "Aucun locuteur enregistré pour le moment",
+ "speakersWillAppear": "Les locuteurs apparaîtront ici lorsque vous utilisez des noms de locuteurs dans vos enregistrements",
+ "totalSpeakers": "locuteurs enregistrés",
+ "usedTimes": "Utilisé",
+ "lastUsed": "Dernière utilisation",
+ "created": "Créé",
+ "used": "Utilisé",
+ "time": "fois",
+ "times": "fois",
+ "last": "Dernier",
+ "added": "Ajouté",
+ "voiceProfile": "Profil Vocal",
+ "voiceMatchSuggestions": "Suggestions de Correspondance Vocale",
+ "match": "correspondance",
+ "confidence": "Confiance",
+ "confidenceHigh": "élevée",
+ "confidenceMedium": "moyenne",
+ "confidenceLow": "faible",
+ "samples": "échantillons",
+ "sample": "échantillon",
+ "viewSnippets": "Voir les Extraits",
+ "noSnippetsAvailable": "Aucun extrait disponible",
+ "failedToLoadSnippets": "Échec du chargement des extraits",
+ "mergeSpeakers": "Fusionner les Locuteurs",
+ "selectToMerge": "Sélectionnez 2+ pour Fusionner",
+ "mergeNSpeakers": "Fusionner {{count}} Locuteurs",
+ "speakersToMerge": "Locuteurs à fusionner :",
+ "keepThisSpeaker": "Conserver ce locuteur (les autres seront fusionnés avec lui) :",
+ "mergeDescription": "Combinez plusieurs profils de locuteurs en un seul. Toutes les incorporations, extraits et données d'utilisation seront fusionnés.",
+ "targetWillReceive": "Le locuteur sélectionné recevra toutes les données vocales et extraits des autres.",
+ "mergeSuccess": "Locuteurs fusionnés avec succès",
+ "mergeFailed": "Échec de la fusion des locuteurs"
+ },
"manageSpeakersModal": {
"created": "Créé",
"description": "Gérez vos intervenants sauvegardés. Ils sont automatiquement sauvegardés lorsque vous utilisez des noms d'intervenants dans vos enregistrements.",
@@ -620,10 +701,13 @@
"wordCount": "Nombre de Mots"
},
"modal": {
+ "addSpeaker": "Ajouter un Nouveau Locuteur",
"colorScheme": "Schéma de Couleurs",
"deleteRecording": "Supprimer l'Enregistrement",
"editAsrTranscription": "Modifier la Transcription ASR",
"editRecording": "Modifier l'Enregistrement",
+ "editSpeakers": "Modifier les Locuteurs",
+ "editParticipants": "Modifier les Participants",
"editTags": "Modifier les Étiquettes d'Enregistrement",
"editTranscription": "Modifier la Transcription",
"identifySpeakers": "Identifier les Orateurs",
@@ -648,6 +732,12 @@
"recording": "Enregistrement",
"settings": "Paramètres",
"signOut": "Déconnexion",
+ "teamManagement": "Gestion de Groupe",
+ "groupManagement": "Gestion de Groupe",
+ "groupManagement": "Gestion de Groupe",
+ "groupManagement": "Gestion de Groupe",
+ "groupManagement": "Gestion de Groupe",
+ "groupManagement": "Gestion de Groupe",
"upload": "Télécharger",
"userProfile": "Profil Utilisateur"
},
@@ -724,8 +814,28 @@
"sharedTranscriptsPage": {
"noSharedTranscripts": "Vous n'avez pas encore partagé de transcriptions."
},
+ "sharing": {
+ "publicLink": "Lien Public",
+ "publicLinks": "lien(s) public(s)",
+ "publicLinksGenerated": "lien(s) public(s) généré(s)",
+ "internalSharing": "Partage Interne",
+ "searchUsers": "Rechercher des utilisateurs...",
+ "canEdit": "Peut modifier",
+ "canReshare": "Peut repartager",
+ "notSharedYet": "Pas encore partagé",
+ "sharedBy": "Partagé par",
+ "sharedWith": "Partagé avec",
+ "sharedBadge": "Partagé",
+ "publicBadge": "Public",
+ "teamBadge": "Équipe",
+ "teamRecording": "Enregistrement d'équipe",
+ "users": "utilisateur(s)",
+ "unknown": "Inconnu"
+ },
"sidebar": {
"advancedSearch": "Recherche Avancée",
+ "archived": "Archivé",
+ "archivedRecordings": "Enregistrements Archivés",
"dateRange": "Plage de Dates",
"filters": "Filtres",
"highlighted": "Mis en Évidence",
@@ -733,12 +843,13 @@
"lastMonth": "Mois Dernier",
"lastWeek": "Semaine Dernière",
"loadMore": "Charger Plus",
- "markAsRead": "Mark as read",
- "moveToInbox": "Move to Inbox",
+ "markAsRead": "Marquer comme lu",
+ "moveToInbox": "Déplacer vers la boîte de réception",
"noRecordings": "Aucun enregistrement trouvé",
"older": "Plus Ancien",
- "removeFromHighlighted": "Remove from starred",
+ "removeFromHighlighted": "Retirer des favoris",
"searchRecordings": "Rechercher des enregistrements...",
+ "sharedWithMe": "Partagé avec Moi",
"sortBy": "Trier Par",
"sortByDate": "Date de Création",
"sortByMeetingDate": "Date de Réunion",
@@ -788,8 +899,10 @@
"addTag": "Ajouter une Étiquette",
"clearTagFilter": "Effacer le filtre",
"createTag": "Créer une Étiquette",
+ "currentTags": "Étiquettes Actuelles",
"filterByTag": "Filtrer par étiquette",
"manageAllTags": "Gérer Toutes les Étiquettes",
+ "noAvailableTags": "Aucune étiquette disponible",
"noTags": "Aucune étiquette",
"removeTag": "Supprimer l'Étiquette",
"tagColor": "Couleur de l'Étiquette",
@@ -803,6 +916,43 @@
"noTagsAssigned": "Aucune étiquette assignée à cet enregistrement",
"searchTags": "Rechercher des étiquettes..."
},
+ "groups": {
+ "title": "Gestion de Groupe",
+ "createTeam": "Créer une Équipe",
+ "editTeam": "Modifier l'Équipe",
+ "deleteTeam": "Supprimer l'Équipe",
+ "updateTeam": "Mettre à jour l'Équipe",
+ "teamName": "Nom de l'Équipe",
+ "teamNamePlaceholder": "Entrez le nom de l'équipe",
+ "teamLead": "Chef d'Équipe",
+ "selectTeamLead": "Sélectionner le chef d'équipe...",
+ "members": "Membres",
+ "noMembers": "Aucun membre dans cette équipe",
+ "addMembers": "Ajouter des membres...",
+ "searchUsers": "Rechercher des utilisateurs...",
+ "syncTeamShares": "Synchroniser les Partages d'Équipe",
+ "syncTeamSharesDescription": "Cela partagera rétroactivement tous les enregistrements avec des étiquettes d'équipe avec les membres appropriés selon les paramètres de partage de l'étiquette.",
+ "syncComplete": "Partages d'équipe synchronisés avec succès",
+ "confirmDelete": "Êtes-vous sûr de vouloir supprimer cette équipe ? Cette action ne peut pas être annulée.",
+ "teamTags": "Étiquettes d'Équipe",
+ "createTeamTag": "Créer une Nouvelle Étiquette d'Équipe",
+ "editTeamTag": "Modifier l'Étiquette d'Équipe",
+ "retentionPeriod": "Période de Rétention (jours)",
+ "retentionPlaceholder": "Laisser vide pour utiliser la rétention globale",
+ "retentionHelp": "Les enregistrements avec cette étiquette seront supprimés après ce nombre de jours. Laisser vide pour utiliser la rétention globale ({{days}} jours).",
+ "dayRetention": "jours de rétention",
+ "globalRetention": "Rétention globale",
+ "autoShare": "Partage automatique",
+ "autoShareTeam": "Partager automatiquement les enregistrements avec tous les membres de l'équipe lorsque cette étiquette est appliquée",
+ "shareWithAdmins": "Partager les enregistrements avec les administrateurs de l'équipe lorsque cette étiquette est appliquée",
+ "autoShareNote": "Note : Si les deux sont activés, tous les membres de l'équipe auront accès. Si seulement \"administrateurs de l'équipe\" est activé, seuls les chefs d'équipe auront accès.",
+ "deletionExempt": "Exempté de suppression",
+ "deletionExemptHelp": "Les enregistrements avec cette étiquette seront exemptés de suppression automatique, même s'ils dépassent la période de rétention.",
+ "autoSharesWithTeam": "Partage automatiquement avec tous les membres de l'équipe",
+ "sharesWithAdminsOnly": "Partage uniquement avec les administrateurs de l'équipe",
+ "noTeams": "Aucune équipe créée",
+ "noTeamTags": "Aucune étiquette d'équipe créée"
+ },
"time": {
"dayAgo": "Il y a 1 jour",
"daysAgo": "Il y a {{count}} jours",
@@ -849,10 +999,10 @@
"queued": "En file d'attente",
"selectFiles": "Sélectionner des Fichiers",
"summarizing": "Résumé...",
- "supportedFormats": "Formats pris en charge",
+ "supportedFormats": "Supports MP3, WAV, M4A, MP4, MOV, AVI, AMR, et plus",
"title": "Télécharger Audio",
"transcribing": "Transcription...",
- "untitled": "Untitled Recording",
+ "untitled": "Enregistrement Sans Titre",
"uploadProgress": "Progression du Téléchargement",
"willAutoSummarize": "Résumé automatique après la transcription"
},
@@ -874,5 +1024,38 @@
"end": "Fin",
"location": "Lieu",
"attendees": "Participants"
+ },
+ "tooltips": {
+ "copyTranscript": "Copier la transcription",
+ "downloadTranscriptWithTemplate": "Télécharger la transcription avec modèle",
+ "editTranscript": "Modifier la transcription",
+ "doubleClickToEdit": "Double-cliquez pour modifier",
+ "editTitle": "Modifier le titre",
+ "markAsRead": "Marquer comme lu",
+ "moveToInbox": "Déplacer vers la boîte de réception",
+ "removeHighlight": "Retirer le surlignage",
+ "highlight": "Surligner",
+ "reprocessWithAsr": "Retraiter avec ASR",
+ "reprocessTranscription": "Retraiter la transcription",
+ "shareWithUsers": "Partager avec des utilisateurs",
+ "removeFromQueue": "Retirer de la file d'attente",
+ "changeSpeaker": "Changer le locuteur",
+ "editText": "Modifier le texte",
+ "clearChat": "Effacer le chat",
+ "restoreChat": "Restaurer le chat",
+ "maximizeChat": "Maximiser le chat",
+ "switchToLightMode": "Passer en Mode Clair",
+ "switchToDarkMode": "Passer en Mode Sombre",
+ "revokePublicSharing": "Révoquer la permission de partage public",
+ "grantPublicSharing": "Accorder la permission de partage public",
+ "removeAdmin": "Retirer l'Administrateur",
+ "makeAdmin": "Nommer Administrateur",
+ "manageMembers": "Gérer les Membres",
+ "manageTeamTags": "Gérer les Étiquettes de Groupe",
+ "editTeam": "Modifier le Groupe",
+ "deleteTeam": "Supprimer le Groupe",
+ "removeFromTeam": "Retirer de l'équipe",
+ "followPlayerDisabled": "Activer le défilement automatique - la transcription suit la lecture audio",
+ "followPlayerEnabled": "Désactiver le défilement automatique - la transcription reste en place"
}
}
\ No newline at end of file
diff --git a/static/locales/zh.json b/static/locales/zh.json
index d4e9f264..fc043d85 100644
--- a/static/locales/zh.json
+++ b/static/locales/zh.json
@@ -132,7 +132,9 @@
"viewGuide": "查看模板指南",
"selectTemplate": "选择模板",
"default": "默认",
- "downloadWithoutTemplate": "不使用模板下载"
+ "downloadWithoutTemplate": "不使用模板下载",
+ "downloadDefault": "下载默认",
+ "chooseTemplate": "选择模板..."
},
"admin": {
"title": "管理员",
@@ -321,6 +323,7 @@
"vectorStoreStatus": "向量存储状态"
},
"buttons": {
+ "addSegment": "添加片段",
"cancel": "取消",
"clearAllFilters": "清除所有筛选",
"clearCompleted": "清除已完成的上传",
@@ -346,10 +349,15 @@
"editTag": "编辑标签",
"editTags": "编辑标签",
"editTranscription": "编辑转录",
+ "editSpeakers": "编辑发言人...",
"editUser": "编辑用户",
"help": "帮助",
"identifySpeakers": "识别发言人",
+ "next": "下一个",
+ "previous": "上一个",
"refresh": "刷新",
+ "addSpeaker": "添加发言人",
+ "saveNames": "保存名称",
"reprocessSummary": "重新处理摘要",
"reprocessTranscription": "重新处理转录",
"reprocessWithAsr": "使用ASR重新处理",
@@ -387,13 +395,35 @@
},
"colorScheme": {
"chooseRecording": "从侧边栏选择一个录音以查看其转录和摘要",
+ "darkThemes": "深色主题",
+ "lightThemes": "浅色主题",
+ "resetToDefault": "重置为默认",
"selectRecording": "选择录音",
"subtitle": "使用美观的颜色主题自定义您的界面",
- "title": "配色方案"
+ "title": "选择配色方案",
+ "themes": {
+ "light": {
+ "blue": { "name": "海洋蓝", "description": "专业风格的经典蓝色主题" },
+ "emerald": { "name": "森林翠绿", "description": "清新自然的绿色主题" },
+ "purple": { "name": "皇家紫", "description": "优雅精致的紫色主题" },
+ "rose": { "name": "日落玫瑰", "description": "温暖柔和的粉色主题" },
+ "amber": { "name": "金色琥珀", "description": "明亮温暖的黄色主题" },
+ "teal": { "name": "海洋青", "description": "清凉宁静的青色主题" }
+ },
+ "dark": {
+ "blue": { "name": "午夜蓝", "description": "专注工作的深蓝主题" },
+ "emerald": { "name": "暗夜森林", "description": "舒适观看的浓绿主题" },
+ "purple": { "name": "深紫", "description": "激发创意的神秘紫色主题" },
+ "rose": { "name": "暗玫瑰", "description": "微妙温暖的柔粉主题" },
+ "amber": { "name": "暗琥珀", "description": "舒适温馨的棕色主题" },
+ "teal": { "name": "深青", "description": "平静专注的深青主题" }
+ }
+ }
},
"common": {
"back": "返回",
"cancel": "取消",
+ "changesSaved": "更改已保存",
"close": "关闭",
"confirm": "确认",
"delete": "删除",
@@ -555,6 +585,9 @@
"approachingLimit": "接近 {{limit}}MB 限制",
"askAboutTranscription": "询问有关此转录的问题",
"audioPlayer": "音频播放器",
+ "audioDeletedMessage": "音频文件已归档,无法播放。",
+ "audioDeletedTitle": "音频文件已删除",
+ "audioDeletedDescription": "此录音的音频文件已被删除,但转录内容仍然可用。",
"autoIdentify": "自动识别",
"bothAudioDesc": "录制您的声音 + 会议参与者(推荐用于在线会议)",
"clearFilters": "清除筛选",
@@ -571,6 +604,8 @@
"entireScreen": "整个屏幕",
"estimatedSize": "预计大小",
"generatingSummary": "生成摘要中...",
+ "groups": "组",
+ "identifying": "识别中...",
"howToRecordSystemAudio": "如何录制系统音频",
"importantNote": "重要提示",
"lines": "{{count}} 行",
@@ -580,9 +615,14 @@
"microphoneDesc": "仅录制您的声音",
"modelReasoning": "模型推理",
"moreSpeakersThanColors": "发言人数超过可用颜色数",
+ "navigate": "导航",
"noDateSet": "未设置日期",
"noParticipants": "无参与者",
"noTagsCreated": "尚未创建标签。",
+ "of": "/",
+ "playFromHere": "从此处播放",
+ "addSegmentBelow": "在下方添加片段",
+ "deleteSegment": "删除片段",
"processingTime": "处理时间",
"processingTimeDescription": "这可能需要几分钟完成。处理期间您可以继续使用应用。",
"processingTranscription": "处理转录中...",
@@ -660,7 +700,11 @@
"uploadFiles": "上传文件",
"uploading": "上传中",
"viewDetails": "查看详情",
- "waitingToUpload": "等待上传"
+ "waitingToUpload": "等待上传",
+ "youHaveXSpeakers": "您有 {{count}} 位发言人,但只有8种独特的颜色可用。颜色将在第8位发言人之后重复。",
+ "publicLinkDesc": "任何拥有此链接的人都可以访问录音",
+ "internalSharingDesc": "与您组织中的特定用户分享",
+ "enterSpeakerName": "输入发言人姓名..."
},
"inquire": {
"title": "查询",
@@ -747,10 +791,13 @@
"wordCount": "字数"
},
"modal": {
+ "addSpeaker": "添加新发言人",
"colorScheme": "配色方案",
"deleteRecording": "删除录音",
"editAsrTranscription": "编辑 ASR 转录",
"editRecording": "编辑录音",
+ "editSpeakers": "编辑发言人",
+ "editParticipants": "编辑参与者",
"editTags": "编辑录音标签",
"editTranscription": "编辑转录",
"identifySpeakers": "识别发言人",
@@ -775,6 +822,12 @@
"recording": "录音",
"settings": "设置",
"signOut": "退出登录",
+ "teamManagement": "群组管理",
+ "groupManagement": "群组管理",
+ "groupManagement": "群组管理",
+ "groupManagement": "群组管理",
+ "groupManagement": "群组管理",
+ "groupManagement": "群组管理",
"upload": "上传",
"userProfile": "用户资料"
},
@@ -849,7 +902,28 @@
"time": "次",
"times": "次",
"last": "上次",
- "added": "添加时间"
+ "added": "添加时间",
+ "voiceProfile": "声音档案",
+ "voiceMatchSuggestions": "声音匹配建议",
+ "match": "匹配",
+ "confidence": "置信度",
+ "confidenceHigh": "高",
+ "confidenceMedium": "中",
+ "confidenceLow": "低",
+ "samples": "个样本",
+ "sample": "个样本",
+ "viewSnippets": "查看片段",
+ "noSnippetsAvailable": "无可用片段",
+ "failedToLoadSnippets": "加载片段失败",
+ "mergeSpeakers": "合并发言人",
+ "selectToMerge": "选择2个以上进行合并",
+ "mergeNSpeakers": "合并 {{count}} 个发言人",
+ "speakersToMerge": "要合并的发言人:",
+ "keepThisSpeaker": "保留此发言人(其他将合并到其中):",
+ "mergeDescription": "将多个发言人档案合并为一个。所有嵌入、片段和使用数据将被合并。",
+ "targetWillReceive": "选定的发言人将接收所有其他人的声音数据和片段。",
+ "mergeSuccess": "发言人合并成功",
+ "mergeFailed": "合并发言人失败"
},
"sharedTranscripts": {
"noSharedTranscripts": "您尚未分享任何转录。",
@@ -860,8 +934,28 @@
"sharedTranscriptsPage": {
"noSharedTranscripts": "您尚未分享任何转录。"
},
+ "sharing": {
+ "publicLink": "公开链接",
+ "publicLinks": "个公开链接",
+ "publicLinksGenerated": "个公开链接已生成",
+ "internalSharing": "内部分享",
+ "searchUsers": "搜索用户...",
+ "canEdit": "可以编辑",
+ "canReshare": "可以转发",
+ "notSharedYet": "尚未分享",
+ "sharedBy": "分享者",
+ "sharedWith": "分享给",
+ "sharedBadge": "已分享",
+ "publicBadge": "公开",
+ "teamBadge": "团队",
+ "teamRecording": "团队录音",
+ "users": "位用户",
+ "unknown": "未知"
+ },
"sidebar": {
"advancedSearch": "高级搜索",
+ "archived": "已归档",
+ "archivedRecordings": "已归档录音",
"dateRange": "日期范围",
"filters": "筛选器",
"highlighted": "已标记",
@@ -875,6 +969,7 @@
"older": "更早",
"removeFromHighlighted": "取消标记",
"searchRecordings": "搜索录音",
+ "sharedWithMe": "分享给我",
"sortBy": "排序方式",
"sortByDate": "按日期排序",
"sortByMeetingDate": "会议日期",
@@ -935,8 +1030,10 @@
"addTag": "添加标签",
"clearTagFilter": "清除筛选",
"createTag": "创建标签",
+ "currentTags": "当前标签",
"filterByTag": "按标签筛选",
"manageAllTags": "管理所有标签",
+ "noAvailableTags": "没有可用标签",
"noTags": "无标签",
"removeTag": "删除标签",
"tagColor": "标签颜色",
@@ -950,6 +1047,43 @@
"noTagsAssigned": "此录音未分配标签",
"searchTags": "搜索标签..."
},
+ "groups": {
+ "title": "群组管理",
+ "createTeam": "创建团队",
+ "editTeam": "编辑团队",
+ "deleteTeam": "删除团队",
+ "updateTeam": "更新团队",
+ "teamName": "团队名称",
+ "teamNamePlaceholder": "输入团队名称",
+ "teamLead": "团队负责人",
+ "selectTeamLead": "选择团队负责人...",
+ "members": "成员",
+ "noMembers": "此团队暂无成员",
+ "addMembers": "添加成员...",
+ "searchUsers": "搜索用户...",
+ "syncTeamShares": "同步团队分享",
+ "syncTeamSharesDescription": "这将根据标签的分享设置,追溯性地将所有带有团队标签的录音分享给相应的团队成员。",
+ "syncComplete": "团队分享同步成功",
+ "confirmDelete": "确定要删除此团队吗?此操作无法撤销。",
+ "teamTags": "团队标签",
+ "createTeamTag": "创建新团队标签",
+ "editTeamTag": "编辑团队标签",
+ "retentionPeriod": "保留期限(天)",
+ "retentionPlaceholder": "留空则使用全局保留期限",
+ "retentionHelp": "带有此标签的录音将在此天数后删除。留空则使用全局保留期限({{days}}天)。",
+ "dayRetention": "天保留期限",
+ "globalRetention": "全局保留期限",
+ "autoShare": "自动分享",
+ "autoShareTeam": "应用此标签时自动与所有团队成员分享录音",
+ "shareWithAdmins": "应用此标签时与团队管理员分享录音",
+ "autoShareNote": "注意:如果两者都启用,所有团队成员都将有访问权限。如果只启用\"团队管理员\",则只有团队负责人有访问权限。",
+ "deletionExempt": "免于删除",
+ "deletionExemptHelp": "带有此标签的录音将免于自动删除,即使超过保留期限。",
+ "autoSharesWithTeam": "自动与所有团队成员分享",
+ "sharesWithAdminsOnly": "仅与团队管理员分享",
+ "noTeams": "尚未创建团队",
+ "noTeamTags": "尚未创建团队标签"
+ },
"time": {
"dayAgo": "1 天前",
"daysAgo": "{{count}} 天前",
@@ -996,7 +1130,7 @@
"queued": "排队中",
"selectFiles": "选择文件",
"summarizing": "生成摘要中...",
- "supportedFormats": "支持的格式",
+ "supportedFormats": "支持 MP3, WAV, M4A, MP4, MOV, AVI, AMR 等格式",
"title": "上传音频",
"transcribing": "转录中...",
"untitled": "无标题录音",
@@ -1038,5 +1172,38 @@
"end": "结束",
"location": "地点",
"attendees": "参与者"
+ },
+ "tooltips": {
+ "copyTranscript": "复制转录",
+ "downloadTranscriptWithTemplate": "使用模板下载转录",
+ "editTranscript": "编辑转录",
+ "doubleClickToEdit": "双击编辑",
+ "editTitle": "编辑标题",
+ "markAsRead": "标记为已读",
+ "moveToInbox": "移至收件箱",
+ "removeHighlight": "移除高亮",
+ "highlight": "高亮",
+ "reprocessWithAsr": "使用ASR重新处理",
+ "reprocessTranscription": "重新处理转录",
+ "shareWithUsers": "与用户分享",
+ "removeFromQueue": "从队列中移除",
+ "changeSpeaker": "更改发言人",
+ "editText": "编辑文本",
+ "clearChat": "清空聊天",
+ "restoreChat": "恢复聊天",
+ "maximizeChat": "最大化聊天",
+ "switchToLightMode": "切换到浅色模式",
+ "switchToDarkMode": "切换到深色模式",
+ "revokePublicSharing": "撤销公开分享权限",
+ "grantPublicSharing": "授予公开分享权限",
+ "removeAdmin": "移除管理员",
+ "makeAdmin": "设为管理员",
+ "manageMembers": "管理成员",
+ "manageTeamTags": "管理群组标签",
+ "editTeam": "编辑群组",
+ "deleteTeam": "删除群组",
+ "removeFromTeam": "从团队中移除",
+ "followPlayerDisabled": "启用自动滚动 - 文字记录跟随音频播放",
+ "followPlayerEnabled": "禁用自动滚动 - 文字记录保持位置"
}
}
\ No newline at end of file
diff --git a/static/robots.txt b/static/robots.txt
new file mode 100644
index 00000000..7275cbad
--- /dev/null
+++ b/static/robots.txt
@@ -0,0 +1,65 @@
+# Speakr - Block all web crawlers and search engines
+# This application contains private user data and should not be indexed
+
+User-agent: *
+Disallow: /
+
+# Specific directives for major search engines
+User-agent: Googlebot
+Disallow: /
+
+User-agent: Googlebot-Image
+Disallow: /
+
+User-agent: Bingbot
+Disallow: /
+
+User-agent: Slurp
+Disallow: /
+
+User-agent: DuckDuckBot
+Disallow: /
+
+User-agent: Baiduspider
+Disallow: /
+
+User-agent: YandexBot
+Disallow: /
+
+User-agent: ia_archiver
+Disallow: /
+
+# AI Crawlers
+User-agent: GPTBot
+Disallow: /
+
+User-agent: ChatGPT-User
+Disallow: /
+
+User-agent: CCBot
+Disallow: /
+
+User-agent: anthropic-ai
+Disallow: /
+
+User-agent: Claude-Web
+Disallow: /
+
+User-agent: cohere-ai
+Disallow: /
+
+# Social Media Crawlers
+User-agent: facebookexternalhit
+Disallow: /
+
+User-agent: Twitterbot
+Disallow: /
+
+User-agent: LinkedInBot
+Disallow: /
+
+User-agent: Slackbot
+Disallow: /
+
+User-agent: Discordbot
+Disallow: /
diff --git a/static/service-worker.js b/static/service-worker.js
index 798a6211..3a5845d0 100644
--- a/static/service-worker.js
+++ b/static/service-worker.js
@@ -1,15 +1,15 @@
// Speakr Service Worker
// Provides offline support and background capabilities for recording
-const CACHE_VERSION = 'speakr-v1';
+const CACHE_VERSION = 'speakr-v2';
const CACHE_STATIC = `${CACHE_VERSION}-static`;
const CACHE_DYNAMIC = `${CACHE_VERSION}-dynamic`;
// Files to cache for offline functionality
const STATIC_ASSETS = [
'/',
- '/static/css/style.css',
- '/static/js/app.js',
+ '/static/css/styles.css',
+ '/static/js/app.modular.js',
'/static/manifest.json',
'/static/offline.html',
'/static/img/icon-192x192.png',
diff --git a/static/sw.js b/static/sw.js
index c2170441..7a6e5b7f 100644
--- a/static/sw.js
+++ b/static/sw.js
@@ -1,20 +1,22 @@
-const CACHE_NAME = 'Speakr-cache-v3';
+const CACHE_NAME = 'Speakr-cache-v4';
const ASSETS_TO_CACHE = [
'/',
'/static/offline.html',
'/static/manifest.json',
'/static/css/styles.css',
- '/static/js/app.js',
- '/static/img/icon-192x192.png', // Assuming you will add this
- '/static/img/icon-512x512.png', // Assuming you will add this
- '/static/img/favicon.ico', // Keep existing SVG as a fallback or for other uses
- // HTML templates (these are typically served via routes, but caching the routes themselves is handled by fetch strategies)
- // We cache '/' which should serve the main page.
- // Other specific page routes like /login, /register, /account will be handled by networkFirst.
- // CDN assets - caching these can be beneficial but also complex if they change often.
- 'https://cdn.tailwindcss.com',
- 'https://unpkg.com/vue@3/dist/vue.global.js',
- 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css'
+ '/static/js/app.modular.js',
+ '/static/js/i18n.js',
+ '/static/js/csrf-refresh.js',
+ '/static/img/icon-192x192.png',
+ '/static/img/icon-512x512.png',
+ '/static/img/favicon.ico',
+ // Local vendor assets (no external CDN dependencies)
+ '/static/vendor/js/tailwind.min.js',
+ '/static/vendor/js/vue.global.js',
+ '/static/vendor/js/marked.min.js',
+ '/static/vendor/js/easymde.min.js',
+ '/static/vendor/css/fontawesome.min.css',
+ '/static/vendor/css/easymde.min.css'
];
// Function to update shortcuts (structure from your example)
diff --git a/templates/account.html b/templates/account.html
index 1d4c90ac..3d0a5584 100644
--- a/templates/account.html
+++ b/templates/account.html
@@ -4,6 +4,7 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="csrf-token" content="{{ csrf_token() }}">
+ <meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
<title>{{ title }} - Speakr</title>
<link rel="icon" href="{{ url_for('static', filename='img/favicon.ico') }}" type="image/svg+xml">
<!-- All dependencies bundled locally for offline support -->
@@ -15,7 +16,6 @@
<!-- Loading overlay to prevent FOUC -->
{% include 'includes/loading_overlay.html' %}
- <script src="{{ url_for('static', filename='js/loading.js') }}"></script>
<script>
// Initialize i18n
@@ -23,20 +23,20 @@
async function initializeI18n(language) {
const userLanguage = language || "{{ user_language }}";
-
+
// Initialize the global i18n instance
if (window.i18n) {
await window.i18n.init(userLanguage);
-
+
// Create a shorthand translation function
t = (key, params) => window.i18n.t(key, params);
-
+
// Update all elements with data-i18n attribute
document.querySelectorAll('[data-i18n]').forEach(el => {
const key = el.getAttribute('data-i18n');
el.textContent = t(key);
});
-
+
// Update all elements with data-i18n-placeholder attribute
document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
const key = el.getAttribute('data-i18n-placeholder');
@@ -52,7 +52,7 @@
const key = el.getAttribute('data-i18n');
el.textContent = t(key);
});
-
+
// Update all elements with data-i18n-placeholder attribute
document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
const key = el.getAttribute('data-i18n-placeholder');
@@ -109,7 +109,7 @@
formData.append('output_language', document.getElementById('output_language').value || '');
// Send AJAX request to update language preference
- const response = await fetch('{{ url_for("account") }}', {
+ const response = await fetch('{{ url_for("auth.account") }}', {
method: 'POST',
headers: {
'X-Requested-With': 'XMLHttpRequest',
@@ -322,13 +322,77 @@
.scrollbar-hide::-webkit-scrollbar {
display: none;
}
+
+ /* Custom themed audio player for speaker snippets */
+ .snippet-audio-container {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 6px 8px;
+ background: var(--bg-tertiary);
+ border: 1px solid var(--border-secondary);
+ border-radius: 6px;
+ width: 100%;
+ }
+
+ .snippet-audio-btn {
+ width: 24px;
+ height: 24px;
+ border-radius: 50%;
+ background: var(--bg-accent);
+ color: var(--text-accent);
+ border: none;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ cursor: pointer;
+ flex-shrink: 0;
+ font-size: 10px;
+ transition: opacity 0.2s;
+ }
+
+ .snippet-audio-btn:hover {
+ opacity: 0.8;
+ }
+
+ .snippet-audio-progress {
+ flex: 1;
+ height: 4px;
+ background: var(--bg-secondary);
+ border-radius: 2px;
+ position: relative;
+ cursor: pointer;
+ overflow: hidden;
+ }
+
+ .snippet-audio-progress-bar {
+ position: absolute;
+ left: 0;
+ top: 0;
+ height: 100%;
+ background: var(--bg-accent);
+ border-radius: 2px;
+ transition: width 0.1s linear;
+ }
+
+ .snippet-audio-time {
+ font-size: 10px;
+ color: var(--text-muted);
+ font-variant-numeric: tabular-nums;
+ flex-shrink: 0;
+ }
+
+ /* Hide the native audio element */
+ .snippet-audio {
+ display: none;
+ }
</style>
</head>
<body class="bg-[var(--bg-primary)] text-[var(--text-primary)]">
<div class="main-container container mx-auto px-4 sm:px-6 lg:px-8 py-6">
<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">
+ <a href="{{ url_for('recordings.index') }}" class="flex items-center">
<img src="{{ url_for('static', filename='img/icon-192x192.png') }}" alt="Speakr Logo" class="h-9 w-9 mr-2">
Speakr
</a>
@@ -344,18 +408,19 @@
<i class="fas fa-chevron-down ml-2"></i>
</button>
<div id="userDropdownMenu" class="hidden absolute right-0 mt-2 w-48 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg shadow-lg z-10">
- <a href="{{ url_for('index') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)]">
+ <a href="{{ url_for('recordings.index') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)]">
<i class="fas fa-home mr-2"></i> <span data-i18n="nav.home">Home</span>
</a>
- <a href="{{ url_for('account') }}" class="block px-4 py-2 text-[var(--text-accent)] bg-[var(--bg-accent)]">
+ <a href="{{ url_for('auth.account') }}" class="block px-4 py-2 text-[var(--text-accent)] bg-[var(--bg-accent)]">
<i class="fas fa-user-circle mr-2"></i> <span data-i18n="nav.account">Account</span>
</a>
- {% if current_user.is_admin %}
- <a href="{{ url_for('admin') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)]">
- <i class="fas fa-user-shield mr-2"></i> <span data-i18n="nav.admin">Admin</span>
+ {% if current_user.is_admin or is_team_admin %}
+ <a href="{{ url_for('admin.admin') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)]">
+ <i class="fas {% if current_user.is_admin %}fa-user-shield{% else %}fa-users-cog{% endif %} mr-2"></i>
+ <span data-i18n="{% if current_user.is_admin %}nav.admin{% else %}nav.groupManagement{% endif %}">{% if current_user.is_admin %}Admin{% else %}Team Management{% endif %}</span>
</a>
{% endif %}
- <a href="{{ url_for('logout') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-danger)]">
+ <a href="{{ url_for('auth.logout') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-danger)]">
<i class="fas fa-sign-out-alt mr-2"></i> <span data-i18n="nav.signOut">Logout</span>
</a>
</div>
@@ -419,7 +484,7 @@
<div class="grid grid-cols-1 md:grid-cols-2 gap-8">
<!-- Left Column: Form -->
<div>
- <form id="accountInfoForm" method="POST" action="{{ url_for('account') }}" class="space-y-6">
+ <form id="accountInfoForm" method="POST" action="{{ url_for('auth.account') }}" class="space-y-6">
<div class="mb-6">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<h3 class="text-lg font-medium text-[var(--text-secondary)] mb-2" data-i18n="account.personalInfo">Personal Information</h3>
@@ -527,7 +592,7 @@
<div class="mt-6"> <!-- Added mt-6 for spacing, was mt-8 on Account Actions -->
<h3 class="text-lg font-medium text-[var(--text-secondary)] mb-2" data-i18n="account.accountActions">Account Actions</h3>
<div class="flex flex-col space-y-3">
- <a href="{{ url_for('index') }}" class="inline-flex items-center px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--border-focus)] transition-colors duration-200">
+ <a href="{{ url_for('recordings.index') }}" class="inline-flex items-center px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--border-focus)] transition-colors duration-200">
<i class="fas fa-microphone mr-2"></i> <span data-i18n="account.goToRecordings">Go to Recordings</span>
</a>
<button id="changePasswordBtn" class="inline-flex items-center px-4 py-2 border border-[var(--border-secondary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--border-focus)] transition-colors duration-200">
@@ -542,7 +607,7 @@
<div id="content-prompts" class="hidden tab-content pt-6">
<h2 class="text-2xl font-semibold text-[var(--text-primary)] mb-6" data-i18n="accountTabs.promptOptions">Prompt Options</h2>
- <form id="customPromptsForm" method="POST" action="{{ url_for('account') }}" class="space-y-6">
+ <form id="customPromptsForm" method="POST" action="{{ url_for('auth.account') }}" class="space-y-6">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<!-- Event Extraction Settings -->
@@ -631,52 +696,96 @@
</div>
<div id="content-shares" class="hidden tab-content pt-6">
- <h2 class="text-2xl font-semibold text-[var(--text-primary)] mb-6" data-i18n="accountTabs.sharedTranscripts">My Shared Transcripts</h2>
+ <h2 class="text-2xl font-semibold text-[var(--text-primary)] mb-6" data-i18n="accountTabs.sharedTranscripts">Shared Transcripts</h2>
<div id="shares-container" class="space-y-4">
<!-- Shares will be loaded here by JavaScript -->
</div>
</div>
- <div id="content-speakers" class="hidden tab-content pt-6">
- <div class="flex-shrink-0">
- <h2 class="text-2xl font-semibold text-[var(--text-primary)] mb-4" data-i18n="accountTabs.speakersManagement">Speakers Management</h2>
- <p class="text-[var(--text-secondary)] mb-4" data-i18n="speakersManagement.description">Manage your saved speakers. These are automatically saved when you use speaker names in your recordings.</p>
+ <div id="content-speakers" class="hidden tab-content pt-6 flex flex-col h-full">
+ <!-- Header -->
+ <div class="flex-shrink-0 mb-4">
+ <h2 class="text-2xl font-semibold text-[var(--text-primary)] mb-2" data-i18n="accountTabs.speakersManagement">Speakers Management</h2>
+ <p class="text-sm text-[var(--text-secondary)]" data-i18n="speakersManagement.description">Manage your saved speakers. These are automatically saved when you use speaker names in your recordings.</p>
</div>
-
+
+ <!-- Top toolbar with bulk actions -->
+ <div class="flex-shrink-0 flex justify-between items-center py-3 px-4 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-primary)] mb-3">
+ <div class="flex items-center gap-4">
+ <label class="flex items-center text-sm text-[var(--text-muted)] cursor-pointer hover:text-[var(--text-primary)] transition-colors">
+ <input type="checkbox" id="selectAllSpeakersTop" class="select-all-checkbox mr-2 rounded border-gray-300 dark:border-gray-600 text-blue-600 focus:ring-blue-500">
+ <span>Select All</span>
+ </label>
+ <span class="text-sm text-[var(--text-muted)]">
+ <span id="speakersTabCountTop" class="speakers-count">0</span> <span data-i18n="speakersManagement.totalSpeakers">speakers saved</span>
+ </span>
+ </div>
+ <div class="flex space-x-2">
+ <button class="bulk-delete-btn px-3 py-1.5 text-sm bg-red-600 dark:bg-red-500 text-white rounded-md hover:bg-red-700 dark:hover:bg-red-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors" disabled>
+ <i class="fas fa-trash mr-1"></i>
+ <span>Delete</span>
+ </button>
+ <button class="bulk-clear-btn px-3 py-1.5 text-sm bg-orange-600 dark:bg-orange-500 text-white rounded-md hover:bg-orange-700 dark:hover:bg-orange-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors" disabled>
+ <i class="fas fa-waveform-lines mr-1"></i>
+ <span>Clear Profiles</span>
+ </button>
+ <button class="bulk-merge-btn px-3 py-1.5 text-sm bg-[var(--bg-accent)] text-[var(--text-accent)] rounded-md hover:bg-[var(--bg-accent-hover)] disabled:opacity-50 disabled:cursor-not-allowed transition-colors" disabled>
+ <i class="fas fa-object-group mr-1"></i>
+ <span>Merge</span>
+ </button>
+ </div>
+ </div>
+
+ <!-- Scrollable content area -->
<div class="flex-1 overflow-y-auto min-h-0 pr-2" style="scrollbar-width: thin; scrollbar-color: var(--border-secondary) transparent;">
<!-- Loading state -->
<div id="speakersTabLoading" class="text-center py-8 hidden">
<i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
<p class="text-[var(--text-muted)] mt-2" data-i18n="speakersManagement.loadingSpeakers">Loading speakers...</p>
</div>
-
+
<!-- Error state -->
<div id="speakersTabError" class="hidden bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)] p-3 rounded-lg mb-4">
<i class="fas fa-exclamation-triangle mr-2"></i>
<span id="speakersTabErrorMessage" data-i18n="speakersManagement.failedToLoad">Failed to load speakers</span>
</div>
-
+
<!-- Empty state -->
<div id="speakersTabEmpty" class="text-center py-12 hidden">
<i class="fas fa-users text-4xl text-[var(--text-light)] mb-4"></i>
<p class="text-[var(--text-muted)] text-lg mb-2" data-i18n="speakersManagement.noSpeakersYet">No speakers saved yet</p>
<p class="text-sm text-[var(--text-light)]" data-i18n="speakersManagement.speakersWillAppear">Speakers will appear here when you use speaker names in your recordings</p>
</div>
-
- <!-- Speakers grid with scrollable container -->
- <div id="speakersTabGrid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 pb-4">
+
+ <!-- Speakers grid -->
+ <div id="speakersTabGrid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5 gap-3">
<!-- Speakers will be populated here -->
</div>
</div>
-
- <!-- Fixed footer with count and actions -->
- <div class="flex-shrink-0 flex justify-between items-center mt-4 pt-4 border-t border-[var(--border-primary)]">
- <div class="text-sm text-[var(--text-muted)]">
- <span id="speakersTabCount">0</span> <span data-i18n="speakersManagement.totalSpeakers">speakers saved</span>
+
+ <!-- Bottom toolbar with bulk actions -->
+ <div class="flex-shrink-0 flex justify-between items-center py-3 px-4 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-primary)] mt-3">
+ <div class="flex items-center gap-4">
+ <label class="flex items-center text-sm text-[var(--text-muted)] cursor-pointer hover:text-[var(--text-primary)] transition-colors">
+ <input type="checkbox" id="selectAllSpeakersBottom" class="select-all-checkbox mr-2 rounded border-gray-300 dark:border-gray-600 text-blue-600 focus:ring-blue-500">
+ <span>Select All</span>
+ </label>
+ <span class="text-sm text-[var(--text-muted)]">
+ <span id="speakersTabCountBottom" class="speakers-count">0</span> <span data-i18n="speakersManagement.totalSpeakers">speakers saved</span>
+ </span>
</div>
- <div class="flex space-x-3">
- <button id="deleteAllSpeakersTabBtn" class="px-4 py-2 bg-[var(--bg-danger)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-danger-hover)] disabled:opacity-50 disabled:cursor-not-allowed" disabled>
- <i class="fas fa-trash mr-2"></i> <span data-i18n="buttons.deleteAll">Delete All</span>
+ <div class="flex space-x-2">
+ <button class="bulk-delete-btn px-3 py-1.5 text-sm bg-red-600 dark:bg-red-500 text-white rounded-md hover:bg-red-700 dark:hover:bg-red-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors" disabled>
+ <i class="fas fa-trash mr-1"></i>
+ <span>Delete</span>
+ </button>
+ <button class="bulk-clear-btn px-3 py-1.5 text-sm bg-orange-600 dark:bg-orange-500 text-white rounded-md hover:bg-orange-700 dark:hover:bg-orange-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors" disabled>
+ <i class="fas fa-waveform-lines mr-1"></i>
+ <span>Clear Profiles</span>
+ </button>
+ <button class="bulk-merge-btn px-3 py-1.5 text-sm bg-[var(--bg-accent)] text-[var(--text-accent)] rounded-md hover:bg-[var(--bg-accent-hover)] disabled:opacity-50 disabled:cursor-not-allowed transition-colors" disabled>
+ <i class="fas fa-object-group mr-1"></i>
+ <span>Merge</span>
</button>
</div>
</div>
@@ -1056,20 +1165,20 @@
<h3 class="text-xl font-semibold text-[var(--text-primary)]" data-i18n="account.changePassword">Change Password</h3>
<button id="closeModalBtn" class="text-[var(--text-light)] hover:text-[var(--text-muted)] text-2xl leading-none">&times;</button>
</div>
- <form id="changePasswordForm" method="POST" action="{{ url_for('change_password') }}">
+ <form id="changePasswordForm" method="POST" action="{{ url_for('auth.change_password') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<div class="mb-4">
<label for="current_password" class="block text-sm font-medium text-[var(--text-secondary)] mb-1" data-i18n="changePasswordModal.currentPassword">Current Password</label>
- <input type="password" id="current_password" name="current_password" required class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
+ <input type="password" id="current_password" name="current_password" autocomplete="current-password" required class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
</div>
<div class="mb-4">
<label for="new_password" class="block text-sm font-medium text-[var(--text-secondary)] mb-1" data-i18n="changePasswordModal.newPassword">New Password</label>
- <input type="password" id="new_password" name="new_password" required minlength="8" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
+ <input type="password" id="new_password" name="new_password" autocomplete="new-password" required minlength="8" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
<p class="text-xs text-[var(--text-muted)] mt-1" data-i18n="changePasswordModal.passwordRequirement">Password must be at least 8 characters long</p>
</div>
<div class="mb-6">
<label for="confirm_password" class="block text-sm font-medium text-[var(--text-secondary)] mb-1" data-i18n="changePasswordModal.confirmPassword">Confirm New Password</label>
- <input type="password" id="confirm_password" name="confirm_password" required class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
+ <input type="password" id="confirm_password" name="confirm_password" autocomplete="new-password" required class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
</div>
<div class="flex justify-end space-x-3">
<button type="button" id="cancelBtn" class="px-4 py-2 bg-[var(--bg-tertiary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--border-secondary)]">Cancel</button>
@@ -1154,6 +1263,220 @@
</div>
</div>
+ <!-- Delete Selected Speakers Confirmation Modal -->
+ <div id="deleteSelectedSpeakersModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm hidden">
+ <div class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-md transform transition-all duration-300 ease-in-out">
+ <!-- Header -->
+ <div class="p-6 border-b border-[var(--border-primary)]">
+ <div class="flex items-center gap-4">
+ <div class="w-12 h-12 bg-gradient-to-br from-red-500 to-red-600 rounded-full flex items-center justify-center shadow-lg">
+ <i class="fas fa-trash text-white text-lg"></i>
+ </div>
+ <div>
+ <h3 class="text-xl font-bold text-[var(--text-primary)]">Delete Speakers</h3>
+ <p class="text-sm text-[var(--text-muted)] mt-0.5">This action cannot be undone</p>
+ </div>
+ </div>
+ </div>
+
+ <!-- Content -->
+ <div class="p-6">
+ <div class="mb-4">
+ <p class="text-[var(--text-secondary)] mb-3">
+ You are about to delete <strong id="deleteSelectedCount" class="text-[var(--text-primary)]">0</strong> speaker(s):
+ </p>
+ <div id="deleteSelectedSpeakersList" class="max-h-48 overflow-y-auto space-y-2 bg-[var(--bg-tertiary)] rounded-lg p-3 border border-[var(--border-primary)]">
+ <!-- Populated dynamically -->
+ </div>
+ </div>
+
+ <div class="flex items-start space-x-3 bg-red-50 dark:bg-red-900/20 p-3 rounded-lg border border-red-200 dark:border-red-800">
+ <div class="w-6 h-6 bg-red-100 dark:bg-red-900/40 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
+ <i class="fas fa-exclamation-triangle text-red-600 dark:text-red-400 text-xs"></i>
+ </div>
+ <div>
+ <p class="text-sm text-red-800 dark:text-red-200">
+ All voice profiles, recordings associations, and usage data will be permanently deleted.
+ </p>
+ </div>
+ </div>
+ </div>
+
+ <!-- Footer -->
+ <div class="bg-[var(--bg-tertiary)] px-6 py-4 rounded-b-xl flex justify-end space-x-3 border-t border-[var(--border-primary)]">
+ <button id="cancelDeleteSelectedBtn" class="px-5 py-2.5 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] transition-all duration-200 flex items-center shadow-sm font-medium">
+ <i class="fas fa-times mr-2"></i>
+ Cancel
+ </button>
+ <button id="confirmDeleteSelectedBtn" class="px-5 py-2.5 bg-gradient-to-r from-red-500 to-red-600 text-white rounded-lg hover:from-red-600 hover:to-red-700 transition-all duration-200 flex items-center shadow-lg font-medium">
+ <i class="fas fa-trash mr-2"></i>
+ Delete Speakers
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Clear Voice Profiles Confirmation Modal -->
+ <div id="clearVoiceProfilesModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm hidden">
+ <div class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-md transform transition-all duration-300 ease-in-out">
+ <!-- Header -->
+ <div class="bg-gradient-to-r from-orange-500 to-[var(--bg-secondary)] p-5 rounded-t-xl flex items-center">
+ <div class="flex items-center">
+ <div class="w-12 h-12 bg-gradient-to-br from-orange-500 to-amber-600 rounded-full flex items-center justify-center mr-4 shadow-lg">
+ <i class="fas fa-waveform-lines text-white text-lg"></i>
+ </div>
+ <div>
+ <h3 class="text-xl font-bold text-[var(--text-primary)] mb-1">Clear Voice Profiles</h3>
+ <p class="text-sm text-[var(--text-muted)]">Remove voice recognition data</p>
+ </div>
+ </div>
+ </div>
+
+ <!-- Content -->
+ <div class="p-6 modal-content">
+ <div class="mb-4">
+ <p class="text-[var(--text-secondary)] mb-3">
+ Clear voice profiles for <strong id="clearVoiceProfilesCount" class="text-[var(--text-primary)]">0</strong> speaker(s):
+ </p>
+ <div id="clearVoiceProfilesList" class="max-h-48 overflow-y-auto space-y-2 bg-[var(--bg-tertiary)] rounded-lg p-3 border border-[var(--border-primary)]">
+ <!-- Populated dynamically -->
+ </div>
+ </div>
+
+ <div class="space-y-3">
+ <div class="flex items-start space-x-3">
+ <div class="w-6 h-6 bg-amber-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
+ <i class="fas fa-info-circle text-amber-600 text-xs"></i>
+ </div>
+ <div>
+ <p class="text-[var(--text-secondary)] font-medium mb-1">What will happen:</p>
+ <p class="text-sm text-[var(--text-muted)]">
+ All voice embeddings and recognition data will be removed. Speaker names and usage history will be preserved.
+ </p>
+ </div>
+ </div>
+
+ <div class="flex items-start space-x-3">
+ <div class="w-6 h-6 bg-green-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
+ <i class="fas fa-check text-green-600 text-xs"></i>
+ </div>
+ <div>
+ <p class="text-sm text-[var(--text-muted)]">
+ New voice profiles will be created when you identify these speakers in future recordings.
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Footer -->
+ <div class="bg-[var(--bg-tertiary)] px-6 py-4 rounded-b-xl flex justify-end space-x-3 border-t border-[var(--border-primary)]">
+ <button id="cancelClearVoiceProfilesBtn" class="px-5 py-2.5 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] transition-all duration-200 flex items-center shadow-sm font-medium">
+ <i class="fas fa-times mr-2"></i>
+ Cancel
+ </button>
+ <button id="confirmClearVoiceProfilesBtn" class="px-5 py-2.5 bg-gradient-to-r from-orange-500 to-amber-600 text-white rounded-lg hover:from-orange-600 hover:to-amber-700 transition-all duration-200 flex items-center shadow-lg font-medium">
+ <i class="fas fa-waveform-lines mr-2"></i>
+ Clear Profiles
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Merge Speakers Modal -->
+ <div id="mergeSpeakersModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-60 p-4 backdrop-blur-sm hidden">
+ <div class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-lg max-h-[80vh] flex flex-col transform transition-all duration-300 ease-in-out">
+ <!-- Header -->
+ <div class="bg-gradient-to-r from-[var(--bg-accent)] to-[var(--bg-secondary)] p-5 rounded-t-xl flex items-center justify-between flex-shrink-0">
+ <div class="flex items-center">
+ <div class="w-12 h-12 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center mr-4 shadow-lg">
+ <i class="fas fa-object-group text-white text-lg"></i>
+ </div>
+ <div>
+ <h3 class="text-xl font-bold text-[var(--text-primary)] mb-1">Merge Speakers</h3>
+ <p class="text-sm text-[var(--text-muted)]">Combine speaker profiles</p>
+ </div>
+ </div>
+ <button id="closeMergeModal" class="text-[var(--text-light)] hover:text-[var(--text-muted)] text-2xl leading-none w-8 h-8 flex items-center justify-center rounded-full hover:bg-[var(--bg-tertiary)] transition-colors">&times;</button>
+ </div>
+
+ <!-- Info Section -->
+ <div class="p-6 flex-shrink-0 border-b border-[var(--border-primary)]">
+ <div class="flex items-start space-x-3">
+ <div class="w-6 h-6 bg-blue-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
+ <i class="fas fa-info-circle text-blue-600 text-xs"></i>
+ </div>
+ <div>
+ <p class="text-sm text-[var(--text-secondary)]">
+ Click on the speaker you want to keep. All voice data, snippets, and usage statistics from other speakers will be merged into it.
+ </p>
+ </div>
+ </div>
+ </div>
+
+ <!-- Scrollable speaker list -->
+ <div class="flex-1 overflow-y-auto min-h-0 p-6">
+ <div id="mergeSpeakersList" class="space-y-2">
+ <!-- Populated dynamically -->
+ </div>
+ </div>
+
+ <!-- Footer -->
+ <div class="bg-[var(--bg-tertiary)] px-6 py-4 rounded-b-xl flex justify-end space-x-3 border-t border-[var(--border-primary)] flex-shrink-0">
+ <button id="cancelMergeBtn" class="px-5 py-2.5 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] transition-all duration-200 flex items-center shadow-sm font-medium">
+ <i class="fas fa-times mr-2"></i>
+ Cancel
+ </button>
+ <button id="executeMergeBtn" class="px-5 py-2.5 bg-gradient-to-r from-blue-500 to-purple-600 text-white rounded-lg hover:from-blue-600 hover:to-purple-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 flex items-center shadow-lg font-medium" disabled>
+ <i class="fas fa-object-group mr-2"></i>
+ <span>Merge Speakers</span>
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Edit Speaker Modal -->
+ <div id="editSpeakerModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-60 p-4 backdrop-blur-sm hidden">
+ <div class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-md transform transition-all duration-300 ease-in-out">
+ <!-- Header -->
+ <div class="p-5 border-b border-[var(--border-primary)]">
+ <div class="flex items-center justify-between">
+ <div class="flex items-center">
+ <div class="w-10 h-10 bg-[var(--bg-accent)] rounded-full flex items-center justify-center mr-3">
+ <i class="fas fa-edit text-[var(--text-button)]"></i>
+ </div>
+ <h3 class="text-lg font-bold text-[var(--text-primary)]">Edit Speaker Name</h3>
+ </div>
+ <button id="closeEditSpeakerModal" class="text-[var(--text-light)] hover:text-[var(--text-muted)] text-2xl leading-none w-8 h-8 flex items-center justify-center rounded-full hover:bg-[var(--bg-tertiary)] transition-colors">&times;</button>
+ </div>
+ </div>
+
+ <!-- Body -->
+ <div class="p-6">
+ <label for="editSpeakerNameInput" class="block text-sm font-medium text-[var(--text-secondary)] mb-2">
+ Speaker Name
+ </label>
+ <input
+ type="text"
+ id="editSpeakerNameInput"
+ class="w-full px-4 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
+ placeholder="Enter speaker name">
+ <div id="editSpeakerError" class="mt-2 text-sm text-[var(--text-danger)] hidden"></div>
+ </div>
+
+ <!-- Footer -->
+ <div class="bg-[var(--bg-tertiary)] px-6 py-4 rounded-b-xl flex justify-end space-x-3 border-t border-[var(--border-primary)]">
+ <button id="cancelEditSpeakerBtn" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] transition-colors">
+ Cancel
+ </button>
+ <button id="saveEditSpeakerBtn" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors">
+ <i class="fas fa-save mr-2"></i>
+ Save
+ </button>
+ </div>
+ </div>
+ </div>
+
<!-- Create/Edit Tag Modal -->
<div id="tagModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
<div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
@@ -1184,7 +1507,91 @@
<textarea id="tagCustomPrompt" name="custom_prompt" rows="4" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]" placeholder="Optional: Custom prompt for generating summaries for recordings with this tag" data-i18n-placeholder="editTagModal.customPromptPlaceholder"></textarea>
<p class="text-xs text-[var(--text-light)] mt-1" data-i18n="editTagModal.leaveBlankPrompt">Leave blank to use your default summary prompt</p>
</div>
-
+
+ <!-- Group Selection (only shown if internal sharing is enabled and user is admin of some groups) -->
+ <div id="tagGroupSelectionSection" class="hidden">
+ <label for="tagGroupId" class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Group Assignment (Optional)</label>
+ <select id="tagGroupId" name="group_id" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
+ <option value="">Personal Tag (Not Associated with a Group)</option>
+ <!-- Group options will be populated dynamically -->
+ </select>
+ <p class="text-xs text-[var(--text-light)] mt-1">
+ Assign this tag to a group to enable auto-sharing when applied to recordings
+ </p>
+ </div>
+
+ <!-- Group-Specific Settings (only shown when a group is selected) -->
+ <div id="tagGroupSettingsSection" class="hidden border-t border-[var(--border-primary)] pt-4 mt-4">
+ <h4 class="text-sm font-medium text-[var(--text-secondary)] mb-3">
+ <i class="fas fa-users mr-2"></i>Group Sharing Settings
+ </h4>
+
+ <div class="space-y-3">
+ <div class="flex items-start space-x-3">
+ <input type="checkbox" id="tagAutoShareOnApply" name="auto_share_on_apply" checked class="mt-1 h-4 w-4 text-[var(--bg-accent)] border-gray-300 rounded focus:ring-[var(--border-focus)]">
+ <div class="flex-1">
+ <label for="tagAutoShareOnApply" class="block text-sm font-medium text-[var(--text-secondary)] cursor-pointer">
+ <i class="fas fa-share-alt mr-1"></i>
+ Auto-share recordings with all group members when this tag is applied
+ </label>
+ <p class="text-xs text-[var(--text-light)] mt-1">
+ All group members will automatically get access to recordings with this tag
+ </p>
+ </div>
+ </div>
+
+ <div class="flex items-start space-x-3">
+ <input type="checkbox" id="tagShareWithGroupLead" name="share_with_group_lead" checked class="mt-1 h-4 w-4 text-[var(--bg-accent)] border-gray-300 rounded focus:ring-[var(--border-focus)]">
+ <div class="flex-1">
+ <label for="tagShareWithGroupLead" class="block text-sm font-medium text-[var(--text-secondary)] cursor-pointer">
+ <i class="fas fa-user-shield mr-1"></i>
+ Share recordings with group admins only when this tag is applied
+ </label>
+ <p class="text-xs text-[var(--text-light)] mt-1">
+ Only group admins will get access (not all members)
+ </p>
+ </div>
+ </div>
+ </div>
+ <p class="text-xs text-[var(--text-light)] italic mt-3">
+ Note: If both are enabled, all group members will have access. If only "group admins" is enabled, only group leads will have access.
+ </p>
+ </div>
+
+ <!-- Retention Period Override (only shown when auto-deletion is enabled) -->
+ <div id="tagRetentionSection" class="hidden border-t border-[var(--border-primary)] pt-4 mt-4">
+ <h4 class="text-sm font-medium text-[var(--text-secondary)] mb-3">
+ <i class="fas fa-clock mr-2"></i>Retention & Auto-Deletion Settings
+ </h4>
+
+ <div class="space-y-3">
+ <!-- Retention Period Override -->
+ <div id="tagRetentionDaysContainer">
+ <label for="tagRetentionDays" class="block text-sm font-medium text-[var(--text-secondary)] mb-1">
+ Retention Period (days)
+ </label>
+ <input type="number" id="tagRetentionDays" name="retention_days" min="1" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]" placeholder="Leave empty to use global retention">
+ <p class="text-xs text-[var(--text-light)] mt-1">
+ Leave empty to use global retention period. Set a custom value to override for recordings with this tag.
+ </p>
+ </div>
+
+ <!-- Deletion Protection Checkbox -->
+ <div class="flex items-start space-x-3 p-3 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-md">
+ <input type="checkbox" id="tagProtectFromDeletion" class="mt-1 h-4 w-4 text-[var(--bg-accent)] border-gray-300 rounded focus:ring-[var(--border-focus)]">
+ <div class="flex-1">
+ <label for="tagProtectFromDeletion" class="block text-sm font-medium text-[var(--text-secondary)] cursor-pointer">
+ <i class="fas fa-shield-alt mr-1 text-yellow-600 dark:text-yellow-400"></i>
+ Protect from Auto-Deletion (Infinite Retention)
+ </label>
+ <p class="text-xs text-[var(--text-light)] mt-1">
+ Recordings with this tag will never be automatically deleted. When enabled, retention period is set to infinite.
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+
{% if use_asr_endpoint %}
<div class="border-t border-[var(--border-primary)] pt-4">
<h4 class="text-sm font-medium text-[var(--text-secondary)] mb-3" data-i18n="editTagModal.asrDefaultSettings">ASR Default Settings</h4>
@@ -1224,12 +1631,157 @@
<script>
document.addEventListener('DOMContentLoaded', async function() {
- // Initialize i18n
- await initializeI18n();
+ try {
+ // Initialize i18n
+ await initializeI18n();
+ } catch (error) {
+ console.error('Error initializing i18n:', error);
+ }
+
+ // Setup merge modal event listeners
+ const closeMergeModalBtn = document.getElementById('closeMergeModal');
+ const cancelMergeBtn = document.getElementById('cancelMergeBtn');
+ const executeMergeBtn = document.getElementById('executeMergeBtn');
+ const mergeSpeakersModal = document.getElementById('mergeSpeakersModal');
+
+ if (closeMergeModalBtn) {
+ closeMergeModalBtn.addEventListener('click', () => {
+ mergeSpeakersModal.classList.add('hidden');
+ });
+ }
+
+ if (cancelMergeBtn) {
+ cancelMergeBtn.addEventListener('click', () => {
+ mergeSpeakersModal.classList.add('hidden');
+ });
+ }
+
+ if (executeMergeBtn) {
+ executeMergeBtn.addEventListener('click', () => {
+ executeSpeakerMerge();
+ });
+ }
+
+ // Setup edit speaker modal event listeners
+ const closeEditSpeakerModalBtn = document.getElementById('closeEditSpeakerModal');
+ const cancelEditSpeakerBtn = document.getElementById('cancelEditSpeakerBtn');
+ const saveEditSpeakerBtn = document.getElementById('saveEditSpeakerBtn');
+ const editSpeakerModal = document.getElementById('editSpeakerModal');
+ const editSpeakerNameInput = document.getElementById('editSpeakerNameInput');
+ const editSpeakerError = document.getElementById('editSpeakerError');
+
+ let currentEditingSpeakerId = null;
+
+ function closeEditSpeakerModalFn() {
+ editSpeakerModal.classList.add('hidden');
+ editSpeakerNameInput.value = '';
+ editSpeakerError.classList.add('hidden');
+ currentEditingSpeakerId = null;
+ }
+
+ if (closeEditSpeakerModalBtn) {
+ closeEditSpeakerModalBtn.addEventListener('click', closeEditSpeakerModalFn);
+ }
+
+ if (cancelEditSpeakerBtn) {
+ cancelEditSpeakerBtn.addEventListener('click', closeEditSpeakerModalFn);
+ }
+
+ // Close modal when clicking outside
+ editSpeakerModal.addEventListener('click', (event) => {
+ if (event.target === editSpeakerModal) {
+ closeEditSpeakerModalFn();
+ }
+ });
+
+ // Handle Enter key to save
+ editSpeakerNameInput.addEventListener('keypress', (event) => {
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ saveEditSpeakerBtn.click();
+ }
+ });
+
+ if (saveEditSpeakerBtn) {
+ saveEditSpeakerBtn.addEventListener('click', async () => {
+ const newName = editSpeakerNameInput.value.trim();
+
+ if (!newName) {
+ editSpeakerError.textContent = 'Speaker name cannot be empty';
+ editSpeakerError.classList.remove('hidden');
+ return;
+ }
- // Hide loading overlay after everything is ready
+ try {
+ const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
+ const response = await fetch(`/speakers/${currentEditingSpeakerId}`, {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({ name: newName })
+ });
+
+ const data = await response.json();
+
+ if (!response.ok) {
+ editSpeakerError.textContent = data.error || 'Failed to update speaker';
+ editSpeakerError.classList.remove('hidden');
+ return;
+ }
+
+ showToast('Speaker name updated successfully');
+ closeEditSpeakerModalFn();
+
+ // Reload speakers - reset flag to force reload
+ speakersTabLoaded = false;
+ await loadSpeakersTab();
+ } catch (error) {
+ console.error('Error updating speaker:', error);
+ editSpeakerError.textContent = 'Failed to update speaker';
+ editSpeakerError.classList.remove('hidden');
+ }
+ });
+ }
+
+ // Setup delete selected speakers modal event listeners
+ const cancelDeleteSelectedBtn = document.getElementById('cancelDeleteSelectedBtn');
+ const confirmDeleteSelectedBtn = document.getElementById('confirmDeleteSelectedBtn');
+ const deleteSelectedSpeakersModal = document.getElementById('deleteSelectedSpeakersModal');
+
+ if (cancelDeleteSelectedBtn) {
+ cancelDeleteSelectedBtn.addEventListener('click', () => {
+ deleteSelectedSpeakersModal.classList.add('hidden');
+ });
+ }
+
+ if (confirmDeleteSelectedBtn) {
+ confirmDeleteSelectedBtn.addEventListener('click', () => {
+ executeDeleteSelectedSpeakers();
+ });
+ }
+
+ // Setup clear voice profiles modal event listeners
+ const cancelClearVoiceProfilesBtn = document.getElementById('cancelClearVoiceProfilesBtn');
+ const confirmClearVoiceProfilesBtn = document.getElementById('confirmClearVoiceProfilesBtn');
+ const clearVoiceProfilesModal = document.getElementById('clearVoiceProfilesModal');
+
+ if (cancelClearVoiceProfilesBtn) {
+ cancelClearVoiceProfilesBtn.addEventListener('click', () => {
+ clearVoiceProfilesModal.classList.add('hidden');
+ });
+ }
+
+ if (confirmClearVoiceProfilesBtn) {
+ confirmClearVoiceProfilesBtn.addEventListener('click', () => {
+ executeClearVoiceProfiles();
+ });
+ }
+
+ // Hide loading overlay
if (window.AppLoader) {
- AppLoader.waitForReady();
+ window.AppLoader.hide();
}
// Setup scroll indicators for tabs
@@ -1419,39 +1971,38 @@
const speakersTabEmpty = document.getElementById('speakersTabEmpty');
const speakersTabGrid = document.getElementById('speakersTabGrid');
const speakersTabCount = document.getElementById('speakersTabCount');
- const deleteAllSpeakersTabBtn = document.getElementById('deleteAllSpeakersTabBtn');
-
+
// Show loading state
speakersTabLoading.classList.remove('hidden');
speakersTabError.classList.add('hidden');
speakersTabEmpty.classList.add('hidden');
speakersTabGrid.classList.add('hidden');
-
+
try {
const response = await fetch('/speakers');
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
-
+
speakersTabData = await response.json();
speakersTabLoaded = true;
-
+
// Hide loading state
speakersTabLoading.classList.add('hidden');
-
+
if (speakersTabData.length === 0) {
speakersTabEmpty.classList.remove('hidden');
speakersTabGrid.classList.add('hidden');
- deleteAllSpeakersTabBtn.disabled = true;
} else {
speakersTabEmpty.classList.add('hidden');
speakersTabGrid.classList.remove('hidden');
- deleteAllSpeakersTabBtn.disabled = false;
renderSpeakersTabGrid();
}
- // Update count
- speakersTabCount.textContent = speakersTabData.length;
+ // Update counts in all locations
+ document.querySelectorAll('.speakers-count').forEach(el => {
+ el.textContent = speakersTabData.length;
+ });
} catch (error) {
console.error('Error loading speakers:', error);
@@ -1460,65 +2011,139 @@
speakersTabEmpty.classList.add('hidden');
speakersTabGrid.classList.add('hidden');
speakersTabErrorMessage.textContent = error.message;
- speakersTabCount.textContent = '0';
+ document.querySelectorAll('.speakers-count').forEach(el => {
+ el.textContent = '0';
+ });
}
}
function renderSpeakersTabGrid() {
const speakersTabGrid = document.getElementById('speakersTabGrid');
speakersTabGrid.innerHTML = '';
-
+
speakersTabData.forEach(speaker => {
const createdDate = new Date(speaker.created_at).toLocaleDateString();
const lastUsedDate = new Date(speaker.last_used).toLocaleDateString();
-
+
+ // Voice profile status
+ const hasVoiceProfile = speaker.embedding_count && speaker.embedding_count > 0;
+ const confidenceLevel = speaker.confidence_score
+ ? (speaker.confidence_score >= 0.8 ? 'high' : speaker.confidence_score >= 0.6 ? 'medium' : 'low')
+ : null;
+ const confidenceBadge = hasVoiceProfile && confidenceLevel
+ ? `<span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium" style="background-color: ${confidenceLevel === 'high' ? '#10b981' : confidenceLevel === 'medium' ? '#f59e0b' : '#f97316'}; color: white;">
+ <i class="fas fa-shield-alt mr-1"></i>${confidenceLevel}
+ </span>`
+ : '';
+
const speakerCard = document.createElement('div');
- speakerCard.className = 'bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-primary)] p-4 hover:border-[var(--border-accent)] transition-colors duration-200';
-
+ speakerCard.className = 'bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-primary)] hover:border-[var(--border-accent)] transition-colors duration-200';
+ speakerCard.dataset.speakerId = speaker.id;
+
speakerCard.innerHTML = `
- <div class="flex flex-col h-full">
- <div class="flex items-start justify-between mb-3">
- <div class="flex items-center flex-1 min-w-0">
- <i class="fas fa-user text-[var(--text-accent)] mr-2 flex-shrink-0"></i>
- <h3 class="font-medium text-base text-[var(--text-primary)] truncate">${escapeHtml(speaker.name)}</h3>
+ <div class="p-3">
+ <!-- Header with checkbox, name, and action buttons -->
+ <div class="flex items-center justify-between mb-2">
+ <div class="flex items-center flex-1 min-w-0 gap-2">
+ <input type="checkbox" class="speaker-select-checkbox rounded border-gray-300 dark:border-gray-600 text-blue-600 focus:ring-blue-500 flex-shrink-0"
+ data-speaker-id="${speaker.id}" data-speaker-name="${escapeHtml(speaker.name)}">
+ <i class="fas fa-user text-[var(--text-accent)] text-sm flex-shrink-0"></i>
+ <h3 class="font-medium text-sm text-[var(--text-primary)] truncate">${escapeHtml(speaker.name)}</h3>
+ </div>
+ <div class="flex gap-1 flex-shrink-0">
+ <button class="edit-speaker-tab-btn p-1 text-[var(--text-accent)] hover:bg-[var(--bg-accent-light)] rounded transition-colors"
+ data-speaker-id="${speaker.id}"
+ data-speaker-name="${escapeHtml(speaker.name)}"
+ title="Edit speaker name">
+ <i class="fas fa-edit text-xs"></i>
+ </button>
+ <button class="delete-speaker-tab-btn p-1 text-[var(--text-danger)] hover:bg-[var(--bg-danger-light)] rounded transition-colors"
+ data-speaker-id="${speaker.id}"
+ data-speaker-name="${escapeHtml(speaker.name)}"
+ title="Delete speaker">
+ <i class="fas fa-trash text-xs"></i>
+ </button>
</div>
- <button class="delete-speaker-tab-btn ml-2 p-1.5 text-[var(--text-danger)] hover:bg-[var(--bg-danger-light)] rounded-md transition-colors duration-200 flex-shrink-0"
- data-speaker-id="${speaker.id}"
- data-speaker-name="${escapeHtml(speaker.name)}"
- data-i18n-title="buttons.deleteSpeaker">
- <i class="fas fa-trash text-sm"></i>
- </button>
</div>
- <div class="space-y-1 text-xs text-[var(--text-muted)]">
- <p class="flex items-center">
- <i class="fas fa-chart-line mr-1.5 text-xs opacity-60"></i>
- ${t('speakersManagement.used')} ${speaker.use_count} ${t('speakersManagement.' + (speaker.use_count !== 1 ? 'times' : 'time'))}
- </p>
- <p class="flex items-center">
- <i class="fas fa-clock mr-1.5 text-xs opacity-60"></i>
- ${t('speakersManagement.last')}: ${lastUsedDate}
- </p>
- <p class="flex items-center">
- <i class="fas fa-calendar-plus mr-1.5 text-xs opacity-60"></i>
- ${t('speakersManagement.added')}: ${createdDate}
- </p>
+
+ <!-- Voice Profile Badge (if exists) -->
+ ${hasVoiceProfile ? `
+ <div class="flex items-center justify-between gap-2 mb-2 px-2 py-1 bg-[var(--bg-secondary)] rounded">
+ <div class="flex items-center gap-1.5 min-w-0">
+ <i class="fas fa-waveform-lines text-blue-500 text-[10px] flex-shrink-0"></i>
+ <span class="text-[10px] text-[var(--text-muted)] truncate">${speaker.embedding_count} sample${speaker.embedding_count !== 1 ? 's' : ''}</span>
+ </div>
+ ${confidenceBadge}
+ </div>
+ ` : ''}
+
+ <!-- Stats in compact grid -->
+ <div class="grid grid-cols-2 gap-1 text-[10px] text-[var(--text-muted)] mb-2">
+ <div class="flex items-center gap-1">
+ <i class="fas fa-chart-line opacity-60"></i>
+ <span>${speaker.use_count}x</span>
+ </div>
+ <div class="flex items-center gap-1">
+ <i class="fas fa-clock opacity-60"></i>
+ <span class="truncate">${lastUsedDate}</span>
+ </div>
+ </div>
+
+ <!-- View Voice Samples Button -->
+ <button class="view-snippets-btn w-full px-2 py-1 text-[10px] bg-[var(--bg-secondary)] hover:bg-[var(--bg-primary)] text-[var(--text-secondary)] rounded border border-[var(--border-secondary)] transition-colors"
+ data-speaker-id="${speaker.id}">
+ <i class="fas fa-volume-up mr-1"></i>
+ <span>Voice Samples</span>
+ <i class="fas fa-chevron-down ml-1 transition-transform duration-200"></i>
+ </button>
+
+ <!-- Snippets Container -->
+ <div class="snippets-container mt-2 hidden">
+ <div class="snippets-loading text-center py-3">
+ <i class="fas fa-spinner fa-spin text-[var(--text-muted)] text-xs"></i>
+ </div>
+ <div class="snippets-content"></div>
</div>
</div>
`;
-
+
+ // Add edit functionality
+ const editBtn = speakerCard.querySelector('.edit-speaker-tab-btn');
+ editBtn.addEventListener('click', () => openEditSpeakerModal(speaker.id, speaker.name));
+
// Add delete functionality
const deleteBtn = speakerCard.querySelector('.delete-speaker-tab-btn');
deleteBtn.addEventListener('click', () => deleteSpeakerFromTab(speaker.id, speaker.name));
-
+
+ // Add view snippets functionality
+ const viewSnippetsBtn = speakerCard.querySelector('.view-snippets-btn');
+ const snippetsContainer = speakerCard.querySelector('.snippets-container');
+ viewSnippetsBtn.addEventListener('click', () => toggleSpeakerSnippets(speaker.id, viewSnippetsBtn, snippetsContainer));
+
speakersTabGrid.appendChild(speakerCard);
});
+
+ // Update bulk operation buttons state
+ updateBulkOperationButtons();
}
+ function openEditSpeakerModal(speakerId, currentName) {
+ currentEditingSpeakerId = speakerId;
+ editSpeakerNameInput.value = currentName;
+ editSpeakerError.classList.add('hidden');
+ editSpeakerModal.classList.remove('hidden');
+ // Focus input and select text for easy editing
+ setTimeout(() => {
+ editSpeakerNameInput.focus();
+ editSpeakerNameInput.select();
+ }, 100);
+ }
+
async function deleteSpeakerFromTab(speakerId, speakerName) {
if (!confirm(`Are you sure you want to delete "${speakerName}"?`)) {
return;
}
-
+
try {
// Get CSRF token
const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
@@ -1544,65 +2169,514 @@
if (speakersTabData.length === 0) {
document.getElementById('speakersTabEmpty').classList.remove('hidden');
document.getElementById('speakersTabGrid').classList.add('hidden');
- document.getElementById('deleteAllSpeakersTabBtn').disabled = true;
} else {
renderSpeakersTabGrid();
}
- document.getElementById('speakersTabCount').textContent = speakersTabData.length;
+ document.querySelectorAll('.speakers-count').forEach(el => {
+ el.textContent = speakersTabData.length;
+ });
showToast(`Speaker "${speakerName}" deleted successfully`);
} catch (error) {
console.error('Error deleting speaker:', error);
showToast(`Failed to delete speaker: ${error.message}`, 'error');
}
}
-
- // Delete all speakers from tab
- document.getElementById('deleteAllSpeakersTabBtn')?.addEventListener('click', async () => {
- if (!confirm('Are you sure you want to delete all speakers? This action cannot be undone.')) {
+
+ // Toggle speaker snippets
+ async function toggleSpeakerSnippets(speakerId, button, container) {
+ const isExpanded = !container.classList.contains('hidden');
+ const chevron = button.querySelector('.fa-chevron-down');
+
+ if (isExpanded) {
+ container.classList.add('hidden');
+ chevron.classList.remove('rotate-180');
+ // Pause all audio players in this container
+ container.querySelectorAll('audio').forEach(audio => audio.pause());
return;
}
-
+
+ // Expand and load snippets
+ container.classList.remove('hidden');
+ chevron.classList.add('rotate-180');
+
+ const loadingEl = container.querySelector('.snippets-loading');
+ const contentEl = container.querySelector('.snippets-content');
+
+ loadingEl.classList.remove('hidden');
+ contentEl.classList.add('hidden');
+
try {
- // Get CSRF token
- const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
-
- const headers = {};
- if (csrfToken) {
- headers['X-CSRFToken'] = csrfToken;
+ const response = await fetch(`/speakers/${speakerId}/snippets?limit=3`);
+ if (!response.ok) throw new Error('Failed to load snippets');
+
+ const data = await response.json();
+ const snippets = data.snippets || [];
+
+ loadingEl.classList.add('hidden');
+ contentEl.classList.remove('hidden');
+
+ if (snippets.length === 0) {
+ contentEl.innerHTML = `
+ <div class="text-xs text-[var(--text-muted)] text-center py-3 px-2">
+ <i class="fas fa-info-circle mb-2 text-blue-500"></i>
+ <p class="mb-1">No voice samples found</p>
+ <p class="text-[10px] leading-relaxed">Voice samples are created when you identify speakers in recordings</p>
+ </div>
+ `;
+ } else {
+ contentEl.innerHTML = `
+ <div class="space-y-2 mt-2">
+ ${snippets.map((snippet, idx) => `
+ <div class="bg-[var(--bg-secondary)] p-2 rounded border border-[var(--border-secondary)]">
+ <!-- Compact audio player -->
+ <div class="flex items-center gap-2">
+ <div
+ class="flex items-center justify-center w-5 h-5 rounded-full bg-[var(--bg-accent)] text-[var(--text-accent)] text-[10px] font-medium flex-shrink-0 cursor-help"
+ title="${escapeHtml(snippet.recording_title)}">
+ ${idx + 1}
+ </div>
+ <div class="snippet-audio-container">
+ <button class="snippet-audio-btn snippet-play-btn" data-audio-id="snippet-${speakerId}-${idx}">
+ <i class="fas fa-play"></i>
+ </button>
+ <div class="snippet-audio-progress" data-audio-id="snippet-${speakerId}-${idx}">
+ <div class="snippet-audio-progress-bar"></div>
+ </div>
+ <div class="snippet-audio-time">
+ <span class="snippet-current-time">0:00</span>
+ </div>
+ <audio
+ class="snippet-audio"
+ id="snippet-${speakerId}-${idx}"
+ preload="none"
+ src="/speakers/snippet-audio/${snippet.recording_id}?start=${snippet.start_time}&duration=${snippet.duration}">
+ </audio>
+ </div>
+ </div>
+ </div>
+ `).join('')}
+ </div>
+ `;
+
+ // Initialize custom audio players
+ initSnippetAudioPlayers(contentEl, speakerId);
}
-
- // Delete all speakers one by one
- const deletePromises = speakersTabData.map(speaker =>
- fetch(`/speakers/${speaker.id}`, {
+ } catch (error) {
+ console.error('Error loading snippets:', error);
+ loadingEl.classList.add('hidden');
+ contentEl.classList.remove('hidden');
+ contentEl.innerHTML = '<p class="text-xs text-red-500 text-center py-2">Failed to load snippets</p>';
+ }
+ }
+
+ // Initialize custom audio players for snippets
+ function initSnippetAudioPlayers(container, speakerId) {
+ const savedVolume = window.vueApp?.playerVolume ?? 1.0;
+
+ container.querySelectorAll('.snippet-audio').forEach(audio => {
+ const audioId = audio.id;
+ const playBtn = container.querySelector(`.snippet-play-btn[data-audio-id="${audioId}"]`);
+ const progressBar = container.querySelector(`.snippet-audio-progress[data-audio-id="${audioId}"]`);
+ const progressFill = progressBar.querySelector('.snippet-audio-progress-bar');
+ const timeDisplay = playBtn.closest('.snippet-audio-container').querySelector('.snippet-current-time');
+ const icon = playBtn.querySelector('i');
+
+ // Set volume
+ audio.volume = savedVolume;
+
+ // Play/pause button
+ playBtn.addEventListener('click', () => {
+ if (audio.paused) {
+ // Pause all other snippet audios
+ container.querySelectorAll('.snippet-audio').forEach(otherAudio => {
+ if (otherAudio !== audio && !otherAudio.paused) {
+ otherAudio.pause();
+ }
+ });
+ audio.play();
+ } else {
+ audio.pause();
+ }
+ });
+
+ // Update play/pause icon
+ audio.addEventListener('play', () => {
+ icon.classList.remove('fa-play');
+ icon.classList.add('fa-pause');
+ });
+
+ audio.addEventListener('pause', () => {
+ icon.classList.remove('fa-pause');
+ icon.classList.add('fa-play');
+ });
+
+ // Update progress and time
+ audio.addEventListener('timeupdate', () => {
+ if (audio.duration) {
+ const percent = (audio.currentTime / audio.duration) * 100;
+ progressFill.style.width = percent + '%';
+ timeDisplay.textContent = formatTime(audio.currentTime);
+ }
+ });
+
+ // Reset on end
+ audio.addEventListener('ended', () => {
+ progressFill.style.width = '0%';
+ timeDisplay.textContent = '0:00';
+ icon.classList.remove('fa-pause');
+ icon.classList.add('fa-play');
+ });
+
+ // Seek by clicking progress bar
+ progressBar.addEventListener('click', (e) => {
+ const rect = progressBar.getBoundingClientRect();
+ const percent = (e.clientX - rect.left) / rect.width;
+ audio.currentTime = percent * audio.duration;
+ });
+ });
+
+ // Helper to format time
+ function formatTime(seconds) {
+ const mins = Math.floor(seconds / 60);
+ const secs = Math.floor(seconds % 60);
+ return `${mins}:${secs.toString().padStart(2, '0')}`;
+ }
+ }
+
+ // Update bulk operation buttons based on checkboxes
+ function updateBulkOperationButtons() {
+ const checkboxes = document.querySelectorAll('.speaker-select-checkbox:checked');
+ const count = checkboxes.length;
+
+ // Update all merge buttons
+ document.querySelectorAll('.bulk-merge-btn').forEach(btn => {
+ btn.disabled = count < 2;
+ const btnText = btn.querySelector('span');
+ if (btnText) {
+ btnText.textContent = count >= 2 ? `Merge (${count})` : 'Merge';
+ }
+ });
+
+ // Update all delete buttons
+ document.querySelectorAll('.bulk-delete-btn').forEach(btn => {
+ btn.disabled = count === 0;
+ const btnText = btn.querySelector('span');
+ if (btnText) {
+ btnText.textContent = count > 0 ? `Delete (${count})` : 'Delete';
+ }
+ });
+
+ // Update all clear profile buttons
+ document.querySelectorAll('.bulk-clear-btn').forEach(btn => {
+ btn.disabled = count === 0;
+ const btnText = btn.querySelector('span');
+ if (btnText) {
+ btnText.textContent = count > 0 ? `Clear (${count})` : 'Clear Profiles';
+ }
+ });
+
+ // Update speaker counts
+ document.querySelectorAll('.speakers-count').forEach(el => {
+ el.textContent = speakersTabData.length;
+ });
+
+ // Update select-all checkboxes state
+ const allCheckboxes = document.querySelectorAll('.speaker-select-checkbox');
+ const checkedCheckboxes = document.querySelectorAll('.speaker-select-checkbox:checked');
+ const allSelected = allCheckboxes.length === checkedCheckboxes.length && allCheckboxes.length > 0;
+ document.querySelectorAll('.select-all-checkbox').forEach(cb => {
+ cb.checked = allSelected;
+ });
+ }
+
+ // Handle checkbox changes
+ document.addEventListener('change', (e) => {
+ // Handle select-all checkboxes
+ if (e.target.classList.contains('select-all-checkbox')) {
+ const checkboxes = document.querySelectorAll('.speaker-select-checkbox');
+ checkboxes.forEach(cb => cb.checked = e.target.checked);
+ // Sync all select-all checkboxes
+ document.querySelectorAll('.select-all-checkbox').forEach(cb => {
+ cb.checked = e.target.checked;
+ });
+ updateBulkOperationButtons();
+ } else if (e.target.classList.contains('speaker-select-checkbox')) {
+ updateBulkOperationButtons();
+ }
+ });
+
+ // Handle bulk operation button clicks
+ document.addEventListener('click', (e) => {
+ const btn = e.target.closest('.bulk-delete-btn, .bulk-clear-btn, .bulk-merge-btn');
+ if (!btn) return;
+
+ if (btn.classList.contains('bulk-delete-btn')) {
+ deleteSelectedSpeakers();
+ } else if (btn.classList.contains('bulk-clear-btn')) {
+ clearSelectedVoiceProfiles();
+ } else if (btn.classList.contains('bulk-merge-btn')) {
+ openMergeSpeakersModal();
+ }
+ });
+
+ // Track selected target speaker for merge
+ let mergeTargetSpeakerId = null;
+
+ // Open merge modal
+ async function openMergeSpeakersModal() {
+ const checkboxes = document.querySelectorAll('.speaker-select-checkbox:checked');
+ if (checkboxes.length < 2) {
+ showToast('Please select at least 2 speakers to merge', 'error');
+ return;
+ }
+
+ const selectedSpeakers = Array.from(checkboxes).map(cb => ({
+ id: parseInt(cb.dataset.speakerId),
+ name: cb.dataset.speakerName
+ }));
+
+ const modal = document.getElementById('mergeSpeakersModal');
+ const list = document.getElementById('mergeSpeakersList');
+ const executeBtn = document.getElementById('executeMergeBtn');
+
+ // Reset target selection
+ mergeTargetSpeakerId = null;
+ executeBtn.disabled = true;
+
+ // Populate list with clickable cards
+ list.innerHTML = selectedSpeakers.map(s => `
+ <div class="merge-speaker-card flex items-center justify-between px-4 py-3 bg-[var(--bg-tertiary)] hover:bg-[var(--bg-primary)] border-2 border-transparent rounded-lg cursor-pointer transition-all"
+ data-speaker-id="${s.id}">
+ <div class="flex items-center">
+ <i class="fas fa-user text-[var(--text-accent)] mr-3"></i>
+ <span class="text-[var(--text-primary)] font-medium">${escapeHtml(s.name)}</span>
+ </div>
+ <i class="fas fa-check text-green-500 text-lg hidden check-icon"></i>
+ </div>
+ `).join('');
+
+ // Add click handlers to speaker cards
+ list.querySelectorAll('.merge-speaker-card').forEach(card => {
+ card.addEventListener('click', function() {
+ // Remove selection from all cards
+ list.querySelectorAll('.merge-speaker-card').forEach(c => {
+ c.classList.remove('border-green-500', 'bg-[var(--bg-accent)]', 'bg-opacity-10');
+ c.querySelector('.check-icon').classList.add('hidden');
+ });
+
+ // Select this card
+ this.classList.add('border-green-500', 'bg-[var(--bg-accent)]', 'bg-opacity-10');
+ this.querySelector('.check-icon').classList.remove('hidden');
+
+ mergeTargetSpeakerId = parseInt(this.dataset.speakerId);
+ executeBtn.disabled = false;
+ });
+ });
+
+ modal.classList.remove('hidden');
+ }
+
+ // Execute speaker merge
+ async function executeSpeakerMerge() {
+ const targetId = mergeTargetSpeakerId;
+
+ if (!targetId) {
+ showToast('Please select which speaker to keep', 'error');
+ return;
+ }
+
+ const checkboxes = document.querySelectorAll('.speaker-select-checkbox:checked');
+ const allIds = Array.from(checkboxes).map(cb => parseInt(cb.dataset.speakerId));
+ const sourceIds = allIds.filter(id => id !== targetId);
+
+ if (sourceIds.length === 0) {
+ showToast('No source speakers to merge', 'error');
+ return;
+ }
+
+ try {
+ const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
+
+ const response = await fetch('/speakers/merge', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({
+ target_id: targetId,
+ source_ids: sourceIds
+ })
+ });
+
+ const data = await response.json();
+ if (!response.ok) throw new Error(data.error || 'Merge failed');
+
+ showToast(data.message || 'Speakers merged successfully');
+ document.getElementById('mergeSpeakersModal').classList.add('hidden');
+
+ // Reload speakers - reset flag to force reload
+ speakersTabLoaded = false;
+ await loadSpeakersTab();
+ } catch (error) {
+ console.error('Error merging speakers:', error);
+ showToast(`Failed to merge speakers: ${error.message}`, 'error');
+ }
+ }
+
+ // Open delete selected speakers modal
+ function deleteSelectedSpeakers() {
+ const checkboxes = document.querySelectorAll('.speaker-select-checkbox:checked');
+ if (checkboxes.length === 0) {
+ showToast('Please select speakers to delete', 'error');
+ return;
+ }
+
+ const selectedSpeakers = Array.from(checkboxes).map(cb => ({
+ id: parseInt(cb.dataset.speakerId),
+ name: cb.dataset.speakerName
+ }));
+
+ const modal = document.getElementById('deleteSelectedSpeakersModal');
+ const countEl = document.getElementById('deleteSelectedCount');
+ const listEl = document.getElementById('deleteSelectedSpeakersList');
+
+ // Update count
+ countEl.textContent = selectedSpeakers.length;
+
+ // Populate list
+ listEl.innerHTML = selectedSpeakers.map(s => `
+ <div class="flex items-center px-3 py-2 bg-[var(--bg-secondary)] rounded border border-[var(--border-secondary)]">
+ <i class="fas fa-user text-[var(--text-accent)] mr-2"></i>
+ <span class="text-[var(--text-primary)]">${escapeHtml(s.name)}</span>
+ </div>
+ `).join('');
+
+ modal.classList.remove('hidden');
+ }
+
+ // Execute deletion of selected speakers
+ async function executeDeleteSelectedSpeakers() {
+ const checkboxes = document.querySelectorAll('.speaker-select-checkbox:checked');
+ const selectedSpeakers = Array.from(checkboxes).map(cb => ({
+ id: parseInt(cb.dataset.speakerId),
+ name: cb.dataset.speakerName
+ }));
+
+ // Hide modal
+ document.getElementById('deleteSelectedSpeakersModal').classList.add('hidden');
+
+ try{
+ const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
+ const headers = csrfToken ? { 'X-CSRFToken': csrfToken } : {};
+
+ const deletePromises = selectedSpeakers.map(speaker =>
+ fetch(`/speakers/${speaker.id}`, {
method: 'DELETE',
headers: headers
})
);
-
+
const results = await Promise.allSettled(deletePromises);
-
- // Check for any failures
const failures = results.filter(result => result.status === 'rejected');
+
if (failures.length > 0) {
console.error('Some speakers failed to delete:', failures);
showToast(`${failures.length} speaker(s) failed to delete`, 'error');
}
-
- // Reset the tab state
+
+ // Reset and reload
speakersTabLoaded = false;
await loadSpeakersTab();
-
+
const successCount = results.length - failures.length;
if (successCount > 0) {
showToast(`${successCount} speaker(s) deleted successfully`);
}
} catch (error) {
- console.error('Error deleting all speakers:', error);
+ console.error('Error deleting speakers:', error);
showToast(`Failed to delete speakers: ${error.message}`, 'error');
}
- });
-
+ }
+
+ // Open clear voice profiles modal
+ function clearSelectedVoiceProfiles() {
+ const checkboxes = document.querySelectorAll('.speaker-select-checkbox:checked');
+ if (checkboxes.length === 0) {
+ showToast('Please select speakers to clear voice profiles', 'error');
+ return;
+ }
+
+ const selectedSpeakers = Array.from(checkboxes).map(cb => ({
+ id: parseInt(cb.dataset.speakerId),
+ name: cb.dataset.speakerName
+ }));
+
+ const modal = document.getElementById('clearVoiceProfilesModal');
+ const countEl = document.getElementById('clearVoiceProfilesCount');
+ const listEl = document.getElementById('clearVoiceProfilesList');
+
+ // Update count
+ countEl.textContent = selectedSpeakers.length;
+
+ // Populate list
+ listEl.innerHTML = selectedSpeakers.map(s => `
+ <div class="flex items-center px-3 py-2 bg-[var(--bg-secondary)] rounded border border-[var(--border-secondary)]">
+ <i class="fas fa-user text-[var(--text-accent)] mr-2"></i>
+ <span class="text-[var(--text-primary)]">${escapeHtml(s.name)}</span>
+ </div>
+ `).join('');
+
+ modal.classList.remove('hidden');
+ }
+
+ // Execute clearing voice profiles
+ async function executeClearVoiceProfiles() {
+ const checkboxes = document.querySelectorAll('.speaker-select-checkbox:checked');
+ const selectedSpeakers = Array.from(checkboxes).map(cb => ({
+ id: parseInt(cb.dataset.speakerId),
+ name: cb.dataset.speakerName
+ }));
+
+ // Hide modal
+ document.getElementById('clearVoiceProfilesModal').classList.add('hidden');
+
+ try {
+ const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
+
+ const clearPromises = selectedSpeakers.map(speaker =>
+ fetch(`/speakers/${speaker.id}/clear_embeddings`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ }
+ })
+ );
+
+ const results = await Promise.allSettled(clearPromises);
+ const failures = results.filter(result => result.status === 'rejected');
+
+ if (failures.length > 0) {
+ console.error('Some voice profiles failed to clear:', failures);
+ showToast(`${failures.length} voice profile(s) failed to clear`, 'error');
+ }
+
+ // Reset and reload
+ speakersTabLoaded = false;
+ await loadSpeakersTab();
+
+ const successCount = results.length - failures.length;
+ if (successCount > 0) {
+ showToast(`${successCount} voice profile(s) cleared successfully`);
+ }
+ } catch (error) {
+ console.error('Error clearing voice profiles:', error);
+ showToast(`Failed to clear voice profiles: ${error.message}`, 'error');
+ }
+ }
+
async function loadSystemInfo() {
try {
const response = await fetch('/api/system/info');
@@ -1670,8 +2744,11 @@
<span class="ml-2">${t('sharedTranscripts.shareNotes')}</span>
</label>
</div>
- <div class="mt-4">
- <input value="{{ request.url_root }}share/${share.public_id}" readonly class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg text-sm">
+ <div class="mt-4 relative">
+ <input value="{{ request.url_root }}share/${share.public_id}" readonly class="share-link-input w-full px-3 py-2 pr-12 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[var(--border-accent)]">
+ <button class="copy-share-link-btn absolute right-1.5 top-1/2 -translate-y-1/2 w-7 h-7 flex items-center justify-center rounded bg-[var(--bg-button)] text-[var(--text-button)] hover:bg-[var(--bg-button-hover)] transition-colors" title="${t('buttons.copy')}">
+ <i class="fas fa-copy text-xs"></i>
+ </button>
</div>
`;
sharesContainer.appendChild(shareEl);
@@ -1683,6 +2760,32 @@
document.querySelectorAll('.share-checkbox').forEach(box => {
box.addEventListener('change', handleUpdateShare);
});
+ document.querySelectorAll('.copy-share-link-btn').forEach(btn => {
+ btn.addEventListener('click', function(e) {
+ const button = e.currentTarget;
+ const input = button.previousElementSibling;
+
+ navigator.clipboard.writeText(input.value).then(() => {
+ const icon = button.querySelector('i');
+
+ // Change to success state
+ icon.className = 'fas fa-check text-xs';
+ button.style.transition = 'background-color 0.2s ease';
+ button.style.backgroundColor = 'var(--bg-success, #10b981)';
+
+ // Revert after delay
+ setTimeout(() => {
+ button.style.backgroundColor = '';
+ icon.className = 'fas fa-copy text-xs';
+ setTimeout(() => {
+ button.style.transition = '';
+ }, 200);
+ }, 1500);
+ }).catch(err => {
+ console.error('Failed to copy:', err);
+ });
+ });
+ });
} catch (error) {
sharesContainer.innerHTML = `<p class="text-center text-red-500">${t('errors.loadingShares')}: ${error.message}</p>`;
@@ -2104,31 +3207,43 @@
// Create toast element
const toast = document.createElement('div');
toast.className = `fixed top-4 right-4 z-50 px-4 py-2 rounded-lg shadow-lg transition-all duration-300 transform translate-x-full ${
- type === 'error'
- ? 'bg-[var(--bg-danger)] text-[var(--text-button)]'
+ type === 'error'
+ ? 'bg-[var(--bg-danger)] text-[var(--text-button)]'
: 'bg-[var(--bg-success-light)] text-[var(--text-success-strong)]'
}`;
+ toast.style.cursor = 'pointer';
toast.innerHTML = `
<div class="flex items-center">
<i class="fas ${type === 'error' ? 'fa-exclamation-circle' : 'fa-check-circle'} mr-2"></i>
<span>${escapeHtml(message)}</span>
</div>
`;
-
+
document.body.appendChild(toast);
-
+
// Animate in
setTimeout(() => {
toast.classList.remove('translate-x-full');
}, 10);
-
- // Animate out and remove
- setTimeout(() => {
+
+ // Function to dismiss the toast
+ const dismissToast = () => {
toast.classList.add('translate-x-full');
setTimeout(() => {
- document.body.removeChild(toast);
+ if (toast.parentNode) {
+ document.body.removeChild(toast);
+ }
}, 300);
- }, 3000);
+ };
+
+ // Add click handler to dismiss toast
+ toast.addEventListener('click', () => {
+ clearTimeout(timeoutId);
+ dismissToast();
+ });
+
+ // Auto-dismiss after 3 seconds
+ const timeoutId = setTimeout(dismissToast, 3000);
}
// ===== TAG MANAGEMENT FUNCTIONALITY =====
@@ -2151,6 +3266,98 @@
let tags = [];
let isEditingTag = false;
+ // Groups where current user is admin (passed from backend)
+ let userAdminGroups = {{ user_admin_groups | tojson }};
+ console.log('User admin groups:', userAdminGroups);
+
+ // Update visibility of group selection based on whether user is admin of any groups
+ function updateGroupSelectionVisibility() {
+ const groupSelectionSection = document.getElementById('tagGroupSelectionSection');
+ if (groupSelectionSection) {
+ const isInternalSharingEnabled = {{ 'true' if enable_internal_sharing else 'false' }};
+ if (isInternalSharingEnabled && userAdminGroups.length > 0) {
+ groupSelectionSection.classList.remove('hidden');
+ populateGroupDropdown();
+ } else {
+ groupSelectionSection.classList.add('hidden');
+ }
+ }
+ }
+
+ // Populate the group dropdown with groups where user is admin
+ function populateGroupDropdown() {
+ const groupSelect = document.getElementById('tagGroupId');
+ if (!groupSelect) return;
+
+ // Clear existing options except the first one
+ while (groupSelect.options.length > 1) {
+ groupSelect.remove(1);
+ }
+
+ // Add group options
+ userAdminGroups.forEach(group => {
+ const option = document.createElement('option');
+ option.value = group.id;
+ option.textContent = group.name;
+ groupSelect.appendChild(option);
+ });
+ }
+
+ // Toggle group settings section based on selection
+ function toggleGroupSettings() {
+ const groupSelect = document.getElementById('tagGroupId');
+ const groupSettingsSection = document.getElementById('tagGroupSettingsSection');
+
+ if (groupSelect && groupSettingsSection) {
+ if (groupSelect.value) {
+ groupSettingsSection.classList.remove('hidden');
+ } else {
+ groupSettingsSection.classList.add('hidden');
+ }
+ }
+ }
+
+ // Add event listener for group selection changes
+ const tagGroupSelect = document.getElementById('tagGroupId');
+ if (tagGroupSelect) {
+ tagGroupSelect.addEventListener('change', toggleGroupSettings);
+ }
+
+ // Add event listener for protect from deletion checkbox
+ const tagProtectCheckbox = document.getElementById('tagProtectFromDeletion');
+ const tagRetentionDaysInput = document.getElementById('tagRetentionDays');
+
+ if (tagProtectCheckbox && tagRetentionDaysInput) {
+ tagProtectCheckbox.addEventListener('change', function() {
+ if (this.checked) {
+ // When protect is enabled, disable retention field and set to -1
+ tagRetentionDaysInput.value = '';
+ tagRetentionDaysInput.disabled = true;
+ tagRetentionDaysInput.classList.add('opacity-50', 'cursor-not-allowed');
+ tagRetentionDaysInput.placeholder = 'Infinite retention (protected)';
+ } else {
+ // When protect is disabled, re-enable retention field
+ tagRetentionDaysInput.disabled = false;
+ tagRetentionDaysInput.classList.remove('opacity-50', 'cursor-not-allowed');
+ tagRetentionDaysInput.placeholder = 'Leave empty to use global retention';
+ }
+ });
+ }
+
+ // Check if auto-deletion is enabled and show/hide the retention section
+ function checkAutoDeletionEnabled() {
+ const isAutoDeletionEnabled = {{ 'true' if enable_auto_deletion else 'false' }};
+ const retentionSection = document.getElementById('tagRetentionSection');
+
+ if (retentionSection && isAutoDeletionEnabled) {
+ retentionSection.classList.remove('hidden');
+ }
+ }
+
+ // Initialize visibility based on user's admin groups
+ updateGroupSelectionVisibility();
+ checkAutoDeletionEnabled();
+
// Load tags from API
async function loadTags() {
showTagsLoadingState();
@@ -2214,54 +3421,133 @@
// Create tag card element
function createTagCard(tag) {
const div = document.createElement('div');
- div.className = 'bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] hover:shadow-md transition-shadow duration-200';
-
+ const isGroupTag = tag.group_id !== null && tag.group_id !== undefined;
+ const canEdit = tag.can_edit !== undefined ? tag.can_edit : true;
+
+ div.className = `bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-primary)] hover:shadow-md transition-shadow duration-200 overflow-hidden`;
+
+ // Build metadata badges
+ const metadata = [];
+
+ // Protection/Retention badge
+ if (tag.protect_from_deletion || tag.retention_days === -1) {
+ metadata.push(`<span class="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium" style="background-color: #f59e0b; color: white;" title="Protected with infinite retention">
+ <i class="fas fa-shield-alt"></i>
+ <span>∞</span>
+ </span>`);
+ } else if (tag.retention_days && tag.retention_days > 0) {
+ metadata.push(`<span class="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium" style="background-color: #2563eb; color: white;" title="Retention: ${tag.retention_days} days">
+ <i class="fas fa-clock"></i>
+ <span>${tag.retention_days}d</span>
+ </span>`);
+ }
+
+ // Sharing badge for group tags
+ if (isGroupTag) {
+ const shareIcon = tag.auto_share_on_apply ? 'user-friends' : (tag.share_with_group_lead ? 'user-tie' : 'user-lock');
+ const shareText = tag.auto_share_on_apply ? 'All members' : (tag.share_with_group_lead ? 'Admins only' : 'Manual');
+ const shareTooltip = tag.auto_share_on_apply ? 'Auto-shares with all group members' : (tag.share_with_group_lead ? 'Shares with group admins only' : 'Manual sharing only');
+ metadata.push(`<span class="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium" style="background-color: #9333ea; color: white;" title="${shareTooltip}">
+ <i class="fas fa-${shareIcon}"></i>
+ <span>${shareText}</span>
+ </span>`);
+ }
+
+ // ASR defaults badges
+ if (tag.default_language) {
+ metadata.push(`<span class="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium" style="background-color: #16a34a; color: white;" title="Language: ${escapeHtml(tag.default_language)}">
+ <i class="fas fa-language"></i>
+ <span>${escapeHtml(tag.default_language).toUpperCase()}</span>
+ </span>`);
+ }
+ if (tag.default_min_speakers || tag.default_max_speakers) {
+ const min = tag.default_min_speakers || '?';
+ const max = tag.default_max_speakers || '?';
+ metadata.push(`<span class="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium" style="background-color: #0d9488; color: white;" title="Speaker range: ${min}-${max}">
+ <i class="fas fa-users"></i>
+ <span>${min}-${max}</span>
+ </span>`);
+ }
+
+ // Custom prompt indicator
+ const hasPrompt = tag.custom_prompt && tag.custom_prompt.trim().length > 0;
+
div.innerHTML = `
- <div class="flex items-start justify-between mb-3">
- <div class="flex items-center">
- <div class="w-4 h-4 rounded-full mr-3" style="background-color: ${escapeHtml(tag.color)}"></div>
- <h3 class="font-semibold text-[var(--text-primary)]">${escapeHtml(tag.name)}</h3>
+ <!-- Header with color indicator and name -->
+ <div class="flex items-center justify-between gap-2 px-3 py-2 bg-[var(--bg-secondary)] border-b border-[var(--border-primary)]">
+ <div class="flex items-center gap-2 flex-1 min-w-0">
+ ${isGroupTag
+ ? `<i class="fas fa-users flex-shrink-0 text-sm" style="color: ${escapeHtml(tag.color)}"></i>`
+ : `<div class="w-3 h-3 rounded-full flex-shrink-0 border border-white/20" style="background-color: ${escapeHtml(tag.color)}"></div>`
+ }
+ <h3 class="font-semibold text-sm text-[var(--text-primary)] truncate" title="${escapeHtml(tag.name)}">
+ ${isGroupTag ? `<span class="text-xs opacity-60">${escapeHtml(tag.group_name || 'Group')}:</span> ` : ''}${escapeHtml(tag.name)}
+ </h3>
</div>
- <div class="flex space-x-1">
- <button class="edit-tag-btn p-1 text-[var(--text-muted)] hover:text-[var(--text-accent)] rounded"
- data-tag-id="${tag.id}" data-i18n-title="buttons.editTag">
- <i class="fas fa-edit text-sm"></i>
- </button>
- <button class="delete-tag-btn p-1 text-[var(--text-muted)] hover:text-[var(--text-danger)] rounded"
- data-tag-id="${tag.id}" data-i18n-title="buttons.deleteTag">
- <i class="fas fa-trash text-sm"></i>
- </button>
+ <div class="flex items-center gap-1 flex-shrink-0">
+ ${!canEdit ? `
+ <span class="px-1.5 py-0.5 text-[10px] text-[var(--text-muted)] bg-[var(--bg-secondary)] rounded border border-[var(--border-secondary)]" title="Team tag - cannot edit">
+ <i class="fas fa-lock"></i>
+ </span>
+ ` : ''}
+ ${canEdit ? `
+ <button class="edit-tag-btn p-1 text-[var(--text-muted)] hover:text-[var(--text-accent)] transition-colors rounded" data-tag-id="${tag.id}" title="Edit tag">
+ <i class="fas fa-edit text-xs"></i>
+ </button>
+ <button class="delete-tag-btn p-1 text-[var(--text-muted)] hover:text-red-500 transition-colors rounded" data-tag-id="${tag.id}" title="Delete tag">
+ <i class="fas fa-trash text-xs"></i>
+ </button>
+ ` : ''}
</div>
</div>
-
- <div class="space-y-2 text-sm text-[var(--text-muted)]">
- ${tag.custom_prompt ? `
- <div>
- <span class="font-medium">${t('tagManagement.customPrompt')}:</span>
- <span class="text-xs">${escapeHtml(tag.custom_prompt.substring(0, 60))}${tag.custom_prompt.length > 60 ? '...' : ''}</span>
- </div>
- ` : ''}
-
- ${tag.default_language || tag.default_min_speakers || tag.default_max_speakers ? `
- <div class="pt-2 border-t border-[var(--border-secondary)]">
- <span class="font-medium text-xs">${t('tagManagement.asrDefaults')}:</span>
- <div class="flex flex-wrap gap-2 mt-1">
- ${tag.default_language ? `<span class="inline-flex items-center px-2 py-1 rounded-full text-xs bg-[var(--bg-accent)] text-[var(--text-accent)]">${t('form.language')}: ${escapeHtml(tag.default_language)}</span>` : ''}
- ${tag.default_min_speakers ? `<span class="inline-flex items-center px-2 py-1 rounded-full text-xs bg-[var(--bg-accent)] text-[var(--text-accent)]">${t('tagManagement.minSpeakers')}: ${tag.default_min_speakers}</span>` : ''}
- ${tag.default_max_speakers ? `<span class="inline-flex items-center px-2 py-1 rounded-full text-xs bg-[var(--bg-accent)] text-[var(--text-accent)]">${t('tagManagement.maxSpeakers')}: ${tag.default_max_speakers}</span>` : ''}
+
+ <!-- Metadata badges -->
+ ${metadata.length > 0 ? `
+ <div class="px-3 py-2 flex flex-wrap gap-1.5">
+ ${metadata.join('')}
+ </div>
+ ` : ''}
+
+ <!-- Custom prompt section (collapsible) -->
+ ${hasPrompt ? `
+ <div class="border-t border-[var(--border-primary)]">
+ <button class="toggle-prompt-btn w-full px-3 py-2 flex items-center justify-between text-left hover:bg-[var(--bg-secondary)] transition-colors group" data-tag-id="${tag.id}">
+ <span class="text-xs font-medium text-[var(--text-secondary)] flex items-center gap-1.5">
+ <i class="fas fa-message-lines text-[10px]"></i>
+ Custom Prompt
+ </span>
+ <i class="fas fa-chevron-down text-[10px] text-[var(--text-muted)] transition-transform group-hover:text-[var(--text-secondary)]"></i>
+ </button>
+ <div class="prompt-content hidden px-3 pb-2">
+ <div class="text-xs text-[var(--text-muted)] bg-[var(--bg-secondary)] rounded p-2 max-h-24 overflow-y-auto custom-scrollbar border border-[var(--border-secondary)]">
+ ${escapeHtml(tag.custom_prompt)}
</div>
</div>
- ` : ''}
- </div>
+ </div>
+ ` : ''}
`;
-
+
// Add event listeners
const editBtn = div.querySelector('.edit-tag-btn');
const deleteBtn = div.querySelector('.delete-tag-btn');
-
- editBtn.addEventListener('click', () => editTag(tag));
- deleteBtn.addEventListener('click', () => deleteTag(tag.id, tag.name));
-
+ const toggleBtn = div.querySelector('.toggle-prompt-btn');
+
+ if (editBtn) {
+ editBtn.addEventListener('click', () => editTag(tag));
+ }
+ if (deleteBtn) {
+ deleteBtn.addEventListener('click', () => deleteTag(tag.id, tag.name));
+ }
+ if (toggleBtn) {
+ toggleBtn.addEventListener('click', function(e) {
+ e.preventDefault();
+ const content = this.nextElementSibling;
+ const icon = this.querySelector('.fa-chevron-down');
+ content.classList.toggle('hidden');
+ icon.style.transform = content.classList.contains('hidden') ? 'rotate(0deg)' : 'rotate(180deg)';
+ });
+ }
+
return div;
}
@@ -2295,13 +3581,79 @@
isEditingTag = true;
tagModalTitle.textContent = 'Edit Tag';
saveTagBtn.innerHTML = '<i class="fas fa-save mr-2"></i> Update Tag';
-
+
// Populate form
document.getElementById('tagId').value = tag.id;
document.getElementById('tagName').value = tag.name;
document.getElementById('tagColor').value = tag.color;
document.getElementById('tagCustomPrompt').value = tag.custom_prompt || '';
-
+
+ // Populate group selection
+ const groupIdSelect = document.getElementById('tagGroupId');
+ const groupSelectionSection = document.getElementById('tagGroupSelectionSection');
+ const isInternalSharingEnabled = {{ 'true' if enable_internal_sharing else 'false' }};
+
+ if (groupIdSelect && isInternalSharingEnabled) {
+ // If this tag has a group_id, force show the group selection section
+ if (tag.group_id) {
+ groupSelectionSection?.classList.remove('hidden');
+
+ // Ensure the current group is in the dropdown (in case async load hasn't finished)
+ if (tag.group_name) {
+ // Check if option already exists
+ const existingOption = Array.from(groupIdSelect.options).find(opt => opt.value == tag.group_id);
+ if (!existingOption) {
+ // Add the current group as an option
+ const option = document.createElement('option');
+ option.value = tag.group_id;
+ option.textContent = tag.group_name;
+ groupIdSelect.appendChild(option);
+ }
+ }
+ }
+
+ groupIdSelect.value = tag.group_id || '';
+ toggleGroupSettings();
+ }
+
+ // Populate group-specific settings
+ if (document.getElementById('tagAutoShareOnApply')) {
+ document.getElementById('tagAutoShareOnApply').checked = tag.auto_share_on_apply !== undefined ? tag.auto_share_on_apply : true;
+ }
+ if (document.getElementById('tagShareWithGroupLead')) {
+ document.getElementById('tagShareWithGroupLead').checked = tag.share_with_group_lead !== undefined ? tag.share_with_group_lead : true;
+ }
+
+ // Populate retention settings
+ // If retention_days is -1, it means protected from deletion
+ const retentionDaysInput = document.getElementById('tagRetentionDays');
+ const protectCheckbox = document.getElementById('tagProtectFromDeletion');
+
+ if (tag.retention_days === -1 || tag.protect_from_deletion) {
+ // Protected from deletion
+ if (protectCheckbox) {
+ protectCheckbox.checked = true;
+ }
+ if (retentionDaysInput) {
+ retentionDaysInput.value = '';
+ retentionDaysInput.disabled = true;
+ retentionDaysInput.classList.add('opacity-50', 'cursor-not-allowed');
+ retentionDaysInput.placeholder = 'Infinite retention (protected)';
+ }
+ } else {
+ // Not protected
+ if (protectCheckbox) {
+ protectCheckbox.checked = false;
+ }
+ if (retentionDaysInput) {
+ retentionDaysInput.value = tag.retention_days || '';
+ retentionDaysInput.disabled = false;
+ retentionDaysInput.classList.remove('opacity-50', 'cursor-not-allowed');
+ retentionDaysInput.placeholder = 'Leave empty to use global retention';
+ }
+ }
+
+ // Populate ASR settings
if (document.getElementById('tagLanguage')) {
document.getElementById('tagLanguage').value = tag.default_language || '';
}
@@ -2318,8 +3670,36 @@
saveTagBtn.innerHTML = '<i class="fas fa-save mr-2"></i> Save Tag';
tagForm.reset();
document.getElementById('tagColor').value = '#3B82F6';
+
+ // Reset group selection
+ if (document.getElementById('tagGroupId')) {
+ document.getElementById('tagGroupId').value = '';
+ toggleGroupSettings();
+ }
+
+ // Set default values for group settings
+ if (document.getElementById('tagAutoShareOnApply')) {
+ document.getElementById('tagAutoShareOnApply').checked = true;
+ }
+ if (document.getElementById('tagShareWithGroupLead')) {
+ document.getElementById('tagShareWithGroupLead').checked = true;
+ }
+
+ // Clear retention settings and ensure field is enabled
+ const retentionInput = document.getElementById('tagRetentionDays');
+ const protectCheck = document.getElementById('tagProtectFromDeletion');
+
+ if (retentionInput) {
+ retentionInput.value = '';
+ retentionInput.disabled = false;
+ retentionInput.classList.remove('opacity-50', 'cursor-not-allowed');
+ retentionInput.placeholder = 'Leave empty to use global retention';
+ }
+ if (protectCheck) {
+ protectCheck.checked = false;
+ }
}
-
+
tagModal.classList.remove('hidden');
}
@@ -2365,16 +3745,39 @@
// Save tag form submission
tagForm.addEventListener('submit', async (e) => {
e.preventDefault();
-
+
const formData = new FormData(tagForm);
+
+ // Determine retention_days: -1 if protected, otherwise use the input value
+ const isProtected = document.getElementById('tagProtectFromDeletion')?.checked || false;
+ let retentionDays = null;
+
+ if (isProtected) {
+ retentionDays = -1; // -1 means protected/infinite retention
+ } else {
+ const retentionInput = formData.get('retention_days');
+ retentionDays = retentionInput ? parseInt(retentionInput) : null;
+ }
+
const tagData = {
name: formData.get('name'),
color: formData.get('color'),
custom_prompt: formData.get('custom_prompt') || null,
default_language: formData.get('default_language') || null,
default_min_speakers: formData.get('default_min_speakers') ? parseInt(formData.get('default_min_speakers')) : null,
- default_max_speakers: formData.get('default_max_speakers') ? parseInt(formData.get('default_max_speakers')) : null
+ default_max_speakers: formData.get('default_max_speakers') ? parseInt(formData.get('default_max_speakers')) : null,
+ retention_days: retentionDays
};
+
+ // Add group-related fields
+ const groupId = formData.get('group_id');
+ if (groupId) {
+ tagData.group_id = parseInt(groupId);
+ tagData.auto_share_on_apply = document.getElementById('tagAutoShareOnApply')?.checked || false;
+ tagData.share_with_group_lead = document.getElementById('tagShareWithGroupLead')?.checked || false;
+ } else {
+ tagData.group_id = null;
+ }
try {
const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
@@ -2767,17 +4170,30 @@
function showToast(message, type = 'info') {
// Simple toast notification
const toast = document.createElement('div');
- toast.className = `fixed bottom-4 right-4 px-4 py-2 rounded-md text-white z-50 ${
+ toast.className = `fixed top-4 right-4 px-4 py-2 rounded-md text-white z-50 ${
type === 'success' ? 'bg-green-600' :
type === 'error' ? 'bg-red-600' :
'bg-blue-600'
}`;
+ toast.style.cursor = 'pointer';
toast.textContent = message;
document.body.appendChild(toast);
- setTimeout(() => {
- toast.remove();
- }, 3000);
+ // Function to dismiss the toast
+ const dismissToast = () => {
+ if (toast.parentNode) {
+ toast.remove();
+ }
+ };
+
+ // Add click handler to dismiss toast
+ toast.addEventListener('click', () => {
+ clearTimeout(timeoutId);
+ dismissToast();
+ });
+
+ // Auto-dismiss after 3 seconds
+ const timeoutId = setTimeout(dismissToast, 3000);
}
});
</script>
diff --git a/templates/admin.html b/templates/admin.html
index 5e369279..2ff90085 100644
--- a/templates/admin.html
+++ b/templates/admin.html
@@ -4,7 +4,8 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="csrf-token" content="{{ csrf_token() }}">
- <title>Admin Dashboard - Speakr</title>
+ <meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
+ <title>{% if is_group_admin_only %}Group Management{% else %}Admin Dashboard{% endif %} - Speakr</title>
<!-- Loading overlay to prevent FOUC - MUST be first -->
{% include 'includes/loading_overlay.html' %}
@@ -18,7 +19,6 @@
<link rel="stylesheet" href="{{ url_for('static', filename='vendor/css/fontawesome.min.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
<script src="{{ url_for('static', filename='js/i18n.js') }}"></script>
- <script src="{{ url_for('static', filename='js/loading.js') }}"></script>
<style>
/* Hide Vue content until compiled */
[v-cloak] {
@@ -33,6 +33,22 @@
.scrollbar-hide::-webkit-scrollbar {
display: none;
}
+
+ /* Custom select dropdown styling */
+ select {
+ appearance: none;
+ -webkit-appearance: none;
+ -moz-appearance: none;
+ padding-right: 2.5rem !important;
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23666' d='M6 9L1 4h10z'/%3E%3C/svg%3E");
+ background-repeat: no-repeat;
+ background-position: right 0.75rem center;
+ background-size: 12px 12px;
+ }
+
+ .dark select {
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23aaa' d='M6 9L1 4h10z'/%3E%3C/svg%3E");
+ }
</style>
<script>
// Initialize i18n
@@ -100,7 +116,7 @@
<div id="app" v-cloak class="container mx-auto px-4 sm:px-6 lg:px-8 py-6 flex flex-col min-h-screen">
<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">
+ <a href="{{ url_for('recordings.index') }}" class="flex items-center">
<img src="{{ url_for('static', filename='img/icon-192x192.png') }}" alt="Speakr Logo" class="h-9 w-9 mr-2">
Speakr
</a>
@@ -111,21 +127,22 @@
</button>
<div class="relative">
<button @click="isUserMenuOpen = !isUserMenuOpen" class="flex items-center px-3 py-2 border border-[var(--border-secondary)] rounded-lg text-[var(--text-secondary)] hover:text-[var(--text-accent)] focus:outline-none">
- <i class="fas fa-user-shield mr-2"></i>
+ <i :class="isTeamAdminOnly ? 'fas fa-users-cog mr-2' : 'fas fa-user-shield mr-2'"></i>
<span>{{ current_user.username }}</span>
<i class="fas fa-chevron-down ml-2"></i>
</button>
<div v-if="isUserMenuOpen" class="absolute right-0 mt-2 w-48 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg shadow-lg z-10">
- <a href="{{ url_for('index') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)]">
+ <a href="{{ url_for('recordings.index') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)]">
<i class="fas fa-home mr-2"></i> ${t('nav.home')}
</a>
- <a href="{{ url_for('account') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)]">
+ <a href="{{ url_for('auth.account') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)]">
<i class="fas fa-user mr-2"></i> ${t('nav.account')}
</a>
- <a href="{{ url_for('admin') }}" class="block px-4 py-2 text-[var(--text-accent)] bg-[var(--bg-accent)]">
- <i class="fas fa-user-shield mr-2"></i> ${t('nav.admin')}
+ <a href="{{ url_for('admin.admin') }}" class="block px-4 py-2 text-[var(--text-accent)] bg-[var(--bg-accent)]">
+ <i :class="isTeamAdminOnly ? 'fas fa-users-cog mr-2' : 'fas fa-user-shield mr-2'"></i>
+ <span v-text="isTeamAdminOnly ? t('nav.groupManagement') : t('nav.admin')"></span>
</a>
- <a href="{{ url_for('logout') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-danger)]">
+ <a href="{{ url_for('auth.logout') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-danger)]">
<i class="fas fa-sign-out-alt mr-2"></i> ${t('nav.signOut')}
</a>
</div>
@@ -135,7 +152,7 @@
<main class="flex-grow">
<div class="bg-[var(--bg-secondary)] p-4 sm:p-6 lg:p-8 rounded-xl shadow-lg border border-[var(--border-primary)]">
- <h2 class="text-2xl font-semibold text-[var(--text-primary)] mb-6">Admin Dashboard</h2>
+ <h2 class="text-2xl font-semibold text-[var(--text-primary)] mb-6" v-text="isTeamAdminOnly ? t('nav.groupManagement') : t('nav.adminDashboard')"></h2>
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
@@ -159,30 +176,34 @@
</div>
<nav class="tab-nav px-1 sm:px-4 lg:px-6 pt-3 sm:pt-4 lg:pt-6 pb-4 sm:pb-6 -mb-px overflow-x-auto scrollbar-hide" aria-label="Tabs" id="admin-tabs-container">
<div class="inline-flex gap-1 sm:gap-2">
- <button @click="activeTab = 'users'"
+ <button v-if="!isTeamAdminOnly" @click="activeTab = 'users'"
:class="activeTab === 'users' ? 'border-[var(--border-accent)] text-[var(--text-accent)]' : 'border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)]'"
class="inline-flex items-center whitespace-nowrap py-1 px-1.5 sm:py-3 sm:px-3 border-b-2 font-medium text-xs sm:text-sm rounded-t-md sm:rounded-t-lg hover:bg-[var(--bg-tertiary)]">
<i class="fas fa-users mr-0.5 sm:mr-2 text-xs sm:text-sm"></i><span>${t('adminDashboard.userManagement')}</span>
</button>
- <button @click="activeTab = 'stats'"
+ <button v-if="!isTeamAdminOnly" @click="activeTab = 'stats'"
:class="activeTab === 'stats' ? 'border-[var(--border-accent)] text-[var(--text-accent)]' : 'border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)]'"
class="inline-flex items-center whitespace-nowrap py-1 px-1.5 sm:py-3 sm:px-3 border-b-2 font-medium text-xs sm:text-sm rounded-t-md sm:rounded-t-lg hover:bg-[var(--bg-tertiary)]">
<i class="fas fa-chart-bar mr-0.5 sm:mr-2 text-xs sm:text-sm"></i><span>${t('adminDashboard.systemStatistics')}</span>
</button>
- <button @click="activeTab = 'settings'"
+ <button v-if="!isTeamAdminOnly" @click="activeTab = 'settings'"
:class="activeTab === 'settings' ? 'border-[var(--border-accent)] text-[var(--text-accent)]' : 'border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)]'"
class="inline-flex items-center whitespace-nowrap py-1 px-1.5 sm:py-3 sm:px-3 border-b-2 font-medium text-xs sm:text-sm rounded-t-md sm:rounded-t-lg hover:bg-[var(--bg-tertiary)]">
<i class="fas fa-cogs mr-0.5 sm:mr-2 text-xs sm:text-sm"></i><span>${t('adminDashboard.systemSettings')}</span>
</button>
- <button @click="activeTab = 'prompts'"
+ <button v-if="!isTeamAdminOnly" @click="activeTab = 'prompts'"
:class="activeTab === 'prompts' ? 'border-[var(--border-accent)] text-[var(--text-accent)]' : 'border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)]'"
class="inline-flex items-center whitespace-nowrap py-1 px-1.5 sm:py-3 sm:px-3 border-b-2 font-medium text-xs sm:text-sm rounded-t-md sm:rounded-t-lg hover:bg-[var(--bg-tertiary)]">
<i class="fas fa-file-alt mr-0.5 sm:mr-2 text-xs sm:text-sm"></i><span>${t('adminDashboard.defaultPrompts')}</span>
</button>
- <button @click="activeTab = 'vectorstore'"
+ <button @click="activeTab = 'groups'"
+ :class="activeTab === 'groups' ? 'border-[var(--border-accent)] text-[var(--text-accent)]' : 'border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)]'"
+ class="inline-flex items-center whitespace-nowrap py-1 px-1.5 sm:py-3 sm:px-3 border-b-2 font-medium text-xs sm:text-sm rounded-t-md sm:rounded-t-lg hover:bg-[var(--bg-tertiary)]">
+ <i class="fas fa-users-cog mr-0.5 sm:mr-2 text-xs sm:text-sm"></i><span>Groups</span>
+ </button>
+ <button v-if="!isTeamAdminOnly && inquireModeEnabled" @click="activeTab = 'vectorstore'"
:class="activeTab === 'vectorstore' ? 'border-[var(--border-accent)] text-[var(--text-accent)]' : 'border-transparent text-[var(--text-muted)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)]'"
- class="inline-flex items-center whitespace-nowrap py-1 px-1.5 sm:py-3 sm:px-3 border-b-2 font-medium text-xs sm:text-sm rounded-t-md sm:rounded-t-lg hover:bg-[var(--bg-tertiary)]"
- v-if="inquireModeEnabled">
+ class="inline-flex items-center whitespace-nowrap py-1 px-1.5 sm:py-3 sm:px-3 border-b-2 font-medium text-xs sm:text-sm rounded-t-md sm:rounded-t-lg hover:bg-[var(--bg-tertiary)]">
<i class="fas fa-database mr-0.5 sm:mr-2 text-xs sm:text-sm"></i><span>${t('adminDashboard.vectorStore')}</span>
</button>
</div>
@@ -218,6 +239,7 @@
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">${t('adminDashboard.username')}</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">${t('adminDashboard.email')}</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">${t('adminDashboard.admin')}</th>
+ <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">Public Share</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">${t('adminDashboard.recordings')}</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">${t('adminDashboard.storageUsed')}</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">${t('adminDashboard.actions')}</th>
@@ -229,8 +251,20 @@
<td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-[var(--text-primary)]">${ user.username }</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">${ user.email }</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">
- <span v-if="user.is_admin" class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-[var(--bg-success-light)] text-[var(--text-success-strong)]">Yes</span>
- <span v-else class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-[var(--bg-pending-light)] text-[var(--text-pending-strong)]">No</span>
+ <span v-if="user.is_admin" class="px-2 inline-flex items-center text-xs leading-5 font-semibold rounded-full bg-[var(--bg-success-light)] text-[var(--text-success-strong)]">Yes</span>
+ <span v-else class="px-2 inline-flex items-center text-xs leading-5 font-semibold rounded-full bg-[var(--bg-pending-light)] text-[var(--text-pending-strong)]">No</span>
+ </td>
+ <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">
+ <button @click="togglePublicSharingPermission(user)"
+ class="inline-flex items-center"
+ :title="user.can_share_publicly ? 'Revoke public sharing permission' : 'Grant public sharing permission'">
+ <span v-if="user.can_share_publicly" class="px-2 inline-flex items-center text-xs leading-5 font-semibold rounded-full bg-[var(--bg-success-light)] text-[var(--text-success-strong)]">
+ <i class="fas fa-check mr-1"></i> Allowed
+ </span>
+ <span v-else class="px-2 inline-flex items-center text-xs leading-5 font-semibold rounded-full bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)]">
+ <i class="fas fa-times mr-1"></i> Blocked
+ </span>
+ </button>
</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">${ user.recordings_count }</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">${ formatFileSize(user.storage_used) }</td>
@@ -249,7 +283,7 @@
</td>
</tr>
<tr v-if="filteredUsers.length === 0">
- <td colspan="7" class="px-6 py-4 text-center text-sm text-[var(--text-muted)]">
+ <td colspan="8" class="px-6 py-4 text-center text-sm text-[var(--text-muted)]">
<div v-if="isLoadingUsers">
<i class="fas fa-spinner fa-spin mr-2"></i> Loading users...
</div>
@@ -719,13 +753,80 @@ Summarization Instructions:
</div>
</div>
</div>
+
+ <!-- Groups Tab -->
+ <div v-show="activeTab === 'groups'">
+ <div class="flex justify-between items-center mb-4">
+ <h3 class="text-lg font-medium text-[var(--text-secondary)]">Group Management</h3>
+ <button v-if="!isTeamAdminOnly" @click="openCreateTeamModal" 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-plus mr-2"></i> Create Group
+ </button>
+ </div>
+
+ <!-- Groups List -->
+ <div class="bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] overflow-hidden">
+ <div v-if="groups.length > 0">
+ <table class="min-w-full divide-y divide-[var(--border-primary)]">
+ <thead class="bg-[var(--bg-tertiary)]">
+ <tr>
+ <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">Group Name</th>
+ <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">Description</th>
+ <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">Members</th>
+ <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">Created</th>
+ <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">Actions</th>
+ </tr>
+ </thead>
+ <tbody class="bg-[var(--bg-secondary)] divide-y divide-[var(--border-primary)]">
+ <tr v-for="group in groups" :key="group.id" class="hover:bg-[var(--bg-tertiary)]">
+ <td class="px-6 py-4 whitespace-nowrap">
+ <div class="text-sm font-medium text-[var(--text-primary)]">${ group.name }</div>
+ </td>
+ <td class="px-6 py-4">
+ <div class="text-sm text-[var(--text-secondary)]">${ group.description || 'No description' }</div>
+ </td>
+ <td class="px-6 py-4 whitespace-nowrap">
+ <div class="text-sm text-[var(--text-secondary)]">
+ <i class="fas fa-users mr-1"></i>
+ ${ group.member_count || 0 } members
+ </div>
+ </td>
+ <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-muted)]">
+ ${ new Date(group.created_at).toLocaleDateString() }
+ </td>
+ <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium space-x-2">
+ <button @click="openManageTeamModal(group)" class="text-blue-500 hover:text-blue-700" title="Manage Members">
+ <i class="fas fa-users-cog"></i>
+ </button>
+ <button @click="openManageTeamTagsModal(group)" class="text-purple-500 hover:text-purple-700" title="Manage Group Tags">
+ <i class="fas fa-tags"></i>
+ </button>
+ <button @click="openEditTeamModal(group)" class="text-[var(--text-accent)] hover:text-[var(--text-accent-hover)]" title="Edit Group">
+ <i class="fas fa-edit"></i>
+ </button>
+ <button v-if="!isTeamAdminOnly" @click="confirmDeleteTeam(group)" class="text-red-500 hover:text-red-700" title="Delete Group">
+ <i class="fas fa-trash"></i>
+ </button>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ <div v-else class="p-8 text-center">
+ <i class="fas fa-users-slash text-4xl text-[var(--text-muted)] mb-3"></i>
+ <p class="text-[var(--text-muted)]" v-text="isTeamAdminOnly ? 'You are not an admin of any groups yet' : 'No groups created yet'"></p>
+ <button v-if="!isTeamAdminOnly" @click="openCreateTeamModal" class="mt-4 px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)]">
+ <i class="fas fa-plus mr-2"></i> Create Your First Group
+ </button>
+ </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 &copy; {{ now.year }}
</footer>
-
+
<!-- Add User Modal -->
<div v-if="showAddUserModal" @click.self="showAddUserModal = false" class="fixed inset-0 bg-black bg-opacity-70 backdrop-blur-sm flex items-center justify-center z-50 p-4">
<div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-md">
@@ -952,8 +1053,379 @@ Summarization Instructions:
</div>
</div>
</div>
+
+ <!-- Create/Edit Group Modal -->
+ <div v-if="showTeamModal" @click.self="closeTeamModal" class="fixed inset-0 bg-black bg-opacity-70 backdrop-blur-sm flex items-center justify-center z-50 p-4">
+ <div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-md">
+ <div class="flex justify-between items-center mb-4">
+ <h3 class="text-xl font-semibold text-[var(--text-primary)]">${ editingTeam ? 'Edit Group' : 'Create Group' }</h3>
+ <button @click="closeTeamModal" class="text-[var(--text-muted)] hover:text-[var(--text-secondary)]">&times;</button>
+ </div>
+ <form @submit.prevent="saveTeam">
+ <div class="space-y-4">
+ <div>
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Group Name *</label>
+ <input v-model="teamForm.name" type="text" required
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
+ placeholder="Enter group name">
+ </div>
+ <div>
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Description</label>
+ <textarea v-model="teamForm.description" rows="3"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
+ placeholder="Optional description"></textarea>
+ </div>
+ <div v-if="teamError" class="p-3 bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)] rounded-md text-sm">
+ ${ teamError }
+ </div>
+ </div>
+ <div class="flex justify-end space-x-3 mt-6">
+ <button type="button" @click="closeTeamModal"
+ class="px-4 py-2 border border-[var(--border-secondary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--bg-tertiary)]">
+ Cancel
+ </button>
+ <button type="submit"
+ class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)]">
+ ${ editingTeam ? 'Update Group' : 'Create Group' }
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+
+ <!-- Manage Group Members Modal -->
+ <div v-if="showManageTeamModal" @click.self="closeManageTeamModal" class="fixed inset-0 bg-black bg-opacity-70 backdrop-blur-sm flex items-center justify-center z-50 p-4">
+ <div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
+ <div class="flex justify-between items-center mb-4">
+ <h3 class="text-xl font-semibold text-[var(--text-primary)]">Manage Group: ${ currentTeam?.name }</h3>
+ <button @click="closeManageTeamModal" class="text-[var(--text-muted)] hover:text-[var(--text-secondary)]">&times;</button>
+ </div>
+
+ <!-- Add Member Section -->
+ <div class="mb-6 p-4 bg-[var(--bg-tertiary)] rounded-lg">
+ <h4 class="text-sm font-medium text-[var(--text-secondary)] mb-3">Add Member</h4>
+ <div class="flex space-x-2">
+ <div class="flex-1">
+ <select v-model="newMemberUserId"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
+ <option value="">Select a user...</option>
+ <option v-for="user in availableUsers" :key="user.id" :value="user.id">
+ ${ user.username } (${ user.email })
+ </option>
+ </select>
+ </div>
+ <div>
+ <select v-model="newMemberRole"
+ class="px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
+ <option value="member">Member</option>
+ <option value="admin">Admin</option>
+ </select>
+ </div>
+ <button @click="addTeamMember" :disabled="!newMemberUserId"
+ class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)] disabled:opacity-50 disabled:cursor-not-allowed">
+ <i class="fas fa-plus"></i> Add
+ </button>
+ </div>
+ </div>
+
+ <!-- Current Members -->
+ <div>
+ <h4 class="text-sm font-medium text-[var(--text-secondary)] mb-3">Current Members (${ teamMembers.length })</h4>
+ <div v-if="teamMembers.length > 0" class="space-y-2">
+ <div v-for="member in teamMembers" :key="member.user_id"
+ class="flex items-center justify-between p-3 bg-[var(--bg-tertiary)] rounded-md">
+ <div class="flex items-center space-x-3">
+ <i class="fas fa-user text-[var(--text-muted)]"></i>
+ <div>
+ <div class="text-sm font-medium text-[var(--text-primary)]">${ member.username }</div>
+ <div class="text-xs text-[var(--text-muted)]">${ member.email }</div>
+ </div>
+ </div>
+ <div class="flex items-center space-x-2">
+ <select v-model="member.role" @change="updateMemberRole(member)"
+ class="px-2 py-1 text-sm border border-[var(--border-secondary)] rounded bg-[var(--bg-input)] text-[var(--text-primary)]">
+ <option value="member">Member</option>
+ <option value="admin">Admin</option>
+ </select>
+ <button @click="removeTeamMember(member)"
+ class="text-red-500 hover:text-red-700" title="Remove from group">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+ </div>
+ </div>
+ <div v-else class="text-center py-4 text-[var(--text-muted)]">
+ No members yet
+ </div>
+ </div>
+
+ <div v-if="teamMemberError" class="mt-4 p-3 bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)] rounded-md text-sm">
+ ${ teamMemberError }
+ </div>
+
+ <div class="flex justify-between mt-6">
+ <button @click="syncTeamShares"
+ class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 flex items-center gap-2">
+ <i class="fas fa-sync-alt"></i>
+ Sync Group Shares
+ </button>
+ <button @click="closeManageTeamModal"
+ class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)]">
+ Done
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Sync Group Shares Confirmation Modal -->
+ <div v-if="showSyncSharesModal" @click.self="showSyncSharesModal = false" class="fixed inset-0 bg-black bg-opacity-70 backdrop-blur-sm flex items-center justify-center z-50 p-4">
+ <div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-md">
+ <div class="flex justify-between items-center mb-4">
+ <h3 class="text-xl font-semibold text-[var(--text-primary)]">Sync Group Shares</h3>
+ <button @click="showSyncSharesModal = false" class="text-[var(--text-muted)] hover:text-[var(--text-secondary)]">&times;</button>
+ </div>
+ <p class="mb-4 text-[var(--text-secondary)]">
+ This will create shares for all recordings with group tags that have auto-sharing enabled.
+ </p>
+ <p class="mb-4 text-[var(--text-muted)] text-sm">
+ <i class="fas fa-info-circle mr-1"></i>
+ Only missing shares will be created - existing shares won't be duplicated.
+ </p>
+ <div class="flex justify-end space-x-3">
+ <button @click="showSyncSharesModal = false" class="px-4 py-2 border border-[var(--border-secondary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--bg-tertiary)]">Cancel</button>
+ <button @click="confirmSyncShares" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
+ <i class="fas fa-sync-alt mr-2"></i>Sync Now
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Sync Results Modal -->
+ <div v-if="showSyncResultsModal" @click.self="showSyncResultsModal = false" class="fixed inset-0 bg-black bg-opacity-70 backdrop-blur-sm flex items-center justify-center z-50 p-4">
+ <div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-md">
+ <div class="flex justify-between items-center mb-4">
+ <h3 class="text-xl font-semibold text-[var(--text-primary)]">
+ <i class="fas fa-check-circle text-green-500 mr-2"></i>Sync Complete
+ </h3>
+ <button @click="showSyncResultsModal = false" class="text-[var(--text-muted)] hover:text-[var(--text-secondary)]">&times;</button>
+ </div>
+ <div class="mb-4 space-y-2">
+ <div class="flex justify-between text-[var(--text-secondary)]">
+ <span>Shares created:</span>
+ <span class="font-semibold">${ syncResults.shares_created }</span>
+ </div>
+ <div class="flex justify-between text-[var(--text-secondary)]">
+ <span>Recordings processed:</span>
+ <span class="font-semibold">${ syncResults.recordings_processed }</span>
+ </div>
+ </div>
+ <div class="flex justify-end">
+ <button @click="showSyncResultsModal = false" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)]">
+ Done
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Delete Group Confirmation Modal -->
+ <div v-if="showDeleteTeamModal" @click.self="showDeleteTeamModal = false" class="fixed inset-0 bg-black bg-opacity-70 backdrop-blur-sm flex items-center justify-center z-50 p-4">
+ <div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-md">
+ <div class="flex justify-between items-center mb-4">
+ <h3 class="text-xl font-semibold text-[var(--text-primary)]">Delete Group</h3>
+ <button @click="showDeleteTeamModal = false" class="text-[var(--text-muted)] hover:text-[var(--text-secondary)]">&times;</button>
+ </div>
+ <p class="mb-4 text-[var(--text-secondary)]">Are you sure you want to delete the group <span class="font-semibold">${ teamToDelete?.name }</span>? This will remove all members from the group. This action cannot be undone.</p>
+ <div class="flex justify-end space-x-3">
+ <button @click="showDeleteTeamModal = false" class="px-4 py-2 border border-[var(--border-secondary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--bg-tertiary)]">Cancel</button>
+ <button @click="deleteTeam" class="px-4 py-2 bg-[var(--bg-danger)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-danger-hover)]">Delete Group</button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Manage Group Tags Modal -->
+ <div v-if="showManageTeamTagsModal" @click.self="closeManageTeamTagsModal" class="fixed inset-0 bg-black bg-opacity-70 backdrop-blur-sm flex items-center justify-center z-50 p-4">
+ <div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-3xl max-h-[90vh] overflow-y-auto">
+ <div class="flex justify-between items-center mb-4">
+ <h3 class="text-xl font-semibold text-[var(--text-primary)]">Manage Tags for ${ currentTeam?.name }</h3>
+ <button @click="closeManageTeamTagsModal" class="text-[var(--text-muted)] hover:text-[var(--text-secondary)]">&times;</button>
+ </div>
+
+ <!-- Create/Edit Tag Form -->
+ <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg mb-4 border border-[var(--border-primary)]">
+ <div class="flex justify-between items-center mb-3">
+ <h4 class="text-sm font-medium text-[var(--text-secondary)]">
+ ${ editingTeamTagId ? 'Edit Group Tag' : 'Create New Group Tag' }
+ </h4>
+ <button v-if="editingTeamTagId" @click="cancelEditTeamTag" type="button" class="text-xs text-[var(--text-muted)] hover:text-[var(--text-primary)]">
+ <i class="fas fa-times mr-1"></i> Cancel
+ </button>
+ </div>
+ <form @submit.prevent="saveTeamTag" class="space-y-3">
+ <div class="grid grid-cols-2 gap-3">
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">Tag Name *</label>
+ <input v-model="newTeamTag.name" type="text" required maxlength="50"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-input)] text-[var(--text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)]"
+ placeholder="e.g., Project Alpha">
+ </div>
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">Color</label>
+ <input v-model="newTeamTag.color" type="color"
+ class="w-full h-10 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-input)] cursor-pointer">
+ </div>
+ </div>
+
+ <!-- Custom Prompt -->
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">
+ Custom Summarization Prompt
+ <span class="text-[var(--text-muted)] font-normal">- Optional AI instructions</span>
+ </label>
+ <textarea v-model="newTeamTag.custom_prompt" rows="3"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-input)] text-[var(--text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)]"
+ placeholder="Enter custom instructions for AI summarization (e.g., 'Focus on action items and deadlines')"></textarea>
+ <p class="text-xs text-[var(--text-muted)] mt-1">
+ Recordings with this tag will use this prompt for AI summaries and chat.
+ </p>
+ </div>
+
+ <!-- Transcription Settings -->
+ <div class="grid grid-cols-3 gap-3">
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">Default Language</label>
+ <select v-model="newTeamTag.default_language"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-input)] text-[var(--text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)]">
+ <option value="">Auto-detect</option>
+ <option value="en">English</option>
+ <option value="es">Spanish</option>
+ <option value="fr">French</option>
+ <option value="de">German</option>
+ <option value="zh">Chinese</option>
+ <option value="ja">Japanese</option>
+ <option value="pt">Portuguese</option>
+ <option value="it">Italian</option>
+ </select>
+ </div>
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">Min Speakers</label>
+ <input v-model.number="newTeamTag.default_min_speakers" type="number" min="1" max="10"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-input)] text-[var(--text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)]"
+ placeholder="1">
+ </div>
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">Max Speakers</label>
+ <input v-model.number="newTeamTag.default_max_speakers" type="number" min="1" max="10"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-input)] text-[var(--text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)]"
+ placeholder="5">
+ </div>
+ </div>
+
+ <!-- Retention and Protection -->
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">
+ Retention Period (days)
+ <span class="text-[var(--text-muted)] font-normal">- Optional override for auto-deletion</span>
+ </label>
+ <input v-model.number="newTeamTag.retention_days" type="number" min="0" step="1"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-input)] text-[var(--text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)]"
+ placeholder="Leave empty to use global retention">
+ <p class="text-xs text-[var(--text-muted)] mt-1">
+ Recordings with this tag will be deleted after this many days. Leave empty to use global retention (${ globalRetentionDays } days).
+ </p>
+ </div>
+ <div class="flex items-center">
+ <input v-model="newTeamTag.protect_from_deletion" type="checkbox" id="protectFromDeletion"
+ class="mr-2 h-4 w-4 text-[var(--text-accent)] border-[var(--border-secondary)] rounded focus:ring-[var(--border-focus)]">
+ <label for="protectFromDeletion" class="text-xs text-[var(--text-secondary)]">
+ <i class="fas fa-shield-alt mr-1"></i> Protect recordings with this tag from auto-deletion
+ </label>
+ </div>
+ <div class="space-y-2">
+ <div class="flex items-center">
+ <input v-model="newTeamTag.auto_share_on_apply" type="checkbox" id="autoShareOnApply"
+ class="mr-2 h-4 w-4 text-[var(--text-accent)] border-[var(--border-secondary)] rounded focus:ring-[var(--border-focus)]">
+ <label for="autoShareOnApply" class="text-xs text-[var(--text-secondary)]">
+ <i class="fas fa-user-friends mr-1"></i> Auto-share recordings with all group members when this tag is applied
+ </label>
+ </div>
+ <div class="flex items-center">
+ <input v-model="newTeamTag.share_with_group_lead" type="checkbox" id="shareWithGroupLead"
+ class="mr-2 h-4 w-4 text-[var(--text-accent)] border-[var(--border-secondary)] rounded focus:ring-[var(--border-focus)]">
+ <label for="shareWithGroupLead" class="text-xs text-[var(--text-secondary)]">
+ <i class="fas fa-user-tie mr-1"></i> Share recordings with group admins when this tag is applied
+ </label>
+ </div>
+ <p class="text-xs text-[var(--text-muted)] ml-6">
+ Note: If both are enabled, all group members will have access. If only "group admins" is enabled, only group leads will have access.
+ </p>
+ </div>
+ <div v-if="teamTagError" class="text-[var(--text-danger)] text-xs">${ teamTagError }</div>
+ <button type="submit" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)] text-sm">
+ <i :class="editingTeamTagId ? 'fas fa-save' : 'fas fa-plus'" class="mr-1"></i>
+ ${ editingTeamTagId ? 'Update Tag' : 'Create Tag' }
+ </button>
+ </form>
+ </div>
+
+ <!-- Existing Group Tags -->
+ <div>
+ <h4 class="text-sm font-medium text-[var(--text-secondary)] mb-3">Group Tags</h4>
+ <div v-if="teamTags.length > 0" class="space-y-3">
+ <div v-for="tag in teamTags" :key="tag.id"
+ class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)]">
+ <div class="flex items-start justify-between mb-2">
+ <div class="flex items-center space-x-3 flex-1">
+ <span class="inline-block w-4 h-4 rounded flex-shrink-0" :style="{ backgroundColor: tag.color }"></span>
+ <div class="flex-1">
+ <div class="text-sm font-medium text-[var(--text-primary)]">${ tag.name }</div>
+ <div class="text-xs text-[var(--text-muted)] mt-1 space-x-3">
+ <span v-if="tag.retention_days">
+ <i class="fas fa-clock mr-1"></i> ${ tag.retention_days } day retention
+ </span>
+ <span v-else>
+ <i class="fas fa-globe mr-1"></i> Global retention
+ </span>
+ <span v-if="tag.protect_from_deletion" class="text-green-500">
+ <i class="fas fa-shield-alt mr-1"></i> Protected
+ </span>
+ </div>
+ </div>
+ </div>
+ <div class="flex gap-2 flex-shrink-0">
+ <button @click="editTeamTag(tag)" class="text-blue-500 hover:text-blue-700 px-2 py-1" title="Edit Tag">
+ <i class="fas fa-edit"></i>
+ </button>
+ <button @click="deleteTeamTag(tag)" class="text-red-500 hover:text-red-700 px-2 py-1" title="Delete Tag">
+ <i class="fas fa-trash"></i>
+ </button>
+ </div>
+ </div>
+
+ <!-- Additional details if configured -->
+ <div v-if="tag.custom_prompt || tag.default_language || tag.default_min_speakers || tag.default_max_speakers"
+ class="mt-2 pt-2 border-t border-[var(--border-secondary)] space-y-1">
+ <div v-if="tag.custom_prompt" class="text-xs text-[var(--text-muted)]">
+ <i class="fas fa-comment-dots mr-1"></i> Custom prompt configured
+ </div>
+ <div v-if="tag.default_language" class="text-xs text-[var(--text-muted)]">
+ <i class="fas fa-language mr-1"></i> Language: ${ tag.default_language.toUpperCase() }
+ </div>
+ <div v-if="tag.default_min_speakers || tag.default_max_speakers" class="text-xs text-[var(--text-muted)]">
+ <i class="fas fa-users mr-1"></i> Speakers:
+ <span v-if="tag.default_min_speakers">${ tag.default_min_speakers }-</span><span v-if="tag.default_max_speakers">${ tag.default_max_speakers }</span><span v-else>auto</span>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div v-else class="text-center py-8 text-[var(--text-muted)]">
+ <i class="fas fa-tags text-3xl mb-2"></i>
+ <p class="text-sm">No group tags created yet</p>
+ </div>
+ </div>
+ </div>
+ </div>
</div>
-
+
<script>
const { createApp, ref, computed, onMounted, watch } = Vue
@@ -966,7 +1438,8 @@ Summarization Instructions:
setup() {
// State
- const activeTab = ref('users');
+ const isTeamAdminOnly = ref({% if is_group_admin_only %}true{% else %}false{% endif %});
+ const activeTab = ref({% if is_group_admin_only %}'teams'{% else %}'users'{% endif %});
const users = ref([]);
const stats = ref({
total_users: 0,
@@ -1012,7 +1485,44 @@ Summarization Instructions:
});
const isProcessingRecordings = ref(false);
const processingResult = ref(null);
-
+
+ // Teams state
+ const groups = ref([]);
+ const showTeamModal = ref(false);
+ const showManageTeamModal = ref(false);
+ const showDeleteTeamModal = ref(false);
+ const showSyncSharesModal = ref(false);
+ const showSyncResultsModal = ref(false);
+ const syncResults = ref({ shares_created: 0, recordings_processed: 0 });
+ const editingTeam = ref(null);
+ const teamToDelete = ref(null);
+ const currentTeam = ref(null);
+ const teamForm = ref({ name: '', description: '' });
+ const teamError = ref('');
+ const teamMembers = ref([]);
+ const newMemberUserId = ref('');
+ const newMemberRole = ref('member');
+ const teamMemberError = ref('');
+
+ // Group Tags state
+ const showManageTeamTagsModal = ref(false);
+ const teamTags = ref([]);
+ const editingTeamTagId = ref(null);
+ const newTeamTag = ref({
+ name: '',
+ color: '#3B82F6',
+ custom_prompt: '',
+ default_language: '',
+ default_min_speakers: null,
+ default_max_speakers: null,
+ retention_days: null,
+ protect_from_deletion: false,
+ auto_share_on_apply: true,
+ share_with_group_lead: true
+ });
+ const teamTagError = ref('');
+ const globalRetentionDays = ref({{ global_retention_days }});
+
// Default Prompts state
const defaultSummaryPrompt = ref('');
const isSavingPrompt = ref(false);
@@ -1027,13 +1537,19 @@ Summarization Instructions:
// Computed properties
const filteredUsers = computed(() => {
if (!userSearchQuery.value) return users.value;
-
+
const query = userSearchQuery.value.toLowerCase();
- return users.value.filter(user =>
- user.username.toLowerCase().includes(query) ||
+ return users.value.filter(user =>
+ user.username.toLowerCase().includes(query) ||
user.email.toLowerCase().includes(query)
);
});
+
+ const availableUsers = computed(() => {
+ if (!currentTeam.value) return users.value;
+ const memberUserIds = teamMembers.value.map(m => m.user_id);
+ return users.value.filter(user => !memberUserIds.includes(user.id));
+ });
// Methods
const loadUsers = async () => {
@@ -1385,32 +1901,480 @@ Summarization Instructions:
try {
// Get CSRF token
const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
-
+
const headers = {};
-
+
if (csrfToken) {
headers['X-CSRFToken'] = csrfToken;
}
-
+
const response = await fetch(`/admin/users/${user.id}/toggle-admin`, {
method: 'POST',
headers: headers
});
-
+
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || 'Failed to toggle admin status');
}
-
+
// Reload users
await loadUsers();
-
+
} catch (error) {
console.error('Error toggling admin status:', error);
alert(error.message);
}
};
-
+
+ const togglePublicSharingPermission = async (user) => {
+ try {
+ const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
+ const headers = { 'Content-Type': 'application/json' };
+
+ if (csrfToken) {
+ headers['X-CSRFToken'] = csrfToken;
+ }
+
+ const response = await fetch(`/admin/users/${user.id}`, {
+ method: 'PUT',
+ headers: headers,
+ body: JSON.stringify({
+ can_share_publicly: !user.can_share_publicly
+ })
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(errorData.error || 'Failed to toggle public sharing permission');
+ }
+
+ // Reload users
+ await loadUsers();
+
+ } catch (error) {
+ console.error('Error toggling public sharing permission:', error);
+ alert(error.message);
+ }
+ };
+
+ // Group Management Functions
+ const loadGroups = async () => {
+ try {
+ const response = await fetch('/api/admin/groups');
+ if (!response.ok) throw new Error('Failed to load groups');
+ const data = await response.json();
+ groups.value = data.groups || [];
+ } catch (error) {
+ console.error('Error loading teams:', error);
+ }
+ };
+
+ const openCreateTeamModal = () => {
+ editingTeam.value = null;
+ teamForm.value = { name: '', description: '' };
+ teamError.value = '';
+ showTeamModal.value = true;
+ };
+
+ const openEditTeamModal = (group) => {
+ editingTeam.value = group;
+ teamForm.value = { name: group.name, description: group.description || '' };
+ teamError.value = '';
+ showTeamModal.value = true;
+ };
+
+ const closeTeamModal = () => {
+ showTeamModal.value = false;
+ editingTeam.value = null;
+ teamForm.value = { name: '', description: '' };
+ teamError.value = '';
+ };
+
+ const saveTeam = async () => {
+ teamError.value = '';
+ try {
+ const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
+ const headers = { 'Content-Type': 'application/json' };
+ if (csrfToken) headers['X-CSRFToken'] = csrfToken;
+
+ const url = editingTeam.value
+ ? `/api/admin/groups/${editingTeam.value.id}`
+ : '/api/admin/groups';
+ const method = editingTeam.value ? 'PUT' : 'POST';
+
+ const response = await fetch(url, {
+ method,
+ headers,
+ body: JSON.stringify(teamForm.value)
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to save group');
+ }
+
+ closeTeamModal();
+ await loadGroups();
+ } catch (error) {
+ teamError.value = error.message;
+ }
+ };
+
+ const confirmDeleteTeam = (group) => {
+ teamToDelete.value = group;
+ showDeleteTeamModal.value = true;
+ };
+
+ const deleteTeam = async () => {
+ try {
+ const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
+ const headers = {};
+ if (csrfToken) headers['X-CSRFToken'] = csrfToken;
+
+ const response = await fetch(`/api/admin/groups/${teamToDelete.value.id}`, {
+ method: 'DELETE',
+ headers
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to delete group');
+ }
+
+ showDeleteTeamModal.value = false;
+ teamToDelete.value = null;
+ await loadGroups();
+ } catch (error) {
+ alert(error.message);
+ }
+ };
+
+ const openManageTeamModal = async (group) => {
+ currentTeam.value = group;
+ newMemberUserId.value = '';
+ newMemberRole.value = 'member';
+ teamMemberError.value = '';
+ showManageTeamModal.value = true;
+ await loadTeamMembers(group.id);
+ };
+
+ const closeManageTeamModal = () => {
+ showManageTeamModal.value = false;
+ currentTeam.value = null;
+ teamMembers.value = [];
+ newMemberUserId.value = '';
+ newMemberRole.value = 'member';
+ teamMemberError.value = '';
+ };
+
+ const loadTeamMembers = async (groupId) => {
+ try {
+ const response = await fetch(`/api/admin/groups/${groupId}`);
+ if (!response.ok) throw new Error('Failed to load group members');
+ const data = await response.json();
+ teamMembers.value = data.members || [];
+ } catch (error) {
+ console.error('Error loading group members:', error);
+ teamMemberError.value = error.message;
+ }
+ };
+
+ const addTeamMember = async () => {
+ if (!newMemberUserId.value) return;
+
+ teamMemberError.value = '';
+ try {
+ const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
+ const headers = { 'Content-Type': 'application/json' };
+ if (csrfToken) headers['X-CSRFToken'] = csrfToken;
+
+ const response = await fetch(`/api/admin/groups/${currentTeam.value.id}/members`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({
+ user_id: parseInt(newMemberUserId.value),
+ role: newMemberRole.value
+ })
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to add member');
+ }
+
+ newMemberUserId.value = '';
+ newMemberRole.value = 'member';
+ await loadTeamMembers(currentTeam.value.id);
+ await loadGroups(); // Refresh to update member count
+ } catch (error) {
+ teamMemberError.value = error.message;
+ }
+ };
+
+ const updateMemberRole = async (member) => {
+ teamMemberError.value = '';
+ try {
+ const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
+ const headers = { 'Content-Type': 'application/json' };
+ if (csrfToken) headers['X-CSRFToken'] = csrfToken;
+
+ const response = await fetch(`/api/admin/groups/${currentTeam.value.id}/members/${member.user_id}`, {
+ method: 'PUT',
+ headers,
+ body: JSON.stringify({ role: member.role })
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to update role');
+ }
+ } catch (error) {
+ teamMemberError.value = error.message;
+ await loadTeamMembers(currentTeam.value.id); // Reload to revert on error
+ }
+ };
+
+ const removeTeamMember = async (member) => {
+ if (!confirm(`Remove ${member.username} from the group?`)) return;
+
+ teamMemberError.value = '';
+ try {
+ const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
+ const headers = {};
+ if (csrfToken) headers['X-CSRFToken'] = csrfToken;
+
+ const response = await fetch(`/api/admin/groups/${currentTeam.value.id}/members/${member.user_id}`, {
+ method: 'DELETE',
+ headers
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to remove member');
+ }
+
+ await loadTeamMembers(currentTeam.value.id);
+ await loadGroups(); // Refresh to update member count
+ } catch (error) {
+ teamMemberError.value = error.message;
+ }
+ };
+
+ const syncTeamShares = () => {
+ if (!currentTeam.value) return;
+ showSyncSharesModal.value = true;
+ };
+
+ const confirmSyncShares = async () => {
+ showSyncSharesModal.value = false;
+ teamMemberError.value = '';
+
+ try {
+ const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
+ const headers = { 'Content-Type': 'application/json' };
+ if (csrfToken) headers['X-CSRFToken'] = csrfToken;
+
+ const response = await fetch(`/api/groups/${currentTeam.value.id}/sync-shares`, {
+ method: 'POST',
+ headers
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to sync shares');
+ }
+
+ const result = await response.json();
+ syncResults.value = {
+ shares_created: result.shares_created,
+ recordings_processed: result.recordings_processed
+ };
+ showSyncResultsModal.value = true;
+ } catch (error) {
+ teamMemberError.value = error.message;
+ }
+ };
+
+ // Group Tags Management
+ const openManageTeamTagsModal = async (group) => {
+ currentTeam.value = group;
+ teamTagError.value = '';
+ await loadTeamTags(group.id);
+ showManageTeamTagsModal.value = true;
+ };
+
+ const closeManageTeamTagsModal = () => {
+ showManageTeamTagsModal.value = false;
+ currentTeam.value = null;
+ teamTags.value = [];
+ editingTeamTagId.value = null;
+ newTeamTag.value = {
+ name: '',
+ color: '#3B82F6',
+ custom_prompt: '',
+ default_language: '',
+ default_min_speakers: null,
+ default_max_speakers: null,
+ retention_days: null,
+ protect_from_deletion: false,
+ auto_share_on_apply: true,
+ share_with_group_lead: true
+ };
+ teamTagError.value = '';
+ };
+
+ const loadTeamTags = async (groupId) => {
+ try {
+ const response = await fetch(`/api/groups/${groupId}/tags`);
+ if (!response.ok) throw new Error('Failed to load group tags');
+ const data = await response.json();
+ teamTags.value = data.tags || [];
+ } catch (error) {
+ teamTagError.value = error.message;
+ }
+ };
+
+ const editTeamTag = (tag) => {
+ editingTeamTagId.value = tag.id;
+ newTeamTag.value = {
+ name: tag.name,
+ color: tag.color,
+ custom_prompt: tag.custom_prompt || '',
+ default_language: tag.default_language || '',
+ default_min_speakers: tag.default_min_speakers,
+ default_max_speakers: tag.default_max_speakers,
+ retention_days: tag.retention_days,
+ protect_from_deletion: tag.protect_from_deletion || false,
+ auto_share_on_apply: tag.auto_share_on_apply !== undefined ? tag.auto_share_on_apply : true,
+ share_with_group_lead: tag.share_with_group_lead !== undefined ? tag.share_with_group_lead : true
+ };
+ // Scroll to top of modal
+ document.querySelector('.max-h-\\[90vh\\]')?.scrollTo({ top: 0, behavior: 'smooth' });
+ };
+
+ const cancelEditTeamTag = () => {
+ editingTeamTagId.value = null;
+ newTeamTag.value = {
+ name: '',
+ color: '#3B82F6',
+ custom_prompt: '',
+ default_language: '',
+ default_min_speakers: null,
+ default_max_speakers: null,
+ retention_days: null,
+ protect_from_deletion: false,
+ auto_share_on_apply: true,
+ share_with_group_lead: true
+ };
+ teamTagError.value = '';
+ };
+
+ const saveTeamTag = async () => {
+ teamTagError.value = '';
+ try {
+ const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
+ const headers = { 'Content-Type': 'application/json' };
+ if (csrfToken) headers['X-CSRFToken'] = csrfToken;
+
+ const payload = {
+ name: newTeamTag.value.name,
+ color: newTeamTag.value.color,
+ protect_from_deletion: newTeamTag.value.protect_from_deletion,
+ auto_share_on_apply: newTeamTag.value.auto_share_on_apply,
+ share_with_group_lead: newTeamTag.value.share_with_group_lead
+ };
+
+ // Add custom prompt if provided
+ if (newTeamTag.value.custom_prompt && newTeamTag.value.custom_prompt.trim()) {
+ payload.custom_prompt = newTeamTag.value.custom_prompt.trim();
+ }
+
+ // Add language if selected
+ if (newTeamTag.value.default_language) {
+ payload.default_language = newTeamTag.value.default_language;
+ }
+
+ // Add speaker settings if provided
+ if (newTeamTag.value.default_min_speakers) {
+ payload.default_min_speakers = newTeamTag.value.default_min_speakers;
+ }
+ if (newTeamTag.value.default_max_speakers) {
+ payload.default_max_speakers = newTeamTag.value.default_max_speakers;
+ }
+
+ // Only include retention_days if it's set and > 0
+ if (newTeamTag.value.retention_days && newTeamTag.value.retention_days > 0) {
+ payload.retention_days = newTeamTag.value.retention_days;
+ }
+
+ let response;
+ if (editingTeamTagId.value) {
+ // Update existing tag
+ response = await fetch(`/api/tags/${editingTeamTagId.value}`, {
+ method: 'PUT',
+ headers,
+ body: JSON.stringify(payload)
+ });
+ } else {
+ // Create new tag
+ response = await fetch(`/api/groups/${currentTeam.value.id}/tags`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify(payload)
+ });
+ }
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || (editingTeamTagId.value ? 'Failed to update tag' : 'Failed to create tag'));
+ }
+
+ // Reset form and reload
+ editingTeamTagId.value = null;
+ newTeamTag.value = {
+ name: '',
+ color: '#3B82F6',
+ custom_prompt: '',
+ default_language: '',
+ default_min_speakers: null,
+ default_max_speakers: null,
+ retention_days: null,
+ protect_from_deletion: false,
+ auto_share_on_apply: true,
+ share_with_group_lead: true
+ };
+ await loadTeamTags(currentTeam.value.id);
+ } catch (error) {
+ teamTagError.value = error.message;
+ }
+ };
+
+ const deleteTeamTag = async (tag) => {
+ if (!confirm(`Delete the tag "${tag.name}"? This will remove the tag from all recordings.`)) return;
+
+ teamTagError.value = '';
+ try {
+ const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
+ const headers = {};
+ if (csrfToken) headers['X-CSRFToken'] = csrfToken;
+
+ const response = await fetch(`/api/tags/${tag.id}`, {
+ method: 'DELETE',
+ headers
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to delete tag');
+ }
+
+ await loadTeamTags(currentTeam.value.id);
+ } catch (error) {
+ teamTagError.value = error.message;
+ }
+ };
+
const formatFileSize = (bytes) => {
if (!bytes || bytes === 0) return '0 Bytes';
@@ -1606,20 +2570,28 @@ Summarization Instructions:
// Lifecycle hooks - MUST be registered before any await statements
onMounted(async () => {
- loadUsers();
- loadStats();
- initializeDarkMode();
+ // Only load admin-specific data if user is full admin
+ if (!isTeamAdminOnly.value) {
+ loadUsers();
+ loadStats();
- // Load settings first, then default prompt can use that data
- if (activeTab.value === 'settings' || activeTab.value === 'prompts') {
- await loadSettings();
- }
- loadDefaultPrompt();
+ // Load settings first, then default prompt can use that data
+ if (activeTab.value === 'settings' || activeTab.value === 'prompts') {
+ await loadSettings();
+ }
+ loadDefaultPrompt();
- if (inquireModeEnabled.value) {
- loadInquireStatus();
+ if (inquireModeEnabled.value) {
+ loadInquireStatus();
+ }
+ } else {
+ // Group admins only need users list (for adding members) and groups
+ loadUsers();
+ loadGroups();
}
+ initializeDarkMode();
+
// Setup scroll indicators for tabs
const tabsContainer = document.getElementById('admin-tabs-container');
const leftIndicator = document.getElementById('admin-left-scroll-indicator');
@@ -1663,28 +2635,38 @@ Summarization Instructions:
// Watch for tab changes to reload data
watch(activeTab, async (newTab) => {
- if (newTab === 'users') {
- loadUsers();
- } else if (newTab === 'stats') {
- loadStats();
- } else if (newTab === 'settings') {
- await loadSettings();
- } else if (newTab === 'prompts') {
- // If settings aren't loaded, load them first
- if (!settings.value || settings.value.length === 0) {
+ // Only allow full admins to load admin-specific data
+ if (!isTeamAdminOnly.value) {
+ if (newTab === 'users') {
+ loadUsers();
+ } else if (newTab === 'stats') {
+ loadStats();
+ } else if (newTab === 'settings') {
await loadSettings();
+ } else if (newTab === 'prompts') {
+ // If settings aren't loaded, load them first
+ if (!settings.value || settings.value.length === 0) {
+ await loadSettings();
+ }
+ loadDefaultPrompt();
+ } else if (newTab === 'vectorstore' && inquireModeEnabled.value) {
+ loadInquireStatus();
}
- loadDefaultPrompt();
- } else if (newTab === 'vectorstore' && inquireModeEnabled.value) {
- loadInquireStatus();
+ }
+
+ // Both full admins and group admins can access teams
+ if (newTab === 'groups') {
+ loadGroups();
+ loadUsers(); // Load users for member selection
}
});
return {
// i18n - bind to i18n instance to maintain context
t: (key, params) => i18nInstance ? i18nInstance.t(key, params) : key,
-
+
// State
+ isTeamAdminOnly,
activeTab,
users,
stats,
@@ -1717,7 +2699,33 @@ Summarization Instructions:
inquireStatus,
isProcessingRecordings,
processingResult,
-
+
+ // Teams state
+ groups,
+ showTeamModal,
+ showManageTeamModal,
+ showDeleteTeamModal,
+ showSyncSharesModal,
+ showSyncResultsModal,
+ syncResults,
+ editingTeam,
+ teamToDelete,
+ currentTeam,
+ teamForm,
+ teamError,
+ teamMembers,
+ newMemberUserId,
+ newMemberRole,
+ teamMemberError,
+
+ // Group Tags state
+ showManageTeamTagsModal,
+ teamTags,
+ editingTeamTagId,
+ newTeamTag,
+ teamTagError,
+ globalRetentionDays,
+
// Default Prompts state
defaultSummaryPrompt,
isSavingPrompt,
@@ -1728,8 +2736,9 @@ Summarization Instructions:
// Computed
filteredUsers,
+ availableUsers,
getProcessingProgress,
-
+
// Methods
loadUsers,
loadStats,
@@ -1745,9 +2754,36 @@ Summarization Instructions:
confirmDeleteUser,
deleteUser,
toggleAdminStatus,
+ togglePublicSharingPermission,
formatFileSize,
toggleDarkMode,
-
+
+ // Group Management methods
+ loadGroups,
+ openCreateTeamModal,
+ openEditTeamModal,
+ closeTeamModal,
+ saveTeam,
+ confirmDeleteTeam,
+ deleteTeam,
+ openManageTeamModal,
+ closeManageTeamModal,
+ loadTeamMembers,
+ addTeamMember,
+ updateMemberRole,
+ removeTeamMember,
+ syncTeamShares,
+ confirmSyncShares,
+
+ // Group Tags methods
+ openManageTeamTagsModal,
+ closeManageTeamTagsModal,
+ loadTeamTags,
+ saveTeamTag,
+ editTeamTag,
+ cancelEditTeamTag,
+ deleteTeamTag,
+
// Inquire Mode methods
loadInquireStatus,
processAllRecordings,
@@ -1764,17 +2800,8 @@ Summarization Instructions:
// Hide loading overlay after Vue is mounted
Vue.nextTick(() => {
- const overlay = document.querySelector('.app-loading-overlay');
- if (overlay) {
- setTimeout(() => {
- overlay.classList.add('fade-out');
- setTimeout(() => {
- overlay.remove();
- document.body.classList.remove('app-loading');
- }, 300);
- }, 100);
- } else {
- document.body.classList.remove('app-loading');
+ if (window.AppLoader) {
+ window.AppLoader.hide();
}
});
}); // End of initializeI18n().then()
diff --git a/templates/components/detail-view.html b/templates/components/detail-view.html
new file mode 100644
index 00000000..db6358f5
--- /dev/null
+++ b/templates/components/detail-view.html
@@ -0,0 +1,35 @@
+<!-- Detail View Container -->
+<div v-if="currentView === 'detail' && selectedRecording" class="flex-1 flex flex-col overflow-hidden">
+ <!-- Mobile View -->
+ <div v-if="isMobile" class="flex flex-col h-full overflow-hidden">
+ {% include 'components/detail/mobile-header.html' %}
+ {% include 'components/detail/audio-player.html' %}
+ {% include 'components/detail/tab-navigation.html' %}
+
+ <!-- Mobile Tab Content -->
+ <div class="flex-1 overflow-y-auto p-4">
+ {% include 'components/detail/mobile-transcript-panel.html' %}
+ {% include 'components/detail/mobile-summary-panel.html' %}
+ {% include 'components/detail/mobile-notes-panel.html' %}
+ {% include 'components/detail/mobile-chat-panel.html' %}
+ {% include 'components/detail/mobile-events-panel.html' %}
+ </div>
+ </div>
+
+ <!-- Desktop View -->
+ <div v-else class="flex-1 flex flex-col overflow-hidden">
+ {% include 'components/detail/desktop-header.html' %}
+
+ <!-- Main Content Split View -->
+ <div id="mainContentColumns" class="flex-1 flex overflow-hidden">
+ {% include 'components/detail/desktop-transcription-panel.html' %}
+
+ <!-- Resizable Divider -->
+ <div id="mainColumnResizer" @mousedown="startColumnResize"></div>
+
+ {% include 'components/detail/desktop-right-panel.html' %}
+ </div>
+ </div>
+</div>
+
+{% include 'components/detail/empty-state.html' %}
diff --git a/templates/components/detail/audio-player.html b/templates/components/detail/audio-player.html
new file mode 100644
index 00000000..ca5947c9
--- /dev/null
+++ b/templates/components/detail/audio-player.html
@@ -0,0 +1,22 @@
+<!-- Audio Player Component -->
+<div class="bg-[var(--bg-secondary)] p-4 border-b border-[var(--border-primary)] flex-shrink-0">
+ <div class="audio-player-container">
+ <!-- Show message if audio has been deleted -->
+ <div v-if="selectedRecording.audio_deleted_at"
+ class="bg-[var(--bg-tertiary)] border border-[var(--border-primary)] text-[var(--text-muted)] px-4 py-3 rounded-lg flex items-center gap-2 text-sm">
+ <i class="fas fa-info-circle"></i>
+ <span v-text="t('help.audioDeletedMessage')"></span>
+ </div>
+ <!-- Show audio player if audio is available -->
+ <audio v-else
+ ref="audioPlayerElement"
+ controls
+ :src="'/audio/' + selectedRecording.id"
+ :volume="playerVolume"
+ @volumechange="onPlayerVolumeChange"
+ @timeupdate="handleAudioTimeUpdate"
+ class="w-full">
+ Your browser does not support the audio element.
+ </audio>
+ </div>
+</div>
diff --git a/templates/components/detail/desktop-chat-section.html b/templates/components/detail/desktop-chat-section.html
new file mode 100644
index 00000000..0d629f49
--- /dev/null
+++ b/templates/components/detail/desktop-chat-section.html
@@ -0,0 +1,109 @@
+<!-- Desktop Chat Section -->
+<div class="border-t border-[var(--border-primary)] flex flex-col" :class="{'flex-1 overflow-hidden': isChatMaximized}">
+ <!-- Chat Toggle -->
+ <div class="bg-[var(--bg-tertiary)] px-4 py-3 hover:bg-[var(--bg-accent-hover)] transition-colors flex items-center">
+ <button @click="() => { showChat = !showChat; if (!showChat) isChatMaximized = false; }"
+ class="flex-1 text-left flex items-center">
+ <span class="font-medium flex items-center">
+ <i class="fas fa-comments mr-2"></i>
+ ${ t('chat.chatWithTranscription') }
+ </span>
+ </button>
+ <div class="flex items-center gap-2">
+ <button v-if="chatMessages.length > 0"
+ @click="downloadChat"
+ class="p-1 text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors"
+ :title="t('buttons.downloadChat')">
+ <i class="fas fa-download text-sm"></i>
+ </button>
+ <button @click="toggleChatMaximize"
+ class="p-1 text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors"
+ :title="isChatMaximized ? 'Restore chat' : 'Maximize chat'">
+ <i :class="['fas text-sm', isChatMaximized ? 'fa-compress' : 'fa-expand']"></i>
+ </button>
+ <button @click="() => { showChat = !showChat; if (!showChat) isChatMaximized = false; }"
+ class="p-1 text-[var(--text-muted)] hover:text-[var(--text-primary)]">
+ <i :class="['fas transition-transform duration-200', showChat ? 'fa-chevron-down' : 'fa-chevron-up']"></i>
+ </button>
+ </div>
+ </div>
+
+ <!-- Chat Content -->
+ <div v-if="showChat" class="flex flex-col relative" :class="isChatMaximized ? 'flex-1 overflow-hidden' : 'max-h-96'">
+ <!-- Clear button - fixed at top right -->
+ <button v-if="chatMessages.length > 0"
+ @click="clearChat"
+ class="absolute top-2 right-2 p-1 text-[var(--text-muted)] opacity-60 hover:opacity-100 hover:text-[var(--text-danger)] rounded transition-all duration-200 z-20"
+ title="Clear chat">
+ <i class="fas fa-times text-xs"></i>
+ </button>
+
+ <!-- Chat Messages -->
+ <div ref="chatMessagesRef"
+ class="flex-1 overflow-y-auto p-4 space-y-4 bg-[var(--bg-secondary)]">
+ <div v-if="chatMessages.length === 0" class="text-center py-8">
+ <i class="fas fa-robot text-3xl text-[var(--text-muted)] mb-3"></i>
+ <p class="text-[var(--text-muted)]" v-text="t('help.askAboutTranscription')"></p>
+ </div>
+
+ <div v-for="(message, index) in chatMessages"
+ :key="index"
+ :class="[
+ 'message relative group',
+ message.role === 'user' ? 'user-message ml-auto' : 'ai-message',
+ message.role === 'assistant' ? 'pr-10' : ''
+ ]">
+ <!-- Copy button for assistant messages -->
+ <button v-if="message.role === 'assistant'"
+ @click="copyMessage(message.content, $event)"
+ class="absolute top-2 right-2 p-1 text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-tertiary)] rounded transition-all duration-200"
+ :title="t('buttons.copyMessage')">
+ <i class="fas fa-copy text-sm"></i>
+ </button>
+ <!-- Show thinking content if available -->
+ <div v-if="message.thinking && message.role === 'assistant'" class="mb-2">
+ <button @click="message.thinkingExpanded = !message.thinkingExpanded"
+ class="text-xs text-[var(--text-muted)] hover:text-[var(--text-secondary)] flex items-center gap-1">
+ <i :class="['fas', message.thinkingExpanded ? 'fa-chevron-down' : 'fa-chevron-right']"></i>
+ <span v-text="t('help.modelReasoning')"></span>
+ <span class="text-[var(--text-muted)]">(${message.thinking.split('\n').length} lines)</span>
+ </button>
+ <div v-if="message.thinkingExpanded"
+ class="mt-2 p-3 bg-[var(--bg-tertiary)] border border-[var(--border-secondary)] rounded-lg text-xs text-[var(--text-muted)] max-h-64 overflow-y-auto">
+ <pre class="whitespace-pre-wrap font-mono">${message.thinking}</pre>
+ </div>
+ </div>
+ <!-- Main message content -->
+ <div v-if="message.html" v-html="message.html"></div>
+ <div v-else class="whitespace-pre-wrap">${message.content}</div>
+ </div>
+
+ <div v-if="isChatLoading" class="ai-message">
+ <i class="fas fa-spinner fa-spin mr-2"></i>
+ ${ t('chat.thinking') }
+ </div>
+ </div>
+
+ <!-- Chat Input -->
+ <div class="border-t border-[var(--border-primary)] p-4 bg-[var(--bg-tertiary)]">
+ <div class="flex gap-2">
+ <textarea v-model="chatInput"
+ @keydown="handleChatKeydown"
+ :disabled="isChatLoading || selectedRecording.status !== 'COMPLETED'"
+ :placeholder="t('chat.placeholderWithHint')"
+ class="flex-1 px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)] text-sm"
+ rows="2">
+ </textarea>
+ <button @click="sendChatMessage"
+ :disabled="!chatInput.trim() || isChatLoading || selectedRecording.status !== 'COMPLETED'"
+ class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
+ <i class="fas fa-paper-plane"></i>
+ </button>
+ </div>
+ <p v-if="selectedRecording.status !== 'COMPLETED'"
+ class="text-xs text-[var(--text-muted)] mt-2">
+ ${ t('chat.availableAfterTranscription') }
+ </p>
+ </div>
+ </div>
+</div>
diff --git a/templates/components/detail/desktop-events-tab.html b/templates/components/detail/desktop-events-tab.html
new file mode 100644
index 00000000..aa9ab91b
--- /dev/null
+++ b/templates/components/detail/desktop-events-tab.html
@@ -0,0 +1,58 @@
+<!-- Desktop Events Tab -->
+<div v-if="selectedTab === 'events' && selectedRecording.events && selectedRecording.events.length > 0" class="h-full p-4 overflow-y-auto">
+ <div class="space-y-4">
+ <div v-for="event in selectedRecording.events" :key="event.id"
+ class="bg-[var(--bg-tertiary)] rounded-lg p-4 border border-[var(--border-primary)] hover:border-[var(--border-accent)] transition-colors">
+ <div class="flex justify-between items-start mb-3">
+ <div class="flex-1">
+ <h3 class="text-lg font-semibold text-[var(--text-primary)] mb-1">
+ <i class="fas fa-calendar-check mr-2 text-[var(--text-accent)]"></i>
+ ${ event.title }
+ </h3>
+ <p v-if="event.description" class="text-sm text-[var(--text-secondary)] mb-2">
+ ${ event.description }
+ </p>
+ </div>
+ <button @click="downloadEventICS(event)"
+ 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-1.5"
+ :title="t('events.addToCalendar')">
+ <i class="fas fa-download"></i>
+ <span v-text="t('events.addToCalendar')"></span>
+ </button>
+ </div>
+
+ <div class="space-y-2 text-sm">
+ <div class="flex items-center gap-2" v-if="event.start_datetime">
+ <i class="fas fa-clock text-[var(--text-muted)] w-4"></i>
+ <span class="text-[var(--text-secondary)]">
+ <strong v-text="t('events.start') + ':'"></strong> ${ formatEventDateTime(event.start_datetime) }
+ </span>
+ </div>
+ <div class="flex items-center gap-2" v-if="event.end_datetime">
+ <i class="fas fa-clock text-[var(--text-muted)] w-4"></i>
+ <span class="text-[var(--text-secondary)]">
+ <strong v-text="t('events.end') + ':'"></strong> ${ formatEventDateTime(event.end_datetime) }
+ </span>
+ </div>
+ <div class="flex items-center gap-2" v-if="event.location">
+ <i class="fas fa-map-marker-alt text-[var(--text-muted)] w-4"></i>
+ <span class="text-[var(--text-secondary)]">
+ <strong v-text="t('events.location') + ':'"></strong> ${ event.location }
+ </span>
+ </div>
+ <div class="flex items-start gap-2" v-if="event.attendees && event.attendees.length > 0">
+ <i class="fas fa-users text-[var(--text-muted)] w-4 mt-0.5"></i>
+ <div class="text-[var(--text-secondary)]">
+ <strong v-text="t('events.attendees') + ':'"></strong>
+ <span class="ml-1">${ event.attendees.join(', ') }</span>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div v-if="selectedRecording.events.length === 0" class="text-center py-8">
+ <i class="fas fa-calendar-times text-3xl text-[var(--text-muted)] mb-3"></i>
+ <p class="text-[var(--text-muted)]" v-text="t('events.noEvents')"></p>
+ </div>
+ </div>
+</div>
diff --git a/templates/components/detail/desktop-header.html b/templates/components/detail/desktop-header.html
new file mode 100644
index 00000000..d6b00c17
--- /dev/null
+++ b/templates/components/detail/desktop-header.html
@@ -0,0 +1,180 @@
+<!-- Desktop Recording Header -->
+<div class="bg-[var(--bg-secondary)] border-b border-[var(--border-primary)] p-6 flex-shrink-0">
+ <div class="flex flex-col">
+ <div class="flex items-start justify-between">
+ <div class="flex-1 min-w-0">
+ <div class="flex items-center gap-2 mb-2">
+ <h1 v-if="!editingTitle"
+ @dblclick="selectedRecording.can_edit !== false ? toggleEditTitle() : null"
+ :class="[
+ 'text-2xl font-bold truncate transition-opacity',
+ selectedRecording.is_shared ? 'text-[var(--text-accent)]' : 'text-[var(--text-primary)]',
+ selectedRecording.can_edit !== false ? 'cursor-text hover:opacity-80' : ''
+ ]"
+ :title="selectedRecording.can_edit !== false ? 'Double-click to edit' : selectedRecording.title || 'Untitled Recording'">
+ ${selectedRecording.title || 'Untitled Recording'}
+ </h1>
+ <input v-else
+ v-model="selectedRecording.title"
+ @blur="saveTitle"
+ @keyup.enter="saveTitle"
+ @keyup.esc="cancelEditTitle"
+ ref="titleInput"
+ class="text-2xl font-bold bg-transparent border-b-2 border-[var(--border-focus)] focus:outline-none text-[var(--text-primary)] flex-1 px-1"
+ placeholder="Untitled Recording">
+
+ <button v-if="!editingTitle && selectedRecording.can_edit !== false"
+ @click="toggleEditTitle"
+ class="p-1 text-[var(--text-muted)] hover:text-[var(--text-accent)] transition-colors opacity-60 hover:opacity-100 flex-shrink-0"
+ :title="'Edit title'">
+ <i class="fas fa-pen text-sm"></i>
+ </button>
+
+ <!-- Status Badge (for non-completed recordings) -->
+ <span v-if="!editingTitle && selectedRecording.status !== 'COMPLETED'"
+ :class="getStatusClass(selectedRecording.status)"
+ class="inline-flex items-center px-2.5 py-0.5 text-xs font-medium rounded-full whitespace-nowrap flex-shrink-0">
+ ${formatStatus(selectedRecording.status)}
+ </span>
+ </div>
+ </div>
+
+ <!-- Action Buttons -->
+ <div class="flex items-center gap-2 ml-4">
+ <button @click="toggleInbox(selectedRecording)"
+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"
+ :class="selectedRecording.is_inbox ? 'text-blue-500' : ''"
+ :title="selectedRecording.is_inbox ? 'Mark as Read' : 'Move to Inbox'">
+ <i class="fas fa-inbox"></i>
+ </button>
+ <button @click="toggleHighlight(selectedRecording)"
+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"
+ :class="selectedRecording.is_highlighted ? 'text-yellow-500' : ''"
+ :title="selectedRecording.is_highlighted ? 'Remove Highlight' : 'Highlight'">
+ <i class="fas fa-star"></i>
+ </button>
+ <button @click="editRecordingTags(selectedRecording)"
+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"
+ :title="t('buttons.editTags')">
+ <i class="fas fa-tags"></i>
+ </button>
+ <button @click="confirmReprocess('transcription', selectedRecording)" v-if="selectedRecording && selectedRecording.can_edit !== false && (selectedRecording.status === 'COMPLETED' || selectedRecording.status === 'FAILED')"
+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"
+ :title="useAsrEndpoint ? 'Reprocess with ASR' : 'Reprocess transcription'">
+ <i class="fas fa-redo-alt"></i>
+ </button>
+ <button @click="confirmReprocess('summary', selectedRecording)" v-if="selectedRecording && selectedRecording.can_edit !== false && (selectedRecording.status === 'COMPLETED' || selectedRecording.status === 'FAILED')"
+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"
+ :title="t('buttons.reprocessSummary')">
+ <i class="fas fa-sync-alt"></i>
+ </button>
+ <button @click="confirmReset(selectedRecording)" v-if="['PENDING', 'PROCESSING', 'SUMMARIZING', 'FAILED'].includes(selectedRecording.status)"
+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors text-orange-500"
+ :title="t('buttons.resetStuckProcessing')">
+ <i class="fas fa-undo"></i>
+ </button>
+ <button @click="openSpeakerModal" v-if="selectedRecording.transcription && useAsrEndpoint"
+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"
+ :title="t('buttons.identifySpeakers')">
+ <i class="fas fa-user-tag"></i>
+ </button>
+ <button v-if="!selectedRecording.is_shared || (selectedRecording.share_info && selectedRecording.share_info.can_reshare)"
+ @click="openUnifiedShareModal(selectedRecording)"
+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"
+ :title="t('buttons.shareRecording')">
+ <i class="fas fa-share-alt"></i>
+ </button>
+ <button v-if="canDeleteRecordings && selectedRecording.can_delete !== false" @click="confirmDelete(selectedRecording)"
+ class="p-2 rounded-lg hover:bg-[var(--bg-danger-light)] text-[var(--text-danger)] transition-colors">
+ <i class="fas fa-trash"></i>
+ </button>
+ </div>
+ </div>
+
+ <!-- Metadata Row -->
+ <div class="flex flex-wrap items-center gap-x-6 gap-y-2 text-sm text-[var(--text-muted)] mt-2">
+ <!-- Shared Status Badges and Tags -->
+ <div v-if="selectedRecording.is_shared || selectedRecording.shared_with_count > 0 || selectedRecording.public_share_count > 0 || selectedRecording.has_group_tags || (selectedRecording.tags && selectedRecording.tags.length > 0)" class="flex items-center gap-1.5 flex-wrap">
+ <!-- Shared by someone else (INCOMING) -->
+ <span v-if="selectedRecording.is_shared"
+ class="inline-flex items-center justify-center w-5 h-5 text-[10px] font-medium rounded-full bg-purple-500 text-white cursor-help"
+ :title="t('sharing.sharedBy') + ' ' + (selectedRecording.owner_username || t('sharing.unknown'))">
+ <i class="fas fa-arrow-down" style="vertical-align: middle; line-height: 0;"></i>
+ </span>
+
+ <!-- Group indicator (show for both owned and shared recordings with group tags) -->
+ <span v-if="selectedRecording.has_group_tags"
+ class="inline-flex items-center justify-center w-5 h-5 text-[10px] font-medium rounded-full bg-blue-500 text-white cursor-help"
+ :title="t('sharing.teamRecording')">
+ <i class="fas fa-users" style="vertical-align: middle; line-height: 0;"></i>
+ </span>
+
+ <!-- Shared with others (OUTGOING) -->
+ <span v-if="!selectedRecording.is_shared && selectedRecording.shared_with_count > 0"
+ class="inline-flex items-center justify-center w-5 h-5 text-[10px] font-medium rounded-full bg-indigo-500 text-white cursor-help"
+ :title="t('sharing.sharedWith') + ' ' + selectedRecording.shared_with_count + ' ' + t('sharing.users')">
+ <i class="fas fa-arrow-up" style="vertical-align: middle; line-height: 0;"></i>
+ </span>
+
+ <!-- Public link shares -->
+ <span v-if="!selectedRecording.is_shared && selectedRecording.public_share_count > 0"
+ class="inline-flex items-center justify-center w-5 h-5 text-[10px] font-medium rounded-full bg-teal-500 text-white cursor-help"
+ :title="selectedRecording.public_share_count + ' ' + t('sharing.publicLinksGenerated')">
+ <i class="fas fa-globe" style="vertical-align: middle; line-height: 0;"></i>
+ </span>
+
+ <!-- Tags -->
+ <span v-for="tag in selectedRecording.tags" :key="tag.id"
+ class="inline-flex items-center px-2 py-0.5 text-xs font-medium rounded-full cursor-help"
+ :style="{ backgroundColor: tag.color || '#6B7280', color: getContrastTextColor(tag.color || '#6B7280') }"
+ :title="tag.group_id ? ('Group: ' + tag.group_name) : tag.name">
+ <i v-if="tag.group_id" class="fas fa-users mr-1 text-[10px]" style="vertical-align: middle; line-height: 0;"></i>
+ ${tag.name}
+ </span>
+ </div>
+
+ <!-- Participants -->
+ <div class="flex items-center gap-2">
+ <i class="fas fa-users text-[var(--text-accent)]"></i>
+ <span @click="openParticipantsModal"
+ class="cursor-pointer hover:text-[var(--text-accent)] transition-colors max-w-[300px] truncate inline-block"
+ :title="selectedRecording.participants || t('help.noParticipants')">
+ ${selectedRecording.participants || t('help.noParticipants')}
+ </span>
+ </div>
+
+ <!-- Owner (for shared recordings) -->
+ <div v-if="selectedRecording.is_shared" class="flex items-center gap-2">
+ <i class="fas fa-user text-[var(--text-accent)]"></i>
+ <span class="max-w-[300px] truncate inline-block"
+ :title="'Owner: ' + (selectedRecording.owner_username || t('sharing.unknown'))">
+ ${selectedRecording.owner_username || t('sharing.unknown')}
+ </span>
+ </div>
+
+ <!-- Meeting Date -->
+ <div class="flex items-center gap-2">
+ <i class="fas fa-calendar text-[var(--text-accent)]"></i>
+ <span v-if="!editingMeetingDate"
+ @click="toggleEditMeetingDate"
+ class="cursor-pointer hover:text-[var(--text-accent)] transition-colors">
+ ${selectedRecording.meeting_date ? formatDisplayDate(selectedRecording.meeting_date) : 'No date set'}
+ </span>
+ <input v-else
+ v-model="selectedRecording.meeting_date"
+ @blur="toggleEditMeetingDate"
+ @keyup.enter="toggleEditMeetingDate"
+ type="date"
+ class="bg-transparent border-b border-[var(--border-secondary)] focus:border-[var(--border-focus)] outline-none px-1">
+ </div>
+
+ <!-- Other Metadata -->
+ <div v-if="activeRecordingMetadata && activeRecordingMetadata.length > 0" class="flex flex-wrap items-center gap-x-6 gap-y-2">
+ <span v-for="(item, index) in activeRecordingMetadata" :key="index" class="flex items-center gap-1.5">
+ <i :class="item.icon"></i>
+ <span :title="item.fullText || item.text">${item.text}</span>
+ </span>
+ </div>
+ </div>
+ </div>
+</div>
diff --git a/templates/components/detail/desktop-notes-tab.html b/templates/components/detail/desktop-notes-tab.html
new file mode 100644
index 00000000..0aed304b
--- /dev/null
+++ b/templates/components/detail/desktop-notes-tab.html
@@ -0,0 +1,57 @@
+<!-- Desktop 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-4 flex gap-1 z-10">
+ <button @click="copyNotes"
+ :title="t('buttons.copyNotes')"
+ 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="t('buttons.downloadNotes')"
+ 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="t('buttons.editNotes')"
+ 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>
+
+ <div v-if="!editingNotes"
+ class="notes-box h-full"
+ @click="clickToEditNotes">
+ <div v-if="selectedRecording.notes_html"
+ v-html="selectedRecording.notes_html">
+ </div>
+ <div v-else-if="selectedRecording.notes"
+ class="whitespace-pre-wrap">
+ ${selectedRecording.notes}
+ </div>
+ <div v-else class="text-[var(--text-muted)] italic cursor-pointer hover:text-[var(--text-secondary)]">
+ ${ t('help.clickToAddNotes') }
+ </div>
+ </div>
+
+ <div v-else class="h-full flex flex-col">
+ <div class="markdown-editor-container flex-1">
+ <textarea ref="notesMarkdownEditor"
+ v-model="selectedRecording.notes"
+ class="w-full h-full p-4 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]"
+ :placeholder="t('form.enterNotesMarkdown')">
+ </textarea>
+ </div>
+ <div class="flex justify-end gap-2 mt-2">
+ <button @click="cancelEditNotes"
+ class="px-3 py-1 text-sm bg-[var(--bg-secondary)] text-[var(--text-secondary)] border border-[var(--border-secondary)] rounded hover:bg-[var(--bg-tertiary)]">
+ Cancel
+ </button>
+ <button @click="saveEditNotes"
+ class="px-3 py-1 text-sm bg-[var(--bg-button)] text-[var(--text-button)] rounded hover:bg-[var(--bg-button-hover)]">
+ Save
+ </button>
+ </div>
+ </div>
+ </div>
+</div>
diff --git a/templates/components/detail/desktop-right-panel.html b/templates/components/detail/desktop-right-panel.html
new file mode 100644
index 00000000..ac56a60c
--- /dev/null
+++ b/templates/components/detail/desktop-right-panel.html
@@ -0,0 +1,71 @@
+<!-- Desktop Right Panel (Summary/Notes/Chat) -->
+<div id="rightMainColumn" class="flex flex-col overflow-hidden" :style="{width: rightColumnWidth + '%'}">
+ <!-- Audio Player -->
+ <div class="bg-[var(--bg-secondary)] p-4 border-b border-[var(--border-primary)] flex-shrink-0">
+ <div class="audio-player-container">
+ <!-- Show message if audio has been deleted -->
+ <div v-if="selectedRecording.audio_deleted_at"
+ class="bg-[var(--bg-tertiary)] border border-[var(--border-primary)] text-[var(--text-muted)] px-4 py-3 rounded-lg flex items-center gap-2 text-sm">
+ <i class="fas fa-info-circle"></i>
+ <span v-text="t('help.audioDeletedMessage')"></span>
+ </div>
+ <!-- Show audio player if audio is available -->
+ <audio v-else
+ ref="audioPlayerElement"
+ controls
+ :src="'/audio/' + selectedRecording.id"
+ :volume="playerVolume"
+ @volumechange="onPlayerVolumeChange"
+ @timeupdate="handleAudioTimeUpdate"
+ class="w-full">
+ Your browser does not support the audio element.
+ </audio>
+ </div>
+ </div>
+
+ <!-- Summary/Notes Tabs -->
+ <div :class="{'flex-1': !isChatMaximized, 'flex-none': isChatMaximized}" class="flex flex-col overflow-hidden">
+ <!-- Tab Navigation -->
+ <div class="bg-[var(--bg-tertiary)] border-b border-[var(--border-primary)] flex">
+ <button @click="selectedTab = 'summary'"
+ :class="[
+ 'flex-1 px-4 py-3 text-sm font-medium transition-colors',
+ selectedTab === 'summary'
+ ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]'
+ : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]'
+ ]">
+ ${ t('summary.title') }
+ </button>
+ <button @click="selectedTab = 'notes'"
+ :class="[
+ 'flex-1 px-4 py-3 text-sm font-medium transition-colors',
+ selectedTab === 'notes'
+ ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]'
+ : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]'
+ ]">
+ ${ t('notes.title') }
+ </button>
+ <button v-if="selectedRecording.events && selectedRecording.events.length > 0"
+ @click="selectedTab = 'events'"
+ :class="[
+ 'flex-1 px-4 py-3 text-sm font-medium transition-colors',
+ selectedTab === 'events'
+ ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]'
+ : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]'
+ ]">
+ <i class="fas fa-calendar-alt mr-1"></i>
+ ${ t('events.title') } (${ selectedRecording.events.length })
+ </button>
+ </div>
+
+ <!-- Tab Content -->
+ <div v-if="!isChatMaximized" class="flex-1 overflow-hidden">
+ {% include 'components/detail/desktop-summary-tab.html' %}
+ {% include 'components/detail/desktop-notes-tab.html' %}
+ {% include 'components/detail/desktop-events-tab.html' %}
+ </div>
+ </div>
+
+ <!-- Chat Section -->
+ {% include 'components/detail/desktop-chat-section.html' %}
+</div>
diff --git a/templates/components/detail/desktop-summary-tab.html b/templates/components/detail/desktop-summary-tab.html
new file mode 100644
index 00000000..641e2cdf
--- /dev/null
+++ b/templates/components/detail/desktop-summary-tab.html
@@ -0,0 +1,60 @@
+<!-- Desktop Summary Tab -->
+<div v-if="selectedTab === 'summary'" class="h-full p-4 overflow-y-auto">
+ <div v-if="selectedRecording.status === 'SUMMARIZING'" class="text-center py-8">
+ <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
+ <p class="mt-2 text-[var(--text-muted)]" v-text="t('summary.summaryInProgress')"></p>
+ </div>
+
+ <div v-else-if="!selectedRecording.summary" class="text-center py-8">
+ <i class="fas fa-file-alt text-3xl text-[var(--text-muted)] mb-3"></i>
+ <p class="text-[var(--text-muted)] mb-4" v-text="t('summary.noSummary')"></p>
+ <button @click="generateSummary"
+ class="px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 text-white font-medium rounded-lg shadow-lg hover:shadow-xl hover:from-blue-700 hover:to-purple-700 transition-all duration-200 transform hover:scale-105">
+ <i class="fas fa-magic mr-2"></i>${ t('summary.generateSummary') }
+ </button>
+ </div>
+
+ <div v-else class="content-box relative">
+ <div v-if="!editingSummary" class="absolute top-2 right-4 flex gap-1 z-10">
+ <button @click="copySummary"
+ :title="t('buttons.copySummary')"
+ 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="t('buttons.downloadSummary')"
+ 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="t('buttons.editSummary')"
+ 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>
+
+ <div v-if="!editingSummary"
+ class="summary-box"
+ v-html="selectedRecording.summary_html || selectedRecording.summary">
+ </div>
+ <div v-else class="h-full flex flex-col">
+ <div class="markdown-editor-container flex-1">
+ <textarea ref="summaryMarkdownEditor"
+ v-model="selectedRecording.summary"
+ class="w-full h-full p-4 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]"
+ :placeholder="t('form.enterSummaryMarkdown')">
+ </textarea>
+ </div>
+ <div class="flex justify-end gap-2 mt-2">
+ <button @click="cancelEditSummary"
+ class="px-3 py-1 text-sm bg-[var(--bg-secondary)] text-[var(--text-secondary)] border border-[var(--border-secondary)] rounded hover:bg-[var(--bg-tertiary)]">
+ Cancel
+ </button>
+ <button @click="saveEditSummary"
+ class="px-3 py-1 text-sm bg-[var(--bg-button)] text-[var(--text-button)] rounded hover:bg-[var(--bg-button-hover)]">
+ Save
+ </button>
+ </div>
+ </div>
+ </div>
+</div>
diff --git a/templates/components/detail/desktop-transcription-panel.html b/templates/components/detail/desktop-transcription-panel.html
new file mode 100644
index 00000000..81199090
--- /dev/null
+++ b/templates/components/detail/desktop-transcription-panel.html
@@ -0,0 +1,164 @@
+<!-- Desktop Transcription Panel (Left Column) -->
+<div id="leftMainColumn" class="flex flex-col overflow-hidden" :style="{width: leftColumnWidth + '%'}">
+ <!-- Transcription Header -->
+ <div class="bg-[var(--bg-tertiary)] px-4 py-3 border-b border-[var(--border-primary)] flex items-center justify-between">
+ <h3 class="font-semibold flex items-center">
+ <i class="fas fa-file-text mr-2"></i>
+ <span v-text="t('transcription.title')"></span>
+ </h3>
+ <div class="flex items-center gap-2">
+ <!-- Follow Player Checkbox -->
+ <div v-if="processedTranscription.isJson && processedTranscription.hasDialogue"
+ class="follow-player-control text-[var(--text-muted)] hover:text-[var(--text-primary)]"
+ @click="toggleFollowPlayerMode"
+ :title="followPlayerMode ? t('tooltips.followPlayerEnabled') : t('tooltips.followPlayerDisabled')">
+ <input type="checkbox"
+ :checked="followPlayerMode"
+ @click.stop="toggleFollowPlayerMode">
+ <i class="fas fa-arrows-alt-v follow-icon"></i>
+ </div>
+
+ <!-- View Mode Toggle -->
+ <div v-if="processedTranscription.hasDialogue" class="view-mode-toggle">
+ <button @click="toggleTranscriptionViewMode"
+ :class="['toggle-button', transcriptionViewMode === 'simple' ? 'active' : '']">
+ <i class="fas fa-list"></i><span v-text="t('transcription.simple')"></span>
+ </button>
+ <button @click="toggleTranscriptionViewMode"
+ :class="['toggle-button', transcriptionViewMode === 'bubble' ? 'active' : '']">
+ <i class="fas fa-comments"></i><span v-text="t('transcription.bubble')"></span>
+ </button>
+ </div>
+
+ <!-- Copy Button -->
+ <button @click="copyTranscription"
+ class="copy-btn"
+ :title="t('tooltips.copyTranscript')">
+ <i class="fas fa-copy"></i>
+ </button>
+ <!-- Download Button with Dropdown -->
+ <div v-if="selectedRecording && selectedRecording.transcription" class="relative">
+ <button @click="showDownloadMenu = !showDownloadMenu"
+ class="copy-btn flex items-center"
+ :title="t('tooltips.downloadTranscriptWithTemplate')">
+ <i class="fas fa-download"></i>
+ <i class="fas fa-caret-down ml-1 text-[10px] opacity-50"></i>
+ </button>
+ <!-- Dropdown Menu -->
+ <div v-if="showDownloadMenu"
+ class="absolute right-0 top-full mt-1 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg shadow-lg z-50 overflow-hidden whitespace-nowrap">
+ <button @click="downloadWithDefaultTemplate(); showDownloadMenu = false"
+ class="w-full text-left px-3 py-1.5 text-xs hover:bg-[var(--bg-tertiary)] transition-colors flex items-center gap-2">
+ <i class="fas fa-star text-[var(--text-accent)] text-[10px]"></i>
+ <span v-text="t('transcriptTemplates.downloadDefault')"></span>
+ </button>
+ <button @click="showTemplateSelector(); showDownloadMenu = false"
+ class="w-full text-left px-3 py-1.5 text-xs hover:bg-[var(--bg-tertiary)] transition-colors flex items-center gap-2 border-t border-[var(--border-secondary)]">
+ <i class="fas fa-list text-[var(--text-muted)] text-[10px]"></i>
+ <span v-text="t('transcriptTemplates.chooseTemplate')"></span>
+ </button>
+ </div>
+ </div>
+ <!-- Click outside to close dropdown -->
+ <div v-if="showDownloadMenu" @click="showDownloadMenu = false" class="fixed inset-0 z-40"></div>
+ <!-- Edit Transcription Button -->
+ <button @click="openTranscriptionEditor"
+ v-if="selectedRecording && selectedRecording.transcription"
+ class="copy-btn"
+ :title="t('tooltips.editTranscript')">
+ <i class="fas fa-edit"></i>
+ </button>
+ </div>
+ </div>
+
+ <!-- Transcription Content -->
+ <div class="flex-1 overflow-y-auto p-4">
+ <div v-if="selectedRecording.status === 'PROCESSING'" class="text-center py-8">
+ <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
+ <p class="mt-2 text-[var(--text-muted)]" v-text="t('help.processingTranscription')"></p>
+ </div>
+
+ <div v-else-if="!selectedRecording.transcription" class="text-center py-8">
+ <i class="fas fa-file-text text-3xl text-[var(--text-muted)] mb-3"></i>
+ <p class="text-[var(--text-muted)]" v-text="t('transcription.noTranscription')"></p>
+ </div>
+
+ <!-- Speaker Legend (for dialogue transcriptions in bubble view only) -->
+ <div v-if="processedTranscription.hasDialogue && processedTranscription.speakers.length > 0 && transcriptionViewMode === 'bubble'"
+ :class="['speaker-legend', legendExpanded ? 'expanded' : '']">
+ <div class="speaker-legend-header" @click="legendExpanded = !legendExpanded">
+ <div class="speaker-legend-title">
+ <i class="fas fa-users"></i>
+ <span v-text="t('help.speakers')"></span>
+ <span class="speaker-count-indicator">(${processedTranscription.speakers.length})</span>
+ </div>
+ <i class="fas fa-chevron-down speaker-legend-toggle"></i>
+ </div>
+ <div class="speaker-legend-content">
+ <div v-for="(speaker, index) in processedTranscription.speakers"
+ :key="`${selectedRecording.id}-speaker-legend-${index}`"
+ :class="['speaker-legend-item', speaker.color]">
+ <span class="speaker-name">${speaker.name}</span>
+ </div>
+ </div>
+ </div>
+
+ <!-- Transcription Display -->
+ <div v-if="selectedRecording.transcription">
+ <!-- Simple View -->
+ <div v-if="!processedTranscription.hasDialogue || transcriptionViewMode === 'simple'"
+ class="transcription-simple-view">
+ <div v-if="processedTranscription.hasDialogue">
+ <div v-for="(segment, index) in processedTranscription.simpleSegments"
+ :key="segment.startTime || Math.random()"
+ :class="['speaker-segment', { 'active-playing-segment': currentPlayingSegmentIndex === index }]"
+ @click="seekAudioFromEvent"
+ :data-start-time="segment.startTime"
+ :data-segment-index="index">
+ <div v-if="segment.showSpeaker"
+ :class="['speaker-tablet', segment.color]">
+ ${segment.speaker}
+ </div>
+ <div class="speaker-text">
+ ${segment.sentence}
+ </div>
+ </div>
+ </div>
+ <div v-else>
+ <div v-if="processedTranscription.simpleSegments && processedTranscription.simpleSegments.length > 0">
+ <div v-for="(segment, index) in processedTranscription.simpleSegments"
+ :key="segment.startTime || Math.random()"
+ :class="['transcript-segment cursor-pointer hover:bg-[var(--bg-accent-hover)] p-2 rounded transition-colors', { 'active-playing-segment': currentPlayingSegmentIndex === index }]"
+ @click="seekAudioFromEvent"
+ :data-start-time="segment.startTime"
+ :data-segment-index="index">
+ ${segment.sentence}
+ </div>
+ </div>
+ <div v-else class="whitespace-pre-wrap">
+ ${processedTranscription.content}
+ </div>
+ </div>
+ </div>
+
+ <!-- Bubble View -->
+ <div v-else-if="transcriptionViewMode === 'bubble'"
+ class="transcription-with-speakers">
+ <template v-for="(row, rowIndex) in processedTranscription.bubbleRows" :key="`${selectedRecording.id}-bubble-row-${rowIndex}`">
+ <div :class="['bubble-row', row.isMe ? 'speaker-me' : '']">
+ <div v-for="(bubble, bubbleIndex) in row.bubbles"
+ :key="bubble.startTime || Math.random()"
+ :class="['speaker-bubble', bubble.color, row.isMe ? 'speaker-me' : '', { 'active-playing-segment': currentPlayingSegmentIndex === getBubbleGlobalIndex(rowIndex, bubbleIndex) }]"
+ @click="seekAudioFromEvent"
+ :data-start-time="bubble.startTime"
+ :data-segment-index="getBubbleGlobalIndex(rowIndex, bubbleIndex)">
+ <div class="speaker-bubble-content">
+ ${bubble.sentence}
+ </div>
+ </div>
+ </div>
+ </template>
+ </div>
+ </div>
+ </div>
+</div>
diff --git a/templates/components/detail/empty-state.html b/templates/components/detail/empty-state.html
new file mode 100644
index 00000000..69565e08
--- /dev/null
+++ b/templates/components/detail/empty-state.html
@@ -0,0 +1,12 @@
+<!-- Empty State -->
+<div v-if="currentView === 'detail' && !selectedRecording" class="flex-1 flex items-center justify-center">
+ <div class="text-center">
+ <i class="fas fa-microphone text-6xl text-[var(--text-muted)] mb-4"></i>
+ <h2 class="text-2xl font-bold mb-2" v-text="t('colorScheme.selectRecording')"></h2>
+ <p class="text-[var(--text-muted)] mb-6" v-text="t('colorScheme.chooseRecording')"></p>
+ <button @click="switchToUploadView"
+ class="px-6 py-3 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors">
+ <i class="fas fa-plus mr-2"></i>Upload New Recording
+ </button>
+ </div>
+</div>
diff --git a/templates/components/detail/mobile-chat-panel.html b/templates/components/detail/mobile-chat-panel.html
new file mode 100644
index 00000000..6041b986
--- /dev/null
+++ b/templates/components/detail/mobile-chat-panel.html
@@ -0,0 +1,55 @@
+<!-- Mobile Chat Panel -->
+<div v-if="mobileTab === 'chat'" class="h-full flex flex-col rounded-lg border border-[var(--border-primary)] overflow-hidden relative">
+ <!-- Clear button - fixed at top right -->
+ <button v-if="chatMessages.length > 0"
+ @click="clearChat"
+ class="absolute top-2 right-2 p-1 text-[var(--text-muted)] opacity-60 hover:opacity-100 hover:text-[var(--text-danger)] rounded transition-all duration-200 z-20"
+ title="Clear chat">
+ <i class="fas fa-times text-xs"></i>
+ </button>
+
+ <div ref="chatMessagesRef" class="flex-1 overflow-y-auto p-4 space-y-4 bg-[var(--bg-secondary)]">
+ <div v-if="chatMessages.length === 0" class="text-center py-8">
+ <i class="fas fa-robot text-3xl text-[var(--text-muted)] mb-3"></i>
+ <p class="text-[var(--text-muted)]" v-text="t('help.askAboutTranscription')"></p>
+ </div>
+ <div v-for="(message, index) in chatMessages" :key="index"
+ :class="['message relative group', message.role === 'user' ? 'user-message ml-auto' : 'ai-message',
+ message.role === 'assistant' ? 'pr-10' : '']">
+ <!-- Copy button for assistant messages -->
+ <button v-if="message.role === 'assistant'"
+ @click="copyMessage(message.content, $event)"
+ class="absolute top-2 right-2 p-1 text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-tertiary)] rounded transition-all duration-200"
+ :title="t('buttons.copyMessage')">
+ <i class="fas fa-copy text-sm"></i>
+ </button>
+ <!-- Show thinking content if available -->
+ <div v-if="message.thinking && message.role === 'assistant'" class="mb-2">
+ <button @click="message.thinkingExpanded = !message.thinkingExpanded"
+ class="text-xs text-[var(--text-muted)] hover:text-[var(--text-secondary)] flex items-center gap-1">
+ <i :class="['fas', message.thinkingExpanded ? 'fa-chevron-down' : 'fa-chevron-right']"></i>
+ <span v-text="t('help.modelReasoning')"></span>
+ <span class="text-[var(--text-muted)]">(${message.thinking.split('\n').length} lines)</span>
+ </button>
+ <div v-if="message.thinkingExpanded"
+ class="mt-2 p-3 bg-[var(--bg-tertiary)] border border-[var(--border-secondary)] rounded-lg text-xs text-[var(--text-muted)] max-h-64 overflow-y-auto">
+ <pre class="whitespace-pre-wrap font-mono">${message.thinking}</pre>
+ </div>
+ </div>
+ <!-- Main message content -->
+ <div v-if="message.html" v-html="message.html"></div>
+ <div v-else class="whitespace-pre-wrap">${message.content}</div>
+ </div>
+ <div v-if="isChatLoading" class="ai-message">
+ <i class="fas fa-spinner fa-spin mr-2"></i> Thinking...
+ </div>
+ </div>
+ <div class="border-t border-[var(--border-primary)] p-4 bg-[var(--bg-tertiary)]">
+ <div class="flex gap-2">
+ <textarea v-model="chatInput" @keydown="handleChatKeydown" :disabled="isChatLoading || selectedRecording.status !== 'COMPLETED'" :placeholder="t('chat.placeholder')" class="flex-1 px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)] text-sm" rows="2"></textarea>
+ <button @click="sendChatMessage" :disabled="!chatInput.trim() || isChatLoading || selectedRecording.status !== 'COMPLETED'" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
+ <i class="fas fa-paper-plane"></i>
+ </button>
+ </div>
+ </div>
+</div>
diff --git a/templates/components/detail/mobile-events-panel.html b/templates/components/detail/mobile-events-panel.html
new file mode 100644
index 00000000..3303cf03
--- /dev/null
+++ b/templates/components/detail/mobile-events-panel.html
@@ -0,0 +1,58 @@
+<!-- Mobile Events Panel -->
+<div v-if="mobileTab === 'events' && selectedRecording.events && selectedRecording.events.length > 0" class="h-full flex flex-col space-y-4">
+ <div class="flex items-center justify-end gap-2 flex-shrink-0 pr-3">
+ <button @click="downloadICS" v-if="selectedRecording.events && selectedRecording.events.length > 0"
+ class="copy-btn"
+ :title="t('buttons.exportCalendar')">
+ <i class="fas fa-calendar-plus"></i>
+ </button>
+ </div>
+ <div class="flex-grow overflow-y-auto mobile-content-box">
+ <div class="space-y-3">
+ <div v-for="event in selectedRecording.events" :key="event.id"
+ class="bg-[var(--bg-tertiary)] rounded-lg p-3 border border-[var(--border-primary)]">
+ <div class="flex justify-between items-start mb-2">
+ <div class="flex-1">
+ <h3 class="text-base font-semibold text-[var(--text-primary)] mb-1">
+ <i class="fas fa-calendar-check mr-2 text-[var(--text-accent)] text-sm"></i>
+ ${ event.title }
+ </h3>
+ <p v-if="event.description" class="text-xs text-[var(--text-secondary)] mb-2">
+ ${ event.description }
+ </p>
+ </div>
+ <button @click="downloadEventICS(event)"
+ class="px-2 py-1 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors text-xs flex items-center gap-1"
+ :title="t('events.addToCalendar')">
+ <i class="fas fa-download text-xs"></i>
+ <span v-text="t('events.add')"></span>
+ </button>
+ </div>
+ <div class="grid grid-cols-1 gap-2 text-xs">
+ <div class="flex items-center text-[var(--text-muted)]">
+ <i class="fas fa-clock mr-2 text-[var(--text-accent)]"></i>
+ <span>
+ ${ formatEventDateTime(event.start_datetime) }
+ <template v-if="event.end_datetime">
+ - ${ formatEventDateTime(event.end_datetime, true) }
+ </template>
+ </span>
+ </div>
+ <div v-if="event.location" class="flex items-center text-[var(--text-muted)]">
+ <i class="fas fa-map-marker-alt mr-2 text-[var(--text-accent)]"></i>
+ <span>${ event.location }</span>
+ </div>
+ <div v-if="event.attendees && event.attendees.length > 0" class="flex items-start text-[var(--text-muted)]">
+ <i class="fas fa-users mr-2 text-[var(--text-accent)] mt-0.5"></i>
+ <div class="flex-1">
+ <span v-for="(attendee, index) in event.attendees" :key="index"
+ class="inline-block bg-[var(--bg-secondary)] px-2 py-0.5 rounded mr-1 mb-1">
+ ${ attendee }
+ </span>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+</div>
diff --git a/templates/components/detail/mobile-header.html b/templates/components/detail/mobile-header.html
new file mode 100644
index 00000000..90670f45
--- /dev/null
+++ b/templates/components/detail/mobile-header.html
@@ -0,0 +1,107 @@
+<!-- Mobile Header for Detail View -->
+<div class="bg-[var(--bg-secondary)] border-b border-[var(--border-primary)] p-4 flex-shrink-0">
+ <div @click="isMetadataExpanded = !isMetadataExpanded" class="cursor-pointer">
+ <div class="flex items-center justify-between gap-3">
+ <div class="flex-1 min-w-0">
+ <div class="flex items-center gap-1.5 mb-1">
+ <h1 v-if="!editingTitle"
+ @dblclick.stop="selectedRecording.can_edit !== false ? toggleEditTitle() : null"
+ :class="[
+ 'text-lg font-bold truncate',
+ selectedRecording.is_shared ? 'text-[var(--text-accent)]' : 'text-[var(--text-primary)]',
+ selectedRecording.can_edit !== false ? 'cursor-text hover:opacity-80 transition-opacity' : ''
+ ]"
+ :title="selectedRecording.can_edit !== false ? 'Double-click to edit' : selectedRecording.title || 'Untitled Recording'">
+ ${selectedRecording.title || 'Untitled Recording'}
+ </h1>
+ <input v-else
+ v-model="selectedRecording.title"
+ @blur="saveTitle"
+ @keyup.enter="saveTitle"
+ @keyup.esc="cancelEditTitle"
+ @click.stop
+ ref="titleInput"
+ class="text-lg font-bold bg-transparent border-b-2 border-[var(--border-focus)] focus:outline-none text-[var(--text-primary)] flex-1 px-1"
+ placeholder="Untitled Recording">
+
+ <button v-if="!editingTitle && selectedRecording.can_edit !== false"
+ @click.stop="toggleEditTitle"
+ class="p-1.5 text-[var(--text-muted)] hover:text-[var(--text-accent)] transition-colors flex-shrink-0">
+ <i class="fas fa-pen text-xs"></i>
+ </button>
+
+ <!-- Status Badge (for non-completed recordings) -->
+ <span v-if="!editingTitle && selectedRecording.status !== 'COMPLETED'"
+ :class="getStatusClass(selectedRecording.status)"
+ class="inline-flex items-center px-2 py-0.5 text-xs font-medium rounded-full whitespace-nowrap flex-shrink-0">
+ ${formatStatus(selectedRecording.status)}
+ </span>
+ </div>
+ <p class="text-sm text-[var(--text-muted)] truncate">
+ ${selectedRecording.participants || t('help.noParticipants')}
+ </p>
+ <!-- Tags and Share Status -->
+ <div v-if="getRecordingTags(selectedRecording).length > 0 || selectedRecording.is_shared || selectedRecording.shared_with_count > 0 || selectedRecording.public_share_count > 0" class="flex flex-wrap gap-1 mt-2">
+ <button v-for="tag in getRecordingTags(selectedRecording)" :key="tag.id"
+ @click.stop="filterByTag(tag)"
+ class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium hover:opacity-80 transition-all cursor-pointer"
+ :style="{ backgroundColor: tag.color, color: getContrastTextColor(tag.color) }"
+ :title="tag.group_id ? ('Group: ' + tag.group_name) : tag.name">
+ <i v-if="tag.group_id" class="fas fa-users mr-1" style="vertical-align: middle; line-height: 0;"></i>
+ <i v-else class="fas fa-tag mr-1" style="vertical-align: middle; line-height: 0;"></i>
+ <span v-text="tag.name"></span>
+ </button>
+ <span v-if="selectedRecording.is_shared" class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-purple-500 text-white">
+ <i class="fas fa-arrow-down mr-1"></i>Shared
+ </span>
+ <span v-if="!selectedRecording.is_shared && selectedRecording.shared_with_count > 0" class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-indigo-500 text-white">
+ <i class="fas fa-arrow-up mr-1"></i>${selectedRecording.shared_with_count}
+ </span>
+ <span v-if="!selectedRecording.is_shared && selectedRecording.public_share_count > 0" class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-teal-500 text-white">
+ <i class="fas fa-globe mr-1"></i>${selectedRecording.public_share_count}
+ </span>
+ </div>
+ </div>
+ <!-- Expand/Collapse Button -->
+ <button @click.stop="isMetadataExpanded = !isMetadataExpanded"
+ class="flex items-center justify-center w-8 h-8 rounded-lg bg-[var(--bg-tertiary)] text-[var(--text-muted)] hover:bg-[var(--bg-accent-hover)] hover:text-[var(--text-accent)] transition-colors flex-shrink-0">
+ <i :class="['fas', 'fa-chevron-down', 'text-sm', 'transition-transform', { 'rotate-180': isMetadataExpanded }]"></i>
+ </button>
+ </div>
+ </div>
+ <!-- Expandable Metadata and Actions -->
+ <div v-if="isMetadataExpanded" class="mt-4 space-y-4">
+ <div class="space-y-2 text-sm text-[var(--text-muted)]">
+ <div class="flex flex-wrap items-center gap-x-4 gap-y-2">
+ <div class="flex items-center gap-2">
+ <i class="fas fa-calendar text-[var(--text-accent)]"></i>
+ <span>${selectedRecording.meeting_date ? formatDisplayDate(selectedRecording.meeting_date) : 'No date set'}</span>
+ </div>
+ <div v-if="selectedRecording.is_shared" class="flex items-center gap-2">
+ <i class="fas fa-user text-[var(--text-accent)]"></i>
+ <span :title="'Owner: ' + (selectedRecording.owner_username || t('sharing.unknown'))">
+ ${selectedRecording.owner_username || t('sharing.unknown')}
+ </span>
+ </div>
+ <template v-if="activeRecordingMetadata" v-for="(item, index) in activeRecordingMetadata" :key="index">
+ <span v-if="!item.isTagItem" class="flex items-center gap-1.5">
+ <i :class="item.icon"></i>
+ <span :title="item.fullText || item.text">${item.text}</span>
+ </span>
+ </template>
+ </div>
+ </div>
+ <!-- Action Buttons -->
+ <div class="flex items-center gap-2 overflow-x-auto pb-2">
+ <button @click="toggleInbox(selectedRecording)" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors" :class="selectedRecording.is_inbox ? 'text-blue-500' : ''"><i class="fas fa-inbox"></i></button>
+ <button @click="toggleHighlight(selectedRecording)" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors" :class="selectedRecording.is_highlighted ? 'text-yellow-500' : ''"><i class="fas fa-star"></i></button>
+ <button @click="editRecordingTags(selectedRecording)" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"><i class="fas fa-tags"></i></button>
+ <button @click="confirmReprocess('transcription', selectedRecording)" v-if="selectedRecording && selectedRecording.can_edit !== false && (selectedRecording.status === 'COMPLETED' || selectedRecording.status === 'FAILED')" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"><i class="fas fa-redo-alt"></i></button>
+ <button @click="confirmReprocess('summary', selectedRecording)" v-if="selectedRecording && selectedRecording.can_edit !== false && (selectedRecording.status === 'COMPLETED' || selectedRecording.status === 'FAILED')" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"><i class="fas fa-sync-alt"></i></button>
+ <button @click="confirmReset(selectedRecording)" v-if="['PENDING', 'PROCESSING', 'SUMMARIZING', 'FAILED'].includes(selectedRecording.status)" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors text-orange-500"><i class="fas fa-undo"></i></button>
+ <button @click="openSpeakerModal" v-if="selectedRecording.transcription && useAsrEndpoint" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"><i class="fas fa-user-tag"></i></button>
+ <button v-if="!selectedRecording.is_shared || (selectedRecording.share_info && selectedRecording.share_info.can_reshare)" @click="openUnifiedShareModal(selectedRecording)" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"><i class="fas fa-share-alt"></i></button>
+ <button v-if="canDeleteRecordings && selectedRecording.can_delete !== false" @click="confirmDelete(selectedRecording)" class="p-2 rounded-lg hover:bg-[var(--bg-danger-light)] text-[var(--text-danger)] transition-colors"><i class="fas fa-trash"></i></button>
+ </div>
+ </div>
+</div>
diff --git a/templates/components/detail/mobile-notes-panel.html b/templates/components/detail/mobile-notes-panel.html
new file mode 100644
index 00000000..52152463
--- /dev/null
+++ b/templates/components/detail/mobile-notes-panel.html
@@ -0,0 +1,26 @@
+<!-- Mobile 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 pr-3">
+ <button @click="copyNotes" class="copy-btn" :title="t('buttons.copyNotes')"><i class="fas fa-copy"></i></button>
+ <button @click="downloadNotes" class="copy-btn" :title="t('buttons.downloadAsWord')"><i class="fas fa-download"></i></button>
+ <button @click="toggleEditNotes" class="copy-btn" :title="t('buttons.editNotes')"><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">
+ <div class="markdown-editor-container flex-1">
+ <textarea ref="notesMarkdownEditor" v-model="selectedRecording.notes"></textarea>
+ </div>
+ <div class="flex justify-end gap-2 mt-2">
+ <button @click="cancelEditNotes" class="px-3 py-1 text-sm bg-[var(--bg-secondary)] text-[var(--text-secondary)] border border-[var(--border-secondary)] rounded hover:bg-[var(--bg-tertiary)]" v-text="t('common.cancel')"></button>
+ <button @click="saveEditNotes" class="px-3 py-1 text-sm bg-[var(--bg-button)] text-[var(--text-button)] border border-transparent rounded hover:bg-[var(--bg-button-hover)]" v-text="t('common.save')"></button>
+ </div>
+ </div>
+ <div v-else @click="clickToEditNotes">
+ <div v-if="!selectedRecording.notes" class="text-center py-8 cursor-pointer hover:text-[var(--text-secondary)]">
+ <i class="fas fa-sticky-note text-3xl text-[var(--text-muted)] mb-3"></i>
+ <p class="text-[var(--text-muted)]" v-text="t('help.clickToAddNotes')"></p>
+ </div>
+ <div v-else class="notes-box h-full" v-html="selectedRecording.notes_html || selectedRecording.notes"></div>
+ </div>
+ </div>
+</div>
diff --git a/templates/components/detail/mobile-summary-panel.html b/templates/components/detail/mobile-summary-panel.html
new file mode 100644
index 00000000..9dff67ab
--- /dev/null
+++ b/templates/components/detail/mobile-summary-panel.html
@@ -0,0 +1,34 @@
+<!-- Mobile 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 pr-3">
+ <button @click="copySummary" class="copy-btn" :title="t('buttons.copySummary')"><i class="fas fa-copy"></i></button>
+ <button @click="downloadSummary" class="copy-btn" :title="t('buttons.downloadAsWord')"><i class="fas fa-download"></i></button>
+ <button @click="toggleEditSummary" class="copy-btn" :title="t('buttons.editSummary')"><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">
+ <div class="markdown-editor-container flex-1">
+ <textarea ref="summaryMarkdownEditor" v-model="selectedRecording.summary"></textarea>
+ </div>
+ <div class="flex justify-end gap-2 mt-2">
+ <button @click="cancelEditSummary" class="px-3 py-1 text-sm bg-[var(--bg-secondary)] text-[var(--text-secondary)] border border-[var(--border-secondary)] rounded hover:bg-[var(--bg-tertiary)]" v-text="t('common.cancel')"></button>
+ <button @click="saveEditSummary" class="px-3 py-1 text-sm bg-[var(--bg-button)] text-[var(--text-button)] border border-transparent rounded hover:bg-[var(--bg-button-hover)]" v-text="t('common.save')"></button>
+ </div>
+ </div>
+ <div v-else>
+ <div v-if="selectedRecording.status === 'SUMMARIZING'" class="text-center py-8">
+ <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
+ <p class="mt-2 text-[var(--text-muted)]" v-text="t('help.generatingSummary')"></p>
+ </div>
+ <div v-else-if="!selectedRecording.summary" class="text-center py-8">
+ <i class="fas fa-file-alt text-3xl text-[var(--text-muted)] mb-3"></i>
+ <p class="text-[var(--text-muted)] mb-4" v-text="t('summary.noSummary')"></p>
+ <button @click="generateSummary"
+ class="px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 text-white font-medium rounded-lg shadow-lg hover:shadow-xl hover:from-blue-700 hover:to-purple-700 transition-all duration-200 transform hover:scale-105">
+ <i class="fas fa-magic mr-2"></i>Generate Summary
+ </button>
+ </div>
+ <div v-else class="summary-box h-full" v-html="selectedRecording.summary_html || selectedRecording.summary"></div>
+ </div>
+ </div>
+</div>
diff --git a/templates/components/detail/mobile-transcript-panel.html b/templates/components/detail/mobile-transcript-panel.html
new file mode 100644
index 00000000..be1918b5
--- /dev/null
+++ b/templates/components/detail/mobile-transcript-panel.html
@@ -0,0 +1,59 @@
+<!-- Mobile Transcript Panel -->
+<div v-if="mobileTab === 'transcript'" class="h-full flex flex-col space-y-4">
+ <div class="flex items-center justify-between gap-2 flex-shrink-0 px-3">
+ <!-- Follow Player Checkbox -->
+ <div v-if="processedTranscription.isJson && processedTranscription.hasDialogue"
+ class="follow-player-control text-[var(--text-muted)]"
+ @click="toggleFollowPlayerMode"
+ :title="followPlayerMode ? t('tooltips.followPlayerEnabled') : t('tooltips.followPlayerDisabled')">
+ <input type="checkbox"
+ :checked="followPlayerMode"
+ @click.stop="toggleFollowPlayerMode">
+ <i class="fas fa-arrows-alt-v follow-icon"></i>
+ </div>
+ <div class="flex items-center gap-2">
+ <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>
+ </div>
+ <button @click="copyTranscription" class="copy-btn" :title="t('tooltips.copyTranscript')"><i class="fas fa-copy"></i></button>
+ <button @click="downloadTranscript" v-if="selectedRecording && selectedRecording.transcription" class="copy-btn" :title="t('tooltips.downloadTranscriptWithTemplate')"><i class="fas fa-download"></i></button>
+ <button @click="openTranscriptionEditor" v-if="selectedRecording && selectedRecording.transcription" class="copy-btn" :title="t('tooltips.editTranscript')"><i class="fas fa-edit"></i></button>
+ </div>
+ </div>
+ <div class="flex-grow overflow-y-auto mobile-content-box">
+ <div v-if="selectedRecording.status === 'PROCESSING'" class="text-center py-8">
+ <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
+ <p class="mt-2 text-[var(--text-muted)]" v-text="t('help.processingTranscription')"></p>
+ </div>
+ <div v-else-if="!selectedRecording.transcription" class="text-center py-8">
+ <i class="fas fa-file-text text-3xl text-[var(--text-muted)] mb-3"></i>
+ <p class="text-[var(--text-muted)]" v-text="t('transcription.noTranscription')"></p>
+ </div>
+ <div v-else>
+ <div v-if="!processedTranscription.hasDialogue || transcriptionViewMode === 'simple'" class="transcription-simple-view">
+ <div v-if="processedTranscription.hasDialogue">
+ <div v-for="(segment, index) in processedTranscription.simpleSegments" :key="segment.startTime || Math.random()" :class="['speaker-segment', { 'active-playing-segment': currentPlayingSegmentIndex === index }]" @click="seekAudioFromEvent" :data-start-time="segment.startTime" :data-segment-index="index">
+ <div v-if="segment.showSpeaker" :class="['speaker-tablet', segment.color]">${segment.speaker}</div>
+ <div class="speaker-text">${segment.sentence}</div>
+ </div>
+ </div>
+ <div v-else>
+ <div v-if="processedTranscription.simpleSegments && processedTranscription.simpleSegments.length > 0">
+ <div v-for="(segment, index) in processedTranscription.simpleSegments" :key="segment.startTime || Math.random()" :class="['transcript-segment cursor-pointer hover:bg-[var(--bg-accent-hover)] p-2 rounded transition-colors', { 'active-playing-segment': currentPlayingSegmentIndex === index }]" @click="seekAudioFromEvent" :data-start-time="segment.startTime" :data-segment-index="index">${segment.sentence}</div>
+ </div>
+ <div v-else class="whitespace-pre-wrap">${processedTranscription.content}</div>
+ </div>
+ </div>
+ <div v-else-if="transcriptionViewMode === 'bubble'" class="transcription-with-speakers">
+ <template v-for="(row, rowIndex) in processedTranscription.bubbleRows" :key="`${selectedRecording.id}-bubble-row-${rowIndex}`">
+ <div :class="['bubble-row', row.isMe ? 'speaker-me' : '']">
+ <div v-for="(bubble, bubbleIndex) in row.bubbles" :key="bubble.startTime || Math.random()" :class="['speaker-bubble', bubble.color, row.isMe ? 'speaker-me' : '', { 'active-playing-segment': currentPlayingSegmentIndex === getBubbleGlobalIndex(rowIndex, bubbleIndex) }]" @click="seekAudioFromEvent" :data-start-time="bubble.startTime" :data-segment-index="getBubbleGlobalIndex(rowIndex, bubbleIndex)">
+ <div class="speaker-bubble-content">${bubble.sentence}</div>
+ </div>
+ </div>
+ </template>
+ </div>
+ </div>
+ </div>
+</div>
diff --git a/templates/components/detail/tab-navigation.html b/templates/components/detail/tab-navigation.html
new file mode 100644
index 00000000..52692814
--- /dev/null
+++ b/templates/components/detail/tab-navigation.html
@@ -0,0 +1,20 @@
+<!-- Tab Navigation for Mobile -->
+<div class="flex-shrink-0 bg-[var(--bg-tertiary)] border-b border-[var(--border-primary)] flex overflow-x-auto">
+ <button @click="mobileTab = 'transcript'"
+ :class="['flex-1 px-4 py-3 text-sm font-medium transition-colors', mobileTab === 'transcript' ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]' : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]']"
+ v-text="t('transcription.title')"></button>
+ <button @click="mobileTab = 'summary'"
+ :class="['flex-1 px-4 py-3 text-sm font-medium transition-colors', mobileTab === 'summary' ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]' : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]']"
+ v-text="t('summary.title')"></button>
+ <button @click="mobileTab = 'notes'"
+ :class="['flex-1 px-4 py-3 text-sm font-medium transition-colors', mobileTab === 'notes' ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]' : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]']"
+ v-text="t('notes.title')"></button>
+ <button @click="mobileTab = 'chat'"
+ :class="['flex-1 px-4 py-3 text-sm font-medium transition-colors', mobileTab === 'chat' ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]' : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]']"
+ v-text="t('chat.title')"></button>
+ <button v-if="selectedRecording.events && selectedRecording.events.length > 0"
+ @click="mobileTab = 'events'"
+ :class="['flex-1 px-4 py-3 text-sm font-medium transition-colors whitespace-nowrap', mobileTab === 'events' ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]' : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]']">
+ <i class="fas fa-calendar-alt mr-1"></i>${ t('events.title') } (${ selectedRecording.events.length })
+ </button>
+</div>
diff --git a/templates/components/header.html b/templates/components/header.html
new file mode 100644
index 00000000..ca38f816
--- /dev/null
+++ b/templates/components/header.html
@@ -0,0 +1,86 @@
+<!-- Header Component -->
+<header class="bg-[var(--bg-secondary)] border-b border-[var(--border-primary)] px-3 sm:px-4 py-3 flex items-center justify-between flex-shrink-0 z-50">
+ <!-- Left side: Menu toggle and logo -->
+ <div class="flex items-center gap-2 sm:gap-4 min-w-0 flex-shrink">
+ <!-- Menu Toggle Button -->
+ <button @click="toggleSidebar"
+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors duration-200 flex-shrink-0 flex items-center justify-center">
+ <i class="fas fa-bars text-lg"></i>
+ </button>
+
+ <!-- Logo and Title -->
+ <div class="flex items-center gap-2 sm:gap-3 min-w-0">
+ <img src="{{ url_for('static', filename='img/icon-32x32.png') }}" alt="Speakr" class="w-7 h-7 sm:w-8 sm:h-8 flex-shrink-0">
+ <h1 class="text-lg sm:text-xl font-bold text-[var(--text-primary)] truncate">Speakr</h1>
+ </div>
+ </div>
+
+ <!-- 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-2 py-1.5 bg-[var(--bg-accent)] text-[var(--text-accent)] rounded-lg hover:opacity-80 transition-opacity text-sm sm:px-4 sm:py-2 sm:min-w-[120px] sm:flex sm:items-center sm:gap-2 sm:justify-center">
+ <i class="fas fa-search"></i>
+ <span class="hidden sm:inline" v-text="t('inquire.title')"></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 sm:px-4 sm:py-2 sm:min-w-[120px] sm:flex sm:items-center sm:gap-2 sm:justify-center">
+ <i class="fas fa-plus mr-1"></i><span v-text="t('nav.newRecording')"></span>
+ </button>
+
+ <!-- User menu -->
+ {% if current_user.is_authenticated %}
+ <div class="relative">
+ <button @click="isUserMenuOpen = !isUserMenuOpen"
+ class="flex items-center gap-1 sm:gap-2 p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors duration-200"
+ :title="t('admin.userMenu')">
+ <i class="fas fa-user-circle text-lg"></i>
+ <span class="hidden lg:inline text-sm">{{ current_user.name if current_user.is_authenticated else 'User' }}</span>
+ <i class="fas fa-chevron-down text-xs hidden sm:inline"></i>
+ </button>
+
+ <!-- User dropdown -->
+ <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><span v-text="t('nav.settings')"></span>
+ </a>
+ <a href="/account#tags" class="block px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors">
+ <i class="fas fa-tags mr-2 w-4 text-center"></i><span v-text="t('help.tagManagement')"></span>
+ </a>
+ <button @click="openSharesList" class="w-full text-left px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors flex items-center">
+ <i class="fas fa-share-alt mr-2 w-4 text-center"></i><span v-text="t('modal.sharedTranscripts')"></span>
+ </button>
+ {% if current_user.is_admin %}
+ <a href="/admin" class="block px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors">
+ <i class="fas fa-user-shield mr-2 w-4 text-center"></i>
+ <span v-text="t('admin.title')"></span>
+ </a>
+ {% elif is_group_admin %}
+ <a href="/group-management" class="block px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors">
+ <i class="fas fa-users-cog mr-2 w-4 text-center"></i>
+ <span v-text="t('nav.groupManagement')"></span>
+ </a>
+ {% endif %}
+ <div class="border-t border-[var(--border-primary)] my-1"></div>
+ <button @click="toggleDarkMode" class="w-full text-left px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors flex items-center">
+ <i :class="isDarkMode ? 'fas fa-sun' : 'fas fa-moon'" class="mr-2 w-4 text-center"></i>
+ <span v-text="isDarkMode ? t('nav.lightMode') : t('nav.darkMode')"></span>
+ </button>
+ <button @click="openColorSchemeModal" class="w-full text-left px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors flex items-center">
+ <i class="fas fa-palette mr-2 w-4 text-center"></i>
+ <span v-text="t('modal.colorScheme')"></span>
+ </button>
+ <div class="border-t border-[var(--border-primary)] my-1"></div>
+ <a href="/logout" class="block px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors">
+ <i class="fas fa-sign-out-alt mr-2 w-4 text-center"></i><span v-text="t('nav.signOut')"></span>
+ </a>
+ </div>
+ </div>
+ {% endif %}
+ </div>
+</header>
diff --git a/templates/components/progress-popup.html b/templates/components/progress-popup.html
new file mode 100644
index 00000000..166b23ec
--- /dev/null
+++ b/templates/components/progress-popup.html
@@ -0,0 +1,104 @@
+<!-- Upload Progress Popup -->
+<div v-if="uploadQueue.length > 0 && !progressPopupClosed"
+ :class="[
+ 'fixed bottom-4 left-4 z-[100] w-96 transition-all duration-300',
+ progressPopupMinimized ? 'minimized' : ''
+ ]">
+ <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-gradient-to-r from-[var(--bg-accent)] to-[var(--bg-accent-hover)] px-4 py-3">
+ <!-- Top row: Title and buttons -->
+ <div class="flex items-center justify-between mb-2">
+ <div class="flex items-center gap-2 min-w-0">
+ <i class="fas fa-upload text-gray-800 dark:text-white animate-pulse"></i>
+ <span class="font-semibold text-gray-800 dark:text-white truncate" v-text="t('uploadProgress.title')"></span>
+ </div>
+ <div class="flex items-center gap-2 flex-shrink-0">
+ <button v-if="completedInQueue > 0" @click="clearCompletedUploads()"
+ class="px-2 py-0.5 text-xs bg-black dark:bg-white bg-opacity-10 dark:bg-opacity-20 hover:bg-opacity-20 dark:hover:bg-opacity-30 rounded transition-all duration-200 text-gray-800 dark:text-white font-medium"
+ :title="t('buttons.clearCompleted')">
+ Clear
+ </button>
+ <button @click="progressPopupMinimized = !progressPopupMinimized"
+ class="p-1 rounded hover:bg-black dark:hover:bg-white hover:bg-opacity-10 dark:hover:bg-opacity-20 transition-colors text-gray-800 dark:text-white">
+ <i :class="progressPopupMinimized ? 'fas fa-chevron-up' : 'fas fa-chevron-down'"></i>
+ </button>
+ <button @click="progressPopupClosed = true"
+ class="p-1 rounded hover:bg-red-600 dark:hover:bg-red-500 hover:bg-opacity-20 dark:hover:bg-opacity-30 text-gray-800 dark:text-white hover:text-white transition-colors">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+ </div>
+ <!-- Overall Progress Bar -->
+ <div class="space-y-1">
+ <div class="flex justify-between items-center text-xs text-gray-800 dark:text-white">
+ <span class="font-medium">${completedInQueue} of ${totalInQueue} files</span>
+ <span class="font-bold">${Math.round((completedInQueue / Math.max(totalInQueue, 1)) * 100)}%</span>
+ </div>
+ <div class="w-full bg-black dark:bg-black bg-opacity-30 dark:bg-opacity-30 rounded-full h-2 overflow-hidden">
+ <div class="bg-gradient-to-r from-[var(--bg-accent)] to-[var(--bg-accent-hover)] h-full rounded-full transition-all duration-500 ease-out relative overflow-hidden"
+ :style="{width: (completedInQueue / Math.max(totalInQueue, 1) * 100) + '%'}">
+ <div class="absolute inset-0 bg-black dark:bg-white opacity-30 dark:opacity-20 animate-pulse"></div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Progress Content -->
+ <div v-if="!progressPopupMinimized" class="p-3 max-h-64 overflow-y-auto">
+ <!-- Currently Processing File -->
+ <div v-if="currentlyProcessingFile" class="mb-3 p-3 bg-[var(--bg-accent)] bg-opacity-10 border border-[var(--border-accent)] rounded-lg">
+ <div class="flex items-center justify-between mb-2">
+ <span class="font-semibold truncate min-w-0 text-sm text-[var(--text-primary)]">${currentlyProcessingFile.file.name}</span>
+ <span class="text-sm flex-shrink-0 ml-2 font-bold text-[var(--text-accent)]">${processingProgress}%</span>
+ </div>
+ <div class="w-full bg-black dark:bg-[var(--bg-tertiary)] bg-opacity-20 rounded-full h-2 mb-2 overflow-hidden">
+ <div class="bg-gradient-to-r from-[var(--bg-accent)] to-[var(--bg-accent-hover)] h-full rounded-full transition-all duration-300 relative"
+ :style="{width: processingProgress + '%'}">
+ <div class="absolute inset-0 bg-black dark:bg-white opacity-30 dark:opacity-20 animate-pulse"></div>
+ </div>
+ </div>
+ <p class="text-xs text-[var(--text-secondary)] font-medium">${processingMessage}</p>
+ </div>
+
+ <!-- Waiting Files -->
+ <div v-if="waitingFilesInQueue.length > 0" class="space-y-2 mb-3">
+ <h4 class="text-xs font-semibold text-[var(--text-secondary)] uppercase tracking-wider opacity-70">Waiting (${waitingFilesInQueue.length})</h4>
+ <div v-for="item in waitingFilesInQueue"
+ :key="item.clientId"
+ class="progress-list-item p-2 bg-[var(--bg-tertiary)] bg-opacity-50 rounded-lg flex items-center gap-2 hover:bg-opacity-70 transition-all duration-200">
+ <i class="fas fa-clock text-[var(--text-muted)] text-sm"></i>
+ <span class="truncate text-sm flex-1 text-[var(--text-primary)]">${item.file.name}</span>
+ <span class="text-xs text-[var(--text-muted)]">${formatFileSize(item.file.size)}</span>
+ <button @click="cancelWaitingFile(item.clientId)"
+ class="p-1 rounded hover:bg-red-500 hover:bg-opacity-20 transition-colors flex-shrink-0"
+ :title="'Remove from queue'">
+ <i class="fas fa-times text-[var(--text-muted)] hover:text-red-500 text-xs"></i>
+ </button>
+ </div>
+ </div>
+
+ <!-- Finished Files -->
+ <div v-if="finishedFilesInQueue.length > 0" class="space-y-2">
+ <h4 class="text-xs font-semibold text-[var(--text-secondary)] uppercase tracking-wider opacity-70" v-text="t('help.completedFiles')"></h4>
+ <div v-for="item in finishedFilesInQueue"
+ :key="item.clientId"
+ class="progress-list-item p-2 bg-[var(--bg-tertiary)] bg-opacity-50 rounded-lg flex items-center gap-2 hover:bg-opacity-70 transition-all duration-200">
+ <i :class="[
+ 'fas',
+ item.status === 'completed' ? 'fa-check-circle text-green-500' : 'fa-exclamation-circle text-red-500'
+ ]"></i>
+ <span class="truncate text-sm flex-1 text-[var(--text-primary)]">${item.file.name}</span>
+ <span :class="[
+ 'text-xs px-2 py-1 rounded-full font-semibold',
+ item.status === 'completed' ? 'bg-green-500 bg-opacity-20 text-green-600 dark:text-green-400' : 'bg-red-500 bg-opacity-20 text-red-600 dark:text-red-400'
+ ]">
+ ${item.status === 'completed' ? t('tagsModal.done') : t('status.failed')}
+ </span>
+ </div>
+ </div>
+ </div>
+ </div>
+</div>
diff --git a/templates/components/recording-view.html b/templates/components/recording-view.html
new file mode 100644
index 00000000..33b96b57
--- /dev/null
+++ b/templates/components/recording-view.html
@@ -0,0 +1,258 @@
+<!-- Recording View -->
+<div v-else-if="currentView === 'recording'" class="flex-1 flex flex-col p-2 md:p-8 bg-[var(--bg-primary)] min-h-0">
+ <div class="flex-1 flex flex-col max-w-4xl w-full mx-auto bg-[var(--bg-secondary)] rounded-xl border border-[var(--border-primary)] min-h-0 overflow-hidden">
+ <!-- Top: Visualizer and Status (Fixed) -->
+ <div class="flex-shrink-0 p-3 md:p-6 text-center bg-[var(--bg-tertiary)] border-b border-[var(--border-primary)]">
+ <div v-if="isRecording" class="w-full mx-auto mb-3 md:mb-4">
+ <!-- Dual visualizer for 'both' mode -->
+ <div v-if="recordingMode === 'both'" class="max-w-4xl mx-auto flex gap-2 md:gap-4">
+ <div class="w-1/2 min-h-[8rem] md:min-h-[12rem] h-32 md:h-48 flex flex-col bg-[var(--bg-primary)] rounded-lg p-1.5 md:p-2">
+ <div class="flex-1 w-full overflow-hidden rounded-md" style="min-height: 6rem;">
+ <canvas ref="micVisualizer" class="w-full h-full"></canvas>
+ </div>
+ <p class="text-xs text-[var(--text-muted)] pt-0.5 md:pt-1" v-text="t('recording.microphone')"></p>
+ </div>
+ <div class="w-1/2 min-h-[8rem] md:min-h-[12rem] h-32 md:h-48 flex flex-col bg-[var(--bg-primary)] rounded-lg p-1.5 md:p-2">
+ <div class="flex-1 w-full overflow-hidden rounded-md" style="min-height: 6rem;">
+ <canvas ref="systemVisualizer" class="w-full h-full"></canvas>
+ </div>
+ <p class="text-xs text-[var(--text-muted)] pt-0.5 md:pt-1" v-text="t('recording.systemAudio')"></p>
+ </div>
+ </div>
+ <!-- Single visualizer for other modes -->
+ <div v-else class="min-h-[8rem] md:min-h-[12rem] h-32 md:h-48 max-w-2xl mx-auto bg-[var(--bg-primary)] rounded-lg p-1.5 md:p-2 flex flex-col">
+ <div class="flex-1 w-full overflow-hidden rounded-md" style="min-height: 6rem;">
+ <canvas ref="visualizer" class="w-full h-full"></canvas>
+ </div>
+ <p class="text-xs text-[var(--text-muted)] pt-0.5 md:pt-1 capitalize">${recordingMode}</p>
+ </div>
+ </div>
+ <div v-if="!isRecording && audioBlobURL" class="w-full mb-3 md:mb-4">
+ <div class="audio-player-container">
+ <audio :src="audioBlobURL" controls class="w-full">
+ Your browser does not support the audio element.
+ </audio>
+ </div>
+ </div>
+
+ <div>
+ <div class="text-xl md:text-2xl font-mono text-[var(--text-accent)]">${formatTime(recordingTime)}</div>
+ <p class="text-xs md:text-sm text-[var(--text-muted)]">${ isRecording ? 'Recording in progress...' : 'Recording finished' }</p>
+ <!-- Real-time file size display -->
+ <div v-if="isRecording && estimatedFileSize > 0" class="mt-1.5">
+ <p class="text-xs text-[var(--text-muted)]">
+ Estimated size: <span class="font-mono">${formatFileSize(estimatedFileSize)}</span>
+ <span v-if="actualBitrate > 0" class="ml-2">
+ (${Math.round(actualBitrate / 1000)}kbps)
+ </span>
+ </p>
+ <!-- Size warning indicator -->
+ <div v-if="estimatedFileSize > (maxRecordingMB * 1024 * 1024 * 0.8)" class="mt-0.5">
+ <div class="flex items-center text-xs text-amber-600 dark:text-amber-400">
+ <i class="fas fa-exclamation-triangle mr-1"></i>
+ <span v-text="t('help.approachingLimit', { limit: maxRecordingMB })"></span>
+ </div>
+ </div>
+ </div>
+
+ <!-- Mobile Background Recording Warning - Below timer -->
+ <div v-if="isRecording && isMobileDevice"
+ class="mt-2 p-2 bg-amber-50 dark:bg-amber-900 dark:bg-opacity-20 border border-amber-300 dark:border-amber-700 rounded">
+ <div class="flex items-start gap-1.5 text-left">
+ <i class="fas fa-exclamation-triangle text-amber-600 dark:text-amber-400 flex-shrink-0 text-xs" style="margin-top: 2px;"></i>
+ <div class="flex-1 min-w-0">
+ <div class="text-xs text-amber-800 dark:text-amber-200 leading-snug">
+ <strong class="font-semibold">Keep this app visible!</strong>
+ <span class="block text-[10px] mt-0.5">Recording pauses if minimized or screen locked.</span>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Scrollable Content Area: Notes + Actions -->
+ <div class="flex-1 min-h-0 overflow-y-auto flex flex-col">
+ <!-- Middle: Notepad (flexible height) -->
+ <div class="flex-1 p-3 md:p-6 flex flex-col" style="min-height: 200px;">
+ <label for="recordingNotes" class="block text-sm font-medium text-[var(--text-secondary)] mb-1.5 flex-shrink-0">
+ <i class="fas fa-pencil-alt mr-1"></i>
+ Recording Notes (Markdown)
+ </label>
+ <div class="flex-1 recording-notes-editor" style="min-height: 150px;">
+ <textarea ref="recordingNotesEditor" v-model="recordingNotes"
+ class="w-full h-full bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg p-2 md:p-3 text-sm focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)] resize-none"
+ :placeholder="t('form.notesPlaceholder')"></textarea>
+ </div>
+ </div>
+
+ <!-- Bottom: Action Buttons -->
+ <div class="flex-shrink-0 p-3 md:p-6 bg-[var(--bg-tertiary)] border-t border-[var(--border-primary)]">
+ <div v-if="isRecording" class="text-center">
+ <button @click="stopRecording"
+ class="px-6 md:px-8 py-2.5 md:py-3 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors animate-pulse text-sm md:text-base">
+ <i class="fas fa-stop mr-2"></i>Stop Recording
+ </button>
+ </div>
+ <div v-if="!isRecording && audioBlobURL" class="flex flex-col gap-3 md:gap-4">
+ <!-- Tag Selection -->
+ <div>
+ <label for="recordingTagSelect" class="block text-sm font-medium text-[var(--text-secondary)] mb-1.5 md:mb-2">
+ <i class="fas fa-tags mr-1"></i>
+ Select Tags (optional, in priority order)
+ </label>
+
+ <!-- Selected Tags Display - Compact -->
+ <div v-if="selectedTags.length > 0" class="mb-2">
+ <div class="p-1.5 bg-[var(--bg-tertiary)] rounded-md border border-[var(--border-secondary)] max-h-16 overflow-y-auto">
+ <div class="flex flex-wrap gap-1">
+ <span v-for="(tag, index) in selectedTags" :key="tag.id"
+ class="inline-flex items-center px-1.5 py-0.5 rounded-full text-[11px] font-medium cursor-help"
+ :style="{ backgroundColor: tag.color, color: getContrastTextColor(tag.color) }"
+ :title="tag.group_id ? ('Group: ' + tag.group_name) : tag.name">
+ <span class="opacity-75 mr-0.5 text-[9px]">${index + 1}.</span>
+ <i v-if="tag.group_id" class="fas fa-users mr-1 text-[9px]"></i>
+ <span v-if="tag.group_id" class="opacity-75">${tag.group_name}: </span>
+ <span>${tag.name}</span>
+ <button @click="removeTagFromSelection(tag.id)"
+ class="ml-1 hover:opacity-100 opacity-70">
+ <i class="fas fa-times" style="font-size: 9px;"></i>
+ </button>
+ </span>
+ </div>
+ </div>
+ </div>
+
+ <!-- Tag Selection Container - Compact -->
+ <div v-if="availableTags.filter(tag => !selectedTagIds.includes(tag.id)).length > 0"
+ class="border border-[var(--border-secondary)] rounded-md bg-[var(--bg-tertiary)] p-2">
+ <!-- Search Filter -->
+ <div class="mb-1.5">
+ <div class="relative">
+ <input v-model="uploadTagSearchFilter"
+ type="text"
+ :placeholder="t('tagsModal.searchTags')"
+ class="w-full px-2 py-1 pl-6 text-xs bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">
+ <i class="fas fa-search absolute left-2 top-1/2 transform -translate-y-1/2 text-[var(--text-muted)]" style="font-size: 9px;"></i>
+ <button v-if="uploadTagSearchFilter"
+ @click="uploadTagSearchFilter = ''"
+ class="absolute right-2 top-1/2 transform -translate-y-1/2 text-[var(--text-muted)] hover:text-[var(--text-primary)]">
+ <i class="fas fa-times" style="font-size: 9px;"></i>
+ </button>
+ </div>
+ </div>
+ <!-- Available Tags Grid -->
+ <div v-if="filteredAvailableTagsForUpload.length > 0"
+ class="overflow-y-auto"
+ style="max-height: 100px;">
+ <div class="grid grid-cols-2 gap-1">
+ <button v-for="tag in filteredAvailableTagsForUpload"
+ :key="tag.id"
+ @click="addTagToSelection(tag.id)"
+ class="group flex items-center justify-between px-1.5 py-1 rounded border border-[var(--border-secondary)] hover:border-[var(--border-focus)] bg-[var(--bg-primary)] hover:bg-[var(--bg-secondary)] transition-all">
+ <div class="flex items-center gap-1 min-w-0">
+ <i v-if="tag.group_id" class="fas fa-users flex-shrink-0 text-[9px]"
+ :style="{ color: tag.color || '#6B7280' }"></i>
+ <span v-else class="w-2 h-2 rounded-full flex-shrink-0"
+ :style="{ backgroundColor: tag.color || '#6B7280' }"></span>
+ <span class="text-[11px] text-[var(--text-primary)] truncate">
+ <span v-if="tag.group_id" class="opacity-75">${tag.group_name}: </span>${tag.name}
+ </span>
+ </div>
+ <i class="fas fa-plus text-[var(--text-muted)] group-hover:text-[var(--text-accent)] transition-colors" style="font-size: 9px;"></i>
+ </button>
+ </div>
+ </div>
+ <div v-else class="py-2 text-center">
+ <p class="text-[11px] text-[var(--text-muted)]">
+ <i class="fas fa-search mr-1" style="font-size: 9px;"></i>
+ No matching tags
+ </p>
+ </div>
+ </div>
+ <!-- Empty States -->
+ <div v-else-if="availableTags.length === 0"
+ class="p-2 bg-[var(--bg-tertiary)] rounded-md border border-[var(--border-secondary)]">
+ <p class="text-xs text-[var(--text-muted)] text-center">
+ <i class="fas fa-info-circle mr-1" style="font-size: 10px;"></i>
+ <span v-text="t('help.noTagsCreated')"></span> <a href="/account#tags" class="text-[var(--text-accent)] hover:underline" v-text="t('help.createTags')"></a>
+ </p>
+ </div>
+ <div v-else class="p-2 bg-[var(--bg-tertiary)] rounded-md border border-[var(--border-secondary)]">
+ <p class="text-xs text-[var(--text-muted)] text-center">
+ <i class="fas fa-check-circle mr-1" style="font-size: 10px;"></i>
+ All tags selected
+ </p>
+ </div>
+
+ <p v-if="selectedTags.some(tag => tag.custom_prompt)" class="text-xs text-[var(--text-muted)] mt-1">
+ <i class="fas fa-info-circle mr-1 text-[var(--text-accent)]"></i>
+ Selected tags include custom summary prompts
+ </p>
+ <p v-if="selectedTags.length > 0 && useAsrEndpoint && selectedTags.some(tag => tag.default_language || tag.default_min_speakers || tag.default_max_speakers)"
+ class="text-xs text-[var(--text-muted)] mt-1">
+ <i class="fas fa-cog mr-1 text-[var(--text-accent)]"></i>
+ First tag's ASR settings will be applied: ${selectedTags[0].name}
+ </p>
+ </div>
+
+ <!-- Advanced Options for ASR (collapsible) -->
+ <div v-if="useAsrEndpoint">
+ <button @click="showAdvancedOptions = !showAdvancedOptions"
+ class="w-full flex items-center justify-between px-3 py-2 bg-[var(--bg-tertiary)] rounded-md hover:bg-[var(--bg-accent)] transition-colors text-xs font-medium">
+ <span class="flex items-center gap-2 text-[var(--text-secondary)]">
+ <i class="fas fa-cog text-[var(--text-muted)]"></i>
+ <span v-text="t('help.advancedAsrOptions')"></span>
+ </span>
+ <i :class="['fas text-[var(--text-muted)]', showAdvancedOptions ? 'fa-chevron-up' : 'fa-chevron-down']"></i>
+ </button>
+
+ <div v-if="showAdvancedOptions" class="mt-2 p-3 bg-[var(--bg-tertiary)] rounded-md border border-[var(--border-secondary)] space-y-3">
+ <div>
+ <label for="recordingAsrLanguage" class="block text-xs font-medium text-[var(--text-secondary)] mb-1">
+ Language
+ </label>
+ <select id="recordingAsrLanguage" v-model="asrLanguage"
+ class="w-full px-2 py-1 bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)] text-xs">
+ <option v-for="lang in languageOptions" :key="lang.value" :value="lang.value" v-text="lang.label"></option>
+ </select>
+ </div>
+
+ <div class="grid grid-cols-2 gap-3">
+ <div>
+ <label for="recordingAsrMinSpeakers" class="block text-xs font-medium text-[var(--text-secondary)] mb-1" v-text="t('form.minSpeakers')">
+ </label>
+ <input type="number" id="recordingAsrMinSpeakers" v-model="asrMinSpeakers"
+ min="1" max="20" :placeholder="t('form.auto')"
+ class="w-full px-2 py-1 bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)] text-xs">
+ </div>
+
+ <div>
+ <label for="recordingAsrMaxSpeakers" class="block text-xs font-medium text-[var(--text-secondary)] mb-1" v-text="t('form.maxSpeakers')">
+ </label>
+ <input type="number" id="recordingAsrMaxSpeakers" v-model="asrMaxSpeakers"
+ min="1" max="20" :placeholder="t('form.auto')"
+ class="w-full px-2 py-1 bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)] text-xs">
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Upload/Discard Buttons -->
+ <div class="flex flex-col sm:flex-row gap-3 justify-center">
+ <button @click="uploadRecordedAudio"
+ class="flex-1 px-6 py-3 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors flex items-center justify-center gap-2">
+ <i class="fas fa-upload"></i>
+ <span v-text="t('help.uploadRecordingNotes')"></span>
+ </button>
+ <button @click="discardRecording"
+ class="px-6 py-3 bg-[var(--bg-danger)] text-white rounded-lg hover:bg-[var(--bg-danger-hover)] transition-colors flex items-center justify-center gap-2">
+ <i class="fas fa-trash"></i>
+ <span v-text="t('help.discard')"></span>
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+</div>
diff --git a/templates/components/sidebar.html b/templates/components/sidebar.html
new file mode 100644
index 00000000..95335690
--- /dev/null
+++ b/templates/components/sidebar.html
@@ -0,0 +1,323 @@
+<!-- Mobile Sidebar Backdrop -->
+<div v-if="!isSidebarCollapsed && isMobileScreen"
+ @click="toggleSidebar"
+ class="fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden">
+</div>
+
+<!-- Sidebar -->
+<aside :class="['sidebar', isSidebarCollapsed ? 'collapsed' : '']">
+ <div class="sidebar-content-wrapper">
+ <!-- Sidebar Header -->
+ <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" v-text="t('nav.recording')"></h2>
+ <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><span v-text="t('common.new')"></span>
+ </button>
+ </div>
+ </div>
+
+ <!-- Search and Sort Controls -->
+ <div class="space-y-3">
+ <!-- Filter Toggle Button -->
+ <div class="flex items-center space-x-2">
+ <button @click="showAdvancedFilters = !showAdvancedFilters"
+ class="flex-1 flex items-center justify-between px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg text-sm hover:bg-[var(--bg-tertiary)] transition-colors">
+ <span class="flex items-center">
+ <i class="fas fa-filter mr-2 text-[var(--text-muted)]"></i>
+ <span v-if="!searchQuery && filterTags.length === 0 && !filterDatePreset && !filterDateRange.start && !filterDateRange.end && !filterTextQuery"
+ v-text="t('sidebar.searchRecordings')">
+ </span>
+ <span v-else class="text-[var(--text-accent)]">
+ Active filters (${ (filterTags.length > 0 ? 1 : 0) + (filterDatePreset || filterDateRange.start || filterDateRange.end ? 1 : 0) + (filterTextQuery ? 1 : 0) })
+ </span>
+ </span>
+ <i :class="['fas fa-chevron-down transition-transform text-[var(--text-muted)]', showAdvancedFilters ? 'rotate-180' : '']"></i>
+ </button>
+ <button v-if="searchQuery || filterTags.length > 0 || filterDatePreset || filterDateRange.start || filterDateRange.end || filterTextQuery"
+ @click="clearAllFilters"
+ class="px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg text-sm hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-primary)] transition-colors"
+ :title="t('buttons.clearAllFilters')">
+ <i class="fas fa-times text-[var(--text-muted)]"></i>
+ </button>
+ </div>
+
+ <!-- Advanced Filters Panel -->
+ <div v-show="showAdvancedFilters" class="p-3 bg-[var(--bg-tertiary)] border border-[var(--border-secondary)] rounded-lg space-y-3">
+ <!-- Text Search -->
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-muted)] mb-1" v-text="t('sidebar.filters')"></label>
+ <div class="relative">
+ <input v-model="filterTextQuery"
+ type="text"
+ :placeholder="t('sidebar.searchRecordings')"
+ class="w-full px-3 py-1.5 pl-8 pr-8 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-md text-sm focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">
+ <i class="fas fa-search absolute left-2.5 top-1/2 transform -translate-y-1/2 text-[var(--text-muted)] text-xs"></i>
+ <button v-if="filterTextQuery"
+ @click="filterTextQuery = ''"
+ class="absolute right-2.5 top-1/2 transform -translate-y-1/2 text-[var(--text-muted)] hover:text-[var(--text-primary)] text-xs"
+ :title="t('buttons.clearSearchText')">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+ </div>
+
+ <!-- Tag Filter -->
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-muted)] mb-1" v-text="t('tags.filterByTag')"></label>
+ <div class="flex flex-wrap gap-1.5">
+ <button v-for="tag in availableTags"
+ :key="tag.id"
+ @click="filterTags.includes(tag.id) ? filterTags = filterTags.filter(id => id !== tag.id) : filterTags.push(tag.id)"
+ :class="[
+ 'px-2 py-1 rounded-full text-xs font-medium transition-all',
+ filterTags.includes(tag.id)
+ ? 'bg-[var(--bg-accent)] text-[var(--text-accent)] ring-1 ring-[var(--border-accent)]'
+ : 'bg-[var(--bg-secondary)] text-[var(--text-secondary)] hover:bg-[var(--bg-input)]'
+ ]">
+ <span class="inline-block w-2 h-2 rounded-full mr-1" :style="{ backgroundColor: tag.color || '#6B7280' }"></span>
+ ${ tag.name }
+ </button>
+ </div>
+ <p v-if="availableTags.length === 0" class="text-xs text-[var(--text-muted)] italic" v-text="t('tags.noTags')"></p>
+ </div>
+
+ <!-- Date Filter -->
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-muted)] mb-1" v-text="t('sidebar.dateRange')"></label>
+ <div class="grid grid-cols-3 gap-1.5 mb-2">
+ <button v-for="preset in datePresetOptions"
+ :key="preset.value"
+ @click="filterDatePreset = filterDatePreset === preset.value ? '' : preset.value; filterDateRange = { start: '', end: '' }"
+ :class="[
+ 'px-2 py-1 rounded-md text-xs transition-all',
+ filterDatePreset === preset.value
+ ? 'bg-[var(--bg-accent)] text-[var(--text-accent)]'
+ : 'bg-[var(--bg-secondary)] text-[var(--text-secondary)] hover:bg-[var(--bg-input)]'
+ ]"
+ :title="preset.label">
+ ${ preset.label }
+ </button>
+ </div>
+ <div class="grid grid-cols-2 gap-2">
+ <div>
+ <input v-model="filterDateRange.start"
+ @change="filterDatePreset = ''"
+ type="date"
+ class="w-full px-2 py-1 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-md text-xs focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]"
+ :placeholder="t('form.dateFrom')">
+ </div>
+ <div>
+ <input v-model="filterDateRange.end"
+ @change="filterDatePreset = ''"
+ type="date"
+ class="w-full px-2 py-1 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-md text-xs focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]"
+ :placeholder="t('form.dateTo')">
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Compact Controls Row -->
+ <div class="flex items-center gap-1.5">
+ <!-- Sort Toggle -->
+ <button @click="sortBy = sortBy === 'created_at' ? 'meeting_date' : 'created_at'"
+ :class="[
+ 'flex-1 flex items-center justify-center gap-1 px-2 py-1.5 border rounded-md text-xs transition-colors',
+ 'bg-[var(--bg-input)] border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)]'
+ ]"
+ :title="sortBy === 'meeting_date' ? t('sidebar.sortByMeetingDate') : t('sidebar.sortByDate')">
+ <i :class="['fas', sortBy === 'meeting_date' ? 'fa-calendar' : 'fa-upload']"></i>
+ <span class="hidden sm:inline">Sort</span>
+ <i class="fas fa-exchange-alt text-[var(--text-muted)] text-[10px]"></i>
+ </button>
+
+ <!-- Archived Toggle (only show when audio-only deletion mode is active) -->
+ <button v-if="enableArchiveToggle" @click="showArchivedRecordings = !showArchivedRecordings"
+ :class="[
+ 'flex-1 flex items-center justify-center gap-1 px-2 py-1.5 border rounded-md text-xs transition-colors',
+ showArchivedRecordings
+ ? 'bg-[var(--bg-accent)] border-[var(--border-accent)] text-[var(--text-accent)]'
+ : 'bg-[var(--bg-input)] border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)]'
+ ]"
+ :title="t('sidebar.archivedRecordings')">
+ <i class="fas fa-archive"></i>
+ <span class="hidden sm:inline">Archived</span>
+ <i :class="['fas text-[10px]', showArchivedRecordings ? 'fa-toggle-on' : 'fa-toggle-off']"></i>
+ </button>
+
+ <!-- Shared Toggle -->
+ <button v-if="enableInternalSharing" @click="showSharedWithMe = !showSharedWithMe"
+ :class="[
+ 'flex-1 flex items-center justify-center gap-1 px-2 py-1.5 border rounded-md text-xs transition-colors',
+ showSharedWithMe
+ ? 'bg-[var(--bg-accent)] border-[var(--border-accent)] text-[var(--text-accent)]'
+ : 'bg-[var(--bg-input)] border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)]'
+ ]"
+ :title="t('sidebar.sharedWithMe')">
+ <i class="fas fa-users"></i>
+ <span class="hidden sm:inline">Shared</span>
+ <i :class="['fas text-[10px]', showSharedWithMe ? 'fa-toggle-on' : 'fa-toggle-off']"></i>
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Recordings List -->
+ <div class="flex-1 overflow-y-auto p-4"
+ @scroll="(e) => {
+ const element = e.target;
+ const threshold = 100; // Load more when 100px from bottom
+ if (element.scrollHeight - element.scrollTop - element.clientHeight < threshold) {
+ loadMoreRecordings();
+ }
+ }">
+ <div v-if="isLoadingRecordings && recordings.length === 0" class="text-center py-8">
+ <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
+ <p class="mt-2 text-[var(--text-muted)]" v-text="t('help.loadingRecordings')"></p>
+ </div>
+
+ <div v-else-if="recordings.length === 0 && !isLoadingRecordings" class="text-center py-8">
+ <i class="fas fa-microphone-slash text-3xl text-[var(--text-muted)] mb-3"></i>
+ <p class="text-[var(--text-muted)]" v-text="t('sidebar.noRecordings')"></p>
+ <p v-if="searchQuery.trim()" class="text-sm text-[var(--text-muted)] mt-1">
+ <span v-text="t('help.tryAdjustingSearch')"></span> <button @click="clearAllFilters()" class="text-[var(--text-accent)] hover:underline" v-text="t('help.clearFilters')"></button>
+ </p>
+ </div>
+
+ <div v-if="recordings.length > 0" class="space-y-2">
+ <div v-for="group in groupedRecordings" :key="group.title" class="mb-6">
+ <h3 class="text-xs font-semibold text-[var(--text-muted)] uppercase tracking-wide mb-2">
+ ${group.title}
+ </h3>
+ <div class="space-y-1">
+ <div v-for="recording in group.items"
+ :key="recording.id"
+ @click="selectRecording(recording)"
+ :class="[
+ 'p-3 rounded-lg cursor-pointer transition-all duration-200 border-2',
+ selectedRecording?.id === recording.id
+ ? 'bg-[var(--bg-accent)] border-[var(--border-accent)]'
+ : recording.is_shared
+ ? 'bg-[var(--bg-secondary)] border-[var(--bg-tertiary)] hover:bg-[var(--bg-accent-hover)]'
+ : 'bg-[var(--bg-tertiary)] border-transparent hover:bg-[var(--bg-accent-hover)]'
+ ]">
+ <!-- Title and Status Row -->
+ <div class="flex items-center justify-between mb-1">
+ <h4 class="font-medium text-sm truncate flex-1 mr-2" :class="selectedRecording?.id === recording.id ? 'text-[var(--text-accent)]' : 'text-[var(--text-primary)]'">
+ ${ recording.title || t('common.untitled') }
+ </h4>
+ <div class="flex items-center gap-0.5 flex-shrink-0">
+ <!-- Combined sharing status badge -->
+ <span v-if="recording.is_shared || recording.has_group_tags || recording.shared_with_count > 0 || recording.public_share_count > 0"
+ class="inline-flex items-center justify-center gap-1 h-5 px-2 rounded-full text-[9px] leading-none bg-violet-100 dark:bg-violet-900/50 border border-violet-300 dark:border-violet-600"
+ :title="[
+ recording.is_shared ? t('sharing.sharedBy') + ' ' + (recording.owner_username || t('sharing.unknown')) : '',
+ recording.has_group_tags ? t('sharing.teamRecording') : '',
+ !recording.is_shared && recording.shared_with_count > 0 ? t('sharing.sharedWith') + ' ' + recording.shared_with_count + ' ' + t('sharing.users') : '',
+ !recording.is_shared && recording.public_share_count > 0 ? recording.public_share_count + ' ' + t('sharing.publicLinksGenerated') : ''
+ ].filter(s => s).join(' • ')">
+ <i v-if="recording.is_shared" class="fas fa-arrow-down text-purple-600 dark:text-purple-400"></i>
+ <i v-if="recording.has_group_tags" class="fas fa-users text-blue-600 dark:text-blue-400"></i>
+ <i v-if="!recording.is_shared && recording.shared_with_count > 0" class="fas fa-arrow-up text-indigo-600 dark:text-indigo-400"></i>
+ <i v-if="!recording.is_shared && recording.public_share_count > 0" class="fas fa-globe text-teal-600 dark:text-teal-400"></i>
+ </span>
+
+ <!-- Show Audio Deleted badge -->
+ <span v-if="recording.audio_deleted_at"
+ class="inline-flex items-center justify-center h-5 px-1.5 rounded-full text-[9px] leading-none bg-gray-200 dark:bg-gray-700 border border-gray-300 dark:border-gray-600"
+ :title="t('sidebar.archived')">
+ <i class="fas fa-file-audio text-gray-600 dark:text-gray-400"></i>
+ </span>
+
+ <!-- Show Failed status for failed recordings -->
+ <span v-if="recording.status === 'FAILED'"
+ class="inline-flex items-center justify-center h-5 px-1.5 rounded-full text-[9px] leading-none bg-red-100 dark:bg-red-900/50 border border-red-300 dark:border-red-700 text-red-700 dark:text-red-400">
+ <i class="fas fa-exclamation-circle"></i>
+ </span>
+
+ <!-- Show Processing status for non-completed recordings -->
+ <span v-else-if="recording.status !== 'COMPLETED'"
+ :class="getStatusClass(recording.status)"
+ class="status-badge">
+ ${formatStatus(recording.status)}
+ </span>
+
+ <!-- For completed recordings, show highlight and inbox badges -->
+ <template v-else>
+ <span v-if="recording.is_highlighted"
+ @click.stop="toggleHighlight(recording)"
+ class="inline-flex items-center justify-center h-5 px-1.5 rounded-full text-[9px] leading-none bg-amber-100 dark:bg-amber-900/50 border border-amber-400 dark:border-amber-600 cursor-pointer hover:bg-amber-200 dark:hover:bg-amber-800/50"
+ :title="t('sidebar.removeFromHighlighted')">
+ <i class="fas fa-star text-amber-600 dark:text-amber-400"></i>
+ </span>
+ <span v-if="recording.is_inbox"
+ @click.stop="toggleInbox(recording)"
+ class="inline-flex items-center justify-center h-5 px-1.5 rounded-full text-[9px] leading-none bg-blue-100 dark:bg-blue-900/50 border border-blue-400 dark:border-blue-600 cursor-pointer hover:bg-blue-200 dark:hover:bg-blue-800/50"
+ :title="t('sidebar.markAsRead')">
+ <i class="fas fa-inbox text-blue-600 dark:text-blue-400"></i>
+ </span>
+ </template>
+ </div>
+ </div>
+
+ <!-- Date and Participants -->
+ <div class="flex flex-wrap items-center gap-x-3 gap-y-1 mt-1 text-xs text-[var(--text-muted)]">
+ <!-- Date -->
+ <div class="flex items-center flex-shrink-0">
+ <i class="fas fa-calendar-alt mr-1 text-[var(--text-muted)]" style="font-size: 10px;"></i>
+ ${formatShortDate(sortBy === 'meeting_date' ? recording.meeting_date : recording.created_at)}
+ </div>
+
+ <!-- Participants -->
+ <div v-if="recording.participants" class="flex items-center min-w-0 flex-1">
+ <i class="fas fa-users mr-1 text-[var(--text-muted)] flex-shrink-0" style="font-size: 10px;"></i>
+ <span class="truncate">
+ ${recording.participants}
+ </span>
+ </div>
+ </div>
+
+ <!-- Tags -->
+ <div v-if="getRecordingTags(recording).length > 0" class="flex flex-wrap gap-1 mt-1">
+ <button v-for="tag in getRecordingTags(recording).slice(0, 4)" :key="tag.id"
+ @click.stop="filterByTag(tag)"
+ class="inline-flex items-center px-1.5 py-0.5 rounded-md text-xs font-medium hover:opacity-80 transition-all cursor-pointer"
+ :style="{ backgroundColor: tag.color, color: getContrastTextColor(tag.color) }"
+ :title="tag.group_id ? ('Group: ' + tag.group_name) : ('Filter by ' + tag.name)">
+ <i v-if="tag.group_id" class="fas fa-users mr-1" style="font-size: 9px; vertical-align: middle; line-height: 0;"></i>
+ <span v-text="tag.name"></span>
+ </button>
+ <span v-if="getRecordingTags(recording).length > 4"
+ class="inline-flex items-center px-1.5 py-0.5 rounded-md text-xs text-[var(--text-muted)]"
+ :title="getRecordingTags(recording).slice(4).map(t => t.name).join(', ')">
+ +${getRecordingTags(recording).length - 4}
+ </span>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Load More Indicator -->
+ <div v-if="isLoadingMore" class="text-center py-4">
+ <i class="fas fa-spinner fa-spin text-lg text-[var(--text-muted)]"></i>
+ <p class="text-sm text-[var(--text-muted)] mt-1" v-text="t('help.loadingMore')"></p>
+ </div>
+
+ <!-- End of Results Indicator -->
+ <div v-else-if="!hasNextPage && totalRecordings > 0" class="text-center py-4 text-xs text-[var(--text-muted)]">
+ <i class="fas fa-check-circle mr-1"></i>
+ <span v-text="t('help.allRecordingsLoaded')"></span>
+ </div>
+ </div>
+ </div>
+ </div>
+</aside>
diff --git a/templates/components/upload-view.html b/templates/components/upload-view.html
new file mode 100644
index 00000000..05eaf15e
--- /dev/null
+++ b/templates/components/upload-view.html
@@ -0,0 +1,275 @@
+<!-- Upload View -->
+<div v-if="currentView === 'upload'" class="flex-1 flex items-center justify-center p-4 md:p-8 overflow-y-auto">
+ <div class="max-w-lg w-full my-auto">
+ <!-- Compact Header -->
+ <div class="text-center mb-3">
+ <h2 class="text-lg font-semibold flex items-center justify-center gap-2">
+ <i class="fas fa-microphone text-[var(--text-accent)]"></i>
+ <span v-text="t('upload.title')"></span>
+ </h2>
+ </div>
+
+ <div class="bg-[var(--bg-secondary)] p-4 md:p-6 rounded-xl border border-[var(--border-primary)]">
+ <!-- File Upload Area -->
+ <div @drop="handleDrop" @dragover="handleDragOver" @dragleave="handleDragLeave" @click="$refs.fileInput.click()"
+ :class="['border-2 border-dashed rounded-lg p-6 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-2xl text-[var(--text-muted)] mb-2"></i>
+ <p class="text-sm text-[var(--text-secondary)] mb-1" v-text="t('upload.dropzone')"></p>
+ <p class="text-xs text-[var(--text-muted)]" v-text="t('upload.supportedFormats')"></p>
+ </div>
+ <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">
+
+ <!-- Queued Files Display -->
+ <div v-if="pendingQueueFiles.length > 0" class="mt-3">
+ <div class="flex items-center justify-between mb-1.5">
+ <h4 class="text-xs font-medium text-[var(--text-secondary)]">
+ <i class="fas fa-list mr-1"></i>
+ Files to Upload (${pendingQueueFiles.length})
+ </h4>
+ </div>
+ <div class="space-y-1 max-h-32 overflow-y-auto">
+ <div v-for="item in pendingQueueFiles" :key="item.clientId"
+ class="flex items-center justify-between px-2 py-1.5 bg-[var(--bg-tertiary)] rounded border border-[var(--border-secondary)]">
+ <div class="flex items-center gap-1.5 min-w-0 flex-1">
+ <i class="fas fa-file-audio text-[var(--text-muted)] text-xs"></i>
+ <span class="text-xs text-[var(--text-primary)] truncate">${item.file.name}</span>
+ <span class="text-[10px] text-[var(--text-muted)] flex-shrink-0">(${formatFileSize(item.file.size)})</span>
+ </div>
+ <button @click="removeFromQueue(item.clientId)"
+ class="ml-1.5 p-0.5 text-[var(--text-muted)] hover:text-red-500 transition-colors flex-shrink-0"
+ title="Remove from queue">
+ <i class="fas fa-times text-xs"></i>
+ </button>
+ </div>
+ </div>
+ <!-- Upload Button -->
+ <button @click="startUpload"
+ class="w-full mt-2 px-4 py-2.5 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors flex items-center justify-center gap-2 font-medium text-sm">
+ <i class="fas fa-cloud-upload-alt"></i>
+ <span>Upload ${pendingQueueFiles.length} File${pendingQueueFiles.length !== 1 ? 's' : ''}</span>
+ </button>
+ </div>
+
+ <!-- Divider (hidden when files are selected) -->
+ <div v-if="pendingQueueFiles.length === 0" class="my-4 flex items-center">
+ <div class="flex-grow border-t border-[var(--border-secondary)]"></div>
+ <span class="flex-shrink mx-3 text-[10px] text-[var(--text-muted)] uppercase" v-text="t('common.or')"></span>
+ <div class="flex-grow border-t border-[var(--border-secondary)]"></div>
+ </div>
+
+ <!-- Audio Recording Options (hidden when files are selected) -->
+ <div v-if="pendingQueueFiles.length === 0" class="space-y-2">
+ <h3 class="text-xs font-medium text-[var(--text-secondary)] text-center" v-text="t('recording.title')"></h3>
+
+ <!-- Microphone Recording -->
+ <button @click="startRecording('microphone')"
+ class="w-full px-3 py-2.5 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors flex items-center justify-center gap-2 text-sm">
+ <i class="fas fa-microphone"></i>
+ <span v-text="t('recording.microphone')"></span>
+ </button>
+
+ <!-- System Audio and Both - Side by Side -->
+ <div v-if="canRecordSystemAudio" class="grid grid-cols-2 gap-2">
+ <!-- System Audio Recording -->
+ <button @click="startRecording('system')"
+ class="px-3 py-2.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center justify-center gap-1.5 text-sm">
+ <i class="fas fa-desktop"></i>
+ <span v-text="t('recording.systemAudio')"></span>
+ </button>
+
+ <!-- Both Audio Sources -->
+ <button @click="startRecording('both')"
+ class="px-3 py-2.5 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors flex items-center justify-center gap-1 text-sm">
+ <i class="fas fa-microphone"></i>
+ <i class="fas fa-desktop"></i>
+ <span class="hidden sm:inline" v-text="t('recording.microphoneAndSystem')"></span>
+ <span class="sm:hidden">Mic + Sys</span>
+ </button>
+ </div>
+
+ <!-- Help Text - Compact -->
+ <div class="text-[10px] text-[var(--text-muted)] space-y-0.5 mt-2">
+ <div class="flex items-center justify-between">
+ <span><strong v-text="t('recording.microphone') + ':'"></strong> <span v-text="t('help.microphoneDesc')"></span></span>
+ <i class="fas fa-microphone text-red-500 flex-shrink-0 ml-1"></i>
+ </div>
+ <div v-if="canRecordSystemAudio" class="flex items-center justify-between">
+ <span><strong v-text="t('recording.systemAudio') + ':'"></strong> <span v-text="t('help.systemAudioDesc')"></span></span>
+ <i class="fas fa-desktop text-blue-500 flex-shrink-0 ml-1"></i>
+ </div>
+ <div v-if="canRecordSystemAudio" class="flex items-center justify-between">
+ <span><strong v-text="t('recording.microphoneAndSystem') + ':'"></strong> <span v-text="t('help.bothAudioDesc')"></span></span>
+ <div class="flex items-center gap-0.5 flex-shrink-0 ml-1">
+ <i class="fas fa-microphone text-purple-500"></i>
+ <i class="fas fa-desktop text-purple-500"></i>
+ </div>
+ </div>
+ <div v-if="!canRecordSystemAudio" class="text-amber-600 dark:text-amber-400">
+ <i class="fas fa-exclamation-triangle mr-1"></i>
+ ${ t('recording.systemAudioNotSupported') }
+ <button @click="showSystemAudioHelp = true" class="ml-1 text-blue-500 hover:text-blue-600 underline">
+ <span v-text="t('buttons.help')"></span>
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Tag Selection -->
+ <div class="mt-4">
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-2">
+ <i class="fas fa-tags mr-1 text-[var(--text-muted)]"></i>
+ ${ t('tags.title') }
+ </label>
+
+ <!-- Selected Tags Display - Compact -->
+ <div v-if="selectedTags.length > 0" class="mb-2">
+ <div class="p-1.5 bg-[var(--bg-tertiary)] rounded-md border border-[var(--border-secondary)] max-h-16 overflow-y-auto">
+ <div class="flex flex-wrap gap-1">
+ <span v-for="(tag, index) in selectedTags" :key="tag.id"
+ class="inline-flex items-center px-1.5 py-0.5 rounded-full text-[11px] font-medium cursor-help"
+ :style="{ backgroundColor: tag.color, color: getContrastTextColor(tag.color) }"
+ :title="tag.group_id ? ('Group: ' + tag.group_name) : tag.name">
+ <span class="opacity-75 mr-0.5 text-[9px]">${index + 1}.</span>
+ <i v-if="tag.group_id" class="fas fa-users mr-1 text-[9px]"></i>
+ <span v-if="tag.group_id" class="opacity-75">${tag.group_name}: </span>
+ <span>${tag.name}</span>
+ <button @click="removeTagFromSelection(tag.id)"
+ class="ml-1 hover:opacity-100 opacity-70">
+ <i class="fas fa-times" style="font-size: 9px;"></i>
+ </button>
+ </span>
+ </div>
+ </div>
+ <p class="text-[10px] text-[var(--text-muted)] mt-0.5">
+ <i class="fas fa-info-circle mr-0.5" style="font-size: 9px;"></i>
+ Tags ordered by priority
+ </p>
+ </div>
+
+ <!-- Tag Selection Container - Compact -->
+ <div v-if="availableTags.filter(tag => !selectedTagIds.includes(tag.id)).length > 0"
+ class="border border-[var(--border-secondary)] rounded-md bg-[var(--bg-tertiary)] p-2">
+ <!-- Search Filter (always visible if tags available) -->
+ <div class="mb-1.5">
+ <div class="relative">
+ <input v-model="uploadTagSearchFilter"
+ type="text"
+ :placeholder="t('tagsModal.searchTags')"
+ class="w-full px-2 py-1 pl-6 text-xs bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">
+ <i class="fas fa-search absolute left-2 top-1/2 transform -translate-y-1/2 text-[var(--text-muted)]" style="font-size: 9px;"></i>
+ <button v-if="uploadTagSearchFilter"
+ @click="uploadTagSearchFilter = ''"
+ class="absolute right-2 top-1/2 transform -translate-y-1/2 text-[var(--text-muted)] hover:text-[var(--text-primary)]">
+ <i class="fas fa-times" style="font-size: 9px;"></i>
+ </button>
+ </div>
+ </div>
+
+ <!-- Available Tags Grid - Fixed Height -->
+ <div v-if="filteredAvailableTagsForUpload.length > 0"
+ class="overflow-y-auto"
+ style="max-height: 100px;">
+ <div class="grid grid-cols-2 gap-1">
+ <button v-for="tag in filteredAvailableTagsForUpload"
+ :key="tag.id"
+ @click="addTagToSelection(tag.id)"
+ class="group flex items-center justify-between px-1.5 py-1 rounded border border-[var(--border-secondary)] hover:border-[var(--border-focus)] bg-[var(--bg-primary)] hover:bg-[var(--bg-secondary)] transition-all">
+ <div class="flex items-center gap-1 min-w-0">
+ <i v-if="tag.group_id" class="fas fa-users flex-shrink-0" style="font-size: 9px;" :style="{ color: tag.color || '#6B7280' }"></i>
+ <span v-else class="w-2 h-2 rounded-full flex-shrink-0"
+ :style="{ backgroundColor: tag.color || '#6B7280' }"></span>
+ <span class="text-[11px] text-[var(--text-primary)] truncate">
+ <span v-if="tag.group_id" class="opacity-75">${tag.group_name}: </span>${tag.name}
+ </span>
+ </div>
+ <i class="fas fa-plus text-[var(--text-muted)] group-hover:text-[var(--text-accent)] transition-colors" style="font-size: 9px;"></i>
+ </button>
+ </div>
+ </div>
+ <div v-else class="py-2 text-center">
+ <p class="text-[11px] text-[var(--text-muted)]">
+ <i class="fas fa-search mr-1" style="font-size: 9px;"></i>
+ No matching tags
+ </p>
+ </div>
+ </div>
+ <!-- Empty States -->
+ <div v-else-if="availableTags.length === 0"
+ class="p-2 bg-[var(--bg-tertiary)] rounded-md border border-[var(--border-secondary)]">
+ <p class="text-xs text-[var(--text-muted)] text-center">
+ <i class="fas fa-info-circle mr-1" style="font-size: 10px;"></i>
+ <span v-text="t('help.noTagsCreated')"></span> <a href="/account#tags" class="text-[var(--text-accent)] hover:underline" v-text="t('help.createTags')"></a>
+ </p>
+ </div>
+ <div v-else class="p-2 bg-[var(--bg-tertiary)] rounded-md border border-[var(--border-secondary)]">
+ <p class="text-xs text-[var(--text-muted)] text-center">
+ <i class="fas fa-check-circle mr-1" style="font-size: 10px;"></i>
+ All tags selected
+ </p>
+ </div>
+
+ <p v-if="selectedTags.some(tag => tag.custom_prompt)" class="text-xs text-[var(--text-muted)] mt-1">
+ <i class="fas fa-info-circle mr-1 text-[var(--text-accent)]"></i>
+ Selected tags include custom summary prompts
+ </p>
+ <p v-if="selectedTags.length > 0 && useAsrEndpoint && selectedTags.some(tag => tag.default_language || tag.default_min_speakers || tag.default_max_speakers)"
+ class="text-xs text-[var(--text-muted)] mt-1">
+ <i class="fas fa-cog mr-1 text-[var(--text-accent)]"></i>
+ First tag's ASR settings will be applied: ${selectedTags[0].name}
+ </p>
+ </div>
+
+ <!-- Advanced Options for ASR (collapsible) -->
+ <div v-if="useAsrEndpoint" class="mt-4">
+ <button @click="showAdvancedOptions = !showAdvancedOptions"
+ class="w-full flex items-center justify-between px-3 py-2 bg-[var(--bg-tertiary)] rounded-md hover:bg-[var(--bg-accent)] transition-colors text-xs font-medium">
+ <span class="flex items-center gap-2 text-[var(--text-secondary)]">
+ <i class="fas fa-cog text-[var(--text-muted)]"></i>
+ <span v-text="t('help.advancedAsrOptions')"></span>
+ </span>
+ <i :class="['fas text-[var(--text-muted)]', showAdvancedOptions ? 'fa-chevron-up' : 'fa-chevron-down']"></i>
+ </button>
+
+ <div v-show="showAdvancedOptions" class="mt-2 p-3 bg-[var(--bg-tertiary)] rounded-md space-y-3 border border-[var(--border-secondary)]">
+ <!-- Language Selection -->
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">
+ Transcription Language
+ </label>
+ <select v-model="uploadLanguage"
+ class="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">
+ <option v-for="lang in languageOptions" :key="lang.value" :value="lang.value" v-text="lang.label"></option>
+ </select>
+ </div>
+
+ <!-- Speaker Settings -->
+ <div class="grid grid-cols-2 gap-3">
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1" v-text="t('form.minSpeakers')">
+ </label>
+ <input v-model.number="uploadMinSpeakers"
+ type="number"
+ min="1"
+ max="20"
+ class="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">
+ </div>
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1" v-text="t('form.maxSpeakers')">
+ </label>
+ <input v-model.number="uploadMaxSpeakers"
+ type="number"
+ min="1"
+ max="20"
+ class="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">
+ </div>
+ </div>
+
+ <p class="text-xs text-[var(--text-muted)] pt-1">
+ <i class="fas fa-info-circle mr-1 text-[var(--text-accent)]"></i>
+ Settings apply to all files in this session
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+</div>
diff --git a/templates/group-admin.html b/templates/group-admin.html
new file mode 100644
index 00000000..67fc5c97
--- /dev/null
+++ b/templates/group-admin.html
@@ -0,0 +1,1185 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <meta name="csrf-token" content="{{ csrf_token() }}">
+ <meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
+ <title>Group Management - Speakr</title>
+
+ <!-- Loading overlay to prevent FOUC - MUST be first -->
+ {% include 'includes/loading_overlay.html' %}
+
+ <link rel="icon" href="{{ url_for('static', filename='img/favicon.ico') }}" type="image/svg+xml">
+ <!-- All dependencies bundled locally for offline support -->
+<script src="{{ url_for('static', filename='vendor/js/tailwind.min.js') }}"></script>
+ <!-- All dependencies bundled locally for offline support -->
+<script src="{{ url_for('static', filename='vendor/js/vue.global.js') }}"></script>
+ <!-- All dependencies bundled locally for offline support -->
+<link rel="stylesheet" href="{{ url_for('static', filename='vendor/css/fontawesome.min.css') }}">
+ <link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
+ <script src="{{ url_for('static', filename='js/i18n.js') }}"></script>
+ <style>
+ /* Hide Vue content until compiled */
+ [v-cloak] {
+ display: none !important;
+ }
+
+ /* Hide scrollbar for tabs */
+ .scrollbar-hide {
+ -ms-overflow-style: none;
+ scrollbar-width: none;
+ }
+ .scrollbar-hide::-webkit-scrollbar {
+ display: none;
+ }
+
+ /* Custom select dropdown styling */
+ select {
+ appearance: none;
+ -webkit-appearance: none;
+ -moz-appearance: none;
+ padding-right: 2.5rem !important;
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23666' d='M6 9L1 4h10z'/%3E%3C/svg%3E");
+ background-repeat: no-repeat;
+ background-position: right 0.75rem center;
+ background-size: 12px 12px;
+ }
+
+ .dark select {
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23aaa' d='M6 9L1 4h10z'/%3E%3C/svg%3E");
+ }
+ </style>
+ <script>
+ // Initialize i18n
+ let t = (key) => key; // Default fallback
+
+ async function initializeI18n() {
+ const userLanguage = "{{ user_language }}";
+
+ // Initialize the global i18n instance
+ if (window.i18n) {
+ await window.i18n.init(userLanguage);
+
+ // Create a shorthand translation function
+ t = (key, params) => window.i18n.t(key, params);
+
+ // Update all elements with data-i18n attribute
+ document.querySelectorAll('[data-i18n]').forEach(el => {
+ const key = el.getAttribute('data-i18n');
+ el.textContent = t(key);
+ });
+
+ // Update all elements with data-i18n-placeholder attribute
+ document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
+ const key = el.getAttribute('data-i18n-placeholder');
+ el.placeholder = t(key);
+ });
+ }
+ }
+
+ // Function to apply the theme based on localStorage
+ function applyTheme() {
+ // Guard against early execution
+ if (!document.documentElement) return;
+
+ // Apply dark mode
+ const savedMode = localStorage.getItem('darkMode');
+ const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
+ if (savedMode === 'true' || (savedMode === null && prefersDark)) {
+ document.documentElement.classList.add('dark');
+ } else {
+ document.documentElement.classList.remove('dark');
+ }
+
+ // Apply color scheme
+ const savedScheme = localStorage.getItem('colorScheme') || 'blue';
+ const isDark = document.documentElement.classList.contains('dark');
+ const themePrefix = isDark ? 'theme-dark-' : 'theme-light-';
+
+ // Remove all other theme classes
+ const themeClasses = ['blue', 'emerald', 'purple', 'rose', 'amber', 'teal'];
+ themeClasses.forEach(theme => {
+ document.documentElement.classList.remove(`theme-light-${theme}`);
+ document.documentElement.classList.remove(`theme-dark-${theme}`);
+ });
+
+ // Add the correct theme class
+ if (savedScheme !== 'blue') {
+ document.documentElement.classList.add(themePrefix + savedScheme);
+ }
+ }
+ applyTheme();
+ </script>
+</head>
+<body class="bg-[var(--bg-primary)] text-[var(--text-primary)]">
+ <div id="app" v-cloak class="container mx-auto px-4 sm:px-6 lg:px-8 py-6 flex flex-col min-h-screen">
+ <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('recordings.index') }}" class="flex items-center">
+ <img src="{{ url_for('static', filename='img/icon-192x192.png') }}" alt="Speakr Logo" class="h-9 w-9 mr-2">
+ Speakr
+ </a>
+ </h1>
+ <div class="flex items-center space-x-2">
+ <button @click="toggleDarkMode" class="p-2 rounded-full text-[var(--text-muted)] hover:bg-[var(--bg-tertiary)] dark:text-gray-400 dark:hover:bg-gray-700 transition-colors duration-200" :title="isDarkMode ? 'Switch to Light Mode' : 'Switch to Dark Mode'">
+ <i :class="isDarkMode ? 'fas fa-sun' : 'fas fa-moon'"></i>
+ </button>
+ <div class="relative">
+ <button @click="isUserMenuOpen = !isUserMenuOpen" class="flex items-center px-3 py-2 border border-[var(--border-secondary)] rounded-lg text-[var(--text-secondary)] hover:text-[var(--text-accent)] focus:outline-none">
+ <i class="fas fa-users-cog mr-2"></i>
+ <span>{{ current_user.username }}</span>
+ <i class="fas fa-chevron-down ml-2"></i>
+ </button>
+ <div v-if="isUserMenuOpen" class="absolute right-0 mt-2 w-48 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg shadow-lg z-10">
+ <a href="{{ url_for('recordings.index') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)]">
+ <i class="fas fa-home mr-2"></i> Home
+ </a>
+ <a href="{{ url_for('auth.account') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-accent)]">
+ <i class="fas fa-user mr-2"></i> Account
+ </a>
+ <a href="{{ url_for('admin.group_management') }}" class="block px-4 py-2 text-[var(--text-accent)] bg-[var(--bg-accent)]">
+ <i class="fas fa-users-cog mr-2"></i>
+ Group Management
+ </a>
+ <a href="{{ url_for('auth.logout') }}" class="block px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-danger)]">
+ <i class="fas fa-sign-out-alt mr-2"></i> Sign Out
+ </a>
+ </div>
+ </div>
+ </div>
+ </header>
+
+ <main class="flex-grow">
+ <div class="bg-[var(--bg-secondary)] p-4 sm:p-6 lg:p-8 rounded-xl shadow-lg border border-[var(--border-primary)]">
+ <h2 class="text-2xl font-semibold text-[var(--text-primary)] mb-6">Group Management</h2>
+
+ {% with messages = get_flashed_messages(with_categories=true) %}
+ {% if messages %}
+ {% for category, message in messages %}
+ <div class="mb-4 p-3 rounded-lg {% if category == 'success' %}bg-[var(--bg-success-light)] text-[var(--text-success-strong)]{% elif category == 'danger' %}bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)]{% else %}bg-[var(--bg-info-light)] text-[var(--text-info-strong)]{% endif %}">
+ {{ message }}
+ </div>
+ {% endfor %}
+ {% endif %}
+ {% endwith %}
+
+ <!-- Tabs -->
+ <!-- Main Content Area -->
+ <div class="p-6">
+ <!-- Groups Management -->
+ <div v-show="activeTab === 'groups'">
+ <div class="flex justify-between items-center mb-4">
+ <h3 class="text-lg font-medium text-[var(--text-secondary)]">Group Management</h3>
+ <button v-if="!isTeamAdminOnly" @click="openCreateTeamModal" 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-plus mr-2"></i> Create Group
+ </button>
+ </div>
+
+ <!-- Groups List -->
+ <div class="bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] overflow-hidden">
+ <div v-if="groups.length > 0">
+ <table class="min-w-full divide-y divide-[var(--border-primary)]">
+ <thead class="bg-[var(--bg-tertiary)]">
+ <tr>
+ <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">Group Name</th>
+ <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">Description</th>
+ <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">Members</th>
+ <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">Created</th>
+ <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-[var(--text-muted)] uppercase tracking-wider">Actions</th>
+ </tr>
+ </thead>
+ <tbody class="bg-[var(--bg-secondary)] divide-y divide-[var(--border-primary)]">
+ <tr v-for="group in groups" :key="group.id" class="hover:bg-[var(--bg-tertiary)]">
+ <td class="px-6 py-4 whitespace-nowrap">
+ <div class="text-sm font-medium text-[var(--text-primary)]">${ group.name }</div>
+ </td>
+ <td class="px-6 py-4">
+ <div class="text-sm text-[var(--text-secondary)]">${ group.description || 'No description' }</div>
+ </td>
+ <td class="px-6 py-4 whitespace-nowrap">
+ <div class="text-sm text-[var(--text-secondary)]">
+ <i class="fas fa-users mr-1"></i>
+ ${ group.member_count || 0 } members
+ </div>
+ </td>
+ <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-muted)]">
+ ${ new Date(group.created_at).toLocaleDateString() }
+ </td>
+ <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium space-x-2">
+ <button @click="openManageTeamModal(group)" class="text-blue-500 hover:text-blue-700" title="Manage Members">
+ <i class="fas fa-users-cog"></i>
+ </button>
+ <button @click="openManageTeamTagsModal(group)" class="text-purple-500 hover:text-purple-700" title="Manage Group Tags">
+ <i class="fas fa-tags"></i>
+ </button>
+ <button @click="openEditTeamModal(group)" class="text-[var(--text-accent)] hover:text-[var(--text-accent-hover)]" title="Edit Group">
+ <i class="fas fa-edit"></i>
+ </button>
+ <button v-if="!isTeamAdminOnly" @click="confirmDeleteTeam(group)" class="text-red-500 hover:text-red-700" title="Delete Group">
+ <i class="fas fa-trash"></i>
+ </button>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ <div v-else class="p-8 text-center">
+ <i class="fas fa-users-slash text-4xl text-[var(--text-muted)] mb-3"></i>
+ <p class="text-[var(--text-muted)]" v-text="isTeamAdminOnly ? 'You are not an admin of any groups yet' : 'No groups created yet'"></p>
+ <button v-if="!isTeamAdminOnly" @click="openCreateTeamModal" class="mt-4 px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)]">
+ <i class="fas fa-plus mr-2"></i> Create Your First Group
+ </button>
+ </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 &copy; {{ now.year }}
+ </footer>
+ <!-- Create/Edit Group Modal -->
+ <div v-if="showTeamModal" @click.self="closeTeamModal" class="fixed inset-0 bg-black bg-opacity-70 backdrop-blur-sm flex items-center justify-center z-50 p-4">
+ <div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-md">
+ <div class="flex justify-between items-center mb-4">
+ <h3 class="text-xl font-semibold text-[var(--text-primary)]">${ editingTeam ? 'Edit Group' : 'Create Group' }</h3>
+ <button @click="closeTeamModal" class="text-[var(--text-muted)] hover:text-[var(--text-secondary)]">&times;</button>
+ </div>
+ <form @submit.prevent="saveTeam">
+ <div class="space-y-4">
+ <div>
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Group Name *</label>
+ <input v-model="teamForm.name" type="text" required
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
+ placeholder="Enter group name">
+ </div>
+ <div>
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Description</label>
+ <textarea v-model="teamForm.description" rows="3"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]"
+ placeholder="Optional description"></textarea>
+ </div>
+ <div v-if="teamError" class="p-3 bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)] rounded-md text-sm">
+ ${ teamError }
+ </div>
+ </div>
+ <div class="flex justify-end space-x-3 mt-6">
+ <button type="button" @click="closeTeamModal"
+ class="px-4 py-2 border border-[var(--border-secondary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--bg-tertiary)]">
+ Cancel
+ </button>
+ <button type="submit"
+ class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)]">
+ ${ editingTeam ? 'Update Group' : 'Create Group' }
+ </button>
+ </div>
+ </form>
+ </div>
+ </div>
+
+ <!-- Manage Group Members Modal -->
+ <div v-if="showManageTeamModal" @click.self="closeManageTeamModal" class="fixed inset-0 bg-black bg-opacity-70 backdrop-blur-sm flex items-center justify-center z-50 p-4">
+ <div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
+ <div class="flex justify-between items-center mb-4">
+ <h3 class="text-xl font-semibold text-[var(--text-primary)]">Manage Group: ${ currentTeam?.name }</h3>
+ <button @click="closeManageTeamModal" class="text-[var(--text-muted)] hover:text-[var(--text-secondary)]">&times;</button>
+ </div>
+
+ <!-- Add Member Section -->
+ <div class="mb-6 p-4 bg-[var(--bg-tertiary)] rounded-lg">
+ <h4 class="text-sm font-medium text-[var(--text-secondary)] mb-3">Add Member</h4>
+ <div class="flex space-x-2">
+ <div class="flex-1">
+ <select v-model="newMemberUserId"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
+ <option value="">Select a user...</option>
+ <option v-for="user in availableUsers" :key="user.id" :value="user.id">
+ ${ user.username } (${ user.email })
+ </option>
+ </select>
+ </div>
+ <div>
+ <select v-model="newMemberRole"
+ class="px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
+ <option value="member">Member</option>
+ <option value="admin">Admin</option>
+ </select>
+ </div>
+ <button @click="addTeamMember" :disabled="!newMemberUserId"
+ class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)] disabled:opacity-50 disabled:cursor-not-allowed">
+ <i class="fas fa-plus"></i> Add
+ </button>
+ </div>
+ </div>
+
+ <!-- Current Members -->
+ <div>
+ <h4 class="text-sm font-medium text-[var(--text-secondary)] mb-3">Current Members (${ teamMembers.length })</h4>
+ <div v-if="teamMembers.length > 0" class="space-y-2">
+ <div v-for="member in teamMembers" :key="member.user_id"
+ class="flex items-center justify-between p-3 bg-[var(--bg-tertiary)] rounded-md">
+ <div class="flex items-center space-x-3">
+ <i class="fas fa-user text-[var(--text-muted)]"></i>
+ <div>
+ <div class="text-sm font-medium text-[var(--text-primary)]">${ member.username }</div>
+ <div class="text-xs text-[var(--text-muted)]">${ member.email }</div>
+ </div>
+ </div>
+ <div class="flex items-center space-x-2">
+ <select v-model="member.role" @change="updateMemberRole(member)"
+ class="px-2 py-1 text-sm border border-[var(--border-secondary)] rounded bg-[var(--bg-input)] text-[var(--text-primary)]">
+ <option value="member">Member</option>
+ <option value="admin">Admin</option>
+ </select>
+ <button @click="removeTeamMember(member)"
+ class="text-red-500 hover:text-red-700" title="Remove from group">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+ </div>
+ </div>
+ <div v-else class="text-center py-4 text-[var(--text-muted)]">
+ No members yet
+ </div>
+ </div>
+
+ <div v-if="teamMemberError" class="mt-4 p-3 bg-[var(--bg-danger-light)] text-[var(--text-danger-strong)] rounded-md text-sm">
+ ${ teamMemberError }
+ </div>
+
+ <div class="flex justify-between mt-6">
+ <button @click="syncTeamShares"
+ class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 flex items-center gap-2">
+ <i class="fas fa-sync-alt"></i>
+ Sync Group Shares
+ </button>
+ <button @click="closeManageTeamModal"
+ class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)]">
+ Done
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Sync Group Shares Confirmation Modal -->
+ <div v-if="showSyncSharesModal" @click.self="showSyncSharesModal = false" class="fixed inset-0 bg-black bg-opacity-70 backdrop-blur-sm flex items-center justify-center z-50 p-4">
+ <div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-md">
+ <div class="flex justify-between items-center mb-4">
+ <h3 class="text-xl font-semibold text-[var(--text-primary)]">Sync Group Shares</h3>
+ <button @click="showSyncSharesModal = false" class="text-[var(--text-muted)] hover:text-[var(--text-secondary)]">&times;</button>
+ </div>
+ <p class="mb-4 text-[var(--text-secondary)]">
+ This will create shares for all recordings with group tags that have auto-sharing enabled.
+ </p>
+ <p class="mb-4 text-[var(--text-muted)] text-sm">
+ <i class="fas fa-info-circle mr-1"></i>
+ Only missing shares will be created - existing shares won't be duplicated.
+ </p>
+ <div class="flex justify-end space-x-3">
+ <button @click="showSyncSharesModal = false" class="px-4 py-2 border border-[var(--border-secondary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--bg-tertiary)]">Cancel</button>
+ <button @click="confirmSyncShares" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
+ <i class="fas fa-sync-alt mr-2"></i>Sync Now
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Sync Results Modal -->
+ <div v-if="showSyncResultsModal" @click.self="showSyncResultsModal = false" class="fixed inset-0 bg-black bg-opacity-70 backdrop-blur-sm flex items-center justify-center z-50 p-4">
+ <div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-md">
+ <div class="flex justify-between items-center mb-4">
+ <h3 class="text-xl font-semibold text-[var(--text-primary)]">
+ <i class="fas fa-check-circle text-green-500 mr-2"></i>Sync Complete
+ </h3>
+ <button @click="showSyncResultsModal = false" class="text-[var(--text-muted)] hover:text-[var(--text-secondary)]">&times;</button>
+ </div>
+ <div class="mb-4 space-y-2">
+ <div class="flex justify-between text-[var(--text-secondary)]">
+ <span>Shares created:</span>
+ <span class="font-semibold">${ syncResults.shares_created }</span>
+ </div>
+ <div class="flex justify-between text-[var(--text-secondary)]">
+ <span>Recordings processed:</span>
+ <span class="font-semibold">${ syncResults.recordings_processed }</span>
+ </div>
+ </div>
+ <div class="flex justify-end">
+ <button @click="showSyncResultsModal = false" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)]">
+ Done
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Delete Group Confirmation Modal -->
+ <div v-if="showDeleteTeamModal" @click.self="showDeleteTeamModal = false" class="fixed inset-0 bg-black bg-opacity-70 backdrop-blur-sm flex items-center justify-center z-50 p-4">
+ <div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-md">
+ <div class="flex justify-between items-center mb-4">
+ <h3 class="text-xl font-semibold text-[var(--text-primary)]">Delete Group</h3>
+ <button @click="showDeleteTeamModal = false" class="text-[var(--text-muted)] hover:text-[var(--text-secondary)]">&times;</button>
+ </div>
+ <p class="mb-4 text-[var(--text-secondary)]">Are you sure you want to delete the group <span class="font-semibold">${ teamToDelete?.name }</span>? This will remove all members from the group. This action cannot be undone.</p>
+ <div class="flex justify-end space-x-3">
+ <button @click="showDeleteTeamModal = false" class="px-4 py-2 border border-[var(--border-secondary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--bg-tertiary)]">Cancel</button>
+ <button @click="deleteTeam" class="px-4 py-2 bg-[var(--bg-danger)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-danger-hover)]">Delete Group</button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Manage Group Tags Modal -->
+ <div v-if="showManageTeamTagsModal" @click.self="closeManageTeamTagsModal" class="fixed inset-0 bg-black bg-opacity-70 backdrop-blur-sm flex items-center justify-center z-50 p-4">
+ <div class="bg-[var(--bg-secondary)] p-6 rounded-lg shadow-xl w-full max-w-3xl max-h-[90vh] overflow-y-auto">
+ <div class="flex justify-between items-center mb-4">
+ <h3 class="text-xl font-semibold text-[var(--text-primary)]">Manage Tags for ${ currentTeam?.name }</h3>
+ <button @click="closeManageTeamTagsModal" class="text-[var(--text-muted)] hover:text-[var(--text-secondary)]">&times;</button>
+ </div>
+
+ <!-- Create/Edit Tag Form -->
+ <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg mb-4 border border-[var(--border-primary)]">
+ <div class="flex justify-between items-center mb-3">
+ <h4 class="text-sm font-medium text-[var(--text-secondary)]">
+ ${ editingTeamTagId ? 'Edit Group Tag' : 'Create New Group Tag' }
+ </h4>
+ <button v-if="editingTeamTagId" @click="cancelEditTeamTag" type="button" class="text-xs text-[var(--text-muted)] hover:text-[var(--text-primary)]">
+ <i class="fas fa-times mr-1"></i> Cancel
+ </button>
+ </div>
+ <form @submit.prevent="saveTeamTag" class="space-y-3">
+ <div class="grid grid-cols-2 gap-3">
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">Tag Name *</label>
+ <input v-model="newTeamTag.name" type="text" required maxlength="50"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-input)] text-[var(--text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)]"
+ placeholder="e.g., Project Alpha">
+ </div>
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">Color</label>
+ <input v-model="newTeamTag.color" type="color"
+ class="w-full h-10 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-input)] cursor-pointer">
+ </div>
+ </div>
+
+ <!-- Custom Prompt -->
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">
+ Custom Summarization Prompt
+ <span class="text-[var(--text-muted)] font-normal">- Optional AI instructions</span>
+ </label>
+ <textarea v-model="newTeamTag.custom_prompt" rows="3"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-input)] text-[var(--text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)]"
+ placeholder="Enter custom instructions for AI summarization (e.g., 'Focus on action items and deadlines')"></textarea>
+ <p class="text-xs text-[var(--text-muted)] mt-1">
+ Recordings with this tag will use this prompt for AI summaries and chat.
+ </p>
+ </div>
+
+ <!-- Transcription Settings -->
+ <div class="grid grid-cols-3 gap-3">
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">Default Language</label>
+ <select v-model="newTeamTag.default_language"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-input)] text-[var(--text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)]">
+ <option value="">Auto-detect</option>
+ <option value="en">English</option>
+ <option value="es">Spanish</option>
+ <option value="fr">French</option>
+ <option value="de">German</option>
+ <option value="zh">Chinese</option>
+ <option value="ja">Japanese</option>
+ <option value="pt">Portuguese</option>
+ <option value="it">Italian</option>
+ </select>
+ </div>
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">Min Speakers</label>
+ <input v-model.number="newTeamTag.default_min_speakers" type="number" min="1" max="10"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-input)] text-[var(--text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)]"
+ placeholder="1">
+ </div>
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">Max Speakers</label>
+ <input v-model.number="newTeamTag.default_max_speakers" type="number" min="1" max="10"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-input)] text-[var(--text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)]"
+ placeholder="5">
+ </div>
+ </div>
+
+ <!-- Retention and Protection -->
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">
+ Retention Period (days)
+ <span class="text-[var(--text-muted)] font-normal">- Optional override for auto-deletion</span>
+ </label>
+ <input v-model.number="newTeamTag.retention_days" type="number" min="0" step="1"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-input)] text-[var(--text-primary)] text-sm focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)]"
+ placeholder="Leave empty to use global retention">
+ <p class="text-xs text-[var(--text-muted)] mt-1">
+ Recordings with this tag will be deleted after this many days. Leave empty to use global retention (${ globalRetentionDays } days).
+ </p>
+ </div>
+ <div class="flex items-center">
+ <input v-model="newTeamTag.protect_from_deletion" type="checkbox" id="protectFromDeletion"
+ class="mr-2 h-4 w-4 text-[var(--text-accent)] border-[var(--border-secondary)] rounded focus:ring-[var(--border-focus)]">
+ <label for="protectFromDeletion" class="text-xs text-[var(--text-secondary)]">
+ <i class="fas fa-shield-alt mr-1"></i> Protect recordings with this tag from auto-deletion
+ </label>
+ </div>
+ <div class="space-y-2">
+ <div class="flex items-center">
+ <input v-model="newTeamTag.auto_share_on_apply" type="checkbox" id="autoShareOnApply"
+ class="mr-2 h-4 w-4 text-[var(--text-accent)] border-[var(--border-secondary)] rounded focus:ring-[var(--border-focus)]">
+ <label for="autoShareOnApply" class="text-xs text-[var(--text-secondary)]">
+ <i class="fas fa-user-friends mr-1"></i> Auto-share recordings with all group members when this tag is applied
+ </label>
+ </div>
+ <div class="flex items-center">
+ <input v-model="newTeamTag.share_with_group_lead" type="checkbox" id="shareWithGroupLead"
+ class="mr-2 h-4 w-4 text-[var(--text-accent)] border-[var(--border-secondary)] rounded focus:ring-[var(--border-focus)]">
+ <label for="shareWithGroupLead" class="text-xs text-[var(--text-secondary)]">
+ <i class="fas fa-user-tie mr-1"></i> Share recordings with group admins when this tag is applied
+ </label>
+ </div>
+ <p class="text-xs text-[var(--text-muted)] ml-6">
+ Note: If both are enabled, all group members will have access. If only "group admins" is enabled, only group leads will have access.
+ </p>
+ </div>
+ <div v-if="teamTagError" class="text-[var(--text-danger)] text-xs">${ teamTagError }</div>
+ <button type="submit" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)] text-sm">
+ <i :class="editingTeamTagId ? 'fas fa-save' : 'fas fa-plus'" class="mr-1"></i>
+ ${ editingTeamTagId ? 'Update Tag' : 'Create Tag' }
+ </button>
+ </form>
+ </div>
+
+ <!-- Existing Group Tags -->
+ <div>
+ <h4 class="text-sm font-medium text-[var(--text-secondary)] mb-3">Group Tags</h4>
+ <div v-if="teamTags.length > 0" class="space-y-3">
+ <div v-for="tag in teamTags" :key="tag.id"
+ class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)]">
+ <div class="flex items-start justify-between mb-2">
+ <div class="flex items-center space-x-3 flex-1">
+ <span class="inline-block w-4 h-4 rounded flex-shrink-0" :style="{ backgroundColor: tag.color }"></span>
+ <div class="flex-1">
+ <div class="text-sm font-medium text-[var(--text-primary)]">${ tag.name }</div>
+ <div class="text-xs text-[var(--text-muted)] mt-1 space-x-3">
+ <span v-if="tag.retention_days">
+ <i class="fas fa-clock mr-1"></i> ${ tag.retention_days } day retention
+ </span>
+ <span v-else>
+ <i class="fas fa-globe mr-1"></i> Global retention
+ </span>
+ <span v-if="tag.protect_from_deletion" class="text-green-500">
+ <i class="fas fa-shield-alt mr-1"></i> Protected
+ </span>
+ </div>
+ </div>
+ </div>
+ <div class="flex gap-2 flex-shrink-0">
+ <button @click="editTeamTag(tag)" class="text-blue-500 hover:text-blue-700 px-2 py-1" title="Edit Tag">
+ <i class="fas fa-edit"></i>
+ </button>
+ <button @click="deleteTeamTag(tag)" class="text-red-500 hover:text-red-700 px-2 py-1" title="Delete Tag">
+ <i class="fas fa-trash"></i>
+ </button>
+ </div>
+ </div>
+
+ <!-- Additional details if configured -->
+ <div v-if="tag.custom_prompt || tag.default_language || tag.default_min_speakers || tag.default_max_speakers"
+ class="mt-2 pt-2 border-t border-[var(--border-secondary)] space-y-1">
+ <div v-if="tag.custom_prompt" class="text-xs text-[var(--text-muted)]">
+ <i class="fas fa-comment-dots mr-1"></i> Custom prompt configured
+ </div>
+ <div v-if="tag.default_language" class="text-xs text-[var(--text-muted)]">
+ <i class="fas fa-language mr-1"></i> Language: ${ tag.default_language.toUpperCase() }
+ </div>
+ <div v-if="tag.default_min_speakers || tag.default_max_speakers" class="text-xs text-[var(--text-muted)]">
+ <i class="fas fa-users mr-1"></i> Speakers:
+ <span v-if="tag.default_min_speakers">${ tag.default_min_speakers }-</span><span v-if="tag.default_max_speakers">${ tag.default_max_speakers }</span><span v-else>auto</span>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div v-else class="text-center py-8 text-[var(--text-muted)]">
+ <i class="fas fa-tags text-3xl mb-2"></i>
+ <p class="text-sm">No group tags created yet</p>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <script>
+ const { createApp, ref, computed, onMounted, watch } = Vue
+
+ // Initialize i18n before Vue app creation
+ initializeI18n().then(() => {
+ // Get the i18n instance to properly bind the t function
+ const i18nInstance = window.i18n;
+
+ createApp({
+ setup() {
+ // State - groups only
+ const isTeamAdminOnly = ref(true); // This page is only for group admins
+ const activeTab = ref('groups'); // Single tab page
+ const groups = ref([]);
+ const globalRetentionDays = ref({{ global_retention_days }});
+ const isDarkMode = ref(document.documentElement.classList.contains('dark'));
+ const isUserMenuOpen = ref(false);
+
+ // Group modals state
+ const showTeamModal = ref(false);
+ const showManageTeamModal = ref(false);
+ const showDeleteTeamModal = ref(false);
+ const showSyncSharesModal = ref(false);
+ const showSyncResultsModal = ref(false);
+ const showManageTeamTagsModal = ref(false);
+ const editingTeam = ref(null);
+ const teamToDelete = ref(null);
+ const currentTeam = ref(null);
+ const teamForm = ref({ name: '', description: '' });
+ const teamError = ref('');
+ const teamMembers = ref([]);
+ const teamMemberError = ref('');
+ const newMemberUserId = ref('');
+ const newMemberRole = ref('member');
+ const availableUsers = ref([]);
+ const teamTags = ref([]);
+ const editingTeamTagId = ref(null);
+ const newTeamTag = ref({
+ name: '',
+ color: '#3B82F6',
+ custom_prompt: '',
+ default_language: '',
+ default_min_speakers: null,
+ default_max_speakers: null,
+ retention_days: null,
+ protect_from_deletion: false,
+ auto_share_on_apply: true,
+ share_with_group_lead: true
+ });
+ const teamTagError = ref('');
+ const syncResults = ref({ shares_created: 0, recordings_processed: 0 });
+ const users = ref([]);
+
+ const loadGroups = async () => {
+ try {
+ const response = await fetch('/api/admin/groups');
+ if (!response.ok) throw new Error('Failed to load groups');
+ const data = await response.json();
+ groups.value = data.groups || [];
+ } catch (error) {
+ console.error('Error loading teams:', error);
+ }
+ };
+
+ const openCreateTeamModal = () => {
+ editingTeam.value = null;
+ teamForm.value = { name: '', description: '' };
+ teamError.value = '';
+ showTeamModal.value = true;
+ };
+
+ const openEditTeamModal = (group) => {
+ editingTeam.value = group;
+ teamForm.value = { name: group.name, description: group.description || '' };
+ teamError.value = '';
+ showTeamModal.value = true;
+ };
+
+ const closeTeamModal = () => {
+ showTeamModal.value = false;
+ editingTeam.value = null;
+ teamForm.value = { name: '', description: '' };
+ teamError.value = '';
+ };
+
+ const saveTeam = async () => {
+ teamError.value = '';
+ try {
+ const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
+ const headers = { 'Content-Type': 'application/json' };
+ if (csrfToken) headers['X-CSRFToken'] = csrfToken;
+
+ const url = editingTeam.value
+ ? `/api/admin/groups/${editingTeam.value.id}`
+ : '/api/admin/groups';
+ const method = editingTeam.value ? 'PUT' : 'POST';
+
+ const response = await fetch(url, {
+ method,
+ headers,
+ body: JSON.stringify(teamForm.value)
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to save group');
+ }
+
+ closeTeamModal();
+ await loadGroups();
+ } catch (error) {
+ teamError.value = error.message;
+ }
+ };
+
+ const confirmDeleteTeam = (group) => {
+ teamToDelete.value = group;
+ showDeleteTeamModal.value = true;
+ };
+
+ const deleteTeam = async () => {
+ try {
+ const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
+ const headers = {};
+ if (csrfToken) headers['X-CSRFToken'] = csrfToken;
+
+ const response = await fetch(`/api/admin/groups/${teamToDelete.value.id}`, {
+ method: 'DELETE',
+ headers
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to delete group');
+ }
+
+ showDeleteTeamModal.value = false;
+ teamToDelete.value = null;
+ await loadGroups();
+ } catch (error) {
+ alert(error.message);
+ }
+ };
+
+ const openManageTeamModal = async (group) => {
+ currentTeam.value = group;
+ newMemberUserId.value = '';
+ newMemberRole.value = 'member';
+ teamMemberError.value = '';
+ showManageTeamModal.value = true;
+ await loadTeamMembers(group.id);
+ };
+
+ const closeManageTeamModal = () => {
+ showManageTeamModal.value = false;
+ currentTeam.value = null;
+ teamMembers.value = [];
+ newMemberUserId.value = '';
+ newMemberRole.value = 'member';
+ teamMemberError.value = '';
+ };
+
+ const loadTeamMembers = async (groupId) => {
+ try {
+ const response = await fetch(`/api/admin/groups/${groupId}`);
+ if (!response.ok) throw new Error('Failed to load group members');
+ const data = await response.json();
+ teamMembers.value = data.members || [];
+ } catch (error) {
+ console.error('Error loading group members:', error);
+ teamMemberError.value = error.message;
+ }
+ };
+
+ const addTeamMember = async () => {
+ if (!newMemberUserId.value) return;
+
+ teamMemberError.value = '';
+ try {
+ const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
+ const headers = { 'Content-Type': 'application/json' };
+ if (csrfToken) headers['X-CSRFToken'] = csrfToken;
+
+ const response = await fetch(`/api/admin/groups/${currentTeam.value.id}/members`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({
+ user_id: parseInt(newMemberUserId.value),
+ role: newMemberRole.value
+ })
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to add member');
+ }
+
+ newMemberUserId.value = '';
+ newMemberRole.value = 'member';
+ await loadTeamMembers(currentTeam.value.id);
+ await loadGroups(); // Refresh to update member count
+ } catch (error) {
+ teamMemberError.value = error.message;
+ }
+ };
+
+ const updateMemberRole = async (member) => {
+ teamMemberError.value = '';
+ try {
+ const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
+ const headers = { 'Content-Type': 'application/json' };
+ if (csrfToken) headers['X-CSRFToken'] = csrfToken;
+
+ const response = await fetch(`/api/admin/groups/${currentTeam.value.id}/members/${member.user_id}`, {
+ method: 'PUT',
+ headers,
+ body: JSON.stringify({ role: member.role })
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to update role');
+ }
+ } catch (error) {
+ teamMemberError.value = error.message;
+ await loadTeamMembers(currentTeam.value.id); // Reload to revert on error
+ }
+ };
+
+ const removeTeamMember = async (member) => {
+ if (!confirm(`Remove ${member.username} from the group?`)) return;
+
+ teamMemberError.value = '';
+ try {
+ const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
+ const headers = {};
+ if (csrfToken) headers['X-CSRFToken'] = csrfToken;
+
+ const response = await fetch(`/api/admin/groups/${currentTeam.value.id}/members/${member.user_id}`, {
+ method: 'DELETE',
+ headers
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to remove member');
+ }
+
+ await loadTeamMembers(currentTeam.value.id);
+ await loadGroups(); // Refresh to update member count
+ } catch (error) {
+ teamMemberError.value = error.message;
+ }
+ };
+
+ const syncTeamShares = () => {
+ if (!currentTeam.value) return;
+ showSyncSharesModal.value = true;
+ };
+
+ const confirmSyncShares = async () => {
+ showSyncSharesModal.value = false;
+ teamMemberError.value = '';
+
+ try {
+ const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
+ const headers = { 'Content-Type': 'application/json' };
+ if (csrfToken) headers['X-CSRFToken'] = csrfToken;
+
+ const response = await fetch(`/api/groups/${currentTeam.value.id}/sync-shares`, {
+ method: 'POST',
+ headers
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to sync shares');
+ }
+
+ const result = await response.json();
+ syncResults.value = {
+ shares_created: result.shares_created,
+ recordings_processed: result.recordings_processed
+ };
+ showSyncResultsModal.value = true;
+ } catch (error) {
+ teamMemberError.value = error.message;
+ }
+ };
+
+ // Group Tags Management
+ const openManageTeamTagsModal = async (group) => {
+ currentTeam.value = group;
+ teamTagError.value = '';
+ await loadTeamTags(group.id);
+ showManageTeamTagsModal.value = true;
+ };
+
+ const closeManageTeamTagsModal = () => {
+ showManageTeamTagsModal.value = false;
+ currentTeam.value = null;
+ teamTags.value = [];
+ editingTeamTagId.value = null;
+ newTeamTag.value = {
+ name: '',
+ color: '#3B82F6',
+ custom_prompt: '',
+ default_language: '',
+ default_min_speakers: null,
+ default_max_speakers: null,
+ retention_days: null,
+ protect_from_deletion: false,
+ auto_share_on_apply: true,
+ share_with_group_lead: true
+ };
+ teamTagError.value = '';
+ };
+
+ const loadTeamTags = async (groupId) => {
+ try {
+ const response = await fetch(`/api/groups/${groupId}/tags`);
+ if (!response.ok) throw new Error('Failed to load group tags');
+ const data = await response.json();
+ teamTags.value = data.tags || [];
+ } catch (error) {
+ teamTagError.value = error.message;
+ }
+ };
+
+ const editTeamTag = (tag) => {
+ editingTeamTagId.value = tag.id;
+ newTeamTag.value = {
+ name: tag.name,
+ color: tag.color,
+ custom_prompt: tag.custom_prompt || '',
+ default_language: tag.default_language || '',
+ default_min_speakers: tag.default_min_speakers,
+ default_max_speakers: tag.default_max_speakers,
+ retention_days: tag.retention_days,
+ protect_from_deletion: tag.protect_from_deletion || false,
+ auto_share_on_apply: tag.auto_share_on_apply !== undefined ? tag.auto_share_on_apply : true,
+ share_with_group_lead: tag.share_with_group_lead !== undefined ? tag.share_with_group_lead : true
+ };
+ // Scroll to top of modal
+ document.querySelector('.max-h-\\[90vh\\]')?.scrollTo({ top: 0, behavior: 'smooth' });
+ };
+
+ const cancelEditTeamTag = () => {
+ editingTeamTagId.value = null;
+ newTeamTag.value = {
+ name: '',
+ color: '#3B82F6',
+ custom_prompt: '',
+ default_language: '',
+ default_min_speakers: null,
+ default_max_speakers: null,
+ retention_days: null,
+ protect_from_deletion: false,
+ auto_share_on_apply: true,
+ share_with_group_lead: true
+ };
+ teamTagError.value = '';
+ };
+
+ const saveTeamTag = async () => {
+ teamTagError.value = '';
+ try {
+ const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
+ const headers = { 'Content-Type': 'application/json' };
+ if (csrfToken) headers['X-CSRFToken'] = csrfToken;
+
+ const payload = {
+ name: newTeamTag.value.name,
+ color: newTeamTag.value.color,
+ protect_from_deletion: newTeamTag.value.protect_from_deletion,
+ auto_share_on_apply: newTeamTag.value.auto_share_on_apply,
+ share_with_group_lead: newTeamTag.value.share_with_group_lead
+ };
+
+ // Add custom prompt if provided
+ if (newTeamTag.value.custom_prompt && newTeamTag.value.custom_prompt.trim()) {
+ payload.custom_prompt = newTeamTag.value.custom_prompt.trim();
+ }
+
+ // Add language if selected
+ if (newTeamTag.value.default_language) {
+ payload.default_language = newTeamTag.value.default_language;
+ }
+
+ // Add speaker settings if provided
+ if (newTeamTag.value.default_min_speakers) {
+ payload.default_min_speakers = newTeamTag.value.default_min_speakers;
+ }
+ if (newTeamTag.value.default_max_speakers) {
+ payload.default_max_speakers = newTeamTag.value.default_max_speakers;
+ }
+
+ // Only include retention_days if it's set and > 0
+ if (newTeamTag.value.retention_days && newTeamTag.value.retention_days > 0) {
+ payload.retention_days = newTeamTag.value.retention_days;
+ }
+
+ let response;
+ if (editingTeamTagId.value) {
+ // Update existing tag
+ response = await fetch(`/api/tags/${editingTeamTagId.value}`, {
+ method: 'PUT',
+ headers,
+ body: JSON.stringify(payload)
+ });
+ } else {
+ // Create new tag
+ response = await fetch(`/api/groups/${currentTeam.value.id}/tags`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify(payload)
+ });
+ }
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || (editingTeamTagId.value ? 'Failed to update tag' : 'Failed to create tag'));
+ }
+
+ // Reset form and reload
+ editingTeamTagId.value = null;
+ newTeamTag.value = {
+ name: '',
+ color: '#3B82F6',
+ custom_prompt: '',
+ default_language: '',
+ default_min_speakers: null,
+ default_max_speakers: null,
+ retention_days: null,
+ protect_from_deletion: false,
+ auto_share_on_apply: true,
+ share_with_group_lead: true
+ };
+ await loadTeamTags(currentTeam.value.id);
+ } catch (error) {
+ teamTagError.value = error.message;
+ }
+ };
+
+ const deleteTeamTag = async (tag) => {
+ if (!confirm(`Delete the tag "${tag.name}"? This will remove the tag from all recordings.`)) return;
+
+ teamTagError.value = '';
+ try {
+ const csrfToken = document.querySelector('meta[name=csrf-token]')?.getAttribute('content');
+ const headers = {};
+ if (csrfToken) headers['X-CSRFToken'] = csrfToken;
+
+ const response = await fetch(`/api/tags/${tag.id}`, {
+ method: 'DELETE',
+ headers
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to delete tag');
+ }
+
+ await loadTeamTags(currentTeam.value.id);
+ } catch (error) {
+ teamTagError.value = error.message;
+ }
+ };
+
+ const formatFileSize = (bytes) => {
+ if (!bytes || bytes === 0) return '0 Bytes';
+
+ const k = 1024;
+ const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
+
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
+ };
+
+ const toggleDarkMode = () => {
+ isDarkMode.value = !isDarkMode.value;
+ if (isDarkMode.value) {
+ document.documentElement.classList.add('dark');
+ localStorage.setItem('darkMode', 'true');
+ } else {
+ document.documentElement.classList.remove('dark');
+ localStorage.setItem('darkMode', 'false');
+ }
+ };
+
+ const initializeDarkMode = () => {
+ const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
+ const savedMode = localStorage.getItem('darkMode');
+ if (savedMode === 'true' || (savedMode === null && prefersDark)) {
+ isDarkMode.value = true;
+ document.documentElement.classList.add('dark');
+ }
+ };
+
+ onMounted(async () => {
+ loadGroups();
+ initializeDarkMode();
+ });
+
+ return {
+ // i18n - bind to i18n instance to maintain context
+ t: (key, params) => i18nInstance ? i18nInstance.t(key, params) : key,
+
+ // State
+ isTeamAdminOnly,
+ activeTab,
+ groups,
+ globalRetentionDays,
+ isDarkMode,
+ isUserMenuOpen,
+ toggleDarkMode,
+ showTeamModal,
+ showManageTeamModal,
+ showDeleteTeamModal,
+ showSyncSharesModal,
+ showSyncResultsModal,
+ showManageTeamTagsModal,
+ editingTeam,
+ teamToDelete,
+ currentTeam,
+ teamForm,
+ teamError,
+ teamMembers,
+ teamMemberError,
+ newMemberUserId,
+ newMemberRole,
+ availableUsers,
+ teamTags,
+ editingTeamTagId,
+ newTeamTag,
+ teamTagError,
+ syncResults,
+ users,
+ loadGroups,
+ openCreateTeamModal,
+ openEditTeamModal,
+ closeTeamModal,
+ saveTeam,
+ confirmDeleteTeam,
+ deleteTeam,
+ openManageTeamModal,
+ closeManageTeamModal,
+ loadTeamMembers,
+ addTeamMember,
+ updateMemberRole,
+ removeTeamMember,
+ syncTeamShares,
+ confirmSyncShares,
+ openManageTeamTagsModal,
+ closeManageTeamTagsModal,
+ loadTeamTags,
+ editTeamTag,
+ cancelEditTeamTag,
+ saveTeamTag,
+ deleteTeamTag
+ }
+ },
+ delimiters: ['${', '}'] // Use different delimiters to avoid conflict with Flask's Jinja2
+ }).mount('#app');
+
+ // Hide loading overlay after Vue app is mounted
+ if (window.AppLoader) {
+ window.AppLoader.hide();
+ }
+ }); // End of initializeI18n().then()
+ </script>
+</body>
+</html>
diff --git a/templates/includes/loading_overlay.html b/templates/includes/loading_overlay.html
index c9d20324..178cb62d 100644
--- a/templates/includes/loading_overlay.html
+++ b/templates/includes/loading_overlay.html
@@ -51,10 +51,19 @@
<script>
// Immediate loading overlay initialization
(function() {
- document.body.classList.add('app-loading');
- var overlay = document.createElement('div');
- overlay.className = 'app-loading-overlay';
- overlay.innerHTML = '<div class="app-loading-content"><div class="app-loading-spinner"></div><div class="app-loading-text">Loading Speakr...</div></div>';
- document.body.appendChild(overlay);
+ function initLoadingOverlay() {
+ if (!document.body) {
+ // Body not ready yet, wait a bit
+ setTimeout(initLoadingOverlay, 10);
+ return;
+ }
+ document.body.classList.add('app-loading');
+ var overlay = document.createElement('div');
+ overlay.className = 'app-loading-overlay';
+ overlay.innerHTML = '<div class="app-loading-content"><div class="app-loading-spinner"></div><div class="app-loading-text">Loading Speakr...</div></div>';
+ document.body.appendChild(overlay);
+ }
+ initLoadingOverlay();
})();
-</script>
\ No newline at end of file
+</script>
+<script src="{{ url_for('static', filename='js/loading.js') }}"></script>
\ No newline at end of file
diff --git a/templates/index.html b/templates/index.html
index 45b52248..9d84eb22 100644
--- a/templates/index.html
+++ b/templates/index.html
@@ -4,6 +4,7 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="csrf-token" content="{{ csrf_token() }}">
+ <meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
<title>Speakr - Audio Transcription & Summarization</title>
{% include 'includes/loading_overlay.html' %}
<!-- All dependencies bundled locally for offline support -->
@@ -44,2983 +45,97 @@
<div class="text-white text-lg">Loading...</div>
</div>
<div id="app" v-cloak
- data-use-asr-endpoint="{{ use_asr_endpoint }}"
+ data-use-asr-endpoint="{{ use_asr_endpoint }}"
+ data-enable-archive-toggle="{{ enable_archive_toggle }}"
+ data-enable-internal-sharing="{{ enable_internal_sharing }}"
data-current-user-name="{{ current_user.name if current_user.is_authenticated else '' }}"
data-user-language="{{ user_language }}"
class="h-full flex flex-col opacity-0 transition-opacity duration-500">
-
- <!-- Header -->
- <header class="bg-[var(--bg-secondary)] border-b border-[var(--border-primary)] px-3 sm:px-4 py-3 flex items-center justify-between flex-shrink-0 z-50">
- <!-- Left side: Menu toggle and logo -->
- <div class="flex items-center gap-2 sm:gap-4 min-w-0 flex-shrink">
- <!-- Menu Toggle Button -->
- <button @click="toggleSidebar"
- class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors duration-200 flex-shrink-0 flex items-center justify-center">
- <i class="fas fa-bars text-lg"></i>
- </button>
-
- <!-- Logo and Title -->
- <div class="flex items-center gap-2 sm:gap-3 min-w-0">
- <img src="{{ url_for('static', filename='img/icon-32x32.png') }}" alt="Speakr" class="w-7 h-7 sm:w-8 sm:h-8 flex-shrink-0">
- <h1 class="text-lg sm:text-xl font-bold text-[var(--text-primary)] truncate">Speakr</h1>
- </div>
- </div>
-
- <!-- 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-2 py-1.5 bg-[var(--bg-accent)] text-[var(--text-accent)] rounded-lg hover:opacity-80 transition-opacity text-sm sm:px-4 sm:py-2 sm:min-w-[120px] sm:flex sm:items-center sm:gap-2 sm:justify-center">
- <i class="fas fa-search"></i>
- <span class="hidden sm:inline" v-text="t('inquire.title')"></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 sm:px-4 sm:py-2 sm:min-w-[120px] sm:flex sm:items-center sm:gap-2 sm:justify-center">
- <i class="fas fa-plus mr-1"></i><span v-text="t('nav.newRecording')"></span>
- </button>
- <!-- User menu -->
- {% if current_user.is_authenticated %}
- <div class="relative">
- <button @click="isUserMenuOpen = !isUserMenuOpen"
- class="flex items-center gap-1 sm:gap-2 p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors duration-200"
- :title="t('admin.userMenu')">
- <i class="fas fa-user-circle text-lg"></i>
- <span class="hidden lg:inline text-sm">{{ current_user.name if current_user.is_authenticated else 'User' }}</span>
- <i class="fas fa-chevron-down text-xs hidden sm:inline"></i>
- </button>
-
- <!-- User dropdown -->
- <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><span v-text="t('nav.settings')"></span>
- </a>
- <a href="/account#tags" class="block px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors">
- <i class="fas fa-tags mr-2 w-4 text-center"></i><span v-text="t('help.tagManagement')"></span>
- </a>
- <button @click="openSharesList" class="w-full text-left px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors flex items-center">
- <i class="fas fa-share-alt mr-2 w-4 text-center"></i><span v-text="t('modal.sharedTranscripts')"></span>
- </button>
- {% if current_user.is_admin %}
- <a href="/admin" class="block px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors">
- <i class="fas fa-user-shield mr-2 w-4 text-center"></i><span v-text="t('admin.title')"></span>
- </a>
- {% endif %}
- <div class="border-t border-[var(--border-primary)] my-1"></div>
- <button @click="toggleDarkMode" class="w-full text-left px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors flex items-center">
- <i :class="isDarkMode ? 'fas fa-sun' : 'fas fa-moon'" class="mr-2 w-4 text-center"></i>
- <span v-text="isDarkMode ? t('nav.lightMode') : t('nav.darkMode')"></span>
- </button>
- <button @click="openColorSchemeModal" class="w-full text-left px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors flex items-center">
- <i class="fas fa-palette mr-2 w-4 text-center"></i>
- <span v-text="t('modal.colorScheme')"></span>
- </button>
- <div class="border-t border-[var(--border-primary)] my-1"></div>
- <a href="/logout" class="block px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors">
- <i class="fas fa-sign-out-alt mr-2 w-4 text-center"></i><span v-text="t('nav.signOut')"></span>
- </a>
- </div>
- </div>
- {% endif %}
- </div>
- </header>
+ <!-- Header -->
+ {% include 'components/header.html' %}
<div class="flex-1 flex overflow-hidden relative">
<!-- Mobile Sidebar Backdrop -->
- <div v-if="!isSidebarCollapsed && isMobileScreen"
+ <div v-if="!isSidebarCollapsed && isMobileScreen"
@click="toggleSidebar"
class="fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden">
</div>
-
- <!-- Sidebar -->
- <aside :class="['sidebar', isSidebarCollapsed ? 'collapsed' : '']">
- <div class="sidebar-content-wrapper">
- <!-- Sidebar Header -->
- <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" v-text="t('nav.recording')"></h2>
- <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><span v-text="t('common.new')"></span>
- </button>
- </div>
- </div>
-
- <!-- Search and Sort Controls -->
- <div class="space-y-3">
- <!-- Filter Toggle Button -->
- <div class="flex items-center space-x-2">
- <button @click="showAdvancedFilters = !showAdvancedFilters"
- class="flex-1 flex items-center justify-between px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg text-sm hover:bg-[var(--bg-tertiary)] transition-colors">
- <span class="flex items-center">
- <i class="fas fa-filter mr-2 text-[var(--text-muted)]"></i>
- <span v-if="!searchQuery && filterTags.length === 0 && !filterDatePreset && !filterDateRange.start && !filterDateRange.end && !filterTextQuery"
- v-text="t('sidebar.searchRecordings')">
- </span>
- <span v-else class="text-[var(--text-accent)]">
- Active filters (${ (filterTags.length > 0 ? 1 : 0) + (filterDatePreset || filterDateRange.start || filterDateRange.end ? 1 : 0) + (filterTextQuery ? 1 : 0) })
- </span>
- </span>
- <i :class="['fas fa-chevron-down transition-transform text-[var(--text-muted)]', showAdvancedFilters ? 'rotate-180' : '']"></i>
- </button>
- <button v-if="searchQuery || filterTags.length > 0 || filterDatePreset || filterDateRange.start || filterDateRange.end || filterTextQuery"
- @click="clearAllFilters"
- class="px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg text-sm hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-primary)] transition-colors"
- :title="t('buttons.clearAllFilters')">
- <i class="fas fa-times text-[var(--text-muted)]"></i>
- </button>
- </div>
-
- <!-- Advanced Filters Panel -->
- <div v-show="showAdvancedFilters" class="p-3 bg-[var(--bg-tertiary)] border border-[var(--border-secondary)] rounded-lg space-y-3">
- <!-- Text Search -->
- <div>
- <label class="block text-xs font-medium text-[var(--text-muted)] mb-1" v-text="t('sidebar.filters')"></label>
- <div class="relative">
- <input v-model="filterTextQuery"
- type="text"
- :placeholder="t('sidebar.searchRecordings')"
- class="w-full px-3 py-1.5 pl-8 pr-8 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-md text-sm focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">
- <i class="fas fa-search absolute left-2.5 top-1/2 transform -translate-y-1/2 text-[var(--text-muted)] text-xs"></i>
- <button v-if="filterTextQuery"
- @click="filterTextQuery = ''"
- class="absolute right-2.5 top-1/2 transform -translate-y-1/2 text-[var(--text-muted)] hover:text-[var(--text-primary)] text-xs"
- :title="t('buttons.clearSearchText')">
- <i class="fas fa-times"></i>
- </button>
- </div>
- </div>
-
- <!-- Tag Filter -->
- <div>
- <label class="block text-xs font-medium text-[var(--text-muted)] mb-1" v-text="t('tags.filterByTag')"></label>
- <div class="flex flex-wrap gap-1.5">
- <button v-for="tag in availableTags"
- :key="tag.id"
- @click="filterTags.includes(tag.id) ? filterTags = filterTags.filter(id => id !== tag.id) : filterTags.push(tag.id)"
- :class="[
- 'px-2 py-1 rounded-full text-xs font-medium transition-all',
- filterTags.includes(tag.id)
- ? 'bg-[var(--bg-accent)] text-[var(--text-accent)] ring-1 ring-[var(--border-accent)]'
- : 'bg-[var(--bg-secondary)] text-[var(--text-secondary)] hover:bg-[var(--bg-input)]'
- ]">
- <span class="inline-block w-2 h-2 rounded-full mr-1" :style="{ backgroundColor: tag.color || '#6B7280' }"></span>
- ${ tag.name }
- </button>
- </div>
- <p v-if="availableTags.length === 0" class="text-xs text-[var(--text-muted)] italic" v-text="t('tags.noTags')"></p>
- </div>
-
- <!-- Date Filter -->
- <div>
- <label class="block text-xs font-medium text-[var(--text-muted)] mb-1" v-text="t('sidebar.dateRange')"></label>
- <div class="grid grid-cols-3 gap-1.5 mb-2">
- <button v-for="preset in datePresetOptions"
- :key="preset.value"
- @click="filterDatePreset = filterDatePreset === preset.value ? '' : preset.value; filterDateRange = { start: '', end: '' }"
- :class="[
- 'px-2 py-1 rounded-md text-xs transition-all',
- filterDatePreset === preset.value
- ? 'bg-[var(--bg-accent)] text-[var(--text-accent)]'
- : 'bg-[var(--bg-secondary)] text-[var(--text-secondary)] hover:bg-[var(--bg-input)]'
- ]"
- :title="preset.label">
- ${ preset.label }
- </button>
- </div>
- <div class="grid grid-cols-2 gap-2">
- <div>
- <input v-model="filterDateRange.start"
- @change="filterDatePreset = ''"
- type="date"
- class="w-full px-2 py-1 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-md text-xs focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]"
- :placeholder="t('form.dateFrom')">
- </div>
- <div>
- <input v-model="filterDateRange.end"
- @change="filterDatePreset = ''"
- type="date"
- class="w-full px-2 py-1 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-md text-xs focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]"
- :placeholder="t('form.dateTo')">
- </div>
- </div>
- </div>
- </div>
-
- <!-- Sort Toggle -->
- <button @click="sortBy = sortBy === 'created_at' ? 'meeting_date' : 'created_at'"
- class="w-full flex items-center justify-between px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg text-sm hover:bg-[var(--bg-tertiary)] transition-colors">
- <span class="flex items-center">
- <i :class="['fas mr-2 text-[var(--text-muted)]', sortBy === 'meeting_date' ? 'fa-calendar' : 'fa-upload']"></i>
- <span v-text="t('sidebar.sortBy')"></span>: <span v-text="sortBy === 'meeting_date' ? t('sidebar.sortByMeetingDate') : t('sidebar.sortByDate')"></span>
- </span>
- <i class="fas fa-exchange-alt text-[var(--text-muted)]"></i>
- </button>
- </div>
- </div>
-
- <!-- Recordings List -->
- <div class="flex-1 overflow-y-auto p-4"
- @scroll="(e) => {
- const element = e.target;
- const threshold = 100; // Load more when 100px from bottom
- if (element.scrollHeight - element.scrollTop - element.clientHeight < threshold) {
- loadMoreRecordings();
- }
- }">
- <div v-if="isLoadingRecordings && recordings.length === 0" class="text-center py-8">
- <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
- <p class="mt-2 text-[var(--text-muted)]" v-text="t('help.loadingRecordings')"></p>
- </div>
-
- <div v-else-if="recordings.length === 0 && !isLoadingRecordings" class="text-center py-8">
- <i class="fas fa-microphone-slash text-3xl text-[var(--text-muted)] mb-3"></i>
- <p class="text-[var(--text-muted)]" v-text="t('sidebar.noRecordings')"></p>
- <p v-if="searchQuery.trim()" class="text-sm text-[var(--text-muted)] mt-1">
- <span v-text="t('help.tryAdjustingSearch')"></span> <button @click="clearAllFilters()" class="text-[var(--text-accent)] hover:underline" v-text="t('help.clearFilters')"></button>
- </p>
- </div>
-
- <div v-if="recordings.length > 0" class="space-y-2">
- <div v-for="group in groupedRecordings" :key="group.title" class="mb-6">
- <h3 class="text-xs font-semibold text-[var(--text-muted)] uppercase tracking-wide mb-2">
- ${group.title}
- </h3>
- <div class="space-y-1">
- <div v-for="recording in group.items"
- :key="recording.id"
- @click="selectRecording(recording)"
- :class="[
- 'p-3 rounded-lg cursor-pointer transition-all duration-200 border',
- selectedRecording?.id === recording.id
- ? 'bg-[var(--bg-accent)] border-[var(--border-accent)]'
- : 'bg-[var(--bg-tertiary)] border-transparent hover:bg-[var(--bg-accent-hover)]'
- ]">
- <!-- Title and Status Row -->
- <div class="flex items-center justify-between mb-1">
- <h4 class="font-medium text-sm truncate flex-1 mr-2" :class="selectedRecording?.id === recording.id ? 'text-[var(--text-accent)]' : 'text-[var(--text-primary)]'">
- ${ recording.title || t('common.untitled') }
- </h4>
- <div class="flex items-center gap-1 flex-shrink-0">
- <!-- Show Failed status for failed recordings -->
- <span v-if="recording.status === 'FAILED'"
- class="status-badge status-failed">
- <i class="fas fa-exclamation-circle mr-1"></i>
- ${ t('common.failed') }
- </span>
-
- <!-- Show Processing status for non-completed recordings -->
- <span v-else-if="recording.status !== 'COMPLETED'"
- :class="getStatusClass(recording.status)"
- class="status-badge">
- ${formatStatus(recording.status)}
- </span>
-
- <!-- For completed recordings, show highlight and inbox badges -->
- <template v-else>
- <span v-if="recording.is_highlighted"
- @click.stop="toggleHighlight(recording)"
- class="status-badge status-highlighted clickable-badge"
- :title="t('sidebar.removeFromHighlighted')">
- <i class="fas fa-star"></i>
- </span>
- <span v-if="recording.is_inbox"
- @click.stop="toggleInbox(recording)"
- class="status-badge status-inbox clickable-badge"
- :title="t('sidebar.markAsRead')">
- <i class="fas fa-inbox"></i>
- </span>
- </template>
- </div>
- </div>
- <!-- Date -->
- <p class="text-xs text-[var(--text-muted)] mt-1 flex items-center">
- <i class="fas fa-calendar-alt mr-1.5 text-[var(--text-muted)]" style="font-size: 10px;"></i>
- ${formatDisplayDate(sortBy === 'meeting_date' ? recording.meeting_date : recording.created_at)}
- </p>
-
- <!-- Participants -->
- <div v-if="recording.participants" class="text-xs text-[var(--text-muted)] mt-1 flex items-start">
- <i class="fas fa-users mr-1.5 text-[var(--text-muted)] flex-shrink-0" style="font-size: 10px; margin-top: 2px;"></i>
- <span class="truncate">
- ${recording.participants}
- </span>
- </div>
-
- <!-- Tags -->
- <div v-if="getRecordingTags(recording).length > 0" class="flex flex-wrap gap-1 mt-1">
- <button v-for="tag in getRecordingTags(recording).slice(0, 2)" :key="tag.id"
- @click.stop="filterByTag(tag)"
- class="inline-flex items-center px-1.5 py-0.5 rounded-md text-xs font-medium text-white hover:opacity-80 transition-opacity cursor-pointer"
- :style="{ backgroundColor: tag.color }"
- :title="'Filter by ' + tag.name">
- <span v-text="tag.name"></span>
- </button>
- <span v-if="getRecordingTags(recording).length > 2"
- class="inline-flex items-center px-1.5 py-0.5 rounded-md text-xs text-[var(--text-muted)]"
- :title="getRecordingTags(recording).slice(2).map(t => t.name).join(', ')">
- +${getRecordingTags(recording).length - 2} more
- </span>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Load More Indicator -->
- <div v-if="isLoadingMore" class="text-center py-4">
- <i class="fas fa-spinner fa-spin text-lg text-[var(--text-muted)]"></i>
- <p class="text-sm text-[var(--text-muted)] mt-1" v-text="t('help.loadingMore')"></p>
- </div>
-
- <!-- End of Results Indicator -->
- <div v-else-if="!hasNextPage && totalRecordings > 0" class="text-center py-4 text-xs text-[var(--text-muted)]">
- <i class="fas fa-check-circle mr-1"></i>
- <span v-text="t('help.allRecordingsLoaded')"></span>
- </div>
- </div>
- </div>
- </div>
- </aside>
-
- <!-- Main Content -->
- <main class="main-content"
- :class="{ 'sidebar-open': !isSidebarCollapsed }">
+ <!-- Sidebar -->
+ {% include 'components/sidebar.html' %}
- <div class="flex-1 flex flex-col overflow-hidden">
+ <!-- Main Content Area -->
+ <main :class="['flex-1 flex flex-col overflow-hidden main-content', !isSidebarCollapsed && !isMobileScreen ? 'sidebar-open' : '']">
<!-- Upload View -->
- <div v-if="currentView === 'upload'" class="flex-1 flex items-center justify-center p-4 md:p-8 overflow-y-auto">
- <div class="max-w-lg w-full my-auto">
- <div class="text-center mb-8">
- <i class="fas fa-microphone text-5xl md:text-6xl text-[var(--text-accent)] mb-4"></i>
- <h2 class="text-2xl md:text-3xl font-bold mb-2" v-text="t('upload.title')"></h2>
- <p class="text-[var(--text-muted)]" v-text="t('upload.dropzone')"></p>
- </div>
-
- <div class="bg-[var(--bg-secondary)] p-6 rounded-xl border border-[var(--border-primary)]">
- <!-- File Upload Area -->
- <div @drop="handleDrop" @dragover="handleDragOver" @dragleave="handleDragLeave" @click="$refs.fileInput.click()"
- :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" v-text="t('upload.dropzone')"></p>
- <p class="text-xs text-[var(--text-muted)]" v-text="t('upload.supportedFormats')"></p>
- </div>
- <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">
- <div class="flex-grow border-t border-[var(--border-secondary)]"></div>
- <span class="flex-shrink mx-4 text-xs text-[var(--text-muted)] uppercase" v-text="t('common.or')"></span>
- <div class="flex-grow border-t border-[var(--border-secondary)]"></div>
- </div>
-
- <!-- Audio Recording Options -->
- <div class="space-y-3">
- <h3 class="text-sm font-medium text-[var(--text-secondary)] text-center" v-text="t('recording.title')"></h3>
-
- <!-- Microphone Recording -->
- <button @click="startRecording('microphone')"
- class="w-full px-4 py-3 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors flex items-center justify-center gap-2">
- <i class="fas fa-microphone"></i>
- <span v-text="t('recording.microphone')"></span>
- </button>
-
- <!-- System Audio Recording -->
- <button @click="startRecording('system')"
- v-if="canRecordSystemAudio"
- class="w-full px-4 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center justify-center gap-2">
- <i class="fas fa-desktop"></i>
- <span v-text="t('recording.systemAudio')"></span>
- </button>
-
- <!-- Both Audio Sources -->
- <button @click="startRecording('both')"
- v-if="canRecordSystemAudio"
- class="w-full px-4 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors flex items-center justify-center gap-2">
- <i class="fas fa-microphone"></i>
- <i class="fas fa-desktop ml-1"></i>
- <span v-text="t('recording.microphoneAndSystem')"></span>
- </button>
-
- <!-- Help Text -->
- <div class="text-xs text-[var(--text-muted)] space-y-1 mt-3">
- <div class="flex items-center justify-between">
- <span><strong v-text="t('recording.microphone') + ':'"></strong> <span v-text="t('help.microphoneDesc')"></span></span>
- <i class="fas fa-microphone text-red-500 flex-shrink-0"></i>
- </div>
- <div v-if="canRecordSystemAudio" class="flex items-center justify-between">
- <span><strong v-text="t('recording.systemAudio') + ':'"></strong> <span v-text="t('help.systemAudioDesc')"></span></span>
- <i class="fas fa-desktop text-blue-500 flex-shrink-0"></i>
- </div>
- <div v-if="canRecordSystemAudio" class="flex items-center justify-between">
- <span><strong v-text="t('recording.microphoneAndSystem') + ':'"></strong> <span v-text="t('help.bothAudioDesc')"></span></span>
- <div class="flex items-center gap-1 flex-shrink-0">
- <i class="fas fa-microphone text-purple-500"></i>
- <i class="fas fa-desktop text-purple-500"></i>
- </div>
- </div>
- <div v-if="!canRecordSystemAudio" class="text-amber-600 dark:text-amber-400">
- <i class="fas fa-exclamation-triangle mr-1"></i>
- ${ t('recording.systemAudioNotSupported') }
- <button @click="showSystemAudioHelp = true" class="ml-2 text-blue-500 hover:text-blue-600 underline text-sm">
- <span v-text="t('buttons.help')"></span>
- </button>
- </div>
- </div>
- </div>
-
- <!-- Tag Selection -->
- <div class="mt-4">
- <label class="block text-sm font-medium text-[var(--text-secondary)] mb-2">
- <i class="fas fa-tags mr-1 text-[var(--text-muted)]"></i>
- ${ t('tags.title') }
- </label>
-
- <!-- Selected Tags Display - Compact -->
- <div v-if="selectedTags.length > 0" class="mb-2">
- <div class="p-1.5 bg-[var(--bg-tertiary)] rounded-md border border-[var(--border-secondary)] max-h-16 overflow-y-auto">
- <div class="flex flex-wrap gap-1">
- <span v-for="(tag, index) in selectedTags" :key="tag.id"
- class="inline-flex items-center px-1.5 py-0.5 rounded-full text-[11px] font-medium text-white"
- :style="{ backgroundColor: tag.color }">
- <span class="opacity-75 mr-0.5 text-[9px]">${index + 1}.</span>
- <span>${tag.name}</span>
- <button @click="removeTagFromSelection(tag.id)"
- class="ml-1 hover:opacity-100 opacity-70">
- <i class="fas fa-times" style="font-size: 9px;"></i>
- </button>
- </span>
- </div>
- </div>
- <p class="text-[10px] text-[var(--text-muted)] mt-0.5">
- <i class="fas fa-info-circle mr-0.5" style="font-size: 9px;"></i>
- Tags ordered by priority
- </p>
- </div>
-
- <!-- Tag Selection Container - Compact -->
- <div v-if="availableTags.filter(tag => !selectedTagIds.includes(tag.id)).length > 0"
- class="border border-[var(--border-secondary)] rounded-md bg-[var(--bg-tertiary)] p-2">
- <!-- Search Filter (always visible if tags available) -->
- <div class="mb-1.5">
- <div class="relative">
- <input v-model="uploadTagSearchFilter"
- type="text"
- :placeholder="t('tagsModal.searchTags')"
- class="w-full px-2 py-1 pl-6 text-xs bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">
- <i class="fas fa-search absolute left-2 top-1/2 transform -translate-y-1/2 text-[var(--text-muted)]" style="font-size: 9px;"></i>
- <button v-if="uploadTagSearchFilter"
- @click="uploadTagSearchFilter = ''"
- class="absolute right-2 top-1/2 transform -translate-y-1/2 text-[var(--text-muted)] hover:text-[var(--text-primary)]">
- <i class="fas fa-times" style="font-size: 9px;"></i>
- </button>
- </div>
- </div>
-
- <!-- Available Tags Grid - Fixed Height -->
- <div v-if="filteredAvailableTagsForUpload.length > 0"
- class="overflow-y-auto"
- style="max-height: 100px;">
- <div class="grid grid-cols-2 gap-1">
- <button v-for="tag in filteredAvailableTagsForUpload"
- :key="tag.id"
- @click="addTagToSelection(tag.id)"
- class="group flex items-center justify-between px-1.5 py-1 rounded border border-[var(--border-secondary)] hover:border-[var(--border-focus)] bg-[var(--bg-primary)] hover:bg-[var(--bg-secondary)] transition-all">
- <div class="flex items-center gap-1 min-w-0">
- <span class="w-2 h-2 rounded-full flex-shrink-0"
- :style="{ backgroundColor: tag.color || '#6B7280' }"></span>
- <span class="text-[11px] text-[var(--text-primary)] truncate" v-text="tag.name"></span>
- </div>
- <i class="fas fa-plus text-[var(--text-muted)] group-hover:text-[var(--text-accent)] transition-colors" style="font-size: 9px;"></i>
- </button>
- </div>
- </div>
- <div v-else class="py-2 text-center">
- <p class="text-[11px] text-[var(--text-muted)]">
- <i class="fas fa-search mr-1" style="font-size: 9px;"></i>
- No matching tags
- </p>
- </div>
- </div>
- <!-- Empty States -->
- <div v-else-if="availableTags.length === 0"
- class="p-2 bg-[var(--bg-tertiary)] rounded-md border border-[var(--border-secondary)]">
- <p class="text-xs text-[var(--text-muted)] text-center">
- <i class="fas fa-info-circle mr-1" style="font-size: 10px;"></i>
- <span v-text="t('help.noTagsCreated')"></span> <a href="/account#tags" class="text-[var(--text-accent)] hover:underline" v-text="t('help.createTags')"></a>
- </p>
- </div>
- <div v-else class="p-2 bg-[var(--bg-tertiary)] rounded-md border border-[var(--border-secondary)]">
- <p class="text-xs text-[var(--text-muted)] text-center">
- <i class="fas fa-check-circle mr-1" style="font-size: 10px;"></i>
- All tags selected
- </p>
- </div>
-
- <p v-if="selectedTags.some(tag => tag.custom_prompt)" class="text-xs text-[var(--text-muted)] mt-1">
- <i class="fas fa-info-circle mr-1 text-[var(--text-accent)]"></i>
- Selected tags include custom summary prompts
- </p>
- <p v-if="selectedTags.length > 0 && useAsrEndpoint && selectedTags.some(tag => tag.default_language || tag.default_min_speakers || tag.default_max_speakers)"
- class="text-xs text-[var(--text-muted)] mt-1">
- <i class="fas fa-cog mr-1 text-[var(--text-accent)]"></i>
- First tag's ASR settings will be applied: ${selectedTags[0].name}
- </p>
- </div>
-
- <!-- Advanced Options for ASR (collapsible) -->
- <div v-if="useAsrEndpoint" class="mt-4">
- <button @click="showAdvancedOptions = !showAdvancedOptions"
- class="w-full flex items-center justify-between px-3 py-2 bg-[var(--bg-tertiary)] rounded-md hover:bg-[var(--bg-accent)] transition-colors text-xs font-medium">
- <span class="flex items-center gap-2 text-[var(--text-secondary)]">
- <i class="fas fa-cog text-[var(--text-muted)]"></i>
- <span v-text="t('help.advancedAsrOptions')"></span>
- </span>
- <i :class="['fas text-[var(--text-muted)]', showAdvancedOptions ? 'fa-chevron-up' : 'fa-chevron-down']"></i>
- </button>
-
- <div v-show="showAdvancedOptions" class="mt-2 p-3 bg-[var(--bg-tertiary)] rounded-md space-y-3 border border-[var(--border-secondary)]">
- <!-- Language Selection -->
- <div>
- <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">
- Transcription Language
- </label>
- <select v-model="uploadLanguage"
- class="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">
- <option v-for="lang in languageOptions" :key="lang.value" :value="lang.value" v-text="lang.label"></option>
- </select>
- </div>
-
- <!-- Speaker Settings -->
- <div class="grid grid-cols-2 gap-3">
- <div>
- <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1" v-text="t('form.minSpeakers')">
- </label>
- <input v-model.number="uploadMinSpeakers"
- type="number"
- min="1"
- max="20"
- class="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">
- </div>
- <div>
- <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1" v-text="t('form.maxSpeakers')">
- </label>
- <input v-model.number="uploadMaxSpeakers"
- type="number"
- min="1"
- max="20"
- class="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">
- </div>
- </div>
-
- <p class="text-xs text-[var(--text-muted)] pt-1">
- <i class="fas fa-info-circle mr-1 text-[var(--text-accent)]"></i>
- Settings apply to all files in this session
- </p>
- </div>
- </div>
- </div>
- </div>
- </div>
+ {% include 'components/upload-view.html' %}
<!-- Recording View -->
- <div v-else-if="currentView === 'recording'" class="flex-1 flex flex-col p-2 md:p-8 bg-[var(--bg-primary)] min-h-0">
- <div class="flex-1 flex flex-col max-w-4xl w-full mx-auto bg-[var(--bg-secondary)] rounded-xl border border-[var(--border-primary)] min-h-0 overflow-hidden">
- <!-- Top: Visualizer and Status (Fixed) -->
- <div class="flex-shrink-0 p-3 md:p-6 text-center bg-[var(--bg-tertiary)] border-b border-[var(--border-primary)]">
- <div v-if="isRecording" class="w-full mx-auto mb-3 md:mb-4">
- <!-- Dual visualizer for 'both' mode -->
- <div v-if="recordingMode === 'both'" class="max-w-4xl mx-auto flex gap-2 md:gap-4">
- <div class="w-1/2 min-h-[8rem] md:min-h-[12rem] h-32 md:h-48 flex flex-col bg-[var(--bg-primary)] rounded-lg p-1.5 md:p-2">
- <div class="flex-1 w-full overflow-hidden rounded-md" style="min-height: 6rem;">
- <canvas ref="micVisualizer" class="w-full h-full"></canvas>
- </div>
- <p class="text-xs text-[var(--text-muted)] pt-0.5 md:pt-1" v-text="t('recording.microphone')"></p>
- </div>
- <div class="w-1/2 min-h-[8rem] md:min-h-[12rem] h-32 md:h-48 flex flex-col bg-[var(--bg-primary)] rounded-lg p-1.5 md:p-2">
- <div class="flex-1 w-full overflow-hidden rounded-md" style="min-height: 6rem;">
- <canvas ref="systemVisualizer" class="w-full h-full"></canvas>
- </div>
- <p class="text-xs text-[var(--text-muted)] pt-0.5 md:pt-1" v-text="t('recording.systemAudio')"></p>
- </div>
- </div>
- <!-- Single visualizer for other modes -->
- <div v-else class="min-h-[8rem] md:min-h-[12rem] h-32 md:h-48 max-w-2xl mx-auto bg-[var(--bg-primary)] rounded-lg p-1.5 md:p-2 flex flex-col">
- <div class="flex-1 w-full overflow-hidden rounded-md" style="min-height: 6rem;">
- <canvas ref="visualizer" class="w-full h-full"></canvas>
- </div>
- <p class="text-xs text-[var(--text-muted)] pt-0.5 md:pt-1 capitalize">${recordingMode}</p>
- </div>
- </div>
- <div v-if="!isRecording && audioBlobURL" class="w-full mb-3 md:mb-4">
- <div class="audio-player-container">
- <audio :src="audioBlobURL" controls class="w-full">
- Your browser does not support the audio element.
- </audio>
- </div>
- </div>
-
- <div>
- <div class="text-xl md:text-2xl font-mono text-[var(--text-accent)]">${formatTime(recordingTime)}</div>
- <p class="text-xs md:text-sm text-[var(--text-muted)]">${ isRecording ? 'Recording in progress...' : 'Recording finished' }</p>
- <!-- Real-time file size display -->
- <div v-if="isRecording && estimatedFileSize > 0" class="mt-1.5">
- <p class="text-xs text-[var(--text-muted)]">
- Estimated size: <span class="font-mono">${formatFileSize(estimatedFileSize)}</span>
- <span v-if="actualBitrate > 0" class="ml-2">
- (${Math.round(actualBitrate / 1000)}kbps)
- </span>
- </p>
- <!-- Size warning indicator -->
- <div v-if="estimatedFileSize > (maxRecordingMB * 1024 * 1024 * 0.8)" class="mt-0.5">
- <div class="flex items-center text-xs text-amber-600 dark:text-amber-400">
- <i class="fas fa-exclamation-triangle mr-1"></i>
- <span v-text="t('help.approachingLimit', { limit: maxRecordingMB })"></span>
- </div>
- </div>
- </div>
-
- <!-- Mobile Background Recording Warning - Below timer -->
- <div v-if="isRecording && isMobileDevice"
- class="mt-2 p-2 bg-amber-50 dark:bg-amber-900 dark:bg-opacity-20 border border-amber-300 dark:border-amber-700 rounded">
- <div class="flex items-start gap-1.5 text-left">
- <i class="fas fa-exclamation-triangle text-amber-600 dark:text-amber-400 flex-shrink-0 text-xs" style="margin-top: 2px;"></i>
- <div class="flex-1 min-w-0">
- <div class="text-xs text-amber-800 dark:text-amber-200 leading-snug">
- <strong class="font-semibold">Keep this app visible!</strong>
- <span class="block text-[10px] mt-0.5">Recording pauses if minimized or screen locked.</span>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Scrollable Content Area: Notes + Actions -->
- <div class="flex-1 min-h-0 overflow-y-auto flex flex-col">
- <!-- Middle: Notepad (flexible height) -->
- <div class="flex-1 p-3 md:p-6 flex flex-col" style="min-height: 200px;">
- <label for="recordingNotes" class="block text-sm font-medium text-[var(--text-secondary)] mb-1.5 flex-shrink-0">
- <i class="fas fa-pencil-alt mr-1"></i>
- Recording Notes (Markdown)
- </label>
- <div class="flex-1 recording-notes-editor" style="min-height: 150px;">
- <textarea ref="recordingNotesEditor" v-model="recordingNotes"
- class="w-full h-full bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg p-2 md:p-3 text-sm focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)] resize-none"
- :placeholder="t('form.notesPlaceholder')"></textarea>
- </div>
- </div>
-
- <!-- Bottom: Action Buttons -->
- <div class="flex-shrink-0 p-3 md:p-6 bg-[var(--bg-tertiary)] border-t border-[var(--border-primary)]">
- <div v-if="isRecording" class="text-center">
- <button @click="stopRecording"
- class="px-6 md:px-8 py-2.5 md:py-3 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors animate-pulse text-sm md:text-base">
- <i class="fas fa-stop mr-2"></i>Stop Recording
- </button>
- </div>
- <div v-if="!isRecording && audioBlobURL" class="flex flex-col gap-3 md:gap-4">
- <!-- Tag Selection -->
- <div>
- <label for="recordingTagSelect" class="block text-sm font-medium text-[var(--text-secondary)] mb-1.5 md:mb-2">
- <i class="fas fa-tags mr-1"></i>
- Select Tags (optional, in priority order)
- </label>
-
- <!-- Selected Tags Display - Compact -->
- <div v-if="selectedTags.length > 0" class="mb-2">
- <div class="p-1.5 bg-[var(--bg-tertiary)] rounded-md border border-[var(--border-secondary)] max-h-16 overflow-y-auto">
- <div class="flex flex-wrap gap-1">
- <span v-for="(tag, index) in selectedTags" :key="tag.id"
- class="inline-flex items-center px-1.5 py-0.5 rounded-full text-[11px] font-medium text-white"
- :style="{ backgroundColor: tag.color }">
- <span class="opacity-75 mr-0.5 text-[9px]">${index + 1}.</span>
- <span>${tag.name}</span>
- <button @click="removeTagFromSelection(tag.id)"
- class="ml-1 hover:opacity-100 opacity-70">
- <i class="fas fa-times" style="font-size: 9px;"></i>
- </button>
- </span>
- </div>
- </div>
- </div>
-
- <!-- Tag Selection Container - Compact -->
- <div v-if="availableTags.filter(tag => !selectedTagIds.includes(tag.id)).length > 0"
- class="border border-[var(--border-secondary)] rounded-md bg-[var(--bg-tertiary)] p-2">
- <!-- Search Filter -->
- <div class="mb-1.5">
- <div class="relative">
- <input v-model="uploadTagSearchFilter"
- type="text"
- :placeholder="t('tagsModal.searchTags')"
- class="w-full px-2 py-1 pl-6 text-xs bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">
- <i class="fas fa-search absolute left-2 top-1/2 transform -translate-y-1/2 text-[var(--text-muted)]" style="font-size: 9px;"></i>
- <button v-if="uploadTagSearchFilter"
- @click="uploadTagSearchFilter = ''"
- class="absolute right-2 top-1/2 transform -translate-y-1/2 text-[var(--text-muted)] hover:text-[var(--text-primary)]">
- <i class="fas fa-times" style="font-size: 9px;"></i>
- </button>
- </div>
- </div>
- <!-- Available Tags Grid -->
- <div v-if="filteredAvailableTagsForUpload.length > 0"
- class="overflow-y-auto"
- style="max-height: 100px;">
- <div class="grid grid-cols-2 gap-1">
- <button v-for="tag in filteredAvailableTagsForUpload"
- :key="tag.id"
- @click="addTagToSelection(tag.id)"
- class="group flex items-center justify-between px-1.5 py-1 rounded border border-[var(--border-secondary)] hover:border-[var(--border-focus)] bg-[var(--bg-primary)] hover:bg-[var(--bg-secondary)] transition-all">
- <div class="flex items-center gap-1 min-w-0">
- <span class="w-2 h-2 rounded-full flex-shrink-0"
- :style="{ backgroundColor: tag.color || '#6B7280' }"></span>
- <span class="text-[11px] text-[var(--text-primary)] truncate" v-text="tag.name"></span>
- </div>
- <i class="fas fa-plus text-[var(--text-muted)] group-hover:text-[var(--text-accent)] transition-colors" style="font-size: 9px;"></i>
- </button>
- </div>
- </div>
- <div v-else class="py-2 text-center">
- <p class="text-[11px] text-[var(--text-muted)]">
- <i class="fas fa-search mr-1" style="font-size: 9px;"></i>
- No matching tags
- </p>
- </div>
- </div>
- <!-- Empty States -->
- <div v-else-if="availableTags.length === 0"
- class="p-2 bg-[var(--bg-tertiary)] rounded-md border border-[var(--border-secondary)]">
- <p class="text-xs text-[var(--text-muted)] text-center">
- <i class="fas fa-info-circle mr-1" style="font-size: 10px;"></i>
- <span v-text="t('help.noTagsCreated')"></span> <a href="/account#tags" class="text-[var(--text-accent)] hover:underline" v-text="t('help.createTags')"></a>
- </p>
- </div>
- <div v-else class="p-2 bg-[var(--bg-tertiary)] rounded-md border border-[var(--border-secondary)]">
- <p class="text-xs text-[var(--text-muted)] text-center">
- <i class="fas fa-check-circle mr-1" style="font-size: 10px;"></i>
- All tags selected
- </p>
- </div>
-
- <p v-if="selectedTags.some(tag => tag.custom_prompt)" class="text-xs text-[var(--text-muted)] mt-1">
- <i class="fas fa-info-circle mr-1 text-[var(--text-accent)]"></i>
- Selected tags include custom summary prompts
- </p>
- <p v-if="selectedTags.length > 0 && useAsrEndpoint && selectedTags.some(tag => tag.default_language || tag.default_min_speakers || tag.default_max_speakers)"
- class="text-xs text-[var(--text-muted)] mt-1">
- <i class="fas fa-cog mr-1 text-[var(--text-accent)]"></i>
- First tag's ASR settings will be applied: ${selectedTags[0].name}
- </p>
- </div>
-
- <!-- Advanced Options for ASR (collapsible) -->
- <div v-if="useAsrEndpoint">
- <button @click="showAdvancedOptions = !showAdvancedOptions"
- class="w-full flex items-center justify-between px-3 py-2 bg-[var(--bg-tertiary)] rounded-md hover:bg-[var(--bg-accent)] transition-colors text-xs font-medium">
- <span class="flex items-center gap-2 text-[var(--text-secondary)]">
- <i class="fas fa-cog text-[var(--text-muted)]"></i>
- <span v-text="t('help.advancedAsrOptions')"></span>
- </span>
- <i :class="['fas text-[var(--text-muted)]', showAdvancedOptions ? 'fa-chevron-up' : 'fa-chevron-down']"></i>
- </button>
-
- <div v-if="showAdvancedOptions" class="mt-2 p-3 bg-[var(--bg-tertiary)] rounded-md border border-[var(--border-secondary)] space-y-3">
- <div>
- <label for="recordingAsrLanguage" class="block text-xs font-medium text-[var(--text-secondary)] mb-1">
- Language
- </label>
- <select id="recordingAsrLanguage" v-model="asrLanguage"
- class="w-full px-2 py-1 bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)] text-xs">
- <option v-for="lang in languageOptions" :key="lang.value" :value="lang.value" v-text="lang.label"></option>
- </select>
- </div>
-
- <div class="grid grid-cols-2 gap-3">
- <div>
- <label for="recordingAsrMinSpeakers" class="block text-xs font-medium text-[var(--text-secondary)] mb-1" v-text="t('form.minSpeakers')">
- </label>
- <input type="number" id="recordingAsrMinSpeakers" v-model="asrMinSpeakers"
- min="1" max="20" :placeholder="t('form.auto')"
- class="w-full px-2 py-1 bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)] text-xs">
- </div>
-
- <div>
- <label for="recordingAsrMaxSpeakers" class="block text-xs font-medium text-[var(--text-secondary)] mb-1" v-text="t('form.maxSpeakers')">
- </label>
- <input type="number" id="recordingAsrMaxSpeakers" v-model="asrMaxSpeakers"
- min="1" max="20" :placeholder="t('form.auto')"
- class="w-full px-2 py-1 bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)] text-xs">
- </div>
- </div>
- </div>
- </div>
-
- <!-- Upload/Discard Buttons -->
- <div class="flex flex-col sm:flex-row gap-3 justify-center">
- <button @click="uploadRecordedAudio"
- class="flex-1 px-6 py-3 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors flex items-center justify-center gap-2">
- <i class="fas fa-upload"></i>
- <span v-text="t('help.uploadRecordingNotes')"></span>
- </button>
- <button @click="discardRecording"
- class="px-6 py-3 bg-[var(--bg-danger)] text-white rounded-lg hover:bg-[var(--bg-danger-hover)] transition-colors flex items-center justify-center gap-2">
- <i class="fas fa-trash"></i>
- <span v-text="t('help.discard')"></span>
- </button>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Recording Detail View -->
- <div v-else-if="currentView === 'detail' && selectedRecording" class="flex-1 flex flex-col overflow-hidden">
- <!-- Mobile View -->
- <div v-if="isMobileScreen" class="flex-1 flex flex-col overflow-hidden">
- <!-- Mobile Header -->
- <div class="bg-[var(--bg-secondary)] border-b border-[var(--border-primary)] p-4 flex-shrink-0">
- <div @click="isMetadataExpanded = !isMetadataExpanded" class="cursor-pointer">
- <div class="flex items-start justify-between">
- <div class="flex-1 min-w-0">
- <h1 class="text-lg font-bold text-[var(--text-primary)] truncate">
- ${selectedRecording.title || 'Untitled Recording'}
- </h1>
- <p class="text-sm text-[var(--text-muted)] truncate">
- ${selectedRecording.participants || t('help.noParticipants')}
- </p>
- <div v-if="getRecordingTags(selectedRecording).length > 0" class="flex flex-wrap gap-1 mt-2">
- <button v-for="tag in getRecordingTags(selectedRecording)" :key="tag.id"
- @click="filterByTag(tag)"
- class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium text-white hover:opacity-80 transition-opacity cursor-pointer"
- :style="{ backgroundColor: tag.color }"
- :title="'Filter by ' + tag.name">
- <i class="fas fa-tag mr-1"></i>
- <span v-text="tag.name"></span>
- </button>
- </div>
- </div>
- <i :class="['fas', 'fa-chevron-down', 'transition-transform', { 'rotate-180': isMetadataExpanded }]"></i>
- </div>
- </div>
- <!-- Expandable Metadata and Actions -->
- <div v-if="isMetadataExpanded" class="mt-4 space-y-4">
- <div class="space-y-2 text-sm text-[var(--text-muted)]">
- <div class="flex items-center gap-2">
- <i class="fas fa-calendar text-[var(--text-accent)]"></i>
- <span>${selectedRecording.meeting_date ? formatDisplayDate(selectedRecording.meeting_date) : 'No date set'}</span>
- </div>
- <div v-if="activeRecordingMetadata" class="flex flex-wrap items-center gap-x-4 gap-y-2">
- <template v-for="(item, index) in activeRecordingMetadata" :key="index">
- <!-- Special rendering for tags -->
- <div v-if="item.isTagItem" class="flex items-center gap-1.5">
- <i :class="item.icon" class="text-[var(--text-muted)]"></i>
- <div class="flex flex-wrap items-center gap-1">
- <span v-for="tag in item.tags" :key="tag.id"
- class="inline-flex items-center px-2 py-0.5 text-xs font-medium rounded-full text-white"
- :style="{ backgroundColor: tag.color || '#6B7280' }">
- ${tag.name}
- </span>
- </div>
- </div>
- <!-- Regular metadata items -->
- <span v-else class="flex items-center gap-1.5">
- <i :class="item.icon"></i>
- <span :title="item.fullText || item.text">${item.text}</span>
- </span>
- </template>
- </div>
- <div v-if="selectedRecording.status !== 'COMPLETED'" class="flex items-center gap-2">
- <span :class="getStatusClass(selectedRecording.status)" class="status-badge">
- ${formatStatus(selectedRecording.status)}
- </span>
- </div>
- </div>
- <!-- Action Buttons -->
- <div class="flex items-center gap-2 overflow-x-auto pb-2">
- <button @click="toggleInbox(selectedRecording)" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors" :class="selectedRecording.is_inbox ? 'text-blue-500' : ''" :title="selectedRecording.is_inbox ? t('sidebar.markAsRead') : t('sidebar.moveToInbox')"><i class="fas fa-inbox"></i></button>
- <button @click="toggleHighlight(selectedRecording)" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors" :class="selectedRecording.is_highlighted ? 'text-yellow-500' : ''" :title="selectedRecording.is_highlighted ? t('sidebar.removeFromHighlighted') : t('sidebar.highlighted')"><i class="fas fa-star"></i></button>
- <button @click="editRecording(selectedRecording)" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors" :title="t('common.edit')"><i class="fas fa-edit"></i></button>
- <button @click="editRecordingTags(selectedRecording)" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors" :title="t('tags.title')"><i class="fas fa-tags"></i></button>
- <button @click="reprocessTranscription(selectedRecording.id)" v-if="selectedRecording && (selectedRecording.status === 'COMPLETED' || selectedRecording.status === 'FAILED')" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors" :title="useAsrEndpoint ? 'Reprocess with ASR' : 'Reprocess transcription'"><i class="fas fa-redo-alt"></i></button>
- <button @click="reprocessSummary(selectedRecording.id)" v-if="selectedRecording && (selectedRecording.status === 'COMPLETED' || selectedRecording.status === 'FAILED')" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors" :title="t('buttons.reprocessSummary')"><i class="fas fa-sync-alt"></i></button>
- <button @click="confirmReset(selectedRecording)" v-if="['PROCESSING', 'SUMMARIZING', 'FAILED'].includes(selectedRecording.status)" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors text-orange-500" :title="t('buttons.resetStuckProcessing')"><i class="fas fa-undo"></i></button>
- <button @click="openSpeakerModal" v-if="selectedRecording.transcription && useAsrEndpoint" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors" :title="t('buttons.identifySpeakers')"><i class="fas fa-user-tag"></i></button>
- <button @click="openShareModal(selectedRecording)" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors" :title="t('buttons.shareRecording')"><i class="fas fa-share-alt"></i></button>
- <button @click="confirmDelete(selectedRecording)" class="p-2 rounded-lg hover:bg-[var(--bg-danger-light)] text-[var(--text-danger)] transition-colors"><i class="fas fa-trash"></i></button>
- </div>
- </div>
- </div>
-
- <!-- Mobile Audio Player -->
- <div class="bg-[var(--bg-secondary)] p-4 border-b border-[var(--border-primary)] flex-shrink-0">
- <div class="audio-player-container">
- <audio controls
- :src="'/audio/' + selectedRecording.id"
- :volume="playerVolume"
- @volumechange="onPlayerVolumeChange"
- class="w-full">
- Your browser does not support the audio element.
- </audio>
- </div>
- </div>
-
- <!-- Mobile Tab Navigation -->
- <div class="flex-shrink-0 bg-[var(--bg-tertiary)] border-b border-[var(--border-primary)] flex overflow-x-auto">
- <button @click="mobileTab = 'transcript'" :class="['flex-1 px-4 py-3 text-sm font-medium transition-colors', mobileTab === 'transcript' ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]' : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]']" v-text="t('transcription.title')"></button>
- <button @click="mobileTab = 'summary'" :class="['flex-1 px-4 py-3 text-sm font-medium transition-colors', mobileTab === 'summary' ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]' : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]']" v-text="t('summary.title')"></button>
- <button @click="mobileTab = 'notes'" :class="['flex-1 px-4 py-3 text-sm font-medium transition-colors', mobileTab === 'notes' ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]' : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]']" v-text="t('notes.title')"></button>
- <button @click="mobileTab = 'chat'" :class="['flex-1 px-4 py-3 text-sm font-medium transition-colors', mobileTab === 'chat' ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]' : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]']" v-text="t('chat.title')"></button>
- <button v-if="selectedRecording.events && selectedRecording.events.length > 0"
- @click="mobileTab = 'events'"
- :class="['flex-1 px-4 py-3 text-sm font-medium transition-colors whitespace-nowrap', mobileTab === 'events' ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]' : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]']">
- <i class="fas fa-calendar-alt mr-1"></i>${ t('events.title') } (${ selectedRecording.events.length })
- </button>
- </div>
-
- <!-- Mobile Tab Content -->
- <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 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>
- </div>
- <button @click="copyTranscription" class="copy-btn" title="Copy transcript"><i class="fas fa-copy"></i></button>
- <button @click="downloadTranscript" v-if="selectedRecording && selectedRecording.transcription" class="copy-btn" title="Download transcript with template"><i class="fas fa-download"></i></button>
- <button @click="openTranscriptionEditor" v-if="selectedRecording && selectedRecording.transcription" class="copy-btn" title="Edit transcript"><i class="fas fa-edit"></i></button>
- </div>
- <div class="flex-grow overflow-y-auto mobile-content-box">
- <div v-if="selectedRecording.status === 'PROCESSING'" class="text-center py-8">
- <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
- <p class="mt-2 text-[var(--text-muted)]" v-text="t('help.processingTranscription')"></p>
- </div>
- <div v-else-if="!selectedRecording.transcription" class="text-center py-8">
- <i class="fas fa-file-text text-3xl text-[var(--text-muted)] mb-3"></i>
- <p class="text-[var(--text-muted)]" v-text="t('transcription.noTranscription')"></p>
- </div>
- <div v-else>
- <div v-if="!processedTranscription.hasDialogue || transcriptionViewMode === 'simple'" class="transcription-simple-view">
- <div v-if="processedTranscription.hasDialogue">
- <div v-for="segment in processedTranscription.simpleSegments" :key="segment.startTime || Math.random()" class="speaker-segment" @click="seekAudioFromEvent" :data-start-time="segment.startTime">
- <div v-if="segment.showSpeaker" :class="['speaker-tablet', segment.color]">${segment.speaker}</div>
- <div class="speaker-text">${segment.sentence}</div>
- </div>
- </div>
- <div v-else>
- <div v-if="processedTranscription.simpleSegments && processedTranscription.simpleSegments.length > 0">
- <div v-for="segment in processedTranscription.simpleSegments" :key="segment.startTime || Math.random()" class="transcript-segment cursor-pointer hover:bg-[var(--bg-accent-hover)] p-2 rounded transition-colors" @click="seekAudioFromEvent" :data-start-time="segment.startTime">${segment.sentence}</div>
- </div>
- <div v-else class="whitespace-pre-wrap">${processedTranscription.content}</div>
- </div>
- </div>
- <div v-else-if="transcriptionViewMode === 'bubble'" class="transcription-with-speakers">
- <div v-for="(row, rowIndex) in processedTranscription.bubbleRows" :key="`${selectedRecording.id}-bubble-row-${rowIndex}`" :class="['bubble-row', row.isMe ? 'speaker-me' : '']">
- <div v-for="bubble in row.bubbles" :key="bubble.startTime || Math.random()" :class="['speaker-bubble', bubble.color, row.isMe ? 'speaker-me' : '']" @click="seekAudioFromEvent" :data-start-time="bubble.startTime">
- <div class="speaker-bubble-content">${bubble.sentence}</div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </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 pr-3">
- <button @click="copySummary" class="copy-btn" :title="t('buttons.copySummary')"><i class="fas fa-copy"></i></button>
- <button @click="downloadSummary" class="copy-btn" :title="t('buttons.downloadAsWord')"><i class="fas fa-download"></i></button>
- <button @click="toggleEditSummary" class="copy-btn" :title="t('buttons.editSummary')"><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">
- <div class="markdown-editor-container flex-1">
- <textarea ref="summaryMarkdownEditor" v-model="selectedRecording.summary"></textarea>
- </div>
- <div class="flex justify-end gap-2 mt-2">
- <button @click="cancelEditSummary" class="px-3 py-1 text-sm bg-[var(--bg-secondary)] text-[var(--text-secondary)] border border-[var(--border-secondary)] rounded hover:bg-[var(--bg-tertiary)]" v-text="t('common.cancel')"></button>
- <button @click="saveEditSummary" class="px-3 py-1 text-sm bg-[var(--bg-button)] text-[var(--text-button)] rounded hover:bg-[var(--bg-button-hover)]" v-text="t('common.save')"></button>
- </div>
- </div>
- <div v-else>
- <div v-if="selectedRecording.status === 'SUMMARIZING'" class="text-center py-8">
- <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
- <p class="mt-2 text-[var(--text-muted)]" v-text="t('help.generatingSummary')"></p>
- </div>
- <div v-else-if="!selectedRecording.summary" class="text-center py-8">
- <i class="fas fa-file-alt text-3xl text-[var(--text-muted)] mb-3"></i>
- <p class="text-[var(--text-muted)] mb-4" v-text="t('summary.noSummary')"></p>
- <button @click="generateSummary"
- class="px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 text-white font-medium rounded-lg shadow-lg hover:shadow-xl hover:from-blue-700 hover:to-purple-700 transition-all duration-200 transform hover:scale-105">
- <i class="fas fa-magic mr-2"></i>Generate Summary
- </button>
- </div>
- <div v-else class="summary-box h-full" v-html="selectedRecording.summary_html || selectedRecording.summary"></div>
- </div>
- </div>
- </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 pr-3">
- <button @click="copyNotes" class="copy-btn" :title="t('buttons.copyNotes')"><i class="fas fa-copy"></i></button>
- <button @click="downloadNotes" class="copy-btn" :title="t('buttons.downloadAsWord')"><i class="fas fa-download"></i></button>
- <button @click="toggleEditNotes" class="copy-btn" :title="t('buttons.editNotes')"><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">
- <div class="markdown-editor-container flex-1">
- <textarea ref="notesMarkdownEditor" v-model="selectedRecording.notes"></textarea>
- </div>
- <div class="flex justify-end gap-2 mt-2">
- <button @click="cancelEditNotes" class="px-3 py-1 text-sm bg-[var(--bg-secondary)] text-[var(--text-secondary)] border border-[var(--border-secondary)] rounded hover:bg-[var(--bg-tertiary)]" v-text="t('common.cancel')"></button>
- <button @click="saveEditNotes" class="px-3 py-1 text-sm bg-[var(--bg-button)] text-[var(--text-button)] rounded hover:bg-[var(--bg-button-hover)]" v-text="t('common.save')"></button>
- </div>
- </div>
- <div v-else @click="clickToEditNotes">
- <div v-if="!selectedRecording.notes" class="text-center py-8 cursor-pointer hover:text-[var(--text-secondary)]">
- <i class="fas fa-sticky-note text-3xl text-[var(--text-muted)] mb-3"></i>
- <p class="text-[var(--text-muted)]" v-text="t('help.clickToAddNotes')"></p>
- </div>
- <div v-else class="notes-box h-full" v-html="selectedRecording.notes_html || selectedRecording.notes"></div>
- </div>
- </div>
- </div>
- <!-- Chat Panel -->
- <div v-if="mobileTab === 'chat'" class="h-full flex flex-col rounded-lg border border-[var(--border-primary)] overflow-hidden relative">
- <!-- Clear button - fixed at top right -->
- <button v-if="chatMessages.length > 0"
- @click="clearChat"
- class="absolute top-2 right-2 p-1 text-[var(--text-muted)] opacity-60 hover:opacity-100 hover:text-[var(--text-danger)] rounded transition-all duration-200 z-20"
- title="Clear chat">
- <i class="fas fa-times text-xs"></i>
- </button>
-
- <div ref="chatMessagesRef" class="flex-1 overflow-y-auto p-4 space-y-4 bg-[var(--bg-secondary)]">
- <div v-if="chatMessages.length === 0" class="text-center py-8">
- <i class="fas fa-robot text-3xl text-[var(--text-muted)] mb-3"></i>
- <p class="text-[var(--text-muted)]" v-text="t('help.askAboutTranscription')"></p>
- </div>
- <div v-for="(message, index) in chatMessages" :key="index"
- :class="['message relative group', message.role === 'user' ? 'user-message ml-auto' : 'ai-message',
- message.role === 'assistant' ? 'pr-10' : '']">
- <!-- Copy button for assistant messages -->
- <button v-if="message.role === 'assistant'"
- @click="copyMessage(message.content, $event)"
- class="absolute top-2 right-2 p-1 text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-tertiary)] rounded transition-all duration-200"
- :title="t('buttons.copyMessage')">
- <i class="fas fa-copy text-sm"></i>
- </button>
- <!-- Show thinking content if available -->
- <div v-if="message.thinking && message.role === 'assistant'" class="mb-2">
- <button @click="message.thinkingExpanded = !message.thinkingExpanded"
- class="text-xs text-[var(--text-muted)] hover:text-[var(--text-secondary)] flex items-center gap-1">
- <i :class="['fas', message.thinkingExpanded ? 'fa-chevron-down' : 'fa-chevron-right']"></i>
- <span v-text="t('help.modelReasoning')"></span>
- <span class="text-[var(--text-muted)]">(${message.thinking.split('\n').length} lines)</span>
- </button>
- <div v-if="message.thinkingExpanded"
- class="mt-2 p-3 bg-[var(--bg-tertiary)] border border-[var(--border-secondary)] rounded-lg text-xs text-[var(--text-muted)] max-h-64 overflow-y-auto">
- <pre class="whitespace-pre-wrap font-mono">${message.thinking}</pre>
- </div>
- </div>
- <!-- Main message content -->
- <div v-if="message.html" v-html="message.html"></div>
- <div v-else class="whitespace-pre-wrap">${message.content}</div>
- </div>
- <div v-if="isChatLoading" class="ai-message">
- <i class="fas fa-spinner fa-spin mr-2"></i> Thinking...
- </div>
- </div>
- <div class="border-t border-[var(--border-primary)] p-4 bg-[var(--bg-tertiary)]">
- <div class="flex gap-2">
- <textarea v-model="chatInput" @keydown="handleChatKeydown" :disabled="isChatLoading || selectedRecording.status !== 'COMPLETED'" :placeholder="t('chat.placeholder')" class="flex-1 px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)] text-sm" rows="2"></textarea>
- <button @click="sendChatMessage" :disabled="!chatInput.trim() || isChatLoading || selectedRecording.status !== 'COMPLETED'" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
- <i class="fas fa-paper-plane"></i>
- </button>
- </div>
- </div>
- </div>
- <!-- Events Panel (Mobile) -->
- <div v-if="mobileTab === 'events' && selectedRecording.events && selectedRecording.events.length > 0" class="h-full flex flex-col space-y-4">
- <div class="flex items-center justify-end gap-2 flex-shrink-0 pr-3">
- <button @click="downloadICS" v-if="selectedRecording.events && selectedRecording.events.length > 0"
- class="copy-btn"
- :title="t('buttons.exportCalendar')">
- <i class="fas fa-calendar-plus"></i>
- </button>
- </div>
- <div class="flex-grow overflow-y-auto mobile-content-box">
- <div class="space-y-3">
- <div v-for="event in selectedRecording.events" :key="event.id"
- class="bg-[var(--bg-tertiary)] rounded-lg p-3 border border-[var(--border-primary)]">
- <div class="flex justify-between items-start mb-2">
- <div class="flex-1">
- <h3 class="text-base font-semibold text-[var(--text-primary)] mb-1">
- <i class="fas fa-calendar-check mr-2 text-[var(--text-accent)] text-sm"></i>
- ${ event.title }
- </h3>
- <p v-if="event.description" class="text-xs text-[var(--text-secondary)] mb-2">
- ${ event.description }
- </p>
- </div>
- <button @click="downloadEventICS(event)"
- class="px-2 py-1 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors text-xs flex items-center gap-1"
- :title="t('events.addToCalendar')">
- <i class="fas fa-download text-xs"></i>
- <span v-text="t('events.add')"></span>
- </button>
- </div>
- <div class="grid grid-cols-1 gap-2 text-xs">
- <div class="flex items-center text-[var(--text-muted)]">
- <i class="fas fa-clock mr-2 text-[var(--text-accent)]"></i>
- <span>
- ${ formatEventDateTime(event.start_datetime) }
- <template v-if="event.end_datetime">
- - ${ formatEventDateTime(event.end_datetime, true) }
- </template>
- </span>
- </div>
- <div v-if="event.location" class="flex items-center text-[var(--text-muted)]">
- <i class="fas fa-map-marker-alt mr-2 text-[var(--text-accent)]"></i>
- <span>${ event.location }</span>
- </div>
- <div v-if="event.attendees && event.attendees.length > 0" class="flex items-start text-[var(--text-muted)]">
- <i class="fas fa-users mr-2 text-[var(--text-accent)] mt-0.5"></i>
- <div class="flex-1">
- <span v-for="(attendee, index) in event.attendees" :key="index"
- class="inline-block bg-[var(--bg-secondary)] px-2 py-0.5 rounded mr-1 mb-1">
- ${ attendee }
- </span>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- <!-- Desktop View -->
- <div v-else class="flex-1 flex flex-col overflow-hidden">
- <!-- Recording Header -->
- <div class="bg-[var(--bg-secondary)] border-b border-[var(--border-primary)] p-6 flex-shrink-0">
- <div class="flex flex-col">
- <div class="flex items-start justify-between">
- <div class="flex-1 min-w-0">
- <h1 class="text-2xl font-bold text-[var(--text-primary)] mb-2">
- ${selectedRecording.title || 'Untitled Recording'}
- </h1>
- </div>
-
- <!-- Action Buttons -->
- <div class="flex items-center gap-2 ml-4">
- <button @click="toggleInbox(selectedRecording)"
- class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"
- :class="selectedRecording.is_inbox ? 'text-blue-500' : ''"
- :title="selectedRecording.is_inbox ? 'Mark as Read' : 'Move to Inbox'">
- <i class="fas fa-inbox"></i>
- </button>
- <button @click="toggleHighlight(selectedRecording)"
- class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"
- :class="selectedRecording.is_highlighted ? 'text-yellow-500' : ''"
- :title="selectedRecording.is_highlighted ? 'Remove Highlight' : 'Highlight'">
- <i class="fas fa-star"></i>
- </button>
- <button @click="editRecording(selectedRecording)"
- class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors">
- <i class="fas fa-edit"></i>
- </button>
- <button @click="editRecordingTags(selectedRecording)"
- class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"
- :title="t('buttons.editTags')">
- <i class="fas fa-tags"></i>
- </button>
- <button @click="reprocessTranscription(selectedRecording.id)" v-if="selectedRecording && (selectedRecording.status === 'COMPLETED' || selectedRecording.status === 'FAILED')"
- class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"
- :title="useAsrEndpoint ? 'Reprocess with ASR' : 'Reprocess transcription'">
- <i class="fas fa-redo-alt"></i>
- </button>
- <button @click="reprocessSummary(selectedRecording.id)" v-if="selectedRecording && (selectedRecording.status === 'COMPLETED' || selectedRecording.status === 'FAILED')"
- class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"
- :title="t('buttons.reprocessSummary')">
- <i class="fas fa-sync-alt"></i>
- </button>
- <button @click="confirmReset(selectedRecording)" v-if="['PROCESSING', 'SUMMARIZING', 'FAILED'].includes(selectedRecording.status)"
- class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors text-orange-500"
- :title="t('buttons.resetStuckProcessing')">
- <i class="fas fa-undo"></i>
- </button>
- <button @click="openSpeakerModal" v-if="selectedRecording.transcription && useAsrEndpoint"
- class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"
- :title="t('buttons.identifySpeakers')">
- <i class="fas fa-user-tag"></i>
- </button>
- <button @click="openShareModal(selectedRecording)"
- class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"
- :title="t('buttons.shareRecording')">
- <i class="fas fa-share-alt"></i>
- </button>
- <button @click="confirmDelete(selectedRecording)"
- class="p-2 rounded-lg hover:bg-[var(--bg-danger-light)] text-[var(--text-danger)] transition-colors">
- <i class="fas fa-trash"></i>
- </button>
- </div>
- </div>
-
- <!-- Metadata Row -->
- <div class="flex flex-wrap items-center gap-x-6 gap-y-2 text-sm text-[var(--text-muted)] mt-2">
- <!-- Participants -->
- <div class="flex items-center gap-2">
- <i class="fas fa-users text-[var(--text-accent)]"></i>
- <span v-if="!editingParticipants"
- @click="toggleEditParticipants"
- class="cursor-pointer hover:text-[var(--text-accent)] transition-colors">
- ${selectedRecording.participants || t('help.noParticipants')}
- </span>
- <input v-else
- v-model="selectedRecording.participants"
- @blur="toggleEditParticipants"
- @keyup.enter="toggleEditParticipants"
- class="bg-transparent border-b border-[var(--border-secondary)] focus:border-[var(--border-focus)] outline-none px-1">
- </div>
-
- <!-- Meeting Date -->
- <div class="flex items-center gap-2">
- <i class="fas fa-calendar text-[var(--text-accent)]"></i>
- <span v-if="!editingMeetingDate"
- @click="toggleEditMeetingDate"
- class="cursor-pointer hover:text-[var(--text-accent)] transition-colors">
- ${selectedRecording.meeting_date ? formatDisplayDate(selectedRecording.meeting_date) : 'No date set'}
- </span>
- <input v-else
- v-model="selectedRecording.meeting_date"
- @blur="toggleEditMeetingDate"
- @keyup.enter="toggleEditMeetingDate"
- type="date"
- class="bg-transparent border-b border-[var(--border-secondary)] focus:border-[var(--border-focus)] outline-none px-1">
- </div>
-
- <!-- Other Metadata -->
- <div v-if="activeRecordingMetadata" class="flex flex-wrap items-center gap-x-6 gap-y-2">
- <template v-for="(item, index) in activeRecordingMetadata" :key="index">
- <!-- Special rendering for tags -->
- <div v-if="item.isTagItem" class="flex items-center gap-1.5">
- <i :class="item.icon" class="text-[var(--text-muted)]"></i>
- <div class="flex flex-wrap items-center gap-1">
- <span v-for="tag in item.tags" :key="tag.id"
- class="inline-flex items-center px-2 py-0.5 text-xs font-medium rounded-full text-white"
- :style="{ backgroundColor: tag.color || '#6B7280' }">
- ${tag.name}
- </span>
- </div>
- </div>
- <!-- Regular metadata items -->
- <span v-else class="flex items-center gap-1.5">
- <i :class="item.icon"></i>
- <span :title="item.fullText || item.text">${item.text}</span>
- </span>
- </template>
- </div>
-
- <!-- Status -->
- <div v-if="selectedRecording.status !== 'COMPLETED'" class="flex items-center gap-2">
- <span :class="getStatusClass(selectedRecording.status)" class="status-badge">
- ${formatStatus(selectedRecording.status)}
- </span>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Main Content Split View -->
- <div id="mainContentColumns" class="flex-1 flex overflow-hidden">
- <!-- Left Panel: Transcription -->
- <div id="leftMainColumn" class="flex flex-col overflow-hidden" :style="{width: leftColumnWidth + '%'}">
- <!-- Transcription Header -->
- <div class="bg-[var(--bg-tertiary)] px-4 py-3 border-b border-[var(--border-primary)] flex items-center justify-between">
- <h3 class="font-semibold flex items-center">
- <i class="fas fa-file-text mr-2"></i>
- <span v-text="t('transcription.title')"></span>
- </h3>
- <div class="flex items-center gap-2">
- <!-- View Mode Toggle -->
- <div v-if="processedTranscription.hasDialogue" class="view-mode-toggle">
- <button @click="toggleTranscriptionViewMode"
- :class="['toggle-button', transcriptionViewMode === 'simple' ? 'active' : '']">
- <i class="fas fa-list"></i><span v-text="t('transcription.simple')"></span>
- </button>
- <button @click="toggleTranscriptionViewMode"
- :class="['toggle-button', transcriptionViewMode === 'bubble' ? 'active' : '']">
- <i class="fas fa-comments"></i><span v-text="t('transcription.bubble')"></span>
- </button>
- </div>
-
- <!-- Copy Button -->
- <button @click="copyTranscription"
- class="copy-btn">
- <i class="fas fa-copy mr-1"></i><span v-text="t('transcription.copy')"></span>
- </button>
- <!-- Download Button -->
- <button @click="downloadTranscript"
- v-if="selectedRecording && selectedRecording.transcription"
- class="copy-btn"
- title="Download transcript with template">
- <i class="fas fa-download mr-1"></i><span v-text="t('transcription.download')"></span>
- </button>
- <!-- Edit Transcription Button -->
- <button @click="openTranscriptionEditor"
- v-if="selectedRecording && selectedRecording.transcription"
- class="copy-btn">
- <i class="fas fa-edit mr-1"></i><span v-text="t('transcription.edit')"></span>
- </button>
- </div>
- </div>
-
- <!-- Transcription Content -->
- <div class="flex-1 overflow-y-auto p-4">
- <div v-if="selectedRecording.status === 'PROCESSING'" class="text-center py-8">
- <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
- <p class="mt-2 text-[var(--text-muted)]" v-text="t('help.processingTranscription')"></p>
- </div>
-
- <div v-else-if="!selectedRecording.transcription" class="text-center py-8">
- <i class="fas fa-file-text text-3xl text-[var(--text-muted)] mb-3"></i>
- <p class="text-[var(--text-muted)]" v-text="t('transcription.noTranscription')"></p>
- </div>
-
- <!-- Speaker Legend (for dialogue transcriptions in bubble view only) -->
- <div v-if="processedTranscription.hasDialogue && processedTranscription.speakers.length > 0 && transcriptionViewMode === 'bubble'"
- :class="['speaker-legend', legendExpanded ? 'expanded' : '']">
- <div class="speaker-legend-header" @click="legendExpanded = !legendExpanded">
- <div class="speaker-legend-title">
- <i class="fas fa-users"></i>
- <span v-text="t('help.speakers')"></span>
- <span class="speaker-count-indicator">(${processedTranscription.speakers.length})</span>
- </div>
- <i class="fas fa-chevron-down speaker-legend-toggle"></i>
- </div>
- <div class="speaker-legend-content">
- <div v-for="(speaker, index) in processedTranscription.speakers"
- :key="`${selectedRecording.id}-speaker-legend-${index}`"
- :class="['speaker-legend-item', speaker.color]">
- <span class="speaker-name">${speaker.name}</span>
- </div>
- </div>
- </div>
-
- <!-- Transcription Display -->
- <div v-if="selectedRecording.transcription">
- <!-- Simple View -->
- <div v-if="!processedTranscription.hasDialogue || transcriptionViewMode === 'simple'"
- class="transcription-simple-view">
- <div v-if="processedTranscription.hasDialogue">
- <div v-for="segment in processedTranscription.simpleSegments"
- :key="segment.startTime || Math.random()"
- class="speaker-segment"
- @click="seekAudioFromEvent"
- :data-start-time="segment.startTime">
- <div v-if="segment.showSpeaker"
- :class="['speaker-tablet', segment.color]">
- ${segment.speaker}
- </div>
- <div class="speaker-text">
- ${segment.sentence}
- </div>
- </div>
- </div>
- <div v-else>
- <div v-if="processedTranscription.simpleSegments && processedTranscription.simpleSegments.length > 0">
- <div v-for="segment in processedTranscription.simpleSegments"
- :key="segment.startTime || Math.random()"
- class="transcript-segment cursor-pointer hover:bg-[var(--bg-accent-hover)] p-2 rounded transition-colors"
- @click="seekAudioFromEvent"
- :data-start-time="segment.startTime">
- ${segment.sentence}
- </div>
- </div>
- <div v-else class="whitespace-pre-wrap">
- ${processedTranscription.content}
- </div>
- </div>
- </div>
-
- <!-- Bubble View -->
- <div v-else-if="transcriptionViewMode === 'bubble'"
- class="transcription-with-speakers">
- <div v-for="(row, rowIndex) in processedTranscription.bubbleRows"
- :key="`${selectedRecording.id}-bubble-row-${rowIndex}`"
- :class="['bubble-row', row.isMe ? 'speaker-me' : '']">
- <div v-for="bubble in row.bubbles"
- :key="bubble.startTime || Math.random()"
- :class="['speaker-bubble', bubble.color, row.isMe ? 'speaker-me' : '']"
- @click="seekAudioFromEvent"
- :data-start-time="bubble.startTime">
- <div class="speaker-bubble-content">
- ${bubble.sentence}
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Resizable Divider - Minimal but functional -->
- <div id="mainColumnResizer" @mousedown="startColumnResize"></div>
+ {% include 'components/recording-view.html' %}
- <!-- Right Panel: Summary/Notes and Chat -->
- <div id="rightMainColumn" class="flex flex-col overflow-hidden" :style="{width: rightColumnWidth + '%'}">
- <!-- Audio Player -->
- <div class="bg-[var(--bg-secondary)] p-4 border-b border-[var(--border-primary)] flex-shrink-0">
- <div class="audio-player-container">
- <audio controls
- :src="'/audio/' + selectedRecording.id"
- :volume="playerVolume"
- @volumechange="onPlayerVolumeChange"
- class="w-full">
- Your browser does not support the audio element.
- </audio>
- </div>
- </div>
-
- <!-- Summary/Notes Tabs -->
- <div :class="{'flex-1': !isChatMaximized, 'flex-none': isChatMaximized}" class="flex flex-col overflow-hidden">
- <!-- Tab Navigation -->
- <div class="bg-[var(--bg-tertiary)] border-b border-[var(--border-primary)] flex">
- <button @click="selectedTab = 'summary'"
- :class="[
- 'flex-1 px-4 py-3 text-sm font-medium transition-colors',
- selectedTab === 'summary'
- ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]'
- : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]'
- ]">
- ${ t('summary.title') }
- </button>
- <button @click="selectedTab = 'notes'"
- :class="[
- 'flex-1 px-4 py-3 text-sm font-medium transition-colors',
- selectedTab === 'notes'
- ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]'
- : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]'
- ]">
- ${ t('notes.title') }
- </button>
- <button v-if="selectedRecording.events && selectedRecording.events.length > 0"
- @click="selectedTab = 'events'"
- :class="[
- 'flex-1 px-4 py-3 text-sm font-medium transition-colors',
- selectedTab === 'events'
- ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]'
- : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]'
- ]">
- <i class="fas fa-calendar-alt mr-1"></i>
- ${ t('events.title') } (${ selectedRecording.events.length })
- </button>
- </div>
-
- <!-- Tab Content -->
- <div v-if="!isChatMaximized" class="flex-1 overflow-hidden">
- <!-- Summary Tab -->
- <div v-if="selectedTab === 'summary'" class="h-full p-4 overflow-y-auto">
- <div v-if="selectedRecording.status === 'SUMMARIZING'" class="text-center py-8">
- <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
- <p class="mt-2 text-[var(--text-muted)]" v-text="t('summary.summaryInProgress')"></p>
- </div>
-
- <div v-else-if="!selectedRecording.summary" class="text-center py-8">
- <i class="fas fa-file-alt text-3xl text-[var(--text-muted)] mb-3"></i>
- <p class="text-[var(--text-muted)] mb-4" v-text="t('summary.noSummary')"></p>
- <button @click="generateSummary"
- class="px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 text-white font-medium rounded-lg shadow-lg hover:shadow-xl hover:from-blue-700 hover:to-purple-700 transition-all duration-200 transform hover:scale-105">
- <i class="fas fa-magic mr-2"></i>${ t('summary.generateSummary') }
- </button>
- </div>
-
- <div v-else class="content-box relative">
- <div v-if="!editingSummary" class="absolute top-2 right-4 flex gap-1 z-10">
- <button @click="copySummary"
- :title="t('buttons.copySummary')"
- 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="t('buttons.downloadSummary')"
- 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="t('buttons.editSummary')"
- 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>
-
- <div v-if="!editingSummary"
- class="summary-box"
- v-html="selectedRecording.summary_html || selectedRecording.summary">
- </div>
- <div v-else class="h-full flex flex-col">
- <div class="markdown-editor-container flex-1">
- <textarea ref="summaryMarkdownEditor"
- v-model="selectedRecording.summary"
- class="w-full h-full p-4 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]"
- :placeholder="t('form.enterSummaryMarkdown')">
- </textarea>
- </div>
- <div class="flex justify-end gap-2 mt-2">
- <button @click="cancelEditSummary"
- class="px-3 py-1 text-sm bg-[var(--bg-secondary)] text-[var(--text-secondary)] border border-[var(--border-secondary)] rounded hover:bg-[var(--bg-tertiary)]">
- Cancel
- </button>
- <button @click="saveEditSummary"
- class="px-3 py-1 text-sm bg-[var(--bg-button)] text-[var(--text-button)] rounded hover:bg-[var(--bg-button-hover)]">
- Save
- </button>
- </div>
- </div>
- </div>
- </div>
-
- <!-- 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-4 flex gap-1 z-10">
- <button @click="copyNotes"
- :title="t('buttons.copyNotes')"
- 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="t('buttons.downloadNotes')"
- 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="t('buttons.editNotes')"
- 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>
-
- <div v-if="!editingNotes"
- class="notes-box h-full"
- @click="clickToEditNotes">
- <div v-if="selectedRecording.notes_html"
- v-html="selectedRecording.notes_html">
- </div>
- <div v-else-if="selectedRecording.notes"
- class="whitespace-pre-wrap">
- ${selectedRecording.notes}
- </div>
- <div v-else class="text-[var(--text-muted)] italic cursor-pointer hover:text-[var(--text-secondary)]">
- ${ t('help.clickToAddNotes') }
- </div>
- </div>
-
- <div v-else class="h-full flex flex-col">
- <div class="markdown-editor-container flex-1">
- <textarea ref="notesMarkdownEditor"
- v-model="selectedRecording.notes"
- class="w-full h-full p-4 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]"
- :placeholder="t('form.enterNotesMarkdown')">
- </textarea>
- </div>
- <div class="flex justify-end gap-2 mt-2">
- <button @click="cancelEditNotes"
- class="px-3 py-1 text-sm bg-[var(--bg-secondary)] text-[var(--text-secondary)] border border-[var(--border-secondary)] rounded hover:bg-[var(--bg-tertiary)]">
- Cancel
- </button>
- <button @click="saveEditNotes"
- class="px-3 py-1 text-sm bg-[var(--bg-button)] text-[var(--text-button)] rounded hover:bg-[var(--bg-button-hover)]">
- Save
- </button>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Events Tab -->
- <div v-if="selectedTab === 'events' && selectedRecording.events && selectedRecording.events.length > 0" class="h-full p-4 overflow-y-auto">
- <div class="space-y-4">
- <div v-for="event in selectedRecording.events" :key="event.id"
- class="bg-[var(--bg-tertiary)] rounded-lg p-4 border border-[var(--border-primary)] hover:border-[var(--border-accent)] transition-colors">
- <div class="flex justify-between items-start mb-3">
- <div class="flex-1">
- <h3 class="text-lg font-semibold text-[var(--text-primary)] mb-1">
- <i class="fas fa-calendar-check mr-2 text-[var(--text-accent)]"></i>
- ${ event.title }
- </h3>
- <p v-if="event.description" class="text-sm text-[var(--text-secondary)] mb-2">
- ${ event.description }
- </p>
- </div>
- <button @click="downloadEventICS(event)"
- 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-1.5"
- :title="t('events.addToCalendar')">
- <i class="fas fa-download"></i>
- <span v-text="t('events.addToCalendar')"></span>
- </button>
- </div>
-
- <div class="space-y-2 text-sm">
- <div class="flex items-center gap-2" v-if="event.start_datetime">
- <i class="fas fa-clock text-[var(--text-muted)] w-4"></i>
- <span class="text-[var(--text-secondary)]">
- <strong v-text="t('events.start') + ':'"></strong> ${ formatEventDateTime(event.start_datetime) }
- </span>
- </div>
- <div class="flex items-center gap-2" v-if="event.end_datetime">
- <i class="fas fa-clock text-[var(--text-muted)] w-4"></i>
- <span class="text-[var(--text-secondary)]">
- <strong v-text="t('events.end') + ':'"></strong> ${ formatEventDateTime(event.end_datetime) }
- </span>
- </div>
- <div class="flex items-center gap-2" v-if="event.location">
- <i class="fas fa-map-marker-alt text-[var(--text-muted)] w-4"></i>
- <span class="text-[var(--text-secondary)]">
- <strong v-text="t('events.location') + ':'"></strong> ${ event.location }
- </span>
- </div>
- <div class="flex items-start gap-2" v-if="event.attendees && event.attendees.length > 0">
- <i class="fas fa-users text-[var(--text-muted)] w-4 mt-0.5"></i>
- <div class="text-[var(--text-secondary)]">
- <strong v-text="t('events.attendees') + ':'"></strong>
- <span class="ml-1">${ event.attendees.join(', ') }</span>
- </div>
- </div>
- </div>
- </div>
-
- <div v-if="selectedRecording.events.length === 0" class="text-center py-8">
- <i class="fas fa-calendar-times text-3xl text-[var(--text-muted)] mb-3"></i>
- <p class="text-[var(--text-muted)]" v-text="t('events.noEvents')"></p>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Chat Section -->
- <div class="border-t border-[var(--border-primary)] flex flex-col" :class="{'flex-1 overflow-hidden': isChatMaximized}">
- <!-- Chat Toggle -->
- <div class="bg-[var(--bg-tertiary)] px-4 py-3 hover:bg-[var(--bg-accent-hover)] transition-colors flex items-center">
- <button @click="() => { showChat = !showChat; if (!showChat) isChatMaximized = false; }"
- class="flex-1 text-left flex items-center">
- <span class="font-medium flex items-center">
- <i class="fas fa-comments mr-2"></i>
- ${ t('chat.chatWithTranscription') }
- </span>
- </button>
- <div class="flex items-center gap-2">
- <button v-if="chatMessages.length > 0"
- @click="downloadChat"
- class="p-1 text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors"
- :title="t('buttons.downloadChat')">
- <i class="fas fa-download text-sm"></i>
- </button>
- <button @click="toggleChatMaximize"
- class="p-1 text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors"
- :title="isChatMaximized ? 'Restore chat' : 'Maximize chat'">
- <i :class="['fas text-sm', isChatMaximized ? 'fa-compress' : 'fa-expand']"></i>
- </button>
- <button @click="() => { showChat = !showChat; if (!showChat) isChatMaximized = false; }"
- class="p-1 text-[var(--text-muted)] hover:text-[var(--text-primary)]">
- <i :class="['fas transition-transform duration-200', showChat ? 'fa-chevron-down' : 'fa-chevron-up']"></i>
- </button>
- </div>
- </div>
-
- <!-- Chat Content -->
- <div v-if="showChat" class="flex flex-col relative" :class="isChatMaximized ? 'flex-1 overflow-hidden' : 'max-h-96'">
- <!-- Clear button - fixed at top right -->
- <button v-if="chatMessages.length > 0"
- @click="clearChat"
- class="absolute top-2 right-2 p-1 text-[var(--text-muted)] opacity-60 hover:opacity-100 hover:text-[var(--text-danger)] rounded transition-all duration-200 z-20"
- title="Clear chat">
- <i class="fas fa-times text-xs"></i>
- </button>
-
- <!-- Chat Messages -->
- <div ref="chatMessagesRef"
- class="flex-1 overflow-y-auto p-4 space-y-4 bg-[var(--bg-secondary)]">
- <div v-if="chatMessages.length === 0" class="text-center py-8">
- <i class="fas fa-robot text-3xl text-[var(--text-muted)] mb-3"></i>
- <p class="text-[var(--text-muted)]" v-text="t('help.askAboutTranscription')"></p>
- </div>
-
- <div v-for="(message, index) in chatMessages"
- :key="index"
- :class="[
- 'message relative group',
- message.role === 'user' ? 'user-message ml-auto' : 'ai-message',
- message.role === 'assistant' ? 'pr-10' : ''
- ]">
- <!-- Copy button for assistant messages -->
- <button v-if="message.role === 'assistant'"
- @click="copyMessage(message.content, $event)"
- class="absolute top-2 right-2 p-1 text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-tertiary)] rounded transition-all duration-200"
- :title="t('buttons.copyMessage')">
- <i class="fas fa-copy text-sm"></i>
- </button>
- <!-- Show thinking content if available -->
- <div v-if="message.thinking && message.role === 'assistant'" class="mb-2">
- <button @click="message.thinkingExpanded = !message.thinkingExpanded"
- class="text-xs text-[var(--text-muted)] hover:text-[var(--text-secondary)] flex items-center gap-1">
- <i :class="['fas', message.thinkingExpanded ? 'fa-chevron-down' : 'fa-chevron-right']"></i>
- <span v-text="t('help.modelReasoning')"></span>
- <span class="text-[var(--text-muted)]">(${message.thinking.split('\n').length} lines)</span>
- </button>
- <div v-if="message.thinkingExpanded"
- class="mt-2 p-3 bg-[var(--bg-tertiary)] border border-[var(--border-secondary)] rounded-lg text-xs text-[var(--text-muted)] max-h-64 overflow-y-auto">
- <pre class="whitespace-pre-wrap font-mono">${message.thinking}</pre>
- </div>
- </div>
- <!-- Main message content -->
- <div v-if="message.html" v-html="message.html"></div>
- <div v-else class="whitespace-pre-wrap">${message.content}</div>
- </div>
-
- <div v-if="isChatLoading" class="ai-message">
- <i class="fas fa-spinner fa-spin mr-2"></i>
- ${ t('chat.thinking') }
- </div>
- </div>
-
- <!-- Chat Input -->
- <div class="border-t border-[var(--border-primary)] p-4 bg-[var(--bg-tertiary)]">
- <div class="flex gap-2">
- <textarea v-model="chatInput"
- @keydown="handleChatKeydown"
- :disabled="isChatLoading || selectedRecording.status !== 'COMPLETED'"
- :placeholder="t('chat.placeholderWithHint')"
- class="flex-1 px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)] text-sm"
- rows="2">
- </textarea>
- <button @click="sendChatMessage"
- :disabled="!chatInput.trim() || isChatLoading || selectedRecording.status !== 'COMPLETED'"
- class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
- <i class="fas fa-paper-plane"></i>
- </button>
- </div>
- <p v-if="selectedRecording.status !== 'COMPLETED'"
- class="text-xs text-[var(--text-muted)] mt-2">
- ${ t('chat.availableAfterTranscription') }
- </p>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Empty State -->
- <div v-else-if="currentView === 'detail' && !selectedRecording" class="flex-1 flex items-center justify-center">
- <div class="text-center">
- <i class="fas fa-microphone text-6xl text-[var(--text-muted)] mb-4"></i>
- <h2 class="text-2xl font-bold mb-2" v-text="t('colorScheme.selectRecording')"></h2>
- <p class="text-[var(--text-muted)] mb-6" v-text="t('colorScheme.chooseRecording')"></p>
- <button @click="switchToUploadView"
- class="px-6 py-3 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors">
- <i class="fas fa-plus mr-2"></i>Upload New Recording
- </button>
- </div>
- </div>
- </div>
+ <!-- Detail View -->
+ {% include 'components/detail-view.html' %}
+ </main>
</div>
<!-- Upload Progress Popup -->
- <div v-if="uploadQueue.length > 0 && !progressPopupClosed"
- :class="[
- 'fixed bottom-4 left-4 z-[100] w-96 transition-all duration-300',
- progressPopupMinimized ? 'minimized' : ''
- ]">
- <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-gradient-to-r from-[var(--bg-accent)] to-[var(--bg-accent-hover)] px-4 py-3">
- <!-- Top row: Title and buttons -->
- <div class="flex items-center justify-between mb-2">
- <div class="flex items-center gap-2 min-w-0">
- <i class="fas fa-upload text-gray-800 dark:text-white animate-pulse"></i>
- <span class="font-semibold text-gray-800 dark:text-white truncate" v-text="t('uploadProgress.title')"></span>
- </div>
- <div class="flex items-center gap-2 flex-shrink-0">
- <button v-if="completedInQueue > 0" @click="clearCompletedUploads()"
- class="px-2 py-0.5 text-xs bg-black dark:bg-white bg-opacity-10 dark:bg-opacity-20 hover:bg-opacity-20 dark:hover:bg-opacity-30 rounded transition-all duration-200 text-gray-800 dark:text-white font-medium"
- :title="t('buttons.clearCompleted')">
- Clear
- </button>
- <button @click="progressPopupMinimized = !progressPopupMinimized"
- class="p-1 rounded hover:bg-black dark:hover:bg-white hover:bg-opacity-10 dark:hover:bg-opacity-20 transition-colors text-gray-800 dark:text-white">
- <i :class="progressPopupMinimized ? 'fas fa-chevron-up' : 'fas fa-chevron-down'"></i>
- </button>
- <button @click="progressPopupClosed = true"
- class="p-1 rounded hover:bg-red-600 dark:hover:bg-red-500 hover:bg-opacity-20 dark:hover:bg-opacity-30 text-gray-800 dark:text-white hover:text-white transition-colors">
- <i class="fas fa-times"></i>
- </button>
- </div>
- </div>
- <!-- Overall Progress Bar -->
- <div class="space-y-1">
- <div class="flex justify-between items-center text-xs text-gray-800 dark:text-white">
- <span class="font-medium">${completedInQueue} of ${totalInQueue} files</span>
- <span class="font-bold">${Math.round((completedInQueue / Math.max(totalInQueue, 1)) * 100)}%</span>
- </div>
- <div class="w-full bg-black dark:bg-white bg-opacity-10 dark:bg-opacity-20 rounded-full h-2 overflow-hidden">
- <div class="bg-white dark:bg-white bg-opacity-80 dark:bg-opacity-90 h-full rounded-full transition-all duration-500 ease-out relative overflow-hidden"
- :style="{width: (completedInQueue / Math.max(totalInQueue, 1) * 100) + '%'}">
- <div class="absolute inset-0 bg-white opacity-30 animate-pulse"></div>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Progress Content -->
- <div v-if="!progressPopupMinimized" class="p-3 max-h-64 overflow-y-auto">
- <div v-if="currentlyProcessingFile" class="mb-3 p-3 bg-[var(--bg-accent)] bg-opacity-10 border border-[var(--border-accent)] rounded-lg">
- <div class="flex items-center justify-between mb-2">
- <span class="font-semibold truncate min-w-0 text-sm text-[var(--text-primary)]">${currentlyProcessingFile.file.name}</span>
- <span class="text-sm flex-shrink-0 ml-2 font-bold text-[var(--text-accent)]">${processingProgress}%</span>
- </div>
- <div class="w-full bg-[var(--bg-tertiary)] rounded-full h-2 mb-2 overflow-hidden">
- <div class="bg-gradient-to-r from-[var(--bg-accent)] to-[var(--bg-accent-hover)] h-full rounded-full transition-all duration-300 relative"
- :style="{width: processingProgress + '%'}">
- <div class="absolute inset-0 bg-white opacity-20 animate-pulse"></div>
- </div>
- </div>
- <p class="text-xs text-[var(--text-secondary)] font-medium">${processingMessage}</p>
- </div>
-
- <div v-if="finishedFilesInQueue.length > 0" class="space-y-2">
- <h4 class="text-xs font-semibold text-[var(--text-secondary)] uppercase tracking-wider opacity-70" v-text="t('help.completedFiles')"></h4>
- <div v-for="item in finishedFilesInQueue"
- :key="item.clientId"
- class="progress-list-item p-2 bg-[var(--bg-tertiary)] bg-opacity-50 rounded-lg flex items-center gap-2 hover:bg-opacity-70 transition-all duration-200">
- <i :class="[
- 'fas',
- item.status === 'completed' ? 'fa-check-circle text-green-500' : 'fa-exclamation-circle text-red-500'
- ]"></i>
- <span class="truncate text-sm flex-1 text-[var(--text-primary)]">${item.file.name}</span>
- <span :class="[
- 'text-xs px-2 py-1 rounded-full font-semibold',
- item.status === 'completed' ? 'bg-green-500 bg-opacity-20 text-green-600 dark:text-green-400' : 'bg-red-500 bg-opacity-20 text-red-600 dark:text-red-400'
- ]">
- ${item.status === 'completed' ? t('tagsModal.done') : t('status.failed')}
- </span>
- </div>
- </div>
- </div>
- </div>
- </div>
+ {% include 'components/progress-popup.html' %}
<!-- Modals -->
- <!-- Edit Modal -->
- <div v-if="showEditModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
- <div class="bg-[var(--bg-secondary)] rounded-lg shadow-xl w-full max-w-lg">
- <div class="p-6 border-b border-[var(--border-primary)]">
- <h3 class="text-lg font-semibold" v-text="t('modal.editRecording')"></h3>
- </div>
- <div class="p-6 space-y-4">
- <div>
- <label class="block text-sm font-medium mb-2" v-text="t('form.title')"></label>
- <input v-model="editingRecording.title"
- class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]">
- </div>
- <div>
- <label class="block text-sm font-medium mb-2" v-text="t('form.participants')"></label>
- <input v-model="editingRecording.participants"
- class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]">
- </div>
- <div>
- <label class="block text-sm font-medium mb-2" v-text="t('form.meetingDate')"></label>
- <input v-model="editingRecording.meeting_date"
- type="date"
- class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]">
- </div>
- <div>
- <label class="block text-sm font-medium mb-2" v-text="t('form.notes')"></label>
- <textarea v-model="editingRecording.notes"
- rows="4"
- class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]">
- </textarea>
- </div>
- </div>
- <div class="p-6 border-t border-[var(--border-primary)] flex justify-end gap-3">
- <button @click="cancelEdit"
- class="px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] rounded-lg transition-colors">
- Cancel
- </button>
- <button @click="saveEdit"
- class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors">
- Save Changes
- </button>
- </div>
- </div>
- </div>
-
- <!-- Delete Confirmation Modal -->
- <div v-if="showDeleteModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
- <div class="bg-[var(--bg-secondary)] rounded-lg shadow-xl w-full max-w-md">
- <div class="p-6">
- <div class="flex items-center gap-4 mb-4">
- <i class="fas fa-exclamation-triangle text-3xl text-[var(--text-danger)]"></i>
- <div>
- <h3 class="text-lg font-semibold" v-text="t('modal.deleteRecording')"></h3>
- <p class="text-[var(--text-muted)]" v-text="t('help.thisActionCannotBeUndone')"></p>
- </div>
- </div>
- <p class="text-[var(--text-secondary)] mb-6">
- Are you sure you want to delete "${recordingToDelete?.title || 'this recording'}"?
- </p>
- <div class="flex justify-end gap-3">
- <button @click="cancelDelete"
- class="px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] rounded-lg transition-colors">
- Cancel
- </button>
- <button @click="deleteRecording"
- class="px-4 py-2 bg-[var(--bg-danger)] text-white rounded-lg hover:bg-[var(--bg-danger-hover)] transition-colors">
- Delete
- </button>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Edit Recording Tags Modal -->
- <div v-if="showEditTagsModal" @click="closeEditTagsModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
- <div @click.stop class="bg-[var(--bg-secondary)] rounded-lg shadow-xl w-full max-w-lg max-h-[80vh] flex flex-col">
- <div class="flex-shrink-0 p-6 border-b border-[var(--border-primary)]">
- <div class="flex items-center justify-between">
- <h3 class="text-lg font-medium text-[var(--text-primary)]" v-text="t('modal.editTags')"></h3>
- <button @click="closeEditTagsModal" class="text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors">
- <i class="fas fa-times"></i>
- </button>
- </div>
- </div>
- <div class="flex-1 overflow-y-auto p-6 space-y-4">
- <!-- Current Tags Section -->
- <div>
- <label class="block text-sm font-medium text-[var(--text-secondary)] mb-3">
- <i class="fas fa-tags mr-1 text-[var(--text-muted)]"></i>
- <span v-text="t('tagsModal.currentTags')"></span>
- </label>
- <div v-if="getRecordingTags(editingRecording).length > 0" class="p-2 bg-[var(--bg-primary)] rounded-md border border-[var(--border-secondary)] max-h-20 overflow-y-auto">
- <div class="flex flex-wrap gap-1">
- <span v-for="tag in getRecordingTags(editingRecording)" :key="tag.id"
- class="group inline-flex items-center px-1.5 py-0.5 rounded-full text-[11px] font-medium text-white transition-all"
- :style="{ backgroundColor: tag.color }">
- <span v-text="tag.name"></span>
- <button @click="removeTagFromRecording(tag.id)"
- class="ml-1 opacity-70 hover:opacity-100 transition-opacity">
- <i class="fas fa-times" style="font-size: 9px;"></i>
- </button>
- </span>
- </div>
- </div>
- <div v-else class="p-4 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-secondary)]">
- <p class="text-sm text-[var(--text-muted)] text-center">
- <i class="fas fa-inbox mr-1"></i>
- <span v-text="t('tagsModal.noTagsAssigned')"></span>
- </p>
- </div>
- </div>
-
- <!-- Add Tags Section -->
- <div>
- <label class="block text-sm font-medium text-[var(--text-secondary)] mb-3">
- <i class="fas fa-plus-circle mr-1 text-[var(--text-muted)]"></i>
- <span v-text="t('tagsModal.addTags')"></span>
- </label>
-
- <!-- Search Filter (always visible if tags available) -->
- <div v-if="getAvailableTagsForRecording(editingRecording).length > 0" class="mb-2">
- <div class="relative">
- <input v-model="tagSearchFilter"
- type="text"
- :placeholder="t('tagsModal.searchTags')"
- class="w-full px-2 py-1 pl-6 text-xs bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">
- <i class="fas fa-search absolute left-2 top-1/2 transform -translate-y-1/2 text-[var(--text-muted)]" style="font-size: 9px;"></i>
- <button v-if="tagSearchFilter"
- @click="tagSearchFilter = ''"
- class="absolute right-2 top-1/2 transform -translate-y-1/2 text-[var(--text-muted)] hover:text-[var(--text-primary)]">
- <i class="fas fa-times" style="font-size: 9px;"></i>
- </button>
- </div>
- </div>
-
- <!-- Available Tags Grid - Fixed Height -->
- <div v-if="filteredAvailableTagsForModal.length > 0"
- class="border border-[var(--border-secondary)] rounded-md p-1.5 bg-[var(--bg-primary)]"
- style="max-height: 150px; overflow-y: auto;">
- <div class="grid grid-cols-2 gap-1">
- <button v-for="tag in filteredAvailableTagsForModal"
- :key="tag.id"
- @click="addTagToRecording(tag.id)"
- class="group flex items-center justify-between px-1.5 py-1 rounded border border-[var(--border-secondary)] hover:border-[var(--border-focus)] bg-[var(--bg-secondary)] hover:bg-[var(--bg-tertiary)] transition-all">
- <div class="flex items-center gap-1 min-w-0">
- <span class="w-2 h-2 rounded-full flex-shrink-0"
- :style="{ backgroundColor: tag.color || '#6B7280' }"></span>
- <span class="text-[11px] text-[var(--text-primary)] truncate" v-text="tag.name"></span>
- </div>
- <i class="fas fa-plus text-[var(--text-muted)] group-hover:text-[var(--text-accent)] transition-colors" style="font-size: 9px;"></i>
- </button>
- </div>
- </div>
- <div v-else-if="getAvailableTagsForRecording(editingRecording).length > 0"
- class="p-4 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-secondary)]">
- <p class="text-sm text-[var(--text-muted)] text-center">
- <i class="fas fa-search mr-1"></i>
- No tags match your filter
- </p>
- </div>
- <div v-else class="p-4 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-secondary)]">
- <p class="text-sm text-[var(--text-muted)] text-center">
- <i class="fas fa-check-circle mr-1"></i>
- All available tags have been added
- </p>
- </div>
- </div>
- </div>
- <div class="flex-shrink-0 px-6 py-4 bg-[var(--bg-tertiary)] border-t border-[var(--border-primary)] flex justify-end gap-3 rounded-b-lg">
- <button @click="closeEditTagsModal"
- class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-primary)] rounded-md hover:bg-[var(--bg-button-hover)] transition-colors">
- <span v-text="t('tagsModal.done')"></span>
- </button>
- </div>
- </div>
- </div>
-
- <!-- Color Scheme Modal -->
- <div v-if="showColorSchemeModal" class="color-scheme-modal" @click.self="closeColorSchemeModal">
- <div class="color-scheme-modal-content">
- <div class="color-scheme-header">
- <h2 class="color-scheme-title">
- <i class="fas fa-palette"></i>
- Choose Color Scheme
- </h2>
- <p class="color-scheme-subtitle" v-text="t('colorScheme.subtitle')"></p>
- </div>
-
- <div class="color-scheme-body">
- <div class="color-scheme-section">
- <h3 class="color-scheme-section-title">
- <i :class="isDarkMode ? 'fas fa-moon' : 'fas fa-sun'"></i>
- ${isDarkMode ? 'Dark' : 'Light'} Themes
- </h3>
- <div class="color-scheme-grid">
- <div v-for="scheme in colorSchemes[isDarkMode ? 'dark' : 'light']"
- :key="scheme.id"
- @click="selectColorScheme(scheme.id)"
- :class="['color-scheme-option', currentColorScheme === scheme.id ? 'active' : '']">
- <div class="color-scheme-preview">
- <div :class="`preview-${isDarkMode ? 'dark-' : ''}${scheme.id}-primary color-scheme-preview-segment`"></div>
- <div :class="`preview-${isDarkMode ? 'dark-' : ''}${scheme.id}-secondary color-scheme-preview-segment`"></div>
- <div :class="`preview-${isDarkMode ? 'dark-' : ''}${scheme.id}-tertiary color-scheme-preview-segment`"></div>
- </div>
- <div class="color-scheme-name">${scheme.name}</div>
- <div class="color-scheme-description">${scheme.description}</div>
- <div v-if="currentColorScheme === scheme.id" class="color-scheme-check">
- <i class="fas fa-check"></i>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <div class="color-scheme-footer">
- <button @click="resetColorScheme" class="color-scheme-reset-btn">
- <i class="fas fa-undo mr-2"></i>Reset to Default
- </button>
- <button @click="closeColorSchemeModal" class="color-scheme-close-btn">
- Close
- </button>
- </div>
- </div>
- </div>
-
- <!-- Reprocess Confirmation Modal -->
- <div v-if="showReprocessModal" @click="cancelReprocess" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm transition-all duration-300 ease-in-out">
- <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-md transform transition-all duration-300 ease-in-out">
- <!-- Header with gradient background -->
- <div class="bg-gradient-to-r from-[var(--bg-accent)] to-[var(--bg-secondary)] p-5 rounded-t-xl flex items-center">
- <div class="flex items-center">
- <div class="w-12 h-12 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center mr-4 shadow-lg">
- <i class="fas fa-sync-alt text-white text-lg"></i>
- </div>
- <div>
- <h3 class="text-xl font-bold text-[var(--text-primary)] mb-1" v-text="t('help.confirmReprocessingTitle')"></h3>
- <p class="text-sm text-[var(--text-muted)] capitalize">${ reprocessType } reprocessing</p>
- </div>
- </div>
- </div>
-
- <!-- Content -->
- <div class="p-6 modal-content">
- <div v-if="reprocessRecording" class="mb-6">
- <div class="bg-[var(--bg-tertiary)] rounded-lg p-4 border border-[var(--border-primary)]">
- <div class="flex items-start space-x-3">
- <i class="fas fa-file-audio text-[var(--text-accent)] mt-1"></i>
- <div class="flex-1 min-w-0">
- <h4 class="font-medium text-[var(--text-primary)] truncate" :title="reprocessRecording.title">
- ${ reprocessRecording.title || 'Untitled Recording' }
- </h4>
- <p class="text-sm text-[var(--text-muted)] mt-1">
- Created: ${ new Date(reprocessRecording.created_at).toLocaleDateString() }
- </p>
- </div>
- </div>
- </div>
- </div>
-
- <div class="space-y-4">
- <div class="flex items-start space-x-3">
- <div class="w-6 h-6 bg-amber-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
- <i class="fas fa-exclamation-triangle text-amber-600 text-xs"></i>
- </div>
- <div>
- <p class="text-[var(--text-secondary)] font-medium mb-1" v-text="t('help.whatWillHappen')"></p>
- <p class="text-sm text-[var(--text-muted)]" v-if="reprocessType === 'transcription' && !useAsrEndpoint">
- <span v-text="t('reprocessModal.audioReTranscribedFromScratch')"></span>
- </p>
- <p class="text-sm text-[var(--text-muted)]" v-else-if="reprocessType === 'transcription' && useAsrEndpoint">
- <span v-text="t('reprocessModal.audioReTranscribedWithAsr')"></span>
- </p>
- <p class="text-sm text-[var(--text-muted)]" v-else-if="reprocessType === 'summary'">
- <span v-text="t('reprocessModal.newTitleAndSummary')"></span>
- </p>
- </div>
- </div>
-
- <!-- ASR Options -->
- <div v-if="reprocessType === 'transcription' && useAsrEndpoint" class="space-y-4 pt-4 border-t border-[var(--border-primary)]">
- <h4 class="text-md font-semibold text-[var(--text-secondary)]" v-text="t('help.advancedAsrOptions')"></h4>
- <div>
- <label for="asr-language-reprocess" class="block text-sm font-medium text-[var(--text-muted)]" v-text="t('form.language')"></label>
- <input type="text" id="asr-language-reprocess" v-model="asrReprocessOptions.language" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" placeholder="e.g., en, es, zh (optional)">
- </div>
- <div>
- <label for="asr-min-speakers-reprocess" class="block text-sm font-medium text-[var(--text-muted)]" v-text="t('form.minSpeakers')"></label>
- <input type="number" id="asr-min-speakers-reprocess" v-model.number="asrReprocessOptions.min_speakers" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" :placeholder="t('form.optional')">
- </div>
- <div>
- <label for="asr-max-speakers-reprocess" class="block text-sm font-medium text-[var(--text-muted)]" v-text="t('form.maxSpeakers')"></label>
- <input type="number" id="asr-max-speakers-reprocess" v-model.number="asrReprocessOptions.max_speakers" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" :placeholder="t('form.optional')">
- </div>
- </div>
-
- <!-- Custom Prompt Options for Summary Reprocessing -->
- <div v-if="reprocessType === 'summary'" class="space-y-4 pt-4 border-t border-[var(--border-primary)]">
- <h4 class="text-md font-semibold text-[var(--text-secondary)]">Custom Summarization Prompt</h4>
-
- <!-- Prompt Source Selection -->
- <div>
- <label class="block text-sm font-medium text-[var(--text-muted)] mb-2">Prompt Source</label>
- <div class="space-y-2">
- <label class="flex items-center space-x-2 cursor-pointer">
- <input type="radio" v-model="summaryReprocessPromptSource" value="default" class="text-[var(--text-accent)]" name="promptSource">
- <span class="text-sm text-[var(--text-secondary)]">Use default prompt</span>
- </label>
- <label class="flex items-center space-x-2 cursor-pointer" v-if="tagsWithCustomPrompts.length > 0">
- <input type="radio" v-model="summaryReprocessPromptSource" value="tag" class="text-[var(--text-accent)]" name="promptSource">
- <span class="text-sm text-[var(--text-secondary)]">Use prompt from tag</span>
- </label>
- <label class="flex items-center space-x-2 cursor-pointer">
- <input type="radio" v-model="summaryReprocessPromptSource" value="custom" class="text-[var(--text-accent)]" name="promptSource">
- <span class="text-sm text-[var(--text-secondary)]">Enter custom prompt</span>
- </label>
- </div>
- </div>
-
- <!-- Tag Selection (shown when 'tag' is selected) -->
- <div v-if="summaryReprocessPromptSource === 'tag' && tagsWithCustomPrompts.length > 0">
- <label for="reprocess-tag-select" class="block text-sm font-medium text-[var(--text-muted)] mb-2">Select Tag</label>
- <select id="reprocess-tag-select" v-model="summaryReprocessSelectedTagId" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] text-sm bg-[var(--bg-input)] text-[var(--text-primary)]">
- <option value="">Select a tag...</option>
- <option v-for="tag in tagsWithCustomPrompts" :key="tag.id" :value="tag.id">${ tag.name }</option>
- </select>
- <div v-if="summaryReprocessSelectedTagId" class="mt-2 p-2 bg-[var(--bg-tertiary)] rounded text-xs text-[var(--text-muted)] max-h-20 overflow-y-auto">
- <strong>Preview:</strong> ${ getTagPromptPreview(summaryReprocessSelectedTagId) }
- </div>
- </div>
-
- <!-- Custom Prompt Textarea (shown when 'custom' is selected) -->
- <div v-if="summaryReprocessPromptSource === 'custom'">
- <label for="reprocess-custom-prompt" class="block text-sm font-medium text-[var(--text-muted)] mb-2">Custom Prompt</label>
- <textarea id="reprocess-custom-prompt" v-model="summaryReprocessCustomPrompt" rows="4" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" placeholder="Enter your custom summarization instructions..."></textarea>
- </div>
-
- <!-- Info message when no tags with custom prompts exist -->
- <div v-if="summaryReprocessPromptSource === 'tag' && tagsWithCustomPrompts.length === 0" class="text-xs text-[var(--text-muted)] italic">
- No tags with custom prompts available. Create tags with custom prompts in the Account Settings.
- </div>
- </div>
-
- <div class="flex items-start space-x-3">
- <div class="w-6 h-6 bg-blue-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
- <i class="fas fa-clock text-blue-600 text-xs"></i>
- </div>
- <div>
- <p class="text-[var(--text-secondary)] font-medium mb-1" v-text="t('help.processingTime')"></p>
- <p class="text-sm text-[var(--text-muted)]">
- <span v-text="t('help.processingTimeDescription')"></span>
- </p>
- </div>
- </div>
-
- <div class="flex items-start space-x-3" v-if="reprocessType === 'transcription'">
- <div class="w-6 h-6 bg-red-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
- <i class="fas fa-info-circle text-red-600 text-xs"></i>
- </div>
- <div>
- <p class="text-[var(--text-secondary)] font-medium mb-1" v-text="t('help.importantNote')"></p>
- <p class="text-sm text-[var(--text-muted)]">
- <span v-text="t('reprocessModal.manualEditsOverwritten')"></span>
- </p>
- </div>
- </div>
-
- <div class="flex items-start space-x-3" v-else-if="reprocessType === 'summary'">
- <div class="w-6 h-6 bg-red-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
- <i class="fas fa-info-circle text-red-600 text-xs"></i>
- </div>
- <div>
- <p class="text-[var(--text-secondary)] font-medium mb-1" v-text="t('help.importantNote')"></p>
- <p class="text-sm text-[var(--text-muted)]">
- <span v-text="t('reprocessModal.manualEditsOverwrittenSummary')"></span>
- </p>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Footer with action buttons -->
- <div class="bg-[var(--bg-tertiary)] px-6 py-4 rounded-b-xl flex justify-end space-x-3 border-t border-[var(--border-primary)]">
- <button
- @click="cancelReprocess"
- class="px-5 py-2.5 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] transition-all duration-200 flex items-center shadow-sm font-medium">
- <i class="fas fa-times mr-2"></i>
- Cancel
- </button>
- <button
- @click="executeReprocess"
- class="px-5 py-2.5 bg-gradient-to-r from-blue-500 to-purple-600 text-white rounded-lg hover:from-blue-600 hover:to-purple-700 transition-all duration-200 flex items-center shadow-lg font-medium transform hover:scale-105">
- <i class="fas fa-sync-alt mr-2"></i>
- Start Reprocessing
- </button>
- </div>
- </div>
- </div>
- <!-- Reset Status Confirmation Modal -->
- <div v-if="showResetModal" @click="cancelReset" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
- <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-md">
- <div class="p-6 text-center">
- <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-orange-100 dark:bg-orange-800 mb-4">
- <i class="fas fa-exclamation-triangle text-2xl text-orange-500 dark:text-orange-300"></i>
- </div>
- <h3 class="text-lg font-semibold text-[var(--text-primary)] mb-2" v-text="t('modal.resetStatus')"></h3>
- <p class="text-sm text-[var(--text-muted)] mb-6">
- This will mark the recording as 'Failed'. This is useful if processing is stuck. You will be able to reprocess it afterwards.
- </p>
- </div>
- <div class="bg-[var(--bg-tertiary)] px-6 py-4 rounded-b-xl flex justify-end space-x-3">
- <button @click="cancelReset" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)]">
- Cancel
- </button>
- <button @click="executeReset" class="px-4 py-2 bg-orange-500 text-white rounded-lg hover:bg-orange-600">
- Yes, Reset Status
- </button>
- </div>
- </div>
- </div>
- <!-- Simple Transcription Editor Modal -->
- <div v-if="showTextEditorModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
- <div class="bg-[var(--bg-secondary)] rounded-lg shadow-xl w-full max-w-2xl max-h-[90vh] flex flex-col">
- <div class="p-6 border-b border-[var(--border-primary)]">
- <h3 class="text-lg font-semibold" v-text="t('modal.editTranscription')"></h3>
- </div>
- <div class="p-6 space-y-4 overflow-y-auto flex-1">
- <div>
- <label class="block text-sm font-medium mb-2" v-text="t('transcription.title')"></label>
- <textarea v-model="editingTranscriptionContent"
- rows="15"
- class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)] font-mono text-sm">
- </textarea>
- </div>
- </div>
- <div class="p-6 border-t border-[var(--border-primary)] flex justify-end gap-3">
- <button @click="closeTextEditorModal"
- class="px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] rounded-lg transition-colors">
- Cancel
- </button>
- <button @click="saveTranscription"
- class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors">
- Save Changes
- </button>
- </div>
- </div>
- </div>
-
- <!-- ASR Transcription Editor Modal -->
- <div v-if="showAsrEditorModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
- <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-6xl flex flex-col max-h-[90vh]">
- <div class="p-5 border-b border-[var(--border-primary)] flex-shrink-0 flex justify-between items-center">
- <h3 class="text-xl font-bold text-[var(--text-primary)]" v-text="t('modal.editAsrTranscription')"></h3>
- <button @click="closeAsrEditorModal" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors">
- <i class="fas fa-times"></i>
- </button>
- </div>
- <div class="flex-grow overflow-y-auto custom-scrollbar p-6">
- <table class="min-w-full asr-editor-table">
- <thead>
- <tr>
- <th class="w-1/4" v-text="t('help.speakerCount')"></th>
- <th class="w-24" v-text="t('help.startTime')"></th>
- <th class="w-24" v-text="t('help.endTime')"></th>
- <th v-text="t('help.sentence')"></th>
- <th class="w-12"><span class="sr-only" v-text="t('help.actions')"></span></th>
- </tr>
- </thead>
- <tbody>
- <tr v-for="(segment, index) in editingSegments" :key="segment.id || index">
- <td>
- <div class="speaker-combobox" @mouseleave="closeSpeakerSuggestions(index)">
- <input type="text" v-model="segment.speaker" @input="filterSpeakers(index)" @focus="openSpeakerSuggestions(index)" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)] speaker-combobox-input" />
- <div class="speaker-combobox-arrow">
- <i class="fas fa-chevron-down text-xs"></i>
- </div>
- <div v-if="segment.showSuggestions" class="speaker-combobox-suggestions">
- <div v-for="speaker in segment.filteredSpeakers" @mousedown="selectSpeaker(index, speaker)" class="speaker-suggestion-item">${speaker}</div>
- </div>
- </div>
- </td>
- <td>
- <div class="custom-number-input">
- <input type="number" step="0.01" v-model.number="segment.start_time" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" />
- <div class="number-spinners">
- <button @click="adjustTime(index, 'start_time', 0.1)"><svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6"><path stroke-linecap="round" stroke-linejoin="round" d="M4.5 15.75l7.5-7.5 7.5 7.5" /></svg></button>
- <button @click="adjustTime(index, 'start_time', -0.1)"><svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6"><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" /></svg></button>
- </div>
- </div>
- </td>
- <td>
- <div class="custom-number-input">
- <input type="number" step="0.01" v-model.number="segment.end_time" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" />
- <div class="number-spinners">
- <button @click="adjustTime(index, 'end_time', 0.1)"><svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6"><path stroke-linecap="round" stroke-linejoin="round" d="M4.5 15.75l7.5-7.5 7.5 7.5" /></svg></button>
- <button @click="adjustTime(index, 'end_time', -0.1)"><svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6"><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" /></svg></button>
- </div>
- </div>
- </td>
- <td>
- <textarea v-model="segment.sentence" rows="1" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)] resize-y"></textarea>
- </td>
- <td class="text-center">
- <button @click="removeSegment(index)" class="text-red-500 hover:text-red-700">
- <i class="fas fa-trash"></i>
- </button>
- </td>
- </tr>
- </tbody>
- </table>
- <div class="mt-4">
- <button @click="addSegment" class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 flex items-center">
- <i class="fas fa-plus mr-2"></i> Add Segment
- </button>
- </div>
- </div>
- <div class="bg-[var(--bg-tertiary)] px-6 py-4 flex justify-end space-x-3 border-t border-[var(--border-primary)] flex-shrink-0 rounded-b-xl">
- <button @click="closeAsrEditorModal" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)]" v-text="t('common.cancel')"></button>
- <button @click="saveAsrTranscription" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700" v-text="t('buttons.saveChanges')"></button>
- </div>
- </div>
- </div>
-
- <!-- Speaker Identification Modal -->
- <div v-if="showSpeakerModal" @click="closeSpeakerModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
- <div @click.stop @click="closeSpeakerSuggestionsOnClick" class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-4xl flex flex-col h-[85vh]">
- <div class="p-5 border-b border-[var(--border-primary)] flex-shrink-0">
- <h3 class="text-xl font-bold text-[var(--text-primary)]" v-text="t('modal.identifySpeakers')"></h3>
- <!-- Warning for too many speakers -->
- <div v-if="modalSpeakers.length > 8" class="mt-3 p-3 bg-[var(--bg-warn-light)] border border-amber-300 dark:border-amber-800 rounded-lg">
- <div class="flex items-start">
- <i class="fas fa-exclamation-triangle text-[var(--text-warn-strong)] mt-0.5 mr-2"></i>
- <div class="text-sm">
- <p class="font-medium text-[var(--text-warn-strong)]" v-text="t('help.moreSpeakersThanColors')"></p>
- <p class="text-[var(--text-warn-strong)] mt-1" v-text="t('help.youHaveXSpeakers', { count: modalSpeakers.length })">
- </p>
- </div>
- </div>
- </div>
- </div>
- <div class="flex-grow flex overflow-hidden modal-content">
- <div class="w-1/3 p-6 space-y-4 overflow-y-auto custom-scrollbar border-r border-[var(--border-primary)]">
- <div v-for="(speaker, index) in modalSpeakers" :key="`${selectedRecording.id}-speaker-${index}-${speaker}`" class="space-y-3">
- <!-- Speaker label with color indicator and "This is Me" checkbox on same line -->
- <div class="flex items-center justify-between">
- <div class="flex items-center space-x-2">
- <div :class="speakerMap[speaker].color" class="w-4 h-4 rounded-full border border-white/30 shadow-sm flex-shrink-0"></div>
- <span class="font-mono text-sm text-[var(--text-muted)]">${ speakerDisplayMap[speaker] || speaker }</span>
- <span v-if="index >= 8" class="text-xs text-[var(--text-warn-strong)] bg-[var(--bg-warn-light)] px-2 py-0.5 rounded-full" title="Color repeats from speaker ${ ((index % 8) + 1) }">
- Repeat
- </span>
- </div>
- <label class="flex items-center text-sm text-[var(--text-muted)] cursor-pointer hover:text-[var(--text-primary)] transition-colors">
- <input type="checkbox"
- v-model="speakerMap[speaker].isMe"
- @focus="highlightSpeakerInTranscript(speaker)"
- @blur="clearSpeakerHighlight"
- class="speaker-checkbox">
- <span class="ml-2 select-none" v-text="t('help.me')"></span>
- </label>
- </div>
-
- <!-- Autocomplete input field - disabled when "This is Me" is checked -->
- <div class="relative">
- <input
- type="text"
- v-model="speakerMap[speaker].name"
- @input="searchSpeakers($event.target.value, speaker)"
- @focus="focusSpeaker(speaker)"
- @blur="blurSpeaker()"
- :disabled="speakerMap[speaker].isMe"
- class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)] disabled:bg-[var(--bg-tertiary)] disabled:text-[var(--text-muted)] disabled:cursor-not-allowed"
- :placeholder="speakerMap[speaker].isMe ? t('help.me') : t('help.enterNameFor') + ' ' + (speakerDisplayMap[speaker] || speaker)"
- autocomplete="off">
-
- <!-- Loading indicator -->
- <div v-if="loadingSuggestions[speaker] && !speakerMap[speaker].isMe" class="absolute right-3 top-1/2 transform -translate-y-1/2">
- <i class="fas fa-spinner fa-spin text-[var(--text-muted)] text-sm"></i>
- </div>
-
- <!-- Suggestions dropdown - Only show when this input is active -->
- <div v-if="activeSpeakerInput === speaker && speakerSuggestions[speaker] && speakerSuggestions[speaker].length > 0 && !speakerMap[speaker].isMe"
- @click.stop
- class="absolute z-10 w-full mt-1 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-md shadow-lg max-h-48 overflow-y-auto">
- <div class="py-1">
- <div v-for="suggestion in speakerSuggestions[speaker]"
- :key="suggestion.id"
- @click="selectSpeakerSuggestion(speaker, suggestion)"
- class="px-3 py-2 cursor-pointer hover:bg-[var(--bg-tertiary)] flex items-center justify-between">
- <div class="flex-grow">
- <div class="text-sm font-medium text-[var(--text-primary)]">${ suggestion.name }</div>
- <div class="text-xs text-[var(--text-muted)]">
- Used ${ suggestion.use_count } time${ suggestion.use_count !== 1 ? 's' : '' }
- <span v-if="suggestion.last_used">
- • Last: ${ new Date(suggestion.last_used).toLocaleDateString() }
- </span>
- </div>
- </div>
- <i class="fas fa-user text-[var(--text-muted)] ml-2"></i>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Add Speaker Button -->
- <div class="pt-4 border-t border-[var(--border-primary)]">
- <button @click="openAddSpeakerModal" class="w-full px-4 py-2 bg-[var(--bg-accent)] text-[var(--text-accent)] rounded-lg hover:bg-[var(--bg-accent-hover)] transition-colors flex items-center justify-center">
- <i class="fas fa-plus mr-2"></i>
- Add Speaker
- </button>
- </div>
- </div>
- <div class="w-2/3 p-6 flex flex-col overflow-hidden">
- <!-- Audio Player Section -->
- <div class="mb-4 flex-shrink-0">
- <h4 class="font-semibold text-[var(--text-secondary)] mb-2" v-text="t('help.audioPlayer')"></h4>
- <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>
- </div>
-
- <!-- Transcript Section -->
- <div class="flex-grow overflow-y-auto custom-scrollbar speaker-modal-transcript" @click="seekAudioFromEvent">
- <div v-if="processedTranscription.isJson">
- <div v-for="(segment, index) in processedTranscription.simpleSegments" :key="index" class="speaker-segment mb-2 group relative" :data-start-time="segment.startTime">
- <p class="flex items-start">
- <span :class="[segment.color, 'speaker-tag', { 'speaker-highlight': highlightedSpeaker === segment.speakerId }]" :data-speaker-id="segment.speakerId">[${ segment.speaker }]</span>:
- <span class="word cursor-pointer hover:bg-[var(--bg-accent)] hover:text-[var(--text-accent)] rounded px-0.5 flex-1">${ segment.sentence }</span>
-
- <!-- Edit buttons (shown on hover) -->
- <span class="ml-2 opacity-0 group-hover:opacity-100 transition-opacity flex items-center space-x-1 flex-shrink-0">
- <!-- Change Speaker Button -->
- <button @click.stop="openSpeakerChangeDropdown(index)" class="p-1 rounded bg-[var(--bg-tertiary)] hover:bg-[var(--bg-accent)] text-[var(--text-muted)] hover:text-[var(--text-accent)] transition-colors" title="Change speaker">
- <i class="fas fa-user-edit text-xs"></i>
- </button>
- <!-- Edit Text Button -->
- <button @click.stop="openEditTextModal(index)" class="p-1 rounded bg-[var(--bg-tertiary)] hover:bg-[var(--bg-accent)] text-[var(--text-muted)] hover:text-[var(--text-accent)] transition-colors" title="Edit text">
- <i class="fas fa-edit text-xs"></i>
- </button>
- </span>
- </p>
-
- <!-- Speaker Change Dropdown -->
- <div v-if="editingSpeakerIndex === index" @click.stop class="mt-2 p-2 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-primary)] shadow-lg">
- <p class="text-xs text-[var(--text-muted)] mb-2">Select new speaker:</p>
- <div class="space-y-1 max-h-48 overflow-y-auto custom-scrollbar">
- <button v-for="speaker in modalSpeakers" :key="speaker" @click="changeSpeaker(index, speaker)" class="w-full text-left px-3 py-2 rounded hover:bg-[var(--bg-accent)] hover:text-[var(--text-accent)] transition-colors flex items-center space-x-2">
- <div :class="speakerMap[speaker].color" class="w-3 h-3 rounded-full flex-shrink-0"></div>
- <span class="text-sm">${ speakerMap[speaker].name || speaker }</span>
- </button>
- </div>
- </div>
- </div>
- </div>
- <div v-else v-html="highlightedTranscript"></div>
- </div>
-
- <!-- Speaker Navigation Controls (at bottom) - Always visible for consistent height -->
- <div class="mt-3 p-3 bg-[var(--bg-tertiary)] rounded-lg flex items-center justify-between flex-shrink-0" :class="{'opacity-50': !highlightedSpeaker || speakerGroups.length <= 1}">
- <div class="flex items-center space-x-2">
- <span class="text-sm text-[var(--text-muted)]">
- Navigate <span class="font-semibold">${ speakerDisplayMap[highlightedSpeaker] || highlightedSpeaker }</span> groups:
- </span>
- <span class="text-xs text-[var(--text-muted)]">
- (${ currentSpeakerGroupIndex + 1 } of ${ speakerGroups.length })
- </span>
- </div>
- <div class="flex items-center space-x-2">
- <button @mousedown.prevent @click="navigateToPrevSpeakerGroup"
- class="px-3 py-1.5 bg-[var(--bg-secondary)] hover:bg-[var(--bg-primary)] text-[var(--text-secondary)] rounded-md border border-[var(--border-secondary)] transition-all flex items-center text-sm disabled:opacity-50 disabled:cursor-not-allowed"
- :disabled="!highlightedSpeaker || speakerGroups.length <= 1">
- <i class="fas fa-chevron-up mr-1.5"></i>
- Previous
- </button>
- <button @mousedown.prevent @click="navigateToNextSpeakerGroup"
- class="px-3 py-1.5 bg-[var(--bg-secondary)] hover:bg-[var(--bg-primary)] text-[var(--text-secondary)] rounded-md border border-[var(--border-secondary)] transition-all flex items-center text-sm disabled:opacity-50 disabled:cursor-not-allowed"
- :disabled="!highlightedSpeaker || speakerGroups.length <= 1">
- Next
- <i class="fas fa-chevron-down ml-1.5"></i>
- </button>
- </div>
- </div>
- </div>
- </div>
- <div class="p-4 bg-[var(--bg-tertiary)] border-t border-[var(--border-primary)] flex-shrink-0">
- <label class="flex items-center text-sm text-[var(--text-muted)] cursor-pointer hover:text-[var(--text-primary)] transition-colors">
- <input type="checkbox"
- v-model="regenerateSummaryAfterSpeakerUpdate"
- class="speaker-checkbox">
- <span class="ml-2 select-none" v-text="t('help.regenerateSummaryAfterNames')"></span>
- </label>
- </div>
- <div class="bg-[var(--bg-tertiary)] px-6 py-4 flex justify-between items-center border-t border-[var(--border-primary)] flex-shrink-0 rounded-b-xl">
- <div>
- <button @click="autoIdentifySpeakers" class="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 flex items-center" :disabled="isAutoIdentifying">
- <i class="fas fa-magic mr-2"></i>
- <span v-if="!isAutoIdentifying" v-text="t('help.autoIdentify')"></span>
- <span v-else>
- <i class="fas fa-spinner fa-spin mr-2"></i>
- Identifying...
- </span>
- </button>
- </div>
- <div class="flex space-x-3">
- <button @click="closeSpeakerModal" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)]" v-text="t('common.cancel')"></button>
- <button
- @click="saveSpeakerNames"
- :disabled="!hasSpeakerNames"
- :class="hasSpeakerNames
- ? 'px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 cursor-pointer'
- : 'px-4 py-2 bg-gray-400 text-gray-200 rounded-lg cursor-not-allowed'"
- >
- Save Names
- </button>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Add Speaker Modal -->
- <div v-if="showAddSpeakerModal" @click="closeAddSpeakerModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
- <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-md p-6">
- <h3 class="text-xl font-bold text-[var(--text-primary)] mb-4">Add New Speaker</h3>
-
- <!-- "This is Me" checkbox -->
- <div class="mb-4">
- <label class="flex items-center text-sm text-[var(--text-muted)] cursor-pointer hover:text-[var(--text-primary)] transition-colors">
- <input type="checkbox" v-model="newSpeakerIsMe" class="speaker-checkbox">
- <span class="ml-2 select-none">This is Me</span>
- </label>
- </div>
-
- <!-- Speaker name input (disabled if "This is Me" is checked) -->
- <div class="mb-6">
- <label class="block text-sm font-medium text-[var(--text-secondary)] mb-2">
- Speaker Name
- </label>
- <input
- type="text"
- v-model="newSpeakerName"
- :disabled="newSpeakerIsMe"
- :placeholder="newSpeakerIsMe ? 'Me' : 'Enter speaker name...'"
- class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)] disabled:bg-[var(--bg-tertiary)] disabled:text-[var(--text-muted)] disabled:cursor-not-allowed"
- @keyup.enter="addNewSpeaker"
- >
- </div>
-
- <!-- Action buttons -->
- <div class="flex justify-end space-x-3">
- <button @click="closeAddSpeakerModal" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] transition-colors">
- Cancel
- </button>
- <button @click="addNewSpeaker" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
- Add Speaker
- </button>
- </div>
- </div>
- </div>
-
- <!-- Edit Text Modal -->
- <div v-if="showEditTextModal" @click="closeEditTextModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
- <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-2xl p-6">
- <h3 class="text-xl font-bold text-[var(--text-primary)] mb-4">Edit Transcript Text</h3>
-
- <!-- Text editor -->
- <div class="mb-6">
- <label class="block text-sm font-medium text-[var(--text-secondary)] mb-2">
- Text Content
- </label>
- <textarea
- v-model="editedText"
- rows="6"
- class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)] resize-y"
- placeholder="Enter transcript text..."
- ></textarea>
- </div>
-
- <!-- Action buttons -->
- <div class="flex justify-end space-x-3">
- <button @click="closeEditTextModal" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] transition-colors">
- Cancel
- </button>
- <button @click="saveEditedText" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
- Save Changes
- </button>
- </div>
- </div>
- </div>
-
- <!-- Global Error Display -->
- <div v-if="globalError"
- class="fixed top-4 right-4 bg-[var(--bg-danger)] text-white p-4 rounded-lg shadow-lg z-50 max-w-md">
- <div class="flex items-start gap-3">
- <i class="fas fa-exclamation-circle text-lg flex-shrink-0 mt-0.5"></i>
- <div class="flex-1">
- <p class="font-medium" v-text="t('common.error')"></p>
- <p class="text-sm opacity-90">${globalError}</p>
- </div>
- <button @click="globalError = null"
- class="text-white hover:text-gray-200 transition-colors">
- <i class="fas fa-times"></i>
- </button>
- </div>
- </div>
-
- <!-- System Audio Help Modal -->
- <div v-if="showSystemAudioHelp" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 backdrop-blur-sm">
- <div class="bg-[var(--bg-secondary)] w-full h-full md:h-auto md:max-h-[90vh] md:w-full md:max-w-2xl md:rounded-lg md:shadow-xl flex flex-col">
- <div class="p-4 border-b border-[var(--border-primary)] flex-shrink-0">
- <div class="flex items-center justify-between">
- <h3 class="text-lg font-semibold flex items-center">
- <i class="fas fa-desktop mr-2 text-blue-500"></i>
- System Audio Recording
- </h3>
- <button @click="showSystemAudioHelp = false" class="text-[var(--text-muted)] hover:text-[var(--text-primary)]">
- <i class="fas fa-times"></i>
- </button>
- </div>
- </div>
- <div class="p-6 space-y-6 overflow-y-auto flex-grow">
- <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)]">
- <h4 class="font-medium text-[var(--text-primary)] mb-2" v-text="t('help.howToRecordSystemAudio')"></h4>
- <p class="text-sm text-[var(--text-muted)]" v-text="t('help.toCaptureAudioFromMeetings')">
- </p>
- <ol class="list-decimal list-inside space-y-2 text-sm text-[var(--text-secondary)] mt-3">
- <li v-text="t('help.recordSystemSteps1')"></li>
- <li><span v-text="t('help.recordSystemSteps2')"></span> <strong>"${ t('help.entireScreen') }"</strong> or a <strong v-text="t('help.specificBrowserTab')"></strong>.</li>
- <li><span v-text="t('help.recordSystemSteps3')"></span> <strong>"${ t('help.shareTabAudio') }"</strong> or <strong>"${ t('help.shareSystemAudio') }"</strong>.</li>
- </ol>
- <p class="text-xs text-amber-600 dark:text-amber-400 mt-3"><i class="fas fa-exclamation-triangle mr-1"></i><span v-text="t('help.sharingWindowNoAudio')"></span></p>
- </div>
-
- <div class="space-y-4">
- <h4 class="font-medium text-[var(--text-primary)]" v-text="t('help.troubleshooting')"></h4>
-
- <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)]">
- <h5 class="font-medium text-[var(--text-primary)] mb-2" v-text="t('help.whyNotWorking')"></h5>
- <p class="text-sm text-[var(--text-muted)]">
- System audio recording requires a secure (HTTPS) connection. If you are developing locally, you may need to enable a browser flag.
- </p>
- </div>
-
- <!-- Chrome Solution -->
- <div v-if="browser === 'chrome'" class="bg-[var(--bg-accent)] p-4 rounded-lg border border-[var(--border-accent)]">
- <h5 class="font-medium text-[var(--text-accent)] mb-3 flex items-center">
- <i class="fab fa-chrome mr-2"></i>
- For Chrome on Localhost
- </h5>
- <ol class="list-decimal list-inside space-y-2 text-sm text-[var(--text-secondary)]">
- <li>Go to: <code class="bg-[var(--bg-secondary)] px-2 py-1 rounded text-xs ml-1">chrome://flags/#unsafely-treat-insecure-origin-as-secure</code></li>
- <li>Add your local URL (e.g., <code class="bg-[var(--bg-secondary)] px-2 py-1 rounded text-xs ml-1">http://localhost:8899</code>)</li>
- <li>Set to <strong>"Enabled"</strong> and relaunch Chrome.</li>
- </ol>
- </div>
-
- <!-- Firefox Solution -->
- <div v-else-if="browser === 'firefox'" class="bg-[var(--bg-accent)] p-4 rounded-lg border border-[var(--border-accent)]">
- <h5 class="font-medium text-[var(--text-accent)] mb-3 flex items-center">
- <i class="fab fa-firefox-browser mr-2"></i>
- For Firefox on Localhost
- </h5>
- <p class="text-sm text-[var(--text-secondary)]">
- System audio recording is not well-supported on Firefox, even with these changes. For best results, please use Chrome.
- </p>
- <ol class="list-decimal list-inside space-y-2 text-sm text-[var(--text-secondary)] mt-2">
- <li>Go to: <code class="bg-[var(--bg-secondary)] px-2 py-1 rounded text-xs ml-1">about:config</code></li>
- <li>Search for <code class="bg-[var(--bg-secondary)] px-2 py-1 rounded text-xs ml-1">media.devices.insecure.enabled</code> and set it to `true`.</li>
- <li>Restart Firefox.</li>
- </ol>
- </div>
-
- <!-- Other Browsers -->
- <div v-else class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)]">
- <h5 class="font-medium text-[var(--text-primary)] mb-2" v-text="t('help.unsupportedBrowser')"></h5>
- <p class="text-sm text-[var(--text-muted)]">
- For the best experience with system audio recording, we recommend using Google Chrome.
- </p>
- </div>
- </div>
- </div>
- <div class="p-4 border-t border-[var(--border-primary)] flex justify-end flex-shrink-0">
- <button @click="showSystemAudioHelp = false"
- class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors">
- Got it
- </button>
- </div>
- </div>
- </div>
-
- <!-- Recording Disclaimer Modal -->
- <div v-if="showRecordingDisclaimerModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
- <div class="bg-[var(--bg-secondary)] rounded-lg shadow-xl w-full max-w-2xl max-h-[80vh] flex flex-col overflow-hidden">
- <div class="flex-shrink-0 p-6 border-b border-[var(--border-primary)]">
- <div class="flex items-center gap-3">
- <i class="fas fa-info-circle text-2xl text-[var(--text-accent)]"></i>
- <h3 class="text-xl font-semibold text-[var(--text-primary)]" v-text="t('modal.recordingNotice')"></h3>
- </div>
- </div>
- <div class="flex-1 overflow-y-auto p-6">
- <!-- Render markdown content -->
- <div class="prose prose-sm max-w-none text-[var(--text-secondary)]"
- style="color: var(--text-secondary); line-height: 1.6;">
- <div v-html="recordingDisclaimer"></div>
- </div>
- </div>
- <div class="flex-shrink-0 p-6 border-t border-[var(--border-primary)] bg-[var(--bg-tertiary)] rounded-b-lg">
- <div class="flex justify-end gap-3">
- <button @click="cancelRecordingDisclaimer"
- class="px-6 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-secondary)] rounded-lg transition-colors border border-[var(--border-secondary)]">
- Cancel
- </button>
- <button @click="acceptRecordingDisclaimer"
- class="px-6 py-2 bg-[var(--bg-accent)] text-white rounded-lg hover:bg-[var(--bg-accent-hover)] transition-colors">
- <i class="fas fa-microphone mr-2"></i>
- Start Recording
- </button>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Toast Container -->
- <div id="toastContainer" class="fixed bottom-4 right-4 z-50 space-y-2"></div>
-
- <!-- Share Modal -->
- <div v-if="showShareModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
- <div class="bg-[var(--bg-secondary)] rounded-lg shadow-xl w-full max-w-lg">
- <div class="p-6 border-b border-[var(--border-primary)]">
- <h3 class="text-lg font-semibold" v-text="t('modal.shareRecording')"></h3>
- </div>
- <div class="p-6 space-y-4">
- <p class="text-sm text-[var(--text-muted)]" v-text="t('help.createPublicLink')"></p>
- <div v-if="!generatedShareLink">
- <div class="flex items-center mb-2">
- <input type="checkbox" v-model="shareOptions.share_summary" id="share_summary" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
- <label for="share_summary" class="ml-2 block text-sm text-[var(--text-secondary)]" v-text="t('form.shareSummary')"></label>
- </div>
- <div class="flex items-center">
- <input type="checkbox" v-model="shareOptions.share_notes" id="share_notes" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
- <label for="share_notes" class="ml-2 block text-sm text-[var(--text-secondary)]" v-text="t('form.shareNotes')"></label>
- </div>
- </div>
- <div v-if="generatedShareLink" class="mt-4">
- <div v-if="existingShareDetected" class="mb-3 p-3 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
- <div class="flex items-start gap-2">
- <i class="fas fa-info-circle text-blue-600 dark:text-blue-400 mt-0.5"></i>
- <div class="text-sm text-blue-800 dark:text-blue-300">
- <p class="font-medium">Using existing share link</p>
- <p class="mt-1 text-xs opacity-90">This recording was already shared. The same link has been retrieved.</p>
- </div>
- </div>
- </div>
- <label class="block text-sm font-medium mb-2" v-text="t('form.shareableLink')"></label>
- <div class="flex items-center gap-2">
- <input :value="generatedShareLink" readonly class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg">
- <button @click="copyShareLink" class="px-3 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)]">
- <i class="fas fa-copy"></i>
- </button>
- </div>
- <div v-if="existingShareDetected" class="mt-3">
- <button @click="createShare(true)" class="text-sm text-[var(--text-accent)] hover:underline">
- <i class="fas fa-plus-circle mr-1"></i>Create a new share link instead
- </button>
- </div>
- </div>
- </div>
- <div class="p-6 border-t border-[var(--border-primary)] flex justify-end gap-3">
- <button @click="closeShareModal" class="px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] rounded-lg transition-colors">
- Cancel
- </button>
- <button @click="createShare()" v-if="!generatedShareLink" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors">
- Create Link
- </button>
- </div>
- </div>
- </div>
-
- <!-- Shares List Modal -->
- <div v-if="showSharesListModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
- <div class="bg-[var(--bg-secondary)] rounded-lg shadow-xl w-full max-w-2xl max-h-[80vh] flex flex-col">
- <div class="p-6 border-b border-[var(--border-primary)] flex justify-between items-center">
- <h3 class="text-lg font-semibold" v-text="t('modal.sharedTranscripts')"></h3>
- <button @click="closeSharesList" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors">
- <i class="fas fa-times"></i>
- </button>
- </div>
- <div class="p-6 space-y-4 overflow-y-auto">
- <div v-if="isLoadingShares" class="text-center">
- <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
- </div>
- <div v-else-if="userShares.length === 0" class="text-center text-[var(--text-muted)]">
- <span v-text="t('sharedTranscripts.noSharedTranscripts')"></span>
- </div>
- <div v-else class="space-y-3">
- <div v-for="share in userShares" :key="share.id" class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)]">
- <div class="flex justify-between items-start">
- <div>
- <p class="font-semibold">${share.recording_title}</p>
- <p class="text-sm text-[var(--text-muted)]">${ t('help.sharedOn') }: ${share.created_at}</p>
- </div>
- <button @click="confirmDeleteShare(share)" class="text-red-500 hover:text-red-700 p-1"><i class="fas fa-trash"></i></button>
- </div>
- <div class="mt-4 flex items-center gap-4">
- <label class="flex items-center text-sm">
- <input type="checkbox" v-model="share.share_summary" @change="updateShare(share)" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
- <span class="ml-2" v-text="t('form.shareSummary')"></span>
- </label>
- <label class="flex items-center text-sm">
- <input type="checkbox" v-model="share.share_notes" @change="updateShare(share)" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
- <span class="ml-2" v-text="t('form.shareNotes')"></span>
- </label>
- </div>
- <div class="mt-4">
- <input :value="'{{ request.url_root }}share/' + share.public_id" readonly class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg text-sm">
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Share Delete Confirmation Modal -->
- <div v-if="showShareDeleteModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
- <div class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-md transform transition-all duration-300 ease-in-out">
- <!-- Header with gradient background -->
- <div class="bg-gradient-to-r from-red-500 to-red-600 p-5 rounded-t-xl">
- <div class="flex items-center">
- <div class="w-12 h-12 bg-white/20 backdrop-blur rounded-full flex items-center justify-center mr-4">
- <i class="fas fa-trash-alt text-white text-lg"></i>
- </div>
- <div>
- <h3 class="text-lg font-bold text-white">Delete Shared Link</h3>
- <p class="text-red-100 text-sm mt-1">This action cannot be undone</p>
- </div>
- </div>
- </div>
-
- <!-- Content -->
- <div class="p-6">
- <p class="text-[var(--text-secondary)] mb-4">
- Are you sure you want to delete the shared link for:
- </p>
- <div v-if="shareToDelete" class="bg-[var(--bg-tertiary)] p-3 rounded-lg border border-[var(--border-primary)]">
- <p class="font-medium text-[var(--text-primary)]">${shareToDelete.recording_title}</p>
- <p class="text-sm text-[var(--text-muted)] mt-1">Shared on: ${shareToDelete.created_at}</p>
- </div>
- <div class="mt-4 p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
- <div class="flex items-start">
- <i class="fas fa-exclamation-triangle text-red-600 dark:text-red-400 mt-0.5 mr-2"></i>
- <p class="text-sm text-red-800 dark:text-red-300">
- The share link will be permanently deleted and anyone with this link will no longer be able to access the recording.
- </p>
- </div>
- </div>
- </div>
-
- <!-- Actions -->
- <div class="p-6 pt-0 flex justify-end gap-3">
- <button @click="cancelDeleteShare" class="px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] rounded-lg transition-colors">
- Cancel
- </button>
- <button @click="deleteShare" class="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors flex items-center gap-2">
- <i class="fas fa-trash"></i>
- Delete Share Link
- </button>
- </div>
- </div>
- </div>
+ {% include 'modals/delete-modal.html' %}
+ {% include 'modals/edit-tags-modal.html' %}
+ {% include 'modals/shares-list-modal.html' %}
+ {% include 'modals/reset-modal.html' %}
+ {% include 'modals/reprocess-modal.html' %}
+ {% include 'modals/speaker-modal.html' %}
+ {% include 'modals/add-speaker-modal.html' %}
+ {% include 'modals/edit-text-modal.html' %}
+ {% include 'modals/text-editor-modal.html' %}
+ {% include 'modals/asr-editor-modal.html' %}
+ {% include 'modals/edit-speakers-modal.html' %}
+ {% include 'modals/edit-participants-modal.html' %}
+ {% include 'modals/color-scheme-modal.html' %}
+ {% include 'modals/system-audio-help-modal.html' %}
+ {% include 'modals/unified-share-modal.html' %}
+ {% include 'modals/share-delete-modal.html' %}
+ {% include 'modals/global-error.html' %}
+ {% include 'modals/toast-container.html' %}
</div>
<!-- CSRF Token Management -->
<script src="{{ url_for('static', filename='js/csrf-refresh.js') }}"></script>
-
+
<!-- i18n System -->
<script src="{{ url_for('static', filename='js/i18n.js') }}"></script>
-
+
<!-- Initialize i18n immediately with fallback -->
<script>
// Ensure i18n is initialized before Vue app
(async function() {
- if (window.i18n && window.i18n.init) {
- const userLang = localStorage.getItem('preferredLanguage') || '{{ user_language }}' || 'en';
- try {
- await window.i18n.init(userLang);
- console.log('i18n pre-initialized with language:', userLang);
- } catch (error) {
- console.error('Failed to initialize i18n:', error);
+ const startTime = Date.now();
+ const maxWait = 3000; // Max 3 seconds for i18n to load
+
+ try {
+ if (window.i18n && window.i18n.init) {
+ const userLang = localStorage.getItem('preferredLanguage') || '{{ user_language }}' || 'en';
+
+ // Race between i18n init and timeout
+ await Promise.race([
+ window.i18n.init(userLang),
+ new Promise((resolve) => setTimeout(resolve, maxWait))
+ ]);
+
+ const elapsed = Date.now() - startTime;
+ console.log('i18n initialized in', elapsed, 'ms');
+ } else {
+ console.warn('i18n not available, continuing without translations');
}
+ } catch (error) {
+ console.error('Failed to initialize i18n:', error);
+ // Continue anyway - app will use fallback translations
}
-
- // Hide loader after i18n is ready
+
+ // Hide initial loader after i18n attempt
const loader = document.getElementById('loader');
if (loader) {
loader.style.display = 'none';
@@ -3028,28 +143,9 @@
})();
</script>
- <!-- Service Worker Registration for PWA and Background Recording -->
- <script>
- // Register service worker for PWA functionality and background recording support
- if ('serviceWorker' in navigator) {
- window.addEventListener('load', () => {
- navigator.serviceWorker.register('/static/service-worker.js')
- .then((registration) => {
- console.log('Service Worker registered successfully:', registration.scope);
-
- // Check for updates periodically
- setInterval(() => {
- registration.update();
- }, 60000); // Check every minute
- })
- .catch((error) => {
- console.error('Service Worker registration failed:', error);
- });
- });
- }
- </script>
+ <!-- Service Worker Registration handled by app.modular.js -->
<!-- Vue.js Application Script -->
- <script src="{{ url_for('static', filename='js/app.js') }}"></script>
+ <script type="module" src="{{ url_for('static', filename='js/app.modular.js') }}"></script>
</body>
</html>
diff --git a/templates/index.original.html.backup b/templates/index.original.html.backup
new file mode 100644
index 00000000..f15a36eb
--- /dev/null
+++ b/templates/index.original.html.backup
@@ -0,0 +1,3480 @@
+<!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>Speakr - Audio Transcription & Summarization</title>
+ {% include 'includes/loading_overlay.html' %}
+ <!-- All dependencies bundled locally for offline support -->
+ <script src="{{ url_for('static', filename='vendor/js/tailwind.min.js') }}"></script>
+ <script src="{{ url_for('static', filename='vendor/js/vue.global.js') }}"></script>
+ <script src="{{ url_for('static', filename='vendor/js/marked.min.js') }}"></script>
+ <link rel="stylesheet" href="{{ url_for('static', filename='vendor/css/easymde.min.css') }}">
+ <script src="{{ url_for('static', filename='vendor/js/easymde.min.js') }}"></script>
+ <link rel="stylesheet" href="{{ url_for('static', filename='vendor/css/fontawesome.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') }}">
+ <link rel="icon" type="image/png" sizes="16x16" href="{{ url_for('static', filename='img/icon-16x16.png') }}">
+ <link rel="apple-touch-icon" sizes="180x180" href="{{ url_for('static', filename='img/icon-180x180.png') }}">
+ <link rel="manifest" href="{{ url_for('static', filename='manifest.json') }}">
+ <meta name="theme-color" content="#2563eb">
+ <script>
+ tailwind.config = {
+ darkMode: 'class',
+ theme: {
+ extend: {
+ maxHeight: {
+ '85vh': '85vh',
+ '90vh': '90vh'
+ },
+ colors: {
+ primary: 'var(--bg-primary)',
+ secondary: 'var(--bg-secondary)',
+ accent: 'var(--bg-accent)'
+ }
+ }
+ }
+ }
+ </script>
+</head>
+<body class="h-full bg-[var(--bg-primary)] text-[var(--text-primary)] transition-colors duration-300">
+ <div id="loader" class="fixed inset-0 bg-gray-800 flex items-center justify-center z-50">
+ <div class="text-white text-lg">Loading...</div>
+ </div>
+ <div id="app" v-cloak
+ data-use-asr-endpoint="{{ use_asr_endpoint }}"
+ data-current-user-name="{{ current_user.name if current_user.is_authenticated else '' }}"
+ data-user-language="{{ user_language }}"
+ class="h-full flex flex-col opacity-0 transition-opacity duration-500">
+
+ <!-- Header -->
+ <header class="bg-[var(--bg-secondary)] border-b border-[var(--border-primary)] px-3 sm:px-4 py-3 flex items-center justify-between flex-shrink-0 z-50">
+ <!-- Left side: Menu toggle and logo -->
+ <div class="flex items-center gap-2 sm:gap-4 min-w-0 flex-shrink">
+ <!-- Menu Toggle Button -->
+ <button @click="toggleSidebar"
+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors duration-200 flex-shrink-0 flex items-center justify-center">
+ <i class="fas fa-bars text-lg"></i>
+ </button>
+
+ <!-- Logo and Title -->
+ <div class="flex items-center gap-2 sm:gap-3 min-w-0">
+ <img src="{{ url_for('static', filename='img/icon-32x32.png') }}" alt="Speakr" class="w-7 h-7 sm:w-8 sm:h-8 flex-shrink-0">
+ <h1 class="text-lg sm:text-xl font-bold text-[var(--text-primary)] truncate">Speakr</h1>
+ </div>
+ </div>
+
+ <!-- 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-2 py-1.5 bg-[var(--bg-accent)] text-[var(--text-accent)] rounded-lg hover:opacity-80 transition-opacity text-sm sm:px-4 sm:py-2 sm:min-w-[120px] sm:flex sm:items-center sm:gap-2 sm:justify-center">
+ <i class="fas fa-search"></i>
+ <span class="hidden sm:inline" v-text="t('inquire.title')"></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 sm:px-4 sm:py-2 sm:min-w-[120px] sm:flex sm:items-center sm:gap-2 sm:justify-center">
+ <i class="fas fa-plus mr-1"></i><span v-text="t('nav.newRecording')"></span>
+ </button>
+
+ <!-- User menu -->
+ {% if current_user.is_authenticated %}
+ <div class="relative">
+ <button @click="isUserMenuOpen = !isUserMenuOpen"
+ class="flex items-center gap-1 sm:gap-2 p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors duration-200"
+ :title="t('admin.userMenu')">
+ <i class="fas fa-user-circle text-lg"></i>
+ <span class="hidden lg:inline text-sm">{{ current_user.name if current_user.is_authenticated else 'User' }}</span>
+ <i class="fas fa-chevron-down text-xs hidden sm:inline"></i>
+ </button>
+
+ <!-- User dropdown -->
+ <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><span v-text="t('nav.settings')"></span>
+ </a>
+ <a href="/account#tags" class="block px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors">
+ <i class="fas fa-tags mr-2 w-4 text-center"></i><span v-text="t('help.tagManagement')"></span>
+ </a>
+ <button @click="openSharesList" class="w-full text-left px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors flex items-center">
+ <i class="fas fa-share-alt mr-2 w-4 text-center"></i><span v-text="t('modal.sharedTranscripts')"></span>
+ </button>
+ {% if current_user.is_admin or is_team_admin %}
+ <a href="/admin" class="block px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors">
+ <i class="fas fa-{% if current_user.is_admin %}user-shield{% else %}users-cog{% endif %} mr-2 w-4 text-center"></i>
+ <span v-text="{% if current_user.is_admin %}t('admin.title'){% else %}t('nav.teamManagement'){% endif %}"></span>
+ </a>
+ {% endif %}
+ <div class="border-t border-[var(--border-primary)] my-1"></div>
+ <button @click="toggleDarkMode" class="w-full text-left px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors flex items-center">
+ <i :class="isDarkMode ? 'fas fa-sun' : 'fas fa-moon'" class="mr-2 w-4 text-center"></i>
+ <span v-text="isDarkMode ? t('nav.lightMode') : t('nav.darkMode')"></span>
+ </button>
+ <button @click="openColorSchemeModal" class="w-full text-left px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors flex items-center">
+ <i class="fas fa-palette mr-2 w-4 text-center"></i>
+ <span v-text="t('modal.colorScheme')"></span>
+ </button>
+ <div class="border-t border-[var(--border-primary)] my-1"></div>
+ <a href="/logout" class="block px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors">
+ <i class="fas fa-sign-out-alt mr-2 w-4 text-center"></i><span v-text="t('nav.signOut')"></span>
+ </a>
+ </div>
+ </div>
+ {% endif %}
+ </div>
+ </header>
+
+ <div class="flex-1 flex overflow-hidden relative">
+ <!-- Mobile Sidebar Backdrop -->
+ <div v-if="!isSidebarCollapsed && isMobileScreen"
+ @click="toggleSidebar"
+ class="fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden">
+ </div>
+
+ <!-- Sidebar -->
+ <aside :class="['sidebar', isSidebarCollapsed ? 'collapsed' : '']">
+ <div class="sidebar-content-wrapper">
+ <!-- Sidebar Header -->
+ <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" v-text="t('nav.recording')"></h2>
+ <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><span v-text="t('common.new')"></span>
+ </button>
+ </div>
+ </div>
+
+ <!-- Search and Sort Controls -->
+ <div class="space-y-3">
+ <!-- Filter Toggle Button -->
+ <div class="flex items-center space-x-2">
+ <button @click="showAdvancedFilters = !showAdvancedFilters"
+ class="flex-1 flex items-center justify-between px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg text-sm hover:bg-[var(--bg-tertiary)] transition-colors">
+ <span class="flex items-center">
+ <i class="fas fa-filter mr-2 text-[var(--text-muted)]"></i>
+ <span v-if="!searchQuery && filterTags.length === 0 && !filterDatePreset && !filterDateRange.start && !filterDateRange.end && !filterTextQuery"
+ v-text="t('sidebar.searchRecordings')">
+ </span>
+ <span v-else class="text-[var(--text-accent)]">
+ Active filters (${ (filterTags.length > 0 ? 1 : 0) + (filterDatePreset || filterDateRange.start || filterDateRange.end ? 1 : 0) + (filterTextQuery ? 1 : 0) })
+ </span>
+ </span>
+ <i :class="['fas fa-chevron-down transition-transform text-[var(--text-muted)]', showAdvancedFilters ? 'rotate-180' : '']"></i>
+ </button>
+ <button v-if="searchQuery || filterTags.length > 0 || filterDatePreset || filterDateRange.start || filterDateRange.end || filterTextQuery"
+ @click="clearAllFilters"
+ class="px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg text-sm hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-primary)] transition-colors"
+ :title="t('buttons.clearAllFilters')">
+ <i class="fas fa-times text-[var(--text-muted)]"></i>
+ </button>
+ </div>
+
+ <!-- Advanced Filters Panel -->
+ <div v-show="showAdvancedFilters" class="p-3 bg-[var(--bg-tertiary)] border border-[var(--border-secondary)] rounded-lg space-y-3">
+ <!-- Text Search -->
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-muted)] mb-1" v-text="t('sidebar.filters')"></label>
+ <div class="relative">
+ <input v-model="filterTextQuery"
+ type="text"
+ :placeholder="t('sidebar.searchRecordings')"
+ class="w-full px-3 py-1.5 pl-8 pr-8 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-md text-sm focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">
+ <i class="fas fa-search absolute left-2.5 top-1/2 transform -translate-y-1/2 text-[var(--text-muted)] text-xs"></i>
+ <button v-if="filterTextQuery"
+ @click="filterTextQuery = ''"
+ class="absolute right-2.5 top-1/2 transform -translate-y-1/2 text-[var(--text-muted)] hover:text-[var(--text-primary)] text-xs"
+ :title="t('buttons.clearSearchText')">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+ </div>
+
+ <!-- Tag Filter -->
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-muted)] mb-1" v-text="t('tags.filterByTag')"></label>
+ <div class="flex flex-wrap gap-1.5">
+ <button v-for="tag in availableTags"
+ :key="tag.id"
+ @click="filterTags.includes(tag.id) ? filterTags = filterTags.filter(id => id !== tag.id) : filterTags.push(tag.id)"
+ :class="[
+ 'px-2 py-1 rounded-full text-xs font-medium transition-all',
+ filterTags.includes(tag.id)
+ ? 'bg-[var(--bg-accent)] text-[var(--text-accent)] ring-1 ring-[var(--border-accent)]'
+ : 'bg-[var(--bg-secondary)] text-[var(--text-secondary)] hover:bg-[var(--bg-input)]'
+ ]">
+ <span class="inline-block w-2 h-2 rounded-full mr-1" :style="{ backgroundColor: tag.color || '#6B7280' }"></span>
+ ${ tag.name }
+ </button>
+ </div>
+ <p v-if="availableTags.length === 0" class="text-xs text-[var(--text-muted)] italic" v-text="t('tags.noTags')"></p>
+ </div>
+
+ <!-- Date Filter -->
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-muted)] mb-1" v-text="t('sidebar.dateRange')"></label>
+ <div class="grid grid-cols-3 gap-1.5 mb-2">
+ <button v-for="preset in datePresetOptions"
+ :key="preset.value"
+ @click="filterDatePreset = filterDatePreset === preset.value ? '' : preset.value; filterDateRange = { start: '', end: '' }"
+ :class="[
+ 'px-2 py-1 rounded-md text-xs transition-all',
+ filterDatePreset === preset.value
+ ? 'bg-[var(--bg-accent)] text-[var(--text-accent)]'
+ : 'bg-[var(--bg-secondary)] text-[var(--text-secondary)] hover:bg-[var(--bg-input)]'
+ ]"
+ :title="preset.label">
+ ${ preset.label }
+ </button>
+ </div>
+ <div class="grid grid-cols-2 gap-2">
+ <div>
+ <input v-model="filterDateRange.start"
+ @change="filterDatePreset = ''"
+ type="date"
+ class="w-full px-2 py-1 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-md text-xs focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]"
+ :placeholder="t('form.dateFrom')">
+ </div>
+ <div>
+ <input v-model="filterDateRange.end"
+ @change="filterDatePreset = ''"
+ type="date"
+ class="w-full px-2 py-1 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-md text-xs focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]"
+ :placeholder="t('form.dateTo')">
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Sort Toggle -->
+ <button @click="sortBy = sortBy === 'created_at' ? 'meeting_date' : 'created_at'"
+ class="w-full flex items-center justify-between px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg text-sm hover:bg-[var(--bg-tertiary)] transition-colors">
+ <span class="flex items-center">
+ <i :class="['fas mr-2 text-[var(--text-muted)]', sortBy === 'meeting_date' ? 'fa-calendar' : 'fa-upload']"></i>
+ <span v-text="t('sidebar.sortBy')"></span>: <span v-text="sortBy === 'meeting_date' ? t('sidebar.sortByMeetingDate') : t('sidebar.sortByDate')"></span>
+ </span>
+ <i class="fas fa-exchange-alt text-[var(--text-muted)]"></i>
+ </button>
+
+ <!-- Archived Recordings Toggle -->
+ <button @click="showArchivedRecordings = !showArchivedRecordings"
+ :class="[
+ 'w-full flex items-center justify-between px-3 py-2 border rounded-lg text-sm transition-colors',
+ showArchivedRecordings
+ ? 'bg-[var(--bg-accent)] border-[var(--border-accent)] text-[var(--text-accent)]'
+ : 'bg-[var(--bg-input)] border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)]'
+ ]">
+ <span class="flex items-center">
+ <i class="fas fa-archive mr-2"></i>
+ <span v-text="t('sidebar.archivedRecordings')"></span>
+ </span>
+ <i :class="['fas', showArchivedRecordings ? 'fa-toggle-on' : 'fa-toggle-off']"></i>
+ </button>
+
+ <!-- Shared with Me Toggle -->
+ <button v-if="enableInternalSharing" @click="showSharedWithMe = !showSharedWithMe"
+ :class="[
+ 'w-full flex items-center justify-between px-3 py-2 border rounded-lg text-sm transition-colors mt-2',
+ showSharedWithMe
+ ? 'bg-[var(--bg-accent)] border-[var(--border-accent)] text-[var(--text-accent)]'
+ : 'bg-[var(--bg-input)] border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)]'
+ ]">
+ <span class="flex items-center">
+ <i class="fas fa-users mr-2"></i>
+ <span v-text="t('sidebar.sharedWithMe')"></span>
+ </span>
+ <i :class="['fas', showSharedWithMe ? 'fa-toggle-on' : 'fa-toggle-off']"></i>
+ </button>
+ </div>
+ </div>
+
+ <!-- Recordings List -->
+ <div class="flex-1 overflow-y-auto p-4"
+ @scroll="(e) => {
+ const element = e.target;
+ const threshold = 100; // Load more when 100px from bottom
+ if (element.scrollHeight - element.scrollTop - element.clientHeight < threshold) {
+ loadMoreRecordings();
+ }
+ }">
+ <div v-if="isLoadingRecordings && recordings.length === 0" class="text-center py-8">
+ <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
+ <p class="mt-2 text-[var(--text-muted)]" v-text="t('help.loadingRecordings')"></p>
+ </div>
+
+ <div v-else-if="recordings.length === 0 && !isLoadingRecordings" class="text-center py-8">
+ <i class="fas fa-microphone-slash text-3xl text-[var(--text-muted)] mb-3"></i>
+ <p class="text-[var(--text-muted)]" v-text="t('sidebar.noRecordings')"></p>
+ <p v-if="searchQuery.trim()" class="text-sm text-[var(--text-muted)] mt-1">
+ <span v-text="t('help.tryAdjustingSearch')"></span> <button @click="clearAllFilters()" class="text-[var(--text-accent)] hover:underline" v-text="t('help.clearFilters')"></button>
+ </p>
+ </div>
+
+ <div v-if="recordings.length > 0" class="space-y-2">
+ <div v-for="group in groupedRecordings" :key="group.title" class="mb-6">
+ <h3 class="text-xs font-semibold text-[var(--text-muted)] uppercase tracking-wide mb-2">
+ ${group.title}
+ </h3>
+ <div class="space-y-1">
+ <div v-for="recording in group.items"
+ :key="recording.id"
+ @click="selectRecording(recording)"
+ :class="[
+ 'p-3 rounded-lg cursor-pointer transition-all duration-200 border',
+ selectedRecording?.id === recording.id
+ ? 'bg-[var(--bg-accent)] border-[var(--border-accent)]'
+ : 'bg-[var(--bg-tertiary)] border-transparent hover:bg-[var(--bg-accent-hover)]'
+ ]">
+ <!-- Title and Status Row -->
+ <div class="flex items-center justify-between mb-1">
+ <h4 class="font-medium text-sm truncate flex-1 mr-2" :class="selectedRecording?.id === recording.id ? 'text-[var(--text-accent)]' : 'text-[var(--text-primary)]'">
+ ${ recording.title || t('common.untitled') }
+ </h4>
+ <div class="flex items-center gap-0.5 flex-shrink-0">
+ <!-- Combined sharing status badge -->
+ <span v-if="recording.is_shared || recording.has_group_tags || recording.shared_with_count > 0 || recording.public_share_count > 0"
+ class="inline-flex items-center justify-center gap-1 h-5 px-1.5 rounded-full text-[9px] leading-none bg-violet-100 dark:bg-violet-900/50 border border-violet-300 dark:border-violet-600"
+ :title="[
+ recording.is_shared ? t('sharing.sharedBy') + ' ' + (recording.owner_username || t('sharing.unknown')) : '',
+ recording.has_group_tags ? t('sharing.teamRecording') : '',
+ !recording.is_shared && recording.shared_with_count > 0 ? t('sharing.sharedWith') + ' ' + recording.shared_with_count + ' ' + t('sharing.users') : '',
+ !recording.is_shared && recording.public_share_count > 0 ? recording.public_share_count + ' ' + t('sharing.publicLinksGenerated') : ''
+ ].filter(s => s).join(' • ')">
+ <i v-if="recording.is_shared" class="fas fa-arrow-down text-purple-600 dark:text-purple-400" style="line-height: 1;"></i>
+ <i v-if="recording.has_group_tags" class="fas fa-users text-blue-600 dark:text-blue-400" style="line-height: 1;"></i>
+ <i v-if="!recording.is_shared && recording.shared_with_count > 0" class="fas fa-arrow-up text-indigo-600 dark:text-indigo-400" style="line-height: 1;"></i>
+ <i v-if="!recording.is_shared && recording.public_share_count > 0" class="fas fa-globe text-teal-600 dark:text-teal-400" style="line-height: 1;"></i>
+ </span>
+
+ <!-- Show Audio Deleted badge -->
+ <span v-if="recording.audio_deleted_at"
+ class="inline-flex items-center justify-center h-5 px-1.5 rounded-full text-[9px] leading-none bg-gray-200 dark:bg-gray-700 border border-gray-300 dark:border-gray-600"
+ :title="t('sidebar.archived')">
+ <i class="fas fa-file-audio text-gray-600 dark:text-gray-400"></i>
+ </span>
+
+ <!-- Show Failed status for failed recordings -->
+ <span v-if="recording.status === 'FAILED'"
+ class="inline-flex items-center justify-center h-5 px-1.5 rounded-full text-[9px] leading-none bg-red-100 dark:bg-red-900/50 border border-red-300 dark:border-red-700 text-red-700 dark:text-red-400">
+ <i class="fas fa-exclamation-circle"></i>
+ </span>
+
+ <!-- Show Processing status for non-completed recordings -->
+ <span v-else-if="recording.status !== 'COMPLETED'"
+ :class="getStatusClass(recording.status)"
+ class="status-badge">
+ ${formatStatus(recording.status)}
+ </span>
+
+ <!-- For completed recordings, show highlight and inbox badges -->
+ <template v-else>
+ <span v-if="recording.is_highlighted"
+ @click.stop="toggleHighlight(recording)"
+ class="inline-flex items-center justify-center h-5 px-1.5 rounded-full text-[9px] leading-none bg-amber-100 dark:bg-amber-900/50 border border-amber-400 dark:border-amber-600 cursor-pointer hover:bg-amber-200 dark:hover:bg-amber-800/50"
+ :title="t('sidebar.removeFromHighlighted')">
+ <i class="fas fa-star text-amber-600 dark:text-amber-400"></i>
+ </span>
+ <span v-if="recording.is_inbox"
+ @click.stop="toggleInbox(recording)"
+ class="inline-flex items-center justify-center h-5 px-1.5 rounded-full text-[9px] leading-none bg-blue-100 dark:bg-blue-900/50 border border-blue-400 dark:border-blue-600 cursor-pointer hover:bg-blue-200 dark:hover:bg-blue-800/50"
+ :title="t('sidebar.markAsRead')">
+ <i class="fas fa-inbox text-blue-600 dark:text-blue-400"></i>
+ </span>
+ </template>
+ </div>
+ </div>
+
+ <!-- Date and Participants -->
+ <div class="flex flex-wrap items-center gap-x-3 gap-y-1 mt-1 text-xs text-[var(--text-muted)]">
+ <!-- Date -->
+ <div class="flex items-center flex-shrink-0">
+ <i class="fas fa-calendar-alt mr-1 text-[var(--text-muted)]" style="font-size: 10px;"></i>
+ ${formatShortDate(sortBy === 'meeting_date' ? recording.meeting_date : recording.created_at)}
+ </div>
+
+ <!-- Participants -->
+ <div v-if="recording.participants" class="flex items-center min-w-0 flex-1">
+ <i class="fas fa-users mr-1 text-[var(--text-muted)] flex-shrink-0" style="font-size: 10px;"></i>
+ <span class="truncate">
+ ${recording.participants}
+ </span>
+ </div>
+ </div>
+
+ <!-- Tags -->
+ <div v-if="getRecordingTags(recording).length > 0" class="flex flex-wrap gap-1 mt-1">
+ <button v-for="tag in getRecordingTags(recording).slice(0, 4)" :key="tag.id"
+ @click.stop="filterByTag(tag)"
+ class="inline-flex items-center px-1.5 py-0.5 rounded-md text-xs font-medium text-white hover:opacity-80 transition-all cursor-pointer"
+ :style="{ backgroundColor: tag.color }"
+ :title="(tag.group_id ? '👥 Group Tag: ' : 'Filter by ') + tag.name">
+ <i v-if="tag.group_id" class="fas fa-users mr-1" style="font-size: 9px;"></i>
+ <span v-text="tag.name"></span>
+ </button>
+ <span v-if="getRecordingTags(recording).length > 4"
+ class="inline-flex items-center px-1.5 py-0.5 rounded-md text-xs text-[var(--text-muted)]"
+ :title="getRecordingTags(recording).slice(4).map(t => t.name).join(', ')">
+ +${getRecordingTags(recording).length - 4}
+ </span>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Load More Indicator -->
+ <div v-if="isLoadingMore" class="text-center py-4">
+ <i class="fas fa-spinner fa-spin text-lg text-[var(--text-muted)]"></i>
+ <p class="text-sm text-[var(--text-muted)] mt-1" v-text="t('help.loadingMore')"></p>
+ </div>
+
+ <!-- End of Results Indicator -->
+ <div v-else-if="!hasNextPage && totalRecordings > 0" class="text-center py-4 text-xs text-[var(--text-muted)]">
+ <i class="fas fa-check-circle mr-1"></i>
+ <span v-text="t('help.allRecordingsLoaded')"></span>
+ </div>
+ </div>
+ </div>
+ </div>
+ </aside>
+
+ <!-- Main Content -->
+ <main class="main-content"
+ :class="{ 'sidebar-open': !isSidebarCollapsed }">
+
+ <div class="flex-1 flex flex-col overflow-hidden">
+ <!-- Upload View -->
+ <div v-if="currentView === 'upload'" class="flex-1 flex items-center justify-center p-4 md:p-8 overflow-y-auto">
+ <div class="max-w-lg w-full my-auto">
+ <div class="text-center mb-8">
+ <i class="fas fa-microphone text-5xl md:text-6xl text-[var(--text-accent)] mb-4"></i>
+ <h2 class="text-2xl md:text-3xl font-bold mb-2" v-text="t('upload.title')"></h2>
+ <p class="text-[var(--text-muted)]" v-text="t('upload.dropzone')"></p>
+ </div>
+
+ <div class="bg-[var(--bg-secondary)] p-6 rounded-xl border border-[var(--border-primary)]">
+ <!-- File Upload Area -->
+ <div @drop="handleDrop" @dragover="handleDragOver" @dragleave="handleDragLeave" @click="$refs.fileInput.click()"
+ :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" v-text="t('upload.dropzone')"></p>
+ <p class="text-xs text-[var(--text-muted)]" v-text="t('upload.supportedFormats')"></p>
+ </div>
+ <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">
+
+ <!-- Queued Files Display -->
+ <div v-if="pendingQueueFiles.length > 0" class="mt-4">
+ <div class="flex items-center justify-between mb-2">
+ <h4 class="text-sm font-medium text-[var(--text-secondary)]">
+ <i class="fas fa-list mr-1"></i>
+ Files to Upload (${pendingQueueFiles.length})
+ </h4>
+ </div>
+ <div class="space-y-2 max-h-40 overflow-y-auto">
+ <div v-for="item in pendingQueueFiles" :key="item.clientId"
+ class="flex items-center justify-between p-2 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-secondary)]">
+ <div class="flex items-center gap-2 min-w-0 flex-1">
+ <i class="fas fa-file-audio text-[var(--text-muted)]"></i>
+ <span class="text-sm text-[var(--text-primary)] truncate">${item.file.name}</span>
+ <span class="text-xs text-[var(--text-muted)] flex-shrink-0">(${formatFileSize(item.file.size)})</span>
+ </div>
+ <button @click="removeFromQueue(item.clientId)"
+ class="ml-2 p-1 text-[var(--text-muted)] hover:text-red-500 transition-colors flex-shrink-0"
+ title="Remove from queue">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+ </div>
+ <!-- Upload Button -->
+ <button @click="startUpload"
+ class="w-full mt-3 px-4 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors flex items-center justify-center gap-2 font-medium">
+ <i class="fas fa-cloud-upload-alt"></i>
+ <span>Upload ${pendingQueueFiles.length} File${pendingQueueFiles.length !== 1 ? 's' : ''}</span>
+ </button>
+ </div>
+
+ <!-- Divider (hidden when files are selected) -->
+ <div v-if="pendingQueueFiles.length === 0" class="my-6 flex items-center">
+ <div class="flex-grow border-t border-[var(--border-secondary)]"></div>
+ <span class="flex-shrink mx-4 text-xs text-[var(--text-muted)] uppercase" v-text="t('common.or')"></span>
+ <div class="flex-grow border-t border-[var(--border-secondary)]"></div>
+ </div>
+
+ <!-- Audio Recording Options (hidden when files are selected) -->
+ <div v-if="pendingQueueFiles.length === 0" class="space-y-3">
+ <h3 class="text-sm font-medium text-[var(--text-secondary)] text-center" v-text="t('recording.title')"></h3>
+
+ <!-- Microphone Recording -->
+ <button @click="startRecording('microphone')"
+ class="w-full px-4 py-3 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors flex items-center justify-center gap-2">
+ <i class="fas fa-microphone"></i>
+ <span v-text="t('recording.microphone')"></span>
+ </button>
+
+ <!-- System Audio Recording -->
+ <button @click="startRecording('system')"
+ v-if="canRecordSystemAudio"
+ class="w-full px-4 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center justify-center gap-2">
+ <i class="fas fa-desktop"></i>
+ <span v-text="t('recording.systemAudio')"></span>
+ </button>
+
+ <!-- Both Audio Sources -->
+ <button @click="startRecording('both')"
+ v-if="canRecordSystemAudio"
+ class="w-full px-4 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors flex items-center justify-center gap-2">
+ <i class="fas fa-microphone"></i>
+ <i class="fas fa-desktop ml-1"></i>
+ <span v-text="t('recording.microphoneAndSystem')"></span>
+ </button>
+
+ <!-- Help Text -->
+ <div class="text-xs text-[var(--text-muted)] space-y-1 mt-3">
+ <div class="flex items-center justify-between">
+ <span><strong v-text="t('recording.microphone') + ':'"></strong> <span v-text="t('help.microphoneDesc')"></span></span>
+ <i class="fas fa-microphone text-red-500 flex-shrink-0"></i>
+ </div>
+ <div v-if="canRecordSystemAudio" class="flex items-center justify-between">
+ <span><strong v-text="t('recording.systemAudio') + ':'"></strong> <span v-text="t('help.systemAudioDesc')"></span></span>
+ <i class="fas fa-desktop text-blue-500 flex-shrink-0"></i>
+ </div>
+ <div v-if="canRecordSystemAudio" class="flex items-center justify-between">
+ <span><strong v-text="t('recording.microphoneAndSystem') + ':'"></strong> <span v-text="t('help.bothAudioDesc')"></span></span>
+ <div class="flex items-center gap-1 flex-shrink-0">
+ <i class="fas fa-microphone text-purple-500"></i>
+ <i class="fas fa-desktop text-purple-500"></i>
+ </div>
+ </div>
+ <div v-if="!canRecordSystemAudio" class="text-amber-600 dark:text-amber-400">
+ <i class="fas fa-exclamation-triangle mr-1"></i>
+ ${ t('recording.systemAudioNotSupported') }
+ <button @click="showSystemAudioHelp = true" class="ml-2 text-blue-500 hover:text-blue-600 underline text-sm">
+ <span v-text="t('buttons.help')"></span>
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Tag Selection -->
+ <div class="mt-4">
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-2">
+ <i class="fas fa-tags mr-1 text-[var(--text-muted)]"></i>
+ ${ t('tags.title') }
+ </label>
+
+ <!-- Selected Tags Display - Compact -->
+ <div v-if="selectedTags.length > 0" class="mb-2">
+ <div class="p-1.5 bg-[var(--bg-tertiary)] rounded-md border border-[var(--border-secondary)] max-h-16 overflow-y-auto">
+ <div class="flex flex-wrap gap-1">
+ <span v-for="(tag, index) in selectedTags" :key="tag.id"
+ class="inline-flex items-center px-1.5 py-0.5 rounded-full text-[11px] font-medium text-white"
+ :style="{ backgroundColor: tag.color }">
+ <span class="opacity-75 mr-0.5 text-[9px]">${index + 1}.</span>
+ <span>${tag.name}</span>
+ <button @click="removeTagFromSelection(tag.id)"
+ class="ml-1 hover:opacity-100 opacity-70">
+ <i class="fas fa-times" style="font-size: 9px;"></i>
+ </button>
+ </span>
+ </div>
+ </div>
+ <p class="text-[10px] text-[var(--text-muted)] mt-0.5">
+ <i class="fas fa-info-circle mr-0.5" style="font-size: 9px;"></i>
+ Tags ordered by priority
+ </p>
+ </div>
+
+ <!-- Tag Selection Container - Compact -->
+ <div v-if="availableTags.filter(tag => !selectedTagIds.includes(tag.id)).length > 0"
+ class="border border-[var(--border-secondary)] rounded-md bg-[var(--bg-tertiary)] p-2">
+ <!-- Search Filter (always visible if tags available) -->
+ <div class="mb-1.5">
+ <div class="relative">
+ <input v-model="uploadTagSearchFilter"
+ type="text"
+ :placeholder="t('tagsModal.searchTags')"
+ class="w-full px-2 py-1 pl-6 text-xs bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">
+ <i class="fas fa-search absolute left-2 top-1/2 transform -translate-y-1/2 text-[var(--text-muted)]" style="font-size: 9px;"></i>
+ <button v-if="uploadTagSearchFilter"
+ @click="uploadTagSearchFilter = ''"
+ class="absolute right-2 top-1/2 transform -translate-y-1/2 text-[var(--text-muted)] hover:text-[var(--text-primary)]">
+ <i class="fas fa-times" style="font-size: 9px;"></i>
+ </button>
+ </div>
+ </div>
+
+ <!-- Available Tags Grid - Fixed Height -->
+ <div v-if="filteredAvailableTagsForUpload.length > 0"
+ class="overflow-y-auto"
+ style="max-height: 100px;">
+ <div class="grid grid-cols-2 gap-1">
+ <button v-for="tag in filteredAvailableTagsForUpload"
+ :key="tag.id"
+ @click="addTagToSelection(tag.id)"
+ class="group flex items-center justify-between px-1.5 py-1 rounded border border-[var(--border-secondary)] hover:border-[var(--border-focus)] bg-[var(--bg-primary)] hover:bg-[var(--bg-secondary)] transition-all">
+ <div class="flex items-center gap-1 min-w-0">
+ <span class="w-2 h-2 rounded-full flex-shrink-0"
+ :style="{ backgroundColor: tag.color || '#6B7280' }"></span>
+ <span class="text-[11px] text-[var(--text-primary)] truncate" v-text="tag.name"></span>
+ </div>
+ <i class="fas fa-plus text-[var(--text-muted)] group-hover:text-[var(--text-accent)] transition-colors" style="font-size: 9px;"></i>
+ </button>
+ </div>
+ </div>
+ <div v-else class="py-2 text-center">
+ <p class="text-[11px] text-[var(--text-muted)]">
+ <i class="fas fa-search mr-1" style="font-size: 9px;"></i>
+ No matching tags
+ </p>
+ </div>
+ </div>
+ <!-- Empty States -->
+ <div v-else-if="availableTags.length === 0"
+ class="p-2 bg-[var(--bg-tertiary)] rounded-md border border-[var(--border-secondary)]">
+ <p class="text-xs text-[var(--text-muted)] text-center">
+ <i class="fas fa-info-circle mr-1" style="font-size: 10px;"></i>
+ <span v-text="t('help.noTagsCreated')"></span> <a href="/account#tags" class="text-[var(--text-accent)] hover:underline" v-text="t('help.createTags')"></a>
+ </p>
+ </div>
+ <div v-else class="p-2 bg-[var(--bg-tertiary)] rounded-md border border-[var(--border-secondary)]">
+ <p class="text-xs text-[var(--text-muted)] text-center">
+ <i class="fas fa-check-circle mr-1" style="font-size: 10px;"></i>
+ All tags selected
+ </p>
+ </div>
+
+ <p v-if="selectedTags.some(tag => tag.custom_prompt)" class="text-xs text-[var(--text-muted)] mt-1">
+ <i class="fas fa-info-circle mr-1 text-[var(--text-accent)]"></i>
+ Selected tags include custom summary prompts
+ </p>
+ <p v-if="selectedTags.length > 0 && useAsrEndpoint && selectedTags.some(tag => tag.default_language || tag.default_min_speakers || tag.default_max_speakers)"
+ class="text-xs text-[var(--text-muted)] mt-1">
+ <i class="fas fa-cog mr-1 text-[var(--text-accent)]"></i>
+ First tag's ASR settings will be applied: ${selectedTags[0].name}
+ </p>
+ </div>
+
+ <!-- Advanced Options for ASR (collapsible) -->
+ <div v-if="useAsrEndpoint" class="mt-4">
+ <button @click="showAdvancedOptions = !showAdvancedOptions"
+ class="w-full flex items-center justify-between px-3 py-2 bg-[var(--bg-tertiary)] rounded-md hover:bg-[var(--bg-accent)] transition-colors text-xs font-medium">
+ <span class="flex items-center gap-2 text-[var(--text-secondary)]">
+ <i class="fas fa-cog text-[var(--text-muted)]"></i>
+ <span v-text="t('help.advancedAsrOptions')"></span>
+ </span>
+ <i :class="['fas text-[var(--text-muted)]', showAdvancedOptions ? 'fa-chevron-up' : 'fa-chevron-down']"></i>
+ </button>
+
+ <div v-show="showAdvancedOptions" class="mt-2 p-3 bg-[var(--bg-tertiary)] rounded-md space-y-3 border border-[var(--border-secondary)]">
+ <!-- Language Selection -->
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1">
+ Transcription Language
+ </label>
+ <select v-model="uploadLanguage"
+ class="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">
+ <option v-for="lang in languageOptions" :key="lang.value" :value="lang.value" v-text="lang.label"></option>
+ </select>
+ </div>
+
+ <!-- Speaker Settings -->
+ <div class="grid grid-cols-2 gap-3">
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1" v-text="t('form.minSpeakers')">
+ </label>
+ <input v-model.number="uploadMinSpeakers"
+ type="number"
+ min="1"
+ max="20"
+ class="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">
+ </div>
+ <div>
+ <label class="block text-xs font-medium text-[var(--text-secondary)] mb-1" v-text="t('form.maxSpeakers')">
+ </label>
+ <input v-model.number="uploadMaxSpeakers"
+ type="number"
+ min="1"
+ max="20"
+ class="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">
+ </div>
+ </div>
+
+ <p class="text-xs text-[var(--text-muted)] pt-1">
+ <i class="fas fa-info-circle mr-1 text-[var(--text-accent)]"></i>
+ Settings apply to all files in this session
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Recording View -->
+ <div v-else-if="currentView === 'recording'" class="flex-1 flex flex-col p-2 md:p-8 bg-[var(--bg-primary)] min-h-0">
+ <div class="flex-1 flex flex-col max-w-4xl w-full mx-auto bg-[var(--bg-secondary)] rounded-xl border border-[var(--border-primary)] min-h-0 overflow-hidden">
+ <!-- Top: Visualizer and Status (Fixed) -->
+ <div class="flex-shrink-0 p-3 md:p-6 text-center bg-[var(--bg-tertiary)] border-b border-[var(--border-primary)]">
+ <div v-if="isRecording" class="w-full mx-auto mb-3 md:mb-4">
+ <!-- Dual visualizer for 'both' mode -->
+ <div v-if="recordingMode === 'both'" class="max-w-4xl mx-auto flex gap-2 md:gap-4">
+ <div class="w-1/2 min-h-[8rem] md:min-h-[12rem] h-32 md:h-48 flex flex-col bg-[var(--bg-primary)] rounded-lg p-1.5 md:p-2">
+ <div class="flex-1 w-full overflow-hidden rounded-md" style="min-height: 6rem;">
+ <canvas ref="micVisualizer" class="w-full h-full"></canvas>
+ </div>
+ <p class="text-xs text-[var(--text-muted)] pt-0.5 md:pt-1" v-text="t('recording.microphone')"></p>
+ </div>
+ <div class="w-1/2 min-h-[8rem] md:min-h-[12rem] h-32 md:h-48 flex flex-col bg-[var(--bg-primary)] rounded-lg p-1.5 md:p-2">
+ <div class="flex-1 w-full overflow-hidden rounded-md" style="min-height: 6rem;">
+ <canvas ref="systemVisualizer" class="w-full h-full"></canvas>
+ </div>
+ <p class="text-xs text-[var(--text-muted)] pt-0.5 md:pt-1" v-text="t('recording.systemAudio')"></p>
+ </div>
+ </div>
+ <!-- Single visualizer for other modes -->
+ <div v-else class="min-h-[8rem] md:min-h-[12rem] h-32 md:h-48 max-w-2xl mx-auto bg-[var(--bg-primary)] rounded-lg p-1.5 md:p-2 flex flex-col">
+ <div class="flex-1 w-full overflow-hidden rounded-md" style="min-height: 6rem;">
+ <canvas ref="visualizer" class="w-full h-full"></canvas>
+ </div>
+ <p class="text-xs text-[var(--text-muted)] pt-0.5 md:pt-1 capitalize">${recordingMode}</p>
+ </div>
+ </div>
+ <div v-if="!isRecording && audioBlobURL" class="w-full mb-3 md:mb-4">
+ <div class="audio-player-container">
+ <audio :src="audioBlobURL" controls class="w-full">
+ Your browser does not support the audio element.
+ </audio>
+ </div>
+ </div>
+
+ <div>
+ <div class="text-xl md:text-2xl font-mono text-[var(--text-accent)]">${formatTime(recordingTime)}</div>
+ <p class="text-xs md:text-sm text-[var(--text-muted)]">${ isRecording ? 'Recording in progress...' : 'Recording finished' }</p>
+ <!-- Real-time file size display -->
+ <div v-if="isRecording && estimatedFileSize > 0" class="mt-1.5">
+ <p class="text-xs text-[var(--text-muted)]">
+ Estimated size: <span class="font-mono">${formatFileSize(estimatedFileSize)}</span>
+ <span v-if="actualBitrate > 0" class="ml-2">
+ (${Math.round(actualBitrate / 1000)}kbps)
+ </span>
+ </p>
+ <!-- Size warning indicator -->
+ <div v-if="estimatedFileSize > (maxRecordingMB * 1024 * 1024 * 0.8)" class="mt-0.5">
+ <div class="flex items-center text-xs text-amber-600 dark:text-amber-400">
+ <i class="fas fa-exclamation-triangle mr-1"></i>
+ <span v-text="t('help.approachingLimit', { limit: maxRecordingMB })"></span>
+ </div>
+ </div>
+ </div>
+
+ <!-- Mobile Background Recording Warning - Below timer -->
+ <div v-if="isRecording && isMobileDevice"
+ class="mt-2 p-2 bg-amber-50 dark:bg-amber-900 dark:bg-opacity-20 border border-amber-300 dark:border-amber-700 rounded">
+ <div class="flex items-start gap-1.5 text-left">
+ <i class="fas fa-exclamation-triangle text-amber-600 dark:text-amber-400 flex-shrink-0 text-xs" style="margin-top: 2px;"></i>
+ <div class="flex-1 min-w-0">
+ <div class="text-xs text-amber-800 dark:text-amber-200 leading-snug">
+ <strong class="font-semibold">Keep this app visible!</strong>
+ <span class="block text-[10px] mt-0.5">Recording pauses if minimized or screen locked.</span>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Scrollable Content Area: Notes + Actions -->
+ <div class="flex-1 min-h-0 overflow-y-auto flex flex-col">
+ <!-- Middle: Notepad (flexible height) -->
+ <div class="flex-1 p-3 md:p-6 flex flex-col" style="min-height: 200px;">
+ <label for="recordingNotes" class="block text-sm font-medium text-[var(--text-secondary)] mb-1.5 flex-shrink-0">
+ <i class="fas fa-pencil-alt mr-1"></i>
+ Recording Notes (Markdown)
+ </label>
+ <div class="flex-1 recording-notes-editor" style="min-height: 150px;">
+ <textarea ref="recordingNotesEditor" v-model="recordingNotes"
+ class="w-full h-full bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg p-2 md:p-3 text-sm focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)] resize-none"
+ :placeholder="t('form.notesPlaceholder')"></textarea>
+ </div>
+ </div>
+
+ <!-- Bottom: Action Buttons -->
+ <div class="flex-shrink-0 p-3 md:p-6 bg-[var(--bg-tertiary)] border-t border-[var(--border-primary)]">
+ <div v-if="isRecording" class="text-center">
+ <button @click="stopRecording"
+ class="px-6 md:px-8 py-2.5 md:py-3 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors animate-pulse text-sm md:text-base">
+ <i class="fas fa-stop mr-2"></i>Stop Recording
+ </button>
+ </div>
+ <div v-if="!isRecording && audioBlobURL" class="flex flex-col gap-3 md:gap-4">
+ <!-- Tag Selection -->
+ <div>
+ <label for="recordingTagSelect" class="block text-sm font-medium text-[var(--text-secondary)] mb-1.5 md:mb-2">
+ <i class="fas fa-tags mr-1"></i>
+ Select Tags (optional, in priority order)
+ </label>
+
+ <!-- Selected Tags Display - Compact -->
+ <div v-if="selectedTags.length > 0" class="mb-2">
+ <div class="p-1.5 bg-[var(--bg-tertiary)] rounded-md border border-[var(--border-secondary)] max-h-16 overflow-y-auto">
+ <div class="flex flex-wrap gap-1">
+ <span v-for="(tag, index) in selectedTags" :key="tag.id"
+ class="inline-flex items-center px-1.5 py-0.5 rounded-full text-[11px] font-medium text-white"
+ :style="{ backgroundColor: tag.color }">
+ <span class="opacity-75 mr-0.5 text-[9px]">${index + 1}.</span>
+ <span>${tag.name}</span>
+ <button @click="removeTagFromSelection(tag.id)"
+ class="ml-1 hover:opacity-100 opacity-70">
+ <i class="fas fa-times" style="font-size: 9px;"></i>
+ </button>
+ </span>
+ </div>
+ </div>
+ </div>
+
+ <!-- Tag Selection Container - Compact -->
+ <div v-if="availableTags.filter(tag => !selectedTagIds.includes(tag.id)).length > 0"
+ class="border border-[var(--border-secondary)] rounded-md bg-[var(--bg-tertiary)] p-2">
+ <!-- Search Filter -->
+ <div class="mb-1.5">
+ <div class="relative">
+ <input v-model="uploadTagSearchFilter"
+ type="text"
+ :placeholder="t('tagsModal.searchTags')"
+ class="w-full px-2 py-1 pl-6 text-xs bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">
+ <i class="fas fa-search absolute left-2 top-1/2 transform -translate-y-1/2 text-[var(--text-muted)]" style="font-size: 9px;"></i>
+ <button v-if="uploadTagSearchFilter"
+ @click="uploadTagSearchFilter = ''"
+ class="absolute right-2 top-1/2 transform -translate-y-1/2 text-[var(--text-muted)] hover:text-[var(--text-primary)]">
+ <i class="fas fa-times" style="font-size: 9px;"></i>
+ </button>
+ </div>
+ </div>
+ <!-- Available Tags Grid -->
+ <div v-if="filteredAvailableTagsForUpload.length > 0"
+ class="overflow-y-auto"
+ style="max-height: 100px;">
+ <div class="grid grid-cols-2 gap-1">
+ <button v-for="tag in filteredAvailableTagsForUpload"
+ :key="tag.id"
+ @click="addTagToSelection(tag.id)"
+ class="group flex items-center justify-between px-1.5 py-1 rounded border border-[var(--border-secondary)] hover:border-[var(--border-focus)] bg-[var(--bg-primary)] hover:bg-[var(--bg-secondary)] transition-all">
+ <div class="flex items-center gap-1 min-w-0">
+ <span class="w-2 h-2 rounded-full flex-shrink-0"
+ :style="{ backgroundColor: tag.color || '#6B7280' }"></span>
+ <span class="text-[11px] text-[var(--text-primary)] truncate" v-text="tag.name"></span>
+ </div>
+ <i class="fas fa-plus text-[var(--text-muted)] group-hover:text-[var(--text-accent)] transition-colors" style="font-size: 9px;"></i>
+ </button>
+ </div>
+ </div>
+ <div v-else class="py-2 text-center">
+ <p class="text-[11px] text-[var(--text-muted)]">
+ <i class="fas fa-search mr-1" style="font-size: 9px;"></i>
+ No matching tags
+ </p>
+ </div>
+ </div>
+ <!-- Empty States -->
+ <div v-else-if="availableTags.length === 0"
+ class="p-2 bg-[var(--bg-tertiary)] rounded-md border border-[var(--border-secondary)]">
+ <p class="text-xs text-[var(--text-muted)] text-center">
+ <i class="fas fa-info-circle mr-1" style="font-size: 10px;"></i>
+ <span v-text="t('help.noTagsCreated')"></span> <a href="/account#tags" class="text-[var(--text-accent)] hover:underline" v-text="t('help.createTags')"></a>
+ </p>
+ </div>
+ <div v-else class="p-2 bg-[var(--bg-tertiary)] rounded-md border border-[var(--border-secondary)]">
+ <p class="text-xs text-[var(--text-muted)] text-center">
+ <i class="fas fa-check-circle mr-1" style="font-size: 10px;"></i>
+ All tags selected
+ </p>
+ </div>
+
+ <p v-if="selectedTags.some(tag => tag.custom_prompt)" class="text-xs text-[var(--text-muted)] mt-1">
+ <i class="fas fa-info-circle mr-1 text-[var(--text-accent)]"></i>
+ Selected tags include custom summary prompts
+ </p>
+ <p v-if="selectedTags.length > 0 && useAsrEndpoint && selectedTags.some(tag => tag.default_language || tag.default_min_speakers || tag.default_max_speakers)"
+ class="text-xs text-[var(--text-muted)] mt-1">
+ <i class="fas fa-cog mr-1 text-[var(--text-accent)]"></i>
+ First tag's ASR settings will be applied: ${selectedTags[0].name}
+ </p>
+ </div>
+
+ <!-- Advanced Options for ASR (collapsible) -->
+ <div v-if="useAsrEndpoint">
+ <button @click="showAdvancedOptions = !showAdvancedOptions"
+ class="w-full flex items-center justify-between px-3 py-2 bg-[var(--bg-tertiary)] rounded-md hover:bg-[var(--bg-accent)] transition-colors text-xs font-medium">
+ <span class="flex items-center gap-2 text-[var(--text-secondary)]">
+ <i class="fas fa-cog text-[var(--text-muted)]"></i>
+ <span v-text="t('help.advancedAsrOptions')"></span>
+ </span>
+ <i :class="['fas text-[var(--text-muted)]', showAdvancedOptions ? 'fa-chevron-up' : 'fa-chevron-down']"></i>
+ </button>
+
+ <div v-if="showAdvancedOptions" class="mt-2 p-3 bg-[var(--bg-tertiary)] rounded-md border border-[var(--border-secondary)] space-y-3">
+ <div>
+ <label for="recordingAsrLanguage" class="block text-xs font-medium text-[var(--text-secondary)] mb-1">
+ Language
+ </label>
+ <select id="recordingAsrLanguage" v-model="asrLanguage"
+ class="w-full px-2 py-1 bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)] text-xs">
+ <option v-for="lang in languageOptions" :key="lang.value" :value="lang.value" v-text="lang.label"></option>
+ </select>
+ </div>
+
+ <div class="grid grid-cols-2 gap-3">
+ <div>
+ <label for="recordingAsrMinSpeakers" class="block text-xs font-medium text-[var(--text-secondary)] mb-1" v-text="t('form.minSpeakers')">
+ </label>
+ <input type="number" id="recordingAsrMinSpeakers" v-model="asrMinSpeakers"
+ min="1" max="20" :placeholder="t('form.auto')"
+ class="w-full px-2 py-1 bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)] text-xs">
+ </div>
+
+ <div>
+ <label for="recordingAsrMaxSpeakers" class="block text-xs font-medium text-[var(--text-secondary)] mb-1" v-text="t('form.maxSpeakers')">
+ </label>
+ <input type="number" id="recordingAsrMaxSpeakers" v-model="asrMaxSpeakers"
+ min="1" max="20" :placeholder="t('form.auto')"
+ class="w-full px-2 py-1 bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)] text-xs">
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Upload/Discard Buttons -->
+ <div class="flex flex-col sm:flex-row gap-3 justify-center">
+ <button @click="uploadRecordedAudio"
+ class="flex-1 px-6 py-3 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors flex items-center justify-center gap-2">
+ <i class="fas fa-upload"></i>
+ <span v-text="t('help.uploadRecordingNotes')"></span>
+ </button>
+ <button @click="discardRecording"
+ class="px-6 py-3 bg-[var(--bg-danger)] text-white rounded-lg hover:bg-[var(--bg-danger-hover)] transition-colors flex items-center justify-center gap-2">
+ <i class="fas fa-trash"></i>
+ <span v-text="t('help.discard')"></span>
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Recording Detail View -->
+ <div v-else-if="currentView === 'detail' && selectedRecording" class="flex-1 flex flex-col overflow-hidden">
+ <!-- Mobile View -->
+ <div v-if="isMobileScreen" class="flex-1 flex flex-col overflow-hidden">
+ <!-- Mobile Header -->
+ <div class="bg-[var(--bg-secondary)] border-b border-[var(--border-primary)] p-4 flex-shrink-0">
+ <div @click="isMetadataExpanded = !isMetadataExpanded" class="cursor-pointer">
+ <div class="flex items-start justify-between">
+ <div class="flex-1 min-w-0">
+ <h1 class="text-lg font-bold text-[var(--text-primary)] truncate">
+ ${selectedRecording.title || 'Untitled Recording'}
+ </h1>
+ <p class="text-sm text-[var(--text-muted)] truncate">
+ ${selectedRecording.participants || t('help.noParticipants')}
+ </p>
+ <!-- Tags and Share Status -->
+ <div v-if="getRecordingTags(selectedRecording).length > 0 || selectedRecording.is_shared || selectedRecording.shared_with_count > 0 || selectedRecording.public_share_count > 0" class="flex flex-wrap gap-1 mt-2">
+ <!-- Tags -->
+ <button v-for="tag in getRecordingTags(selectedRecording)" :key="tag.id"
+ @click.stop="filterByTag(tag)"
+ class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium text-white hover:opacity-80 transition-all cursor-pointer"
+ :style="{ backgroundColor: tag.color }"
+ :title="(tag.group_id ? '👥 Group Tag: ' : 'Filter by ') + tag.name">
+ <i v-if="tag.group_id" class="fas fa-users mr-1"></i>
+ <i v-else class="fas fa-tag mr-1"></i>
+ <span v-text="tag.name"></span>
+ </button>
+
+ <!-- Shared Status Badges -->
+ <span v-if="selectedRecording.is_shared"
+ class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-purple-500 text-white">
+ <i class="fas fa-arrow-down mr-1"></i>
+ Shared
+ </span>
+
+ <span v-if="!selectedRecording.is_shared && selectedRecording.shared_with_count > 0"
+ class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-indigo-500 text-white">
+ <i class="fas fa-arrow-up mr-1"></i>
+ ${selectedRecording.shared_with_count}
+ </span>
+
+ <span v-if="!selectedRecording.is_shared && selectedRecording.public_share_count > 0"
+ class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-teal-500 text-white">
+ <i class="fas fa-globe mr-1"></i>
+ ${selectedRecording.public_share_count}
+ </span>
+ </div>
+ </div>
+ <i :class="['fas', 'fa-chevron-down', 'transition-transform', { 'rotate-180': isMetadataExpanded }]"></i>
+ </div>
+ </div>
+ <!-- Expandable Metadata and Actions -->
+ <div v-if="isMetadataExpanded" class="mt-4 space-y-4">
+ <div class="space-y-2 text-sm text-[var(--text-muted)]">
+ <!-- Combined metadata in horizontal flow -->
+ <div class="flex flex-wrap items-center gap-x-4 gap-y-2">
+ <!-- Meeting date -->
+ <div class="flex items-center gap-2">
+ <i class="fas fa-calendar text-[var(--text-accent)]"></i>
+ <span>${selectedRecording.meeting_date ? formatDisplayDate(selectedRecording.meeting_date) : 'No date set'}</span>
+ </div>
+
+ <!-- Other metadata (upload date, file size, etc.) -->
+ <template v-if="activeRecordingMetadata" v-for="(item, index) in activeRecordingMetadata" :key="index">
+ <!-- Skip tags as they're shown in header -->
+ <span v-if="!item.isTagItem" class="flex items-center gap-1.5">
+ <i :class="item.icon"></i>
+ <span :title="item.fullText || item.text">${item.text}</span>
+ </span>
+ </template>
+ </div>
+
+ <!-- Status badge (if not completed) -->
+ <div v-if="selectedRecording.status !== 'COMPLETED'" class="flex items-center gap-2">
+ <span :class="getStatusClass(selectedRecording.status)" class="status-badge">
+ ${formatStatus(selectedRecording.status)}
+ </span>
+ </div>
+ </div>
+ <!-- Action Buttons -->
+ <div class="flex items-center gap-2 overflow-x-auto pb-2">
+ <button @click="toggleInbox(selectedRecording)" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors" :class="selectedRecording.is_inbox ? 'text-blue-500' : ''" :title="selectedRecording.is_inbox ? t('sidebar.markAsRead') : t('sidebar.moveToInbox')"><i class="fas fa-inbox"></i></button>
+ <button @click="toggleHighlight(selectedRecording)" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors" :class="selectedRecording.is_highlighted ? 'text-yellow-500' : ''" :title="selectedRecording.is_highlighted ? t('sidebar.removeFromHighlighted') : t('sidebar.highlighted')"><i class="fas fa-star"></i></button>
+ <button @click="editRecording(selectedRecording)" v-if="selectedRecording.can_edit !== false" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors" :title="t('common.edit')"><i class="fas fa-edit"></i></button>
+ <button @click="editRecordingTags(selectedRecording)" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors" :title="t('tags.title')"><i class="fas fa-tags"></i></button>
+ <button @click="reprocessTranscription(selectedRecording.id)" v-if="selectedRecording && selectedRecording.can_edit !== false && (selectedRecording.status === 'COMPLETED' || selectedRecording.status === 'FAILED')" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors" :title="useAsrEndpoint ? 'Reprocess with ASR' : 'Reprocess transcription'"><i class="fas fa-redo-alt"></i></button>
+ <button @click="reprocessSummary(selectedRecording.id)" v-if="selectedRecording && selectedRecording.can_edit !== false && (selectedRecording.status === 'COMPLETED' || selectedRecording.status === 'FAILED')" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors" :title="t('buttons.reprocessSummary')"><i class="fas fa-sync-alt"></i></button>
+ <button @click="confirmReset(selectedRecording)" v-if="['PENDING', 'PROCESSING', 'SUMMARIZING', 'FAILED'].includes(selectedRecording.status)" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors text-orange-500" :title="t('buttons.resetStuckProcessing')"><i class="fas fa-undo"></i></button>
+ <button @click="openSpeakerModal" v-if="selectedRecording.transcription && useAsrEndpoint" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors" :title="t('buttons.identifySpeakers')"><i class="fas fa-user-tag"></i></button>
+ <button @click="openShareModal(selectedRecording)" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors" :title="t('buttons.shareRecording')"><i class="fas fa-share-alt"></i></button>
+ <button v-if="enableInternalSharing" @click="openUnifiedShareModal(selectedRecording)" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors text-blue-500" title="Share with Users"><i class="fas fa-users"></i></button>
+ <button v-if="canDeleteRecordings" @click="confirmDelete(selectedRecording)" class="p-2 rounded-lg hover:bg-[var(--bg-danger-light)] text-[var(--text-danger)] transition-colors"><i class="fas fa-trash"></i></button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Mobile Audio Player -->
+ <div class="bg-[var(--bg-secondary)] p-4 border-b border-[var(--border-primary)] flex-shrink-0">
+ <div class="audio-player-container">
+ <!-- Show message if audio has been deleted -->
+ <div v-if="selectedRecording.audio_deleted_at"
+ class="bg-[var(--bg-tertiary)] border border-[var(--border-primary)] text-[var(--text-muted)] px-4 py-3 rounded-lg flex items-center gap-2 text-sm">
+ <i class="fas fa-info-circle"></i>
+ <span v-text="t('help.audioDeletedMessage')"></span>
+ </div>
+ <!-- Show audio player if audio is available -->
+ <audio v-else
+ controls
+ :src="'/audio/' + selectedRecording.id"
+ :volume="playerVolume"
+ @volumechange="onPlayerVolumeChange"
+ class="w-full">
+ Your browser does not support the audio element.
+ </audio>
+ </div>
+ </div>
+
+ <!-- Mobile Tab Navigation -->
+ <div class="flex-shrink-0 bg-[var(--bg-tertiary)] border-b border-[var(--border-primary)] flex overflow-x-auto">
+ <button @click="mobileTab = 'transcript'" :class="['flex-1 px-4 py-3 text-sm font-medium transition-colors', mobileTab === 'transcript' ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]' : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]']" v-text="t('transcription.title')"></button>
+ <button @click="mobileTab = 'summary'" :class="['flex-1 px-4 py-3 text-sm font-medium transition-colors', mobileTab === 'summary' ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]' : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]']" v-text="t('summary.title')"></button>
+ <button @click="mobileTab = 'notes'" :class="['flex-1 px-4 py-3 text-sm font-medium transition-colors', mobileTab === 'notes' ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]' : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]']" v-text="t('notes.title')"></button>
+ <button @click="mobileTab = 'chat'" :class="['flex-1 px-4 py-3 text-sm font-medium transition-colors', mobileTab === 'chat' ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]' : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]']" v-text="t('chat.title')"></button>
+ <button v-if="selectedRecording.events && selectedRecording.events.length > 0"
+ @click="mobileTab = 'events'"
+ :class="['flex-1 px-4 py-3 text-sm font-medium transition-colors whitespace-nowrap', mobileTab === 'events' ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]' : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]']">
+ <i class="fas fa-calendar-alt mr-1"></i>${ t('events.title') } (${ selectedRecording.events.length })
+ </button>
+ </div>
+
+ <!-- Mobile Tab Content -->
+ <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 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>
+ </div>
+ <button @click="copyTranscription" class="copy-btn" title="Copy transcript"><i class="fas fa-copy"></i></button>
+ <button @click="downloadTranscript" v-if="selectedRecording && selectedRecording.transcription" class="copy-btn" title="Download transcript with template"><i class="fas fa-download"></i></button>
+ <button @click="openTranscriptionEditor" v-if="selectedRecording && selectedRecording.transcription" class="copy-btn" title="Edit transcript"><i class="fas fa-edit"></i></button>
+ </div>
+ <div class="flex-grow overflow-y-auto mobile-content-box">
+ <div v-if="selectedRecording.status === 'PROCESSING'" class="text-center py-8">
+ <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
+ <p class="mt-2 text-[var(--text-muted)]" v-text="t('help.processingTranscription')"></p>
+ </div>
+ <div v-else-if="!selectedRecording.transcription" class="text-center py-8">
+ <i class="fas fa-file-text text-3xl text-[var(--text-muted)] mb-3"></i>
+ <p class="text-[var(--text-muted)]" v-text="t('transcription.noTranscription')"></p>
+ </div>
+ <div v-else>
+ <div v-if="!processedTranscription.hasDialogue || transcriptionViewMode === 'simple'" class="transcription-simple-view">
+ <div v-if="processedTranscription.hasDialogue">
+ <div v-for="segment in processedTranscription.simpleSegments" :key="segment.startTime || Math.random()" class="speaker-segment" @click="seekAudioFromEvent" :data-start-time="segment.startTime">
+ <div v-if="segment.showSpeaker" :class="['speaker-tablet', segment.color]">${segment.speaker}</div>
+ <div class="speaker-text">${segment.sentence}</div>
+ </div>
+ </div>
+ <div v-else>
+ <div v-if="processedTranscription.simpleSegments && processedTranscription.simpleSegments.length > 0">
+ <div v-for="segment in processedTranscription.simpleSegments" :key="segment.startTime || Math.random()" class="transcript-segment cursor-pointer hover:bg-[var(--bg-accent-hover)] p-2 rounded transition-colors" @click="seekAudioFromEvent" :data-start-time="segment.startTime">${segment.sentence}</div>
+ </div>
+ <div v-else class="whitespace-pre-wrap">${processedTranscription.content}</div>
+ </div>
+ </div>
+ <div v-else-if="transcriptionViewMode === 'bubble'" class="transcription-with-speakers">
+ <div v-for="(row, rowIndex) in processedTranscription.bubbleRows" :key="`${selectedRecording.id}-bubble-row-${rowIndex}`" :class="['bubble-row', row.isMe ? 'speaker-me' : '']">
+ <div v-for="bubble in row.bubbles" :key="bubble.startTime || Math.random()" :class="['speaker-bubble', bubble.color, row.isMe ? 'speaker-me' : '']" @click="seekAudioFromEvent" :data-start-time="bubble.startTime">
+ <div class="speaker-bubble-content">${bubble.sentence}</div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </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 pr-3">
+ <button @click="copySummary" class="copy-btn" :title="t('buttons.copySummary')"><i class="fas fa-copy"></i></button>
+ <button @click="downloadSummary" class="copy-btn" :title="t('buttons.downloadAsWord')"><i class="fas fa-download"></i></button>
+ <button @click="toggleEditSummary" class="copy-btn" :title="t('buttons.editSummary')"><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">
+ <div class="markdown-editor-container flex-1">
+ <textarea ref="summaryMarkdownEditor" v-model="selectedRecording.summary"></textarea>
+ </div>
+ <div class="flex justify-end gap-2 mt-2">
+ <button @click="cancelEditSummary" class="px-3 py-1 text-sm bg-[var(--bg-secondary)] text-[var(--text-secondary)] border border-[var(--border-secondary)] rounded hover:bg-[var(--bg-tertiary)]" v-text="t('common.cancel')"></button>
+ <button @click="saveEditSummary" class="px-3 py-1 text-sm bg-[var(--bg-button)] text-[var(--text-button)] rounded hover:bg-[var(--bg-button-hover)]" v-text="t('common.save')"></button>
+ </div>
+ </div>
+ <div v-else>
+ <div v-if="selectedRecording.status === 'SUMMARIZING'" class="text-center py-8">
+ <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
+ <p class="mt-2 text-[var(--text-muted)]" v-text="t('help.generatingSummary')"></p>
+ </div>
+ <div v-else-if="!selectedRecording.summary" class="text-center py-8">
+ <i class="fas fa-file-alt text-3xl text-[var(--text-muted)] mb-3"></i>
+ <p class="text-[var(--text-muted)] mb-4" v-text="t('summary.noSummary')"></p>
+ <button @click="generateSummary"
+ class="px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 text-white font-medium rounded-lg shadow-lg hover:shadow-xl hover:from-blue-700 hover:to-purple-700 transition-all duration-200 transform hover:scale-105">
+ <i class="fas fa-magic mr-2"></i>Generate Summary
+ </button>
+ </div>
+ <div v-else class="summary-box h-full" v-html="selectedRecording.summary_html || selectedRecording.summary"></div>
+ </div>
+ </div>
+ </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 pr-3">
+ <button @click="copyNotes" class="copy-btn" :title="t('buttons.copyNotes')"><i class="fas fa-copy"></i></button>
+ <button @click="downloadNotes" class="copy-btn" :title="t('buttons.downloadAsWord')"><i class="fas fa-download"></i></button>
+ <button @click="toggleEditNotes" class="copy-btn" :title="t('buttons.editNotes')"><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">
+ <div class="markdown-editor-container flex-1">
+ <textarea ref="notesMarkdownEditor" v-model="selectedRecording.notes"></textarea>
+ </div>
+ <div class="flex justify-end gap-2 mt-2">
+ <button @click="cancelEditNotes" class="px-3 py-1 text-sm bg-[var(--bg-secondary)] text-[var(--text-secondary)] border border-[var(--border-secondary)] rounded hover:bg-[var(--bg-tertiary)]" v-text="t('common.cancel')"></button>
+ <button @click="saveEditNotes" class="px-3 py-1 text-sm bg-[var(--bg-button)] text-[var(--text-button)] rounded hover:bg-[var(--bg-button-hover)]" v-text="t('common.save')"></button>
+ </div>
+ </div>
+ <div v-else @click="clickToEditNotes">
+ <div v-if="!selectedRecording.notes" class="text-center py-8 cursor-pointer hover:text-[var(--text-secondary)]">
+ <i class="fas fa-sticky-note text-3xl text-[var(--text-muted)] mb-3"></i>
+ <p class="text-[var(--text-muted)]" v-text="t('help.clickToAddNotes')"></p>
+ </div>
+ <div v-else class="notes-box h-full" v-html="selectedRecording.notes_html || selectedRecording.notes"></div>
+ </div>
+ </div>
+ </div>
+ <!-- Chat Panel -->
+ <div v-if="mobileTab === 'chat'" class="h-full flex flex-col rounded-lg border border-[var(--border-primary)] overflow-hidden relative">
+ <!-- Clear button - fixed at top right -->
+ <button v-if="chatMessages.length > 0"
+ @click="clearChat"
+ class="absolute top-2 right-2 p-1 text-[var(--text-muted)] opacity-60 hover:opacity-100 hover:text-[var(--text-danger)] rounded transition-all duration-200 z-20"
+ title="Clear chat">
+ <i class="fas fa-times text-xs"></i>
+ </button>
+
+ <div ref="chatMessagesRef" class="flex-1 overflow-y-auto p-4 space-y-4 bg-[var(--bg-secondary)]">
+ <div v-if="chatMessages.length === 0" class="text-center py-8">
+ <i class="fas fa-robot text-3xl text-[var(--text-muted)] mb-3"></i>
+ <p class="text-[var(--text-muted)]" v-text="t('help.askAboutTranscription')"></p>
+ </div>
+ <div v-for="(message, index) in chatMessages" :key="index"
+ :class="['message relative group', message.role === 'user' ? 'user-message ml-auto' : 'ai-message',
+ message.role === 'assistant' ? 'pr-10' : '']">
+ <!-- Copy button for assistant messages -->
+ <button v-if="message.role === 'assistant'"
+ @click="copyMessage(message.content, $event)"
+ class="absolute top-2 right-2 p-1 text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-tertiary)] rounded transition-all duration-200"
+ :title="t('buttons.copyMessage')">
+ <i class="fas fa-copy text-sm"></i>
+ </button>
+ <!-- Show thinking content if available -->
+ <div v-if="message.thinking && message.role === 'assistant'" class="mb-2">
+ <button @click="message.thinkingExpanded = !message.thinkingExpanded"
+ class="text-xs text-[var(--text-muted)] hover:text-[var(--text-secondary)] flex items-center gap-1">
+ <i :class="['fas', message.thinkingExpanded ? 'fa-chevron-down' : 'fa-chevron-right']"></i>
+ <span v-text="t('help.modelReasoning')"></span>
+ <span class="text-[var(--text-muted)]">(${message.thinking.split('\n').length} lines)</span>
+ </button>
+ <div v-if="message.thinkingExpanded"
+ class="mt-2 p-3 bg-[var(--bg-tertiary)] border border-[var(--border-secondary)] rounded-lg text-xs text-[var(--text-muted)] max-h-64 overflow-y-auto">
+ <pre class="whitespace-pre-wrap font-mono">${message.thinking}</pre>
+ </div>
+ </div>
+ <!-- Main message content -->
+ <div v-if="message.html" v-html="message.html"></div>
+ <div v-else class="whitespace-pre-wrap">${message.content}</div>
+ </div>
+ <div v-if="isChatLoading" class="ai-message">
+ <i class="fas fa-spinner fa-spin mr-2"></i> Thinking...
+ </div>
+ </div>
+ <div class="border-t border-[var(--border-primary)] p-4 bg-[var(--bg-tertiary)]">
+ <div class="flex gap-2">
+ <textarea v-model="chatInput" @keydown="handleChatKeydown" :disabled="isChatLoading || selectedRecording.status !== 'COMPLETED'" :placeholder="t('chat.placeholder')" class="flex-1 px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)] text-sm" rows="2"></textarea>
+ <button @click="sendChatMessage" :disabled="!chatInput.trim() || isChatLoading || selectedRecording.status !== 'COMPLETED'" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
+ <i class="fas fa-paper-plane"></i>
+ </button>
+ </div>
+ </div>
+ </div>
+ <!-- Events Panel (Mobile) -->
+ <div v-if="mobileTab === 'events' && selectedRecording.events && selectedRecording.events.length > 0" class="h-full flex flex-col space-y-4">
+ <div class="flex items-center justify-end gap-2 flex-shrink-0 pr-3">
+ <button @click="downloadICS" v-if="selectedRecording.events && selectedRecording.events.length > 0"
+ class="copy-btn"
+ :title="t('buttons.exportCalendar')">
+ <i class="fas fa-calendar-plus"></i>
+ </button>
+ </div>
+ <div class="flex-grow overflow-y-auto mobile-content-box">
+ <div class="space-y-3">
+ <div v-for="event in selectedRecording.events" :key="event.id"
+ class="bg-[var(--bg-tertiary)] rounded-lg p-3 border border-[var(--border-primary)]">
+ <div class="flex justify-between items-start mb-2">
+ <div class="flex-1">
+ <h3 class="text-base font-semibold text-[var(--text-primary)] mb-1">
+ <i class="fas fa-calendar-check mr-2 text-[var(--text-accent)] text-sm"></i>
+ ${ event.title }
+ </h3>
+ <p v-if="event.description" class="text-xs text-[var(--text-secondary)] mb-2">
+ ${ event.description }
+ </p>
+ </div>
+ <button @click="downloadEventICS(event)"
+ class="px-2 py-1 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors text-xs flex items-center gap-1"
+ :title="t('events.addToCalendar')">
+ <i class="fas fa-download text-xs"></i>
+ <span v-text="t('events.add')"></span>
+ </button>
+ </div>
+ <div class="grid grid-cols-1 gap-2 text-xs">
+ <div class="flex items-center text-[var(--text-muted)]">
+ <i class="fas fa-clock mr-2 text-[var(--text-accent)]"></i>
+ <span>
+ ${ formatEventDateTime(event.start_datetime) }
+ <template v-if="event.end_datetime">
+ - ${ formatEventDateTime(event.end_datetime, true) }
+ </template>
+ </span>
+ </div>
+ <div v-if="event.location" class="flex items-center text-[var(--text-muted)]">
+ <i class="fas fa-map-marker-alt mr-2 text-[var(--text-accent)]"></i>
+ <span>${ event.location }</span>
+ </div>
+ <div v-if="event.attendees && event.attendees.length > 0" class="flex items-start text-[var(--text-muted)]">
+ <i class="fas fa-users mr-2 text-[var(--text-accent)] mt-0.5"></i>
+ <div class="flex-1">
+ <span v-for="(attendee, index) in event.attendees" :key="index"
+ class="inline-block bg-[var(--bg-secondary)] px-2 py-0.5 rounded mr-1 mb-1">
+ ${ attendee }
+ </span>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ <!-- Desktop View -->
+ <div v-else class="flex-1 flex flex-col overflow-hidden">
+ <!-- Recording Header -->
+ <div class="bg-[var(--bg-secondary)] border-b border-[var(--border-primary)] p-6 flex-shrink-0">
+ <div class="flex flex-col">
+ <div class="flex items-start justify-between">
+ <div class="flex-1 min-w-0">
+ <h1 class="text-2xl font-bold text-[var(--text-primary)] mb-2">
+ ${selectedRecording.title || 'Untitled Recording'}
+ </h1>
+ </div>
+
+ <!-- Action Buttons -->
+ <div class="flex items-center gap-2 ml-4">
+ <button @click="toggleInbox(selectedRecording)"
+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"
+ :class="selectedRecording.is_inbox ? 'text-blue-500' : ''"
+ :title="selectedRecording.is_inbox ? 'Mark as Read' : 'Move to Inbox'">
+ <i class="fas fa-inbox"></i>
+ </button>
+ <button @click="toggleHighlight(selectedRecording)"
+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"
+ :class="selectedRecording.is_highlighted ? 'text-yellow-500' : ''"
+ :title="selectedRecording.is_highlighted ? 'Remove Highlight' : 'Highlight'">
+ <i class="fas fa-star"></i>
+ </button>
+ <button @click="editRecording(selectedRecording)"
+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors">
+ <i class="fas fa-edit"></i>
+ </button>
+ <button @click="editRecordingTags(selectedRecording)"
+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"
+ :title="t('buttons.editTags')">
+ <i class="fas fa-tags"></i>
+ </button>
+ <button @click="reprocessTranscription(selectedRecording.id)" v-if="selectedRecording && selectedRecording.can_edit !== false && (selectedRecording.status === 'COMPLETED' || selectedRecording.status === 'FAILED')"
+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"
+ :title="useAsrEndpoint ? 'Reprocess with ASR' : 'Reprocess transcription'">
+ <i class="fas fa-redo-alt"></i>
+ </button>
+ <button @click="reprocessSummary(selectedRecording.id)" v-if="selectedRecording && selectedRecording.can_edit !== false && (selectedRecording.status === 'COMPLETED' || selectedRecording.status === 'FAILED')"
+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"
+ :title="t('buttons.reprocessSummary')">
+ <i class="fas fa-sync-alt"></i>
+ </button>
+ <button @click="confirmReset(selectedRecording)" v-if="['PENDING', 'PROCESSING', 'SUMMARIZING', 'FAILED'].includes(selectedRecording.status)"
+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors text-orange-500"
+ :title="t('buttons.resetStuckProcessing')">
+ <i class="fas fa-undo"></i>
+ </button>
+ <button @click="openSpeakerModal" v-if="selectedRecording.transcription && useAsrEndpoint"
+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"
+ :title="t('buttons.identifySpeakers')">
+ <i class="fas fa-user-tag"></i>
+ </button>
+ <button @click="openShareModal(selectedRecording)"
+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors"
+ :title="t('buttons.shareRecording')">
+ <i class="fas fa-share-alt"></i>
+ </button>
+ <button v-if="enableInternalSharing" @click="openUnifiedShareModal(selectedRecording)"
+ class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors text-blue-500"
+ title="Share with Users">
+ <i class="fas fa-users"></i>
+ </button>
+ <button v-if="canDeleteRecordings" @click="confirmDelete(selectedRecording)"
+ class="p-2 rounded-lg hover:bg-[var(--bg-danger-light)] text-[var(--text-danger)] transition-colors">
+ <i class="fas fa-trash"></i>
+ </button>
+ </div>
+ </div>
+
+ <!-- Metadata Row -->
+ <div class="flex flex-wrap items-center gap-x-6 gap-y-2 text-sm text-[var(--text-muted)] mt-2">
+ <!-- Shared Status Badges and Tags -->
+ <div v-if="selectedRecording.is_shared || selectedRecording.shared_with_count > 0 || selectedRecording.public_share_count > 0 || selectedRecording.has_group_tags || (selectedRecording.tags && selectedRecording.tags.length > 0)" class="flex items-center gap-1.5 flex-wrap">
+ <!-- Shared by someone else (INCOMING) -->
+ <span v-if="selectedRecording.is_shared"
+ class="inline-flex items-center justify-center w-5 h-5 text-[10px] font-medium rounded-full bg-purple-500 text-white cursor-help"
+ :title="t('sharing.sharedBy') + ' ' + (selectedRecording.owner_username || t('sharing.unknown'))">
+ <i class="fas fa-arrow-down" style="line-height: 1;"></i>
+ </span>
+
+ <!-- Group indicator (show for both owned and shared recordings with group tags) -->
+ <span v-if="selectedRecording.has_group_tags"
+ class="inline-flex items-center justify-center w-5 h-5 text-[10px] font-medium rounded-full bg-blue-500 text-white cursor-help"
+ :title="t('sharing.teamRecording')">
+ <i class="fas fa-users" style="line-height: 1;"></i>
+ </span>
+
+ <!-- Shared with others (OUTGOING) -->
+ <span v-if="!selectedRecording.is_shared && selectedRecording.shared_with_count > 0"
+ class="inline-flex items-center justify-center w-5 h-5 text-[10px] font-medium rounded-full bg-indigo-500 text-white cursor-help"
+ :title="t('sharing.sharedWith') + ' ' + selectedRecording.shared_with_count + ' ' + t('sharing.users')">
+ <i class="fas fa-arrow-up" style="line-height: 1;"></i>
+ </span>
+
+ <!-- Public link shares -->
+ <span v-if="!selectedRecording.is_shared && selectedRecording.public_share_count > 0"
+ class="inline-flex items-center justify-center w-5 h-5 text-[10px] font-medium rounded-full bg-teal-500 text-white cursor-help"
+ :title="selectedRecording.public_share_count + ' ' + t('sharing.publicLinksGenerated')">
+ <i class="fas fa-globe" style="line-height: 1;"></i>
+ </span>
+
+ <!-- Tags -->
+ <span v-for="tag in selectedRecording.tags" :key="tag.id"
+ class="inline-flex items-center px-2 py-0.5 text-xs font-medium rounded-full text-white"
+ :style="{ backgroundColor: tag.color || '#6B7280' }">
+ <i v-if="tag.group_id" class="fas fa-users mr-1 text-[10px]"></i>
+ ${tag.name}
+ </span>
+ </div>
+
+ <!-- Participants -->
+ <div class="flex items-center gap-2">
+ <i class="fas fa-users text-[var(--text-accent)]"></i>
+ <span v-if="!editingParticipants"
+ @click="toggleEditParticipants"
+ class="cursor-pointer hover:text-[var(--text-accent)] transition-colors">
+ ${selectedRecording.participants || t('help.noParticipants')}
+ </span>
+ <input v-else
+ v-model="selectedRecording.participants"
+ @blur="toggleEditParticipants"
+ @keyup.enter="toggleEditParticipants"
+ class="bg-transparent border-b border-[var(--border-secondary)] focus:border-[var(--border-focus)] outline-none px-1">
+ </div>
+
+ <!-- Meeting Date -->
+ <div class="flex items-center gap-2">
+ <i class="fas fa-calendar text-[var(--text-accent)]"></i>
+ <span v-if="!editingMeetingDate"
+ @click="toggleEditMeetingDate"
+ class="cursor-pointer hover:text-[var(--text-accent)] transition-colors">
+ ${selectedRecording.meeting_date ? formatDisplayDate(selectedRecording.meeting_date) : 'No date set'}
+ </span>
+ <input v-else
+ v-model="selectedRecording.meeting_date"
+ @blur="toggleEditMeetingDate"
+ @keyup.enter="toggleEditMeetingDate"
+ type="date"
+ class="bg-transparent border-b border-[var(--border-secondary)] focus:border-[var(--border-focus)] outline-none px-1">
+ </div>
+
+ <!-- Other Metadata -->
+ <div v-if="activeRecordingMetadata && activeRecordingMetadata.length > 0" class="flex flex-wrap items-center gap-x-6 gap-y-2">
+ <span v-for="(item, index) in activeRecordingMetadata" :key="index" class="flex items-center gap-1.5">
+ <i :class="item.icon"></i>
+ <span :title="item.fullText || item.text">${item.text}</span>
+ </span>
+ </div>
+
+ <!-- Status -->
+ <div v-if="selectedRecording.status !== 'COMPLETED'" class="flex items-center gap-2">
+ <span :class="getStatusClass(selectedRecording.status)" class="status-badge">
+ ${formatStatus(selectedRecording.status)}
+ </span>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Main Content Split View -->
+ <div id="mainContentColumns" class="flex-1 flex overflow-hidden">
+ <!-- Left Panel: Transcription -->
+ <div id="leftMainColumn" class="flex flex-col overflow-hidden" :style="{width: leftColumnWidth + '%'}">
+ <!-- Transcription Header -->
+ <div class="bg-[var(--bg-tertiary)] px-4 py-3 border-b border-[var(--border-primary)] flex items-center justify-between">
+ <h3 class="font-semibold flex items-center">
+ <i class="fas fa-file-text mr-2"></i>
+ <span v-text="t('transcription.title')"></span>
+ </h3>
+ <div class="flex items-center gap-2">
+ <!-- View Mode Toggle -->
+ <div v-if="processedTranscription.hasDialogue" class="view-mode-toggle">
+ <button @click="toggleTranscriptionViewMode"
+ :class="['toggle-button', transcriptionViewMode === 'simple' ? 'active' : '']">
+ <i class="fas fa-list"></i><span v-text="t('transcription.simple')"></span>
+ </button>
+ <button @click="toggleTranscriptionViewMode"
+ :class="['toggle-button', transcriptionViewMode === 'bubble' ? 'active' : '']">
+ <i class="fas fa-comments"></i><span v-text="t('transcription.bubble')"></span>
+ </button>
+ </div>
+
+ <!-- Copy Button -->
+ <button @click="copyTranscription"
+ class="copy-btn">
+ <i class="fas fa-copy mr-1"></i><span v-text="t('transcription.copy')"></span>
+ </button>
+ <!-- Download Button -->
+ <button @click="downloadTranscript"
+ v-if="selectedRecording && selectedRecording.transcription"
+ class="copy-btn"
+ title="Download transcript with template">
+ <i class="fas fa-download mr-1"></i><span v-text="t('transcription.download')"></span>
+ </button>
+ <!-- Edit Transcription Button -->
+ <button @click="openTranscriptionEditor"
+ v-if="selectedRecording && selectedRecording.transcription"
+ class="copy-btn">
+ <i class="fas fa-edit mr-1"></i><span v-text="t('transcription.edit')"></span>
+ </button>
+ </div>
+ </div>
+
+ <!-- Transcription Content -->
+ <div class="flex-1 overflow-y-auto p-4">
+ <div v-if="selectedRecording.status === 'PROCESSING'" class="text-center py-8">
+ <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
+ <p class="mt-2 text-[var(--text-muted)]" v-text="t('help.processingTranscription')"></p>
+ </div>
+
+ <div v-else-if="!selectedRecording.transcription" class="text-center py-8">
+ <i class="fas fa-file-text text-3xl text-[var(--text-muted)] mb-3"></i>
+ <p class="text-[var(--text-muted)]" v-text="t('transcription.noTranscription')"></p>
+ </div>
+
+ <!-- Speaker Legend (for dialogue transcriptions in bubble view only) -->
+ <div v-if="processedTranscription.hasDialogue && processedTranscription.speakers.length > 0 && transcriptionViewMode === 'bubble'"
+ :class="['speaker-legend', legendExpanded ? 'expanded' : '']">
+ <div class="speaker-legend-header" @click="legendExpanded = !legendExpanded">
+ <div class="speaker-legend-title">
+ <i class="fas fa-users"></i>
+ <span v-text="t('help.speakers')"></span>
+ <span class="speaker-count-indicator">(${processedTranscription.speakers.length})</span>
+ </div>
+ <i class="fas fa-chevron-down speaker-legend-toggle"></i>
+ </div>
+ <div class="speaker-legend-content">
+ <div v-for="(speaker, index) in processedTranscription.speakers"
+ :key="`${selectedRecording.id}-speaker-legend-${index}`"
+ :class="['speaker-legend-item', speaker.color]">
+ <span class="speaker-name">${speaker.name}</span>
+ </div>
+ </div>
+ </div>
+
+ <!-- Transcription Display -->
+ <div v-if="selectedRecording.transcription">
+ <!-- Simple View -->
+ <div v-if="!processedTranscription.hasDialogue || transcriptionViewMode === 'simple'"
+ class="transcription-simple-view">
+ <div v-if="processedTranscription.hasDialogue">
+ <div v-for="segment in processedTranscription.simpleSegments"
+ :key="segment.startTime || Math.random()"
+ class="speaker-segment"
+ @click="seekAudioFromEvent"
+ :data-start-time="segment.startTime">
+ <div v-if="segment.showSpeaker"
+ :class="['speaker-tablet', segment.color]">
+ ${segment.speaker}
+ </div>
+ <div class="speaker-text">
+ ${segment.sentence}
+ </div>
+ </div>
+ </div>
+ <div v-else>
+ <div v-if="processedTranscription.simpleSegments && processedTranscription.simpleSegments.length > 0">
+ <div v-for="segment in processedTranscription.simpleSegments"
+ :key="segment.startTime || Math.random()"
+ class="transcript-segment cursor-pointer hover:bg-[var(--bg-accent-hover)] p-2 rounded transition-colors"
+ @click="seekAudioFromEvent"
+ :data-start-time="segment.startTime">
+ ${segment.sentence}
+ </div>
+ </div>
+ <div v-else class="whitespace-pre-wrap">
+ ${processedTranscription.content}
+ </div>
+ </div>
+ </div>
+
+ <!-- Bubble View -->
+ <div v-else-if="transcriptionViewMode === 'bubble'"
+ class="transcription-with-speakers">
+ <div v-for="(row, rowIndex) in processedTranscription.bubbleRows"
+ :key="`${selectedRecording.id}-bubble-row-${rowIndex}`"
+ :class="['bubble-row', row.isMe ? 'speaker-me' : '']">
+ <div v-for="bubble in row.bubbles"
+ :key="bubble.startTime || Math.random()"
+ :class="['speaker-bubble', bubble.color, row.isMe ? 'speaker-me' : '']"
+ @click="seekAudioFromEvent"
+ :data-start-time="bubble.startTime">
+ <div class="speaker-bubble-content">
+ ${bubble.sentence}
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Resizable Divider - Minimal but functional -->
+ <div id="mainColumnResizer" @mousedown="startColumnResize"></div>
+
+ <!-- Right Panel: Summary/Notes and Chat -->
+ <div id="rightMainColumn" class="flex flex-col overflow-hidden" :style="{width: rightColumnWidth + '%'}">
+ <!-- Audio Player -->
+ <div class="bg-[var(--bg-secondary)] p-4 border-b border-[var(--border-primary)] flex-shrink-0">
+ <div class="audio-player-container">
+ <!-- Show message if audio has been deleted -->
+ <div v-if="selectedRecording.audio_deleted_at"
+ class="bg-[var(--bg-tertiary)] border border-[var(--border-primary)] text-[var(--text-muted)] px-4 py-3 rounded-lg flex items-center gap-2 text-sm">
+ <i class="fas fa-info-circle"></i>
+ <span v-text="t('help.audioDeletedMessage')"></span>
+ </div>
+ <!-- Show audio player if audio is available -->
+ <audio v-else
+ controls
+ :src="'/audio/' + selectedRecording.id"
+ :volume="playerVolume"
+ @volumechange="onPlayerVolumeChange"
+ class="w-full">
+ Your browser does not support the audio element.
+ </audio>
+ </div>
+ </div>
+
+ <!-- Summary/Notes Tabs -->
+ <div :class="{'flex-1': !isChatMaximized, 'flex-none': isChatMaximized}" class="flex flex-col overflow-hidden">
+ <!-- Tab Navigation -->
+ <div class="bg-[var(--bg-tertiary)] border-b border-[var(--border-primary)] flex">
+ <button @click="selectedTab = 'summary'"
+ :class="[
+ 'flex-1 px-4 py-3 text-sm font-medium transition-colors',
+ selectedTab === 'summary'
+ ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]'
+ : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]'
+ ]">
+ ${ t('summary.title') }
+ </button>
+ <button @click="selectedTab = 'notes'"
+ :class="[
+ 'flex-1 px-4 py-3 text-sm font-medium transition-colors',
+ selectedTab === 'notes'
+ ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]'
+ : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]'
+ ]">
+ ${ t('notes.title') }
+ </button>
+ <button v-if="selectedRecording.events && selectedRecording.events.length > 0"
+ @click="selectedTab = 'events'"
+ :class="[
+ 'flex-1 px-4 py-3 text-sm font-medium transition-colors',
+ selectedTab === 'events'
+ ? 'bg-[var(--bg-secondary)] text-[var(--text-accent)] border-b-2 border-[var(--border-focus)]'
+ : 'text-[var(--text-muted)] hover:text-[var(--text-secondary)]'
+ ]">
+ <i class="fas fa-calendar-alt mr-1"></i>
+ ${ t('events.title') } (${ selectedRecording.events.length })
+ </button>
+ </div>
+
+ <!-- Tab Content -->
+ <div v-if="!isChatMaximized" class="flex-1 overflow-hidden">
+ <!-- Summary Tab -->
+ <div v-if="selectedTab === 'summary'" class="h-full p-4 overflow-y-auto">
+ <div v-if="selectedRecording.status === 'SUMMARIZING'" class="text-center py-8">
+ <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
+ <p class="mt-2 text-[var(--text-muted)]" v-text="t('summary.summaryInProgress')"></p>
+ </div>
+
+ <div v-else-if="!selectedRecording.summary" class="text-center py-8">
+ <i class="fas fa-file-alt text-3xl text-[var(--text-muted)] mb-3"></i>
+ <p class="text-[var(--text-muted)] mb-4" v-text="t('summary.noSummary')"></p>
+ <button @click="generateSummary"
+ class="px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 text-white font-medium rounded-lg shadow-lg hover:shadow-xl hover:from-blue-700 hover:to-purple-700 transition-all duration-200 transform hover:scale-105">
+ <i class="fas fa-magic mr-2"></i>${ t('summary.generateSummary') }
+ </button>
+ </div>
+
+ <div v-else class="content-box relative">
+ <div v-if="!editingSummary" class="absolute top-2 right-4 flex gap-1 z-10">
+ <button @click="copySummary"
+ :title="t('buttons.copySummary')"
+ 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="t('buttons.downloadSummary')"
+ 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="t('buttons.editSummary')"
+ 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>
+
+ <div v-if="!editingSummary"
+ class="summary-box"
+ v-html="selectedRecording.summary_html || selectedRecording.summary">
+ </div>
+ <div v-else class="h-full flex flex-col">
+ <div class="markdown-editor-container flex-1">
+ <textarea ref="summaryMarkdownEditor"
+ v-model="selectedRecording.summary"
+ class="w-full h-full p-4 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]"
+ :placeholder="t('form.enterSummaryMarkdown')">
+ </textarea>
+ </div>
+ <div class="flex justify-end gap-2 mt-2">
+ <button @click="cancelEditSummary"
+ class="px-3 py-1 text-sm bg-[var(--bg-secondary)] text-[var(--text-secondary)] border border-[var(--border-secondary)] rounded hover:bg-[var(--bg-tertiary)]">
+ Cancel
+ </button>
+ <button @click="saveEditSummary"
+ class="px-3 py-1 text-sm bg-[var(--bg-button)] text-[var(--text-button)] rounded hover:bg-[var(--bg-button-hover)]">
+ Save
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- 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-4 flex gap-1 z-10">
+ <button @click="copyNotes"
+ :title="t('buttons.copyNotes')"
+ 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="t('buttons.downloadNotes')"
+ 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="t('buttons.editNotes')"
+ 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>
+
+ <div v-if="!editingNotes"
+ class="notes-box h-full"
+ @click="clickToEditNotes">
+ <div v-if="selectedRecording.notes_html"
+ v-html="selectedRecording.notes_html">
+ </div>
+ <div v-else-if="selectedRecording.notes"
+ class="whitespace-pre-wrap">
+ ${selectedRecording.notes}
+ </div>
+ <div v-else class="text-[var(--text-muted)] italic cursor-pointer hover:text-[var(--text-secondary)]">
+ ${ t('help.clickToAddNotes') }
+ </div>
+ </div>
+
+ <div v-else class="h-full flex flex-col">
+ <div class="markdown-editor-container flex-1">
+ <textarea ref="notesMarkdownEditor"
+ v-model="selectedRecording.notes"
+ class="w-full h-full p-4 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]"
+ :placeholder="t('form.enterNotesMarkdown')">
+ </textarea>
+ </div>
+ <div class="flex justify-end gap-2 mt-2">
+ <button @click="cancelEditNotes"
+ class="px-3 py-1 text-sm bg-[var(--bg-secondary)] text-[var(--text-secondary)] border border-[var(--border-secondary)] rounded hover:bg-[var(--bg-tertiary)]">
+ Cancel
+ </button>
+ <button @click="saveEditNotes"
+ class="px-3 py-1 text-sm bg-[var(--bg-button)] text-[var(--text-button)] rounded hover:bg-[var(--bg-button-hover)]">
+ Save
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Events Tab -->
+ <div v-if="selectedTab === 'events' && selectedRecording.events && selectedRecording.events.length > 0" class="h-full p-4 overflow-y-auto">
+ <div class="space-y-4">
+ <div v-for="event in selectedRecording.events" :key="event.id"
+ class="bg-[var(--bg-tertiary)] rounded-lg p-4 border border-[var(--border-primary)] hover:border-[var(--border-accent)] transition-colors">
+ <div class="flex justify-between items-start mb-3">
+ <div class="flex-1">
+ <h3 class="text-lg font-semibold text-[var(--text-primary)] mb-1">
+ <i class="fas fa-calendar-check mr-2 text-[var(--text-accent)]"></i>
+ ${ event.title }
+ </h3>
+ <p v-if="event.description" class="text-sm text-[var(--text-secondary)] mb-2">
+ ${ event.description }
+ </p>
+ </div>
+ <button @click="downloadEventICS(event)"
+ 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-1.5"
+ :title="t('events.addToCalendar')">
+ <i class="fas fa-download"></i>
+ <span v-text="t('events.addToCalendar')"></span>
+ </button>
+ </div>
+
+ <div class="space-y-2 text-sm">
+ <div class="flex items-center gap-2" v-if="event.start_datetime">
+ <i class="fas fa-clock text-[var(--text-muted)] w-4"></i>
+ <span class="text-[var(--text-secondary)]">
+ <strong v-text="t('events.start') + ':'"></strong> ${ formatEventDateTime(event.start_datetime) }
+ </span>
+ </div>
+ <div class="flex items-center gap-2" v-if="event.end_datetime">
+ <i class="fas fa-clock text-[var(--text-muted)] w-4"></i>
+ <span class="text-[var(--text-secondary)]">
+ <strong v-text="t('events.end') + ':'"></strong> ${ formatEventDateTime(event.end_datetime) }
+ </span>
+ </div>
+ <div class="flex items-center gap-2" v-if="event.location">
+ <i class="fas fa-map-marker-alt text-[var(--text-muted)] w-4"></i>
+ <span class="text-[var(--text-secondary)]">
+ <strong v-text="t('events.location') + ':'"></strong> ${ event.location }
+ </span>
+ </div>
+ <div class="flex items-start gap-2" v-if="event.attendees && event.attendees.length > 0">
+ <i class="fas fa-users text-[var(--text-muted)] w-4 mt-0.5"></i>
+ <div class="text-[var(--text-secondary)]">
+ <strong v-text="t('events.attendees') + ':'"></strong>
+ <span class="ml-1">${ event.attendees.join(', ') }</span>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div v-if="selectedRecording.events.length === 0" class="text-center py-8">
+ <i class="fas fa-calendar-times text-3xl text-[var(--text-muted)] mb-3"></i>
+ <p class="text-[var(--text-muted)]" v-text="t('events.noEvents')"></p>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Chat Section -->
+ <div class="border-t border-[var(--border-primary)] flex flex-col" :class="{'flex-1 overflow-hidden': isChatMaximized}">
+ <!-- Chat Toggle -->
+ <div class="bg-[var(--bg-tertiary)] px-4 py-3 hover:bg-[var(--bg-accent-hover)] transition-colors flex items-center">
+ <button @click="() => { showChat = !showChat; if (!showChat) isChatMaximized = false; }"
+ class="flex-1 text-left flex items-center">
+ <span class="font-medium flex items-center">
+ <i class="fas fa-comments mr-2"></i>
+ ${ t('chat.chatWithTranscription') }
+ </span>
+ </button>
+ <div class="flex items-center gap-2">
+ <button v-if="chatMessages.length > 0"
+ @click="downloadChat"
+ class="p-1 text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors"
+ :title="t('buttons.downloadChat')">
+ <i class="fas fa-download text-sm"></i>
+ </button>
+ <button @click="toggleChatMaximize"
+ class="p-1 text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors"
+ :title="isChatMaximized ? 'Restore chat' : 'Maximize chat'">
+ <i :class="['fas text-sm', isChatMaximized ? 'fa-compress' : 'fa-expand']"></i>
+ </button>
+ <button @click="() => { showChat = !showChat; if (!showChat) isChatMaximized = false; }"
+ class="p-1 text-[var(--text-muted)] hover:text-[var(--text-primary)]">
+ <i :class="['fas transition-transform duration-200', showChat ? 'fa-chevron-down' : 'fa-chevron-up']"></i>
+ </button>
+ </div>
+ </div>
+
+ <!-- Chat Content -->
+ <div v-if="showChat" class="flex flex-col relative" :class="isChatMaximized ? 'flex-1 overflow-hidden' : 'max-h-96'">
+ <!-- Clear button - fixed at top right -->
+ <button v-if="chatMessages.length > 0"
+ @click="clearChat"
+ class="absolute top-2 right-2 p-1 text-[var(--text-muted)] opacity-60 hover:opacity-100 hover:text-[var(--text-danger)] rounded transition-all duration-200 z-20"
+ title="Clear chat">
+ <i class="fas fa-times text-xs"></i>
+ </button>
+
+ <!-- Chat Messages -->
+ <div ref="chatMessagesRef"
+ class="flex-1 overflow-y-auto p-4 space-y-4 bg-[var(--bg-secondary)]">
+ <div v-if="chatMessages.length === 0" class="text-center py-8">
+ <i class="fas fa-robot text-3xl text-[var(--text-muted)] mb-3"></i>
+ <p class="text-[var(--text-muted)]" v-text="t('help.askAboutTranscription')"></p>
+ </div>
+
+ <div v-for="(message, index) in chatMessages"
+ :key="index"
+ :class="[
+ 'message relative group',
+ message.role === 'user' ? 'user-message ml-auto' : 'ai-message',
+ message.role === 'assistant' ? 'pr-10' : ''
+ ]">
+ <!-- Copy button for assistant messages -->
+ <button v-if="message.role === 'assistant'"
+ @click="copyMessage(message.content, $event)"
+ class="absolute top-2 right-2 p-1 text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-tertiary)] rounded transition-all duration-200"
+ :title="t('buttons.copyMessage')">
+ <i class="fas fa-copy text-sm"></i>
+ </button>
+ <!-- Show thinking content if available -->
+ <div v-if="message.thinking && message.role === 'assistant'" class="mb-2">
+ <button @click="message.thinkingExpanded = !message.thinkingExpanded"
+ class="text-xs text-[var(--text-muted)] hover:text-[var(--text-secondary)] flex items-center gap-1">
+ <i :class="['fas', message.thinkingExpanded ? 'fa-chevron-down' : 'fa-chevron-right']"></i>
+ <span v-text="t('help.modelReasoning')"></span>
+ <span class="text-[var(--text-muted)]">(${message.thinking.split('\n').length} lines)</span>
+ </button>
+ <div v-if="message.thinkingExpanded"
+ class="mt-2 p-3 bg-[var(--bg-tertiary)] border border-[var(--border-secondary)] rounded-lg text-xs text-[var(--text-muted)] max-h-64 overflow-y-auto">
+ <pre class="whitespace-pre-wrap font-mono">${message.thinking}</pre>
+ </div>
+ </div>
+ <!-- Main message content -->
+ <div v-if="message.html" v-html="message.html"></div>
+ <div v-else class="whitespace-pre-wrap">${message.content}</div>
+ </div>
+
+ <div v-if="isChatLoading" class="ai-message">
+ <i class="fas fa-spinner fa-spin mr-2"></i>
+ ${ t('chat.thinking') }
+ </div>
+ </div>
+
+ <!-- Chat Input -->
+ <div class="border-t border-[var(--border-primary)] p-4 bg-[var(--bg-tertiary)]">
+ <div class="flex gap-2">
+ <textarea v-model="chatInput"
+ @keydown="handleChatKeydown"
+ :disabled="isChatLoading || selectedRecording.status !== 'COMPLETED'"
+ :placeholder="t('chat.placeholderWithHint')"
+ class="flex-1 px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)] text-sm"
+ rows="2">
+ </textarea>
+ <button @click="sendChatMessage"
+ :disabled="!chatInput.trim() || isChatLoading || selectedRecording.status !== 'COMPLETED'"
+ class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
+ <i class="fas fa-paper-plane"></i>
+ </button>
+ </div>
+ <p v-if="selectedRecording.status !== 'COMPLETED'"
+ class="text-xs text-[var(--text-muted)] mt-2">
+ ${ t('chat.availableAfterTranscription') }
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Empty State -->
+ <div v-else-if="currentView === 'detail' && !selectedRecording" class="flex-1 flex items-center justify-center">
+ <div class="text-center">
+ <i class="fas fa-microphone text-6xl text-[var(--text-muted)] mb-4"></i>
+ <h2 class="text-2xl font-bold mb-2" v-text="t('colorScheme.selectRecording')"></h2>
+ <p class="text-[var(--text-muted)] mb-6" v-text="t('colorScheme.chooseRecording')"></p>
+ <button @click="switchToUploadView"
+ class="px-6 py-3 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors">
+ <i class="fas fa-plus mr-2"></i>Upload New Recording
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Upload Progress Popup -->
+ <div v-if="uploadQueue.length > 0 && !progressPopupClosed"
+ :class="[
+ 'fixed bottom-4 left-4 z-[100] w-96 transition-all duration-300',
+ progressPopupMinimized ? 'minimized' : ''
+ ]">
+ <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-gradient-to-r from-[var(--bg-accent)] to-[var(--bg-accent-hover)] px-4 py-3">
+ <!-- Top row: Title and buttons -->
+ <div class="flex items-center justify-between mb-2">
+ <div class="flex items-center gap-2 min-w-0">
+ <i class="fas fa-upload text-gray-800 dark:text-white animate-pulse"></i>
+ <span class="font-semibold text-gray-800 dark:text-white truncate" v-text="t('uploadProgress.title')"></span>
+ </div>
+ <div class="flex items-center gap-2 flex-shrink-0">
+ <button v-if="completedInQueue > 0" @click="clearCompletedUploads()"
+ class="px-2 py-0.5 text-xs bg-black dark:bg-white bg-opacity-10 dark:bg-opacity-20 hover:bg-opacity-20 dark:hover:bg-opacity-30 rounded transition-all duration-200 text-gray-800 dark:text-white font-medium"
+ :title="t('buttons.clearCompleted')">
+ Clear
+ </button>
+ <button @click="progressPopupMinimized = !progressPopupMinimized"
+ class="p-1 rounded hover:bg-black dark:hover:bg-white hover:bg-opacity-10 dark:hover:bg-opacity-20 transition-colors text-gray-800 dark:text-white">
+ <i :class="progressPopupMinimized ? 'fas fa-chevron-up' : 'fas fa-chevron-down'"></i>
+ </button>
+ <button @click="progressPopupClosed = true"
+ class="p-1 rounded hover:bg-red-600 dark:hover:bg-red-500 hover:bg-opacity-20 dark:hover:bg-opacity-30 text-gray-800 dark:text-white hover:text-white transition-colors">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+ </div>
+ <!-- Overall Progress Bar -->
+ <div class="space-y-1">
+ <div class="flex justify-between items-center text-xs text-gray-800 dark:text-white">
+ <span class="font-medium">${completedInQueue} of ${totalInQueue} files</span>
+ <span class="font-bold">${Math.round((completedInQueue / Math.max(totalInQueue, 1)) * 100)}%</span>
+ </div>
+ <div class="w-full bg-black dark:bg-white bg-opacity-10 dark:bg-opacity-20 rounded-full h-2 overflow-hidden">
+ <div class="bg-white dark:bg-white bg-opacity-80 dark:bg-opacity-90 h-full rounded-full transition-all duration-500 ease-out relative overflow-hidden"
+ :style="{width: (completedInQueue / Math.max(totalInQueue, 1) * 100) + '%'}">
+ <div class="absolute inset-0 bg-white opacity-30 animate-pulse"></div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Progress Content -->
+ <div v-if="!progressPopupMinimized" class="p-3 max-h-64 overflow-y-auto">
+ <div v-if="currentlyProcessingFile" class="mb-3 p-3 bg-[var(--bg-accent)] bg-opacity-10 border border-[var(--border-accent)] rounded-lg">
+ <div class="flex items-center justify-between mb-2">
+ <span class="font-semibold truncate min-w-0 text-sm text-[var(--text-primary)]">${currentlyProcessingFile.file.name}</span>
+ <span class="text-sm flex-shrink-0 ml-2 font-bold text-[var(--text-accent)]">${processingProgress}%</span>
+ </div>
+ <div class="w-full bg-[var(--bg-tertiary)] rounded-full h-2 mb-2 overflow-hidden">
+ <div class="bg-gradient-to-r from-[var(--bg-accent)] to-[var(--bg-accent-hover)] h-full rounded-full transition-all duration-300 relative"
+ :style="{width: processingProgress + '%'}">
+ <div class="absolute inset-0 bg-white opacity-20 animate-pulse"></div>
+ </div>
+ </div>
+ <p class="text-xs text-[var(--text-secondary)] font-medium">${processingMessage}</p>
+ </div>
+
+ <div v-if="finishedFilesInQueue.length > 0" class="space-y-2">
+ <h4 class="text-xs font-semibold text-[var(--text-secondary)] uppercase tracking-wider opacity-70" v-text="t('help.completedFiles')"></h4>
+ <div v-for="item in finishedFilesInQueue"
+ :key="item.clientId"
+ class="progress-list-item p-2 bg-[var(--bg-tertiary)] bg-opacity-50 rounded-lg flex items-center gap-2 hover:bg-opacity-70 transition-all duration-200">
+ <i :class="[
+ 'fas',
+ item.status === 'completed' ? 'fa-check-circle text-green-500' : 'fa-exclamation-circle text-red-500'
+ ]"></i>
+ <span class="truncate text-sm flex-1 text-[var(--text-primary)]">${item.file.name}</span>
+ <span :class="[
+ 'text-xs px-2 py-1 rounded-full font-semibold',
+ item.status === 'completed' ? 'bg-green-500 bg-opacity-20 text-green-600 dark:text-green-400' : 'bg-red-500 bg-opacity-20 text-red-600 dark:text-red-400'
+ ]">
+ ${item.status === 'completed' ? t('tagsModal.done') : t('status.failed')}
+ </span>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Modals -->
+ <!-- Edit Modal -->
+ <div v-if="showEditModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div class="bg-[var(--bg-secondary)] rounded-lg shadow-xl w-full max-w-lg">
+ <div class="p-6 border-b border-[var(--border-primary)]">
+ <h3 class="text-lg font-semibold" v-text="t('modal.editRecording')"></h3>
+ </div>
+ <div class="p-6 space-y-4">
+ <div>
+ <label class="block text-sm font-medium mb-2" v-text="t('form.title')"></label>
+ <input v-model="editingRecording.title"
+ class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]">
+ </div>
+ <div>
+ <label class="block text-sm font-medium mb-2" v-text="t('form.participants')"></label>
+ <input v-model="editingRecording.participants"
+ class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]">
+ </div>
+ <div>
+ <label class="block text-sm font-medium mb-2" v-text="t('form.meetingDate')"></label>
+ <input v-model="editingRecording.meeting_date"
+ type="date"
+ class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]">
+ </div>
+ <div>
+ <label class="block text-sm font-medium mb-2" v-text="t('form.notes')"></label>
+ <textarea v-model="editingRecording.notes"
+ rows="4"
+ class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]">
+ </textarea>
+ </div>
+ </div>
+ <div class="p-6 border-t border-[var(--border-primary)] flex justify-end gap-3">
+ <button @click="cancelEdit"
+ class="px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] rounded-lg transition-colors">
+ Cancel
+ </button>
+ <button @click="saveEdit"
+ class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors">
+ Save Changes
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Delete Confirmation Modal -->
+ <div v-if="showDeleteModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div class="bg-[var(--bg-secondary)] rounded-lg shadow-xl w-full max-w-md">
+ <div class="p-6">
+ <div class="flex items-center gap-4 mb-4">
+ <i class="fas fa-exclamation-triangle text-3xl text-[var(--text-danger)]"></i>
+ <div>
+ <h3 class="text-lg font-semibold" v-text="t('modal.deleteRecording')"></h3>
+ <p class="text-[var(--text-muted)]" v-text="t('help.thisActionCannotBeUndone')"></p>
+ </div>
+ </div>
+ <p class="text-[var(--text-secondary)] mb-6">
+ Are you sure you want to delete "${recordingToDelete?.title || 'this recording'}"?
+ </p>
+ <div class="flex justify-end gap-3">
+ <button @click="cancelDelete"
+ class="px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] rounded-lg transition-colors">
+ Cancel
+ </button>
+ <button @click="deleteRecording"
+ class="px-4 py-2 bg-[var(--bg-danger)] text-white rounded-lg hover:bg-[var(--bg-danger-hover)] transition-colors">
+ Delete
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Edit Recording Tags Modal -->
+ <div v-if="showEditTagsModal" @click="closeEditTagsModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div @click.stop class="bg-[var(--bg-secondary)] rounded-lg shadow-xl w-full max-w-lg max-h-[80vh] flex flex-col">
+ <div class="flex-shrink-0 p-6 border-b border-[var(--border-primary)]">
+ <div class="flex items-center justify-between">
+ <h3 class="text-lg font-medium text-[var(--text-primary)]" v-text="t('modal.editTags')"></h3>
+ <button @click="closeEditTagsModal" class="text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+ </div>
+ <div class="flex-1 overflow-y-auto p-6 space-y-4">
+ <!-- Current Tags Section -->
+ <div>
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-3">
+ <i class="fas fa-tags mr-1 text-[var(--text-muted)]"></i>
+ <span v-text="t('tagsModal.currentTags')"></span>
+ </label>
+ <div v-if="getRecordingTags(editingRecording).length > 0" class="p-2 bg-[var(--bg-primary)] rounded-md border border-[var(--border-secondary)] max-h-20 overflow-y-auto">
+ <div class="flex flex-wrap gap-1">
+ <span v-for="tag in getRecordingTags(editingRecording)" :key="tag.id"
+ class="group inline-flex items-center px-1.5 py-0.5 rounded-full text-[11px] font-medium text-white transition-all"
+ :style="{ backgroundColor: tag.color }"
+ :title="tag.group_id ? '👥 Team Tag' : ''">
+ <i v-if="tag.group_id" class="fas fa-users mr-1" style="font-size: 9px;"></i>
+ <span v-text="tag.name"></span>
+ <button @click="removeTagFromRecording(tag.id)"
+ class="ml-1 opacity-70 hover:opacity-100 transition-opacity">
+ <i class="fas fa-times" style="font-size: 9px;"></i>
+ </button>
+ </span>
+ </div>
+ </div>
+ <div v-else class="p-4 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-secondary)]">
+ <p class="text-sm text-[var(--text-muted)] text-center">
+ <i class="fas fa-inbox mr-1"></i>
+ <span v-text="t('tagsModal.noTagsAssigned')"></span>
+ </p>
+ </div>
+ </div>
+
+ <!-- Add Tags Section -->
+ <div>
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-3">
+ <i class="fas fa-plus-circle mr-1 text-[var(--text-muted)]"></i>
+ <span v-text="t('tagsModal.addTags')"></span>
+ </label>
+
+ <!-- Search Filter (always visible if tags available) -->
+ <div v-if="getAvailableTagsForRecording(editingRecording).length > 0" class="mb-2">
+ <div class="relative">
+ <input v-model="tagSearchFilter"
+ type="text"
+ :placeholder="t('tagsModal.searchTags')"
+ class="w-full px-2 py-1 pl-6 text-xs bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-primary)] rounded focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">
+ <i class="fas fa-search absolute left-2 top-1/2 transform -translate-y-1/2 text-[var(--text-muted)]" style="font-size: 9px;"></i>
+ <button v-if="tagSearchFilter"
+ @click="tagSearchFilter = ''"
+ class="absolute right-2 top-1/2 transform -translate-y-1/2 text-[var(--text-muted)] hover:text-[var(--text-primary)]">
+ <i class="fas fa-times" style="font-size: 9px;"></i>
+ </button>
+ </div>
+ </div>
+
+ <!-- Available Tags Grid - Fixed Height -->
+ <div v-if="filteredAvailableTagsForModal.length > 0"
+ class="border border-[var(--border-secondary)] rounded-md p-1.5 bg-[var(--bg-primary)]"
+ style="max-height: 150px; overflow-y: auto;">
+ <div class="grid grid-cols-2 gap-1">
+ <button v-for="tag in filteredAvailableTagsForModal"
+ :key="tag.id"
+ @click="addTagToRecording(tag.id)"
+ class="group flex items-center justify-between px-1.5 py-1 rounded border transition-all"
+ :class="tag.group_id ? 'border-blue-400 bg-blue-50 dark:bg-blue-900/20 hover:bg-blue-100 dark:hover:bg-blue-900/30' : 'border-[var(--border-secondary)] bg-[var(--bg-secondary)] hover:border-[var(--border-focus)] hover:bg-[var(--bg-tertiary)]'">
+ <div class="flex items-center gap-1 min-w-0">
+ <span class="w-2 h-2 rounded-full flex-shrink-0"
+ :style="{ backgroundColor: tag.color || '#6B7280' }"></span>
+ <i v-if="tag.group_id" class="fas fa-users text-blue-600 dark:text-blue-400" style="font-size: 9px;"></i>
+ <span class="text-[11px] text-[var(--text-primary)] truncate" v-text="tag.name"></span>
+ </div>
+ <i class="fas fa-plus text-[var(--text-muted)] group-hover:text-[var(--text-accent)] transition-colors" style="font-size: 9px;"></i>
+ </button>
+ </div>
+ </div>
+ <div v-else-if="getAvailableTagsForRecording(editingRecording).length > 0"
+ class="p-4 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-secondary)]">
+ <p class="text-sm text-[var(--text-muted)] text-center">
+ <i class="fas fa-search mr-1"></i>
+ No tags match your filter
+ </p>
+ </div>
+ <div v-else class="p-4 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-secondary)]">
+ <p class="text-sm text-[var(--text-muted)] text-center">
+ <i class="fas fa-check-circle mr-1"></i>
+ All available tags have been added
+ </p>
+ </div>
+ </div>
+ </div>
+ <div class="flex-shrink-0 px-6 py-4 bg-[var(--bg-tertiary)] border-t border-[var(--border-primary)] flex justify-end gap-3 rounded-b-lg">
+ <button @click="closeEditTagsModal"
+ class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-primary)] rounded-md hover:bg-[var(--bg-button-hover)] transition-colors">
+ <span v-text="t('tagsModal.done')"></span>
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Color Scheme Modal -->
+ <div v-if="showColorSchemeModal" class="color-scheme-modal" @click.self="closeColorSchemeModal">
+ <div class="color-scheme-modal-content">
+ <div class="color-scheme-header">
+ <h2 class="color-scheme-title">
+ <i class="fas fa-palette"></i>
+ <span v-text="t('colorScheme.title')"></span>
+ </h2>
+ <p class="color-scheme-subtitle" v-text="t('colorScheme.subtitle')"></p>
+ </div>
+
+ <div class="color-scheme-body">
+ <div class="color-scheme-section">
+ <h3 class="color-scheme-section-title">
+ <i :class="isDarkMode ? 'fas fa-moon' : 'fas fa-sun'"></i>
+ <span v-text="isDarkMode ? t('colorScheme.darkThemes') : t('colorScheme.lightThemes')"></span>
+ </h3>
+ <div class="color-scheme-grid">
+ <div v-for="scheme in colorSchemes[isDarkMode ? 'dark' : 'light']"
+ :key="scheme.id"
+ @click="selectColorScheme(scheme.id)"
+ :class="['color-scheme-option', currentColorScheme === scheme.id ? 'active' : '']">
+ <div class="color-scheme-preview">
+ <div :class="`preview-${isDarkMode ? 'dark-' : ''}${scheme.id}-primary color-scheme-preview-segment`"></div>
+ <div :class="`preview-${isDarkMode ? 'dark-' : ''}${scheme.id}-secondary color-scheme-preview-segment`"></div>
+ <div :class="`preview-${isDarkMode ? 'dark-' : ''}${scheme.id}-tertiary color-scheme-preview-segment`"></div>
+ </div>
+ <div class="color-scheme-name" v-text="t('colorScheme.themes.' + (isDarkMode ? 'dark' : 'light') + '.' + scheme.id + '.name')"></div>
+ <div class="color-scheme-description" v-text="t('colorScheme.themes.' + (isDarkMode ? 'dark' : 'light') + '.' + scheme.id + '.description')"></div>
+ <div v-if="currentColorScheme === scheme.id" class="color-scheme-check">
+ <i class="fas fa-check"></i>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div class="color-scheme-footer">
+ <button @click="resetColorScheme" class="color-scheme-reset-btn">
+ <i class="fas fa-undo mr-2"></i><span v-text="t('colorScheme.resetToDefault')"></span>
+ </button>
+ <button @click="closeColorSchemeModal" class="color-scheme-close-btn" v-text="t('common.close')">
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Reprocess Confirmation Modal -->
+ <div v-if="showReprocessModal" @click="cancelReprocess" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm transition-all duration-300 ease-in-out">
+ <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-md transform transition-all duration-300 ease-in-out">
+ <!-- Header with gradient background -->
+ <div class="bg-gradient-to-r from-[var(--bg-accent)] to-[var(--bg-secondary)] p-5 rounded-t-xl flex items-center">
+ <div class="flex items-center">
+ <div class="w-12 h-12 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center mr-4 shadow-lg">
+ <i class="fas fa-sync-alt text-white text-lg"></i>
+ </div>
+ <div>
+ <h3 class="text-xl font-bold text-[var(--text-primary)] mb-1" v-text="t('help.confirmReprocessingTitle')"></h3>
+ <p class="text-sm text-[var(--text-muted)] capitalize">${ reprocessType } reprocessing</p>
+ </div>
+ </div>
+ </div>
+
+ <!-- Content -->
+ <div class="p-6 modal-content">
+ <div v-if="reprocessRecording" class="mb-6">
+ <div class="bg-[var(--bg-tertiary)] rounded-lg p-4 border border-[var(--border-primary)]">
+ <div class="flex items-start space-x-3">
+ <i class="fas fa-file-audio text-[var(--text-accent)] mt-1"></i>
+ <div class="flex-1 min-w-0">
+ <h4 class="font-medium text-[var(--text-primary)] truncate" :title="reprocessRecording.title">
+ ${ reprocessRecording.title || 'Untitled Recording' }
+ </h4>
+ <p class="text-sm text-[var(--text-muted)] mt-1">
+ Created: ${ new Date(reprocessRecording.created_at).toLocaleDateString() }
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div class="space-y-4">
+ <div class="flex items-start space-x-3">
+ <div class="w-6 h-6 bg-amber-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
+ <i class="fas fa-exclamation-triangle text-amber-600 text-xs"></i>
+ </div>
+ <div>
+ <p class="text-[var(--text-secondary)] font-medium mb-1" v-text="t('help.whatWillHappen')"></p>
+ <p class="text-sm text-[var(--text-muted)]" v-if="reprocessType === 'transcription' && !useAsrEndpoint">
+ <span v-text="t('reprocessModal.audioReTranscribedFromScratch')"></span>
+ </p>
+ <p class="text-sm text-[var(--text-muted)]" v-else-if="reprocessType === 'transcription' && useAsrEndpoint">
+ <span v-text="t('reprocessModal.audioReTranscribedWithAsr')"></span>
+ </p>
+ <p class="text-sm text-[var(--text-muted)]" v-else-if="reprocessType === 'summary'">
+ <span v-text="t('reprocessModal.newTitleAndSummary')"></span>
+ </p>
+ </div>
+ </div>
+
+ <!-- ASR Options -->
+ <div v-if="reprocessType === 'transcription' && useAsrEndpoint" class="space-y-4 pt-4 border-t border-[var(--border-primary)]">
+ <h4 class="text-md font-semibold text-[var(--text-secondary)]" v-text="t('help.advancedAsrOptions')"></h4>
+ <div>
+ <label for="asr-language-reprocess" class="block text-sm font-medium text-[var(--text-muted)]" v-text="t('form.language')"></label>
+ <input type="text" id="asr-language-reprocess" v-model="asrReprocessOptions.language" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" placeholder="e.g., en, es, zh (optional)">
+ </div>
+ <div>
+ <label for="asr-min-speakers-reprocess" class="block text-sm font-medium text-[var(--text-muted)]" v-text="t('form.minSpeakers')"></label>
+ <input type="number" id="asr-min-speakers-reprocess" v-model.number="asrReprocessOptions.min_speakers" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" :placeholder="t('form.optional')">
+ </div>
+ <div>
+ <label for="asr-max-speakers-reprocess" class="block text-sm font-medium text-[var(--text-muted)]" v-text="t('form.maxSpeakers')"></label>
+ <input type="number" id="asr-max-speakers-reprocess" v-model.number="asrReprocessOptions.max_speakers" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" :placeholder="t('form.optional')">
+ </div>
+ </div>
+
+ <!-- Custom Prompt Options for Summary Reprocessing -->
+ <div v-if="reprocessType === 'summary'" class="space-y-4 pt-4 border-t border-[var(--border-primary)]">
+ <h4 class="text-md font-semibold text-[var(--text-secondary)]">Custom Summarization Prompt</h4>
+
+ <!-- Prompt Source Selection -->
+ <div>
+ <label class="block text-sm font-medium text-[var(--text-muted)] mb-2">Prompt Source</label>
+ <div class="space-y-2">
+ <label class="flex items-center space-x-2 cursor-pointer">
+ <input type="radio" v-model="summaryReprocessPromptSource" value="default" class="text-[var(--text-accent)]" name="promptSource">
+ <span class="text-sm text-[var(--text-secondary)]">Use default prompt</span>
+ </label>
+ <label class="flex items-center space-x-2 cursor-pointer" v-if="tagsWithCustomPrompts.length > 0">
+ <input type="radio" v-model="summaryReprocessPromptSource" value="tag" class="text-[var(--text-accent)]" name="promptSource">
+ <span class="text-sm text-[var(--text-secondary)]">Use prompt from tag</span>
+ </label>
+ <label class="flex items-center space-x-2 cursor-pointer">
+ <input type="radio" v-model="summaryReprocessPromptSource" value="custom" class="text-[var(--text-accent)]" name="promptSource">
+ <span class="text-sm text-[var(--text-secondary)]">Enter custom prompt</span>
+ </label>
+ </div>
+ </div>
+
+ <!-- Tag Selection (shown when 'tag' is selected) -->
+ <div v-if="summaryReprocessPromptSource === 'tag' && tagsWithCustomPrompts.length > 0">
+ <label for="reprocess-tag-select" class="block text-sm font-medium text-[var(--text-muted)] mb-2">Select Tag</label>
+ <select id="reprocess-tag-select" v-model="summaryReprocessSelectedTagId" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] text-sm bg-[var(--bg-input)] text-[var(--text-primary)]">
+ <option value="">Select a tag...</option>
+ <option v-for="tag in tagsWithCustomPrompts" :key="tag.id" :value="tag.id">${ tag.name }</option>
+ </select>
+ <div v-if="summaryReprocessSelectedTagId" class="mt-2 p-2 bg-[var(--bg-tertiary)] rounded text-xs text-[var(--text-muted)] max-h-20 overflow-y-auto">
+ <strong>Preview:</strong> ${ getTagPromptPreview(summaryReprocessSelectedTagId) }
+ </div>
+ </div>
+
+ <!-- Custom Prompt Textarea (shown when 'custom' is selected) -->
+ <div v-if="summaryReprocessPromptSource === 'custom'">
+ <label for="reprocess-custom-prompt" class="block text-sm font-medium text-[var(--text-muted)] mb-2">Custom Prompt</label>
+ <textarea id="reprocess-custom-prompt" v-model="summaryReprocessCustomPrompt" rows="4" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" placeholder="Enter your custom summarization instructions..."></textarea>
+ </div>
+
+ <!-- Info message when no tags with custom prompts exist -->
+ <div v-if="summaryReprocessPromptSource === 'tag' && tagsWithCustomPrompts.length === 0" class="text-xs text-[var(--text-muted)] italic">
+ No tags with custom prompts available. Create tags with custom prompts in the Account Settings.
+ </div>
+ </div>
+
+ <div class="flex items-start space-x-3">
+ <div class="w-6 h-6 bg-blue-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
+ <i class="fas fa-clock text-blue-600 text-xs"></i>
+ </div>
+ <div>
+ <p class="text-[var(--text-secondary)] font-medium mb-1" v-text="t('help.processingTime')"></p>
+ <p class="text-sm text-[var(--text-muted)]">
+ <span v-text="t('help.processingTimeDescription')"></span>
+ </p>
+ </div>
+ </div>
+
+ <div class="flex items-start space-x-3" v-if="reprocessType === 'transcription'">
+ <div class="w-6 h-6 bg-red-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
+ <i class="fas fa-info-circle text-red-600 text-xs"></i>
+ </div>
+ <div>
+ <p class="text-[var(--text-secondary)] font-medium mb-1" v-text="t('help.importantNote')"></p>
+ <p class="text-sm text-[var(--text-muted)]">
+ <span v-text="t('reprocessModal.manualEditsOverwritten')"></span>
+ </p>
+ </div>
+ </div>
+
+ <div class="flex items-start space-x-3" v-else-if="reprocessType === 'summary'">
+ <div class="w-6 h-6 bg-red-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
+ <i class="fas fa-info-circle text-red-600 text-xs"></i>
+ </div>
+ <div>
+ <p class="text-[var(--text-secondary)] font-medium mb-1" v-text="t('help.importantNote')"></p>
+ <p class="text-sm text-[var(--text-muted)]">
+ <span v-text="t('reprocessModal.manualEditsOverwrittenSummary')"></span>
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Footer with action buttons -->
+ <div class="bg-[var(--bg-tertiary)] px-6 py-4 rounded-b-xl flex justify-end space-x-3 border-t border-[var(--border-primary)]">
+ <button
+ @click="cancelReprocess"
+ class="px-5 py-2.5 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] transition-all duration-200 flex items-center shadow-sm font-medium">
+ <i class="fas fa-times mr-2"></i>
+ Cancel
+ </button>
+ <button
+ @click="executeReprocess"
+ class="px-5 py-2.5 bg-gradient-to-r from-blue-500 to-purple-600 text-white rounded-lg hover:from-blue-600 hover:to-purple-700 transition-all duration-200 flex items-center shadow-lg font-medium transform hover:scale-105">
+ <i class="fas fa-sync-alt mr-2"></i>
+ Start Reprocessing
+ </button>
+ </div>
+ </div>
+ </div>
+ <!-- Reset Status Confirmation Modal -->
+ <div v-if="showResetModal" @click="cancelReset" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-md">
+ <div class="p-6 text-center">
+ <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-orange-100 dark:bg-orange-800 mb-4">
+ <i class="fas fa-exclamation-triangle text-2xl text-orange-500 dark:text-orange-300"></i>
+ </div>
+ <h3 class="text-lg font-semibold text-[var(--text-primary)] mb-2" v-text="t('modal.resetStatus')"></h3>
+ <p class="text-sm text-[var(--text-muted)] mb-6">
+ This will mark the recording as 'Failed'. This is useful if processing is stuck. You will be able to reprocess it afterwards.
+ </p>
+ </div>
+ <div class="bg-[var(--bg-tertiary)] px-6 py-4 rounded-b-xl flex justify-end space-x-3">
+ <button @click="cancelReset" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)]">
+ Cancel
+ </button>
+ <button @click="executeReset" class="px-4 py-2 bg-orange-500 text-white rounded-lg hover:bg-orange-600">
+ Yes, Reset Status
+ </button>
+ </div>
+ </div>
+ </div>
+ <!-- Simple Transcription Editor Modal -->
+ <div v-if="showTextEditorModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div class="bg-[var(--bg-secondary)] rounded-lg shadow-xl w-full max-w-2xl max-h-[90vh] flex flex-col">
+ <div class="p-6 border-b border-[var(--border-primary)]">
+ <h3 class="text-lg font-semibold" v-text="t('modal.editTranscription')"></h3>
+ </div>
+ <div class="p-6 space-y-4 overflow-y-auto flex-1">
+ <div>
+ <label class="block text-sm font-medium mb-2" v-text="t('transcription.title')"></label>
+ <textarea v-model="editingTranscriptionContent"
+ rows="15"
+ class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)] font-mono text-sm">
+ </textarea>
+ </div>
+ </div>
+ <div class="p-6 border-t border-[var(--border-primary)] flex justify-end gap-3">
+ <button @click="closeTextEditorModal"
+ class="px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] rounded-lg transition-colors">
+ Cancel
+ </button>
+ <button @click="saveTranscription"
+ class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors">
+ Save Changes
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- ASR Transcription Editor Modal -->
+ <div v-if="showAsrEditorModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div @click="closeAllSpeakerSuggestions" class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-6xl flex flex-col max-h-[90vh]">
+ <div class="p-5 border-b border-[var(--border-primary)] flex-shrink-0 flex justify-between items-center">
+ <h3 class="text-xl font-bold text-[var(--text-primary)]" v-text="t('modal.editAsrTranscription')"></h3>
+ <button @click="closeAsrEditorModal" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+
+ <!-- Audio Player Section -->
+ <div class="px-6 py-4 border-b border-[var(--border-primary)] flex-shrink-0">
+ <div class="audio-player-container">
+ <!-- Show message if audio has been deleted -->
+ <div v-if="selectedRecording.audio_deleted_at"
+ class="bg-[var(--bg-tertiary)] border border-[var(--border-primary)] text-[var(--text-secondary)] px-4 py-3 rounded-lg flex items-center gap-2 text-sm">
+ <i class="fas fa-info-circle"></i>
+ <span v-text="t('help.audioDeletedMessage')"></span>
+ </div>
+ <audio v-else ref="asrEditorAudio" controls class="w-full" :key="'asr-editor-' + selectedRecording.id" :src="'/audio/' + selectedRecording.id" :volume="playerVolume" @volumechange="onPlayerVolumeChange">
+ Your browser does not support the audio element.
+ </audio>
+ </div>
+ </div>
+
+ <div class="flex-grow overflow-y-auto custom-scrollbar" @scroll="closeAllSpeakerSuggestions">
+ <table class="min-w-full asr-editor-table border border-[var(--border-primary)]">
+ <thead class="sticky top-0 z-10">
+ <tr class="text-xs uppercase text-[var(--text-muted)]">
+ <th class="w-40 text-left py-2 px-3 font-medium border border-[var(--border-primary)] bg-[var(--bg-tertiary)]" v-text="t('help.speakerCount')"></th>
+ <th class="w-20 text-left py-2 px-3 font-medium border border-[var(--border-primary)] bg-[var(--bg-tertiary)]" v-text="t('help.startTime')"></th>
+ <th class="w-20 text-left py-2 px-3 font-medium border border-[var(--border-primary)] bg-[var(--bg-tertiary)]" v-text="t('help.endTime')"></th>
+ <th class="text-left py-2 px-3 font-medium border border-[var(--border-primary)] bg-[var(--bg-tertiary)]" v-text="t('help.sentence')"></th>
+ <th class="w-24 text-center py-2 px-1 font-medium border border-[var(--border-primary)] bg-[var(--bg-tertiary)]"><span class="sr-only" v-text="t('help.actions')"></span></th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="(segment, index) in editingSegments" :key="segment.id || index" class="hover:bg-[var(--bg-tertiary)] transition-colors border-b border-[var(--border-primary)]">
+ <td class="border-r border-[var(--border-primary)] align-middle">
+ <div class="relative h-full" :ref="'speakerDropdown' + index">
+ <div class="flex items-center h-full">
+ <input type="text" v-model="segment.speaker"
+ @input="filterSpeakers(index); openSpeakerSuggestions(index)"
+ @focus="openSpeakerSuggestions(index)"
+ class="w-full h-full px-3 py-2.5 pr-7 bg-transparent border-0 focus:outline-none text-sm text-[var(--text-primary)]" />
+ <button type="button" @click.stop="openSpeakerSuggestions(index)"
+ class="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-[var(--text-muted)] hover:text-[var(--text-primary)] cursor-pointer">
+ <i class="fas fa-chevron-down text-xs"></i>
+ </button>
+ </div>
+ </div>
+ <!-- Fixed position dropdown that can escape modal overflow -->
+ <teleport to="body">
+ <div v-if="segment.showSuggestions"
+ class="fixed z-[100] w-40 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-md shadow-lg max-h-48 overflow-y-auto"
+ :style="getDropdownPosition(index)">
+ <div v-for="speaker in segment.filteredSpeakers" @mousedown.prevent="selectSpeaker(index, speaker)" class="px-3 py-2 cursor-pointer hover:bg-[var(--bg-tertiary)] text-sm">${speaker}</div>
+ <div @mousedown.prevent="openEditSpeakersModal" class="px-3 py-2 cursor-pointer hover:bg-[var(--bg-accent)] text-sm text-[var(--text-accent)] border-t border-[var(--border-primary)] flex items-center">
+ <i class="fas fa-user-edit mr-2"></i> <span v-text="t('buttons.editSpeakers')"></span>
+ </div>
+ </div>
+ </teleport>
+ </td>
+ <td class="border-r border-[var(--border-primary)] align-middle">
+ <input type="number" step="0.01" v-model.number="segment.start_time" class="w-full px-3 py-2.5 bg-transparent border-0 focus:outline-none text-sm text-[var(--text-primary)] text-center" />
+ </td>
+ <td class="border-r border-[var(--border-primary)] align-middle">
+ <input type="number" step="0.01" v-model.number="segment.end_time" class="w-full px-3 py-2.5 bg-transparent border-0 focus:outline-none text-sm text-[var(--text-primary)] text-center" />
+ </td>
+ <td class="border-r border-[var(--border-primary)] align-top">
+ <textarea v-model="segment.sentence" rows="1" class="w-full px-3 py-2.5 bg-transparent border-0 focus:outline-none text-sm text-[var(--text-primary)] resize-none max-h-20 overflow-y-auto custom-scrollbar block" @input="autoResizeTextarea($event)"></textarea>
+ </td>
+ <td class="px-1 text-center align-middle">
+ <div class="flex items-center justify-center gap-1">
+ <button @click="seekToSegmentTime(segment.start_time)" class="p-1.5 rounded hover:bg-[var(--bg-accent)] text-[var(--text-muted)] hover:text-[var(--text-accent)] transition-colors" :title="t('help.playFromHere')">
+ <i class="fas fa-play text-xs"></i>
+ </button>
+ <button @click="addSegmentBelow(index)" class="p-1.5 rounded hover:bg-green-600/20 text-[var(--text-muted)] hover:text-green-500 transition-colors" :title="t('help.addSegmentBelow')">
+ <i class="fas fa-plus text-xs"></i>
+ </button>
+ <button @click="removeSegment(index)" class="p-1.5 rounded hover:bg-red-600/20 text-[var(--text-muted)] hover:text-red-500 transition-colors" :title="t('help.deleteSegment')">
+ <i class="fas fa-trash text-xs"></i>
+ </button>
+ </div>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ <div class="py-4 flex justify-center">
+ <button @click="addSegment" class="px-4 py-2 bg-[var(--bg-accent)] text-[var(--text-accent)] rounded-lg hover:bg-[var(--bg-accent-hover)] flex items-center text-sm">
+ <i class="fas fa-plus mr-2"></i> Add Segment
+ </button>
+ </div>
+ </div>
+ <div class="bg-[var(--bg-tertiary)] px-6 py-4 flex justify-end space-x-3 border-t border-[var(--border-primary)] flex-shrink-0 rounded-b-xl">
+ <button @click="closeAsrEditorModal" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)]" v-text="t('common.cancel')"></button>
+ <button @click="saveAsrTranscription" class="px-4 py-2 bg-[var(--bg-accent)] text-[var(--text-accent)] rounded-lg hover:bg-[var(--bg-accent-hover)]" v-text="t('buttons.saveChanges')"></button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Edit Speakers Modal (for ASR Editor) -->
+ <div v-if="showEditSpeakersModal" class="fixed inset-0 bg-black bg-opacity-80 flex items-center justify-center z-[60] p-4 backdrop-blur-sm">
+ <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-md flex flex-col max-h-[80vh]">
+ <div class="p-5 border-b border-[var(--border-primary)] flex-shrink-0 flex justify-between items-center">
+ <h3 class="text-lg font-bold text-[var(--text-primary)]" v-text="t('buttons.editSpeakers')"></h3>
+ <button @click="closeEditSpeakersModal" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+ <div class="flex-grow overflow-y-auto custom-scrollbar p-5 space-y-3">
+ <div v-for="(speaker, index) in editingSpeakersList" :key="index" class="flex items-center gap-2">
+ <div class="relative flex-1" :ref="'editSpeakerInput' + index">
+ <input type="text" v-model="editingSpeakersList[index]"
+ @input="filterEditingSpeakerSuggestions(index)"
+ @focus="filterEditingSpeakerSuggestions(index)"
+ @blur="setTimeout(() => closeEditingSpeakerSuggestions(index), 200)"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-1 focus:ring-[var(--border-focus)] text-sm bg-[var(--bg-input)] text-[var(--text-primary)]"
+ placeholder="Speaker name">
+ </div>
+ <button @click="removeEditingSpeaker(index)" class="p-2 rounded hover:bg-red-600/20 text-[var(--text-muted)] hover:text-red-500 transition-colors" title="Remove speaker">
+ <i class="fas fa-trash text-sm"></i>
+ </button>
+ </div>
+ <button @click="addEditingSpeaker" class="w-full px-3 py-2 border border-dashed border-[var(--border-secondary)] rounded-md text-sm text-[var(--text-muted)] hover:border-[var(--border-focus)] hover:text-[var(--text-primary)] transition-colors flex items-center justify-center gap-2">
+ <i class="fas fa-plus"></i> Add Speaker
+ </button>
+ </div>
+ <div class="bg-[var(--bg-tertiary)] px-5 py-4 flex justify-end space-x-3 border-t border-[var(--border-primary)] flex-shrink-0 rounded-b-xl">
+ <button @click="closeEditSpeakersModal" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] text-sm">Cancel</button>
+ <button @click="saveEditingSpeakers" class="px-4 py-2 bg-[var(--bg-accent)] text-[var(--text-accent)] rounded-lg hover:bg-[var(--bg-accent-hover)] text-sm">Save</button>
+ </div>
+ <!-- Teleported autocomplete dropdowns -->
+ <teleport to="body">
+ <template v-for="(speaker, index) in editingSpeakersList" :key="'suggestion-' + index">
+ <div v-if="editingSpeakerSuggestions[index] && editingSpeakerSuggestions[index].length > 0"
+ class="fixed z-[200] bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-md shadow-lg max-h-32 overflow-y-auto"
+ :style="getEditSpeakerDropdownPosition(index)">
+ <div v-for="suggestion in editingSpeakerSuggestions[index]"
+ @mousedown.prevent="selectEditingSpeakerSuggestion(index, suggestion)"
+ class="px-3 py-2 cursor-pointer hover:bg-[var(--bg-tertiary)] text-sm text-[var(--text-primary)]">${suggestion}</div>
+ </div>
+ </template>
+ </teleport>
+ </div>
+ </div>
+
+ <!-- Speaker Identification Modal -->
+ <div v-if="showSpeakerModal" @click="closeSpeakerModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div @click.stop @click="closeSpeakerSuggestionsOnClick" class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-4xl flex flex-col h-[85vh]">
+ <div class="p-5 border-b border-[var(--border-primary)] flex-shrink-0">
+ <h3 class="text-xl font-bold text-[var(--text-primary)]" v-text="t('modal.identifySpeakers')"></h3>
+ <!-- Warning for too many speakers -->
+ <div v-if="modalSpeakers.length > 8" class="mt-3 p-3 bg-[var(--bg-warn-light)] border border-amber-300 dark:border-amber-800 rounded-lg">
+ <div class="flex items-start">
+ <i class="fas fa-exclamation-triangle text-[var(--text-warn-strong)] mt-0.5 mr-2"></i>
+ <div class="text-sm">
+ <p class="font-medium text-[var(--text-warn-strong)]" v-text="t('help.moreSpeakersThanColors')"></p>
+ <p class="text-[var(--text-warn-strong)] mt-1" v-text="t('help.youHaveXSpeakers', { count: modalSpeakers.length })">
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div class="flex-grow flex overflow-hidden modal-content">
+ <div class="w-1/3 p-6 space-y-4 overflow-y-auto custom-scrollbar border-r border-[var(--border-primary)]">
+ <div v-for="(speaker, index) in modalSpeakers" :key="`${selectedRecording.id}-speaker-${index}-${speaker}`" class="space-y-3">
+ <!-- Speaker label with color indicator and "This is Me" checkbox on same line -->
+ <div class="flex items-center justify-between">
+ <div class="flex items-center space-x-2">
+ <div :class="speakerMap[speaker].color" class="w-4 h-4 rounded-full border border-white/30 shadow-sm flex-shrink-0"></div>
+ <span class="font-mono text-sm text-[var(--text-muted)]">${ speakerDisplayMap[speaker] || speaker }</span>
+ <span v-if="index >= 8" class="text-xs text-[var(--text-warn-strong)] bg-[var(--bg-warn-light)] px-2 py-0.5 rounded-full" title="Color repeats from speaker ${ ((index % 8) + 1) }">
+ Repeat
+ </span>
+ </div>
+ <label class="flex items-center text-sm text-[var(--text-muted)] cursor-pointer hover:text-[var(--text-primary)] transition-colors">
+ <input type="checkbox"
+ v-model="speakerMap[speaker].isMe"
+ @focus="highlightSpeakerInTranscript(speaker)"
+ @blur="clearSpeakerHighlight"
+ class="speaker-checkbox">
+ <span class="ml-2 select-none" v-text="t('help.me')"></span>
+ </label>
+ </div>
+
+ <!-- Autocomplete input field - disabled when "This is Me" is checked -->
+ <div class="relative">
+ <input
+ type="text"
+ v-model="speakerMap[speaker].name"
+ @input="searchSpeakers($event.target.value, speaker)"
+ @focus="focusSpeaker(speaker)"
+ @blur="blurSpeaker()"
+ :disabled="speakerMap[speaker].isMe"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)] disabled:bg-[var(--bg-tertiary)] disabled:text-[var(--text-muted)] disabled:cursor-not-allowed"
+ :placeholder="speakerMap[speaker].isMe ? t('help.me') : t('help.enterNameFor') + ' ' + (speakerDisplayMap[speaker] || speaker)"
+ autocomplete="off">
+
+ <!-- Loading indicator -->
+ <div v-if="loadingSuggestions[speaker] && !speakerMap[speaker].isMe" class="absolute right-3 top-1/2 transform -translate-y-1/2">
+ <i class="fas fa-spinner fa-spin text-[var(--text-muted)] text-sm"></i>
+ </div>
+
+ <!-- Suggestions dropdown - Only show when this input is active -->
+ <div v-if="activeSpeakerInput === speaker && speakerSuggestions[speaker] && speakerSuggestions[speaker].length > 0 && !speakerMap[speaker].isMe"
+ @click.stop
+ class="absolute z-10 w-full mt-1 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-md shadow-lg max-h-48 overflow-y-auto">
+ <div class="py-1">
+ <div v-for="suggestion in speakerSuggestions[speaker]"
+ :key="suggestion.id"
+ @click="selectSpeakerSuggestion(speaker, suggestion)"
+ class="px-3 py-2 cursor-pointer hover:bg-[var(--bg-tertiary)] flex items-center justify-between">
+ <div class="flex-grow">
+ <div class="text-sm font-medium text-[var(--text-primary)]">${ suggestion.name }</div>
+ <div class="text-xs text-[var(--text-muted)]">
+ Used ${ suggestion.use_count } time${ suggestion.use_count !== 1 ? 's' : '' }
+ <span v-if="suggestion.last_used">
+ • Last: ${ new Date(suggestion.last_used).toLocaleDateString() }
+ </span>
+ </div>
+ </div>
+ <i class="fas fa-user text-[var(--text-muted)] ml-2"></i>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Add Speaker Button -->
+ <div class="pt-4 border-t border-[var(--border-primary)]">
+ <button @click="openAddSpeakerModal" class="w-full px-4 py-2 bg-[var(--bg-accent)] text-[var(--text-accent)] rounded-lg hover:bg-[var(--bg-accent-hover)] transition-colors flex items-center justify-center">
+ <i class="fas fa-plus mr-2"></i>
+ <span v-text="t('buttons.addSpeaker')"></span>
+ </button>
+ </div>
+ </div>
+ <div class="w-2/3 p-6 flex flex-col overflow-hidden">
+ <!-- Audio Player Section -->
+ <div class="mb-4 flex-shrink-0">
+ <h4 class="font-semibold text-[var(--text-secondary)] mb-2" v-text="t('help.audioPlayer')"></h4>
+ <div class="audio-player-container">
+ <!-- Show message if audio has been deleted -->
+ <div v-if="selectedRecording.audio_deleted_at"
+ class="bg-[var(--bg-tertiary)] border border-[var(--border-primary)] text-[var(--text-secondary)] px-4 py-3 rounded-lg flex items-center gap-2 text-sm">
+ <i class="fas fa-info-circle"></i>
+ <span v-text="t('help.audioDeletedMessage')"></span>
+ </div>
+ <audio v-else 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>
+ </div>
+
+ <!-- Transcript Section -->
+ <div class="flex-grow overflow-y-auto custom-scrollbar speaker-modal-transcript" @click="seekAudioFromEvent">
+ <div v-if="processedTranscription.isJson">
+ <div v-for="(segment, index) in processedTranscription.simpleSegments" :key="index" class="speaker-segment mb-2 group relative" :data-start-time="segment.startTime">
+ <p class="flex items-baseline">
+ <span :class="[segment.color, 'speaker-tag', { 'speaker-highlight': highlightedSpeaker === segment.speakerId }]" :data-speaker-id="segment.speakerId" class="inline-block w-[120px] flex-shrink-0 truncate" :title="segment.speaker">${ segment.speaker }</span>
+ <span class="mx-1 flex-shrink-0">:</span>
+ <span class="word cursor-pointer hover:bg-[var(--bg-accent)] hover:text-[var(--text-accent)] rounded px-0.5 flex-1">${ segment.sentence }</span>
+
+ <!-- Edit buttons (shown on hover) -->
+ <span class="ml-2 opacity-0 group-hover:opacity-100 transition-opacity flex items-center space-x-1 flex-shrink-0">
+ <!-- Change Speaker Button -->
+ <button @click.stop="openSpeakerChangeDropdown(index)" class="p-1 rounded bg-[var(--bg-tertiary)] hover:bg-[var(--bg-accent)] text-[var(--text-muted)] hover:text-[var(--text-accent)] transition-colors" title="Change speaker">
+ <i class="fas fa-user-edit text-xs"></i>
+ </button>
+ <!-- Edit Text Button -->
+ <button @click.stop="openEditTextModal(index)" class="p-1 rounded bg-[var(--bg-tertiary)] hover:bg-[var(--bg-accent)] text-[var(--text-muted)] hover:text-[var(--text-accent)] transition-colors" title="Edit text">
+ <i class="fas fa-edit text-xs"></i>
+ </button>
+ </span>
+ </p>
+
+ <!-- Speaker Change Dropdown -->
+ <div v-if="editingSpeakerIndex === index" @click.stop class="mt-2 p-2 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-primary)] shadow-lg">
+ <p class="text-xs text-[var(--text-muted)] mb-2">Select new speaker:</p>
+ <div class="space-y-1 max-h-48 overflow-y-auto custom-scrollbar">
+ <button v-for="speaker in modalSpeakers" :key="speaker" @click="changeSpeaker(index, speaker)" class="w-full text-left px-3 py-2 rounded hover:bg-[var(--bg-accent)] hover:text-[var(--text-accent)] transition-colors flex items-center space-x-2">
+ <div :class="speakerMap[speaker].color" class="w-3 h-3 rounded-full flex-shrink-0"></div>
+ <span class="text-sm">${ speakerMap[speaker].name || speaker }</span>
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div v-else v-html="highlightedTranscript"></div>
+ </div>
+
+ <!-- Speaker Navigation Controls (at bottom) - Always visible for consistent height -->
+ <div class="mt-3 p-3 bg-[var(--bg-tertiary)] rounded-lg flex items-center justify-between flex-shrink-0" :class="{'opacity-50': !highlightedSpeaker || speakerGroups.length <= 1}">
+ <div class="flex items-center space-x-2">
+ <span class="text-sm text-[var(--text-muted)]">
+ <span v-text="t('help.navigate')"></span> <span class="font-semibold">${ speakerDisplayMap[highlightedSpeaker] || highlightedSpeaker }</span> <span v-text="t('help.groups')"></span>:
+ </span>
+ <span class="text-xs text-[var(--text-muted)]">
+ (${ currentSpeakerGroupIndex + 1 } <span v-text="t('help.of')"></span> ${ speakerGroups.length })
+ </span>
+ </div>
+ <div class="flex items-center space-x-2">
+ <button @mousedown.prevent @click="navigateToPrevSpeakerGroup"
+ class="px-3 py-1.5 bg-[var(--bg-secondary)] hover:bg-[var(--bg-primary)] text-[var(--text-secondary)] rounded-md border border-[var(--border-secondary)] transition-all flex items-center text-sm disabled:opacity-50 disabled:cursor-not-allowed"
+ :disabled="!highlightedSpeaker || speakerGroups.length <= 1">
+ <i class="fas fa-chevron-up mr-1.5"></i>
+ <span v-text="t('buttons.previous')"></span>
+ </button>
+ <button @mousedown.prevent @click="navigateToNextSpeakerGroup"
+ class="px-3 py-1.5 bg-[var(--bg-secondary)] hover:bg-[var(--bg-primary)] text-[var(--text-secondary)] rounded-md border border-[var(--border-secondary)] transition-all flex items-center text-sm disabled:opacity-50 disabled:cursor-not-allowed"
+ :disabled="!highlightedSpeaker || speakerGroups.length <= 1">
+ <span v-text="t('buttons.next')"></span>
+ <i class="fas fa-chevron-down ml-1.5"></i>
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div class="p-4 bg-[var(--bg-tertiary)] border-t border-[var(--border-primary)] flex-shrink-0">
+ <label class="flex items-center text-sm text-[var(--text-muted)] cursor-pointer hover:text-[var(--text-primary)] transition-colors">
+ <input type="checkbox"
+ v-model="regenerateSummaryAfterSpeakerUpdate"
+ class="speaker-checkbox">
+ <span class="ml-2 select-none" v-text="t('help.regenerateSummaryAfterNames')"></span>
+ </label>
+ </div>
+ <div class="bg-[var(--bg-tertiary)] px-6 py-4 flex justify-between items-center border-t border-[var(--border-primary)] flex-shrink-0 rounded-b-xl">
+ <div>
+ <button @click="autoIdentifySpeakers" class="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 flex items-center" :disabled="isAutoIdentifying">
+ <i class="fas fa-magic mr-2"></i>
+ <span v-if="!isAutoIdentifying" v-text="t('help.autoIdentify')"></span>
+ <span v-else>
+ <i class="fas fa-spinner fa-spin mr-2"></i>
+ <span v-text="t('help.identifying')"></span>
+ </span>
+ </button>
+ </div>
+ <div class="flex space-x-3">
+ <button @click="closeSpeakerModal" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)]" v-text="t('common.cancel')"></button>
+ <button
+ @click="saveSpeakerNames"
+ :disabled="!hasSpeakerNames"
+ :class="hasSpeakerNames
+ ? 'px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 cursor-pointer'
+ : 'px-4 py-2 bg-gray-400 text-gray-200 rounded-lg cursor-not-allowed'"
+ v-text="t('buttons.saveNames')"
+ >
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Add Speaker Modal -->
+ <div v-if="showAddSpeakerModal" @click="closeAddSpeakerModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-md p-6">
+ <h3 class="text-xl font-bold text-[var(--text-primary)] mb-4">Add New Speaker</h3>
+
+ <!-- "This is Me" checkbox -->
+ <div class="mb-4">
+ <label class="flex items-center text-sm text-[var(--text-muted)] cursor-pointer hover:text-[var(--text-primary)] transition-colors">
+ <input type="checkbox" v-model="newSpeakerIsMe" class="speaker-checkbox">
+ <span class="ml-2 select-none">This is Me</span>
+ </label>
+ </div>
+
+ <!-- Speaker name input (disabled if "This is Me" is checked) -->
+ <div class="mb-6">
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-2">
+ Speaker Name
+ </label>
+ <input
+ type="text"
+ v-model="newSpeakerName"
+ :disabled="newSpeakerIsMe"
+ :placeholder="newSpeakerIsMe ? 'Me' : 'Enter speaker name...'"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)] disabled:bg-[var(--bg-tertiary)] disabled:text-[var(--text-muted)] disabled:cursor-not-allowed"
+ @keyup.enter="addNewSpeaker"
+ >
+ </div>
+
+ <!-- Action buttons -->
+ <div class="flex justify-end space-x-3">
+ <button @click="closeAddSpeakerModal" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] transition-colors">
+ Cancel
+ </button>
+ <button @click="addNewSpeaker" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
+ Add Speaker
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Edit Text Modal -->
+ <div v-if="showEditTextModal" @click="closeEditTextModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-2xl p-6">
+ <h3 class="text-xl font-bold text-[var(--text-primary)] mb-4">Edit Transcript Text</h3>
+
+ <!-- Text editor -->
+ <div class="mb-6">
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-2">
+ Text Content
+ </label>
+ <textarea
+ v-model="editedText"
+ rows="6"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)] resize-y"
+ placeholder="Enter transcript text..."
+ ></textarea>
+ </div>
+
+ <!-- Action buttons -->
+ <div class="flex justify-end space-x-3">
+ <button @click="closeEditTextModal" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] transition-colors">
+ Cancel
+ </button>
+ <button @click="saveEditedText" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
+ Save Changes
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Global Error Display -->
+ <div v-if="globalError"
+ class="fixed top-4 right-4 bg-[var(--bg-danger)] text-white p-4 rounded-lg shadow-lg z-50 max-w-md">
+ <div class="flex items-start gap-3">
+ <i class="fas fa-exclamation-circle text-lg flex-shrink-0 mt-0.5"></i>
+ <div class="flex-1">
+ <p class="font-medium" v-text="t('common.error')"></p>
+ <p class="text-sm opacity-90">${globalError}</p>
+ </div>
+ <button @click="globalError = null"
+ class="text-white hover:text-gray-200 transition-colors">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+ </div>
+
+ <!-- System Audio Help Modal -->
+ <div v-if="showSystemAudioHelp" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 backdrop-blur-sm">
+ <div class="bg-[var(--bg-secondary)] w-full h-full md:h-auto md:max-h-[90vh] md:w-full md:max-w-2xl md:rounded-lg md:shadow-xl flex flex-col">
+ <div class="p-4 border-b border-[var(--border-primary)] flex-shrink-0">
+ <div class="flex items-center justify-between">
+ <h3 class="text-lg font-semibold flex items-center">
+ <i class="fas fa-desktop mr-2 text-blue-500"></i>
+ System Audio Recording
+ </h3>
+ <button @click="showSystemAudioHelp = false" class="text-[var(--text-muted)] hover:text-[var(--text-primary)]">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+ </div>
+ <div class="p-6 space-y-6 overflow-y-auto flex-grow">
+ <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)]">
+ <h4 class="font-medium text-[var(--text-primary)] mb-2" v-text="t('help.howToRecordSystemAudio')"></h4>
+ <p class="text-sm text-[var(--text-muted)]" v-text="t('help.toCaptureAudioFromMeetings')">
+ </p>
+ <ol class="list-decimal list-inside space-y-2 text-sm text-[var(--text-secondary)] mt-3">
+ <li v-text="t('help.recordSystemSteps1')"></li>
+ <li><span v-text="t('help.recordSystemSteps2')"></span> <strong>"${ t('help.entireScreen') }"</strong> or a <strong v-text="t('help.specificBrowserTab')"></strong>.</li>
+ <li><span v-text="t('help.recordSystemSteps3')"></span> <strong>"${ t('help.shareTabAudio') }"</strong> or <strong>"${ t('help.shareSystemAudio') }"</strong>.</li>
+ </ol>
+ <p class="text-xs text-amber-600 dark:text-amber-400 mt-3"><i class="fas fa-exclamation-triangle mr-1"></i><span v-text="t('help.sharingWindowNoAudio')"></span></p>
+ </div>
+
+ <div class="space-y-4">
+ <h4 class="font-medium text-[var(--text-primary)]" v-text="t('help.troubleshooting')"></h4>
+
+ <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)]">
+ <h5 class="font-medium text-[var(--text-primary)] mb-2" v-text="t('help.whyNotWorking')"></h5>
+ <p class="text-sm text-[var(--text-muted)]">
+ System audio recording requires a secure (HTTPS) connection. If you are developing locally, you may need to enable a browser flag.
+ </p>
+ </div>
+
+ <!-- Chrome Solution -->
+ <div v-if="browser === 'chrome'" class="bg-[var(--bg-accent)] p-4 rounded-lg border border-[var(--border-accent)]">
+ <h5 class="font-medium text-[var(--text-accent)] mb-3 flex items-center">
+ <i class="fab fa-chrome mr-2"></i>
+ For Chrome on Localhost
+ </h5>
+ <ol class="list-decimal list-inside space-y-2 text-sm text-[var(--text-secondary)]">
+ <li>Go to: <code class="bg-[var(--bg-secondary)] px-2 py-1 rounded text-xs ml-1">chrome://flags/#unsafely-treat-insecure-origin-as-secure</code></li>
+ <li>Add your local URL (e.g., <code class="bg-[var(--bg-secondary)] px-2 py-1 rounded text-xs ml-1">http://localhost:8899</code>)</li>
+ <li>Set to <strong>"Enabled"</strong> and relaunch Chrome.</li>
+ </ol>
+ </div>
+
+ <!-- Firefox Solution -->
+ <div v-else-if="browser === 'firefox'" class="bg-[var(--bg-accent)] p-4 rounded-lg border border-[var(--border-accent)]">
+ <h5 class="font-medium text-[var(--text-accent)] mb-3 flex items-center">
+ <i class="fab fa-firefox-browser mr-2"></i>
+ For Firefox on Localhost
+ </h5>
+ <p class="text-sm text-[var(--text-secondary)]">
+ System audio recording is not well-supported on Firefox, even with these changes. For best results, please use Chrome.
+ </p>
+ <ol class="list-decimal list-inside space-y-2 text-sm text-[var(--text-secondary)] mt-2">
+ <li>Go to: <code class="bg-[var(--bg-secondary)] px-2 py-1 rounded text-xs ml-1">about:config</code></li>
+ <li>Search for <code class="bg-[var(--bg-secondary)] px-2 py-1 rounded text-xs ml-1">media.devices.insecure.enabled</code> and set it to `true`.</li>
+ <li>Restart Firefox.</li>
+ </ol>
+ </div>
+
+ <!-- Other Browsers -->
+ <div v-else class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)]">
+ <h5 class="font-medium text-[var(--text-primary)] mb-2" v-text="t('help.unsupportedBrowser')"></h5>
+ <p class="text-sm text-[var(--text-muted)]">
+ For the best experience with system audio recording, we recommend using Google Chrome.
+ </p>
+ </div>
+ </div>
+ </div>
+ <div class="p-4 border-t border-[var(--border-primary)] flex justify-end flex-shrink-0">
+ <button @click="showSystemAudioHelp = false"
+ class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors">
+ Got it
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Recording Disclaimer Modal -->
+ <div v-if="showRecordingDisclaimerModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div class="bg-[var(--bg-secondary)] rounded-lg shadow-xl w-full max-w-2xl max-h-[80vh] flex flex-col overflow-hidden">
+ <div class="flex-shrink-0 p-6 border-b border-[var(--border-primary)]">
+ <div class="flex items-center gap-3">
+ <i class="fas fa-info-circle text-2xl text-[var(--text-accent)]"></i>
+ <h3 class="text-xl font-semibold text-[var(--text-primary)]" v-text="t('modal.recordingNotice')"></h3>
+ </div>
+ </div>
+ <div class="flex-1 overflow-y-auto p-6">
+ <!-- Render markdown content -->
+ <div class="prose prose-sm max-w-none text-[var(--text-secondary)]"
+ style="color: var(--text-secondary); line-height: 1.6;">
+ <div v-html="recordingDisclaimer"></div>
+ </div>
+ </div>
+ <div class="flex-shrink-0 p-6 border-t border-[var(--border-primary)] bg-[var(--bg-tertiary)] rounded-b-lg">
+ <div class="flex justify-end gap-3">
+ <button @click="cancelRecordingDisclaimer"
+ class="px-6 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-secondary)] rounded-lg transition-colors border border-[var(--border-secondary)]">
+ Cancel
+ </button>
+ <button @click="acceptRecordingDisclaimer"
+ class="px-6 py-2 bg-[var(--bg-accent)] text-white rounded-lg hover:bg-[var(--bg-accent-hover)] transition-colors">
+ <i class="fas fa-microphone mr-2"></i>
+ Start Recording
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Toast Container -->
+ <div id="toastContainer" class="fixed top-4 right-4 z-50 space-y-2"></div>
+
+ <!-- Share Modal -->
+ <div v-if="showShareModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div class="bg-[var(--bg-secondary)] rounded-lg shadow-xl w-full max-w-lg">
+ <div class="p-6 border-b border-[var(--border-primary)]">
+ <h3 class="text-lg font-semibold" v-text="t('modal.shareRecording')"></h3>
+ </div>
+ <div class="p-6 space-y-4">
+ <p class="text-sm text-[var(--text-muted)]" v-text="t('help.createPublicLink')"></p>
+ <div v-if="!generatedShareLink">
+ <div class="flex items-center mb-2">
+ <input type="checkbox" v-model="shareOptions.share_summary" id="share_summary" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
+ <label for="share_summary" class="ml-2 block text-sm text-[var(--text-secondary)]" v-text="t('form.shareSummary')"></label>
+ </div>
+ <div class="flex items-center">
+ <input type="checkbox" v-model="shareOptions.share_notes" id="share_notes" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
+ <label for="share_notes" class="ml-2 block text-sm text-[var(--text-secondary)]" v-text="t('form.shareNotes')"></label>
+ </div>
+ </div>
+ <div v-if="generatedShareLink" class="mt-4">
+ <div v-if="existingShareDetected" class="mb-3 p-3 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
+ <div class="flex items-start gap-2">
+ <i class="fas fa-info-circle text-blue-600 dark:text-blue-400 mt-0.5"></i>
+ <div class="text-sm text-blue-800 dark:text-blue-300">
+ <p class="font-medium">Using existing share link</p>
+ <p class="mt-1 text-xs opacity-90">This recording was already shared. The same link has been retrieved.</p>
+ </div>
+ </div>
+ </div>
+ <label class="block text-sm font-medium mb-2" v-text="t('form.shareableLink')"></label>
+ <div class="flex items-center gap-2">
+ <input :value="generatedShareLink" readonly class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg">
+ <button @click="copyShareLink" class="px-3 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)]">
+ <i class="fas fa-copy"></i>
+ </button>
+ </div>
+ <div v-if="existingShareDetected" class="mt-3">
+ <button @click="createShare(true)" class="text-sm text-[var(--text-accent)] hover:underline">
+ <i class="fas fa-plus-circle mr-1"></i>Create a new share link instead
+ </button>
+ </div>
+ </div>
+ </div>
+ <div class="p-6 border-t border-[var(--border-primary)] flex justify-end gap-3">
+ <button @click="closeShareModal" class="px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] rounded-lg transition-colors">
+ Cancel
+ </button>
+ <button @click="createShare()" v-if="!generatedShareLink" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors">
+ Create Link
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Shares List Modal -->
+ <div v-if="showSharesListModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div class="bg-[var(--bg-secondary)] rounded-lg shadow-xl w-full max-w-2xl max-h-[80vh] flex flex-col">
+ <div class="p-6 border-b border-[var(--border-primary)] flex justify-between items-center">
+ <h3 class="text-lg font-semibold" v-text="t('modal.sharedTranscripts')"></h3>
+ <button @click="closeSharesList" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+ <div class="p-6 space-y-4 overflow-y-auto">
+ <div v-if="isLoadingShares" class="text-center">
+ <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
+ </div>
+ <div v-else-if="userShares.length === 0" class="text-center text-[var(--text-muted)]">
+ <span v-text="t('sharedTranscripts.noSharedTranscripts')"></span>
+ </div>
+ <div v-else class="space-y-3">
+ <div v-for="share in userShares" :key="share.id" class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)]">
+ <div class="flex justify-between items-start">
+ <div>
+ <p class="font-semibold">${share.recording_title}</p>
+ <p class="text-sm text-[var(--text-muted)]">${ t('help.sharedOn') }: ${share.created_at}</p>
+ </div>
+ <button @click="confirmDeleteShare(share)" class="text-red-500 hover:text-red-700 p-1"><i class="fas fa-trash"></i></button>
+ </div>
+ <div class="mt-4 flex items-center gap-4">
+ <label class="flex items-center text-sm">
+ <input type="checkbox" v-model="share.share_summary" @change="updateShare(share)" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
+ <span class="ml-2" v-text="t('form.shareSummary')"></span>
+ </label>
+ <label class="flex items-center text-sm">
+ <input type="checkbox" v-model="share.share_notes" @change="updateShare(share)" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
+ <span class="ml-2" v-text="t('form.shareNotes')"></span>
+ </label>
+ </div>
+ <div class="mt-4">
+ <input :value="'{{ request.url_root }}share/' + share.public_id" readonly class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg text-sm">
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Share Delete Confirmation Modal -->
+ <div v-if="showShareDeleteModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-md transform transition-all duration-300 ease-in-out">
+ <!-- Header with gradient background -->
+ <div class="bg-gradient-to-r from-red-500 to-red-600 p-5 rounded-t-xl">
+ <div class="flex items-center">
+ <div class="w-12 h-12 bg-white/20 backdrop-blur rounded-full flex items-center justify-center mr-4">
+ <i class="fas fa-trash-alt text-white text-lg"></i>
+ </div>
+ <div>
+ <h3 class="text-lg font-bold text-white">Delete Shared Link</h3>
+ <p class="text-red-100 text-sm mt-1">This action cannot be undone</p>
+ </div>
+ </div>
+ </div>
+
+ <!-- Content -->
+ <div class="p-6">
+ <p class="text-[var(--text-secondary)] mb-4">
+ Are you sure you want to delete the shared link for:
+ </p>
+ <div v-if="shareToDelete" class="bg-[var(--bg-tertiary)] p-3 rounded-lg border border-[var(--border-primary)]">
+ <p class="font-medium text-[var(--text-primary)]">${shareToDelete.recording_title}</p>
+ <p class="text-sm text-[var(--text-muted)] mt-1">Shared on: ${shareToDelete.created_at}</p>
+ </div>
+ <div class="mt-4 p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
+ <div class="flex items-start">
+ <i class="fas fa-exclamation-triangle text-red-600 dark:text-red-400 mt-0.5 mr-2"></i>
+ <p class="text-sm text-red-800 dark:text-red-300">
+ The share link will be permanently deleted and anyone with this link will no longer be able to access the recording.
+ </p>
+ </div>
+ </div>
+ </div>
+
+ <!-- Actions -->
+ <div class="p-6 pt-0 flex justify-end gap-3">
+ <button @click="cancelDeleteShare" class="px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] rounded-lg transition-colors">
+ Cancel
+ </button>
+ <button @click="deleteShare" class="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors flex items-center gap-2">
+ <i class="fas fa-trash"></i>
+ Delete Share Link
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- Unified Internal Share Modal -->
+ <div v-if="showUnifiedShareModal && enableInternalSharing" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-3xl max-h-[90vh] flex flex-col">
+ <!-- Header -->
+ <div class="p-6 border-b border-[var(--border-primary)] flex justify-between items-center flex-shrink-0">
+ <div>
+ <h3 class="text-xl font-bold text-[var(--text-primary)]">Share Recording</h3>
+ <p class="text-sm text-[var(--text-muted)] mt-1">Share with users and manage access</p>
+ </div>
+ <button @click="closeUnifiedShareModal" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+
+ <!-- Content -->
+ <div class="flex-1 overflow-y-auto p-6 space-y-6">
+ <!-- Share with New User Section -->
+ <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)]">
+ <h4 class="font-semibold text-[var(--text-primary)] mb-3 flex items-center">
+ <i class="fas fa-user-plus mr-2 text-blue-500"></i>
+ Share with User
+ </h4>
+
+ <!-- User Search/Selection -->
+ <div v-if="showUsernamesInUI" class="space-y-3">
+ <!-- Search Input (for filtering) -->
+ <div class="relative">
+ <input
+ v-model="internalShareUserSearch"
+ @input="searchInternalShareUsers"
+ type="text"
+ placeholder="Search users..."
+ class="w-full px-4 py-2 pl-10 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
+ <i class="fas fa-search absolute left-3 top-3 text-[var(--text-muted)]"></i>
+ </div>
+
+ <!-- User Grid -->
+ <div v-if="isLoadingAllUsers" class="text-center py-8">
+ <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
+ <p class="mt-2 text-sm text-[var(--text-muted)]">Loading users...</p>
+ </div>
+ <div v-else-if="internalShareSearchResults.length === 0" class="text-center py-8 text-[var(--text-muted)]">
+ <i class="fas fa-users-slash text-3xl mb-2"></i>
+ <p>No users found</p>
+ </div>
+ <div v-else class="grid grid-cols-1 sm:grid-cols-2 gap-2 max-h-64 overflow-y-auto custom-scrollbar">
+ <div
+ v-for="user in internalShareSearchResults"
+ :key="user.id"
+ @click="createInternalShare(user.id, user.username)"
+ class="group p-3 bg-[var(--bg-secondary)] hover:bg-[var(--bg-hover)] rounded-lg border border-[var(--border-secondary)] hover:border-blue-500 cursor-pointer transition-all">
+ <div class="flex items-center justify-between">
+ <div class="flex items-center space-x-2 flex-1 min-w-0">
+ <div class="w-8 h-8 rounded-full bg-gradient-to-br from-blue-400 to-purple-500 flex items-center justify-center flex-shrink-0">
+ <span class="text-white text-xs font-bold">${user.username.charAt(0).toUpperCase()}</span>
+ </div>
+ <div class="flex-1 min-w-0">
+ <p class="font-medium text-[var(--text-primary)] truncate">${user.username}</p>
+ <p v-if="user.email" class="text-xs text-[var(--text-muted)] truncate">${user.email}</p>
+ </div>
+ </div>
+ <i class="fas fa-user-plus text-blue-500 group-hover:scale-110 transition-transform ml-2"></i>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Username Search Input (when SHOW_USERNAMES_IN_UI is disabled) -->
+ <div v-else class="space-y-3">
+ <p class="text-sm text-[var(--text-muted)]">Enter a username to share with</p>
+ <div class="relative">
+ <input
+ v-model="internalShareUserSearch"
+ @input="searchInternalShareUsers"
+ type="text"
+ placeholder="Type username to search..."
+ class="w-full px-4 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
+ <i v-if="isSearchingUsers" class="fas fa-spinner fa-spin absolute right-3 top-3 text-[var(--text-muted)]"></i>
+ </div>
+
+ <!-- Search Results -->
+ <div v-if="internalShareSearchResults.length > 0" class="space-y-2 max-h-48 overflow-y-auto">
+ <div
+ v-for="user in internalShareSearchResults"
+ :key="user.id"
+ @click="createInternalShare(user.id, user.username)"
+ class="p-3 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-hover)] hover:border-blue-500 cursor-pointer transition-all">
+ <div class="flex items-center justify-between">
+ <p class="font-medium">${'User #' + user.id}</p>
+ <i class="fas fa-user-plus text-blue-500"></i>
+ </div>
+ </div>
+ </div>
+
+ <div v-else-if="internalShareUserSearch.length >= 2 && !isSearchingUsers" class="text-center py-4 text-[var(--text-muted)]">
+ <i class="fas fa-search text-2xl mb-2"></i>
+ <p>No users found</p>
+ </div>
+
+ <div v-else-if="internalShareUserSearch.length < 2" class="text-center py-4 text-[var(--text-muted)]">
+ <i class="fas fa-keyboard text-2xl mb-2"></i>
+ <p>Type at least 2 characters to search</p>
+ </div>
+ </div>
+
+ <!-- Permissions -->
+ <div class="border-t border-[var(--border-primary)] mt-4 pt-4 space-y-2">
+ <p class="text-sm font-medium text-[var(--text-secondary)]">Share Permissions</p>
+ <div class="flex items-center">
+ <input type="checkbox" v-model="internalSharePermissions.can_edit" id="unified_share_can_edit" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
+ <label for="unified_share_can_edit" class="ml-2 block text-sm text-[var(--text-secondary)]">
+ <i class="fas fa-pencil-alt mr-1"></i>Allow editing notes and metadata
+ </label>
+ </div>
+ <div class="flex items-center">
+ <input type="checkbox" v-model="internalSharePermissions.can_reshare" id="unified_share_can_reshare" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
+ <label for="unified_share_can_reshare" class="ml-2 block text-sm text-[var(--text-secondary)]">
+ <i class="fas fa-share-alt mr-1"></i>Allow re-sharing with others
+ </label>
+ </div>
+ </div>
+ </div>
+
+ <!-- Already Shared With Section -->
+ <div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)]">
+ <h4 class="font-semibold text-[var(--text-primary)] mb-3 flex items-center justify-between">
+ <span>
+ <i class="fas fa-users-cog mr-2 text-purple-500"></i>
+ Already Shared With
+ </span>
+ <span v-if="recordingInternalShares.length > 0" class="text-sm font-normal text-[var(--text-muted)]">
+ ${recordingInternalShares.length} user(s)
+ </span>
+ </h4>
+
+ <div v-if="isLoadingInternalShares" class="text-center py-8">
+ <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
+ <p class="mt-2 text-sm text-[var(--text-muted)]">Loading shares...</p>
+ </div>
+ <div v-else-if="recordingInternalShares.length === 0" class="text-center py-8 text-[var(--text-muted)]">
+ <i class="fas fa-user-slash text-3xl mb-3"></i>
+ <p>Not shared with anyone yet</p>
+ <p class="text-sm mt-1">Select a user above to share this recording</p>
+ </div>
+ <div v-else class="space-y-2 max-h-80 overflow-y-auto custom-scrollbar">
+ <div
+ v-for="share in recordingInternalShares"
+ :key="share.user_id"
+ class="bg-[var(--bg-secondary)] p-4 rounded-lg border border-[var(--border-secondary)] hover:border-[var(--border-primary)] transition-colors">
+ <div class="flex justify-between items-start">
+ <div class="flex items-center space-x-3 flex-1">
+ <div class="w-10 h-10 rounded-full bg-gradient-to-br from-purple-400 to-pink-500 flex items-center justify-center flex-shrink-0">
+ <span class="text-white text-sm font-bold">${showUsernamesInUI ? share.username.charAt(0).toUpperCase() : '#'}</span>
+ </div>
+ <div class="flex-1">
+ <p class="font-semibold text-[var(--text-primary)]">${ showUsernamesInUI ? share.username : 'User #' + share.user_id }</p>
+ <p class="text-xs text-[var(--text-muted)] mt-1">Shared on ${share.created_at}</p>
+ <div class="flex gap-3 mt-2 text-xs">
+ <span v-if="share.can_edit" class="inline-flex items-center px-2 py-1 rounded-full bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400">
+ <i class="fas fa-pencil-alt mr-1"></i>Can edit
+ </span>
+ <span v-if="share.can_reshare" class="inline-flex items-center px-2 py-1 rounded-full bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400">
+ <i class="fas fa-share-alt mr-1"></i>Can re-share
+ </span>
+ <span v-if="!share.can_edit && !share.can_reshare" class="inline-flex items-center px-2 py-1 rounded-full bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-400">
+ <i class="fas fa-eye mr-1"></i>View only
+ </span>
+ </div>
+ </div>
+ </div>
+ <button
+ @click="revokeInternalShare(share.id, share.username)"
+ class="text-red-500 hover:text-red-700 p-2 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors ml-2"
+ title="Revoke access">
+ <i class="fas fa-user-times"></i>
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Footer -->
+ <div class="p-6 border-t border-[var(--border-primary)] flex justify-end flex-shrink-0">
+ <button @click="closeUnifiedShareModal" class="px-5 py-2.5 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-all duration-200 flex items-center font-medium">
+ <i class="fas fa-check mr-2"></i>
+ Done
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- CSRF Token Management -->
+ <script src="{{ url_for('static', filename='js/csrf-refresh.js') }}"></script>
+
+ <!-- i18n System -->
+ <script src="{{ url_for('static', filename='js/i18n.js') }}"></script>
+
+ <!-- Initialize i18n immediately with fallback -->
+ <script>
+ // Ensure i18n is initialized before Vue app
+ (async function() {
+ if (window.i18n && window.i18n.init) {
+ const userLang = localStorage.getItem('preferredLanguage') || '{{ user_language }}' || 'en';
+ try {
+ await window.i18n.init(userLang);
+ console.log('i18n pre-initialized with language:', userLang);
+ } catch (error) {
+ console.error('Failed to initialize i18n:', error);
+ }
+ }
+
+ // Hide loader after i18n is ready
+ const loader = document.getElementById('loader');
+ if (loader) {
+ loader.style.display = 'none';
+ }
+ })();
+ </script>
+
+ <!-- Service Worker Registration for PWA and Background Recording -->
+ <script>
+ // Register service worker for PWA functionality and background recording support
+ if ('serviceWorker' in navigator) {
+ window.addEventListener('load', () => {
+ navigator.serviceWorker.register('/static/service-worker.js')
+ .then((registration) => {
+ console.log('Service Worker registered successfully:', registration.scope);
+
+ // Check for updates periodically
+ setInterval(() => {
+ registration.update();
+ }, 60000); // Check every minute
+ })
+ .catch((error) => {
+ console.error('Service Worker registration failed:', error);
+ });
+ });
+ }
+ </script>
+
+ <!-- Vue.js Application Script -->
+ <script src="{{ url_for('static', filename='js/app.js') }}"></script>
+</body>
+</html>
diff --git a/templates/inquire.html b/templates/inquire.html
index 52e1143e..6543b6bd 100644
--- a/templates/inquire.html
+++ b/templates/inquire.html
@@ -4,6 +4,7 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="csrf-token" content="{{ csrf_token() }}">
+ <meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
<title>Inquire Mode - Speakr</title>
<!-- All dependencies bundled locally for offline support -->
<script src="{{ url_for('static', filename='vendor/js/tailwind.min.js') }}"></script>
@@ -20,7 +21,6 @@
<!-- Loading overlay to prevent FOUC -->
{% include 'includes/loading_overlay.html' %}
- <script src="{{ url_for('static', filename='js/loading.js') }}"></script>
<script>
tailwind.config = {
@@ -183,9 +183,10 @@
<button @click="openSharesList" class="w-full text-left px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors flex items-center">
<i class="fas fa-share-alt mr-2 w-4 text-center"></i><span v-text="t('modal.sharedTranscripts')"></span>
</button>
- {% if current_user.is_admin %}
+ {% if current_user.is_admin or is_group_admin %}
<a href="/admin" class="block px-4 py-2 hover:bg-[var(--bg-tertiary)] transition-colors">
- <i class="fas fa-user-shield mr-2 w-4 text-center"></i><span v-text="t('admin.title')"></span>
+ <i class="fas fa-{% if current_user.is_admin %}user-shield{% else %}users-cog{% endif %} mr-2 w-4 text-center"></i>
+ <span v-text="{% if current_user.is_admin %}t('admin.title'){% else %}t('nav.groupManagement'){% endif %}"></span>
</a>
{% endif %}
<div class="border-t border-[var(--border-primary)] my-1"></div>
@@ -430,26 +431,26 @@
</div>
<!-- Toast Container -->
- <div id="toastContainer" class="fixed bottom-4 right-4 z-50 space-y-2"></div>
+ <div id="toastContainer" class="fixed top-4 right-4 z-50 space-y-2"></div>
<!-- Color Scheme Modal -->
<div v-if="showColorSchemeModal" class="color-scheme-modal" @click.self="closeColorSchemeModal">
<div class="color-scheme-modal-content">
<div class="color-scheme-header">
<h2 class="color-scheme-title">
<i class="fas fa-palette"></i>
- Choose Color Scheme
+ <span v-text="t('colorScheme.title')"></span>
</h2>
<p class="color-scheme-subtitle" v-text="t('colorScheme.subtitle')"></p>
</div>
-
+
<div class="color-scheme-body">
<div class="color-scheme-section">
<h3 class="color-scheme-section-title">
<i :class="isDarkMode ? 'fas fa-moon' : 'fas fa-sun'"></i>
- ${isDarkMode ? 'Dark' : 'Light'} Themes
+ <span v-text="isDarkMode ? t('colorScheme.darkThemes') : t('colorScheme.lightThemes')"></span>
</h3>
<div class="color-scheme-grid">
- <div v-for="scheme in colorSchemes[isDarkMode ? 'dark' : 'light']"
+ <div v-for="scheme in colorSchemes[isDarkMode ? 'dark' : 'light']"
:key="scheme.id"
@click="selectColorScheme(scheme.id)"
:class="['color-scheme-option', currentColorScheme === scheme.id ? 'active' : '']">
@@ -458,8 +459,8 @@
<div :class="`preview-${isDarkMode ? 'dark-' : ''}${scheme.id}-secondary color-scheme-preview-segment`"></div>
<div :class="`preview-${isDarkMode ? 'dark-' : ''}${scheme.id}-tertiary color-scheme-preview-segment`"></div>
</div>
- <div class="color-scheme-name">${scheme.name}</div>
- <div class="color-scheme-description">${scheme.description}</div>
+ <div class="color-scheme-name" v-text="t('colorScheme.themes.' + (isDarkMode ? 'dark' : 'light') + '.' + scheme.id + '.name')"></div>
+ <div class="color-scheme-description" v-text="t('colorScheme.themes.' + (isDarkMode ? 'dark' : 'light') + '.' + scheme.id + '.description')"></div>
<div v-if="currentColorScheme === scheme.id" class="color-scheme-check">
<i class="fas fa-check"></i>
</div>
@@ -467,13 +468,12 @@
</div>
</div>
</div>
-
+
<div class="color-scheme-footer">
<button @click="resetColorScheme" class="color-scheme-reset-btn">
- <i class="fas fa-undo mr-2"></i>Reset to Default
+ <i class="fas fa-undo mr-2"></i><span v-text="t('colorScheme.resetToDefault')"></span>
</button>
- <button @click="closeColorSchemeModal" class="color-scheme-close-btn">
- Close
+ <button @click="closeColorSchemeModal" class="color-scheme-close-btn" v-text="t('common.close')">
</button>
</div>
</div>
diff --git a/templates/login.html b/templates/login.html
index 0df3560d..4af4d1cd 100644
--- a/templates/login.html
+++ b/templates/login.html
@@ -3,6 +3,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
<title>{{ title }} - Speakr</title>
<link rel="icon" href="{{ url_for('static', filename='img/favicon.ico') }}" type="image/svg+xml">
<!-- All dependencies bundled locally for offline support -->
@@ -13,7 +14,6 @@
<!-- Loading overlay to prevent FOUC -->
{% include 'includes/loading_overlay.html' %}
- <script src="{{ url_for('static', filename='js/loading.js') }}"></script>
<script>
// Function to apply the theme based on localStorage
@@ -54,7 +54,7 @@
<div class="container mx-auto px-4 sm:px-6 lg:px-8 py-6 flex flex-col min-h-screen">
<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">
+ <a href="{{ url_for('recordings.index') }}" class="flex items-center">
<img src="{{ url_for('static', filename='img/favicon.ico') }}" alt="Speakr Logo" class="h-9 w-9 mr-2">
Speakr
</a>
@@ -75,7 +75,7 @@
{% endif %}
{% endwith %}
- <form method="POST" action="{{ url_for('login') }}">
+ <form method="POST" action="{{ url_for('auth.login') }}">
{{ form.hidden_tag() }}
<div class="mb-4">
@@ -116,7 +116,7 @@
<div class="text-center text-sm text-[var(--text-muted)]">
<span>Don't have an account?</span>
- <a href="{{ url_for('register') }}" class="font-medium text-[var(--text-accent)] hover:underline">Register here</a>
+ <a href="{{ url_for('auth.register') }}" class="font-medium text-[var(--text-accent)] hover:underline">Register here</a>
</div>
</div>
</form>
diff --git a/templates/modals/add-speaker-modal.html b/templates/modals/add-speaker-modal.html
new file mode 100644
index 00000000..0ebe5ce8
--- /dev/null
+++ b/templates/modals/add-speaker-modal.html
@@ -0,0 +1,68 @@
+<!-- Add Speaker Modal -->
+<div v-if="showAddSpeakerModal" @click="closeAddSpeakerModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-md p-6">
+ <h3 class="text-xl font-bold text-[var(--text-primary)] mb-4" v-text="t('modal.addSpeaker')"></h3>
+
+ <!-- "This is Me" checkbox -->
+ <div class="mb-4">
+ <label class="flex items-center text-sm text-[var(--text-muted)] cursor-pointer hover:text-[var(--text-primary)] transition-colors">
+ <input type="checkbox" v-model="newSpeakerIsMe" class="speaker-checkbox">
+ <span class="ml-2 select-none" v-text="t('help.me')"></span>
+ </label>
+ </div>
+
+ <!-- Speaker name input with autocomplete (disabled if "This is Me" is checked) -->
+ <div class="mb-6 relative">
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-2" v-text="t('help.speakerName')">
+ </label>
+ <input
+ type="text"
+ v-model="newSpeakerName"
+ @input="searchNewSpeaker"
+ @focus="showNewSpeakerSuggestions = true"
+ @blur="hideNewSpeakerSuggestionsDelayed"
+ :disabled="newSpeakerIsMe"
+ :placeholder="newSpeakerIsMe ? currentUserName : t('help.enterSpeakerName')"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)] disabled:bg-[var(--bg-tertiary)] disabled:text-[var(--text-muted)] disabled:cursor-not-allowed"
+ @keyup.enter="addNewSpeaker"
+ autocomplete="off"
+ >
+
+ <!-- Loading indicator -->
+ <div v-if="loadingNewSpeakerSuggestions && !newSpeakerIsMe" class="absolute right-3 top-[42px] transform -translate-y-1/2">
+ <i class="fas fa-spinner fa-spin text-[var(--text-muted)] text-sm"></i>
+ </div>
+
+ <!-- Suggestions dropdown -->
+ <div v-if="showNewSpeakerSuggestions && newSpeakerSuggestions.length > 0 && !newSpeakerIsMe"
+ @click.stop
+ class="absolute z-10 w-full mt-1 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-md shadow-lg max-h-48 overflow-y-auto">
+ <div class="py-1">
+ <div v-for="suggestion in newSpeakerSuggestions"
+ :key="suggestion.id"
+ @click="selectNewSpeakerSuggestion(suggestion)"
+ class="px-3 py-2 cursor-pointer hover:bg-[var(--bg-tertiary)] flex items-center justify-between">
+ <div class="flex-grow">
+ <div class="text-sm font-medium text-[var(--text-primary)]">${ suggestion.name }</div>
+ <div class="text-xs text-[var(--text-muted)]">
+ Used ${ suggestion.use_count } time${ suggestion.use_count !== 1 ? 's' : '' }
+ <span v-if="suggestion.last_used">
+ • Last: ${ new Date(suggestion.last_used).toLocaleDateString() }
+ </span>
+ </div>
+ </div>
+ <i class="fas fa-user text-[var(--text-muted)] ml-2"></i>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Action buttons -->
+ <div class="flex justify-end space-x-3">
+ <button @click="closeAddSpeakerModal" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] transition-colors" v-text="t('common.cancel')">
+ </button>
+ <button @click="addNewSpeaker" class="px-4 py-2 bg-[var(--bg-accent)] text-[var(--text-accent)] rounded-lg hover:bg-[var(--bg-accent-hover)] transition-colors" v-text="t('buttons.addSpeaker')">
+ </button>
+ </div>
+ </div>
+</div>
diff --git a/templates/modals/asr-editor-modal.html b/templates/modals/asr-editor-modal.html
new file mode 100644
index 00000000..1bfabf60
--- /dev/null
+++ b/templates/modals/asr-editor-modal.html
@@ -0,0 +1,100 @@
+<!-- ASR Editor Modal -->
+<div v-if="showAsrEditorModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div @click="closeAllSpeakerSuggestions" class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-6xl flex flex-col max-h-[90vh]">
+ <div class="p-5 border-b border-[var(--border-primary)] flex-shrink-0 flex justify-between items-center">
+ <h3 class="text-xl font-bold text-[var(--text-primary)]" v-text="t('modal.editAsrTranscription')"></h3>
+ <button @click="closeAsrEditorModal" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+
+ <!-- Audio Player Section -->
+ <div class="px-6 py-4 border-b border-[var(--border-primary)] flex-shrink-0">
+ <div class="audio-player-container">
+ <!-- Show message if audio has been deleted -->
+ <div v-if="selectedRecording.audio_deleted_at"
+ class="bg-[var(--bg-tertiary)] border border-[var(--border-primary)] text-[var(--text-secondary)] px-4 py-3 rounded-lg flex items-center gap-2 text-sm">
+ <i class="fas fa-info-circle"></i>
+ <span v-text="t('help.audioDeletedMessage')"></span>
+ </div>
+ <audio v-else ref="asrEditorAudio" controls class="w-full" :key="'asr-editor-' + selectedRecording.id" :src="'/audio/' + selectedRecording.id" :volume="playerVolume" @volumechange="onPlayerVolumeChange">
+ Your browser does not support the audio element.
+ </audio>
+ </div>
+ </div>
+
+ <div class="flex-grow overflow-y-auto custom-scrollbar" @scroll="closeAllSpeakerSuggestions">
+ <table class="min-w-full asr-editor-table border border-[var(--border-primary)]">
+ <thead class="sticky top-0 z-10">
+ <tr class="text-xs uppercase text-[var(--text-muted)]">
+ <th class="w-40 text-left py-2 px-3 font-medium border border-[var(--border-primary)] bg-[var(--bg-tertiary)]" v-text="t('help.speakerCount')"></th>
+ <th class="w-20 text-left py-2 px-3 font-medium border border-[var(--border-primary)] bg-[var(--bg-tertiary)]" v-text="t('help.startTime')"></th>
+ <th class="w-20 text-left py-2 px-3 font-medium border border-[var(--border-primary)] bg-[var(--bg-tertiary)]" v-text="t('help.endTime')"></th>
+ <th class="text-left py-2 px-3 font-medium border border-[var(--border-primary)] bg-[var(--bg-tertiary)]" v-text="t('help.sentence')"></th>
+ <th class="w-24 text-center py-2 px-1 font-medium border border-[var(--border-primary)] bg-[var(--bg-tertiary)]"><span class="sr-only" v-text="t('help.actions')"></span></th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="(segment, index) in editingSegments" :key="segment.id || index" class="hover:bg-[var(--bg-tertiary)] transition-colors border-b border-[var(--border-primary)]">
+ <td class="border-r border-[var(--border-primary)] align-middle">
+ <div class="relative h-full" :ref="'speakerDropdown' + index">
+ <div class="flex items-center h-full">
+ <input type="text" v-model="segment.speaker"
+ @input="filterSpeakers(index); openSpeakerSuggestions(index)"
+ @focus="openSpeakerSuggestions(index)"
+ class="w-full h-full px-3 py-2.5 pr-7 bg-transparent border-0 focus:outline-none text-sm text-[var(--text-primary)]" />
+ <button type="button" @click.stop="openSpeakerSuggestions(index)"
+ class="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-[var(--text-muted)] hover:text-[var(--text-primary)] cursor-pointer">
+ <i class="fas fa-chevron-down text-xs"></i>
+ </button>
+ </div>
+ </div>
+ <!-- Fixed position dropdown that can escape modal overflow -->
+ <teleport to="body">
+ <div v-if="segment.showSuggestions"
+ class="fixed z-[100] w-40 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-md shadow-lg max-h-48 overflow-y-auto"
+ :style="getDropdownPosition(index)">
+ <div v-for="speaker in segment.filteredSpeakers" :key="speaker" @mousedown.prevent="selectSpeaker(index, speaker)" class="px-3 py-2 cursor-pointer hover:bg-[var(--bg-tertiary)] text-sm">${speaker}</div>
+ <div @mousedown.prevent="openEditSpeakersModal" class="px-3 py-2 cursor-pointer hover:bg-[var(--bg-accent)] text-sm text-[var(--text-accent)] border-t border-[var(--border-primary)] flex items-center">
+ <i class="fas fa-user-edit mr-2"></i> <span v-text="t('buttons.editSpeakers')"></span>
+ </div>
+ </div>
+ </teleport>
+ </td>
+ <td class="border-r border-[var(--border-primary)] align-middle">
+ <input type="number" step="0.01" v-model.number="segment.start_time" class="w-full px-3 py-2.5 bg-transparent border-0 focus:outline-none text-sm text-[var(--text-primary)] text-center" />
+ </td>
+ <td class="border-r border-[var(--border-primary)] align-middle">
+ <input type="number" step="0.01" v-model.number="segment.end_time" class="w-full px-3 py-2.5 bg-transparent border-0 focus:outline-none text-sm text-[var(--text-primary)] text-center" />
+ </td>
+ <td class="border-r border-[var(--border-primary)] align-top">
+ <textarea v-model="segment.sentence" rows="1" class="w-full px-3 py-2.5 bg-transparent border-0 focus:outline-none text-sm text-[var(--text-primary)] resize-none max-h-20 overflow-y-auto custom-scrollbar block" @input="autoResizeTextarea($event)"></textarea>
+ </td>
+ <td class="px-1 text-center align-middle">
+ <div class="flex items-center justify-center gap-1">
+ <button @click="seekToSegmentTime(segment.start_time)" class="p-1.5 rounded hover:bg-[var(--bg-accent)] text-[var(--text-muted)] hover:text-[var(--text-accent)] transition-colors" :title="t('help.playFromHere')">
+ <i class="fas fa-play text-xs"></i>
+ </button>
+ <button @click="addSegmentBelow(index)" class="p-1.5 rounded hover:bg-green-600/20 text-[var(--text-muted)] hover:text-green-500 transition-colors" :title="t('help.addSegmentBelow')">
+ <i class="fas fa-plus text-xs"></i>
+ </button>
+ <button @click="removeSegment(index)" class="p-1.5 rounded hover:bg-red-600/20 text-[var(--text-muted)] hover:text-red-500 transition-colors" :title="t('help.deleteSegment')">
+ <i class="fas fa-trash text-xs"></i>
+ </button>
+ </div>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ <div class="py-4 flex justify-center">
+ <button @click="addSegment" class="px-4 py-2 bg-[var(--bg-accent)] text-[var(--text-accent)] rounded-lg hover:bg-[var(--bg-accent-hover)] flex items-center text-sm">
+ <i class="fas fa-plus mr-2"></i> <span v-text="t('buttons.addSegment')"></span>
+ </button>
+ </div>
+ </div>
+ <div class="bg-[var(--bg-tertiary)] px-6 py-4 flex justify-end space-x-3 border-t border-[var(--border-primary)] flex-shrink-0 rounded-b-xl">
+ <button @click="closeAsrEditorModal" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)]" v-text="t('common.cancel')"></button>
+ <button @click="saveAsrTranscription" class="px-4 py-2 bg-[var(--bg-accent)] text-[var(--text-accent)] rounded-lg hover:bg-[var(--bg-accent-hover)]" v-text="t('buttons.saveChanges')"></button>
+ </div>
+ </div>
+</div>
diff --git a/templates/modals/color-scheme-modal.html b/templates/modals/color-scheme-modal.html
new file mode 100644
index 00000000..e331ab27
--- /dev/null
+++ b/templates/modals/color-scheme-modal.html
@@ -0,0 +1,46 @@
+<!-- Color Scheme Modal -->
+<div v-if="showColorSchemeModal" class="color-scheme-modal" @click.self="closeColorSchemeModal">
+ <div class="color-scheme-modal-content">
+ <div class="color-scheme-header">
+ <h2 class="color-scheme-title">
+ <i class="fas fa-palette"></i>
+ <span v-text="t('colorScheme.title')"></span>
+ </h2>
+ <p class="color-scheme-subtitle" v-text="t('colorScheme.subtitle')"></p>
+ </div>
+
+ <div class="color-scheme-body">
+ <div class="color-scheme-section">
+ <h3 class="color-scheme-section-title">
+ <i :class="isDarkMode ? 'fas fa-moon' : 'fas fa-sun'"></i>
+ <span v-text="isDarkMode ? t('colorScheme.darkThemes') : t('colorScheme.lightThemes')"></span>
+ </h3>
+ <div class="color-scheme-grid">
+ <div v-for="scheme in colorSchemes[isDarkMode ? 'dark' : 'light']"
+ :key="scheme.id"
+ @click="selectColorScheme(scheme.id)"
+ :class="['color-scheme-option', currentColorScheme === scheme.id ? 'active' : '']">
+ <div class="color-scheme-preview">
+ <div :class="`preview-${isDarkMode ? 'dark-' : ''}${scheme.id}-primary color-scheme-preview-segment`"></div>
+ <div :class="`preview-${isDarkMode ? 'dark-' : ''}${scheme.id}-secondary color-scheme-preview-segment`"></div>
+ <div :class="`preview-${isDarkMode ? 'dark-' : ''}${scheme.id}-tertiary color-scheme-preview-segment`"></div>
+ </div>
+ <div class="color-scheme-name" v-text="t('colorScheme.themes.' + (isDarkMode ? 'dark' : 'light') + '.' + scheme.id + '.name')"></div>
+ <div class="color-scheme-description" v-text="t('colorScheme.themes.' + (isDarkMode ? 'dark' : 'light') + '.' + scheme.id + '.description')"></div>
+ <div v-if="currentColorScheme === scheme.id" class="color-scheme-check">
+ <i class="fas fa-check"></i>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div class="color-scheme-footer">
+ <button @click="resetColorScheme" class="color-scheme-reset-btn">
+ <i class="fas fa-undo mr-2"></i><span v-text="t('colorScheme.resetToDefault')"></span>
+ </button>
+ <button @click="closeColorSchemeModal" class="color-scheme-close-btn" v-text="t('common.close')">
+ </button>
+ </div>
+ </div>
+</div>
diff --git a/templates/modals/delete-modal.html b/templates/modals/delete-modal.html
new file mode 100644
index 00000000..19fac012
--- /dev/null
+++ b/templates/modals/delete-modal.html
@@ -0,0 +1,27 @@
+<!-- Delete Confirmation Modal -->
+<div v-if="showDeleteModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div class="bg-[var(--bg-secondary)] rounded-lg shadow-xl w-full max-w-md">
+ <div class="p-6">
+ <div class="flex items-center gap-4 mb-4">
+ <i class="fas fa-exclamation-triangle text-3xl text-[var(--text-danger)]"></i>
+ <div>
+ <h3 class="text-lg font-semibold" v-text="t('modal.deleteRecording')"></h3>
+ <p class="text-[var(--text-muted)]" v-text="t('help.thisActionCannotBeUndone')"></p>
+ </div>
+ </div>
+ <p class="text-[var(--text-secondary)] mb-6">
+ Are you sure you want to delete "${recordingToDelete?.title || 'this recording'}"?
+ </p>
+ <div class="flex justify-end gap-3">
+ <button @click="cancelDelete"
+ class="px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] rounded-lg transition-colors">
+ Cancel
+ </button>
+ <button @click="deleteRecording"
+ class="px-4 py-2 bg-[var(--bg-danger)] text-white rounded-lg hover:bg-[var(--bg-danger-hover)] transition-colors">
+ Delete
+ </button>
+ </div>
+ </div>
+ </div>
+</div>
diff --git a/templates/modals/edit-modal.html b/templates/modals/edit-modal.html
new file mode 100644
index 00000000..a74686ed
--- /dev/null
+++ b/templates/modals/edit-modal.html
@@ -0,0 +1,43 @@
+<!-- Edit Modal -->
+<div v-if="showEditModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div class="bg-[var(--bg-secondary)] rounded-lg shadow-xl w-full max-w-lg">
+ <div class="p-6 border-b border-[var(--border-primary)]">
+ <h3 class="text-lg font-semibold" v-text="t('modal.editRecording')"></h3>
+ </div>
+ <div class="p-6 space-y-4">
+ <div>
+ <label class="block text-sm font-medium mb-2" v-text="t('form.title')"></label>
+ <input v-model="editingRecording.title"
+ class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]">
+ </div>
+ <div>
+ <label class="block text-sm font-medium mb-2" v-text="t('form.participants')"></label>
+ <input v-model="editingRecording.participants"
+ class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]">
+ </div>
+ <div>
+ <label class="block text-sm font-medium mb-2" v-text="t('form.meetingDate')"></label>
+ <input v-model="editingRecording.meeting_date"
+ type="date"
+ class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]">
+ </div>
+ <div>
+ <label class="block text-sm font-medium mb-2" v-text="t('form.notes')"></label>
+ <textarea v-model="editingRecording.notes"
+ rows="4"
+ class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]">
+ </textarea>
+ </div>
+ </div>
+ <div class="p-6 border-t border-[var(--border-primary)] flex justify-end gap-3">
+ <button @click="cancelEdit"
+ class="px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] rounded-lg transition-colors">
+ Cancel
+ </button>
+ <button @click="saveEdit"
+ class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors">
+ Save Changes
+ </button>
+ </div>
+ </div>
+</div>
diff --git a/templates/modals/edit-participants-modal.html b/templates/modals/edit-participants-modal.html
new file mode 100644
index 00000000..a55faea4
--- /dev/null
+++ b/templates/modals/edit-participants-modal.html
@@ -0,0 +1,56 @@
+<!-- Edit Participants Modal -->
+<div v-if="showEditParticipantsModal" @click="closeEditParticipantsModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div @click.stop="closeAllParticipantSuggestions" class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-md max-h-[80vh] flex flex-col">
+ <div class="p-6 border-b border-[var(--border-primary)] flex-shrink-0">
+ <h3 class="text-lg font-semibold" v-text="t('modal.editParticipants')"></h3>
+ </div>
+ <div class="p-6 overflow-y-auto flex-1" @scroll="closeAllParticipantSuggestions">
+ <p class="text-sm text-[var(--text-muted)] mb-4">Manage participants for this recording.</p>
+
+ <div class="space-y-2">
+ <div v-for="(participant, index) in editingParticipantsList" :key="index" class="relative">
+ <div class="flex items-center gap-2">
+ <div class="flex-1 relative" @click.stop>
+ <input v-model="participant.name"
+ @input="filterParticipantSuggestions(index)"
+ @focus="filterParticipantSuggestions(index)"
+ @blur="closeParticipantSuggestionsDelayed(index)"
+ type="text"
+ class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)] text-sm"
+ placeholder="Participant name...">
+ </div>
+ <!-- Teleported Suggestions dropdown -->
+ <teleport to="body">
+ <div v-if="editingParticipantSuggestions[index]?.length > 0"
+ class="fixed z-[100] bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg shadow-lg max-h-32 overflow-y-auto"
+ :style="getParticipantDropdownPosition(index)">
+ <button v-for="suggestion in editingParticipantSuggestions[index]" :key="suggestion"
+ @mousedown="selectParticipantSuggestion(index, suggestion)"
+ class="w-full px-3 py-2 text-left hover:bg-[var(--bg-tertiary)] transition-colors text-sm">
+ ${suggestion}
+ </button>
+ </div>
+ </teleport>
+ <button @click="removeParticipant(index)"
+ class="p-1 text-[var(--text-muted)] hover:text-red-500 transition-colors">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <button @click="addParticipant"
+ class="mt-4 w-full px-3 py-2 border border-dashed border-[var(--border-secondary)] rounded-lg text-sm text-[var(--text-muted)] hover:border-[var(--border-accent)] hover:text-[var(--text-accent)] transition-colors">
+ <i class="fas fa-plus mr-2"></i>Add Participant
+ </button>
+ </div>
+ <div class="p-6 border-t border-[var(--border-primary)] flex justify-end gap-3">
+ <button @click="closeEditParticipantsModal" class="px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] rounded-lg transition-colors">
+ Cancel
+ </button>
+ <button @click="saveParticipants" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors">
+ Save Changes
+ </button>
+ </div>
+ </div>
+</div>
diff --git a/templates/modals/edit-speakers-modal.html b/templates/modals/edit-speakers-modal.html
new file mode 100644
index 00000000..aaf3bc2c
--- /dev/null
+++ b/templates/modals/edit-speakers-modal.html
@@ -0,0 +1,58 @@
+<!-- Edit Speakers Modal -->
+<div v-if="showEditSpeakersModal" @click="closeEditSpeakersModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-md max-h-[80vh] flex flex-col">
+ <div class="p-6 border-b border-[var(--border-primary)] flex-shrink-0">
+ <h3 class="text-lg font-semibold" v-text="t('modal.editSpeakers')"></h3>
+ </div>
+ <div class="p-6 overflow-y-auto flex-1">
+ <p class="text-sm text-[var(--text-muted)] mb-4">Rename speakers in the transcript.</p>
+
+ <div class="space-y-3">
+ <div v-for="(speaker, index) in editingSpeakersList" :key="index" class="relative">
+ <div class="flex items-center gap-2">
+ <span class="w-24 text-sm text-[var(--text-muted)] truncate">${speaker.original || 'New'}</span>
+ <i class="fas fa-arrow-right text-[var(--text-muted)]"></i>
+ <div class="flex-1 relative" :ref="'editSpeakerInput' + index">
+ <input v-model="speaker.current"
+ @input="filterEditingSpeakerSuggestions(index)"
+ @focus="filterEditingSpeakerSuggestions(index)"
+ @blur="onEditSpeakerBlur(index)"
+ type="text"
+ class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)] text-sm"
+ placeholder="New name...">
+ </div>
+ <!-- Teleported Suggestions dropdown -->
+ <teleport to="body">
+ <div v-if="editingSpeakerSuggestions[index]?.length > 0"
+ class="fixed z-[100] bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-lg shadow-lg max-h-32 overflow-y-auto"
+ :style="getEditSpeakerDropdownPosition(index)">
+ <button v-for="suggestion in editingSpeakerSuggestions[index]" :key="suggestion.id"
+ @mousedown="selectEditingSpeakerSuggestion(index, suggestion.name)"
+ class="w-full px-3 py-2 text-left hover:bg-[var(--bg-tertiary)] transition-colors text-sm">
+ ${suggestion.name}
+ </button>
+ </div>
+ </teleport>
+ <button @click="removeEditingSpeaker(index)"
+ class="p-1 text-[var(--text-muted)] hover:text-red-500 transition-colors">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <button @click="addEditingSpeaker"
+ class="mt-4 w-full px-3 py-2 border border-dashed border-[var(--border-secondary)] rounded-lg text-sm text-[var(--text-muted)] hover:border-[var(--border-accent)] hover:text-[var(--text-accent)] transition-colors">
+ <i class="fas fa-plus mr-2"></i>Add Speaker
+ </button>
+ </div>
+ <div class="p-6 border-t border-[var(--border-primary)] flex justify-end gap-3">
+ <button @click="closeEditSpeakersModal" class="px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] rounded-lg transition-colors">
+ Cancel
+ </button>
+ <button @click="saveEditingSpeakers" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors">
+ Save Changes
+ </button>
+ </div>
+ </div>
+</div>
diff --git a/templates/modals/edit-tags-modal.html b/templates/modals/edit-tags-modal.html
new file mode 100644
index 00000000..e9012a31
--- /dev/null
+++ b/templates/modals/edit-tags-modal.html
@@ -0,0 +1,61 @@
+<!-- Edit Tags Modal -->
+<div v-if="showEditTagsModal" @click="closeEditTagsModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-md max-h-[80vh] flex flex-col">
+ <div class="p-6 border-b border-[var(--border-primary)] flex-shrink-0">
+ <h3 class="text-lg font-semibold" v-text="t('modal.editTags')"></h3>
+ </div>
+ <div class="p-6 overflow-y-auto flex-1">
+ <!-- Current Tags -->
+ <div class="mb-4">
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-2" v-text="t('tags.currentTags')"></label>
+ <div v-if="selectedRecording && getRecordingTags(selectedRecording).length > 0" class="flex flex-wrap gap-2">
+ <span v-for="tag in getRecordingTags(selectedRecording)" :key="tag.id"
+ class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium cursor-help"
+ :style="{ backgroundColor: tag.color, color: getContrastTextColor(tag.color) }"
+ :title="tag.group_id ? ('Group: ' + tag.group_name) : tag.name">
+ <i v-if="tag.group_id" class="fas fa-users mr-1.5 text-xs"></i>
+ <span v-if="tag.group_id" class="opacity-75">${ tag.group_name }: </span>${ tag.name }
+ <button @click="removeTagFromRecording(tag.id)" class="ml-2 hover:opacity-80">
+ <i class="fas fa-times text-xs"></i>
+ </button>
+ </span>
+ </div>
+ <p v-else class="text-sm text-[var(--text-muted)] italic" v-text="t('tags.noTags')"></p>
+ </div>
+
+ <!-- Add Tags -->
+ <div>
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-2" v-text="t('tags.addTag')"></label>
+
+ <!-- Search -->
+ <div class="relative mb-3">
+ <input v-model="tagSearchFilter" type="text" :placeholder="t('tagsModal.searchTags')"
+ class="w-full px-3 py-2 pl-9 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]">
+ <i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-[var(--text-muted)]"></i>
+ </div>
+
+ <!-- Available Tags -->
+ <div class="max-h-48 overflow-y-auto space-y-2">
+ <button v-for="tag in filteredAvailableTagsForModal" :key="tag.id"
+ @click="addTagToRecording(tag.id)"
+ class="w-full flex items-center justify-between px-3 py-2 rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] transition-colors">
+ <div class="flex items-center gap-2">
+ <i v-if="tag.group_id" class="fas fa-users text-xs flex-shrink-0" :style="{ color: tag.color }"></i>
+ <span v-else class="w-3 h-3 rounded-full flex-shrink-0" :style="{ backgroundColor: tag.color }"></span>
+ <span class="text-sm">
+ <span v-if="tag.group_id" class="opacity-75">${ tag.group_name }: </span>${ tag.name }
+ </span>
+ </div>
+ <i class="fas fa-plus text-[var(--text-muted)]"></i>
+ </button>
+ </div>
+ <p v-if="filteredAvailableTagsForModal.length === 0" class="text-sm text-[var(--text-muted)] text-center py-4" v-text="t('tags.noAvailableTags')"></p>
+ </div>
+ </div>
+ <div class="p-6 border-t border-[var(--border-primary)] flex justify-end">
+ <button @click="closeEditTagsModal" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors">
+ <span v-text="t('tagsModal.done')"></span>
+ </button>
+ </div>
+ </div>
+</div>
diff --git a/templates/modals/edit-text-modal.html b/templates/modals/edit-text-modal.html
new file mode 100644
index 00000000..6ad03c0e
--- /dev/null
+++ b/templates/modals/edit-text-modal.html
@@ -0,0 +1,29 @@
+<!-- Edit Text Modal -->
+<div v-if="showEditTextModal" @click="closeEditTextModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-2xl p-6">
+ <h3 class="text-xl font-bold text-[var(--text-primary)] mb-4">Edit Transcript Text</h3>
+
+ <!-- Text editor -->
+ <div class="mb-6">
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-2">
+ Text Content
+ </label>
+ <textarea
+ v-model="editedText"
+ rows="6"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)] resize-y"
+ placeholder="Enter transcript text..."
+ ></textarea>
+ </div>
+
+ <!-- Action buttons -->
+ <div class="flex justify-end space-x-3">
+ <button @click="closeEditTextModal" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] transition-colors">
+ Cancel
+ </button>
+ <button @click="saveEditedText" class="px-4 py-2 bg-[var(--bg-accent)] text-[var(--text-accent)] rounded-lg hover:bg-[var(--bg-accent-hover)] transition-colors">
+ Save Changes
+ </button>
+ </div>
+ </div>
+</div>
diff --git a/templates/modals/global-error.html b/templates/modals/global-error.html
new file mode 100644
index 00000000..5126bc06
--- /dev/null
+++ b/templates/modals/global-error.html
@@ -0,0 +1,18 @@
+<!-- Global Error Display - DEPRECATED: Now using toast system for all errors -->
+<!-- Keeping this commented out in case we need to revert
+<div v-if="globalError"
+ class="fixed top-4 right-4 text-white p-4 rounded-lg shadow-lg z-[60] max-w-md border"
+ style="background-color: #ef4444; border-color: #dc2626;">
+ <div class="flex items-start gap-3">
+ <i class="fas fa-exclamation-circle text-xl flex-shrink-0 mt-0.5"></i>
+ <div class="flex-1">
+ <p class="font-semibold mb-1" v-text="t('common.error')"></p>
+ <p class="text-sm">${globalError}</p>
+ </div>
+ <button @click="globalError = null"
+ class="text-white hover:opacity-80 transition-opacity flex-shrink-0">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+</div>
+-->
diff --git a/templates/modals/reprocess-modal.html b/templates/modals/reprocess-modal.html
new file mode 100644
index 00000000..b910b9a4
--- /dev/null
+++ b/templates/modals/reprocess-modal.html
@@ -0,0 +1,172 @@
+<!-- Reprocess Modal -->
+<div v-if="showReprocessModal" @click="cancelReprocess" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm transition-all duration-300 ease-in-out">
+ <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-md transform transition-all duration-300 ease-in-out">
+ <!-- Header with gradient background -->
+ <div class="bg-gradient-to-r from-[var(--bg-accent)] to-[var(--bg-secondary)] p-5 rounded-t-xl flex items-center">
+ <div class="flex items-center">
+ <div class="w-12 h-12 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center mr-4 shadow-lg">
+ <i class="fas fa-sync-alt text-white text-lg"></i>
+ </div>
+ <div>
+ <h3 class="text-xl font-bold text-[var(--text-primary)] mb-1" v-text="t('help.confirmReprocessingTitle')"></h3>
+ <p class="text-sm text-[var(--text-muted)] capitalize">${ reprocessType } reprocessing</p>
+ </div>
+ </div>
+ </div>
+
+ <!-- Content -->
+ <div class="p-6 modal-content">
+ <div v-if="reprocessRecording" class="mb-6">
+ <div class="bg-[var(--bg-tertiary)] rounded-lg p-4 border border-[var(--border-primary)]">
+ <div class="flex items-start space-x-3">
+ <i class="fas fa-file-audio text-[var(--text-accent)] mt-1"></i>
+ <div class="flex-1 min-w-0">
+ <h4 class="font-medium text-[var(--text-primary)] truncate" :title="reprocessRecording.title">
+ ${ reprocessRecording.title || 'Untitled Recording' }
+ </h4>
+ <p class="text-sm text-[var(--text-muted)] mt-1">
+ Created: ${ new Date(reprocessRecording.created_at).toLocaleDateString() }
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div class="space-y-4">
+ <div class="flex items-start space-x-3">
+ <div class="w-6 h-6 bg-amber-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
+ <i class="fas fa-exclamation-triangle text-amber-600 text-xs"></i>
+ </div>
+ <div>
+ <p class="text-[var(--text-secondary)] font-medium mb-1" v-text="t('help.whatWillHappen')"></p>
+ <p class="text-sm text-[var(--text-muted)]" v-if="reprocessType === 'transcription' && !useAsrEndpoint">
+ <span v-text="t('reprocessModal.audioReTranscribedFromScratch')"></span>
+ </p>
+ <p class="text-sm text-[var(--text-muted)]" v-else-if="reprocessType === 'transcription' && useAsrEndpoint">
+ <span v-text="t('reprocessModal.audioReTranscribedWithAsr')"></span>
+ </p>
+ <p class="text-sm text-[var(--text-muted)]" v-else-if="reprocessType === 'summary'">
+ <span v-text="t('reprocessModal.newTitleAndSummary')"></span>
+ </p>
+ </div>
+ </div>
+
+ <!-- ASR Options -->
+ <div v-if="reprocessType === 'transcription' && useAsrEndpoint" class="space-y-4 pt-4 border-t border-[var(--border-primary)]">
+ <h4 class="text-md font-semibold text-[var(--text-secondary)]" v-text="t('help.advancedAsrOptions')"></h4>
+ <div>
+ <label for="asr-language-reprocess" class="block text-sm font-medium text-[var(--text-muted)]" v-text="t('form.language')"></label>
+ <input type="text" id="asr-language-reprocess" v-model="asrReprocessOptions.language" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" placeholder="e.g., en, es, zh (optional)">
+ </div>
+ <div>
+ <label for="asr-min-speakers-reprocess" class="block text-sm font-medium text-[var(--text-muted)]" v-text="t('form.minSpeakers')"></label>
+ <input type="number" id="asr-min-speakers-reprocess" v-model.number="asrReprocessOptions.min_speakers" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" :placeholder="t('form.optional')">
+ </div>
+ <div>
+ <label for="asr-max-speakers-reprocess" class="block text-sm font-medium text-[var(--text-muted)]" v-text="t('form.maxSpeakers')"></label>
+ <input type="number" id="asr-max-speakers-reprocess" v-model.number="asrReprocessOptions.max_speakers" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" :placeholder="t('form.optional')">
+ </div>
+ </div>
+
+ <!-- Custom Prompt Options for Summary Reprocessing -->
+ <div v-if="reprocessType === 'summary'" class="space-y-4 pt-4 border-t border-[var(--border-primary)]">
+ <h4 class="text-md font-semibold text-[var(--text-secondary)]">Custom Summarization Prompt</h4>
+
+ <!-- Prompt Source Selection -->
+ <div>
+ <label class="block text-sm font-medium text-[var(--text-muted)] mb-2">Prompt Source</label>
+ <div class="space-y-2">
+ <label class="flex items-center space-x-2 cursor-pointer">
+ <input type="radio" v-model="summaryReprocessPromptSource" value="default" class="text-[var(--text-accent)]" name="promptSource">
+ <span class="text-sm text-[var(--text-secondary)]">Use default prompt</span>
+ </label>
+ <label class="flex items-center space-x-2 cursor-pointer" v-if="tagsWithCustomPrompts.length > 0">
+ <input type="radio" v-model="summaryReprocessPromptSource" value="tag" class="text-[var(--text-accent)]" name="promptSource">
+ <span class="text-sm text-[var(--text-secondary)]">Use prompt from tag</span>
+ </label>
+ <label class="flex items-center space-x-2 cursor-pointer">
+ <input type="radio" v-model="summaryReprocessPromptSource" value="custom" class="text-[var(--text-accent)]" name="promptSource">
+ <span class="text-sm text-[var(--text-secondary)]">Enter custom prompt</span>
+ </label>
+ </div>
+ </div>
+
+ <!-- Tag Selection (shown when 'tag' is selected) -->
+ <div v-if="summaryReprocessPromptSource === 'tag' && tagsWithCustomPrompts.length > 0">
+ <label for="reprocess-tag-select" class="block text-sm font-medium text-[var(--text-muted)] mb-2">Select Tag</label>
+ <select id="reprocess-tag-select" v-model="summaryReprocessSelectedTagId" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] text-sm bg-[var(--bg-input)] text-[var(--text-primary)]">
+ <option value="">Select a tag...</option>
+ <option v-for="tag in tagsWithCustomPrompts" :key="tag.id" :value="tag.id">${ tag.name }</option>
+ </select>
+ <div v-if="summaryReprocessSelectedTagId" class="mt-2 p-2 bg-[var(--bg-tertiary)] rounded text-xs text-[var(--text-muted)] max-h-20 overflow-y-auto">
+ <strong>Preview:</strong> ${ getTagPromptPreview(summaryReprocessSelectedTagId) }
+ </div>
+ </div>
+
+ <!-- Custom Prompt Textarea (shown when 'custom' is selected) -->
+ <div v-if="summaryReprocessPromptSource === 'custom'">
+ <label for="reprocess-custom-prompt" class="block text-sm font-medium text-[var(--text-muted)] mb-2">Custom Prompt</label>
+ <textarea id="reprocess-custom-prompt" v-model="summaryReprocessCustomPrompt" rows="4" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] text-sm bg-[var(--bg-input)] text-[var(--text-primary)]" placeholder="Enter your custom summarization instructions..."></textarea>
+ </div>
+
+ <!-- Info message when no tags with custom prompts exist -->
+ <div v-if="summaryReprocessPromptSource === 'tag' && tagsWithCustomPrompts.length === 0" class="text-xs text-[var(--text-muted)] italic">
+ No tags with custom prompts available. Create tags with custom prompts in the Account Settings.
+ </div>
+ </div>
+
+ <div class="flex items-start space-x-3">
+ <div class="w-6 h-6 bg-blue-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
+ <i class="fas fa-clock text-blue-600 text-xs"></i>
+ </div>
+ <div>
+ <p class="text-[var(--text-secondary)] font-medium mb-1" v-text="t('help.processingTime')"></p>
+ <p class="text-sm text-[var(--text-muted)]">
+ <span v-text="t('help.processingTimeDescription')"></span>
+ </p>
+ </div>
+ </div>
+
+ <div class="flex items-start space-x-3" v-if="reprocessType === 'transcription'">
+ <div class="w-6 h-6 bg-red-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
+ <i class="fas fa-info-circle text-red-600 text-xs"></i>
+ </div>
+ <div>
+ <p class="text-[var(--text-secondary)] font-medium mb-1" v-text="t('help.importantNote')"></p>
+ <p class="text-sm text-[var(--text-muted)]">
+ <span v-text="t('reprocessModal.manualEditsOverwritten')"></span>
+ </p>
+ </div>
+ </div>
+
+ <div class="flex items-start space-x-3" v-else-if="reprocessType === 'summary'">
+ <div class="w-6 h-6 bg-red-100 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
+ <i class="fas fa-info-circle text-red-600 text-xs"></i>
+ </div>
+ <div>
+ <p class="text-[var(--text-secondary)] font-medium mb-1" v-text="t('help.importantNote')"></p>
+ <p class="text-sm text-[var(--text-muted)]">
+ <span v-text="t('reprocessModal.manualEditsOverwrittenSummary')"></span>
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Footer with action buttons -->
+ <div class="bg-[var(--bg-tertiary)] px-6 py-4 rounded-b-xl flex justify-end space-x-3 border-t border-[var(--border-primary)]">
+ <button
+ @click="cancelReprocess"
+ class="px-5 py-2.5 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)] transition-all duration-200 flex items-center shadow-sm font-medium">
+ <i class="fas fa-times mr-2"></i>
+ Cancel
+ </button>
+ <button
+ @click="executeReprocess"
+ class="px-5 py-2.5 bg-gradient-to-r from-blue-500 to-purple-600 text-white rounded-lg hover:from-blue-600 hover:to-purple-700 transition-all duration-200 flex items-center shadow-lg font-medium transform hover:scale-105">
+ <i class="fas fa-sync-alt mr-2"></i>
+ Start Reprocessing
+ </button>
+ </div>
+ </div>
+</div>
diff --git a/templates/modals/reset-modal.html b/templates/modals/reset-modal.html
new file mode 100644
index 00000000..d982888c
--- /dev/null
+++ b/templates/modals/reset-modal.html
@@ -0,0 +1,22 @@
+<!-- Reset Status Confirmation Modal -->
+<div v-if="showResetModal" @click="cancelReset" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-md">
+ <div class="p-6 text-center">
+ <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-orange-100 dark:bg-orange-800 mb-4">
+ <i class="fas fa-exclamation-triangle text-2xl text-orange-500 dark:text-orange-300"></i>
+ </div>
+ <h3 class="text-lg font-semibold text-[var(--text-primary)] mb-2" v-text="t('modal.resetStatus')"></h3>
+ <p class="text-sm text-[var(--text-muted)] mb-6">
+ This will mark the recording as 'Failed'. This is useful if processing is stuck. You will be able to reprocess it afterwards.
+ </p>
+ </div>
+ <div class="bg-[var(--bg-tertiary)] px-6 py-4 rounded-b-xl flex justify-end space-x-3">
+ <button @click="cancelReset" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)]">
+ Cancel
+ </button>
+ <button @click="executeReset" class="px-4 py-2 bg-orange-500 text-white rounded-lg hover:bg-orange-600">
+ Yes, Reset Status
+ </button>
+ </div>
+ </div>
+</div>
diff --git a/templates/modals/share-delete-modal.html b/templates/modals/share-delete-modal.html
new file mode 100644
index 00000000..e2ed495c
--- /dev/null
+++ b/templates/modals/share-delete-modal.html
@@ -0,0 +1,47 @@
+<!-- Share Delete Confirmation Modal -->
+<div v-if="showShareDeleteModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-md transform transition-all duration-300 ease-in-out">
+ <!-- Header with gradient background -->
+ <div class="bg-gradient-to-r from-red-500 to-red-600 p-5 rounded-t-xl">
+ <div class="flex items-center">
+ <div class="w-12 h-12 bg-white/20 backdrop-blur rounded-full flex items-center justify-center mr-4">
+ <i class="fas fa-trash-alt text-white text-lg"></i>
+ </div>
+ <div>
+ <h3 class="text-lg font-bold text-white">Delete Shared Link</h3>
+ <p class="text-red-100 text-sm mt-1">This action cannot be undone</p>
+ </div>
+ </div>
+ </div>
+
+ <!-- Content -->
+ <div class="p-6">
+ <p class="text-[var(--text-secondary)] mb-4">
+ Are you sure you want to delete the shared link for:
+ </p>
+ <div v-if="shareToDelete" class="bg-[var(--bg-tertiary)] p-3 rounded-lg border border-[var(--border-primary)]">
+ <p class="font-medium text-[var(--text-primary)]">${shareToDelete.recording_title}</p>
+ <p class="text-sm text-[var(--text-muted)] mt-1">Shared on: ${shareToDelete.created_at}</p>
+ </div>
+ <div class="mt-4 p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
+ <div class="flex items-start">
+ <i class="fas fa-exclamation-triangle text-red-600 dark:text-red-400 mt-0.5 mr-2"></i>
+ <p class="text-sm text-red-800 dark:text-red-300">
+ The share link will be permanently deleted and anyone with this link will no longer be able to access the recording.
+ </p>
+ </div>
+ </div>
+ </div>
+
+ <!-- Actions -->
+ <div class="p-6 pt-0 flex justify-end gap-3">
+ <button @click="cancelDeleteShare" class="px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] rounded-lg transition-colors">
+ Cancel
+ </button>
+ <button @click="deleteShare" class="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors flex items-center gap-2">
+ <i class="fas fa-trash"></i>
+ Delete Share Link
+ </button>
+ </div>
+ </div>
+</div>
diff --git a/templates/modals/share-modal.html b/templates/modals/share-modal.html
new file mode 100644
index 00000000..0371efba
--- /dev/null
+++ b/templates/modals/share-modal.html
@@ -0,0 +1,82 @@
+<!-- Share Modal -->
+<div v-if="showShareModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div class="bg-[var(--bg-secondary)] rounded-lg shadow-xl w-full max-w-2xl max-h-[80vh] flex flex-col">
+ <div class="px-6 py-4 border-b border-[var(--border-primary)] flex justify-between items-center">
+ <h3 class="text-lg font-semibold" v-text="t('modal.shareRecording')"></h3>
+ <button @click="closeShareModal" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+ <div class="px-6 py-4 space-y-3 overflow-y-auto flex-1">
+ <p class="text-xs text-[var(--text-muted)]" v-text="t('help.createPublicLink')"></p>
+
+ <!-- Share Options -->
+ <div class="flex items-center gap-3 mb-2">
+ <label class="flex items-center">
+ <input type="checkbox" v-model="shareOptions.share_summary" id="share_summary" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
+ <span class="ml-2 text-xs" v-text="t('form.shareSummary')"></span>
+ </label>
+ <label class="flex items-center">
+ <input type="checkbox" v-model="shareOptions.share_notes" id="share_notes" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
+ <span class="ml-2 text-xs" v-text="t('form.shareNotes')"></span>
+ </label>
+ </div>
+
+ <!-- Create New Share Button -->
+ <button @click="createShare(true)" class="w-full px-3 py-2 bg-[var(--bg-accent)] text-white rounded-lg hover:opacity-90 transition-opacity text-sm font-medium">
+ <i class="fas fa-plus-circle mr-1.5"></i>Create New Share Link
+ </button>
+
+ <!-- Loading State -->
+ <div v-if="isLoadingPublicShares" class="text-center py-8">
+ <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
+ <p class="mt-2 text-sm text-[var(--text-muted)]">Loading share links...</p>
+ </div>
+
+ <!-- Existing Shares List -->
+ <div v-else-if="recordingPublicShares.length > 0" class="space-y-2">
+ <h4 class="text-xs font-medium text-[var(--text-secondary)]">
+ Existing Share Links (${recordingPublicShares.length})
+ </h4>
+ <div v-for="share in recordingPublicShares" :key="share.id" class="bg-[var(--bg-tertiary)] p-2.5 rounded-lg border border-[var(--border-primary)]">
+ <div class="flex justify-between items-start mb-2">
+ <div>
+ <p class="text-xs text-[var(--text-muted)]">${ t('help.sharedOn') }: ${share.created_at}</p>
+ </div>
+ <button @click="confirmDeletePublicShare(share)" class="text-red-500 hover:text-red-700 p-1">
+ <i class="fas fa-trash text-xs"></i>
+ </button>
+ </div>
+ <div class="flex items-center gap-3 mb-2">
+ <label class="flex items-center text-xs">
+ <input type="checkbox" v-model="share.share_summary" @change="updateShare(share)" class="h-3.5 w-3.5 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
+ <span class="ml-1.5" v-text="t('form.shareSummary')"></span>
+ </label>
+ <label class="flex items-center text-xs">
+ <input type="checkbox" v-model="share.share_notes" @change="updateShare(share)" class="h-3.5 w-3.5 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
+ <span class="ml-1.5" v-text="t('form.shareNotes')"></span>
+ </label>
+ </div>
+ <div class="relative">
+ <input :value="share.share_url" :id="'share-link-' + share.id" readonly class="w-full px-2 py-1.5 pr-10 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded text-xs font-mono">
+ <button @click="copyPublicShareLinkWithFeedback(share.share_url, share.id)" class="absolute right-1 top-1/2 -translate-y-1/2 w-8 h-7 flex items-center justify-center rounded bg-[var(--bg-button)] text-[var(--text-button)] hover:bg-[var(--bg-button-hover)] transition-colors" :title="t('buttons.copy')">
+ <i :class="copiedShareId === share.id ? 'fas fa-check' : 'fas fa-copy'" class="text-xs"></i>
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- No Shares Yet -->
+ <div v-else-if="!isLoadingPublicShares" class="text-center py-8 text-[var(--text-muted)]">
+ <i class="fas fa-link text-3xl mb-2"></i>
+ <p v-text="t('sharedTranscripts.noSharedTranscripts')"></p>
+ <p class="text-xs mt-1">Click the button above to create one</p>
+ </div>
+ </div>
+ <div class="px-6 py-3 border-t border-[var(--border-primary)] flex justify-end">
+ <button @click="closeShareModal" 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 font-medium">
+ Done
+ </button>
+ </div>
+ </div>
+</div>
diff --git a/templates/modals/shares-list-modal.html b/templates/modals/shares-list-modal.html
new file mode 100644
index 00000000..1da2e7f4
--- /dev/null
+++ b/templates/modals/shares-list-modal.html
@@ -0,0 +1,46 @@
+<!-- Shares List Modal -->
+<div v-if="showSharesListModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div class="bg-[var(--bg-secondary)] rounded-lg shadow-xl w-full max-w-2xl max-h-[80vh] flex flex-col">
+ <div class="p-6 border-b border-[var(--border-primary)] flex justify-between items-center">
+ <h3 class="text-lg font-semibold" v-text="t('modal.sharedTranscripts')"></h3>
+ <button @click="closeSharesList" class="p-2 rounded-lg hover:bg-[var(--bg-tertiary)] transition-colors">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+ <div class="p-6 space-y-4 overflow-y-auto">
+ <div v-if="isLoadingShares" class="text-center">
+ <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
+ </div>
+ <div v-else-if="userShares.length === 0" class="text-center text-[var(--text-muted)]">
+ <span v-text="t('sharedTranscripts.noSharedTranscripts')"></span>
+ </div>
+ <div v-else class="space-y-3">
+ <div v-for="share in userShares" :key="share.id" class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)]">
+ <div class="flex justify-between items-start">
+ <div>
+ <p class="font-semibold">${share.recording_title}</p>
+ <p class="text-sm text-[var(--text-muted)]">${ t('help.sharedOn') }: ${share.created_at}</p>
+ </div>
+ <button @click="confirmDeleteShare(share)" class="text-red-500 hover:text-red-700 p-1"><i class="fas fa-trash"></i></button>
+ </div>
+ <div class="mt-4 flex items-center gap-4">
+ <label class="flex items-center text-sm">
+ <input type="checkbox" v-model="share.share_summary" @change="updateShare(share)" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
+ <span class="ml-2" v-text="t('form.shareSummary')"></span>
+ </label>
+ <label class="flex items-center text-sm">
+ <input type="checkbox" v-model="share.share_notes" @change="updateShare(share)" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
+ <span class="ml-2" v-text="t('form.shareNotes')"></span>
+ </label>
+ </div>
+ <div class="mt-4 relative">
+ <input :value="'{{ request.url_root }}share/' + share.public_id" :id="'share-link-' + share.id" readonly class="w-full px-3 py-2 pr-12 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[var(--border-accent)]">
+ <button @click="copyIndividualShareLink(share.id)" class="absolute right-1.5 top-1/2 -translate-y-1/2 w-7 h-7 flex items-center justify-center rounded bg-[var(--bg-button)] text-[var(--text-button)] hover:bg-[var(--bg-button-hover)] transition-colors" :title="t('buttons.copy')">
+ <i :class="copiedShareId === share.id ? 'fas fa-check' : 'fas fa-copy'" class="text-xs"></i>
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+</div>
diff --git a/templates/modals/speaker-modal.html b/templates/modals/speaker-modal.html
new file mode 100644
index 00000000..93a3eb6e
--- /dev/null
+++ b/templates/modals/speaker-modal.html
@@ -0,0 +1,215 @@
+<!-- Speaker Identification Modal -->
+<div v-if="showSpeakerModal" @click="closeSpeakerModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div @click.stop @click="closeSpeakerSuggestionsOnClick" class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-4xl flex flex-col h-[85vh]">
+ <div class="p-5 border-b border-[var(--border-primary)] flex-shrink-0">
+ <h3 class="text-xl font-bold text-[var(--text-primary)]" v-text="t('modal.identifySpeakers')"></h3>
+ <!-- Warning for too many speakers -->
+ <div v-if="modalSpeakers.length > 8" class="mt-3 p-3 bg-[var(--bg-warn-light)] border border-amber-300 dark:border-amber-800 rounded-lg">
+ <div class="flex items-start">
+ <i class="fas fa-exclamation-triangle text-[var(--text-warn-strong)] mt-0.5 mr-2"></i>
+ <div class="text-sm">
+ <p class="font-medium text-[var(--text-warn-strong)]" v-text="t('help.moreSpeakersThanColors')"></p>
+ <p class="text-[var(--text-warn-strong)] mt-1" v-text="t('help.youHaveXSpeakers', { count: modalSpeakers.length })">
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div class="flex-grow flex overflow-hidden modal-content">
+ <div class="w-1/3 p-6 space-y-4 overflow-y-auto custom-scrollbar border-r border-[var(--border-primary)]">
+ <div v-for="(speaker, index) in modalSpeakers" :key="`${selectedRecording.id}-speaker-${index}-${speaker}`" class="space-y-3">
+ <!-- Speaker label with color indicator and "This is Me" checkbox on same line -->
+ <div class="flex items-center justify-between">
+ <div class="flex items-center space-x-2">
+ <div :class="speakerMap[speaker].color" class="w-4 h-4 rounded-full border border-white/30 shadow-sm flex-shrink-0"></div>
+ <span class="font-mono text-sm text-[var(--text-muted)]">${ speakerDisplayMap[speaker] || speaker }</span>
+ <span v-if="index >= 8" class="text-xs text-[var(--text-warn-strong)] bg-[var(--bg-warn-light)] px-2 py-0.5 rounded-full" :title="`Color repeats from speaker ${((index % 8) + 1)}`">
+ Repeat
+ </span>
+ </div>
+ <label class="flex items-center text-sm text-[var(--text-muted)] cursor-pointer hover:text-[var(--text-primary)] transition-colors">
+ <input type="checkbox"
+ v-model="speakerMap[speaker].isMe"
+ @change="handleIsMeChange(speaker)"
+ @focus="highlightSpeakerInTranscript(speaker)"
+ @blur="clearSpeakerHighlight"
+ class="speaker-checkbox">
+ <span class="ml-2 select-none" v-text="t('help.me')"></span>
+ </label>
+ </div>
+
+ <!-- Autocomplete input field - disabled when "This is Me" is checked -->
+ <div class="relative">
+ <input
+ type="text"
+ v-model="speakerMap[speaker].name"
+ @input="searchSpeakers($event.target.value, speaker)"
+ @focus="focusSpeaker(speaker)"
+ @blur="blurSpeaker()"
+ :disabled="speakerMap[speaker].isMe"
+ class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)] disabled:bg-[var(--bg-tertiary)] disabled:text-[var(--text-muted)] disabled:cursor-not-allowed"
+ :class="{ 'pr-32': shouldShowVoiceSuggestionPill(speaker) }"
+ :placeholder="speakerMap[speaker].isMe ? currentUserName : t('help.enterNameFor') + ' ' + (speakerDisplayMap[speaker] || speaker)"
+ autocomplete="off">
+
+ <!-- Voice match suggestion pill (shown inside input when empty) -->
+ <button v-if="shouldShowVoiceSuggestionPill(speaker)"
+ @click.stop="applyVoiceSuggestion(speaker, voiceSuggestions[speaker][0])"
+ class="absolute right-2 top-1/2 transform -translate-y-1/2 px-2 py-0.5 bg-gradient-to-r from-blue-500 to-purple-500 text-white text-xs rounded-full flex items-center gap-1 hover:from-blue-600 hover:to-purple-600 transition-all shadow-sm hover:shadow group">
+ <i class="fas fa-waveform-lines text-[10px]"></i>
+ <span class="font-medium truncate max-w-[80px]">${ voiceSuggestions[speaker][0].name }</span>
+ <span class="text-[10px] opacity-90">${ voiceSuggestions[speaker][0].similarity }%</span>
+ </button>
+
+ <!-- Loading indicator -->
+ <div v-if="loadingSuggestions[speaker] && !speakerMap[speaker].isMe" class="absolute right-3 top-1/2 transform -translate-y-1/2">
+ <i class="fas fa-spinner fa-spin text-[var(--text-muted)] text-sm"></i>
+ </div>
+
+ <!-- Suggestions dropdown - Only show when this input is active -->
+ <div v-if="activeSpeakerInput === speaker && speakerSuggestions[speaker] && speakerSuggestions[speaker].length > 0 && !speakerMap[speaker].isMe"
+ @click.stop
+ class="absolute z-10 w-full mt-1 bg-[var(--bg-secondary)] border border-[var(--border-primary)] rounded-md shadow-lg max-h-48 overflow-y-auto">
+ <div class="py-1">
+ <div v-for="suggestion in speakerSuggestions[speaker]"
+ :key="suggestion.id"
+ @click="selectSpeakerSuggestion(speaker, suggestion)"
+ class="px-3 py-2 cursor-pointer hover:bg-[var(--bg-tertiary)] flex items-center justify-between">
+ <div class="flex-grow">
+ <div class="text-sm font-medium text-[var(--text-primary)]">${ suggestion.name }</div>
+ <div class="text-xs text-[var(--text-muted)]">
+ Used ${ suggestion.use_count } time${ suggestion.use_count !== 1 ? 's' : '' }
+ <span v-if="suggestion.last_used">
+ • Last: ${ new Date(suggestion.last_used).toLocaleDateString() }
+ </span>
+ </div>
+ </div>
+ <i class="fas fa-user text-[var(--text-muted)] ml-2"></i>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Add Speaker Button -->
+ <div class="pt-4 border-t border-[var(--border-primary)]">
+ <button @click="openAddSpeakerModal" class="w-full px-4 py-2 bg-[var(--bg-accent)] text-[var(--text-accent)] rounded-lg hover:bg-[var(--bg-accent-hover)] transition-colors flex items-center justify-center">
+ <i class="fas fa-plus mr-2"></i>
+ <span v-text="t('buttons.addSpeaker')"></span>
+ </button>
+ </div>
+ </div>
+ <div class="w-2/3 p-6 flex flex-col overflow-hidden">
+ <!-- Audio Player Section -->
+ <div class="mb-4 flex-shrink-0">
+ <h4 class="font-semibold text-[var(--text-secondary)] mb-2" v-text="t('help.audioPlayer')"></h4>
+ <div class="audio-player-container">
+ <!-- Show message if audio has been deleted -->
+ <div v-if="selectedRecording.audio_deleted_at"
+ class="bg-[var(--bg-tertiary)] border border-[var(--border-primary)] text-[var(--text-secondary)] px-4 py-3 rounded-lg flex items-center gap-2 text-sm">
+ <i class="fas fa-info-circle"></i>
+ <span v-text="t('help.audioDeletedMessage')"></span>
+ </div>
+ <audio v-else 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>
+ </div>
+
+ <!-- Transcript Section -->
+ <div class="flex-grow overflow-y-auto custom-scrollbar speaker-modal-transcript" @click="seekAudioFromEvent">
+ <div v-if="processedTranscription.isJson">
+ <div v-for="(segment, index) in processedTranscription.simpleSegments" :key="index" class="speaker-segment mb-2 group relative" :data-start-time="segment.startTime">
+ <p class="flex items-baseline">
+ <span :class="[segment.color, 'speaker-tag', { 'speaker-highlight': highlightedSpeaker === segment.speakerId }]" :data-speaker-id="segment.speakerId" class="inline-block w-[120px] flex-shrink-0 truncate" :title="segment.speaker">${ segment.speaker }</span>
+ <span class="mx-1 flex-shrink-0">:</span>
+ <span class="word cursor-pointer hover:bg-[var(--bg-accent)] hover:text-[var(--text-accent)] rounded px-0.5 flex-1">${ segment.sentence }</span>
+
+ <!-- Edit buttons (shown on hover) -->
+ <span class="ml-2 opacity-0 group-hover:opacity-100 transition-opacity flex items-center space-x-1 flex-shrink-0">
+ <!-- Change Speaker Button -->
+ <button @click.stop="openSpeakerChangeDropdown(index)" class="p-1 rounded bg-[var(--bg-tertiary)] hover:bg-[var(--bg-accent)] text-[var(--text-muted)] hover:text-[var(--text-accent)] transition-colors" title="Change speaker">
+ <i class="fas fa-user-edit text-xs"></i>
+ </button>
+ <!-- Edit Text Button -->
+ <button @click.stop="openEditTextModal(index)" class="p-1 rounded bg-[var(--bg-tertiary)] hover:bg-[var(--bg-accent)] text-[var(--text-muted)] hover:text-[var(--text-accent)] transition-colors" title="Edit text">
+ <i class="fas fa-edit text-xs"></i>
+ </button>
+ </span>
+ </p>
+
+ <!-- Speaker Change Dropdown -->
+ <div v-if="editingSpeakerIndex === index" @click.stop class="mt-2 p-2 bg-[var(--bg-tertiary)] rounded-lg border border-[var(--border-primary)] shadow-lg">
+ <p class="text-xs text-[var(--text-muted)] mb-2">Select new speaker:</p>
+ <div class="space-y-1 max-h-48 overflow-y-auto custom-scrollbar">
+ <button v-for="speaker in modalSpeakers" :key="speaker" @click="changeSpeaker(index, speaker)" class="w-full text-left px-3 py-2 rounded hover:bg-[var(--bg-accent)] hover:text-[var(--text-accent)] transition-colors flex items-center space-x-2">
+ <div :class="speakerMap[speaker].color" class="w-3 h-3 rounded-full flex-shrink-0"></div>
+ <span class="text-sm">${ speakerMap[speaker].name || speaker }</span>
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div v-else v-html="highlightedTranscript"></div>
+ </div>
+
+ <!-- Speaker Navigation Controls (at bottom) - Always visible for consistent height -->
+ <div class="mt-3 p-3 bg-[var(--bg-tertiary)] rounded-lg flex items-center justify-between flex-shrink-0" :class="{'opacity-50': !highlightedSpeaker || speakerGroups.length <= 1}">
+ <div class="flex items-center space-x-2">
+ <span class="text-sm text-[var(--text-muted)]">
+ <span v-text="t('help.navigate')"></span> <span class="font-semibold">${ speakerDisplayMap[highlightedSpeaker] || highlightedSpeaker }</span> <span v-text="t('help.groups')"></span>:
+ </span>
+ <span class="text-xs text-[var(--text-muted)]">
+ (${ currentSpeakerGroupIndex + 1 } <span v-text="t('help.of')"></span> ${ speakerGroups.length })
+ </span>
+ </div>
+ <div class="flex items-center space-x-2">
+ <button @mousedown.prevent @click="navigateToPrevSpeakerGroup"
+ class="px-3 py-1.5 bg-[var(--bg-secondary)] hover:bg-[var(--bg-primary)] text-[var(--text-secondary)] rounded-md border border-[var(--border-secondary)] transition-all flex items-center text-sm disabled:opacity-50 disabled:cursor-not-allowed"
+ :disabled="!highlightedSpeaker || speakerGroups.length <= 1">
+ <i class="fas fa-chevron-up mr-1.5"></i>
+ <span v-text="t('buttons.previous')"></span>
+ </button>
+ <button @mousedown.prevent @click="navigateToNextSpeakerGroup"
+ class="px-3 py-1.5 bg-[var(--bg-secondary)] hover:bg-[var(--bg-primary)] text-[var(--text-secondary)] rounded-md border border-[var(--border-secondary)] transition-all flex items-center text-sm disabled:opacity-50 disabled:cursor-not-allowed"
+ :disabled="!highlightedSpeaker || speakerGroups.length <= 1">
+ <span v-text="t('buttons.next')"></span>
+ <i class="fas fa-chevron-down ml-1.5"></i>
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div class="p-4 bg-[var(--bg-tertiary)] border-t border-[var(--border-primary)] flex-shrink-0">
+ <label class="flex items-center text-sm text-[var(--text-muted)] cursor-pointer hover:text-[var(--text-primary)] transition-colors">
+ <input type="checkbox"
+ v-model="regenerateSummaryAfterSpeakerUpdate"
+ class="speaker-checkbox">
+ <span class="ml-2 select-none" v-text="t('help.regenerateSummaryAfterNames')"></span>
+ </label>
+ </div>
+ <div class="bg-[var(--bg-tertiary)] px-6 py-4 flex justify-between items-center border-t border-[var(--border-primary)] flex-shrink-0 rounded-b-xl">
+ <div>
+ <button @click="autoIdentifySpeakers" class="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 flex items-center" :disabled="isAutoIdentifying">
+ <i class="fas fa-magic mr-2"></i>
+ <span v-if="!isAutoIdentifying" v-text="t('help.autoIdentify')"></span>
+ <span v-else>
+ <i class="fas fa-spinner fa-spin mr-2"></i>
+ <span v-text="t('help.identifying')"></span>
+ </span>
+ </button>
+ </div>
+ <div class="flex space-x-3">
+ <button @click="closeSpeakerModal" class="px-4 py-2 bg-[var(--bg-secondary)] text-[var(--text-secondary)] rounded-lg border border-[var(--border-secondary)] hover:bg-[var(--bg-tertiary)]" v-text="t('common.cancel')"></button>
+ <button
+ @click="saveSpeakerNames"
+ :disabled="!hasSpeakerNames"
+ :class="hasSpeakerNames
+ ? 'px-4 py-2 bg-[var(--bg-accent)] text-[var(--text-accent)] rounded-lg hover:bg-[var(--bg-accent-hover)] cursor-pointer'
+ : 'px-4 py-2 bg-gray-400 text-gray-200 rounded-lg cursor-not-allowed'"
+ v-text="t('buttons.saveNames')"
+ ></button>
+ </div>
+ </div>
+ </div>
+</div>
diff --git a/templates/modals/system-audio-help-modal.html b/templates/modals/system-audio-help-modal.html
new file mode 100644
index 00000000..e093e696
--- /dev/null
+++ b/templates/modals/system-audio-help-modal.html
@@ -0,0 +1,47 @@
+<!-- System Audio Help Modal -->
+<div v-if="showSystemAudioHelp" @click="showSystemAudioHelp = false" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-lg max-h-[80vh] overflow-y-auto">
+ <div class="p-6 border-b border-[var(--border-primary)]">
+ <h3 class="text-lg font-semibold" v-text="t('help.systemAudioHelp')"></h3>
+ </div>
+ <div class="p-6 space-y-4">
+ <div class="p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
+ <div class="flex items-start gap-3">
+ <i class="fas fa-info-circle text-blue-600 dark:text-blue-400 mt-0.5"></i>
+ <div>
+ <p class="font-medium text-blue-800 dark:text-blue-300 mb-2">Browser Compatibility</p>
+ <p class="text-sm text-blue-700 dark:text-blue-400">
+ System audio recording requires a Chromium-based browser (Chrome, Edge, Brave) and is not supported on mobile devices.
+ </p>
+ </div>
+ </div>
+ </div>
+
+ <div>
+ <h4 class="font-medium mb-2">How to record system audio:</h4>
+ <ol class="list-decimal list-inside space-y-2 text-sm text-[var(--text-secondary)]">
+ <li>Click "System Audio" or "Mic + System" button</li>
+ <li>A screen sharing dialog will appear</li>
+ <li>Select a Chrome tab or entire screen</li>
+ <li>Make sure "Share audio" checkbox is enabled</li>
+ <li>Click "Share" to start recording</li>
+ </ol>
+ </div>
+
+ <div>
+ <h4 class="font-medium mb-2">Troubleshooting:</h4>
+ <ul class="list-disc list-inside space-y-1 text-sm text-[var(--text-muted)]">
+ <li>Ensure you're using Chrome, Edge, or Brave</li>
+ <li>Check that "Share audio" option is visible and enabled</li>
+ <li>Some content may have DRM protection that blocks recording</li>
+ <li>Firefox and Safari do not support this feature</li>
+ </ul>
+ </div>
+ </div>
+ <div class="p-6 border-t border-[var(--border-primary)] flex justify-end">
+ <button @click="showSystemAudioHelp = false" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors">
+ Got it
+ </button>
+ </div>
+ </div>
+</div>
diff --git a/templates/modals/text-editor-modal.html b/templates/modals/text-editor-modal.html
new file mode 100644
index 00000000..108d967d
--- /dev/null
+++ b/templates/modals/text-editor-modal.html
@@ -0,0 +1,27 @@
+<!-- Simple Transcription Editor Modal -->
+<div v-if="showTextEditorModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div class="bg-[var(--bg-secondary)] rounded-lg shadow-xl w-full max-w-2xl max-h-[90vh] flex flex-col">
+ <div class="p-6 border-b border-[var(--border-primary)]">
+ <h3 class="text-lg font-semibold" v-text="t('modal.editTranscription')"></h3>
+ </div>
+ <div class="p-6 space-y-4 overflow-y-auto flex-1">
+ <div>
+ <label class="block text-sm font-medium mb-2" v-text="t('transcription.title')"></label>
+ <textarea v-model="editingTranscriptionContent"
+ rows="15"
+ class="w-full px-3 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)] font-mono text-sm">
+ </textarea>
+ </div>
+ </div>
+ <div class="p-6 border-t border-[var(--border-primary)] flex justify-end gap-3">
+ <button @click="closeTextEditorModal"
+ class="px-4 py-2 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] rounded-lg transition-colors">
+ Cancel
+ </button>
+ <button @click="saveTranscription"
+ class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors">
+ Save Changes
+ </button>
+ </div>
+ </div>
+</div>
diff --git a/templates/modals/toast-container.html b/templates/modals/toast-container.html
new file mode 100644
index 00000000..1c977e6c
--- /dev/null
+++ b/templates/modals/toast-container.html
@@ -0,0 +1,2 @@
+<!-- Toast Container -->
+<div id="toastContainer" class="fixed top-4 right-4 z-50 pointer-events-none"></div>
diff --git a/templates/modals/unified-share-modal.html b/templates/modals/unified-share-modal.html
new file mode 100644
index 00000000..4da2c857
--- /dev/null
+++ b/templates/modals/unified-share-modal.html
@@ -0,0 +1,274 @@
+<!-- Unified Share Modal (Public + Internal Sharing) -->
+<div v-if="showUnifiedShareModal" @click="closeUnifiedShareModal" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
+ <div @click.stop class="bg-[var(--bg-secondary)] rounded-xl shadow-2xl w-full max-w-2xl max-h-[90vh] flex flex-col">
+ <div class="px-6 py-4 border-b border-[var(--border-primary)] flex-shrink-0">
+ <h3 class="text-lg font-semibold" v-text="t('modal.shareRecording')"></h3>
+ <p class="text-sm text-[var(--text-muted)] mt-0.5">${internalShareRecording?.title}</p>
+ </div>
+
+ <div class="flex-1 overflow-y-auto">
+ <!-- Public Sharing Section -->
+ <div v-if="!internalShareRecording?.is_shared || internalShareRecording?.share_info?.can_reshare" class="px-6 py-4 border-b border-[var(--border-primary)]">
+ <h4 class="font-medium mb-2 flex items-center gap-2">
+ <i class="fas fa-globe text-[var(--text-accent)]"></i>
+ <span v-text="t('sharing.publicLink')"></span>
+ </h4>
+
+ <p class="text-xs text-[var(--text-muted)] mb-3" v-text="t('help.publicLinkDesc')"></p>
+
+ <div class="space-y-3">
+ <!-- Share Options -->
+ <div class="flex items-center gap-4 mb-2">
+ <label class="flex items-center cursor-pointer">
+ <input type="checkbox" v-model="shareOptions.share_summary" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
+ <span class="ml-2 text-sm" v-text="t('form.shareSummary')"></span>
+ </label>
+ <label class="flex items-center cursor-pointer">
+ <input type="checkbox" v-model="shareOptions.share_notes" class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
+ <span class="ml-2 text-sm" v-text="t('form.shareNotes')"></span>
+ </label>
+ </div>
+
+ <!-- Create New Share Button -->
+ <button @click="createShare(true)"
+ class="w-full px-3 py-2 bg-[var(--bg-accent)] text-white rounded-lg hover:opacity-90 transition-opacity text-sm font-medium">
+ <i class="fas fa-plus-circle mr-1.5"></i>Create New Public Share Link
+ </button>
+
+ <!-- Loading State -->
+ <div v-if="isLoadingPublicShares" class="text-center py-6">
+ <i class="fas fa-spinner fa-spin text-xl text-[var(--text-muted)]"></i>
+ <p class="mt-2 text-xs text-[var(--text-muted)]">Loading share links...</p>
+ </div>
+
+ <!-- Existing Shares List -->
+ <div v-else-if="recordingPublicShares.length > 0" class="space-y-2">
+ <h5 class="text-xs font-medium text-[var(--text-secondary)] mb-1.5">
+ Existing Share Links (${recordingPublicShares.length})
+ </h5>
+ <div v-for="share in recordingPublicShares" :key="share.id"
+ class="bg-[var(--bg-tertiary)] p-2.5 rounded-lg border border-[var(--border-primary)]">
+ <div class="flex items-center justify-between gap-2 mb-2">
+ <div class="flex items-center gap-2 flex-1 min-w-0">
+ <i class="fas fa-calendar text-[var(--text-muted)] text-xs"></i>
+ <span class="text-xs text-[var(--text-muted)] truncate">Created: ${share.created_at}</span>
+ <span v-if="share.share_summary" class="inline-flex items-center px-1.5 py-0.5 rounded text-xs bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400">
+ <i class="fas fa-file-alt mr-1"></i>Summary
+ </span>
+ <span v-if="share.share_notes" class="inline-flex items-center px-1.5 py-0.5 rounded text-xs bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400">
+ <i class="fas fa-sticky-note mr-1"></i>Notes
+ </span>
+ </div>
+ <button @click="confirmDeletePublicShare(share)"
+ class="p-1.5 rounded hover:bg-red-50 dark:hover:bg-red-900/20 text-[var(--text-muted)] hover:text-red-500 transition-colors"
+ :title="'Delete share link'">
+ <i class="fas fa-trash text-xs"></i>
+ </button>
+ </div>
+ <div class="relative">
+ <input :value="share.share_url" :id="'unified-share-link-' + share.id" readonly
+ class="w-full px-2 py-1.5 pr-10 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded text-xs font-mono focus:outline-none focus:ring-2 focus:ring-[var(--ring-focus)]">
+ <button @click="copyPublicShareLinkWithFeedback(share.share_url, share.id)"
+ class="absolute right-1 top-1/2 -translate-y-1/2 w-8 h-7 flex items-center justify-center rounded bg-[var(--bg-button)] text-[var(--text-button)] hover:bg-[var(--bg-button-hover)] transition-all"
+ :title="t('buttons.copy')">
+ <i :class="copiedShareId === share.id ? 'fas fa-check' : 'fas fa-copy'" class="text-xs"></i>
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <!-- No Shares Yet -->
+ <div v-else-if="!isLoadingPublicShares" class="text-center py-4 text-xs text-[var(--text-muted)]">
+ <i class="fas fa-link text-xl mb-1"></i>
+ <p>No public share links yet</p>
+ <p class="text-xs mt-0.5 opacity-75">Click the button above to create one</p>
+ </div>
+ </div>
+ </div>
+
+ <!-- Internal Sharing Section -->
+ <div v-if="enableInternalSharing && (!internalShareRecording?.is_shared || internalShareRecording?.share_info?.can_reshare)" class="px-6 py-4">
+ <h4 class="font-medium mb-2 flex items-center gap-2">
+ <i class="fas fa-users text-[var(--text-accent)]"></i>
+ <span v-text="t('sharing.internalSharing')"></span>
+ </h4>
+
+ <p class="text-xs text-[var(--text-muted)] mb-3" v-text="t('help.internalSharingDesc')"></p>
+
+ <!-- Share with New User Section -->
+ <div class="bg-[var(--bg-tertiary)] p-3 rounded-lg border border-[var(--border-primary)] mb-3">
+ <h5 class="font-medium text-sm text-[var(--text-primary)] mb-2 flex items-center">
+ <i class="fas fa-user-plus mr-1.5 text-blue-500 text-xs"></i>
+ Share with User
+ </h5>
+
+ <!-- User Search/Selection (when SHOW_USERNAMES_IN_UI is enabled) -->
+ <div v-if="showUsernamesInUI" class="space-y-3">
+ <!-- Search Input (for filtering) -->
+ <div class="relative">
+ <input v-model="internalShareUserSearch"
+ @input="searchInternalShareUsers()"
+ type="text"
+ placeholder="Search users..."
+ class="w-full px-4 py-2 pl-10 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
+ <i class="fas fa-search absolute left-3 top-3 text-[var(--text-muted)]"></i>
+ </div>
+
+ <!-- User Grid -->
+ <div v-if="isLoadingAllUsers" class="text-center py-8">
+ <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
+ <p class="mt-2 text-sm text-[var(--text-muted)]">Loading users...</p>
+ </div>
+ <div v-else-if="internalShareSearchResults.length === 0" class="text-center py-8 text-[var(--text-muted)]">
+ <i class="fas fa-users-slash text-3xl mb-2"></i>
+ <p>No users found</p>
+ </div>
+ <div v-else class="grid grid-cols-1 sm:grid-cols-2 gap-2 max-h-64 overflow-y-auto">
+ <div v-for="user in internalShareSearchResults" :key="user.id"
+ @click="createInternalShare(user.id, user.username)"
+ class="group p-2 bg-[var(--bg-secondary)] hover:bg-[var(--bg-hover)] rounded-lg border border-[var(--border-secondary)] hover:border-blue-500 cursor-pointer transition-all">
+ <div class="flex items-center gap-2">
+ <div :class="['w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 font-bold text-xs', getUserColorClass(user.username)]">
+ ${user.username ? user.username.charAt(0).toUpperCase() : '?'}
+ </div>
+ <div class="flex-1 min-w-0">
+ <p class="font-medium text-sm text-[var(--text-primary)] truncate">${user.username}</p>
+ <p v-if="user.email" class="text-xs text-[var(--text-muted)] truncate">${user.email}</p>
+ </div>
+ <i class="fas fa-user-plus text-blue-500 group-hover:scale-110 transition-transform"></i>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Direct Username Entry (when SHOW_USERNAMES_IN_UI is disabled - Privacy Mode) -->
+ <div v-else class="space-y-3">
+ <p class="text-sm text-[var(--text-muted)]">Enter the exact username to share with</p>
+ <div class="flex gap-2">
+ <input v-model="internalShareUserSearch"
+ @keyup.enter="shareWithUsername()"
+ type="text"
+ placeholder="Enter full username..."
+ class="flex-1 px-4 py-2 bg-[var(--bg-input)] border border-[var(--border-secondary)] rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
+ <button @click="shareWithUsername()"
+ :disabled="!internalShareUserSearch.trim() || isSearchingUsers"
+ class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors">
+ <i v-if="isSearchingUsers" class="fas fa-spinner fa-spin"></i>
+ <span v-else>Add</span>
+ </button>
+ </div>
+ <p class="text-xs text-[var(--text-muted)]">
+ <i class="fas fa-info-circle mr-1"></i>
+ You must enter the exact username. If the user exists, they will be added to the share list.
+ </p>
+ </div>
+
+ <!-- Permissions -->
+ <div class="border-t border-[var(--border-primary)] mt-3 pt-2.5 space-y-1.5">
+ <p class="text-xs font-medium text-[var(--text-secondary)] mb-1.5">Share Permissions</p>
+ <div class="flex items-center">
+ <input type="checkbox"
+ v-model="internalSharePermissions.can_edit"
+ :disabled="!internalShareMaxPermissions.can_edit"
+ id="unified_share_can_edit"
+ class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed">
+ <label for="unified_share_can_edit"
+ :class="['ml-2 block text-sm', internalShareMaxPermissions.can_edit ? 'text-[var(--text-secondary)]' : 'text-[var(--text-muted)] opacity-60']">
+ <i class="fas fa-pencil-alt mr-1"></i>Allow editing notes and metadata
+ <span v-if="!internalShareMaxPermissions.can_edit" class="text-xs italic ml-1">(You don't have this permission)</span>
+ </label>
+ </div>
+ <div class="flex items-center">
+ <input type="checkbox"
+ v-model="internalSharePermissions.can_reshare"
+ :disabled="!internalShareMaxPermissions.can_reshare"
+ id="unified_share_can_reshare"
+ class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed">
+ <label for="unified_share_can_reshare"
+ :class="['ml-2 block text-sm', internalShareMaxPermissions.can_reshare ? 'text-[var(--text-secondary)]' : 'text-[var(--text-muted)] opacity-60']">
+ <i class="fas fa-share-alt mr-1"></i>Allow re-sharing with others
+ <span v-if="!internalShareMaxPermissions.can_reshare" class="text-xs italic ml-1">(You don't have this permission)</span>
+ </label>
+ </div>
+ </div>
+ </div>
+
+ <!-- Already Shared With Section -->
+ <div class="bg-[var(--bg-tertiary)] p-3 rounded-lg border border-[var(--border-primary)]">
+ <h5 class="font-medium text-sm text-[var(--text-primary)] mb-2 flex items-center justify-between">
+ <span class="flex items-center">
+ <i class="fas fa-users-cog mr-1.5 text-purple-500 text-xs"></i>
+ Already Shared With
+ </span>
+ <span v-if="recordingInternalShares.length > 0" class="text-xs font-normal text-[var(--text-muted)]">
+ ${recordingInternalShares.length} user(s)
+ </span>
+ </h5>
+
+ <div v-if="isLoadingInternalShares" class="text-center py-8">
+ <i class="fas fa-spinner fa-spin text-2xl text-[var(--text-muted)]"></i>
+ <p class="mt-2 text-sm text-[var(--text-muted)]">Loading shares...</p>
+ </div>
+ <div v-else-if="recordingInternalShares.length === 0" class="text-center py-8 text-[var(--text-muted)]">
+ <i class="fas fa-user-slash text-3xl mb-3"></i>
+ <p>Not shared with anyone yet</p>
+ <p class="text-sm mt-1">Select a user above to share this recording</p>
+ </div>
+ <div v-else class="grid grid-cols-1 sm:grid-cols-2 gap-2 max-h-64 overflow-y-auto">
+ <div v-for="share in recordingInternalShares" :key="share.user_id"
+ class="bg-[var(--bg-secondary)] p-2 rounded-lg border border-[var(--border-secondary)] hover:border-[var(--border-primary)] transition-colors">
+ <div class="flex items-center gap-2">
+ <div :class="['w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 font-bold text-xs', getUserColorClass(share.username)]">
+ ${share.username ? share.username.charAt(0).toUpperCase() : '#'}
+ </div>
+ <div class="flex-1 min-w-0">
+ <p class="font-medium text-sm text-[var(--text-primary)] truncate">${share.username || 'User #' + share.user_id}</p>
+ <p class="text-xs text-[var(--text-muted)] mb-0.5">${share.is_owner ? 'Recording Owner' : formatShareDate(share.created_at)}</p>
+ <div class="flex flex-wrap gap-1 text-[10px]">
+ <span v-if="share.is_owner" class="inline-flex items-center px-1.5 py-0.5 rounded bg-yellow-100 dark:bg-yellow-900/30 text-yellow-700 dark:text-yellow-400 font-medium">
+ <i class="fas fa-crown mr-0.5 text-[9px]"></i>Owner
+ </span>
+ <template v-else>
+ <span v-if="share.can_edit" class="inline-flex items-center px-1.5 py-0.5 rounded bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400">
+ <i class="fas fa-pencil-alt mr-0.5 text-[8px]"></i>Edit
+ </span>
+ <span v-if="share.can_reshare" class="inline-flex items-center px-1.5 py-0.5 rounded bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400">
+ <i class="fas fa-share-alt mr-0.5 text-[8px]"></i>Reshare
+ </span>
+ <span v-if="!share.can_edit && !share.can_reshare" class="inline-flex items-center px-1.5 py-0.5 rounded bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-400">
+ <i class="fas fa-eye mr-0.5 text-[8px]"></i>View
+ </span>
+ </template>
+ </div>
+ </div>
+ <button v-if="!share.is_owner"
+ @click="revokeInternalShare(share.id, share.username || share.user_name)"
+ class="p-1.5 rounded-lg text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors flex-shrink-0"
+ :title="'Revoke access'">
+ <i class="fas fa-user-times text-xs"></i>
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- No Permission Message -->
+ <div v-if="internalShareRecording?.is_shared && !internalShareRecording?.share_info?.can_reshare" class="px-6 py-6 text-center">
+ <div class="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4">
+ <i class="fas fa-info-circle text-yellow-600 dark:text-yellow-400 text-2xl mb-2"></i>
+ <p class="text-sm text-yellow-800 dark:text-yellow-300 font-medium">Sharing Not Available</p>
+ <p class="text-xs text-yellow-700 dark:text-yellow-400 mt-1">
+ This recording was shared with you, but you don't have permission to share it with others.
+ </p>
+ </div>
+ </div>
+
+ <div class="px-6 py-3 border-t border-[var(--border-primary)] flex justify-end flex-shrink-0">
+ <button @click="closeUnifiedShareModal" class="px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-lg hover:bg-[var(--bg-button-hover)] transition-colors">
+ <span v-text="t('tagsModal.done')"></span>
+ </button>
+ </div>
+ </div>
+</div>
diff --git a/templates/register.html b/templates/register.html
index fd8fad3b..f39468e0 100644
--- a/templates/register.html
+++ b/templates/register.html
@@ -3,6 +3,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
<title>{{ title }} - Speakr</title>
<link rel="icon" href="{{ url_for('static', filename='img/favicon.ico') }}" type="image/svg+xml">
<!-- All dependencies bundled locally for offline support -->
@@ -13,7 +14,6 @@
<!-- Loading overlay to prevent FOUC -->
{% include 'includes/loading_overlay.html' %}
- <script src="{{ url_for('static', filename='js/loading.js') }}"></script>
<script>
// Function to apply the theme based on localStorage
@@ -54,7 +54,7 @@
<div class="container mx-auto px-4 sm:px-6 lg:px-8 py-6 flex flex-col min-h-screen">
<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">
+ <a href="{{ url_for('recordings.index') }}" class="flex items-center">
<img src="{{ url_for('static', filename='img/favicon.ico') }}" alt="Speakr Logo" class="h-9 w-9 mr-2">
Speakr
</a>
@@ -75,7 +75,7 @@
{% endif %}
{% endwith %}
- <form method="POST" action="{{ url_for('register') }}">
+ <form method="POST" action="{{ url_for('auth.register') }}">
{{ form.hidden_tag() }}
<div class="mb-4">
@@ -140,7 +140,7 @@
<div class="text-center text-sm text-[var(--text-muted)]">
<span>Already have an account?</span>
- <a href="{{ url_for('login') }}" class="font-medium text-[var(--text-accent)] hover:underline">Login here</a>
+ <a href="{{ url_for('auth.login') }}" class="font-medium text-[var(--text-accent)] hover:underline">Login here</a>
</div>
</div>
</form>
diff --git a/templates/share.html b/templates/share.html
index 3ceb940d..c58a2172 100644
--- a/templates/share.html
+++ b/templates/share.html
@@ -3,6 +3,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
<title>Shared Recording - {{ recording.title }}</title>
<!-- All dependencies bundled locally for offline support -->
<script src="{{ url_for('static', filename='vendor/js/tailwind.min.js') }}"></script>
@@ -16,7 +17,6 @@
<!-- Loading overlay to prevent FOUC -->
{% include 'includes/loading_overlay.html' %}
- <script src="{{ url_for('static', filename='js/loading.js') }}"></script>
<script>
tailwind.config = {
@@ -101,7 +101,14 @@
<!-- Audio Player - Fixed at top -->
<div class="bg-[var(--bg-secondary)] p-4 border-b border-[var(--border-primary)] flex-shrink-0">
<div class="max-w-4xl mx-auto">
- <div class="audio-player-container">
+ <!-- Show message if audio has been deleted -->
+ <div v-if="recording.audio_deleted_at"
+ class="bg-[var(--bg-tertiary)] border border-[var(--border-primary)] text-[var(--text-muted)] px-4 py-3 rounded-lg flex items-center gap-2 text-sm">
+ <i class="fas fa-info-circle"></i>
+ <span>Audio file has been archived and is no longer available for playback.</span>
+ </div>
+ <!-- Show audio player if audio is available -->
+ <div v-else class="audio-player-container">
<audio controls class="w-full" :src="'/share/audio/' + recording.public_id" ref="audioPlayer"></audio>
</div>
</div>
@@ -148,9 +155,9 @@
<!-- Tab Content - Fixed height container -->
<div class="flex-1 flex flex-col overflow-hidden">
- <div class="max-w-4xl mx-auto p-4 flex-1 flex flex-col overflow-hidden">
+ <div class="w-full max-w-4xl mx-auto p-4 flex-1 flex flex-col overflow-hidden">
<!-- Transcription View -->
- <div v-show="activeTab === 'transcription'" class="flex-1 flex flex-col overflow-hidden">
+ <div v-show="activeTab === 'transcription'" class="w-full flex-1 flex flex-col overflow-hidden">
<!-- Transcription Controls -->
<div class="flex items-center justify-between mb-4 flex-shrink-0">
<div v-if="processedTranscription.hasDialogue" class="view-mode-toggle">
@@ -189,7 +196,7 @@
</div>
<!-- Transcription Content - Scrollable Box -->
- <div class="flex-1 overflow-y-auto transcription-box" @click="handleTranscriptClick">
+ <div class="w-full flex-1 overflow-y-auto transcription-box" @click="handleTranscriptClick">
<!-- Simple View -->
<div v-if="transcriptView === 'simple'" class="transcription-simple-view">
<div v-for="segment in processedTranscription.simpleSegments"
@@ -233,13 +240,13 @@
<!-- Summary View -->
{% if recording.summary %}
- <div v-show="activeTab === 'summary'" class="flex-1 flex flex-col overflow-hidden">
+ <div v-show="activeTab === 'summary'" class="w-full flex-1 flex flex-col overflow-hidden">
<div class="flex items-center justify-end mb-4 flex-shrink-0">
<button @click="copySummary" class="copy-btn">
<i class="fas fa-copy mr-1"></i>Copy
</button>
</div>
- <div class="flex-1 overflow-y-auto summary-box">
+ <div class="w-full flex-1 overflow-y-auto summary-box">
{{ recording.summary|safe }}
</div>
</div>
@@ -247,13 +254,13 @@
<!-- Notes View -->
{% if recording.notes %}
- <div v-show="activeTab === 'notes'" class="flex-1 flex flex-col overflow-hidden">
+ <div v-show="activeTab === 'notes'" class="w-full flex-1 flex flex-col overflow-hidden">
<div class="flex items-center justify-end mb-4 flex-shrink-0">
<button @click="copyNotes" class="copy-btn">
<i class="fas fa-copy mr-1"></i>Copy
</button>
</div>
- <div class="flex-1 overflow-y-auto notes-box">
+ <div class="w-full flex-1 overflow-y-auto notes-box">
{{ recording.notes|safe }}
</div>
</div>
@@ -285,7 +292,7 @@
</footer>
<!-- Toast Container -->
- <div id="toastContainer" class="fixed bottom-4 right-4 z-50 space-y-2"></div>
+ <div id="toastContainer" class="fixed top-4 right-4 z-50 space-y-2 pointer-events-none"></div>
</div>
<script>
@@ -394,6 +401,7 @@
});
function seekAudio(startTime) {
+ if (recording.value.audio_deleted_at) return;
if (startTime && audioPlayer.value) {
audioPlayer.value.currentTime = parseFloat(startTime);
audioPlayer.value.play();
@@ -401,6 +409,7 @@
}
function handleTranscriptClick(event) {
+ if (recording.value.audio_deleted_at) return;
const startTime = event.target.dataset.startTime;
if (startTime && audioPlayer.value) {
audioPlayer.value.currentTime = parseFloat(startTime);
@@ -408,7 +417,8 @@
}
}
- function copyTranscript() {
+ function copyTranscript(event) {
+ const button = event?.currentTarget;
let textToCopy = '';
if (processedTranscription.value.isJson) {
textToCopy = processedTranscription.value.segments.map(s => `[${s.speaker}]: ${s.sentence}`).join('\n');
@@ -416,22 +426,41 @@
textToCopy = recording.value.transcription;
}
navigator.clipboard.writeText(textToCopy).then(() => {
+ animateCopyButton(button);
showToast('Transcription copied to clipboard!');
});
}
- function copySummary() {
- navigator.clipboard.writeText(recording.value.summary).then(() => {
+ function copySummary(event) {
+ const button = event?.currentTarget;
+ const textToCopy = recording.value.summary_raw || recording.value.summary;
+ navigator.clipboard.writeText(textToCopy).then(() => {
+ animateCopyButton(button);
showToast('Summary copied to clipboard!');
});
}
- function copyNotes() {
- navigator.clipboard.writeText(recording.value.notes).then(() => {
+ function copyNotes(event) {
+ const button = event?.currentTarget;
+ const textToCopy = recording.value.notes_raw || recording.value.notes;
+ navigator.clipboard.writeText(textToCopy).then(() => {
+ animateCopyButton(button);
showToast('Notes copied to clipboard!');
});
}
+ function animateCopyButton(button) {
+ if (!button) return;
+ const icon = button.querySelector('i');
+ if (icon) {
+ const originalClass = icon.className;
+ icon.className = 'fas fa-check mr-1';
+ setTimeout(() => {
+ icon.className = originalClass;
+ }, 2000);
+ }
+ }
+
function toggleDarkMode() {
const newDarkMode = !isDarkMode.value;
isDarkMode.value = newDarkMode;
@@ -448,19 +477,33 @@
function showToast(message) {
const container = document.getElementById('toastContainer');
const toast = document.createElement('div');
- toast.className = 'toast bg-[var(--bg-success)] text-white px-4 py-2 rounded-lg shadow-lg flex items-center gap-2';
+ toast.className = 'toast bg-[var(--bg-success)] text-white px-4 py-2 rounded-lg shadow-lg flex items-center gap-2 pointer-events-auto';
+ toast.style.cursor = 'pointer';
toast.innerHTML = `<i class="fas fa-check"></i>${message}`;
-
+
container.appendChild(toast);
-
+
// Trigger animation
setTimeout(() => toast.classList.add('show'), 10);
-
- // Remove after 3 seconds
- setTimeout(() => {
+
+ // Function to dismiss the toast
+ const dismissToast = () => {
toast.classList.remove('show');
- setTimeout(() => container.removeChild(toast), 300);
- }, 3000);
+ setTimeout(() => {
+ if (toast.parentNode) {
+ container.removeChild(toast);
+ }
+ }, 300);
+ };
+
+ // Add click handler to dismiss toast
+ toast.addEventListener('click', () => {
+ clearTimeout(timeoutId);
+ dismissToast();
+ });
+
+ // Auto-dismiss after 3 seconds
+ const timeoutId = setTimeout(dismissToast, 3000);
}
return {