Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Format file sizes in the interface language with one shared formatter per side (#481)
Murtaza Nasir8402d1355ba9
diff --git a/docs/user-guide/settings.md b/docs/user-guide/settings.mdindex 06cbaf0d..3da8ed9a 100644--- a/docs/user-guide/settings.md+++ b/docs/user-guide/settings.md@@ -129,7 +129,7 @@ The Preferences tab is the home for display and editor behaviour settings that sThree language settings shape your Speakr experience. The interface language dropdown immediately transforms all menus, buttons, and messages to your chosen language; the transcription language field sets a default ISO 639-1 code that the recognition service uses to optimise accuracy when auto-detect is too slow or ambiguous; and the preferred output language controls the language of titles, summaries, and chat responses regardless of the source audio's language. Leaving the transcription language on **Auto-detect** is the right default for multilingual content.-The interface language also applies to the notices shown after account actions, such as signing in, saving settings or changing a password, and to the email verification and password reset messages. Error messages returned by the API are still in English. Text without a translation for the selected language is shown in English. Dates, times and numbers are formatted for the interface language, independent of the browser language: month and weekday names, the decimal separator and the 12- or 24-hour clock all follow the selected language.+The interface language also applies to the notices shown after account actions, such as signing in, saving settings or changing a password, and to the email verification and password reset messages. Error messages returned by the API are still in English. Text without a translation for the selected language is shown in English. Dates, times, numbers and file sizes are formatted for the interface language, independent of the browser language: month and weekday names, the decimal separator and the 12- or 24-hour clock all follow the selected language. File sizes in exported Markdown follow it as well.These settings used to live on the Account Information tab. They moved here so all preferences that affect your day-to-day Speakr experience live in one place.diff --git a/src/api/auth.py b/src/api/auth.pyindex d5f92914..abfa26ae 100644--- a/src/api/auth.py+++ b/src/api/auth.py@@ -20,7 +20,7 @@ import markdownfrom src.database import dbfrom src.models import User, SystemSetting, GroupMembershipfrom src.utils import password_check, is_safe_url-from src.utils.localization import translate+from src.utils.localization import format_file_size, format_number, translatefrom src.auth.sso import (init_sso_client,is_sso_enabled,@@ -633,9 +633,8 @@ def _storage_usage(user):def _usage_limits(user):"""AI tokens and transcription minutes this month, and storage, each- against its limit when one is set, for the Account page (#413)."""- def size(n):- return f"{n / 1073741824:.1f} GB" if n >= 1073741824 else f"{n / 1048576:.1f} MB"+ against its limit when one is set, for the Account page (#413). The+ numbers are in the interface language's notation (#481)."""def row(key, label_key, icon, used, limit, fmt):pct = round(used / limit * 100, 1) if limit else None@@ -647,7 +646,7 @@ def _usage_limits(user):from src.services.token_tracking import token_trackerrows.append(row('tokens', 'account.aiTokensMonth', 'fa-coins',int(token_tracker.get_monthly_usage(user.id) or 0), user.monthly_token_budget,- lambda n: f"{int(n):,}"))+ lambda n: format_number(int(n))))except Exception as e:current_app.logger.warning(f"Could not read token usage for user {user.id}: {e}")try:@@ -655,12 +654,13 @@ def _usage_limits(user):seconds = int(transcription_tracker.get_monthly_usage(user.id) or 0)budget = user.monthly_transcription_budgetrows.append(row('transcription', 'account.transcriptionMonth', 'fa-microphone',- seconds // 60, (budget // 60) if budget else None, lambda n: f"{int(n):,} min"))+ seconds // 60, (budget // 60) if budget else None,+ lambda n: translate('adminDashboard.statsPage.minutesShort', count=format_number(int(n)))))except Exception as e:current_app.logger.warning(f"Could not read transcription usage for user {user.id}: {e}")storage = _storage_usage(user)if storage:- rows.append(row('storage', 'account.storage', 'fa-hdd', storage['used_bytes'], storage['quota_bytes'], size))+ rows.append(row('storage', 'account.storage', 'fa-hdd', storage['used_bytes'], storage['quota_bytes'], format_file_size))return rowsdiff --git a/src/api/system.py b/src/api/system.pyindex c8d02f9e..a7b76231 100644--- a/src/api/system.py+++ b/src/api/system.py@@ -15,6 +15,7 @@ from src.database import dbfrom src.models import *from src.utils import *from src.config.version import get_version+from src.utils.localization import format_file_sizefrom src.services.llm import TEXT_MODEL_BASE_URL, TEXT_MODEL_NAMEfrom src.config.app_config import ASR_BASE_URL, USE_NEW_TRANSCRIPTION_ARCHITECTURE, TRANSCRIPTION_MODEL_OPTIONSfrom src.services.token_tracking import token_tracker@@ -101,7 +102,8 @@ def save_user_preferences():def _storage_meter(user):- """Storage against the quota; has_quota is False without one."""+ """Storage against the quota; has_quota is False without one. The labels+ are in the interface language's number format (#481)."""try:from src.services.storage_quota import usageu = usage(user)@@ -109,14 +111,11 @@ def _storage_meter(user):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'])}+ 'percentage': u['percentage'], 'used_label': format_file_size(u['used_bytes']),+ 'quota_label': format_file_size(u['quota_bytes'])}@system_bp.route('/api/user/token-budget', methods=['GET'])diff --git a/src/file_exporter.py b/src/file_exporter.pyindex da56278d..e1ad7907 100644--- a/src/file_exporter.py+++ b/src/file_exporter.py@@ -436,18 +436,6 @@ def format_duration(seconds):return f"{secs}s"-def format_file_size(bytes_size):- """Format file size in bytes to human-readable string."""- if not bytes_size:- return ""-- for unit in ['B', 'KB', 'MB', 'GB']:- if bytes_size < 1024:- return f"{bytes_size:.1f} {unit}"- bytes_size /= 1024- return f"{bytes_size:.1f} TB"--def get_user_export_template(user, recording=None):"""Get the export template to use for a recording.@@ -583,7 +571,7 @@ def generate_from_template(recording, user, template_str, labels, user_language,Returns:Rendered markdown string"""- from src.utils.localization import format_date_localized, format_datetime_localized+ from src.utils.localization import format_date_localized, format_datetime_localized, format_file_size# Dates in exported text are the owner's local time (#412).from src.utils.timezones import to_user_localdef _local(dt):@@ -595,7 +583,7 @@ def generate_from_template(recording, user, template_str, labels, user_language,'meeting_date': format_date_localized(_local(recording.meeting_date), user_language) if recording.meeting_date else '','created_at': format_datetime_localized(_local(recording.created_at), user_language) if recording.created_at else '','original_filename': recording.original_filename or '',- 'file_size': format_file_size(recording.file_size) if recording.file_size else '',+ 'file_size': format_file_size(recording.file_size, user_language) if recording.file_size else '','participants': recording.participants or '','tags': ', '.join([tag.name for tag in recording.tags]) if recording.tags else '','transcription_duration': format_duration(recording.transcription_duration_seconds) if recording.transcription_duration_seconds else '',@@ -635,7 +623,7 @@ def generate_default_markdown(recording, user, labels, user_language,Returns:Rendered markdown string"""- from src.utils.localization import format_date_localized, format_datetime_localized+ from src.utils.localization import format_date_localized, format_datetime_localized, format_file_size# Dates in exported text are the owner's local time (#412).from src.utils.timezones import to_user_localdef _local(dt):@@ -664,7 +652,7 @@ def generate_default_markdown(recording, user, labels, user_language,lines.append(f"- **{labels.get('originalFile', 'Original File')}:** {recording.original_filename}")if recording.file_size:- lines.append(f"- **{labels.get('fileSize', 'File Size')}:** {format_file_size(recording.file_size)}")+ lines.append(f"- **{labels.get('fileSize', 'File Size')}:** {format_file_size(recording.file_size, user_language)}")if recording.participants:lines.append(f"- **{labels.get('participants', 'Participants')}:** {recording.participants}")diff --git a/src/utils/localization.py b/src/utils/localization.pyindex cf362dec..15e44837 100644--- a/src/utils/localization.py+++ b/src/utils/localization.py@@ -10,6 +10,7 @@ import jsonimport osimport reimport logging+from decimal import Decimal, ROUND_HALF_UPfrom functools import lru_cachefrom pathlib import Pathfrom typing import Dict, Optional@@ -263,6 +264,11 @@ def request_language() -> str:return request.accept_languages.best_match(available_languages()) or FALLBACK_LANGUAGE+def _resolve_language(language: Optional[str]) -> str:+ """A shipped locale for the given code, else for the current request."""+ return (match_language(language) if language else request_language()) or FALLBACK_LANGUAGE++def _lookup(catalog: dict, key: str) -> Optional[str]:value = catalogfor part in key.split('.'):@@ -284,7 +290,7 @@ def translate(key: str, language: Optional[str] = None, **params) -> str:Returns:The string in that language, else in English, else the key itself."""- language = (match_language(language) if language else request_language()) or FALLBACK_LANGUAGE+ language = _resolve_language(language)text = _lookup(load_locale(language), key)if text is None and language != FALLBACK_LANGUAGE:text = _lookup(load_locale(FALLBACK_LANGUAGE), key)@@ -295,6 +301,43 @@ def translate(key: str, language: Optional[str] = None, **params) -> str:lambda m: str(params[m.group(1)]) if m.group(1) in params else m.group(0), text)+def format_number(value, language: Optional[str] = None, max_fraction_digits: int = 0,+ grouping: bool = True) -> str:+ """+ A number in the interface language's notation, as i18n.formatNumber()+ does in the browser: '1,234.5' in English, '1.234,5' in German (#481).++ Rounds half up to at most max_fraction_digits and drops trailing zeros.+ """+ from babel import Locale+ from babel.numbers import format_decimal+ language = _resolve_language(language)+ rounded = Decimal(value).quantize(Decimal(1).scaleb(-max_fraction_digits), rounding=ROUND_HALF_UP)+ pattern = ('#,##0' if grouping else '0') + ('.' + '#' * max_fraction_digits if max_fraction_digits else '')+ return format_decimal(rounded, format=pattern, locale=Locale.parse(language, sep='-'))+++_FILE_SIZE_UNITS = ('bytes', 'kilobytes', 'megabytes', 'gigabytes', 'terabytes')+++def format_file_size(size, language: Optional[str] = None) -> str:+ """+ A byte count with the fileSize.* units, as i18n.formatFileSize() does in+ the browser: 1024-based, at most one decimal, e.g. '1.5 MB' or '1,5 MB'.+ """+ size = max(Decimal(size or 0), Decimal(0))+ unit = 0+ while unit < len(_FILE_SIZE_UNITS) - 1 and size >= 1024 ** (unit + 1):+ unit += 1+ # 1023.97 KB would round to "1024 KB"; that is 1 MB.+ if unit < len(_FILE_SIZE_UNITS) - 1 and (size / 1024 ** unit).quantize(+ Decimal('0.1'), rounding=ROUND_HALF_UP) >= 1024:+ unit += 1+ # No grouping, as in the browser: German "1.023 B" reads as 1.023.+ count = format_number(size / 1024 ** unit, language, max_fraction_digits=1, grouping=False)+ return translate(f'fileSize.{_FILE_SIZE_UNITS[unit]}', language, count=count)++def clear_locale_cache():"""Clear the locale cache (useful for testing or hot-reloading)."""global _locale_cachediff --git a/static/js/app.modular.js b/static/js/app.modular.jsindex 3f7dbe16..17cb84a2 100644--- a/static/js/app.modular.js+++ b/static/js/app.modular.js@@ -2023,13 +2023,8 @@ document.addEventListener('DOMContentLoaded', async () => {modalAudioIsPlaying.value = false;};- const formatFileSize = (bytes) => {- if (!bytes) return '0 B';- const k = 1024;- const sizes = ['B', 'KB', 'MB', 'GB'];- const i = Math.floor(Math.log(bytes) / Math.log(k));- return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];- };+ // Localized number and units (#481)+ const formatFileSize = (bytes) => window.i18n.formatFileSize(bytes);// Parse a backend INSTANT timestamp. The backend stores/serializes// naive UTC (no zone designator); new Date() would parse a zonelessdiff --git a/static/js/i18n.js b/static/js/i18n.jsindex e18c1d07..95519a01 100644--- a/static/js/i18n.js+++ b/static/js/i18n.js@@ -269,24 +269,22 @@ class I18n {}/**- * Format file size with appropriate unit+ * Format file size with appropriate unit, at most one decimal, in the+ * interface language's number format: "1.5 MB", "1,5 MB" in German (#481).+ * src/utils/localization.py format_file_size() is the server-side twin.* @param {number} bytes - Size in bytes* @returns {string} Formatted file size*/formatFileSize(bytes) {- const units = ['bytes', 'kilobytes', 'megabytes', 'gigabytes'];- const unitValues = [1, 1024, 1048576, 1073741824];-- let unitIndex = 0;- for (let i = unitValues.length - 1; i >= 0; i--) {- if (bytes >= unitValues[i]) {- unitIndex = i;- break;- }- }-- const value = Math.round(bytes / unitValues[unitIndex] * 10) / 10;- return this.t(`fileSize.${units[unitIndex]}`, { count: value });+ const units = ['bytes', 'kilobytes', 'megabytes', 'gigabytes', 'terabytes'];+ const size = Math.max(Number(bytes) || 0, 0);+ let unit = 0;+ while (unit < units.length - 1 && size >= 1024 ** (unit + 1)) unit++;+ // 1023.97 KB would round to "1024 KB"; that is 1 MB.+ if (unit < units.length - 1 && Math.round(size / 1024 ** unit * 10) / 10 >= 1024) unit++;+ // No grouping: below 1 PB the count is under 1024, and German "1.023 B" reads as 1.023.+ const count = this.formatNumber(size / 1024 ** unit, { maximumFractionDigits: 1, useGrouping: false });+ return this.t(`fileSize.${units[unit]}`, { count });}/**diff --git a/static/js/i18n.test.js b/static/js/i18n.test.jsindex 22693e1e..ca42b85e 100644--- a/static/js/i18n.test.js+++ b/static/js/i18n.test.js@@ -144,3 +144,45 @@ describe('interface locale for dates and numbers (#480)', () => {expect(i18n.formatNumber(1234.5)).toBe('1,234.5');});});++describe('file sizes (#481)', () => {+ // The shipped catalogs, so a missing fileSize.* key fails here too.+ const catalog = (code) => JSON.parse(readFileSync(fileURLToPath(new URL(`../locales/${code}.json`, import.meta.url)), 'utf8'));+ const sizes = (code) => {+ const translations = { en: catalog('en') };+ translations[code] = catalog(code);+ return load({ bootstrap: { locale: code, translations } }).i18n;+ };++ it('uses the decimal separator of the interface language', () => {+ expect(sizes('de').formatFileSize(1464812)).toBe('1,4 MB');+ expect(sizes('en').formatFileSize(1464812)).toBe('1.4 MB');+ for (const code of ['es', 'fr', 'pt-BR']) expect(sizes(code).formatFileSize(1464812)).toBe('1,4 MB');+ expect(sizes('zh').formatFileSize(1464812)).toBe('1.4 MB');+ expect(sizes('ru').formatFileSize(1464812)).toBe('1,4 МБ');+ });++ it('keeps zero, whole units and the unit boundaries', () => {+ const de = sizes('de');+ expect(de.formatFileSize(0)).toBe('0 B');+ expect(de.formatFileSize(1023)).toBe('1023 B');+ expect(de.formatFileSize(1024)).toBe('1 KB');+ expect(de.formatFileSize(1536000)).toBe('1,5 MB');+ expect(de.formatFileSize(1024 ** 3)).toBe('1 GB');+ expect(de.formatFileSize(2.5 * 1024 ** 4)).toBe('2,5 TB');+ expect(de.formatFileSize(1024 ** 5)).toBe('1024 TB');+ });++ it('rounds to one decimal and moves up a unit when the rounding reaches 1024', () => {+ const en = sizes('en');+ expect(en.formatFileSize(1530000)).toBe('1.5 MB'); // 1.459 MB+ expect(en.formatFileSize(9 * 1024 ** 2)).toBe('9 MB');+ expect(en.formatFileSize(1024 ** 2 - 1)).toBe('1 MB'); // 1023.999 KB+ expect(en.formatFileSize(1024 ** 3 - 1024)).toBe('1 GB'); // 1023.999 MB+ });++ it('reads a missing or invalid size as zero', () => {+ const en = sizes('en');+ for (const value of [null, undefined, NaN, 'x', -5]) expect(en.formatFileSize(value)).toBe('0 B');+ });+});diff --git a/static/js/modules/composables/ui.js b/static/js/modules/composables/ui.jsindex 34a1f1b0..f4d4e628 100644--- a/static/js/modules/composables/ui.js+++ b/static/js/modules/composables/ui.js@@ -317,14 +317,8 @@ export function useUI(state, utils, processedTranscription) {}};- // Format file size- const formatFileSize = (bytes) => {- if (!bytes) return '0 B';- const k = 1024;- const sizes = ['B', 'KB', 'MB', 'GB'];- const i = Math.floor(Math.log(bytes) / Math.log(k));- return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];- };+ // Format file size: localized number and units (#481)+ const formatFileSize = (bytes) => window.i18n.formatFileSize(bytes);// Format statusconst formatStatus = (status) => {diff --git a/static/js/utils/audioUtils.js b/static/js/utils/audioUtils.jsindex ce613c2f..51675596 100644--- a/static/js/utils/audioUtils.js+++ b/static/js/utils/audioUtils.js@@ -2,14 +2,6 @@* Audio processing and visualization utilities*/-export function formatFileSize(bytes) {- if (bytes === 0) return '0 Bytes';- const k = 1024;- const sizes = ['Bytes', 'KB', 'MB', 'GB'];- const i = Math.floor(Math.log(bytes) / Math.log(k));- return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i];-}-export function createAudioVisualizer(canvas, stream, color = '#3b82f6') {if (!canvas || !stream) return null;diff --git a/static/locales/de.json b/static/locales/de.jsonindex 5e475371..d3ca49dc 100644--- a/static/locales/de.json+++ b/static/locales/de.json@@ -1031,7 +1031,8 @@"bytes": "{{count}} B","gigabytes": "{{count}} GB","kilobytes": "{{count}} KB",- "megabytes": "{{count}} MB"+ "megabytes": "{{count}} MB",+ "terabytes": "{{count}} TB"},"floatingChat": {"dockLeft": "Links andocken",diff --git a/static/locales/en.json b/static/locales/en.jsonindex 6e48872d..f425467a 100644--- a/static/locales/en.json+++ b/static/locales/en.json@@ -1031,7 +1031,8 @@"bytes": "{{count}} B","gigabytes": "{{count}} GB","kilobytes": "{{count}} KB",- "megabytes": "{{count}} MB"+ "megabytes": "{{count}} MB",+ "terabytes": "{{count}} TB"},"floatingChat": {"dockLeft": "Dock left",diff --git a/static/locales/es.json b/static/locales/es.jsonindex 0f148ea8..2a940aeb 100644--- a/static/locales/es.json+++ b/static/locales/es.json@@ -1031,7 +1031,8 @@"bytes": "{{count}} B","gigabytes": "{{count}} GB","kilobytes": "{{count}} KB",- "megabytes": "{{count}} MB"+ "megabytes": "{{count}} MB",+ "terabytes": "{{count}} TB"},"floatingChat": {"dockLeft": "Anclar a la izquierda",diff --git a/static/locales/fr.json b/static/locales/fr.jsonindex 4dcb16a1..2d12b9d9 100644--- a/static/locales/fr.json+++ b/static/locales/fr.json@@ -1031,7 +1031,8 @@"bytes": "{{count}} B","gigabytes": "{{count}} GB","kilobytes": "{{count}} KB",- "megabytes": "{{count}} MB"+ "megabytes": "{{count}} MB",+ "terabytes": "{{count}} TB"},"floatingChat": {"dockLeft": "Ancrer à gauche",diff --git a/static/locales/pt-BR.json b/static/locales/pt-BR.jsonindex 42817ad6..44c41292 100644--- a/static/locales/pt-BR.json+++ b/static/locales/pt-BR.json@@ -1031,7 +1031,8 @@"bytes": "{{count}} B","gigabytes": "{{count}} GB","kilobytes": "{{count}} KB",- "megabytes": "{{count}} MB"+ "megabytes": "{{count}} MB",+ "terabytes": "{{count}} TB"},"floatingChat": {"dockLeft": "Ancorar à esquerda",diff --git a/static/locales/ru.json b/static/locales/ru.jsonindex e542364d..50ca7baa 100644--- a/static/locales/ru.json+++ b/static/locales/ru.json@@ -1031,7 +1031,8 @@"bytes": "{{count}} Б","gigabytes": "{{count}} ГБ","kilobytes": "{{count}} КБ",- "megabytes": "{{count}} МБ"+ "megabytes": "{{count}} МБ",+ "terabytes": "{{count}} ТБ"},"floatingChat": {"dockLeft": "Закрепить слева",diff --git a/static/locales/zh.json b/static/locales/zh.jsonindex 7ae01a9c..fb0b52ec 100644--- a/static/locales/zh.json+++ b/static/locales/zh.json@@ -1031,7 +1031,8 @@"bytes": "{{count}} B","gigabytes": "{{count}} GB","kilobytes": "{{count}} KB",- "megabytes": "{{count}} MB"+ "megabytes": "{{count}} MB",+ "terabytes": "{{count}} TB"},"floatingChat": {"dockLeft": "停靠左侧",diff --git a/templates/admin.html b/templates/admin.htmlindex 897da596..a1bb3db7 100644--- a/templates/admin.html+++ b/templates/admin.html@@ -3497,15 +3497,8 @@ Summarization Instructions:}};- const formatFileSize = (bytes) => {- if (!bytes || bytes === 0) return '0 Bytes';-- const k = 1024;- const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];- const i = Math.floor(Math.log(bytes) / Math.log(k));-- return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];- };+ // Localized number and units (#481)+ const formatFileSize = (bytes) => window.i18n.formatFileSize(bytes);const toggleDarkMode = () => {isDarkMode.value = !isDarkMode.value;diff --git a/templates/group-admin.html b/templates/group-admin.htmlindex 6278adfd..424f6193 100644--- a/templates/group-admin.html+++ b/templates/group-admin.html@@ -1471,15 +1471,8 @@}};- const formatFileSize = (bytes) => {- if (!bytes || bytes === 0) return '0 Bytes';-- const k = 1024;- const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];- const i = Math.floor(Math.log(bytes) / Math.log(k));-- return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];- };+ // Localized number and units (#481)+ const formatFileSize = (bytes) => window.i18n.formatFileSize(bytes);const toggleDarkMode = () => {isDarkMode.value = !isDarkMode.value;diff --git a/tests/test_localization.py b/tests/test_localization.pyindex 96a44a24..ff79a9a6 100644--- a/tests/test_localization.py+++ b/tests/test_localization.py@@ -282,3 +282,69 @@ def test_locale_scanner_allows_a_resolved_locale(call):"""The guard targets the opt-out, not every call: an explicit locale, timezone detection and unrelated locale methods pass."""assert not LOCALE_OPT_OUT.search(call), call+++# File sizes have one formatter per side (#481): i18n.formatFileSize() in the+# browser and format_file_size() in src/utils/localization.py, both with the+# fileSize.* units. A local copy with its own unit list ('B', 'KB', ...) is how+# the dot decimal and "0 Bytes" came back on five pages.+LOCAL_SIZE_UNITS = re.compile(r"""\[\s*['"](?:B|Bytes)['"]\s*,\s*['"]KB['"]""")+SIZE_FORMATTER_OWNERS = {'static/js/i18n.js', 'src/utils/localization.py'}+++def _local_size_formatters():+ found = []+ paths = (list(_walk('static/js', '.js', skip=('.test.js',))) + list(_walk('templates', '.html'))+ + list(_walk('src', '.py')))+ for path in paths:+ rel = os.path.relpath(path, REPO)+ if rel in SIZE_FORMATTER_OWNERS:+ continue+ text = open(path, encoding='utf-8').read()+ for m in LOCAL_SIZE_UNITS.finditer(text):+ found.append(f'{rel}:{text.count(chr(10), 0, m.start()) + 1}')+ return found+++# The API's own byte labels (used_human in /api/v1) stay English on purpose:+# API clients parse them, and they do not render in the interface.+API_SIZE_FORMATTERS = {'src/api/api_v1.py'}+++def test_no_local_file_size_formatter():+ offenders = [o for o in _local_size_formatters() if o.split(':')[0] not in API_SIZE_FORMATTERS]+ assert not offenders, (+ 'file sizes formatted outside i18n.formatFileSize / format_file_size:\n'+ + '\n'.join(f' {o}' for o in offenders))++[email protected]('snippet,matches', [+ ("const sizes = ['B', 'KB', 'MB', 'GB'];", True),+ ('const sizes = ["Bytes", "KB", "MB", "GB", "TB"];', True),+ ("for unit in ['B', 'KB', 'MB', 'GB']:", True),+ ("const units = ['bytes', 'kilobytes', 'megabytes'];", False),+ ("t('fileSize.kilobytes')", False),+])+def test_size_formatter_scanner(snippet, matches):+ """Same guard against a regex that silently matches nothing."""+ assert bool(LOCAL_SIZE_UNITS.search(snippet)) is matches++[email protected]('path', [+ 'static/js/app.modular.js',+ 'static/js/modules/composables/ui.js',+ 'templates/admin.html',+ 'templates/group-admin.html',+])+def test_file_size_call_sites_delegate_to_i18n(path):+ """Positive control: removing a copy must not leave the page without one."""+ text = open(os.path.join(REPO, path), encoding='utf-8').read()+ assert 'window.i18n.formatFileSize(' in text, path+++def test_every_locale_has_every_file_size_unit():+ units = {'bytes', 'kilobytes', 'megabytes', 'gigabytes', 'terabytes'}+ for lang in _languages():+ table = _load(lang).get('fileSize', {})+ assert set(table) == units, f'{lang}.json fileSize has {sorted(table)}'+ assert all('{{count}}' in v for v in table.values()), f'{lang}.json fileSize lacks {{{{count}}}}'diff --git a/tests/test_server_i18n.py b/tests/test_server_i18n.pyindex d72a8cb9..24c11557 100644--- a/tests/test_server_i18n.py+++ b/tests/test_server_i18n.py@@ -16,7 +16,9 @@ import pytestfrom src.app import app, dbfrom src.models import Userfrom src.services import email as email_service-from src.utils.localization import match_language, request_language, translate+from src.utils.localization import (+ format_file_size, format_number, match_language, request_language, translate,+)# ---------------------------------------------------------------------------@@ -65,6 +67,43 @@ def test_match_language_maps_region_codes(code, expected):assert match_language(code) == expected+# ---------------------------------------------------------------------------+# format_number() / format_file_size(): the browser's i18n.formatNumber and+# i18n.formatFileSize on the server (#481), same cases as static/js/i18n.test.js+# ---------------------------------------------------------------------------+[email protected]('lang,expected', [+ ('en', '1.4 MB'), ('zh', '1.4 MB'), ('de', '1,4 MB'), ('es', '1,4 MB'),+ ('fr', '1,4 MB'), ('pt-BR', '1,4 MB'), ('ru', '1,4 МБ'),+])+def test_file_size_uses_the_languages_decimal_separator(lang, expected):+ assert format_file_size(1464812, lang) == expected++[email protected]('size,expected', [+ (0, '0 B'), (None, '0 B'), (-5, '0 B'), (1023, '1023 B'), (1024, '1 KB'),+ (1536000, '1,5 MB'), (9 * 1024 ** 2, '9 MB'), (1024 ** 2 - 1, '1 MB'),+ (1024 ** 3 - 1024, '1 GB'), (1024 ** 3, '1 GB'), (int(2.5 * 1024 ** 4), '2,5 TB'),+ (1024 ** 5, '1024 TB'),+])+def test_file_size_units_and_rounding(size, expected):+ assert format_file_size(size, 'de') == expected+++def test_format_number_groups_and_rounds_in_the_language():+ assert format_number(1234567, 'en') == '1,234,567'+ assert format_number(1234567, 'de') == '1.234.567'+ assert format_number(1234.25, 'de', max_fraction_digits=1) == '1.234,3' # half up+ assert format_number(9.0, 'en', max_fraction_digits=1) == '9'+ assert format_number(1234, 'xx') == '1,234' # unknown language: English+++def test_format_number_uses_the_request_language_by_default():+ with app.test_request_context('/', headers={'Accept-Language': 'de'}):+ assert format_number(1234.5, max_fraction_digits=1) == '1.234,5'+ assert format_file_size(1536000) == '1,5 MB'++def test_outside_a_request_the_language_is_english():assert request_language() == 'en'assert translate('server.flash.userNotFound') == 'User not found.'diff --git a/tests/test_storage_quota.py b/tests/test_storage_quota.pyindex 998e54ce..90109e97 100644--- a/tests/test_storage_quota.py+++ b/tests/test_storage_quota.py@@ -249,7 +249,22 @@ def test_the_header_meter_reports_storage_only_with_a_quota(world):_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"+ assert storage["used_label"] == "9 MB" and storage["quota_label"] == "10 MB"free = world["user"]()_login(client, free)assert client.get("/api/user/token-budget").get_json()["storage"]["has_quota"] is False+++def test_storage_figures_follow_the_interface_language(world):+ """The header meter and the Account page format sizes for the user's+ interface language (#481): a decimal comma in German."""+ u = world["user"](quota_mb=10)+ u.ui_language = "de"+ db.session.commit()+ world["rec"](u, int(1.5 * MB))+ client = app.test_client()+ _login(client, u)+ storage = client.get("/api/user/token-budget").get_json()["storage"]+ assert storage["used_label"] == "1,5 MB" and storage["quota_label"] == "10 MB"+ page = client.get("/account").get_data(as_text=True)+ assert '"used": "1,5 MB", "quota": "10 MB"' in page