Skip to content

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

Python

feat: parse meeting date from filename on upload with preset patterns, custom regex, and timezone-aware conversion (#342)

Murtaza Nasirf1016a077635
diff --git a/src/api/auth.py b/src/api/auth.py
index f14af1f9..60ba216b 100644
--- a/src/api/auth.py
+++ b/src/api/auth.py
@@ -628,6 +628,27 @@ def account():
current_user.transcription_language = normalize_language_code(transcription_lang)
current_user.output_language = output_lang if output_lang else None
+ # 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 as
+ # audio_player_position above).
+ if 'filename_date_pattern' in request.form:
+ from src.utils.filename_dates import VALID_PATTERN_KEYS, validate_custom_regex
+ pattern = request.form.get('filename_date_pattern', 'auto')
+ if pattern not in VALID_PATTERN_KEYS:
+ pattern = 'auto'
+ custom_regex = (request.form.get('filename_date_regex') or '').strip() or None
+ if pattern == 'custom':
+ regex_error = validate_custom_regex(custom_regex or '')
+ if regex_error:
+ if request.headers.get('X-Requested-With') == 'XMLHttpRequest' or request.accept_mimetypes.best == 'application/json':
+ return jsonify({'success': False, 'error': regex_error}), 400
+ flash(regex_error, 'error')
+ return redirect(url_for('auth.account'))
+ current_user.parse_filename_dates = 'parse_filename_dates' in request.form
+ current_user.filename_date_pattern = pattern
+ current_user.filename_date_regex = custom_regex
+
# Check if this is the custom prompts form (has summary_prompt field)
elif 'summary_prompt' in request.form:
# Handle custom prompt updates
diff --git a/src/api/recordings.py b/src/api/recordings.py
index 769a1df7..f0824b8f 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -2656,6 +2656,10 @@ def upload_file():
# Get file's lastModified timestamp from client (milliseconds since epoch)
file_last_modified = request.form.get('file_last_modified')
+ # Client timezone offset (JS getTimezoneOffset(): minutes to add to
+ # local time to reach UTC). Used to convert filename wall-clock dates
+ # to the naive-UTC storage convention.
+ client_tz_offset = request.form.get('client_tz_offset')
# Get selected tags if provided (multiple tags support)
selected_tags = []
@@ -2768,6 +2772,26 @@ def upload_file():
except (ValueError, TypeError) as e:
current_app.logger.warning(f"Could not parse user meeting_date '{user_meeting_date}': {e}")
+ # Then try parsing a date from the filename when the user opted in
+ # (#342). The pattern is explicit user intent, so it outranks the
+ # automatic sources (lastModified / embedded metadata) below.
+ if not meeting_date and current_user.parse_filename_dates and original_filename:
+ from src.utils.filename_dates import parse_filename_date
+ tz_offset = None
+ if client_tz_offset is not None:
+ try:
+ tz_offset = int(client_tz_offset)
+ except (TypeError, ValueError):
+ tz_offset = None
+ meeting_date = parse_filename_date(
+ original_filename,
+ pattern_key=current_user.filename_date_pattern or 'auto',
+ custom_regex=current_user.filename_date_regex,
+ tz_offset_minutes=tz_offset,
+ )
+ if meeting_date:
+ current_app.logger.info(f"Using filename-parsed meeting_date: {meeting_date}")
+
# Then try client-provided file lastModified (most reliable for uploads)
if not meeting_date and file_last_modified:
try:
diff --git a/src/file_monitor.py b/src/file_monitor.py
index 9b1ec527..1ca4fc33 100644
--- a/src/file_monitor.py
+++ b/src/file_monitor.py
@@ -428,13 +428,29 @@ class FileMonitor:
# Create database record
now = datetime.utcnow()
+ # Filename-parsed date first when the owner opted in (#342):
+ # the configured pattern is explicit user intent, so it
+ # outranks embedded metadata. No client timezone exists on
+ # this path, so date-only matches anchor at 12:00 UTC.
+ meeting_date = None
+ if user and user.parse_filename_dates:
+ from src.utils.filename_dates import parse_filename_date
+ meeting_date = parse_filename_date(
+ original_filename,
+ pattern_key=user.filename_date_pattern or 'auto',
+ custom_regex=user.filename_date_regex,
+ )
+ if meeting_date:
+ self.logger.info(f"Using filename-parsed meeting date: {meeting_date}")
+
# Try to extract creation date from file metadata, fall back to current time
- meeting_date = get_creation_date(str(final_path))
- if meeting_date:
- self.logger.info(f"Using file metadata creation date: {meeting_date}")
- else:
- meeting_date = now
- self.logger.debug("No metadata creation date found, using current time")
+ if not meeting_date:
+ meeting_date = get_creation_date(str(final_path))
+ if meeting_date:
+ self.logger.info(f"Using file metadata creation date: {meeting_date}")
+ else:
+ meeting_date = now
+ self.logger.debug("No metadata creation date found, using current time")
# Check for duplicate
if file_hash:
diff --git a/src/init_db.py b/src/init_db.py
index a4e4d941..7ba32a1f 100644
--- a/src/init_db.py
+++ b/src/init_db.py
@@ -400,6 +400,14 @@ def initialize_database(app):
app.logger.info("Added editor_autosave column to user table")
if add_column_if_not_exists(engine, 'user', 'audio_player_position', "VARCHAR(10) DEFAULT 'bottom'"):
app.logger.info("Added audio_player_position column to user table")
+
+ # Filename date parsing (#342)
+ if add_column_if_not_exists(engine, 'user', 'parse_filename_dates', 'BOOLEAN DEFAULT 0'):
+ app.logger.info("Added parse_filename_dates column to user table")
+ if add_column_if_not_exists(engine, 'user', 'filename_date_pattern', "VARCHAR(50) DEFAULT 'auto'"):
+ app.logger.info("Added filename_date_pattern column to user table")
+ if add_column_if_not_exists(engine, 'user', 'filename_date_regex', 'VARCHAR(500)'):
+ app.logger.info("Added filename_date_regex column to user table")
if add_column_if_not_exists(engine, 'tag', 'default_hotwords', 'TEXT'):
app.logger.info("Added default_hotwords column to tag table")
if add_column_if_not_exists(engine, 'tag', 'default_initial_prompt', 'TEXT'):
diff --git a/src/models/user.py b/src/models/user.py
index 364fef75..4e0517d5 100644
--- a/src/models/user.py
+++ b/src/models/user.py
@@ -63,6 +63,13 @@ class User(db.Model, UserMixin):
transcription_hotwords = db.Column(db.Text, nullable=True)
transcription_initial_prompt = db.Column(db.Text, nullable=True)
+ # Parse meeting date from the uploaded filename (#342). When enabled,
+ # a date extracted from the filename takes precedence over file
+ # metadata / lastModified when setting meeting_date on upload.
+ parse_filename_dates = db.Column(db.Boolean, default=False)
+ filename_date_pattern = db.Column(db.String(50), nullable=True, default='auto') # preset key or 'custom'
+ filename_date_regex = db.Column(db.String(500), nullable=True) # named-group regex for 'custom'
+
# Include timestamps in the transcript sent to the summarizer / chat (#304).
# Independent per feature; the *_template_id selects a transcript template to
# format the timestamps (null = a built-in default timestamp format).
diff --git a/src/utils/filename_dates.py b/src/utils/filename_dates.py
new file mode 100644
index 00000000..6effbb9b
--- /dev/null
+++ b/src/utils/filename_dates.py
@@ -0,0 +1,179 @@
+"""
+Parse meeting dates out of uploaded filenames (#342).
+
+Voice recorders and phone apps commonly encode the recording date in the
+filename (``20260716_meeting.mp3``, ``260716_1102.m4a``). When a user
+enables filename date parsing, the date found here takes precedence over
+file metadata / browser lastModified when setting ``meeting_date``.
+
+Timezone semantics: a filename date is a *wall-clock* value in the
+uploader's local timezone. ``meeting_date`` is stored as naive UTC and
+rendered viewer-local, so the parsed value must be shifted to UTC before
+storage. Callers pass ``tz_offset_minutes`` in JavaScript
+``getTimezoneOffset()`` convention (minutes to ADD to local time to get
+UTC; positive west of UTC). When no offset is known, date-only matches
+are anchored at 12:00 UTC so the calendar date survives rendering in any
+viewer timezone, and time-bearing matches are treated as already UTC.
+"""
+
+import re
+from datetime import datetime, timedelta
+from typing import Optional
+
+
+# Presets are matched against the filename stem (extension stripped).
+# Digit lookarounds stop a longer digit run (e.g. a phone number) from
+# donating a spurious "date". Order within AUTO_PRESET_ORDER runs the most
+# specific patterns first.
+PRESET_PATTERNS = {
+ # 20260716_1102, 20260716-1102, "20260716 1102"
+ 'yyyymmdd_hhmm': re.compile(
+ r'(?<!\d)(?P<year>(?:19|20)\d{2})(?P<month>\d{2})(?P<day>\d{2})'
+ r'[_\- ](?P<hour>\d{2})[:.]?(?P<minute>\d{2})(?!\d)'
+ ),
+ # 2026-07-16, 2026_07_16, 2026.07.16, optionally followed by 11-02 / 11:02 / 1102
+ 'yyyy-mm-dd': re.compile(
+ r'(?<!\d)(?P<year>(?:19|20)\d{2})[-_.](?P<month>\d{2})[-_.](?P<day>\d{2})'
+ r'(?:[_\- T](?P<hour>\d{2})[:.\-_]?(?P<minute>\d{2})(?!\d))?'
+ ),
+ # 20260716
+ 'yyyymmdd': re.compile(
+ r'(?<!\d)(?P<year>(?:19|20)\d{2})(?P<month>\d{2})(?P<day>\d{2})(?!\d)'
+ ),
+ # 260716_1102
+ 'yymmdd_hhmm': re.compile(
+ r'(?<!\d)(?P<year>\d{2})(?P<month>\d{2})(?P<day>\d{2})'
+ r'[_\- ](?P<hour>\d{2})[:.]?(?P<minute>\d{2})(?!\d)'
+ ),
+ # 260716 — ambiguous six digits; only used when explicitly selected,
+ # never as part of 'auto' (see AUTO_PRESET_ORDER).
+ 'yymmdd': re.compile(
+ r'(?<!\d)(?P<year>\d{2})(?P<month>\d{2})(?P<day>\d{2})(?!\d)'
+ ),
+}
+
+# 'auto' tries these in order. Bare yymmdd is excluded: any six digits in
+# a filename would qualify, which produces far too many false positives.
+AUTO_PRESET_ORDER = ('yyyymmdd_hhmm', 'yyyy-mm-dd', 'yyyymmdd', 'yymmdd_hhmm')
+
+VALID_PATTERN_KEYS = ('auto',) + tuple(PRESET_PATTERNS.keys()) + ('custom',)
+
+_MIN_YEAR = 1970
+_MAX_YEAR = 2100
+
+
+def _build_datetime(groups) -> Optional[datetime]:
+ """Turn named regex groups into a validated datetime, or None."""
+ try:
+ year = int(groups['year'])
+ if year < 100:
+ year += 2000
+ month = int(groups['month'])
+ day = int(groups['day'])
+ hour = int(groups.get('hour') or 0)
+ minute = int(groups.get('minute') or 0)
+ except (KeyError, TypeError, ValueError):
+ return None
+
+ if not (_MIN_YEAR <= year <= _MAX_YEAR):
+ return None
+ if hour > 23 or minute > 59:
+ return None
+ try:
+ return datetime(year, month, day, hour, minute)
+ except ValueError:
+ return None
+
+
+def _has_time(groups) -> bool:
+ return bool(groups.get('hour'))
+
+
+def parse_filename_date(filename: str, pattern_key: str = 'auto',
+ custom_regex: Optional[str] = None,
+ tz_offset_minutes: Optional[int] = None) -> Optional[datetime]:
+ """
+ Extract a meeting date from *filename* and return it as naive UTC.
+
+ Args:
+ filename: Original filename (extension is stripped before matching).
+ pattern_key: One of VALID_PATTERN_KEYS.
+ custom_regex: Required when pattern_key == 'custom'. Must define
+ named groups ``year``, ``month``, ``day`` and may define
+ ``hour`` and ``minute``.
+ tz_offset_minutes: JavaScript getTimezoneOffset() value for the
+ uploader (minutes to add to local time to reach UTC). None
+ when the client timezone is unknown.
+
+ Returns:
+ Naive-UTC datetime, or None when nothing (valid) matched. Never
+ raises: a broken custom regex simply yields None.
+ """
+ if not filename:
+ return None
+ stem = filename.rsplit('.', 1)[0] if '.' in filename else filename
+
+ candidates = []
+ if pattern_key == 'auto':
+ candidates = [PRESET_PATTERNS[k] for k in AUTO_PRESET_ORDER]
+ elif pattern_key in PRESET_PATTERNS:
+ candidates = [PRESET_PATTERNS[pattern_key]]
+ elif pattern_key == 'custom' and custom_regex:
+ try:
+ candidates = [re.compile(custom_regex)]
+ except re.error:
+ return None
+ else:
+ return None
+
+ for pattern in candidates:
+ try:
+ match = pattern.search(stem)
+ except Exception:
+ continue
+ if not match:
+ continue
+ groups = match.groupdict()
+ parsed = _build_datetime(groups)
+ if parsed is None:
+ continue
+
+ # Local wall-clock -> naive UTC per the storage convention.
+ if tz_offset_minutes is not None:
+ try:
+ offset = int(tz_offset_minutes)
+ except (TypeError, ValueError):
+ offset = None
+ # Sanity-bound the offset to real-world values (UTC-12..UTC+14).
+ if offset is not None and -14 * 60 <= offset <= 12 * 60:
+ return parsed + timedelta(minutes=offset)
+
+ if not _has_time(groups):
+ # Date-only with unknown timezone: anchor at 12:00 UTC so the
+ # calendar date renders unchanged in any viewer timezone.
+ return parsed.replace(hour=12, minute=0)
+ return parsed
+
+ return None
+
+
+def validate_custom_regex(custom_regex: str) -> Optional[str]:
+ """
+ Validate a user-supplied custom regex. Returns an error message string,
+ or None when the regex is acceptable.
+ """
+ if not custom_regex or not custom_regex.strip():
+ return 'Custom pattern is required when the custom option is selected.'
+ if len(custom_regex) > 500:
+ return 'Custom pattern is too long (max 500 characters).'
+ try:
+ compiled = re.compile(custom_regex)
+ except re.error as e:
+ return f'Invalid regular expression: {e}'
+ required = {'year', 'month', 'day'}
+ missing = required - set(compiled.groupindex.keys())
+ if missing:
+ return ('Custom pattern must define named groups (?P<year>...), '
+ '(?P<month>...) and (?P<day>...); missing: '
+ + ', '.join(sorted(missing)))
+ return None
diff --git a/static/js/modules/composables/upload.js b/static/js/modules/composables/upload.js
index 316c2c23..9a9bd773 100644
--- a/static/js/modules/composables/upload.js
+++ b/static/js/modules/composables/upload.js
@@ -462,6 +462,9 @@ export function useUpload(state, utils) {
if (fileItem.file.lastModified) {
const lastModified = fileItem.file.lastModified;
formData.append('file_last_modified', lastModified.toString());
+ // Client timezone offset so filename-parsed wall-clock dates
+ // can be converted to UTC server-side (#342)
+ formData.append('client_tz_offset', new Date().getTimezoneOffset().toString());
}
if (fileItem.notes) {
diff --git a/static/locales/de.json b/static/locales/de.json
index 60bb7ddf..9f64b56f 100644
--- a/static/locales/de.json
+++ b/static/locales/de.json
@@ -1771,6 +1771,14 @@
"description": "Einstellungen zu Anzeige und Editor-Verhalten. Diese werden in deinem Konto gespeichert und gelten geräteübergreifend.",
"editorAutosave": "Automatisches Speichern im Transkript-Editor",
"editorAutosaveHelp": "Wenn aktiviert, werden Änderungen im Transkript-Editor wenige Sekunden nach Tippende automatisch gespeichert. Standardmäßig deaktiviert; speichern erfolgt explizit über die Speichern-Buttons oder Strg+S.",
+ "filenameDatePattern": "Datumsformat im Dateinamen",
+ "filenameDatePatternAuto": "Automatisch (gängige Formate)",
+ "filenameDatePatternCustom": "Eigenes Muster",
+ "filenameDateRegex": "Eigenes Muster (regulärer Ausdruck)",
+ "filenameDateRegexHelp": "Muss die benannten Gruppen year, month und day enthalten; hour und minute sind optional. Beispiel: (?P<year>\\d{4})-(?P<month>\\d{2})-(?P<day>\\d{2})",
+ "filenameDatesSection": "Aufnahmedatum aus dem Dateinamen",
+ "parseFilenameDates": "Aufnahmedatum aus dem Dateinamen lesen",
+ "parseFilenameDatesHelp": "Wenn ein hochgeladener Dateiname ein Datum enthält (z. B. 20260716_meeting.mp3), wird es als Aufnahmedatum verwendet statt der Zeitstempel der Datei. Dateien ohne passendes Datum behalten das bisherige Verhalten.",
"showTimestampsSimpleView": "Zeitstempel in der einfachen Ansicht anzeigen",
"showTimestampsSimpleViewHelp": "Zeigt einen kompakten Zeitstempel mm:ss neben jedem Sprechernamen in der einfachen Ansicht. Die Bubble-Ansicht ist nicht betroffen.",
"transcriptDisplay": "Transkriptanzeige",
diff --git a/static/locales/en.json b/static/locales/en.json
index 0b1ee5fe..8747d4c6 100644
--- a/static/locales/en.json
+++ b/static/locales/en.json
@@ -1262,6 +1262,14 @@
"description": "Display and editor behaviour preferences. These settings are saved to your account and apply across devices.",
"editorAutosave": "Auto-save edits in the transcript editor",
"editorAutosaveHelp": "When enabled, edits in the transcript editor are saved automatically a couple of seconds after you stop typing. When disabled (default), you save explicitly via the Save buttons or Ctrl+S.",
+ "filenameDatePattern": "Filename date format",
+ "filenameDatePatternAuto": "Auto (common formats)",
+ "filenameDatePatternCustom": "Custom pattern",
+ "filenameDateRegex": "Custom pattern (regular expression)",
+ "filenameDateRegexHelp": "Must contain named groups year, month and day; hour and minute are optional. Example: (?P<year>\\d{4})-(?P<month>\\d{2})-(?P<day>\\d{2})",
+ "filenameDatesSection": "Meeting date from filename",
+ "parseFilenameDates": "Parse meeting date from filename",
+ "parseFilenameDatesHelp": "When an uploaded filename contains a date (for example 20260716_meeting.mp3), use it as the meeting date instead of the file's timestamps. Files without a matching date keep the current behaviour.",
"showTimestampsSimpleView": "Show timestamps in simple view",
"showTimestampsSimpleViewHelp": "Display a compact mm:ss timestamp next to each speaker label in the simple transcript view. The bubble view is unaffected.",
"transcriptDisplay": "Transcript display",
diff --git a/static/locales/es.json b/static/locales/es.json
index 34c4fe83..fe25f3aa 100644
--- a/static/locales/es.json
+++ b/static/locales/es.json
@@ -1771,6 +1771,14 @@
"description": "Preferencias de visualización y comportamiento del editor. Estos ajustes se guardan en tu cuenta y se aplican en todos los dispositivos.",
"editorAutosave": "Guardar automáticamente en el editor de transcripción",
"editorAutosaveHelp": "Cuando está activado, las ediciones en el editor de transcripción se guardan automáticamente un par de segundos después de dejar de escribir. Por defecto está desactivado, y guardas explícitamente con los botones Guardar o Ctrl+S.",
+ "filenameDatePattern": "Formato de fecha del nombre de archivo",
+ "filenameDatePatternAuto": "Automático (formatos comunes)",
+ "filenameDatePatternCustom": "Patrón personalizado",
+ "filenameDateRegex": "Patrón personalizado (expresión regular)",
+ "filenameDateRegexHelp": "Debe contener los grupos con nombre year, month y day; hour y minute son opcionales. Ejemplo: (?P<year>\\d{4})-(?P<month>\\d{2})-(?P<day>\\d{2})",
+ "filenameDatesSection": "Fecha de reunión desde el nombre de archivo",
+ "parseFilenameDates": "Extraer la fecha de reunión del nombre de archivo",
+ "parseFilenameDatesHelp": "Cuando un nombre de archivo subido contiene una fecha (por ejemplo 20260716_meeting.mp3), se usa como fecha de reunión en lugar de las marcas de tiempo del archivo. Los archivos sin fecha coincidente mantienen el comportamiento actual.",
"showTimestampsSimpleView": "Mostrar marcas de tiempo en la vista simple",
"showTimestampsSimpleViewHelp": "Muestra una marca de tiempo compacta mm:ss junto a cada etiqueta de hablante en la vista simple. La vista de burbujas no se ve afectada.",
"transcriptDisplay": "Visualización de la transcripción",
diff --git a/static/locales/fr.json b/static/locales/fr.json
index f55435dc..abe84703 100644
--- a/static/locales/fr.json
+++ b/static/locales/fr.json
@@ -1771,6 +1771,14 @@
"description": "Préférences d'affichage et de comportement de l'éditeur. Ces paramètres sont enregistrés sur votre compte et s'appliquent à tous les appareils.",
"editorAutosave": "Enregistrer automatiquement dans l'éditeur de transcription",
"editorAutosaveHelp": "Lorsque cette option est activée, les modifications dans l'éditeur de transcription sont enregistrées automatiquement quelques secondes après l'arrêt de la saisie. Désactivée par défaut, vous enregistrez explicitement via les boutons Enregistrer ou Ctrl+S.",
+ "filenameDatePattern": "Format de date du nom de fichier",
+ "filenameDatePatternAuto": "Automatique (formats courants)",
+ "filenameDatePatternCustom": "Motif personnalisé",
+ "filenameDateRegex": "Motif personnalisé (expression régulière)",
+ "filenameDateRegexHelp": "Doit contenir les groupes nommés year, month et day ; hour et minute sont facultatifs. Exemple : (?P<year>\\d{4})-(?P<month>\\d{2})-(?P<day>\\d{2})",
+ "filenameDatesSection": "Date de réunion depuis le nom de fichier",
+ "parseFilenameDates": "Extraire la date de réunion du nom de fichier",
+ "parseFilenameDatesHelp": "Lorsqu'un nom de fichier importé contient une date (par exemple 20260716_meeting.mp3), elle est utilisée comme date de réunion à la place des horodatages du fichier. Les fichiers sans date correspondante conservent le comportement actuel.",
"showTimestampsSimpleView": "Afficher les horodatages dans la vue simple",
"showTimestampsSimpleViewHelp": "Affiche un horodatage compact mm:ss à côté de chaque libellé de locuteur dans la vue simple. La vue bulle n'est pas affectée.",
"transcriptDisplay": "Affichage de la transcription",
diff --git a/static/locales/pt-BR.json b/static/locales/pt-BR.json
index 2581dde7..cde25794 100644
--- a/static/locales/pt-BR.json
+++ b/static/locales/pt-BR.json
@@ -1750,6 +1750,14 @@
"description": "Preferências de exibição e comportamento do editor. Estas configurações ficam salvas em sua conta e se aplicam a todos os dispositivos.",
"editorAutosave": "Salvar automaticamente as edições no editor de transcrição",
"editorAutosaveHelp": "Quando habilitado, as edições no editor de transcrição são salvas automaticamente alguns segundos após você parar de digitar. Quando desabilitado (padrão), você salva explicitamente pelos botões Salvar ou pelo Ctrl+S.",
+ "filenameDatePattern": "Formato de data do nome do arquivo",
+ "filenameDatePatternAuto": "Automático (formatos comuns)",
+ "filenameDatePatternCustom": "Padrão personalizado",
+ "filenameDateRegex": "Padrão personalizado (expressão regular)",
+ "filenameDateRegexHelp": "Deve conter os grupos nomeados year, month e day; hour e minute são opcionais. Exemplo: (?P<year>\\d{4})-(?P<month>\\d{2})-(?P<day>\\d{2})",
+ "filenameDatesSection": "Data da reunião a partir do nome do arquivo",
+ "parseFilenameDates": "Extrair a data da reunião do nome do arquivo",
+ "parseFilenameDatesHelp": "Quando um nome de arquivo enviado contém uma data (por exemplo 20260716_meeting.mp3), ela é usada como data da reunião em vez dos carimbos de data do arquivo. Arquivos sem data correspondente mantêm o comportamento atual.",
"showTimestampsSimpleView": "Mostrar marcações de tempo na visualização simples",
"showTimestampsSimpleViewHelp": "Exibe uma marcação de tempo compacta mm:ss ao lado de cada rótulo de orador na visualização simples. A visualização em balões não é afetada.",
"transcriptDisplay": "Exibição da transcrição",
diff --git a/static/locales/ru.json b/static/locales/ru.json
index ce5ae62a..dd9389a9 100644
--- a/static/locales/ru.json
+++ b/static/locales/ru.json
@@ -1771,6 +1771,14 @@
"description": "Настройки отображения и поведения редактора. Эти параметры сохраняются в вашей учётной записи и применяются на всех устройствах.",
"editorAutosave": "Автосохранение в редакторе транскрипции",
"editorAutosaveHelp": "Когда включено, правки в редакторе транскрипции сохраняются автоматически через пару секунд после остановки ввода. По умолчанию выключено: сохранение явное через кнопки Сохранить или Ctrl+S.",
+ "filenameDatePattern": "Формат даты в имени файла",
+ "filenameDatePatternAuto": "Автоматически (распространённые форматы)",
+ "filenameDatePatternCustom": "Свой шаблон",
+ "filenameDateRegex": "Свой шаблон (регулярное выражение)",
+ "filenameDateRegexHelp": "Должно содержать именованные группы year, month и day; hour и minute необязательны. Пример: (?P<year>\\d{4})-(?P<month>\\d{2})-(?P<day>\\d{2})",
+ "filenameDatesSection": "Дата встречи из имени файла",
+ "parseFilenameDates": "Извлекать дату встречи из имени файла",
+ "parseFilenameDatesHelp": "Если имя загруженного файла содержит дату (например, 20260716_meeting.mp3), она используется как дата встречи вместо временных меток файла. Файлы без подходящей даты сохраняют текущее поведение.",
"showTimestampsSimpleView": "Показывать временные метки в простом виде",
"showTimestampsSimpleViewHelp": "Показывает компактную временную метку mm:ss рядом с именем каждого говорящего в простом виде. На пузырьковый вид не влияет.",
"transcriptDisplay": "Отображение транскрипции",
diff --git a/static/locales/zh.json b/static/locales/zh.json
index 64f38a6f..d4234de4 100644
--- a/static/locales/zh.json
+++ b/static/locales/zh.json
@@ -1771,6 +1771,14 @@
"description": "显示与编辑器行为偏好。这些设置保存在您的账户中,并在所有设备上生效。",
"editorAutosave": "自动保存转录编辑器中的修改",
"editorAutosaveHelp": "启用后,转录编辑器中的修改会在停止输入约两秒后自动保存。默认关闭,您需要通过保存按钮或 Ctrl+S 手动保存。",
+ "filenameDatePattern": "文件名日期格式",
+ "filenameDatePatternAuto": "自动(常见格式)",
+ "filenameDatePatternCustom": "自定义模式",
+ "filenameDateRegex": "自定义模式(正则表达式)",
+ "filenameDateRegexHelp": "必须包含命名分组 year、month 和 day;hour 和 minute 可选。示例:(?P<year>\\d{4})-(?P<month>\\d{2})-(?P<day>\\d{2})",
+ "filenameDatesSection": "从文件名解析会议日期",
+ "parseFilenameDates": "从文件名解析会议日期",
+ "parseFilenameDatesHelp": "当上传的文件名包含日期(例如 20260716_meeting.mp3)时,将其用作会议日期,而不是文件的时间戳。没有匹配日期的文件保持当前行为。",
"showTimestampsSimpleView": "在简单视图中显示时间戳",
"showTimestampsSimpleViewHelp": "在简单视图中,每个发言人标签旁显示紧凑的 mm:ss 时间戳。气泡视图不受影响。",
"transcriptDisplay": "转录显示",
diff --git a/templates/account.html b/templates/account.html
index 4f5f3690..220679a6 100644
--- a/templates/account.html
+++ b/templates/account.html
@@ -1005,6 +1005,39 @@
<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>
+
+ <h3 class="text-sm font-semibold text-[var(--text-secondary)] uppercase tracking-wide pt-4" data-i18n="preferences.filenameDatesSection">Meeting date from filename</h3>
+ <div class="space-y-4 p-3 bg-[var(--bg-tertiary)] border border-[var(--border-secondary)] rounded-md">
+ <label class="flex items-start gap-3 cursor-pointer">
+ <input type="checkbox" id="prefParseFilenameDates" name="parse_filename_dates" {% if current_user.parse_filename_dates %}checked{% endif %} class="mt-1 h-4 w-4 text-[var(--text-accent)] border-[var(--border-secondary)] rounded focus:ring-[var(--border-focus)] bg-[var(--bg-input)]">
+ <span class="flex-1">
+ <span class="block text-sm font-medium text-[var(--text-primary)]" data-i18n="preferences.parseFilenameDates">Parse meeting date from filename</span>
+ <span class="block text-xs text-[var(--text-muted)] mt-0.5" data-i18n="preferences.parseFilenameDatesHelp">When an uploaded filename contains a date (for example 20260716_meeting.mp3), use it as the meeting date instead of the file's timestamps. Files without a matching date keep the current behaviour.</span>
+ </span>
+ </label>
+ <div>
+ <label for="filename_date_pattern" class="block text-sm font-medium text-[var(--text-muted)]" data-i18n="preferences.filenameDatePattern">Filename date format</label>
+ {% set fdp = current_user.filename_date_pattern or 'auto' %}
+ <select name="filename_date_pattern" id="filename_date_pattern"
+ onchange="document.getElementById('filenameDateRegexRow').style.display = this.value === 'custom' ? '' : 'none';"
+ 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" data-i18n="preferences.filenameDatePatternAuto" {% if fdp == 'auto' %}selected{% endif %}>Auto (common formats)</option>
+ <option value="yyyymmdd" {% if fdp == 'yyyymmdd' %}selected{% endif %}>YYYYMMDD &mdash; 20260716_meeting.mp3</option>
+ <option value="yyyymmdd_hhmm" {% if fdp == 'yyyymmdd_hhmm' %}selected{% endif %}>YYYYMMDD_HHMM &mdash; 20260716_1102.mp3</option>
+ <option value="yyyy-mm-dd" {% if fdp == 'yyyy-mm-dd' %}selected{% endif %}>YYYY-MM-DD &mdash; 2026-07-16 meeting.mp3</option>
+ <option value="yymmdd_hhmm" {% if fdp == 'yymmdd_hhmm' %}selected{% endif %}>YYMMDD_HHMM &mdash; 260716_1102.mp3</option>
+ <option value="yymmdd" {% if fdp == 'yymmdd' %}selected{% endif %}>YYMMDD &mdash; 260716.mp3</option>
+ <option value="custom" data-i18n="preferences.filenameDatePatternCustom" {% if fdp == 'custom' %}selected{% endif %}>Custom pattern</option>
+ </select>
+ </div>
+ <div id="filenameDateRegexRow" {% if fdp != 'custom' %}style="display: none;"{% endif %}>
+ <label for="filename_date_regex" class="block text-sm font-medium text-[var(--text-muted)]" data-i18n="preferences.filenameDateRegex">Custom pattern (regular expression)</label>
+ <input type="text" name="filename_date_regex" id="filename_date_regex" value="{{ current_user.filename_date_regex or '' }}"
+ placeholder="(?P&lt;year&gt;\d{4})(?P&lt;month&gt;\d{2})(?P&lt;day&gt;\d{2})" spellcheck="false"
+ 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)] font-mono">
+ <p class="text-xs text-[var(--text-light)] mt-1" data-i18n="preferences.filenameDateRegexHelp">Must contain named groups year, month and day; hour and minute are optional. Example: (?P&lt;year&gt;\d{4})-(?P&lt;month&gt;\d{2})-(?P&lt;day&gt;\d{2})</p>
+ </div>
+ </div>
</div>
<!-- Right column: Display + Editor toggles -->
diff --git a/tests/test_filename_dates.py b/tests/test_filename_dates.py
new file mode 100644
index 00000000..f008d65b
--- /dev/null
+++ b/tests/test_filename_dates.py
@@ -0,0 +1,264 @@
+"""
+Tests for filename meeting-date parsing (#342).
+
+Covers the parsing utility (presets, auto mode, custom regex, timezone
+conversion, validation) and the account-settings save path.
+"""
+
+import sys
+import os
+from datetime import datetime
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).parent.parent))
+
+from src.utils.filename_dates import (
+ parse_filename_date,
+ validate_custom_regex,
+ VALID_PATTERN_KEYS,
+)
+
+
+# ===========================================================================
+# Preset patterns
+# ===========================================================================
+
+def test_yyyymmdd_basic():
+ assert parse_filename_date('20260716_meeting.mp3', 'yyyymmdd') == datetime(2026, 7, 16, 12, 0)
+
+
+def test_yyyymmdd_hhmm():
+ # Time-bearing match without tz info is treated as UTC.
+ assert parse_filename_date('20260716_1102.mp3', 'yyyymmdd_hhmm') == datetime(2026, 7, 16, 11, 2)
+
+
+def test_yyyy_mm_dd_hyphen():
+ assert parse_filename_date('2026-07-16 team sync.m4a', 'yyyy-mm-dd') == datetime(2026, 7, 16, 12, 0)
+
+
+def test_yyyy_mm_dd_with_time():
+ assert parse_filename_date('2026-07-16 11-02 sync.m4a', 'yyyy-mm-dd') == datetime(2026, 7, 16, 11, 2)
+
+
+def test_yyyy_mm_dd_underscore_and_dot_separators():
+ assert parse_filename_date('2026_07_16.wav', 'yyyy-mm-dd') == datetime(2026, 7, 16, 12, 0)
+ assert parse_filename_date('2026.07.16.wav', 'yyyy-mm-dd') == datetime(2026, 7, 16, 12, 0)
+
+
+def test_yymmdd_hhmm():
+ assert parse_filename_date('260716_1102.mp3', 'yymmdd_hhmm') == datetime(2026, 7, 16, 11, 2)
+
+
+def test_yymmdd_explicit_only():
+ assert parse_filename_date('260716.mp3', 'yymmdd') == datetime(2026, 7, 16, 12, 0)
+
+
+# ===========================================================================
+# Auto mode
+# ===========================================================================
+
+def test_auto_matches_common_formats():
+ assert parse_filename_date('20260716_meeting.mp3', 'auto') == datetime(2026, 7, 16, 12, 0)
+ assert parse_filename_date('20260716_1102_call.mp3', 'auto') == datetime(2026, 7, 16, 11, 2)
+ assert parse_filename_date('rec 2026-07-16.ogg', 'auto') == datetime(2026, 7, 16, 12, 0)
+ assert parse_filename_date('260716_1102.mp3', 'auto') == datetime(2026, 7, 16, 11, 2)
+
+
+def test_auto_excludes_bare_yymmdd():
+ # Any six digits would qualify as yymmdd, so auto must not guess.
+ assert parse_filename_date('123456.mp3', 'auto') is None
+
+
+def test_auto_ignores_phone_numbers():
+ # 10-digit run must not donate an inner "date".
+ assert parse_filename_date('8005551234.wav', 'auto') is None
+
+
+def test_no_match_returns_none():
+ assert parse_filename_date('team meeting notes.mp3', 'auto') is None
+
+
+def test_invalid_calendar_date_rejected():
+ assert parse_filename_date('20261340_x.mp3', 'yyyymmdd') is None # month 13
+ assert parse_filename_date('20260732_x.mp3', 'yyyymmdd') is None # day 32
+
+
+def test_invalid_time_rejected():
+ assert parse_filename_date('20260716_2560.mp3', 'yyyymmdd_hhmm') is None
+
+
+def test_empty_and_none_filename():
+ assert parse_filename_date('', 'auto') is None
+ assert parse_filename_date(None, 'auto') is None
+
+
+# ===========================================================================
+# Timezone conversion
+# ===========================================================================
+
+def test_tz_offset_applied_to_time_match():
+ # UTC-5 (offset +300): 11:02 local -> 16:02 UTC
+ got = parse_filename_date('20260716_1102.mp3', 'yyyymmdd_hhmm', tz_offset_minutes=300)
+ assert got == datetime(2026, 7, 16, 16, 2)
+
+
+def test_tz_offset_applied_to_date_only_match():
+ # With a known offset a date-only match anchors at local midnight.
+ got = parse_filename_date('20260716.mp3', 'yyyymmdd', tz_offset_minutes=300)
+ assert got == datetime(2026, 7, 16, 5, 0)
+
+
+def test_date_only_without_offset_anchors_at_noon_utc():
+ got = parse_filename_date('20260716.mp3', 'yyyymmdd')
+ assert got == datetime(2026, 7, 16, 12, 0)
+
+
+def test_absurd_tz_offset_ignored():
+ got = parse_filename_date('20260716_1102.mp3', 'yyyymmdd_hhmm', tz_offset_minutes=100000)
+ assert got == datetime(2026, 7, 16, 11, 2)
+
+
+# ===========================================================================
+# Custom regex
+# ===========================================================================
+
+def test_custom_regex_named_groups():
+ rx = r'rec-(?P<day>\d{2})\.(?P<month>\d{2})\.(?P<year>\d{4})'
+ got = parse_filename_date('rec-16.07.2026.mp3', 'custom', custom_regex=rx)
+ assert got == datetime(2026, 7, 16, 12, 0)
+
+
+def test_custom_regex_with_time_groups():
+ rx = r'(?P<year>\d{4})(?P<month>\d{2})(?P<day>\d{2})T(?P<hour>\d{2})(?P<minute>\d{2})'
+ got = parse_filename_date('20260716T1102.mp3', 'custom', custom_regex=rx)
+ assert got == datetime(2026, 7, 16, 11, 2)
+
+
+def test_custom_regex_invalid_returns_none():
+ assert parse_filename_date('x.mp3', 'custom', custom_regex='(unclosed') is None
+
+
+def test_custom_without_regex_returns_none():
+ assert parse_filename_date('20260716.mp3', 'custom') is None
+
+
+def test_unknown_pattern_key_returns_none():
+ assert parse_filename_date('20260716.mp3', 'nonsense') is None
+
+
+def test_validate_custom_regex_accepts_good():
+ assert validate_custom_regex(r'(?P<year>\d{4})(?P<month>\d{2})(?P<day>\d{2})') is None
+
+
+def test_validate_custom_regex_missing_groups():
+ err = validate_custom_regex(r'(?P<year>\d{4})')
+ assert err is not None and 'month' in err and 'day' in err
+
+
+def test_validate_custom_regex_broken():
+ assert validate_custom_regex('(unclosed') is not None
+
+
+def test_validate_custom_regex_empty():
+ assert validate_custom_regex('') is not None
+
+
+def test_pattern_keys_include_ui_options():
+ for key in ('auto', 'yyyymmdd', 'yyyymmdd_hhmm', 'yyyy-mm-dd', 'yymmdd_hhmm', 'yymmdd', 'custom'):
+ assert key in VALID_PATTERN_KEYS
+
+
+# ===========================================================================
+# Settings save path (POST /account preferences form)
+# ===========================================================================
+
+os.environ.setdefault('WTF_CSRF_ENABLED', 'false')
+
+from src.app import app, db
+from src.models import User
+
+app.config['WTF_CSRF_ENABLED'] = False
+
+
+def _make_settings_user(suffix):
+ user = User(
+ username=f'fnd_settings_user_{suffix}',
+ email=f'fnd_settings_{suffix}@local.test',
+ )
+ db.session.add(user)
+ db.session.commit()
+ return user
+
+
+def _login(client, user):
+ with client.session_transaction() as sess:
+ sess['_user_id'] = str(user.id)
+ sess['_fresh'] = True
+
+
+def test_settings_save_and_validation():
+ with app.app_context():
+ user = _make_settings_user('a')
+ client = app.test_client()
+ _login(client, user)
+ try:
+ # Enable with a preset.
+ resp = client.post('/account', data={
+ 'preferences_form': '1',
+ 'parse_filename_dates': 'on',
+ 'filename_date_pattern': 'yyyymmdd',
+ }, headers={'X-Requested-With': 'XMLHttpRequest'})
+ assert resp.status_code == 200, resp.data
+ db.session.refresh(user)
+ assert user.parse_filename_dates is True
+ assert user.filename_date_pattern == 'yyyymmdd'
+
+ # Custom with an invalid regex is rejected and does not save.
+ resp = client.post('/account', data={
+ 'preferences_form': '1',
+ 'parse_filename_dates': 'on',
+ 'filename_date_pattern': 'custom',
+ 'filename_date_regex': '(unclosed',
+ }, headers={'X-Requested-With': 'XMLHttpRequest'})
+ assert resp.status_code == 400
+ db.session.rollback()
+ db.session.refresh(user)
+ assert user.filename_date_pattern == 'yyyymmdd'
+
+ # Custom with a valid regex saves.
+ rx = r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})'
+ resp = client.post('/account', data={
+ 'preferences_form': '1',
+ 'parse_filename_dates': 'on',
+ 'filename_date_pattern': 'custom',
+ 'filename_date_regex': rx,
+ }, headers={'X-Requested-With': 'XMLHttpRequest'})
+ assert resp.status_code == 200
+ db.session.refresh(user)
+ assert user.filename_date_pattern == 'custom'
+ assert user.filename_date_regex == rx
+
+ # A preferences POST WITHOUT the section (e.g. the quick
+ # ui-language change) must not clobber the settings.
+ resp = client.post('/account', data={
+ 'preferences_form': '1',
+ 'ui_language': 'en',
+ }, headers={'X-Requested-With': 'XMLHttpRequest'})
+ assert resp.status_code == 200
+ db.session.refresh(user)
+ assert user.parse_filename_dates is True
+ assert user.filename_date_pattern == 'custom'
+
+ # Unknown pattern key falls back to auto.
+ resp = client.post('/account', data={
+ 'preferences_form': '1',
+ 'filename_date_pattern': 'evil-key',
+ }, headers={'X-Requested-With': 'XMLHttpRequest'})
+ assert resp.status_code == 200
+ db.session.refresh(user)
+ assert user.filename_date_pattern == 'auto'
+ finally:
+ db.session.delete(user)
+ db.session.commit()