Skip to content

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

Python

System Statistics: correct monthly numbers, real request count, every recording state and the job queue

Murtaza Nasird9df7aca9dd8
diff --git a/src/api/admin.py b/src/api/admin.py
index 48abb36c..4928bbf8 100644
--- a/src/api/admin.py
+++ b/src/api/admin.py
@@ -436,8 +436,22 @@ def admin_get_stats():
# Get recordings by status
completed_recordings = Recording.query.filter_by(status='COMPLETED').count()
processing_recordings = Recording.query.filter(Recording.status.in_(['PROCESSING', 'SUMMARIZING'])).count()
+ transcribing_recordings = Recording.query.filter_by(status='PROCESSING').count()
+ summarizing_recordings = Recording.query.filter_by(status='SUMMARIZING').count()
pending_recordings = Recording.query.filter_by(status='PENDING').count()
failed_recordings = Recording.query.filter_by(status='FAILED').count()
+ audio_removed_recordings = Recording.query.filter(Recording.audio_deleted_at.isnot(None)).count()
+ archived_recordings = Recording.query.filter(Recording.is_archived.is_(True)).count()
+
+ # The job queue: what is waiting, running, and what failed this week.
+ from datetime import datetime as _dt, timedelta as _td
+ from src.models.processing_job import ProcessingJob
+ jobs_queued = ProcessingJob.query.filter_by(status='queued').count()
+ jobs_running = ProcessingJob.query.filter_by(status='processing').count()
+ jobs_failed_7d = ProcessingJob.query.filter(
+ ProcessingJob.status == 'failed',
+ db.func.coalesce(ProcessingJob.completed_at, ProcessingJob.created_at) >= _dt.utcnow() - _td(days=7),
+ ).count()
# Get total storage used (exclude retention-removed audio — file gone but
# file_size still recorded; see the user-list query above).
@@ -482,9 +496,17 @@ def admin_get_stats():
'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
+ # AI requests this month: every model call except embeddings (chat,
+ # summaries, titles, events, speakers, Inquire). It replaces a "total
+ # queries" figure that was a hard-coded 0.
+ from datetime import date as _date
+ from src.models import TokenUsage
+ from src.services.token_tracking import token_tracker
+ month_start = _date.today().replace(day=1)
+ ai_requests_month = sum(
+ int(n or 0) for op, n in db.session.query(TokenUsage.operation_type, db.func.sum(TokenUsage.request_count))
+ .filter(TokenUsage.date >= month_start).group_by(TokenUsage.operation_type)
+ if not token_tracker.is_embedding_op(op))
return jsonify({
'total_users': total_users,
@@ -495,7 +517,12 @@ def admin_get_stats():
'failed_recordings': failed_recordings,
'total_storage': total_storage,
'top_users': top_users,
- 'total_queries': total_queries
+ 'ai_requests_month': ai_requests_month,
+ 'transcribing_recordings': transcribing_recordings,
+ 'summarizing_recordings': summarizing_recordings,
+ 'audio_removed_recordings': audio_removed_recordings,
+ 'archived_recordings': archived_recordings,
+ 'jobs': {'queued': jobs_queued, 'running': jobs_running, 'failed_7d': jobs_failed_7d},
})
@@ -554,8 +581,10 @@ def admin_get_token_stats():
for r in op_rows
]
+ from src.services.embeddings import embeddings_are_local
return jsonify({
'today': today_usage,
+ 'embeddings_local': embeddings_are_local(),
'current_month': {
'tokens': current_month.get('tokens', 0),
'cost': current_month.get('cost', 0),
diff --git a/src/services/embeddings.py b/src/services/embeddings.py
index 9a7b3f07..ce23b8c7 100644
--- a/src/services/embeddings.py
+++ b/src/services/embeddings.py
@@ -898,4 +898,20 @@ def semantic_search_chunks(user_id, query, filters=None, top_k=5):
# --- Helper Functions for Document Processing ---
+def embeddings_are_local():
+ """True when embeddings are computed on machines the administrator runs:
+ the built-in local model, or an endpoint on a loopback or private address
+ or a .local/.lan/.internal host. Used to show "local" in place of $0."""
+ if not USE_API_EMBEDDINGS:
+ return True
+ import ipaddress
+ from urllib.parse import urlparse
+ host = (urlparse(EMBEDDING_BASE_URL).hostname or '').lower()
+ if host in ('localhost',) or host.endswith(('.local', '.lan', '.internal', '.localhost')):
+ return True
+ try:
+ ip = ipaddress.ip_address(host)
+ return ip.is_private or ip.is_loopback or ip.is_link_local
+ except ValueError:
+ return False
diff --git a/src/services/token_tracking.py b/src/services/token_tracking.py
index 03ddf48b..1805ff4d 100644
--- a/src/services/token_tracking.py
+++ b/src/services/token_tracking.py
@@ -297,8 +297,20 @@ class TokenTracker:
buckets[key]['llm_tokens'] += tokens
buckets[key]['llm_cost'] += cost
- ordered = [buckets[k] for k in sorted(buckets.keys())]
- return ordered[-months:] if len(ordered) > months else ordered
+ # The last N calendar months up to this one, with zeros for months
+ # without usage, so charts keep an even axis and the last entry is
+ # always the current month (it used to be the last month WITH usage).
+ today = date.today()
+ out = []
+ y, m = today.year, today.month
+ for _ in range(max(months, 1)):
+ out.append(buckets.get((y, m)) or {
+ 'year': y, 'month': m, 'tokens': 0, 'cost': 0.0,
+ 'llm_tokens': 0, 'llm_cost': 0.0, 'embedding_tokens': 0, 'embedding_cost': 0.0,
+ 'cached_tokens': 0, 'cache_write_tokens': 0,
+ })
+ y, m = (y, m - 1) if m > 1 else (y - 1, 12)
+ return list(reversed(out))
def get_user_stats(self) -> List[Dict]:
"""Get per-user token usage breakdown for current month."""
diff --git a/src/services/transcription_tracking.py b/src/services/transcription_tracking.py
index ca63f138..80e78173 100644
--- a/src/services/transcription_tracking.py
+++ b/src/services/transcription_tracking.py
@@ -241,19 +241,20 @@ class TranscriptionTracker:
func.sum(TranscriptionUsage.estimated_cost).label('cost')
).group_by('year', 'month').order_by('year', 'month').all()
- # Get last N months
- monthly_data = [
- {
- 'year': int(r.year),
- 'month': int(r.month),
- 'seconds': r.seconds or 0,
- 'minutes': (r.seconds or 0) // 60,
- 'cost': r.cost or 0
- }
- for r in results
- ]
-
- return monthly_data[-months:] if len(monthly_data) > months else monthly_data
+ by_month = {(int(r.year), int(r.month)): r for r in results}
+ # The last N calendar months up to this one, zeros included, so the
+ # last entry is always the current month (it used to be the last
+ # month WITH usage, which showed last month's total as "this month").
+ today = date.today()
+ out = []
+ y, m = today.year, today.month
+ for _ in range(max(months, 1)):
+ r = by_month.get((y, m))
+ seconds = (r.seconds or 0) if r else 0
+ out.append({'year': y, 'month': m, 'seconds': seconds, 'minutes': seconds // 60,
+ 'cost': (r.cost or 0) if r else 0})
+ y, m = (y, m - 1) if m > 1 else (y - 1, 12)
+ return list(reversed(out))
def get_user_stats(self) -> List[Dict]:
"""Get per-user transcription usage breakdown for current month."""
diff --git a/static/locales/de.json b/static/locales/de.json
index e411153f..889ca5a6 100644
--- a/static/locales/de.json
+++ b/static/locales/de.json
@@ -302,14 +302,14 @@
"tokensByOperation": "Tokens nach Vorgang (diesen Monat)",
"noUsage": "Diesen Monat noch keine Nutzung erfasst.",
"requests": "Anf.",
- "cached": "im Cache"
+ "cached": "im Cache",
+ "local": "Lokal"
},
"tokens": "Token",
"topUsers": "Top-Benutzer",
"topUsersByStorage": "Top-Benutzer nach Speicher",
"total": "Gesamt",
"totalChunks": "Gesamte Chunks",
- "totalQueries": "Gesamte Abfragen",
"totalRecordings": "Gesamte Aufnahmen",
"totalStorage": "Gesamter Speicher",
"totalUsers": "Gesamte Benutzer",
@@ -363,7 +363,14 @@
"sourceAdmin": "Aktiv: {{value}} (Admin-Einstellung; Standard {{default}})",
"sourceDefault": "Aktiv: {{value}} (Standard)"
},
- "defaultTimezoneHelp": "Wird für Datumsangaben in erzeugten Titeln verwendet, wenn der Browser eines Benutzers keine Zeitzone gemeldet und der Benutzer keine gewählt hat."
+ "defaultTimezoneHelp": "Wird für Datumsangaben in erzeugten Titeln verwendet, wenn der Browser eines Benutzers keine Zeitzone gemeldet und der Benutzer keine gewählt hat.",
+ "aiRequestsMonth": "KI-Anfragen in diesem Monat",
+ "transcribingRecordings": "Wird transkribiert",
+ "summarizingRecordings": "Wird zusammengefasst",
+ "audioRemovedRecordings": "Audio entfernt",
+ "archivedRecordings": "Archiviert",
+ "jobQueue": "Warteschlange: {{queued}} wartend, {{running}} laufend",
+ "jobsFailed7d": "{{count}} in den letzten 7 Tagen fehlgeschlagen"
},
"apiTokens": {
"activeTokens": "Aktive Token",
diff --git a/static/locales/en.json b/static/locales/en.json
index 36b7bd14..114720e6 100644
--- a/static/locales/en.json
+++ b/static/locales/en.json
@@ -302,14 +302,14 @@
"tokensByOperation": "Tokens by Operation (This Month)",
"noUsage": "No usage recorded yet this month.",
"requests": "req",
- "cached": "cached"
+ "cached": "cached",
+ "local": "Local"
},
"tokens": "tokens",
"topUsers": "Top Users",
"topUsersByStorage": "Top Users by Storage",
"total": "Total",
"totalChunks": "Total Chunks",
- "totalQueries": "Total Queries",
"totalRecordings": "Total Recordings",
"totalStorage": "Total Storage",
"totalUsers": "Total Users",
@@ -363,7 +363,14 @@
"sourceAdmin": "In use: {{value}} (admin setting; default {{default}})",
"sourceDefault": "In use: {{value}} (default)"
},
- "defaultTimezoneHelp": "Used for dates in generated titles when a user's browser has not reported a timezone and the user has not chosen one."
+ "defaultTimezoneHelp": "Used for dates in generated titles when a user's browser has not reported a timezone and the user has not chosen one.",
+ "aiRequestsMonth": "AI requests this month",
+ "transcribingRecordings": "Transcribing",
+ "summarizingRecordings": "Summarizing",
+ "audioRemovedRecordings": "Audio removed",
+ "archivedRecordings": "Archived",
+ "jobQueue": "Job queue: {{queued}} waiting, {{running}} running",
+ "jobsFailed7d": "{{count}} failed in the last 7 days"
},
"apiTokens": {
"activeTokens": "Active Tokens",
diff --git a/static/locales/es.json b/static/locales/es.json
index 4588d442..88d30fa0 100644
--- a/static/locales/es.json
+++ b/static/locales/es.json
@@ -302,14 +302,14 @@
"tokensByOperation": "Tokens por operación (este mes)",
"noUsage": "Aún no se ha registrado uso este mes.",
"requests": "sol.",
- "cached": "en caché"
+ "cached": "en caché",
+ "local": "Local"
},
"tokens": "tokens",
"topUsers": "Usuarios Principales",
"topUsersByStorage": "Principales Usuarios por Almacenamiento",
"total": "Total",
"totalChunks": "Total de Fragmentos",
- "totalQueries": "Total de Consultas",
"totalRecordings": "Total de Grabaciones",
"totalStorage": "Almacenamiento Total",
"totalUsers": "Total de Usuarios",
@@ -363,7 +363,14 @@
"sourceAdmin": "En uso: {{value}} (ajuste del administrador; predeterminado {{default}})",
"sourceDefault": "En uso: {{value}} (predeterminado)"
},
- "defaultTimezoneHelp": "Se usa para las fechas de los títulos generados cuando el navegador de un usuario no ha indicado una zona horaria y el usuario no ha elegido ninguna."
+ "defaultTimezoneHelp": "Se usa para las fechas de los títulos generados cuando el navegador de un usuario no ha indicado una zona horaria y el usuario no ha elegido ninguna.",
+ "aiRequestsMonth": "Solicitudes de IA este mes",
+ "transcribingRecordings": "Transcribiendo",
+ "summarizingRecordings": "Resumiendo",
+ "audioRemovedRecordings": "Audio eliminado",
+ "archivedRecordings": "Archivadas",
+ "jobQueue": "Cola de trabajos: {{queued}} en espera, {{running}} en curso",
+ "jobsFailed7d": "{{count}} fallidos en los últimos 7 días"
},
"apiTokens": {
"activeTokens": "Tokens activos",
diff --git a/static/locales/fr.json b/static/locales/fr.json
index ca126d68..51fb432e 100644
--- a/static/locales/fr.json
+++ b/static/locales/fr.json
@@ -302,14 +302,14 @@
"tokensByOperation": "Jetons par opération (ce mois-ci)",
"noUsage": "Aucune utilisation enregistrée ce mois-ci.",
"requests": "req",
- "cached": "en cache"
+ "cached": "en cache",
+ "local": "Local"
},
"tokens": "jetons",
"topUsers": "Meilleurs Utilisateurs",
"topUsersByStorage": "Principaux Utilisateurs par Stockage",
"total": "Total",
"totalChunks": "Total des Segments",
- "totalQueries": "Total des Requêtes",
"totalRecordings": "Total des Enregistrements",
"totalStorage": "Stockage Total",
"totalUsers": "Total des Utilisateurs",
@@ -363,7 +363,14 @@
"sourceAdmin": "Utilisée : {{value}} (réglage administrateur ; par défaut {{default}})",
"sourceDefault": "Utilisée : {{value}} (par défaut)"
},
- "defaultTimezoneHelp": "Utilisé pour les dates des titres générés lorsque le navigateur d'un utilisateur n'a pas indiqué de fuseau horaire et que l'utilisateur n'en a pas choisi."
+ "defaultTimezoneHelp": "Utilisé pour les dates des titres générés lorsque le navigateur d'un utilisateur n'a pas indiqué de fuseau horaire et que l'utilisateur n'en a pas choisi.",
+ "aiRequestsMonth": "Requêtes IA ce mois-ci",
+ "transcribingRecordings": "Transcription",
+ "summarizingRecordings": "Résumé en cours",
+ "audioRemovedRecordings": "Audio supprimé",
+ "archivedRecordings": "Archivés",
+ "jobQueue": "File d'attente : {{queued}} en attente, {{running}} en cours",
+ "jobsFailed7d": "{{count}} en échec ces 7 derniers jours"
},
"apiTokens": {
"activeTokens": "Jetons actifs",
diff --git a/static/locales/pt-BR.json b/static/locales/pt-BR.json
index 03e06bb9..9169cd20 100644
--- a/static/locales/pt-BR.json
+++ b/static/locales/pt-BR.json
@@ -302,14 +302,14 @@
"tokensByOperation": "Tokens por operação (este mês)",
"noUsage": "Nenhum uso registrado ainda este mês.",
"requests": "req",
- "cached": "em cache"
+ "cached": "em cache",
+ "local": "Local"
},
"tokens": "tokens",
"topUsers": "Principais Usuários",
"topUsersByStorage": "Principais Usuários por Armazenamento",
"total": "Total",
"totalChunks": "Total de Chunks",
- "totalQueries": "Total de Consultas",
"totalRecordings": "Total de Gravações",
"totalStorage": "Armazenamento Total",
"totalUsers": "Total de Usuários",
@@ -363,7 +363,14 @@
"sourceAdmin": "Em uso: {{value}} (configuração do administrador; padrão {{default}})",
"sourceDefault": "Em uso: {{value}} (padrão)"
},
- "defaultTimezoneHelp": "Usado para as datas nos títulos gerados quando o navegador do usuário não informou um fuso horário e o usuário não escolheu nenhum."
+ "defaultTimezoneHelp": "Usado para as datas nos títulos gerados quando o navegador do usuário não informou um fuso horário e o usuário não escolheu nenhum.",
+ "aiRequestsMonth": "Solicitações de IA neste mês",
+ "transcribingRecordings": "Transcrevendo",
+ "summarizingRecordings": "Resumindo",
+ "audioRemovedRecordings": "Áudio removido",
+ "archivedRecordings": "Arquivadas",
+ "jobQueue": "Fila de tarefas: {{queued}} aguardando, {{running}} em execução",
+ "jobsFailed7d": "{{count}} com falha nos últimos 7 dias"
},
"apiTokens": {
"activeTokens": "Tokens Ativos",
diff --git a/static/locales/ru.json b/static/locales/ru.json
index 2ced8982..1eed4cd4 100644
--- a/static/locales/ru.json
+++ b/static/locales/ru.json
@@ -302,14 +302,14 @@
"tokensByOperation": "Токены по операциям (за этот месяц)",
"noUsage": "За этот месяц использование ещё не зафиксировано.",
"requests": "запр.",
- "cached": "из кэша"
+ "cached": "из кэша",
+ "local": "Локально"
},
"tokens": "токенов",
"topUsers": "Топ пользователей",
"topUsersByStorage": "Топ пользователей по использованию хранилища",
"total": "Всего",
"totalChunks": "Всего фрагментов",
- "totalQueries": "Всего запросов",
"totalRecordings": "Всего записей",
"totalStorage": "Общее хранилище",
"totalUsers": "Всего пользователей",
@@ -363,7 +363,14 @@
"sourceAdmin": "Используется: {{value}} (настройка администратора; по умолчанию {{default}})",
"sourceDefault": "Используется: {{value}} (по умолчанию)"
},
- "defaultTimezoneHelp": "Используется для дат в созданных названиях, если браузер пользователя не сообщил часовой пояс и пользователь не выбрал его."
+ "defaultTimezoneHelp": "Используется для дат в созданных названиях, если браузер пользователя не сообщил часовой пояс и пользователь не выбрал его.",
+ "aiRequestsMonth": "Запросы к ИИ за месяц",
+ "transcribingRecordings": "Транскрибируется",
+ "summarizingRecordings": "Создаётся сводка",
+ "audioRemovedRecordings": "Аудио удалено",
+ "archivedRecordings": "В архиве",
+ "jobQueue": "Очередь задач: {{queued}} ожидают, {{running}} выполняются",
+ "jobsFailed7d": "{{count}} с ошибкой за последние 7 дней"
},
"apiTokens": {
"activeTokens": "Активные токены",
diff --git a/static/locales/zh.json b/static/locales/zh.json
index eb15e956..291712cf 100644
--- a/static/locales/zh.json
+++ b/static/locales/zh.json
@@ -302,14 +302,14 @@
"tokensByOperation": "按操作分类的令牌(本月)",
"noUsage": "本月尚无使用记录。",
"requests": "次请求",
- "cached": "已缓存"
+ "cached": "已缓存",
+ "local": "本地"
},
"tokens": "tokens",
"topUsers": "顶级用户",
"topUsersByStorage": "按存储排序的顶级用户",
"total": "合计",
"totalChunks": "总块数",
- "totalQueries": "总查询数",
"totalRecordings": "总录音数",
"totalStorage": "总存储",
"totalUsers": "总用户数",
@@ -363,7 +363,14 @@
"sourceAdmin": "当前:{{value}}(管理员设置;默认 {{default}})",
"sourceDefault": "当前:{{value}}(默认)"
},
- "defaultTimezoneHelp": "当用户的浏览器未报告时区且用户未选择时区时,用于生成标题中的日期。"
+ "defaultTimezoneHelp": "当用户的浏览器未报告时区且用户未选择时区时,用于生成标题中的日期。",
+ "aiRequestsMonth": "本月 AI 请求",
+ "transcribingRecordings": "转录中",
+ "summarizingRecordings": "摘要中",
+ "audioRemovedRecordings": "音频已移除",
+ "archivedRecordings": "已归档",
+ "jobQueue": "任务队列:{{queued}} 个等待,{{running}} 个运行中",
+ "jobsFailed7d": "最近 7 天 {{count}} 个失败"
},
"apiTokens": {
"activeTokens": "活跃令牌",
diff --git a/templates/admin.html b/templates/admin.html
index 6ba31e5d..0bf264d5 100644
--- a/templates/admin.html
+++ b/templates/admin.html
@@ -350,8 +350,8 @@
<i class="fas fa-comments text-xl"></i>
</div>
<div class="ml-4">
- <p class="text-sm font-medium text-[var(--text-muted)]">${t('adminDashboard.totalQueries')}</p>
- <p class="text-2xl font-semibold text-[var(--text-primary)]">${ stats.total_queries }</p>
+ <p class="text-sm font-medium text-[var(--text-muted)]">${t('adminDashboard.aiRequestsMonth')}</p>
+ <p class="text-2xl font-semibold text-[var(--text-primary)]">${ (stats.ai_requests_month || 0).toLocaleString() }</p>
</div>
</div>
</div>
@@ -361,26 +361,45 @@
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
<div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm">
<h4 class="text-md font-medium text-[var(--text-secondary)] mb-3">${t('adminDashboard.recordingStatusDistribution')}</h4>
- <div class="grid grid-cols-2 gap-4">
- <div class="text-center p-3 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] shadow-sm">
- <span class="block text-2xl font-bold text-[var(--text-success-strong)]">${ stats.completed_recordings }</span>
- <span class="block text-sm text-[var(--text-muted)]">${t('adminDashboard.completedRecordings')}</span>
+ <div class="grid grid-cols-2 sm:grid-cols-4 gap-3">
+ <div class="text-center p-3 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)]">
+ <span class="block text-xl font-bold text-[var(--text-success-strong)]">${ stats.completed_recordings }</span>
+ <span class="block text-xs text-[var(--text-muted)]">${t('adminDashboard.completedRecordings')}</span>
</div>
- <div class="text-center p-3 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] shadow-sm">
- <span class="block text-2xl font-bold text-[var(--text-warn-strong)]">${ stats.processing_recordings }</span>
- <span class="block text-sm text-[var(--text-muted)]">${t('adminDashboard.processingRecordings')}</span>
+ <div class="text-center p-3 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)]">
+ <span class="block text-xl font-bold text-[var(--text-warn-strong)]">${ stats.transcribing_recordings }</span>
+ <span class="block text-xs text-[var(--text-muted)]">${t('adminDashboard.transcribingRecordings')}</span>
</div>
- <div class="text-center p-3 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] shadow-sm">
- <span class="block text-2xl font-bold text-[var(--text-pending-strong)]">${ stats.pending_recordings }</span>
- <span class="block text-sm text-[var(--text-muted)]">${t('adminDashboard.pendingRecordings')}</span>
+ <div class="text-center p-3 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)]">
+ <span class="block text-xl font-bold text-[var(--text-warn-strong)]">${ stats.summarizing_recordings }</span>
+ <span class="block text-xs text-[var(--text-muted)]">${t('adminDashboard.summarizingRecordings')}</span>
</div>
- <div class="text-center p-3 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] shadow-sm">
- <span class="block text-2xl font-bold text-[var(--text-danger-strong)]">${ stats.failed_recordings }</span>
- <span class="block text-sm text-[var(--text-muted)]">${t('adminDashboard.failedRecordings')}</span>
+ <div class="text-center p-3 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)]">
+ <span class="block text-xl font-bold text-[var(--text-pending-strong)]">${ stats.pending_recordings }</span>
+ <span class="block text-xs text-[var(--text-muted)]">${t('adminDashboard.pendingRecordings')}</span>
+ </div>
+ <div class="text-center p-3 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)]">
+ <span class="block text-xl font-bold text-[var(--text-danger-strong)]">${ stats.failed_recordings }</span>
+ <span class="block text-xs text-[var(--text-muted)]">${t('adminDashboard.failedRecordings')}</span>
+ </div>
+ <div class="text-center p-3 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)]">
+ <span class="block text-xl font-bold text-[var(--text-secondary)]">${ stats.audio_removed_recordings }</span>
+ <span class="block text-xs text-[var(--text-muted)]">${t('adminDashboard.audioRemovedRecordings')}</span>
+ </div>
+ <div class="text-center p-3 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)]">
+ <span class="block text-xl font-bold text-[var(--text-secondary)]">${ stats.archived_recordings }</span>
+ <span class="block text-xs text-[var(--text-muted)]">${t('adminDashboard.archivedRecordings')}</span>
</div>
</div>
+ <!-- The job queue: waiting, running, failed this week. -->
+ <p class="mt-3 text-sm text-[var(--text-secondary)]">
+ <i class="fas fa-layer-group mr-1 text-[var(--text-muted)]"></i>
+ <span v-text="t('adminDashboard.jobQueue', { queued: stats.jobs.queued, running: stats.jobs.running })"></span>
+ <span v-if="stats.jobs.failed_7d" class="ml-2 text-[var(--text-danger-strong)]"
+ v-text="t('adminDashboard.jobsFailed7d', { count: stats.jobs.failed_7d })"></span>
+ </p>
</div>
-
+
<div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm">
<h4 class="text-md font-medium text-[var(--text-secondary)] mb-3">${t('adminDashboard.topUsersByStorage')}</h4>
<div class="space-y-3">
@@ -509,7 +528,7 @@
</div>
<div class="p-3 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)]">
<p class="text-xs text-[var(--text-muted)]">${ t('adminDashboard.tokenUsage.monthlyCost') }</p>
- <p class="text-lg font-semibold text-[var(--text-primary)]">$${ (tokenStats.current_month?.embedding_cost || 0).toFixed(4) }</p>
+ <p class="text-lg font-semibold text-[var(--text-primary)]" v-text="tokenStats.embeddings_local ? t('adminDashboard.tokenUsage.local') : '$' + (tokenStats.current_month?.embedding_cost || 0).toFixed(4)"></p>
</div>
</div>
</div>
@@ -557,7 +576,7 @@
<!-- Per-User Token Usage -->
<div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm">
<h5 class="text-md font-medium text-[var(--text-secondary)] mb-3">User Token Usage (This Month)</h5>
- <div class="space-y-2 max-h-48 overflow-y-auto">
+ <div class="space-y-2">
<div v-for="user in tokenUserStats" :key="user.user_id" class="p-2 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)]">
<div class="flex justify-between items-center">
<div class="flex items-center">
@@ -681,7 +700,7 @@
<!-- Per-User Transcription Usage -->
<div class="bg-[var(--bg-tertiary)] p-4 rounded-lg border border-[var(--border-primary)] shadow-sm">
<h5 class="text-md font-medium text-[var(--text-secondary)] mb-3">${t('adminDashboard.userTranscriptionUsage')}</h5>
- <div class="space-y-2 max-h-48 overflow-y-auto">
+ <div class="space-y-2">
<div v-for="user in transcriptionUserStats" :key="user.user_id" class="p-2 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)]">
<div class="flex justify-between items-center">
<div class="flex items-center">
@@ -2185,11 +2204,16 @@ Summarization Instructions:
total_users: 0,
total_recordings: 0,
total_storage: 0,
- total_queries: 0,
+ ai_requests_month: 0,
completed_recordings: 0,
processing_recordings: 0,
+ transcribing_recordings: 0,
+ summarizing_recordings: 0,
pending_recordings: 0,
failed_recordings: 0,
+ audio_removed_recordings: 0,
+ archived_recordings: 0,
+ jobs: { queued: 0, running: 0, failed_7d: 0 },
top_users: []
});
const tokenStats = ref({
@@ -2718,7 +2742,7 @@ Summarization Instructions:
maintainAspectRatio: false,
plugins: { legend: { display: false } },
scales: {
- x: { ticks: { color: textColor, maxRotation: 45, minRotation: 45 }, grid: { color: gridColor } },
+ x: { ticks: { color: textColor, maxRotation: 0, autoSkip: true, maxTicksLimit: 8 }, grid: { display: false } },
y: { beginAtZero: true, ticks: { color: textColor }, grid: { color: gridColor } }
}
}
@@ -2726,13 +2750,18 @@ Summarization Instructions:
};
const renderDailyChart = (data) => {
- window._dailyLabels = data.map(d => d.date);
+ const shortMonth = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
+ window._dailyLabels = data.map(d => {
+ const [, m, day] = String(d.date).split('-');
+ return m && day ? `${shortMonth[Number(m) - 1]} ${Number(day)}` : d.date;
+ });
window._dailyData = data;
_renderDailyBar('dailyTokenChart', dailyTokenChart, 'llm_tokens', 'LLM tokens', '79, 70, 229');
_renderDailyBar('dailyEmbeddingChart', dailyEmbeddingChart, 'embedding_tokens', 'Embedding tokens', '34, 197, 94');
};
- // Shared line-chart factory for monthly LLM vs embedding usage.
+ // Monthly totals as bars: a smoothed line drew rises and dips
+ // between months that never happened.
const _renderMonthlyLine = (canvasId, ref_, labels, values, displayLabel, colorRgb) => {
const ctx = document.getElementById(canvasId);
if (!ctx) return;
@@ -2741,17 +2770,15 @@ Summarization Instructions:
const textColor = isDark ? '#9ca3af' : '#6b7280';
const gridColor = isDark ? '#374151' : '#e5e7eb';
ref_.value = new Chart(ctx, {
- type: 'line',
+ type: 'bar',
data: {
labels: labels,
datasets: [{
label: displayLabel,
data: values,
- fill: true,
- backgroundColor: `rgba(${colorRgb}, 0.2)`,
+ backgroundColor: `rgba(${colorRgb}, 0.7)`,
borderColor: `rgba(${colorRgb}, 1)`,
- borderWidth: 2,
- tension: 0.3
+ borderWidth: 1
}]
},
options: {
@@ -2759,7 +2786,7 @@ Summarization Instructions:
maintainAspectRatio: false,
plugins: { legend: { display: false } },
scales: {
- x: { ticks: { color: textColor }, grid: { color: gridColor } },
+ x: { ticks: { color: textColor, maxRotation: 0, autoSkip: true, maxTicksLimit: 12 }, grid: { display: false } },
y: { beginAtZero: true, ticks: { color: textColor }, grid: { color: gridColor } }
}
}
@@ -2768,7 +2795,7 @@ Summarization Instructions:
const renderMonthlyChart = (data) => {
const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
- const labels = data.map(d => `${monthNames[d.month - 1]} ${d.year}`);
+ const labels = data.map(d => d.month === 1 || d === data[0] ? `${monthNames[d.month - 1]} ${d.year}` : monthNames[d.month - 1]);
const llm = data.map(d => d.llm_tokens || 0);
const emb = data.map(d => d.embedding_tokens || 0);
_renderMonthlyLine('monthlyTokenChart', monthlyTokenChart, labels, llm, 'LLM tokens', '22, 163, 74');
diff --git a/tests/test_admin_stats.py b/tests/test_admin_stats.py
new file mode 100644
index 00000000..8391a5a9
--- /dev/null
+++ b/tests/test_admin_stats.py
@@ -0,0 +1,139 @@
+"""System Statistics numbers.
+
+"This month" is the calendar month, also when it has no usage yet (it showed
+the last month WITH usage), months without usage appear as zeros, "AI
+requests this month" counts model calls (it was a hard-coded 0), and the
+recording states and job queue are reported in full.
+
+SHARED-DB: users, usage rows, jobs and recordings are removed afterwards.
+"""
+
+import os
+import secrets
+import sys
+from datetime import date, datetime, timedelta
+from unittest.mock import patch
+
+import pytest
+from flask import g, has_app_context
+from flask.testing import FlaskClient
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from src.app import app, db
+from src.models import Recording, TokenUsage, TranscriptionUsage, User
+from src.models.processing_job import ProcessingJob
+
+
+class _Client(FlaskClient):
+ def open(self, *args, **kwargs):
+ if has_app_context():
+ g.pop('_login_user', None)
+ return super().open(*args, **kwargs)
+
+
+def _last_month(today):
+ first = today.replace(day=1)
+ return (first - timedelta(days=1)).replace(day=15)
+
+
+def world():
+ with app.app_context():
+ s = secrets.token_hex(4)
+ admin = User(username=f"st_{s}", email=f"st_{s}@local.test", password="x", is_admin=True)
+ db.session.add(admin)
+ db.session.commit()
+ ids = {"admin": admin.id}
+ yield ids
+ with app.app_context():
+ db.session.rollback()
+ TokenUsage.query.filter_by(user_id=ids["admin"]).delete()
+ TranscriptionUsage.query.filter_by(user_id=ids["admin"]).delete()
+ ProcessingJob.query.filter_by(user_id=ids["admin"]).delete()
+ Recording.query.filter_by(user_id=ids["admin"]).delete()
+ User.query.filter_by(id=ids["admin"]).delete()
+ db.session.commit()
+
+
+def _client(uid):
+ c = _Client(app, app.response_class, use_cookies=True)
+ with c.session_transaction() as sess:
+ sess["_user_id"] = str(uid)
+ return c
+
+
+def test_this_month_is_the_calendar_month(world):
+ from src.services.token_tracking import token_tracker
+ from src.services.transcription_tracking import transcription_tracker
+ today = date.today()
+ with app.app_context():
+ before_tokens = token_tracker.get_monthly_stats(months=1)[-1]["llm_tokens"]
+ before_seconds = transcription_tracker.get_monthly_stats(months=1)[-1]["seconds"]
+ db.session.add(TokenUsage(user_id=world["admin"], date=_last_month(today), operation_type="summarization",
+ total_tokens=5000, request_count=1, cost=0.5))
+ db.session.add(TranscriptionUsage(user_id=world["admin"], date=_last_month(today), connector_type="asr_endpoint",
+ audio_duration_seconds=6000, estimated_cost=0.1))
+ db.session.commit()
+ tokens = token_tracker.get_monthly_stats(months=1)
+ seconds = transcription_tracker.get_monthly_stats(months=1)
+ assert (tokens[-1]["year"], tokens[-1]["month"]) == (today.year, today.month)
+ assert tokens[-1]["llm_tokens"] == before_tokens # last month's 5000 not counted
+ assert (seconds[-1]["year"], seconds[-1]["month"]) == (today.year, today.month)
+ assert seconds[-1]["seconds"] == before_seconds
+
+
+def test_months_without_usage_are_zeros(world):
+ from src.services.token_tracking import token_tracker
+ from src.services.transcription_tracking import transcription_tracker
+ with app.app_context():
+ months = token_tracker.get_monthly_stats(months=12)
+ tmonths = transcription_tracker.get_monthly_stats(months=12)
+ assert len(months) == 12 and len(tmonths) == 12
+ keys = [(m["year"], m["month"]) for m in months]
+ assert keys == sorted(keys) and len(set(keys)) == 12
+ assert keys[-1] == (date.today().year, date.today().month)
+ for (y1, m1), (y2, m2) in zip(keys, keys[1:]):
+ assert (y2 * 12 + m2) - (y1 * 12 + m1) == 1
+
+
+def test_stats_report_requests_states_and_queue(world):
+ with app.app_context():
+ before = _client(world["admin"]).get("/admin/stats").get_json()
+ db.session.add_all([
+ TokenUsage(user_id=world["admin"], date=date.today(), operation_type="chat", total_tokens=10, request_count=3),
+ TokenUsage(user_id=world["admin"], date=date.today(), operation_type="embedding", total_tokens=10, request_count=50),
+ ])
+ recs = [Recording(user_id=world["admin"], title=t, status=st, original_filename="a.wav")
+ for t, st in (("a", "PROCESSING"), ("b", "SUMMARIZING"), ("c", "COMPLETED"))]
+ recs[2].audio_deleted_at = datetime.utcnow()
+ recs[2].is_archived = True
+ db.session.add_all(recs)
+ db.session.commit()
+ db.session.add_all([
+ ProcessingJob(user_id=world["admin"], recording_id=recs[0].id, job_type="transcribe", status="queued"),
+ ProcessingJob(user_id=world["admin"], recording_id=recs[1].id, job_type="summarize", status="processing"),
+ ProcessingJob(user_id=world["admin"], recording_id=recs[2].id, job_type="transcribe", status="failed",
+ completed_at=datetime.utcnow()),
+ ])
+ db.session.commit()
+ after = _client(world["admin"]).get("/admin/stats").get_json()
+ assert "total_queries" not in after
+ assert after["ai_requests_month"] - before["ai_requests_month"] == 3 # embeddings not counted
+ assert after["transcribing_recordings"] - before["transcribing_recordings"] == 1
+ assert after["summarizing_recordings"] - before["summarizing_recordings"] == 1
+ assert after["audio_removed_recordings"] - before["audio_removed_recordings"] == 1
+ assert after["archived_recordings"] - before["archived_recordings"] == 1
+ assert after["jobs"]["queued"] - before["jobs"]["queued"] == 1
+ assert after["jobs"]["running"] - before["jobs"]["running"] == 1
+ assert after["jobs"]["failed_7d"] - before["jobs"]["failed_7d"] == 1
+
+
[email protected]("url,local", [
+ ("", True), ("http://192.168.68.85:5010/v1", True), ("http://localhost:8080/v1", True),
+ ("http://embed.lan/v1", True), ("https://openrouter.ai/api/v1", False), ("https://api.openai.com/v1", False),
+])
+def test_embeddings_are_local(url, local):
+ from src.services import embeddings as emb
+ with patch.object(emb, "USE_API_EMBEDDINGS", bool(url)), patch.object(emb, "EMBEDDING_BASE_URL", url):
+ assert emb.embeddings_are_local() is local