Skip to content

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

Python

pwa

Murtaza Nasir4154d0d5fb37
diff --git a/app.py b/app.py
index de3a38b1..3d3d7bdd 100644
--- a/app.py
+++ b/app.py
@@ -82,6 +82,8 @@ class User(db.Model, UserMixin):
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"
def __repr__(self):
return f"User('{self.username}', '{self.email}')"
@@ -182,6 +184,13 @@ with app.app_context():
# 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")
+ if add_column_if_not_exists(engine, 'user', 'output_language', 'VARCHAR(50)'):
+ app.logger.info("Added output_language column to user table")
+
except Exception as e:
app.logger.error(f"Error during database migration: {e}")
@@ -217,7 +226,7 @@ app.logger.info(f"Using Whisper API at: {transcription_base_url}")
# --- Background Transcription & Summarization Task ---
def transcribe_audio_task(app_context, recording_id, filepath, original_filename):
"""Runs the transcription and summarization in a background thread."""
- output_language = os.environ.get("OUTPUT_LANGUAGE", None) # Get preferred output language
+ # output_language = os.environ.get("OUTPUT_LANGUAGE", None) # Get preferred output language - Now per user
with app_context: # Need app context for db operations in thread
recording = db.session.get(Recording, recording_id)
@@ -246,8 +255,16 @@ def transcribe_audio_task(app_context, recording_id, filepath, original_filename
# Get the Whisper model name from environment variables
whisper_model = os.environ.get("WHISPER_MODEL", "Systran/faster-distil-whisper-large-v3")
- # Get the transcription language from environment variables
- transcription_language = os.environ.get("TRANSCRIPTION_LANGUAGE", None) # Default to None if not set
+ user_transcription_language = None
+ user_output_language = None
+ if recording and recording.owner: # Check if recording and owner exist
+ user_transcription_language = recording.owner.transcription_language
+ user_output_language = recording.owner.output_language
+
+ # Get the transcription language from user preferences or environment as fallback (optional)
+ # For now, prioritize user setting. If not set by user, it will be None.
+ # transcription_language = user_transcription_language or os.environ.get("TRANSCRIPTION_LANGUAGE", None)
+ transcription_language = user_transcription_language # Prioritize user setting
transcription_params = {
"model": whisper_model,
@@ -285,6 +302,7 @@ def transcribe_audio_task(app_context, recording_id, filepath, original_filename
return # Exit the task cleanly
# Prepare the prompt for OpenRouter
+ # Use user_output_language for prompts
prompt_text = f"""Analyze the following audio transcription and generate a concise title and a brief summary.
Transcription:
@@ -293,7 +311,7 @@ Transcription:
\"\"\"
Respond STRICTLY with a JSON object containing two keys: "title" (a short, descriptive title, max 6 words without using words introductory words and phrases like brief, "discussion on", "Meeting about" etc.) and "summary" (a paragraph summarizing the key points, max 150 words). The title should get to the point without inroductory phrases as we have very little space to show the title.
-{f"Please provide the title and summary in {output_language}." if output_language else ""}
+{f"Please provide the title and summary in {user_output_language}." if user_output_language else ""}
Example Format:
{{
"title": "Q3 Results for SPERO Program",
@@ -303,8 +321,8 @@ Example Format:
JSON Response:""" # The prompt guides the model towards the desired output
system_message_content = "You are an AI assistant that generates titles and summaries for meeting transcripts. Respond only with the requested JSON object."
- if output_language:
- system_message_content += f" Ensure your response (both title and summary) is in {output_language}."
+ if user_output_language: # Use user_output_language here
+ system_message_content += f" Ensure your response (both title and summary) is in {user_output_language}."
try:
# Use the OpenRouter client configured earlier
@@ -415,11 +433,12 @@ def chat_with_transcription():
return jsonify({'error': 'Chat service is not available (OpenRouter client not configured)'}), 503
# Prepare the system prompt with the transcription
- output_language_chat = os.environ.get("OUTPUT_LANGUAGE", None) # Get preferred output language for chat
+ # output_language_chat = os.environ.get("OUTPUT_LANGUAGE", None) # Get preferred output language for chat - Now from user
+ user_chat_output_language = current_user.output_language if current_user.is_authenticated else None
language_instruction = ""
- if output_language_chat:
- language_instruction = f"Please provide all your responses in {output_language_chat}."
+ if user_chat_output_language:
+ language_instruction = f"Please provide all your responses in {user_chat_output_language}."
system_prompt = f"""You are a professional meeting analyst working with Murtaza Nasir, Assistant Professor at Wichita State University. {language_instruction} Analyze the following meeting information and respond to the specific request.
@@ -520,9 +539,26 @@ def logout():
logout_user()
return redirect(url_for('index'))
[email protected]('/account', methods=['GET'])
[email protected]('/account', methods=['GET', 'POST'])
@login_required
def account():
+ if request.method == 'POST':
+ # Handle language preference updates
+ transcription_lang = request.form.get('transcription_language')
+ output_lang = request.form.get('output_language')
+
+ # Validate transcription_lang if needed (e.g., ensure it's a valid ISO code or empty)
+ # For simplicity, we'll save what's given. Add validation if strict format is required.
+ # Example: Check against a list of known valid ISO 639-1 codes.
+ # For now, allow empty string to clear the preference.
+
+ current_user.transcription_language = transcription_lang if transcription_lang else None
+ current_user.output_language = output_lang if output_lang else None
+
+ db.session.commit()
+ flash('Language preferences updated successfully!', 'success')
+ return redirect(url_for('account'))
+
return render_template('account.html', title='Account')
@app.route('/change_password', methods=['POST'])
diff --git a/docker-compose.example.yml b/docker-compose.example.yml
index a67d6f5b..361d9716 100644
--- a/docker-compose.example.yml
+++ b/docker-compose.example.yml
@@ -37,10 +37,9 @@ services:
- TRANSCRIPTION_BASE_URL=http://your_local_api_url:port/v1/
- TRANSCRIPTION_API_KEY=your_transcription_api_key_here
- WHISPER_MODEL=Systran/faster-distil-whisper-large-v3
- - TRANSCRIPTION_LANGUAGE= # Optional: Specify ISO-639-1 language code (e.g., en, es, fr, zh for Chinese). Leave empty for auto-detection.
- - OUTPUT_LANGUAGE= # Optional: Specify desired language for LLM outputs (e.g., English, Spanish, Chinese). Leave empty for English default.
# Application settings
+ # Transcription and Output languages are now per-user settings, configurable on the Account page in the app.
- ALLOW_REGISTRATION=false
# Admin user creation
diff --git a/readme.md b/readme.md
index c8f25c7f..65908130 100644
--- a/readme.md
+++ b/readme.md
@@ -15,16 +15,16 @@ Speakr is a personal, self-hosted web application designed for transcribing audi
* **Audio Upload:** Upload audio files (MP3, WAV, M4A, etc.) via drag-and-drop or file selection.
* **Background Processing:** Transcription and summarization happen in the background without blocking the UI.
-* **Transcription:** Uses OpenAI-compatible Speech-to-Text (STT) APIs (configurable, e.g., self-hosted Whisper).
-* **AI Summarization & Titling:** Generates concise titles and summaries using configurable LLMs via OpenAI-compatible APIs (like OpenRouter).
-* **Interactive Chat:** Ask questions and interact with the transcription content using an AI model.
+* **Transcription:** Uses OpenAI-compatible Speech-to-Text (STT) APIs (configurable, e.g., self-hosted Whisper). Transcription language can be set per user.
+* **AI Summarization & Titling:** Generates concise titles and summaries using configurable LLMs via OpenAI-compatible APIs (like OpenRouter). Output language can be set per user.
+* **Interactive Chat:** Ask questions and interact with the transcription content using an AI model. Chat output language can be set per user.
* **Search, Inbox & Highlight:** For highlighting and easy processing
* **Metadata Editing:** Edit titles, participants, meeting dates, summaries, and notes associated with recordings.
**User Features:**
* **Authentication:** Secure user registration and login system.
-* **Account Management:** Users can change their passwords.
+* **Account Management:** Users can change their passwords and set language preferences (transcription and output language) on their Account page.
* **Recording Gallery:** View, manage, and access all personal recordings.
* **Dark Mode:** Switch between light and dark themes.
@@ -95,8 +95,7 @@ The easiest way to deploy Speakr is using Docker and docker compose.
- TRANSCRIPTION_BASE_URL=http://your_local_api_url:port/v1/
- TRANSCRIPTION_API_KEY=your_transcription_api_key_here
- WHISPER_MODEL=Systran/faster-distil-whisper-large-v3
- - TRANSCRIPTION_LANGUAGE= # Optional: Specify ISO-639-1 language code (e.g., en, es, fr, zh for Chinese). Leave empty for auto-detection.
- - OUTPUT_LANGUAGE= # Optional: Specify desired language for LLM outputs (e.g., English, Spanish, Chinese). Leave empty for English default.
+ # Note: Transcription and Output languages are now per-user settings, configurable on the Account page in the app.
# Application settings
- ALLOW_REGISTRATION=false
@@ -358,23 +357,24 @@ Configuration is primarily handled through environment variables in the `docker-
* `TRANSCRIPTION_BASE_URL`: **Required.** The base URL for your transcription API endpoint (e.g., `http://localhost:8787/v1/`).
* `TRANSCRIPTION_API_KEY`: **Required.** Your API key for the transcription endpoint. For local endpoints, this might be a specific string like "none" or "NA". Check your endpoint's documentation.
* `WHISPER_MODEL`: *Optional.* The specific model name your transcription endpoint uses/expects (e.g., `Systran/faster-distil-whisper-large-v3`). Check your endpoint's requirements.
-* `TRANSCRIPTION_LANGUAGE`: *Optional.* The language of the input audio. Supplying the input language in ISO-639-1 format (e.g., `en` for English, `es` for Spanish) will improve transcription accuracy and latency. If not set, the transcription service will attempt to auto-detect the language.
-* `OUTPUT_LANGUAGE`: *Optional.* The desired language for the generated titles, summaries, and chat responses (e.g., "English", "Spanish", "Chinese"). If not set, outputs will typically be in the language of the transcription or English. Ensure your chosen `TEXT_MODEL_NAME` supports the desired output language.
* `SECRET_KEY`: **Required.** A long, random string used by Flask for session security. The `setup.sh` script generates one if it's missing.
* `ALLOW_REGISTRATION`: *Optional.* Set to `false` to prevent new users from registering via the web UI. Defaults to `true`.
+**Note on Language Preferences:** Transcription language and output language for summaries/chat are now configurable per user on their Account page within the application.
+
## Usage
1. **Register/Login:** Access the web application via your browser. Register a new account (if enabled) or log in.
-2. **Upload:** Go to "New Recording" or drag-and-drop audio files onto the page. Upload progress and subsequent processing status will appear in the bottom-left popup.
-3. **View Recordings:** The main "Gallery" view lists your recordings, grouped by date. Click on a recording to view its details.
-4. **Interact:**
+2. **Set Preferences (Optional):** Go to your Account page to set your preferred transcription and output languages.
+3. **Upload:** Go to "New Recording" or drag-and-drop audio files onto the page. Upload progress and subsequent processing status will appear in the bottom-left popup.
+4. **View Recordings:** The main "Gallery" view lists your recordings, grouped by date. Click on a recording to view its details.
+5. **Interact:**
* Listen to the audio using the player.
- * Read the transcription.
- * Review the AI-generated summary and title.
+ * Read the transcription (will use your preferred transcription language if set).
+ * Review the AI-generated summary and title (will be in your preferred output language if set).
* Read or edit metadata (participants, notes, meeting date). Use the small edit icons or the "Edit Details" button.
- * Use the "Chat with Transcript" panel to ask questions about the recording content.
-5. **Manage:** Edit details or delete recordings using the buttons in the detail view or the icons in the recording list.
+ * Use the "Chat with Transcript" panel to ask questions about the recording content (responses will be in your preferred output language if set).
+6. **Manage:** Edit details or delete recordings using the buttons in the detail view or the icons in the recording list.
## Admin Panel
diff --git a/static/js/app.js b/static/js/app.js
index ad18f720..5e645dd7 100644
--- a/static/js/app.js
+++ b/static/js/app.js
@@ -2,6 +2,19 @@ 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', () => {
+ // 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);
+ });
+ });
+ }
+
createApp({
setup() {
const currentView = ref('gallery');
diff --git a/static/manifest.json b/static/manifest.json
new file mode 100644
index 00000000..5887bbba
--- /dev/null
+++ b/static/manifest.json
@@ -0,0 +1,78 @@
+{
+ "id": "com.whispertranscribe.app",
+ "name": "WhisperTranscribe",
+ "short_name": "WhisperT",
+ "description": "WhisperTranscribe Application - Audio transcription and summarization",
+ "start_url": "/",
+ "scope": "/",
+ "display": "standalone",
+ "display_override": ["window-controls-overlay", "standalone"],
+ "background_color": "#000000",
+ "theme_color": "#000000",
+ "orientation": "any",
+ "prefer_related_applications": false,
+ "categories": ["productivity", "utilities", "business"],
+ "lang": "en",
+ "dir": "ltr",
+ "icons": [
+ {
+ "src": "/static/img/icon-192x192.png",
+ "sizes": "192x192",
+ "type": "image/png",
+ "purpose": "any"
+ },
+ {
+ "src": "/static/img/icon-192x192.png",
+ "sizes": "192x192",
+ "type": "image/png",
+ "purpose": "maskable"
+ },
+ {
+ "src": "/static/img/icon-512x512.png",
+ "sizes": "512x512",
+ "type": "image/png",
+ "purpose": "any"
+ },
+ {
+ "src": "/static/img/icon-512x512.png",
+ "sizes": "512x512",
+ "type": "image/png",
+ "purpose": "maskable"
+ }
+ ],
+ "shortcuts": [
+ {
+ "name": "New Recording",
+ "short_name": "New",
+ "description": "Upload or record new audio",
+ "url": "/#upload",
+ "icons": [{ "src": "/static/img/icon-192x192.png", "sizes": "192x192" }]
+ },
+ {
+ "name": "View Gallery",
+ "short_name": "Gallery",
+ "description": "Access your recordings gallery",
+ "url": "/#gallery",
+ "icons": [{ "src": "/static/img/icon-192x192.png", "sizes": "192x192" }]
+ }
+ ],
+ "share_target": {
+ "action": "/#upload",
+ "method": "POST",
+ "enctype": "multipart/form-data",
+ "params": {
+ "title": "title",
+ "text": "text",
+ "url": "url",
+ "files": [
+ {
+ "name": "shared_audio",
+ "accept": ["audio/*"]
+ }
+ ]
+ }
+ },
+ "edge_side_panel": {
+ "preferred_width": 480
+ }
+}
diff --git a/static/offline.html b/static/offline.html
new file mode 100644
index 00000000..0b46fb39
--- /dev/null
+++ b/static/offline.html
@@ -0,0 +1,64 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Offline - WhisperTranscribe</title>
+ <link rel="icon" href="/static/img/favicon.svg" type="image/svg+xml">
+ <style>
+ body {
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
+ background-color: #f0f2f5;
+ color: #1c1e21;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ height: 100vh;
+ margin: 0;
+ text-align: center;
+ padding: 20px;
+ box-sizing: border-box;
+ }
+ .container {
+ background-color: #ffffff;
+ padding: 40px;
+ border-radius: 8px;
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1), 0 8px 16px rgba(0, 0, 0, 0.1);
+ }
+ img {
+ width: 60px;
+ height: 60px;
+ margin-bottom: 20px;
+ }
+ h1 {
+ font-size: 24px;
+ margin-bottom: 10px;
+ }
+ p {
+ font-size: 16px;
+ color: #606770;
+ }
+ @media (prefers-color-scheme: dark) {
+ body {
+ background-color: #1c1e21;
+ color: #e4e6eb;
+ }
+ .container {
+ background-color: #242526;
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2), 0 8px 16px rgba(0, 0, 0, 0.2);
+ }
+ p {
+ color: #b0b3b8;
+ }
+ }
+ </style>
+</head>
+<body>
+ <div class="container">
+ <img src="/static/img/favicon.svg" alt="WhisperTranscribe Logo">
+ <h1>You're Offline</h1>
+ <p>It looks like you're not connected to the internet. Please check your connection and try again.</p>
+ <p>Some content may be unavailable until you're back online.</p>
+ </div>
+</body>
+</html>
diff --git a/static/sw.js b/static/sw.js
new file mode 100644
index 00000000..73e70592
--- /dev/null
+++ b/static/sw.js
@@ -0,0 +1,261 @@
+const CACHE_NAME = 'whispertranscribe-cache-v3';
+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.svg', // 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'
+];
+
+// Function to update shortcuts (structure from your example)
+// The actual `lists` data would need to be sent from your client-side app.js
+const updateShortcuts = async (lists) => {
+ if (!self.registration || !('shortcuts' in self.registration)) {
+ console.log('Shortcuts API not supported or registration not available.');
+ return;
+ }
+
+ try {
+ let shortcuts = [
+ {
+ name: "New Recording",
+ short_name: "New",
+ description: "Upload or record new audio",
+ url: "/#upload", // Or your direct upload page route
+ icons: [{ src: "/static/img/icon-192x192.png", sizes: "192x192" }]
+ },
+ {
+ name: "View Gallery",
+ short_name: "Gallery",
+ description: "Access your recordings gallery",
+ url: "/#gallery", // Or your direct gallery page route
+ icons: [{ src: "/static/img/icon-192x192.png", sizes: "192x192" }]
+ }
+ ];
+
+ // Example: If you had dynamic lists to add as shortcuts
+ if (Array.isArray(lists) && lists.length > 0) {
+ const dynamicShortcuts = lists.slice(0, 2).map(list => { // Max 2 dynamic, total 4
+ if (list && list.id && list.title) {
+ return {
+ name: list.title,
+ short_name: list.title.length > 10 ? list.title.substring(0, 9) + '…' : list.title,
+ description: `View ${list.title}`,
+ url: `/list/${list.id}`, // Example dynamic URL
+ icons: [{ src: "/static/img/icon-192x192.png", sizes: "192x192" }]
+ };
+ }
+ return null;
+ }).filter(Boolean);
+ shortcuts = [...shortcuts, ...dynamicShortcuts];
+ }
+
+ await self.registration.shortcuts.set(shortcuts);
+ console.log('PWA shortcuts updated successfully:', shortcuts);
+ } catch (error) {
+ console.error('Error updating PWA shortcuts:', error);
+ }
+};
+
+
+// Cache first strategy: Respond from cache if available, otherwise fetch from network and cache.
+const cacheFirst = async (request) => {
+ const responseFromCache = await caches.match(request);
+ if (responseFromCache) {
+ return responseFromCache;
+ }
+ try {
+ const responseFromNetwork = await fetch(request);
+ // Check if the response is valid before caching
+ if (responseFromNetwork && responseFromNetwork.ok) {
+ const cache = await caches.open(CACHE_NAME);
+ cache.put(request, responseFromNetwork.clone());
+ }
+ return responseFromNetwork;
+ } catch (error) {
+ console.error('CacheFirst: Network request failed for:', request.url, error);
+ // For assets, returning a generic error or specific offline asset might be better than network error.
+ // However, if it's a critical asset not found, this indicates an issue.
+ return new Response('Network error trying to fetch asset.', {
+ status: 408,
+ headers: { 'Content-Type': 'text/plain' },
+ });
+ }
+};
+
+// Stale-while-revalidate strategy: Respond from cache immediately if available,
+// then update the cache with a fresh response from the network.
+const staleWhileRevalidate = async (request) => {
+ const cache = await caches.open(CACHE_NAME);
+ const cachedResponsePromise = cache.match(request);
+ const networkResponsePromise = fetch(request).then(networkResponse => {
+ if (networkResponse && networkResponse.ok) {
+ cache.put(request, networkResponse.clone());
+ }
+ return networkResponse;
+ }).catch(error => {
+ console.error('StaleWhileRevalidate: Network request failed for:', request.url, error);
+ // If network fails, we still might have a cached response.
+ // If not, this error will propagate.
+ return new Response('API request failed and no cache available.', {
+ status: 503, // Service Unavailable
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ error: 'Service temporarily unavailable. Please try again later.' })
+ });
+ });
+
+ return (await cachedResponsePromise) || networkResponsePromise;
+};
+
+// Network first strategy: Try to fetch from network first.
+// If network fails, fall back to cache. If cache also fails, serve offline page for navigation.
+const networkFirst = async (request) => {
+ try {
+ const networkResponse = await fetch(request);
+ if (networkResponse && networkResponse.ok) {
+ const cache = await caches.open(CACHE_NAME);
+ cache.put(request, networkResponse.clone());
+ }
+ return networkResponse;
+ } catch (error) {
+ console.warn('NetworkFirst: Network request failed for:', request.url, error);
+ const cachedResponse = await caches.match(request);
+ if (cachedResponse) {
+ return cachedResponse;
+ }
+ // For navigation requests, fall back to the offline page if both network and cache fail.
+ if (request.mode === 'navigate') {
+ const offlinePage = await caches.match('/static/offline.html');
+ if (offlinePage) return offlinePage;
+ }
+ // For other types of requests, or if offline page isn't cached, re-throw or return error.
+ return new Response('Network error and no cache available.', {
+ status: 408,
+ headers: { 'Content-Type': 'text/plain' },
+ });
+ }
+};
+
+self.addEventListener('install', (event) => {
+ self.skipWaiting(); // Activate new service worker immediately
+ event.waitUntil(
+ caches.open(CACHE_NAME).then((cache) => {
+ console.log('Service Worker: Caching app shell');
+ return cache.addAll(ASSETS_TO_CACHE.map(url => new Request(url, { cache: 'reload' }))) // Force reload from network for app shell
+ .catch(error => {
+ console.error('Failed to cache app shell during install:', error);
+ // You might want to log which specific asset failed
+ ASSETS_TO_CACHE.forEach(url => {
+ cache.add(new Request(url, { cache: 'reload' })).catch(err => console.warn(`Failed to cache: ${url}`, err));
+ });
+ });
+ })
+ );
+});
+
+self.addEventListener('activate', (event) => {
+ event.waitUntil(
+ caches.keys().then((cacheNames) => {
+ return Promise.all(
+ cacheNames
+ .filter((name) => name !== CACHE_NAME)
+ .map((name) => {
+ console.log('Service Worker: Deleting old cache', name);
+ return caches.delete(name);
+ })
+ );
+ }).then(() => {
+ console.log('Service Worker: Activated and old caches cleared.');
+ return self.clients.claim(); // Take control of all open clients
+ })
+ );
+});
+
+self.addEventListener('fetch', (event) => {
+ const request = event.request;
+ const url = new URL(request.url);
+
+ // Skip non-GET requests from caching strategies (they should pass through)
+ if (request.method !== 'GET') {
+ // event.respondWith(fetch(request)); // Let non-GET requests pass through to the network
+ return; // Or simply return to let the browser handle it
+ }
+
+ // Serve API calls from /api/ with stale-while-revalidate
+ // (excluding auth-related endpoints)
+ if (url.pathname.startsWith('/api/')) {
+ if (url.pathname.includes('/login') || url.pathname.includes('/logout') || url.pathname.includes('/auth')) {
+ // For auth, always go to network, don't cache
+ event.respondWith(fetch(request));
+ return;
+ }
+ event.respondWith(staleWhileRevalidate(request));
+ return;
+ }
+
+ // Serve /audio/<id> requests with cache-first, then network.
+ // These are media files and can be large, so cache-first is good.
+ if (url.pathname.startsWith('/audio/')) {
+ event.respondWith(cacheFirst(request));
+ return;
+ }
+
+ // Handle navigation requests (HTML pages) with network-first, then cache, then offline page.
+ if (request.mode === 'navigate') {
+ event.respondWith(networkFirst(request));
+ return;
+ }
+
+ // For static assets listed in ASSETS_TO_CACHE, use cache-first.
+ // This ensures that if an asset path is directly requested, it's served from cache if possible.
+ // We need to match against the origin + pathname for ASSETS_TO_CACHE.
+ const requestPath = url.origin === self.origin ? url.pathname : request.url;
+ if (ASSETS_TO_CACHE.includes(requestPath)) {
+ event.respondWith(cacheFirst(request));
+ return;
+ }
+
+ // Default strategy for other GET requests: try cache, then network.
+ // This is a good general fallback for other static assets not explicitly listed
+ // or for assets from other origins if not handled by ASSETS_TO_CACHE.
+ event.respondWith(
+ caches.match(request).then((cachedResponse) => {
+ if (cachedResponse) {
+ return cachedResponse;
+ }
+ return fetch(request).then(networkResponse => {
+ // Optionally cache other successful GET responses here if desired
+ // if (networkResponse && networkResponse.ok) {
+ // const cache = await caches.open(CACHE_NAME);
+ // cache.put(request, networkResponse.clone());
+ // }
+ return networkResponse;
+ }).catch(() => {
+ // If network fails for a non-navigation, non-API, non-explicitly-cached asset
+ // there isn't much we can do other than return an error or nothing.
+ // For simplicity, let the browser handle the error.
+ });
+ })
+ );
+});
+
+// Listen for messages from the client (e.g., to update shortcuts)
+self.addEventListener('message', (event) => {
+ if (event.data && event.data.type === 'UPDATE_SHORTCUTS') {
+ console.log('Service Worker: Received UPDATE_SHORTCUTS message:', event.data.lists);
+ // updateShortcuts(event.data.lists); // Call if you implement dynamic shortcuts based on client data
+ }
+ if (event.data && event.data.type === 'SKIP_WAITING') {
+ self.skipWaiting();
+ }
+});
diff --git a/templates/account.html b/templates/account.html
index 04ff8625..6d9e7709 100644
--- a/templates/account.html
+++ b/templates/account.html
@@ -164,6 +164,25 @@
</div>
</div>
</div>
+
+ <div class="mb-6">
+ <h3 class="text-lg font-medium text-[var(--text-secondary)] mb-2">Language Preferences</h3>
+ <form method="POST" action="{{ url_for('account') }}" class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] space-y-4">
+ <div>
+ <label for="transcription_language" class="block text-sm font-medium text-[var(--text-muted)]">Transcription Language</label>
+ <input type="text" name="transcription_language" id="transcription_language" value="{{ current_user.transcription_language or '' }}" placeholder="e.g., en, es, zh (ISO 639-1 code)" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]">
+ <p class="text-xs text-[var(--text-light)] mt-1">Leave blank for auto-detection by transcription service.</p>
+ </div>
+ <div>
+ <label for="output_language" class="block text-sm font-medium text-[var(--text-muted)]">Preferred Output Language</label>
+ <input type="text" name="output_language" id="output_language" value="{{ current_user.output_language or '' }}" placeholder="e.g., English, Spanish, Chinese" class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]">
+ <p class="text-xs text-[var(--text-light)] mt-1">Language for titles, summaries, and chat. Leave blank for default (usually English or transcription language).</p>
+ </div>
+ <button type="submit" class="inline-flex items-center px-4 py-2 bg-[var(--bg-button)] text-[var(--text-button)] rounded-md hover:bg-[var(--bg-button-hover)] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--border-focus)] transition-colors duration-200">
+ <i class="fas fa-save mr-2"></i> Save Language Preferences
+ </button>
+ </form>
+ </div>
<div>
<h3 class="text-lg font-medium text-[var(--text-secondary)] mb-2">Account Actions</h3>
diff --git a/templates/index.html b/templates/index.html
index 99379765..29ee8efc 100644
--- a/templates/index.html
+++ b/templates/index.html
@@ -4,6 +4,8 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Speakr</title>
+ <link rel="manifest" href="{{ url_for('static', filename='manifest.json') }}">
+ <meta name="theme-color" content="#007bff">
<link rel="icon" href="{{ url_for('static', filename='img/favicon.svg') }}" type="image/svg+xml">
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>