Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Per-user timezone for generated titles (#412): naming-template dates, the template preview and default titles use the owner's zone (browser-detected in auto mode, chosen in Account settings in fixed mode), else the admin default (seeded from the legacy TIMEZONE variable), else UTC as before; stored data and API stay UTC
Murtaza Nasird75fb07e365a
diff --git a/requirements.txt b/requirements.txtindex f3c2a69b..91645be3 100644--- a/requirements.txt+++ b/requirements.txt@@ -23,6 +23,8 @@ gunicorn==21.2.0python-dotenv==1.0.0markdown==3.5.1pytz==2024.1+# IANA timezone data for zoneinfo when the OS has none (#412)+tzdata==2025.2Babel==2.12.1bleach==6.1.0python-docx==1.1.0diff --git a/src/api/admin.py b/src/api/admin.pyindex 55defc95..48abb36c 100644--- a/src/api/admin.py+++ b/src/api/admin.py@@ -849,6 +849,11 @@ def admin_update_setting():if value not in ['true', 'false', '1', '0', 'yes', 'no', True, False, 1, 0]:return jsonify({'error': 'Value must be a valid boolean (true/false, 1/0, yes/no)'}), 400+ if key == 'default_timezone':+ from src.utils.timezones import is_valid_timezone+ if not is_valid_timezone(value):+ return jsonify({'error': 'Value must be a valid IANA timezone, for example Europe/Berlin'}), 400+try:setting = SystemSetting.set_setting(key, value, description, setting_type)diff --git a/src/api/auth.py b/src/api/auth.pyindex 12c1b220..db0f9344 100644--- a/src/api/auth.py+++ b/src/api/auth.py@@ -160,6 +160,24 @@ def _email_notifications_available(user) -> bool:# --- Routes ---+@auth_bp.route('/api/user/timezone', methods=['POST'])+@login_required+def record_timezone():+ """Save the browser's timezone for a user in 'auto' mode (#412).++ Sent by static/js/timezone-sync.js once per browser session. A user who+ chose a zone in Account settings keeps it.+ """+ from src.utils.timezones import record_browser_timezone, user_timezone, MODE_AUTO+ data = request.get_json(silent=True) or {}+ if record_browser_timezone(current_user, data.get('timezone')):+ db.session.commit()+ return jsonify({+ 'timezone': user_timezone(current_user),+ 'mode': current_user.timezone_mode or MODE_AUTO,+ })++@auth_bp.route('/register', methods=['GET', 'POST'])@rate_limit("10 per minute")def register():@@ -646,6 +664,22 @@ def account():current_user.transcription_language = normalize_language_code(transcription_lang)current_user.output_language = output_lang if output_lang else None+ # Timezone for generated titles (#412). Gated on the field being+ # present so tabs that submit 'preferences_form' without it leave the+ # setting alone. 'auto' keeps the detected zone and resumes updating+ # it from the browser; a zone name fixes it.+ if 'timezone' in request.form:+ from src.utils.timezones import is_valid_timezone, MODE_AUTO, MODE_FIXED+ tz_value = (request.form.get('timezone') or '').strip()+ if tz_value == MODE_AUTO or not tz_value:+ current_user.timezone_mode = MODE_AUTO+ detected = (request.form.get('detected_timezone') or '').strip()+ if is_valid_timezone(detected):+ current_user.timezone = detected+ elif is_valid_timezone(tz_value):+ current_user.timezone_mode = MODE_FIXED+ current_user.timezone = tz_value+# Filename date parsing (#342). Gated on the select being present# so other tabs that submit 'preferences_form' without this# section cannot clobber the settings (same reasoning asdiff --git a/src/api/naming_templates.py b/src/api/naming_templates.pyindex beab49de..88e2f3c4 100644--- a/src/api/naming_templates.py+++ b/src/api/naming_templates.py@@ -275,8 +275,14 @@ def test_naming_template(template_id):except ValueError:pass+ # A sample date is a wall-clock time and is used as given (an aware value+ # is converted to the user's zone); the default is "now" in the user's+ # local time, as the title would show it (#412).+ from src.utils.timezones import to_user_local, user_timezone, now_local+ if meeting_date is not None and meeting_date.tzinfo is not None:+ meeting_date = to_user_local(meeting_date, current_user)if not meeting_date:- meeting_date = datetime.now()+ meeting_date = now_local(user_timezone(current_user))# Apply templateresult = template.apply(diff --git a/src/api/recording_sessions.py b/src/api/recording_sessions.pyindex fb76dd19..91b40588 100644--- a/src/api/recording_sessions.py+++ b/src/api/recording_sessions.py@@ -62,7 +62,7 @@ from flask_login import login_required, current_userfrom werkzeug.datastructures import FileStoragefrom src.database import db-from src.models import RecordingSession, Recording, RECORDING_SESSION_STATUSES+from src.models import RecordingSession, Recording, User, RECORDING_SESSION_STATUSESfrom src.services.job_queue import job_queuefrom src.services.recording_stitch import byte_join, session_chunk_paths@@ -586,7 +586,9 @@ def finalize_session(session_id):# Create a placeholder Recording row. The stitch worker will fill in# audio_path and file_size after concat completes.- title = (metadata.get('title') or f"Recording {datetime.utcnow().strftime('%Y-%m-%d %H:%M')}").strip() or "Recording"+ from src.utils.timezones import now_local, user_timezone+ _local_now = now_local(user_timezone(current_user))+ title = (metadata.get('title') or f"Recording {_local_now.strftime('%Y-%m-%d %H:%M')}").strip() or "Recording"notes = metadata.get('notes') or Nonefolder_id = metadata.get('folder_id')if folder_id in ('', 'none', 'null'):@@ -907,7 +909,9 @@ def cleanup_expired_sessions(app=None):for s in candidates:try:if s.status == 'recording' and (s.chunk_count or 0) > 0 and not s.is_sliced_upload:- when = s.created_at.strftime('%Y-%m-%d %H:%M') if s.created_at else ''+ from src.utils.timezones import to_user_local+ _owner = db.session.get(User, s.user_id)+ when = to_user_local(s.created_at, _owner).strftime('%Y-%m-%d %H:%M') if s.created_at else ''title = f"Recovered recording {when}".strip()recovered_rec, _enq_err = _finalize_session_into_stitch(s, user_id=s.user_id, title=title,diff --git a/src/api/recordings.py b/src/api/recordings.pyindex 69b02fcd..0e27d6d9 100644--- a/src/api/recordings.py+++ b/src/api/recordings.py@@ -2804,6 +2804,14 @@ def ingest_uploaded_recording(# local time to reach UTC). Used to convert filename wall-clock dates# to the naive-UTC storage convention.client_tz_offset = form.get('client_tz_offset')+ # The browser's IANA zone (#412): saved for an uploader in 'auto' mode so+ # the title of this very recording already uses it. Only for the+ # uploader's own recordings, never for an owner uploaded on behalf of.+ client_timezone = form.get('client_timezone')+ if client_timezone and current_user.is_authenticated and owner.id == current_user.id:+ from src.utils.timezones import record_browser_timezone+ if record_browser_timezone(owner, client_timezone):+ db.session.commit()# Get selected tags if provided (multiple tags support)selected_tags = []diff --git a/src/init_db.py b/src/init_db.pyindex f527fad8..c0408c03 100644--- a/src/init_db.py+++ b/src/init_db.py@@ -193,6 +193,11 @@ def _run_migrations(app, engine):app.logger.info("Added extract_events column to user table")if add_column_if_not_exists(engine, 'user', 'output_language', 'VARCHAR(50)'):app.logger.info("Added output_language column to user table")+ # Per-user timezone for generated text (#412)+ if add_column_if_not_exists(engine, 'user', 'timezone', 'VARCHAR(64)'):+ app.logger.info("Added timezone column to user table")+ if add_column_if_not_exists(engine, 'user', 'timezone_mode', "VARCHAR(8) DEFAULT 'auto'"):+ app.logger.info("Added timezone_mode column to user table")if add_column_if_not_exists(engine, 'user', 'summary_prompt', 'TEXT'):app.logger.info("Added summary_prompt column to user table")if add_column_if_not_exists(engine, 'user', 'name', 'VARCHAR(100)'):@@ -928,6 +933,19 @@ def _run_migrations(app, engine):)app.logger.info("Initialized enable_folders setting")+ if not SystemSetting.query.filter_by(key='default_timezone').first():+ # Seeded from the legacy TIMEZONE variable (removed in v0.9.0, still in+ # some setups, e.g. the Unraid template) so its intent carries over.+ from src.utils.timezones import is_valid_timezone+ legacy_tz = (os.environ.get('TIMEZONE') or '').strip()+ SystemSetting.set_setting(+ key='default_timezone',+ value=legacy_tz if is_valid_timezone(legacy_tz) else 'UTC',+ description='Timezone for dates in generated titles (naming templates, default titles) for users whose browser has not reported one and who have not chosen one in Account settings.',+ setting_type='string'+ )+ app.logger.info("Initialized default_timezone setting")+with _migration_section(app, failures, "embedding identifier tracking"):# Track the embedding identifier (provider + model) in system_setting# so we can warn when either changes between restarts. Issue #262 —diff --git a/src/models/user.py b/src/models/user.pyindex 3c2a5d1e..39c7d930 100644--- a/src/models/user.py+++ b/src/models/user.py@@ -25,6 +25,11 @@ class User(db.Model, UserMixin):recordings = db.relationship('Recording', backref='owner', lazy=True)transcription_language = db.Column(db.String(10), nullable=True) # For ISO 639-1 codesoutput_language = db.Column(db.String(50), nullable=True) # For full language names like "Spanish"+ # IANA timezone for text the server writes (titles from naming templates) (#412).+ # timezone_mode 'auto': the browser's zone is saved as the user visits;+ # 'fixed': chosen in Account settings. See src/utils/timezones.py.+ timezone = db.Column(db.String(64), nullable=True)+ timezone_mode = db.Column(db.String(8), nullable=True, default='auto')ui_language = db.Column(db.String(10), nullable=True, default='en') # For UI language preference (en, es, fr, zh)summary_prompt = db.Column(db.Text, nullable=True)title_prompt = db.Column(db.Text, nullable=True) # Instructions for AI titles (#400)diff --git a/src/services/titling.py b/src/services/titling.pyindex 096529c3..f3685737 100644--- a/src/services/titling.py+++ b/src/services/titling.py@@ -80,9 +80,11 @@ def compute_title(recording, *, raise_budget_errors=False):title = Noneif template:+ # Dates in the title are written in the owner's local time (#412).+ from src.utils.timezones import to_user_localtitle = template.apply(original_filename=recording.original_filename,- meeting_date=recording.meeting_date,+ meeting_date=to_user_local(recording.meeting_date, recording.owner),ai_title=ai_title,)if not title:diff --git a/src/utils/timezones.py b/src/utils/timezones.pynew file mode 100644index 00000000..bccad26f--- /dev/null+++ b/src/utils/timezones.py@@ -0,0 +1,84 @@+"""Timezones for text the server writes (#412).++Datetimes are stored as naive UTC and the browser converts them for display;+nothing here changes that. Text the server generates itself (titles from naming+templates, default titles) is written in the owner's local time:++1. The user's timezone (an IANA name such as "Europe/Istanbul"). In 'auto'+ mode the browser's zone is saved as the user visits; in 'fixed' mode the+ user picked one in Account settings.+2. Otherwise the admin default timezone (System Settings, seeded from the+ legacy TIMEZONE variable when it is set).+3. Otherwise UTC, which is what all generated text used before #412.++The container's own TZ never matters: conversions use zoneinfo explicitly.+"""++from datetime import datetime, timezone+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError++DEFAULT_SETTING_KEY = 'default_timezone'+MODE_AUTO = 'auto'+MODE_FIXED = 'fixed'+++def is_valid_timezone(name):+ """True for a known IANA zone name."""+ if not name or not isinstance(name, str) or len(name) > 64:+ return False+ try:+ ZoneInfo(name)+ return True+ except (ZoneInfoNotFoundError, ValueError):+ return False+++def deployment_timezone():+ """The admin default timezone, or UTC."""+ from src.models import SystemSetting+ name = SystemSetting.get_setting(DEFAULT_SETTING_KEY, 'UTC')+ return name if is_valid_timezone(name) else 'UTC'+++def user_timezone(user):+ """The zone name used for a user's generated text."""+ name = getattr(user, 'timezone', None) if user is not None else None+ return name if is_valid_timezone(name) else deployment_timezone()+++def to_local(dt, zone_name):+ """A stored naive-UTC datetime as naive wall-clock time in zone_name.++ Aware datetimes are converted from their own zone. None passes through.+ """+ if dt is None:+ return None+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=timezone.utc)+ return dt.astimezone(ZoneInfo(zone_name)).replace(tzinfo=None)+++def to_user_local(dt, user):+ """A stored naive-UTC datetime in the user's local wall-clock time."""+ return to_local(dt, user_timezone(user))+++def now_local(zone_name):+ """The current wall-clock time in zone_name (naive)."""+ return to_local(datetime.utcnow(), zone_name)+++def record_browser_timezone(user, name):+ """Save the browser's zone for a user in auto mode. Returns True if it changed.++ Fixed-mode users keep their chosen zone; invalid names are ignored. The+ caller commits.+ """+ if user is None or not is_valid_timezone(name):+ return False+ if (getattr(user, 'timezone_mode', None) or MODE_AUTO) != MODE_AUTO:+ return False+ if user.timezone == name:+ return False+ user.timezone = name+ return Truediff --git a/static/js/modules/composables/upload.js b/static/js/modules/composables/upload.jsindex 54c0a1b8..4fa19ddf 100644--- a/static/js/modules/composables/upload.js+++ b/static/js/modules/composables/upload.js@@ -583,6 +583,13 @@ export function useUpload(state, utils) {formData.append('client_tz_offset', new Date().getTimezoneOffset().toString());}+ // The browser's IANA zone, so the title of this recording already+ // uses the uploader's local time (#412).+ try {+ const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;+ if (zone) formData.append('client_timezone', zone);+ } catch (e) { /* older browser: the account or admin default applies */ }+if (fileItem.notes) {formData.append('notes', fileItem.notes);}diff --git a/static/js/timezone-sync.js b/static/js/timezone-sync.jsnew file mode 100644index 00000000..3ff90a8a--- /dev/null+++ b/static/js/timezone-sync.js@@ -0,0 +1,34 @@+// Report this browser's timezone for titles the server writes (#412).+//+// Dates on pages are converted in the browser and do not need this. Titles+// from naming templates are written by the server, often with no browser+// involved, so the server keeps each user's zone. In 'auto' mode (the+// default) the zone reported here is saved; a zone chosen in Account settings+// is kept. Sent once per browser session, or again when the zone changes.+(function () {+ var zone;+ try {+ zone = Intl.DateTimeFormat().resolvedOptions().timeZone;+ } catch (e) {+ return;+ }+ if (!zone) return;+ var key = 'speakr.timezoneReported';+ try {+ if (sessionStorage.getItem(key) === zone) return;+ } catch (e) { /* storage unavailable: report anyway */ }+ var meta = document.querySelector('meta[name="csrf-token"]');+ fetch('/api/user/timezone', {+ method: 'POST',+ credentials: 'same-origin',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': meta ? meta.getAttribute('content') : ''+ },+ body: JSON.stringify({ timezone: zone })+ }).then(function (r) {+ if (r.ok) {+ try { sessionStorage.setItem(key, zone); } catch (e) { /* ignore */ }+ }+ }).catch(function () { /* offline or logged out: try again next page */ });+})();diff --git a/static/locales/de.json b/static/locales/de.jsonindex 360a04ce..e411153f 100644--- a/static/locales/de.json+++ b/static/locales/de.json@@ -108,7 +108,10 @@"signInSecurity": "Anmeldung & Sicherheit","password": "Passwort","savedSuccess": "Einstellungen gespeichert",- "contextualSpeakerLabellingHelp": "Sprecher werden anhand des Gesprächskontexts zugeordnet, da Ihre Transkriptions-Engine keine Stimmprofile liefert. Das kann recht ungenau sein, abhängig davon, wie viel das Gespräch darüber verrät, wer spricht, und wie gut Ihr Modell die Sprecher trennt. Für die genaueste, stimmbasierte Sprecherzuordnung wird der WhisperX-ASR-Container empfohlen."+ "contextualSpeakerLabellingHelp": "Sprecher werden anhand des Gesprächskontexts zugeordnet, da Ihre Transkriptions-Engine keine Stimmprofile liefert. Das kann recht ungenau sein, abhängig davon, wie viel das Gespräch darüber verrät, wer spricht, und wie gut Ihr Modell die Sprecher trennt. Für die genaueste, stimmbasierte Sprecherzuordnung wird der WhisperX-ASR-Container empfohlen.",+ "timezone": "Zeitzone",+ "timezoneAutomatic": "Automatisch (dieses Gerät)",+ "timezoneHelp": "Wird für Datumsangaben in Titeln aus Namensvorlagen verwendet. Datumsangaben auf den Seiten folgen immer diesem Gerät."},"accountTabs": {"about": "Über",@@ -359,7 +362,8 @@"invalid": "Geben Sie eine Zahl zwischen 0 und 2 ein.","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."},"apiTokens": {"activeTokens": "Aktive Token",diff --git a/static/locales/en.json b/static/locales/en.jsonindex fefa62b3..36b7bd14 100644--- a/static/locales/en.json+++ b/static/locales/en.json@@ -108,7 +108,10 @@"signInSecurity": "Sign-in & Security","password": "Password","savedSuccess": "Settings saved",- "contextualSpeakerLabellingHelp": "Speakers are matched from the conversation context because your transcription engine does not provide voice fingerprints. This can be quite inaccurate, depending on how much the conversation reveals about who is speaking and how well your model separates speakers. For the most accurate, voice-based speaker matching, the WhisperX ASR container is recommended."+ "contextualSpeakerLabellingHelp": "Speakers are matched from the conversation context because your transcription engine does not provide voice fingerprints. This can be quite inaccurate, depending on how much the conversation reveals about who is speaking and how well your model separates speakers. For the most accurate, voice-based speaker matching, the WhisperX ASR container is recommended.",+ "timezone": "Timezone",+ "timezoneAutomatic": "Automatic (this device)",+ "timezoneHelp": "Used for dates in titles from naming templates. Dates shown on pages always follow this device."},"accountTabs": {"about": "About",@@ -359,7 +362,8 @@"invalid": "Enter a number between 0 and 2.","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."},"apiTokens": {"activeTokens": "Active Tokens",diff --git a/static/locales/es.json b/static/locales/es.jsonindex 62e65be8..4588d442 100644--- a/static/locales/es.json+++ b/static/locales/es.json@@ -108,7 +108,10 @@"signInSecurity": "Inicio de sesión y seguridad","password": "Contraseña","savedSuccess": "Configuración guardada",- "contextualSpeakerLabellingHelp": "Los hablantes se identifican a partir del contexto de la conversación porque su motor de transcripción no proporciona huellas de voz. Esto puede ser bastante impreciso, según cuánto revele la conversación sobre quién habla y con qué precisión su modelo separa a los hablantes. Para la coincidencia de hablantes más precisa, basada en la voz, se recomienda el contenedor WhisperX ASR."+ "contextualSpeakerLabellingHelp": "Los hablantes se identifican a partir del contexto de la conversación porque su motor de transcripción no proporciona huellas de voz. Esto puede ser bastante impreciso, según cuánto revele la conversación sobre quién habla y con qué precisión su modelo separa a los hablantes. Para la coincidencia de hablantes más precisa, basada en la voz, se recomienda el contenedor WhisperX ASR.",+ "timezone": "Zona horaria",+ "timezoneAutomatic": "Automática (este dispositivo)",+ "timezoneHelp": "Se usa para las fechas de los títulos creados con plantillas de nombres. Las fechas mostradas en las páginas siguen siempre este dispositivo."},"accountTabs": {"about": "Acerca de",@@ -359,7 +362,8 @@"invalid": "Introduzca un número entre 0 y 2.","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."},"apiTokens": {"activeTokens": "Tokens activos",diff --git a/static/locales/fr.json b/static/locales/fr.jsonindex a5427d0a..ca126d68 100644--- a/static/locales/fr.json+++ b/static/locales/fr.json@@ -108,7 +108,10 @@"signInSecurity": "Connexion et sécurité","password": "Mot de passe","savedSuccess": "Paramètres enregistrés",- "contextualSpeakerLabellingHelp": "Les locuteurs sont identifiés à partir du contexte de la conversation, car votre moteur de transcription ne fournit pas d'empreintes vocales. Cela peut être assez imprécis, selon ce que la conversation révèle sur l'identité des locuteurs et la capacité de votre modèle à les distinguer. Pour la correspondance de locuteurs la plus précise, basée sur la voix, le conteneur WhisperX ASR est recommandé."+ "contextualSpeakerLabellingHelp": "Les locuteurs sont identifiés à partir du contexte de la conversation, car votre moteur de transcription ne fournit pas d'empreintes vocales. Cela peut être assez imprécis, selon ce que la conversation révèle sur l'identité des locuteurs et la capacité de votre modèle à les distinguer. Pour la correspondance de locuteurs la plus précise, basée sur la voix, le conteneur WhisperX ASR est recommandé.",+ "timezone": "Fuseau horaire",+ "timezoneAutomatic": "Automatique (cet appareil)",+ "timezoneHelp": "Utilisé pour les dates des titres issus des modèles de nommage. Les dates affichées dans les pages suivent toujours cet appareil."},"accountTabs": {"about": "À Propos",@@ -359,7 +362,8 @@"invalid": "Saisissez un nombre entre 0 et 2.","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."},"apiTokens": {"activeTokens": "Jetons actifs",diff --git a/static/locales/pt-BR.json b/static/locales/pt-BR.jsonindex 1762dc8f..03e06bb9 100644--- a/static/locales/pt-BR.json+++ b/static/locales/pt-BR.json@@ -108,7 +108,10 @@"signInSecurity": "Acesso e segurança","password": "Senha","savedSuccess": "Configurações salvas",- "contextualSpeakerLabellingHelp": "Os falantes são identificados a partir do contexto da conversa porque o seu mecanismo de transcrição não fornece impressões de voz. Isso pode ser bastante impreciso, dependendo de quanto a conversa revela sobre quem está falando e de quão bem o seu modelo separa os falantes. Para a correspondência de falantes mais precisa, baseada em voz, recomenda-se o contêiner WhisperX ASR."+ "contextualSpeakerLabellingHelp": "Os falantes são identificados a partir do contexto da conversa porque o seu mecanismo de transcrição não fornece impressões de voz. Isso pode ser bastante impreciso, dependendo de quanto a conversa revela sobre quem está falando e de quão bem o seu modelo separa os falantes. Para a correspondência de falantes mais precisa, baseada em voz, recomenda-se o contêiner WhisperX ASR.",+ "timezone": "Fuso horário",+ "timezoneAutomatic": "Automático (este dispositivo)",+ "timezoneHelp": "Usado para as datas nos títulos criados por modelos de nome. As datas exibidas nas páginas sempre seguem este dispositivo."},"accountTabs": {"about": "Sobre",@@ -359,7 +362,8 @@"invalid": "Informe um número entre 0 e 2.","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."},"apiTokens": {"activeTokens": "Tokens Ativos",diff --git a/static/locales/ru.json b/static/locales/ru.jsonindex 28159725..2ced8982 100644--- a/static/locales/ru.json+++ b/static/locales/ru.json@@ -108,7 +108,10 @@"signInSecurity": "Вход и безопасность","password": "Пароль","savedSuccess": "Настройки сохранены",- "contextualSpeakerLabellingHelp": "Говорящие определяются по контексту разговора, поскольку ваш движок транскрипции не предоставляет голосовые отпечатки. Это может быть довольно неточным в зависимости от того, насколько разговор раскрывает, кто говорит, и насколько хорошо ваша модель разделяет говорящих. Для наиболее точного сопоставления говорящих на основе голоса рекомендуется контейнер WhisperX ASR."+ "contextualSpeakerLabellingHelp": "Говорящие определяются по контексту разговора, поскольку ваш движок транскрипции не предоставляет голосовые отпечатки. Это может быть довольно неточным в зависимости от того, насколько разговор раскрывает, кто говорит, и насколько хорошо ваша модель разделяет говорящих. Для наиболее точного сопоставления говорящих на основе голоса рекомендуется контейнер WhisperX ASR.",+ "timezone": "Часовой пояс",+ "timezoneAutomatic": "Автоматически (это устройство)",+ "timezoneHelp": "Используется для дат в названиях, созданных по шаблонам. Даты на страницах всегда отображаются по этому устройству."},"accountTabs": {"about": "О продукте",@@ -359,7 +362,8 @@"invalid": "Введите число от 0 до 2.","sourceAdmin": "Используется: {{value}} (настройка администратора; по умолчанию {{default}})","sourceDefault": "Используется: {{value}} (по умолчанию)"- }+ },+ "defaultTimezoneHelp": "Используется для дат в созданных названиях, если браузер пользователя не сообщил часовой пояс и пользователь не выбрал его."},"apiTokens": {"activeTokens": "Активные токены",diff --git a/static/locales/zh.json b/static/locales/zh.jsonindex 720e3b3a..eb15e956 100644--- a/static/locales/zh.json+++ b/static/locales/zh.json@@ -108,7 +108,10 @@"signInSecurity": "登录与安全","password": "密码","savedSuccess": "设置已保存",- "contextualSpeakerLabellingHelp": "由于您的转录引擎不提供声纹,说话人是根据对话上下文进行匹配的。这可能相当不准确,取决于对话在多大程度上透露了谁在说话,以及您的模型区分说话人的效果。若需最准确的基于语音的说话人匹配,建议使用 WhisperX ASR 容器。"+ "contextualSpeakerLabellingHelp": "由于您的转录引擎不提供声纹,说话人是根据对话上下文进行匹配的。这可能相当不准确,取决于对话在多大程度上透露了谁在说话,以及您的模型区分说话人的效果。若需最准确的基于语音的说话人匹配,建议使用 WhisperX ASR 容器。",+ "timezone": "时区",+ "timezoneAutomatic": "自动(此设备)",+ "timezoneHelp": "用于命名模板生成的标题中的日期。页面上显示的日期始终跟随此设备。"},"accountTabs": {"about": "关于",@@ -359,7 +362,8 @@"invalid": "请输入 0 到 2 之间的数字。","sourceAdmin": "当前:{{value}}(管理员设置;默认 {{default}})","sourceDefault": "当前:{{value}}(默认)"- }+ },+ "defaultTimezoneHelp": "当用户的浏览器未报告时区且用户未选择时区时,用于生成标题中的日期。"},"apiTokens": {"activeTokens": "活跃令牌",diff --git a/templates/account.html b/templates/account.htmlindex 8d43ef53..3ee837cd 100644--- a/templates/account.html+++ b/templates/account.html@@ -465,6 +465,7 @@<head> so that, as with the former runtime build, they follow the page'sown stylesheets in the cascade. --><link rel="stylesheet" href="{{ url_for('static', filename='css/tailwind.css') }}">+ <script src="{{ url_for('static', filename='js/timezone-sync.js') }}" defer></script></head><body class="bg-[var(--bg-primary)] text-[var(--text-primary)] h-full flex flex-col overflow-hidden">{% set page_label = 'Account' %}@@ -1093,6 +1094,17 @@</select><p class="text-xs text-[var(--text-light)] mt-1" data-i18n="account.languageForSummaries">Language for titles, summaries, and chat. Leave on Default to follow the model's own behaviour.</p></div>+ <div>+ <label for="timezone_select" class="block text-sm font-medium text-[var(--text-muted)]" data-i18n="account.timezone">Timezone</label>+ <select name="timezone" id="timezone_select"+ data-current="{{ current_user.timezone or '' }}"+ data-mode="{{ current_user.timezone_mode or 'auto' }}"+ class="mt-1 block w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md shadow-sm focus:outline-none focus:ring-[var(--border-focus)] focus:border-[var(--border-focus)] sm:text-sm bg-[var(--bg-input)] text-[var(--text-primary)]">+ <option value="auto" id="timezone_auto_option">Automatic (this device)</option>+ </select>+ <input type="hidden" name="detected_timezone" id="detected_timezone" value="">+ <p class="text-xs text-[var(--text-light)] mt-1" data-i18n="account.timezoneHelp">Used for dates in titles from naming templates. Dates shown on pages always follow this device.</p>+ </div></div><h3 class="text-sm font-semibold text-[var(--text-secondary)] uppercase tracking-wide pt-4" data-i18n="preferences.filenameDatesSection">Meeting date from filename</h3>@@ -7742,5 +7754,38 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</co<!-- Webhooks tab logic (#275) --><script src="{{ url_for('static', filename='js/account-webhooks.js') }}"></script>+ <script>+ // Timezone select (#412): every zone the browser knows; "Automatic"+ // follows this device. The detected zone goes with the form.+ (function () {+ var sel = document.getElementById('timezone_select');+ if (!sel) return;+ var detected = '';+ try { detected = Intl.DateTimeFormat().resolvedOptions().timeZone || ''; } catch (e) {}+ document.getElementById('detected_timezone').value = detected;+ var auto = document.getElementById('timezone_auto_option');+ if (detected) auto.dataset.detected = detected;+ var zones = [];+ try { zones = Intl.supportedValuesOf('timeZone'); } catch (e) {}+ var current = sel.dataset.current;+ if (current && zones.indexOf(current) === -1) zones.push(current);+ zones.forEach(function (z) {+ var o = document.createElement('option');+ o.value = z;+ o.textContent = z.replace(/_/g, ' ');+ sel.appendChild(o);+ });+ sel.value = (sel.dataset.mode === 'fixed' && current) ? current : 'auto';+ function label() {+ var base = (window.i18n && window.i18n.t) ? window.i18n.t('account.timezoneAutomatic') : 'Automatic (this device)';+ auto.textContent = detected ? base + ': ' + detected.replace(/_/g, ' ') : base;+ }+ // Set after translations load (the label carries the detected zone,+ // so it is not a plain data-i18n element).+ label();+ if (window.i18n && window.i18n.ready) window.i18n.ready.then(label);+ window.addEventListener('i18nReady', label);+ })();+ </script></body></html>diff --git a/templates/admin.html b/templates/admin.htmlindex e16c5251..6ba31e5d 100644--- a/templates/admin.html+++ b/templates/admin.html@@ -1706,6 +1706,15 @@ Summarization Instructions:<small v-if="!settingUseNoLimit" class="text-[var(--text-muted)]">Recommended: 30000-50000 characters for most LLMs</small></div>+ <!-- Zone picker for default_timezone (#412) -->+ <div v-else-if="editingSetting.key === 'default_timezone'" class="space-y-2">+ <select v-model="settingNewValue"+ 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)]">+ <option v-for="z in timezoneOptions" :key="z" :value="z">${ z.replace(/_/g, ' ') }</option>+ </select>+ <small class="text-[var(--text-muted)]" v-text="t('adminDashboard.defaultTimezoneHelp')"></small>+ </div>+<!-- Special input for max_file_size_mb --><div v-else-if="editingSetting.key === 'max_file_size_mb'" class="space-y-2"><input v-model.number="settingNewValue" type="number" min="1" max="10000" step="50"@@ -2596,6 +2605,7 @@ Summarization Instructions:'max_file_size_mb','max_audio_only_video_size_mb','asr_timeout_seconds',+ 'default_timezone','admin_default_summary_prompt','recording_disclaimer','upload_disclaimer',@@ -2768,6 +2778,12 @@ Summarization Instructions:const showEditSettingModal = ref(false);const editingSetting = ref(null);const settingNewValue = ref('');+ // IANA zones for the default_timezone picker (#412)+ const timezoneOptions = (() => {+ let zones = [];+ try { zones = Intl.supportedValuesOf('timeZone'); } catch (e) { /* older browser */ }+ return zones.includes('UTC') ? zones : ['UTC', ...zones];+ })();const settingUseNoLimit = ref(false);const settingTimeoutMinutes = ref(30);const settingTimeoutSeconds = ref(0);@@ -4159,6 +4175,7 @@ Summarization Instructions:showEditSettingModal,editingSetting,settingNewValue,+ timezoneOptions,settingUseNoLimit,settingTimeoutMinutes,settingTimeoutSeconds,diff --git a/templates/index.html b/templates/index.htmlindex bf0f5caf..ae307cd4 100644--- a/templates/index.html+++ b/templates/index.html@@ -83,6 +83,7 @@<script src="{{ url_for('static', filename='vendor/js/purify.min.js') }}"></script><script src="{{ url_for('static', filename='js/markdown-safe.js') }}"></script><script src="{{ url_for('static', filename='vendor/js/easymde.min.js') }}"></script>+ <script src="{{ url_for('static', filename='js/timezone-sync.js') }}" defer></script></head><body class="h-full bg-[var(--bg-primary)] text-[var(--text-primary)] transition-colors duration-300"><div id="app" v-cloakdiff --git a/templates/inquire.html b/templates/inquire.htmlindex 05dd663b..404b9907 100644--- a/templates/inquire.html+++ b/templates/inquire.html@@ -206,6 +206,7 @@{% include 'includes/i18n_bootstrap.html' %}<script src="{{ url_for('static', filename='js/i18n.js') }}"></script>{% include 'includes/loading_overlay.html' %}+ <script src="{{ url_for('static', filename='js/timezone-sync.js') }}" defer></script></head><body class="h-full bg-[var(--bg-primary)] text-[var(--text-primary)] transition-colors duration-300"><div id="inquire-app" v-cloak class="h-full flex flex-col"diff --git a/tests/test_timezones.py b/tests/test_timezones.pynew file mode 100644index 00000000..0455e5a4--- /dev/null+++ b/tests/test_timezones.py@@ -0,0 +1,225 @@+"""Per-user timezone for text the server writes (#412).++The issue: with a naming template such as "{{datetime}} <label>", a recording+made at 09:13 local time (UTC+3, stored as 06:13 UTC) was titled 06:13. Titles+now use the owner's zone: the browser's zone in 'auto' mode, a zone chosen in+Account settings in 'fixed' mode, else the admin default. Stored data and API+output stay UTC (tests/test_datetime_contract.py).++SHARED-DB: users, recordings and the admin setting are restored afterwards.+"""++import os+import sys+import uuid+from datetime import datetime+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 NamingTemplate, Recording, SystemSetting, User+from src.services.titling import compute_title+from src.tasks import processing+from src.utils import timezones as tz++app.config["WTF_CSRF_ENABLED"] = False+++class _Client(FlaskClient):+ def open(self, *args, **kwargs):+ if has_app_context():+ g.pop('_login_user', None)+ return super().open(*args, **kwargs)+++def admin_default():+ """Pin the admin default for the test, restore it afterwards."""+ with app.app_context():+ old = SystemSetting.get_setting(tz.DEFAULT_SETTING_KEY, None)++ def set_(value):+ with app.app_context():+ SystemSetting.set_setting(tz.DEFAULT_SETTING_KEY, value, setting_type='string')+ db.session.commit()+ set_('UTC')+ yield set_+ with app.app_context():+ if old is None:+ SystemSetting.query.filter_by(key=tz.DEFAULT_SETTING_KEY).delete()+ db.session.commit()+ else:+ set_(old)+++def made():+ ids = []+ yield ids+ with app.app_context():+ db.session.rollback()+ for model, oid in reversed(ids):+ obj = db.session.get(model, oid)+ if obj is not None:+ if isinstance(obj, User):+ obj.default_naming_template_id = None+ db.session.commit()+ db.session.delete(obj)+ db.session.commit()+++def _user(made, **kw):+ s = uuid.uuid4().hex[:8]+ u = User(username=f"tz_{s}", email=f"tz_{s}@local.test", password="x", **kw)+ db.session.add(u)+ db.session.commit()+ made.append((User, u.id))+ return u+++def _client(user_id):+ c = _Client(app, app.response_class, use_cookies=True)+ with c.session_transaction() as sess:+ sess["_user_id"] = str(user_id)+ return c+++# ------------------------------------------------------------------ helpers++def test_to_local_converts_naive_utc_and_handles_dst():+ assert tz.to_local(datetime(2026, 10, 1, 6, 13), "Europe/Istanbul") == datetime(2026, 10, 1, 9, 13)+ assert tz.to_local(datetime(2026, 1, 15, 17, 0), "America/New_York") == datetime(2026, 1, 15, 12, 0) # EST+ assert tz.to_local(datetime(2026, 7, 15, 17, 0), "America/New_York") == datetime(2026, 7, 15, 13, 0) # EDT+ assert tz.to_local(None, "UTC") is None++[email protected]("name,ok", [("Europe/Istanbul", True), ("UTC", True), ("Mars/Olympus", False),+ ("", False), (None, False), ("../../etc/passwd", False)])+def test_is_valid_timezone(name, ok):+ assert tz.is_valid_timezone(name) is ok+++def test_user_zone_falls_back_to_the_admin_default(made, admin_default):+ admin_default("Asia/Tokyo")+ with app.app_context():+ assert tz.user_timezone(_user(made)) == "Asia/Tokyo"+ assert tz.user_timezone(_user(made, timezone="Europe/Istanbul")) == "Europe/Istanbul"+ assert tz.user_timezone(_user(made, timezone="Bogus/Zone")) == "Asia/Tokyo"+++def test_browser_zone_is_saved_in_auto_mode_only(made):+ with app.app_context():+ auto = _user(made, timezone_mode="auto")+ fixed = _user(made, timezone="Europe/Berlin", timezone_mode="fixed")+ assert tz.record_browser_timezone(auto, "Europe/Istanbul") is True+ assert tz.record_browser_timezone(fixed, "Europe/Istanbul") is False+ assert tz.record_browser_timezone(auto, "Not/AZone") is False+ assert (auto.timezone, fixed.timezone) == ("Europe/Istanbul", "Europe/Berlin")+++# -------------------------------------------------------------- titles (#412)++def _templated(made, user, template):+ t = NamingTemplate(user_id=user.id, name="tz", template=template)+ db.session.add(t)+ db.session.commit()+ made.append((NamingTemplate, t.id))+ user.default_naming_template_id = t.id+ db.session.commit()+ r = Recording(user_id=user.id, title="Recording - a.wav", original_filename="a.wav", status="PROCESSING",+ transcription="Speaker 1: hello there everyone, let us start the meeting.",+ meeting_date=datetime(2026, 10, 1, 6, 13, 46))+ db.session.add(r)+ db.session.commit()+ made.append((Recording, r.id))+ return r+++def test_issue_412_title_uses_the_owner_local_time(made, admin_default):+ with app.app_context():+ u = _user(made, timezone="Europe/Istanbul")+ r = _templated(made, u, "{{datetime}} standup")+ with patch.object(processing, "client", None):+ assert compute_title(r) == "2026-10-01 09:13 standup"+++def test_without_any_zone_titles_stay_utc_as_before(made, admin_default):+ with app.app_context():+ u = _user(made)+ r = _templated(made, u, "{{date}} {{time}}")+ with patch.object(processing, "client", None):+ assert compute_title(r) == "2026-10-01 06:13"+++def test_admin_default_applies_to_users_without_a_zone(made, admin_default):+ admin_default("America/Los_Angeles")+ with app.app_context():+ u = _user(made)+ r = _templated(made, u, "{{datetime}}")+ with patch.object(processing, "client", None):+ assert compute_title(r) == "2026-09-30 23:13"+++def test_template_preview_default_is_now_in_the_user_zone(made, admin_default):+ with app.app_context():+ u = _user(made, timezone="Asia/Kolkata")+ t = NamingTemplate(user_id=u.id, name="p", template="{{time}}")+ db.session.add(t)+ db.session.commit()+ made.append((NamingTemplate, t.id))+ c = _client(u.id)+ expected = tz.now_local("Asia/Kolkata").strftime("%H:%M")+ resp = c.post(f"/api/naming-templates/{t.id}/test", json={})+ assert resp.status_code == 200, resp.get_data(as_text=True)[:300]+ assert resp.get_json()["result"] in (expected, tz.now_local("Asia/Kolkata").strftime("%H:%M"))+++# --------------------------------------------------------------- endpoints++def test_timezone_endpoint_saves_the_browser_zone(made):+ with app.app_context():+ u = _user(made)+ uid = u.id+ c = _client(uid)+ resp = c.post("/api/user/timezone", json={"timezone": "Europe/Istanbul"})+ assert resp.status_code == 200 and resp.get_json() == {"timezone": "Europe/Istanbul", "mode": "auto"}+ resp = c.post("/api/user/timezone", json={"timezone": "No/Such"})+ assert resp.get_json()["timezone"] == "Europe/Istanbul"+ with app.app_context():+ assert db.session.get(User, uid).timezone == "Europe/Istanbul"+++def test_account_form_fixes_or_releases_the_zone(made):+ with app.app_context():+ uid = _user(made).id+ c = _client(uid)+ base = {"preferences_form": "1", "ui_language": "en"}+ c.post("/account", data={**base, "timezone": "America/Chicago", "detected_timezone": "Europe/Istanbul"})+ with app.app_context():+ u = db.session.get(User, uid)+ assert (u.timezone, u.timezone_mode) == ("America/Chicago", "fixed")+ # a fixed zone is not replaced by the browser+ c.post("/api/user/timezone", json={"timezone": "Europe/Istanbul"})+ with app.app_context():+ assert db.session.get(User, uid).timezone == "America/Chicago"+ c.post("/account", data={**base, "timezone": "auto", "detected_timezone": "Europe/Istanbul"})+ with app.app_context():+ u = db.session.get(User, uid)+ assert (u.timezone, u.timezone_mode) == ("Europe/Istanbul", "auto")+++def test_admin_default_timezone_is_validated(made, admin_default):+ with app.app_context():+ uid = _user(made, is_admin=True).id+ c = _client(uid)+ bad = c.post("/admin/settings", json={"key": "default_timezone", "value": "Mars/Olympus", "setting_type": "string"})+ assert bad.status_code == 400+ ok = c.post("/admin/settings", json={"key": "default_timezone", "value": "Europe/Berlin", "setting_type": "string"})+ assert ok.status_code == 200, ok.get_data(as_text=True)[:200]+ with app.app_context():+ assert tz.deployment_timezone() == "Europe/Berlin"