Skip to content

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

Python

Header: storage meter beside the token budget when a quota applies (#413)

Murtaza Nasir65267cfe1f1a
diff --git a/src/api/system.py b/src/api/system.py
index 473fe674..8e600087 100644
--- a/src/api/system.py
+++ b/src/api/system.py
@@ -86,12 +86,33 @@ def save_user_preferences():
})
+def _storage_meter(user):
+ """Storage against the quota; has_quota is False without one."""
+ try:
+ from src.services.storage_quota import usage
+ u = usage(user)
+ except Exception as e:
+ current_app.logger.warning(f"Could not read storage usage for user {user.id}: {e}")
+ return {'has_quota': False}
+
+ def label(n):
+ return f"{n / 1073741824:.1f} GB" if n >= 1073741824 else f"{n / 1048576:.1f} MB"
+
+ if not u['quota_bytes']:
+ return {'has_quota': False, 'used_bytes': u['used_bytes']}
+ return {'has_quota': True, 'used_bytes': u['used_bytes'], 'quota_bytes': u['quota_bytes'],
+ 'percentage': u['percentage'], 'used_label': label(u['used_bytes']),
+ 'quota_label': label(u['quota_bytes'])}
+
+
@system_bp.route('/api/user/token-budget', methods=['GET'])
@login_required
def get_user_token_budget():
- """Get current user's token budget status."""
+ """Get current user's token budget status, and storage against the
+ quota for the header meters (#413)."""
try:
user = current_user
+ storage = _storage_meter(user)
# If user has no budget, return null to indicate unlimited
if not user.monthly_token_budget:
@@ -99,7 +120,8 @@ def get_user_token_budget():
'has_budget': False,
'budget': None,
'usage': 0,
- 'percentage': 0
+ 'percentage': 0,
+ 'storage': storage,
})
# Get current usage
@@ -110,7 +132,8 @@ def get_user_token_budget():
'has_budget': True,
'budget': user.monthly_token_budget,
'usage': current_usage,
- 'percentage': round(percentage, 1)
+ 'percentage': round(percentage, 1),
+ 'storage': storage,
})
except Exception as e:
current_app.logger.error(f"Error getting token budget for user {current_user.id}: {e}")
diff --git a/static/locales/de.json b/static/locales/de.json
index e433fbb3..2f99c309 100644
--- a/static/locales/de.json
+++ b/static/locales/de.json
@@ -2295,5 +2295,9 @@
"guidance": "Löschen Sie Aufnahmen oder entfernen Sie deren Audio, oder bitten Sie einen Administrator um ein größeres Kontingent.",
"uploadRefused": "Diese Datei passt nicht in Ihren Speicher: {{used}} von {{quota}} belegt, die Datei hat {{file}}.",
"recordingBlocked": "Ihr Speicher ist voll ({{used}} von {{quota}}). Löschen Sie Aufnahmen oder entfernen Sie deren Audio, bevor Sie erneut aufnehmen."
+ },
+ "usageMeters": {
+ "tokenTooltip": "KI-Tokens diesen Monat: {{used}} von {{budget}}",
+ "storageTooltip": "Speicher: {{used}} von {{quota}}"
}
}
diff --git a/static/locales/en.json b/static/locales/en.json
index a955e97e..1a07166a 100644
--- a/static/locales/en.json
+++ b/static/locales/en.json
@@ -2295,5 +2295,9 @@
"guidance": "Delete recordings or remove their audio, or ask an administrator for a larger quota.",
"uploadRefused": "This file does not fit in your storage: {{used}} of {{quota}} used, and the file is {{file}}.",
"recordingBlocked": "Your storage is full ({{used}} of {{quota}}). Delete recordings or remove their audio before recording again."
+ },
+ "usageMeters": {
+ "tokenTooltip": "AI tokens this month: {{used}} of {{budget}}",
+ "storageTooltip": "Storage: {{used}} of {{quota}}"
}
}
diff --git a/static/locales/es.json b/static/locales/es.json
index 316371b3..545a4e6e 100644
--- a/static/locales/es.json
+++ b/static/locales/es.json
@@ -2295,5 +2295,9 @@
"guidance": "Elimine grabaciones o quite su audio, o pida a un administrador una cuota mayor.",
"uploadRefused": "Este archivo no cabe en su almacenamiento: {{used}} de {{quota}} usados, y el archivo ocupa {{file}}.",
"recordingBlocked": "Su almacenamiento está lleno ({{used}} de {{quota}}). Elimine grabaciones o quite su audio antes de volver a grabar."
+ },
+ "usageMeters": {
+ "tokenTooltip": "Tokens de IA este mes: {{used}} de {{budget}}",
+ "storageTooltip": "Almacenamiento: {{used}} de {{quota}}"
}
}
diff --git a/static/locales/fr.json b/static/locales/fr.json
index cad4f665..73c71eec 100644
--- a/static/locales/fr.json
+++ b/static/locales/fr.json
@@ -2295,5 +2295,9 @@
"guidance": "Supprimez des enregistrements ou leur audio, ou demandez un quota plus grand à un administrateur.",
"uploadRefused": "Ce fichier ne tient pas dans votre stockage : {{used}} sur {{quota}} utilisés, et le fichier fait {{file}}.",
"recordingBlocked": "Votre stockage est plein ({{used}} sur {{quota}}). Supprimez des enregistrements ou leur audio avant d'enregistrer à nouveau."
+ },
+ "usageMeters": {
+ "tokenTooltip": "Tokens IA ce mois-ci : {{used}} sur {{budget}}",
+ "storageTooltip": "Stockage : {{used}} sur {{quota}}"
}
}
diff --git a/static/locales/pt-BR.json b/static/locales/pt-BR.json
index e85defc4..5546d5e5 100644
--- a/static/locales/pt-BR.json
+++ b/static/locales/pt-BR.json
@@ -2295,5 +2295,9 @@
"guidance": "Exclua gravações ou remova o áudio delas, ou peça a um administrador uma cota maior.",
"uploadRefused": "Este arquivo não cabe no seu armazenamento: {{used}} de {{quota}} usados, e o arquivo tem {{file}}.",
"recordingBlocked": "Seu armazenamento está cheio ({{used}} de {{quota}}). Exclua gravações ou remova o áudio delas antes de gravar novamente."
+ },
+ "usageMeters": {
+ "tokenTooltip": "Tokens de IA neste mês: {{used}} de {{budget}}",
+ "storageTooltip": "Armazenamento: {{used}} de {{quota}}"
}
}
diff --git a/static/locales/ru.json b/static/locales/ru.json
index 64b7700f..c36c5fd7 100644
--- a/static/locales/ru.json
+++ b/static/locales/ru.json
@@ -2295,5 +2295,9 @@
"guidance": "Удалите записи или их аудио либо попросите администратора увеличить квоту.",
"uploadRefused": "Файл не помещается в хранилище: использовано {{used}} из {{quota}}, размер файла {{file}}.",
"recordingBlocked": "Хранилище заполнено ({{used}} из {{quota}}). Удалите записи или их аудио, прежде чем записывать снова."
+ },
+ "usageMeters": {
+ "tokenTooltip": "Токены ИИ за месяц: {{used}} из {{budget}}",
+ "storageTooltip": "Хранилище: {{used}} из {{quota}}"
}
}
diff --git a/static/locales/zh.json b/static/locales/zh.json
index 06af537d..15ed4f07 100644
--- a/static/locales/zh.json
+++ b/static/locales/zh.json
@@ -2295,5 +2295,9 @@
"guidance": "请删除录音或删除其音频,或请管理员提高配额。",
"uploadRefused": "此文件超出您的存储空间:已用 {{used}},共 {{quota}},文件大小 {{file}}。",
"recordingBlocked": "您的存储已满(已用 {{used}},共 {{quota}})。请先删除录音或删除其音频再录音。"
+ },
+ "usageMeters": {
+ "tokenTooltip": "本月 AI 令牌:{{used}} / {{budget}}",
+ "storageTooltip": "存储:{{used}} / {{quota}}"
}
}
diff --git a/templates/components/token_budget_indicator.html b/templates/components/token_budget_indicator.html
index 88b27f87..8470cdaa 100644
--- a/templates/components/token_budget_indicator.html
+++ b/templates/components/token_budget_indicator.html
@@ -1,17 +1,35 @@
-<!-- Token Budget Indicator Component -->
-<!-- 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="t('adminDashboard.tokenUsage.title') + ': ' + (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>
- <div class="w-12 h-1 bg-[var(--bg-tertiary)] rounded-full overflow-hidden">
- <div class="h-full rounded-full transition-all duration-300 bg-[var(--text-accent)]"
- :style="{
- width: Math.min(tokenBudget.percentage, 100) + '%',
- backgroundColor: tokenBudget.percentage >= 100 ? '#ef4444' : tokenBudget.percentage >= 80 ? '#f59e0b' : null
- }">
+<!-- Header usage meters: the monthly AI token budget and, when a quota
+ applies, storage (#413). Each shows only when its limit is set. -->
+<div v-if="tokenBudget && (tokenBudget.has_budget || (tokenBudget.storage && tokenBudget.storage.has_quota))"
+ class="hidden sm:flex items-center gap-3">
+ <div v-if="tokenBudget.has_budget"
+ class="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="t('usageMeters.tokenTooltip', { used: (tokenBudget.usage || 0).toLocaleString(), budget: (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>
+ <div class="w-12 h-1 bg-[var(--bg-tertiary)] rounded-full overflow-hidden">
+ <div class="h-full rounded-full transition-all duration-300 bg-[var(--text-accent)]"
+ :style="{
+ width: Math.min(tokenBudget.percentage, 100) + '%',
+ backgroundColor: tokenBudget.percentage >= 100 ? '#ef4444' : tokenBudget.percentage >= 80 ? '#f59e0b' : null
+ }">
+ </div>
</div>
</div>
+ <a v-if="tokenBudget.storage && tokenBudget.storage.has_quota" href="/account"
+ class="flex items-center gap-1.5 px-2 py-1 rounded text-xs text-[var(--text-muted)] hover:text-[var(--text-secondary)] transition-colors"
+ :title="t('usageMeters.storageTooltip', { used: tokenBudget.storage.used_label, quota: tokenBudget.storage.quota_label })">
+ <i class="fas fa-hdd text-[10px]"
+ :style="tokenBudget.storage.percentage >= 100 ? {color: '#ef4444'} : tokenBudget.storage.percentage >= 80 ? {color: '#f59e0b'} : {}"></i>
+ <span :style="tokenBudget.storage.percentage >= 100 ? {color: '#ef4444'} : tokenBudget.storage.percentage >= 80 ? {color: '#f59e0b'} : {}">${ tokenBudget.storage.percentage }%</span>
+ <div class="w-12 h-1 bg-[var(--bg-tertiary)] rounded-full overflow-hidden">
+ <div class="h-full rounded-full transition-all duration-300 bg-[var(--text-accent)]"
+ :style="{
+ width: Math.min(tokenBudget.storage.percentage, 100) + '%',
+ backgroundColor: tokenBudget.storage.percentage >= 100 ? '#ef4444' : tokenBudget.storage.percentage >= 80 ? '#f59e0b' : null
+ }">
+ </div>
+ </div>
+ </a>
</div>
diff --git a/tests/test_storage_quota.py b/tests/test_storage_quota.py
index f60bfa5e..998e54ce 100644
--- a/tests/test_storage_quota.py
+++ b/tests/test_storage_quota.py
@@ -240,3 +240,16 @@ def test_users_see_their_usage(world):
with app.test_client() as c:
me = c.get("/api/v1/users/me", headers={"Authorization": f"Bearer {plain}"}).get_json()
assert me["storage"] == {"used_bytes": 2 * MB, "quota_bytes": 10 * MB, "available_bytes": 8 * MB}
+
+
+def test_the_header_meter_reports_storage_only_with_a_quota(world):
+ u = world["user"](quota_mb=10)
+ world["rec"](u, 9 * MB)
+ client = app.test_client()
+ _login(client, u)
+ storage = client.get("/api/user/token-budget").get_json()["storage"]
+ assert storage["has_quota"] is True and storage["percentage"] == 90.0
+ assert storage["used_label"] == "9.0 MB" and storage["quota_label"] == "10.0 MB"
+ free = world["user"]()
+ _login(client, free)
+ assert client.get("/api/user/token-budget").get_json()["storage"]["has_quota"] is False