Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Add localization for token budget feature
Murtaza Nasir60355470d8fa
diff --git a/README.md b/README.mdindex e1b329cf..c3cd8df1 100644--- a/README.md+++ b/README.md@@ -9,7 +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.7.1-brightgreen.svg"></a>+ <a href="https://github.com/murtaza-nasir/speakr/releases/latest"><img alt="Latest Version" src="https://img.shields.io/badge/version-0.7.2-brightgreen.svg"></a></p><p align="center">@@ -148,14 +148,22 @@ 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.7.1)+## Latest Release (v0.7.2)-**Stability & Audio Improvements**+**Token Budgets, Performance & UX**++- **Token Usage Tracking** - Track LLM token usage per user with detailed statistics and cost breakdowns+- **Per-User Token Budgets** - Set monthly token limits per user with warnings at 80% and blocking at 100%+- **Virtual Scrolling** - Performance optimization for handling 4500+ transcript segments smoothly+- **Audio Player Improvements** - Drag-to-seek, independent modal players, improved theme support+- **File Date Handling** - Uses original recording date from file metadata instead of upload time+- **Codec Configuration** - Configure unsupported audio codecs with automatic conversion++### Previous Release (v0.7.1)- **PostgreSQL Support** - Added `psycopg2-binary` driver for PostgreSQL database option- **Audio Download Button** - Explicit download button next to audio player, works on mobile- **Job Queue Race Condition Fix** - Fixed issue where multiple workers could claim the same job-- **Audio Conversion Pipeline Refactor** - Improved format detection using ffprobe, better codec support*Thanks to [sakowicz](https://github.com/sakowicz), [JadedBlueEyes](https://github.com/JadedBlueEyes), and [Daabramov](https://github.com/Daabramov)*@@ -167,21 +175,6 @@ Complete documentation is available at **[murtaza-nasir.github.io/speakr](https:*Contributed by [Dmitry Abramov](https://github.com/Daabramov)* | [SSO Setup Guide](https://murtaza-nasir.github.io/speakr/admin-guide/sso-setup/)-### Previous Release (v0.6.6)--- **Auto Compression** - Lossless uploads automatically compressed to save storage-- **Speaker Filtering** - Filter recordings by speaker name, starred/inbox toggles--### Previous Release (v0.6.5)--- Separate Chat Model - Configure different AI models for chat vs background tasks-- Custom Datetime Picker - New themed calendar and time selection modal--### Previous Release (v0.6.3)--- API Token Authentication for programmatic access-- Multiple auth methods: Bearer token, X-API-Token, query parameter-### v0.5.9 - Major Release> **⚠️ IMPORTANT:** v0.5.9 introduced significant architectural changes. If upgrading from earlier versions, backup your data first and review the [configuration guide](https://murtaza-nasir.github.io/speakr/getting-started/installation#configuration-updates).@@ -241,6 +234,7 @@ Complete documentation is available at **[murtaza-nasir.github.io/speakr](https:- ✅ PWA enhancements with offline support and background sync (v0.5.10)- ✅ Multi-user job queue with fair scheduling (v0.6.0)- ✅ SSO integration with OIDC providers (v0.7.0)+- ✅ Token usage tracking and per-user budgets (v0.7.2)### Near-term- Bulk operations for recordings (mass delete, export, tagging)diff --git a/VERSION b/VERSIONindex 63f2359f..2c0a9c7b 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-v0.7.1+v0.7.2diff --git a/docs/admin-guide/statistics.md b/docs/admin-guide/statistics.mdindex 80d237dc..786258d1 100644--- a/docs/admin-guide/statistics.md+++ b/docs/admin-guide/statistics.md@@ -34,6 +34,22 @@ System statistics are your crystal ball for infrastructure needs. Storage growthUse these insights proactively. If you see storage growing at 50GB monthly and you have 200GB free, you know you have about four months before needing intervention. This lead time lets you budget for upgrades, plan migrations, or implement retention policies before hitting critical limits.+## Token Usage Statistics++The Token Usage section provides visibility into LLM API consumption across your instance. Four summary cards show today's usage, monthly totals, estimated costs, and any users approaching their budget limits.++**Daily and Monthly Charts**: Interactive charts display token consumption trends over the last 30 days and 12 months. These visualizations help identify usage patterns and predict future costs.++**Per-User Breakdown**: A detailed table shows each user's monthly token consumption alongside their budget limit (if set). Progress bars indicate how much of their budget has been used:++- Green: Under 80% of budget+- Yellow: Between 80-100% (warning zone)+- Red: At or over 100% (blocked)++**Cost Tracking**: When using OpenRouter or other providers that return cost information, the statistics include estimated costs based on actual API responses. This helps with budgeting and identifying high-cost operations.++Use token statistics to identify heavy users, validate budget allocations, and forecast API costs. If certain users consistently hit their limits, you may need to increase their budgets or investigate their usage patterns. See [Token Budget Management](user-management.md#token-budget-management) for setting individual user limits.+---Next: [System Settings](system-settings.md) →\ No newline at end of filediff --git a/docs/admin-guide/user-management.md b/docs/admin-guide/user-management.mdindex c750f5a7..0c29c072 100644--- a/docs/admin-guide/user-management.md+++ b/docs/admin-guide/user-management.md@@ -26,6 +26,21 @@ Beyond the admin role, Speakr offers granular per-user permissions that controlUse 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.+### Token Budget Management++Control LLM costs by setting monthly token budgets for individual users. When creating or editing a user, you can specify a monthly token limit that restricts their AI usage.++++**How Token Budgets Work**:++- **Warning at 80%**: Users see a yellow warning indicator when they reach 80% of their monthly budget+- **Blocked at 100%**: Once the budget is exhausted, AI operations (chat, summarization, etc.) are blocked until the next month+- **Budget Reset**: Token counts reset automatically at the start of each calendar month+- **No Limit**: Leave the budget field empty for unlimited usage++Token budgets are set in increments of 10,000 tokens with a minimum of 100,000. The budget covers all AI operations including summarization, chat, title generation, and event extraction. View detailed token usage statistics in the [System Statistics](statistics.md#token-usage-statistics) section.+## Managing Existing UsersEach 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/assets/images/screenshots/Main view.png b/docs/assets/images/screenshots/Main view.pngindex 791418df..88b1f2cb 100644Binary files a/docs/assets/images/screenshots/Main view.png and b/docs/assets/images/screenshots/Main view.png differdiff --git a/docs/assets/images/screenshots/admin-user-create-token-budget.png b/docs/assets/images/screenshots/admin-user-create-token-budget.pngnew file mode 100644index 00000000..01d64d84Binary files /dev/null and b/docs/assets/images/screenshots/admin-user-create-token-budget.png differdiff --git a/docs/assets/images/screenshots/audio-sync-bubble-view.png b/docs/assets/images/screenshots/audio-sync-bubble-view.pngindex e0badae0..e9f3f393 100644Binary files a/docs/assets/images/screenshots/audio-sync-bubble-view.png and b/docs/assets/images/screenshots/audio-sync-bubble-view.png differdiff --git a/docs/assets/images/screenshots/audio-sync-simple-view.png b/docs/assets/images/screenshots/audio-sync-simple-view.pngindex b38a2994..30aa97d9 100644Binary files a/docs/assets/images/screenshots/audio-sync-simple-view.png and b/docs/assets/images/screenshots/audio-sync-simple-view.png differdiff --git a/docs/assets/images/screenshots/edit-transcription-modal.png b/docs/assets/images/screenshots/edit-transcription-modal.pngindex fb4a49b5..4ba15f82 100644Binary files a/docs/assets/images/screenshots/edit-transcription-modal.png and b/docs/assets/images/screenshots/edit-transcription-modal.png differdiff --git a/docs/assets/images/screenshots/highlighted-transcript-following-simple-light.png b/docs/assets/images/screenshots/highlighted-transcript-following-simple-light.pngindex 7be3cc13..56aa2ff0 100644Binary files a/docs/assets/images/screenshots/highlighted-transcript-following-simple-light.png and b/docs/assets/images/screenshots/highlighted-transcript-following-simple-light.png differdiff --git a/docs/assets/images/screenshots/main-view-recipe-example.png b/docs/assets/images/screenshots/main-view-recipe-example.pngnew file mode 100644index 00000000..23cb3c77Binary files /dev/null and b/docs/assets/images/screenshots/main-view-recipe-example.png differdiff --git a/docs/assets/images/screenshots/main-view-token-usage.png b/docs/assets/images/screenshots/main-view-token-usage.pngnew file mode 100644index 00000000..b99957c0Binary files /dev/null and b/docs/assets/images/screenshots/main-view-token-usage.png differdiff --git a/docs/assets/images/screenshots/markdown-editor.png b/docs/assets/images/screenshots/markdown-editor.pngindex a4736dd9..585e161c 100644Binary files a/docs/assets/images/screenshots/markdown-editor.png and b/docs/assets/images/screenshots/markdown-editor.png differdiff --git a/docs/assets/images/screenshots/speaker-identification-voice-profiles.png b/docs/assets/images/screenshots/speaker-identification-voice-profiles.pngindex 71291f93..0d03654f 100644Binary files a/docs/assets/images/screenshots/speaker-identification-voice-profiles.png and b/docs/assets/images/screenshots/speaker-identification-voice-profiles.png differdiff --git a/docs/assets/images/screenshots/upload-interface.png b/docs/assets/images/screenshots/upload-interface.pngindex 2874c035..6c3d1bf7 100644Binary files a/docs/assets/images/screenshots/upload-interface.png and b/docs/assets/images/screenshots/upload-interface.png differdiff --git a/docs/features.md b/docs/features.mdindex 93370884..17bac927 100644--- a/docs/features.md+++ b/docs/features.md@@ -191,6 +191,14 @@ Integrate with your existing identity provider using OpenID Connect. Speakr suppTrack system health with comprehensive statistics and metrics. Monitor transcription queues, storage usage, and processing performance. Identify bottlenecks and optimize configuration based on actual usage patterns.+### Token Usage Tracking & Budgets++Monitor and control LLM API consumption with per-user token tracking and budget enforcement. The system tracks all AI operations including summarization, chat, title generation, and event extraction.++**Per-User Budgets**: Set monthly token limits for individual users to control costs. Users see their remaining budget in the interface and receive warnings at 80% consumption. Once a budget is exhausted, AI operations are blocked until the next month.++**Admin Dashboard**: View detailed token statistics including daily trends, monthly totals, and per-user breakdowns. Cost tracking is available when using OpenRouter or other providers that return cost information. See the [admin guide](admin-guide/statistics.md#token-usage-statistics) for details.+### Flexible ConfigurationConfigure every aspect of Speakr through [environment variables](getting-started.md#step-3-configure-your-transcription-service) and [admin settings](admin-guide/index.md). Check [system settings](admin-guide/system-settings.md) for global configuration options. Set API endpoints, adjust processing limits, enable or disable features, and customize the user experience. The system adapts to your infrastructure and requirements.diff --git a/docs/screenshots.md b/docs/screenshots.mdindex 61559499..8e6126be 100644--- a/docs/screenshots.md+++ b/docs/screenshots.md@@ -9,7 +9,19 @@ 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/Main view.png" alt="Main Dashboard" />- <p class="caption">Main dashboard with bubble chat interface</p>+ <p class="caption">Main dashboard with chat interface and token usage indicator</p>+ </div>++ <div class="screenshot-item">+ <img src="../assets/images/screenshots/main-view-token-usage.png" alt="Token Usage" />+ <p class="caption">Token usage indicator showing monthly budget consumption</p>+ </div>+</div>++<div class="screenshot-grid">+ <div class="screenshot-item">+ <img src="../assets/images/screenshots/main-view-recipe-example.png" alt="Recipe Example" />+ <p class="caption">Recipe transcription with family sharing enabled</p></div><div class="screenshot-item">@@ -281,6 +293,13 @@ Explore Speakr's powerful features through our visual gallery. Click on any imag<p class="caption">Manage users and monitor system usage</p></div>+ <div class="screenshot-item">+ <img src="../assets/images/screenshots/admin-user-create-token-budget.png" alt="User Token Budget" />+ <p class="caption">Create user with monthly token budget setting</p>+ </div>+</div>++<div class="screenshot-grid"><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>diff --git a/static/js/modules/composables/chat.js b/static/js/modules/composables/chat.jsindex ad21fb43..c653ab9f 100644--- a/static/js/modules/composables/chat.js+++ b/static/js/modules/composables/chat.js@@ -9,7 +9,7 @@ export function useChat(state, utils) {isChatLoading, chatMessagesRef, selectedRecording, csrfToken} = state;- const { showToast, setGlobalError, onChatComplete } = utils;+ const { showToast, setGlobalError, onChatComplete, t } = utils;// Helper function to check if chat is scrolled to bottom (within bottom 5%)const isChatScrolledToBottom = () => {@@ -159,7 +159,7 @@ export function useChat(state, utils) {}if (data.error) {if (data.budget_exceeded) {- throw new Error('Monthly token budget exceeded. Please contact your administrator.');+ throw new Error(t('adminDashboard.tokenBudgetExceeded'));}throw new Error(data.error);}diff --git a/static/locales/de.json b/static/locales/de.jsonindex e0ba8f60..d8671351 100644--- a/static/locales/de.json+++ b/static/locales/de.json@@ -151,6 +151,7 @@"tagPrompts": "Wenn mehrere Tag-Prompts existieren, werden sie in der Reihenfolge zusammengeführt, in der die Tags hinzugefügt wurden","transcriptLimit": "Transkripte sind auf eine konfigurierbare Zeichenanzahl begrenzt (Standard: 30.000)"},+ "currentUsage": "Aktuelle Nutzung","defaultPromptInfo": "Dieser Standard-Prompt wird für alle Benutzer verwendet, die keinen eigenen benutzerdefinierten Prompt in ihren Kontoeinstellungen festgelegt haben.","defaultPrompts": "Standard-Prompts","defaultSummarizationPrompt": "Standard-Zusammenfassungsprompt",@@ -177,6 +178,7 @@"maxFileSizeHelp": "Maximale Dateigröße in Megabyte (1-10000 MB)","megabytes": "MB","minutes": "Minuten",+ "monthlyTokenBudget": "Monatliches Token-Budget","needProcessing": "Benötigt Verarbeitung","never": "Nie","newPasswordLabel": "Neues Passwort (leer lassen, um das aktuelle zu behalten)",@@ -228,6 +230,11 @@"textSearchOnly": "Nur Textsuche","timeoutRecommendation": "Empfohlen: 30-120 Minuten für lange Audiodateien","title": "Administrator-Dashboard",+ "tokenBudgetExceeded": "Monatliches Token-Budget überschritten. Bitte kontaktieren Sie Ihren Administrator.",+ "tokenBudgetHelp": "Legen Sie ein monatliches Token-Limit für KI-Funktionen fest. Leer lassen für unbegrenzt.",+ "tokenBudgetPlaceholder": "Leer lassen für unbegrenzt",+ "tokenUsage": "Token-Nutzung",+ "tokens": "Token","topUsers": "Top-Benutzer","topUsersByStorage": "Top-Benutzer nach Speicher","total": "Gesamt",diff --git a/static/locales/en.json b/static/locales/en.jsonindex e04f964f..d61ec0d4 100644--- a/static/locales/en.json+++ b/static/locales/en.json@@ -168,6 +168,7 @@"tagPrompts": "If multiple tag prompts exist, they are merged in the order tags were added","transcriptLimit": "Transcripts are limited to a configurable character count (default: 30,000)"},+ "currentUsage": "Current usage","defaultPromptInfo": "This default prompt will be used for all users who haven't set their own custom prompt in their account settings.","defaultPrompts": "Default Prompts","defaultSummarizationPrompt": "Default Summarization Prompt",@@ -194,6 +195,7 @@"maxFileSizeHelp": "Maximum file size in megabytes (1-10000 MB)","megabytes": "MB","minutes": "minutes",+ "monthlyTokenBudget": "Monthly Token Budget","needProcessing": "Need Processing","never": "Never","newPasswordLabel": "New Password (leave blank to keep current)",@@ -245,6 +247,11 @@"textSearchOnly": "Text Search Only","timeoutRecommendation": "Recommended: 30-120 minutes for long audio files","title": "Admin Dashboard",+ "tokenBudgetExceeded": "Monthly token budget exceeded. Please contact your administrator.",+ "tokenBudgetHelp": "Set a monthly token limit for AI features. Leave empty for unlimited.",+ "tokenBudgetPlaceholder": "Leave empty for unlimited",+ "tokenUsage": "Token usage",+ "tokens": "tokens","topUsers": "Top Users","topUsersByStorage": "Top Users by Storage","total": "Total",diff --git a/static/locales/es.json b/static/locales/es.jsonindex a7980c69..72a3a714 100644--- a/static/locales/es.json+++ b/static/locales/es.json@@ -151,6 +151,7 @@"tagPrompts": "Si existen múltiples indicaciones de etiquetas, se fusionan en el orden en que se agregaron las etiquetas","transcriptLimit": "Las transcripciones están limitadas a un número configurable de caracteres (predeterminado: 30,000)"},+ "currentUsage": "Uso actual","defaultPromptInfo": "Este prompt predeterminado se utilizará para todos los usuarios que no hayan establecido su propio prompt personalizado en la configuración de su cuenta.","defaultPrompts": "Prompts por Defecto","defaultSummarizationPrompt": "Prompt de Resumen Predeterminado",@@ -177,6 +178,7 @@"maxFileSizeHelp": "Tamaño máximo de archivo en megabytes (1-10000 MB)","megabytes": "MB","minutes": "minutos",+ "monthlyTokenBudget": "Presupuesto Mensual de Tokens","needProcessing": "Necesita Procesamiento","never": "Nunca","newPasswordLabel": "Nueva Contraseña (dejar en blanco para mantener la actual)",@@ -228,6 +230,11 @@"textSearchOnly": "Solo Búsqueda de Texto","timeoutRecommendation": "Recomendado: 30-120 minutos para archivos de audio largos","title": "Panel de Administración",+ "tokenBudgetExceeded": "Presupuesto mensual de tokens excedido. Por favor contacte a su administrador.",+ "tokenBudgetHelp": "Establezca un límite mensual de tokens para funciones de IA. Deje vacío para ilimitado.",+ "tokenBudgetPlaceholder": "Deje vacío para ilimitado",+ "tokenUsage": "Uso de tokens",+ "tokens": "tokens","topUsers": "Usuarios Principales","topUsersByStorage": "Principales Usuarios por Almacenamiento","total": "Total",diff --git a/static/locales/fr.json b/static/locales/fr.jsonindex 9a3d5f7a..ae3074fe 100644--- a/static/locales/fr.json+++ b/static/locales/fr.json@@ -145,6 +145,7 @@"tagPrompts": "Si plusieurs invites d'étiquettes existent, elles sont fusionnées dans l'ordre où les étiquettes ont été ajoutées","transcriptLimit": "Les transcriptions sont limitées à un nombre configurable de caractères (par défaut : 30 000)"},+ "currentUsage": "Utilisation actuelle","defaultPromptInfo": "Cette invite par défaut sera utilisée pour tous les utilisateurs qui n'ont pas défini leur propre invite personnalisée dans les paramètres de leur compte.","defaultPrompts": "Invites par Défaut","defaultSummarizationPrompt": "Invite de Résumé par Défaut",@@ -171,6 +172,7 @@"maxFileSizeHelp": "Taille maximale du fichier en mégaoctets (1-10000 Mo)","megabytes": "Mo","minutes": "minutes",+ "monthlyTokenBudget": "Budget Mensuel de Tokens","needProcessing": "Nécessite un Traitement","never": "Jamais","newPasswordLabel": "Nouveau Mot de Passe (laisser vide pour conserver l'actuel)",@@ -222,6 +224,11 @@"textSearchOnly": "Recherche de Texte Uniquement","timeoutRecommendation": "Recommandé : 30-120 minutes pour les longs fichiers audio","title": "Tableau de Bord Administrateur",+ "tokenBudgetExceeded": "Budget mensuel de tokens dépassé. Veuillez contacter votre administrateur.",+ "tokenBudgetHelp": "Définissez une limite mensuelle de tokens pour les fonctionnalités IA. Laissez vide pour illimité.",+ "tokenBudgetPlaceholder": "Laissez vide pour illimité",+ "tokenUsage": "Utilisation des tokens",+ "tokens": "tokens","topUsers": "Meilleurs Utilisateurs","topUsersByStorage": "Principaux Utilisateurs par Stockage","total": "Total",diff --git a/static/locales/ru.json b/static/locales/ru.jsonindex bd4f3f27..02fe9951 100644--- a/static/locales/ru.json+++ b/static/locales/ru.json@@ -168,6 +168,7 @@"tagPrompts": "Если существует несколько запросов тегов, они объединяются в порядке добавления тегов","transcriptLimit": "Транскрипты ограничены настраиваемым количеством символов (по умолчанию: 30 000)"},+ "currentUsage": "Текущее использование","defaultPromptInfo": "Этот запрос по умолчанию будет использоваться для всех пользователей, которые не настроили свой собственный в настройках аккаунта.","defaultPrompts": "Запросы по умолчанию","defaultSummarizationPrompt": "Запрос резюмирования по умолчанию",@@ -194,6 +195,7 @@"maxFileSizeHelp": "Максимальный размер файла в мегабайтах (1-10000 МБ)","megabytes": "МБ","minutes": "минут",+ "monthlyTokenBudget": "Месячный лимит токенов","needProcessing": "Требуют обработки","never": "Никогда","newPasswordLabel": "Новый пароль (оставьте пустым, чтобы сохранить текущий)",@@ -245,6 +247,11 @@"textSearchOnly": "Только текстовый поиск","timeoutRecommendation": "Рекомендуется: 30-120 минут для длинных аудиофайлов","title": "Панель администратора",+ "tokenBudgetExceeded": "Месячный лимит токенов превышен. Пожалуйста, свяжитесь с администратором.",+ "tokenBudgetHelp": "Установите месячный лимит токенов для функций ИИ. Оставьте пустым для неограниченного использования.",+ "tokenBudgetPlaceholder": "Оставьте пустым для неограниченного",+ "tokenUsage": "Использование токенов",+ "tokens": "токенов","topUsers": "Топ пользователей","topUsersByStorage": "Топ пользователей по использованию хранилища","total": "Всего",diff --git a/static/locales/zh.json b/static/locales/zh.jsonindex 08f8a2c1..fec80b4d 100644--- a/static/locales/zh.json+++ b/static/locales/zh.json@@ -170,6 +170,7 @@"tagPrompts": "如果存在多个标签提示,它们将按添加标签的顺序合并","transcriptLimit": "转录限制为可配置的字符数(默认:30,000)"},+ "currentUsage": "当前使用量","defaultPromptInfo": "此默认提示将用于所有未在账户设置中设置自定义提示的用户。","defaultPrompts": "默认提示","defaultSummarizationPrompt": "默认摘要提示",@@ -196,6 +197,7 @@"maxFileSizeHelp": "最大文件大小(兆字节)(1-10000 MB)","megabytes": "MB","minutes": "分钟",+ "monthlyTokenBudget": "每月令牌预算","needProcessing": "需要处理","never": "从未","newPasswordLabel": "新密码(留空保持不变)",@@ -247,6 +249,11 @@"textSearchOnly": "仅文本搜索","timeoutRecommendation": "推荐:长音频文件使用 30-120 分钟","title": "管理仪表板",+ "tokenBudgetExceeded": "每月令牌预算已超出。请联系您的管理员。",+ "tokenBudgetHelp": "设置 AI 功能的每月令牌限制。留空表示无限制。",+ "tokenBudgetPlaceholder": "留空表示无限制",+ "tokenUsage": "令牌使用量",+ "tokens": "令牌","topUsers": "顶级用户","topUsersByStorage": "按存储排序的顶级用户","total": "总计",diff --git a/templates/admin.html b/templates/admin.htmlindex 4fabb0f8..b07810ac 100644--- a/templates/admin.html+++ b/templates/admin.html@@ -980,9 +980,9 @@ Summarization Instructions:</label></div><div class="mb-4">- <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Monthly Token Budget</label>- <input v-model.number="newUser.monthlyTokenBudget" type="number" min="100000" step="10000" placeholder="Leave empty for unlimited" 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">Set a monthly token limit for AI features. Leave empty for unlimited.</p>+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">${t('adminDashboard.monthlyTokenBudget')}</label>+ <input v-model.number="newUser.monthlyTokenBudget" type="number" min="100000" step="10000" :placeholder="t('adminDashboard.tokenBudgetPlaceholder')" 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">${t('adminDashboard.tokenBudgetHelp')}</p></div><div class="flex justify-end space-x-3"><button type="button" @click="showAddUserModal = false" class="px-4 py-2 border border-[var(--border-secondary)] text-[var(--text-secondary)] rounded-md hover:bg-[var(--bg-tertiary)]">${t('buttons.cancel')}</button>@@ -1020,12 +1020,12 @@ Summarization Instructions:</label></div><div class="mb-4">- <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">Monthly Token Budget</label>- <input v-model.number="editingUser.monthly_token_budget" type="number" min="100000" step="10000" placeholder="Leave empty for unlimited" 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">Set a monthly token limit for AI features. Leave empty for unlimited.</p>+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">${t('adminDashboard.monthlyTokenBudget')}</label>+ <input v-model.number="editingUser.monthly_token_budget" type="number" min="100000" step="10000" :placeholder="t('adminDashboard.tokenBudgetPlaceholder')" 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">${t('adminDashboard.tokenBudgetHelp')}</p><div v-if="editingUser.monthly_token_budget && editingUser.current_token_usage !== undefined" class="mt-2"><div class="flex justify-between text-xs text-[var(--text-muted)] mb-1">- <span>Current usage: ${ editingUser.current_token_usage?.toLocaleString() || 0 } tokens</span>+ <span>${t('adminDashboard.currentUsage')}: ${ editingUser.current_token_usage?.toLocaleString() || 0 } ${t('adminDashboard.tokens')}</span><span :class="{'text-[var(--text-danger-strong)]': editingUser.token_usage_percentage >= 100, 'text-[var(--text-warn-strong)]': editingUser.token_usage_percentage >= 80 && editingUser.token_usage_percentage < 100}">${ editingUser.token_usage_percentage || 0 }%</span></div><div class="w-full bg-[var(--bg-tertiary)] rounded-full h-2">diff --git a/templates/components/token_budget_indicator.html b/templates/components/token_budget_indicator.htmlindex 1f450a40..edbebc23 100644--- a/templates/components/token_budget_indicator.html+++ b/templates/components/token_budget_indicator.html@@ -2,7 +2,7 @@<!-- Only shows if user has a budget limit set --><div v-if="tokenBudget && tokenBudget.has_budget"class="hidden sm:flex items-center gap-1.5 px-2 py-1 rounded text-xs text-[var(--text-muted)] hover:text-[var(--text-secondary)] transition-colors cursor-default"- :title="'Token usage: ' + (tokenBudget.usage || 0).toLocaleString() + ' / ' + (tokenBudget.budget || 0).toLocaleString()">+ :title="t('adminDashboard.tokenUsage') + ': ' + (tokenBudget.usage || 0).toLocaleString() + ' / ' + (tokenBudget.budget || 0).toLocaleString()"><i class="fas fa-coins text-[10px]":style="tokenBudget.percentage >= 100 ? {color: '#ef4444'} : tokenBudget.percentage >= 80 ? {color: '#f59e0b'} : {}"></i><span :style="tokenBudget.percentage >= 100 ? {color: '#ef4444'} : tokenBudget.percentage >= 80 ? {color: '#f59e0b'} : {}">${ tokenBudget.percentage }%</span>diff --git a/templates/inquire.html b/templates/inquire.htmlindex 6d1ff9ae..5fd406b6 100644--- a/templates/inquire.html+++ b/templates/inquire.html@@ -756,7 +756,7 @@return;} else if (data.error) {if (data.budget_exceeded) {- throw new Error('Monthly token budget exceeded. Please contact your administrator for more tokens.');+ throw new Error(t('adminDashboard.tokenBudgetExceeded'));}throw new Error(data.error);}