Skip to content

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

Python

recordings: probe-driven video MIME (stop guessing), reindex Inquire chunks on transcript/speaker edits, configurable RECORDING_CHUNK_SECONDS

Murtaza Nasir4b2f8fa2721b
diff --git a/src/api/recordings.py b/src/api/recordings.py
index 41b5c2a1..4ff5826b 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -9,6 +9,7 @@ import json
import re
import mimetypes
import time
+import threading
import subprocess
from datetime import datetime, timedelta
from src.services.job_queue import job_queue
@@ -102,6 +103,32 @@ VIDEO_PASSTHROUGH_ASR = os.environ.get('VIDEO_PASSTHROUGH_ASR', 'false').lower()
USE_ASR_ENDPOINT = os.environ.get('USE_ASR_ENDPOINT', 'false').lower() == 'true'
ENABLE_CHUNKING = os.environ.get('ENABLE_CHUNKING', 'true').lower() == 'true'
+def reindex_recording_chunks_async(recording_id):
+ """Rebuild a recording's semantic-search (Inquire) chunks in the background.
+
+ The Inquire/RAG chunks are a snapshot of recording.transcription. When the
+ transcription text changes — speaker names applied, transcript edited — the
+ chunks must be rebuilt or Inquire keeps answering from the stale text (e.g.
+ 'SPEAKER_00' instead of the applied name). Runs in a daemon thread so the
+ edit's HTTP response isn't blocked on embedding generation; no-op when
+ Inquire mode is off. process_recording_chunks deletes-then-recreates with
+ rollback safety, so a failure leaves the previous chunks intact.
+ """
+ if not ENABLE_INQUIRE_MODE:
+ return
+ app_obj = current_app._get_current_object()
+
+ def _run():
+ with app_obj.app_context():
+ try:
+ process_recording_chunks(recording_id)
+ app_obj.logger.info(f"Reindexed Inquire chunks for recording {recording_id} after edit")
+ except Exception as e:
+ app_obj.logger.error(f"Failed to reindex Inquire chunks for recording {recording_id}: {e}", exc_info=True)
+
+ threading.Thread(target=_run, name=f"reindex-chunks-{recording_id}", daemon=True).start()
+
+
# Global helpers (will be injected from app)
has_recording_access = None
get_user_recording_status = None
@@ -832,6 +859,11 @@ def update_speakers(recording_id):
db.session.commit()
+ # Speaker names changed the transcription text — rebuild the Inquire
+ # chunks so semantic search answers with the applied names, not the
+ # raw SPEAKER_XX labels. Background + best-effort.
+ reindex_recording_chunks_async(recording_id)
+
summary_queued = False
if regenerate_summary:
current_app.logger.info(f"Queueing summary regeneration for recording {recording_id} after speaker update.")
@@ -916,6 +948,10 @@ def update_transcript(recording_id):
db.session.commit()
+ # The transcript text changed — rebuild Inquire chunks so semantic
+ # search reflects the edits (names, corrections). Background + best-effort.
+ reindex_recording_chunks_async(recording_id)
+
summary_queued = False
if regenerate_summary:
current_app.logger.info(f"Queueing summary regeneration for recording {recording_id} after transcript update.")
@@ -1386,6 +1422,17 @@ def index():
except (TypeError, ValueError):
recording_max_hours = 8.0
+ # MediaRecorder timeslice (seconds) for in-app recordings: how often a
+ # chunk is emitted and streamed to the server. Smaller = finer crash
+ # recovery but more requests / files / DB commits; larger = less server
+ # load. Default 5s. At scale (many concurrent recorders on SQLite) raise
+ # this and/or RECORDING_SESSION_COMMIT_BATCH_SIZE. Clamped to [1, 60].
+ try:
+ recording_chunk_seconds = int(float(os.environ.get('RECORDING_CHUNK_SECONDS', '5')))
+ except (TypeError, ValueError):
+ recording_chunk_seconds = 5
+ recording_chunk_seconds = max(1, min(60, recording_chunk_seconds))
+
return render_template('index.html',
use_asr_endpoint=USE_ASR_ENDPOINT, # Backwards compat
connector_supports_diarization=connector_supports_diarization,
@@ -1398,7 +1445,8 @@ def index():
user_language=user_language,
is_team_admin=is_team_admin,
server_recording_chunks_enabled=server_recording_chunks_enabled,
- recording_max_hours=recording_max_hours)
+ recording_max_hours=recording_max_hours,
+ recording_chunk_seconds=recording_chunk_seconds)
@@ -2427,6 +2475,20 @@ def upload_file():
# Determine MIME type of the final file
mime_type, _ = mimetypes.guess_type(filepath)
+
+ # For a retained-video file, derive the MIME from the file's ACTUAL
+ # container via the shared probe-driven resolver (the same one the
+ # processing task uses) rather than the extension guess, which
+ # mislabels ambiguous containers — notably '.webm', registered as
+ # audio/webm in app.py — and would hide the video player in the UI.
+ # We already have codec_info from the probe above, so no second probe.
+ if keep_video_for_this_upload:
+ from src.utils.mime import resolve_media_mime
+ corrected = resolve_media_mime(filepath, codec_info=codec_info, has_video=True)
+ if corrected != mime_type:
+ current_app.logger.info(f"Resolved video mime {mime_type!r} -> {corrected!r} from container for {filepath}")
+ mime_type = corrected
+
current_app.logger.info(f"Final MIME type: {mime_type} for file {filepath}")
# Get notes from the form
diff --git a/src/tasks/processing.py b/src/tasks/processing.py
index 03d6d1ed..04a00f85 100644
--- a/src/tasks/processing.py
+++ b/src/tasks/processing.py
@@ -1660,9 +1660,12 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_file
current_app.logger.info(f"Video passthrough: sending original video to ASR (no audio extraction)")
actual_filepath = filepath # Send video as-is to connector
if effective_video_retention:
- # Also keep the video for playback
+ # Also keep the video for playback. Derive the MIME from
+ # the file's actual container (we're in the is_video
+ # branch, so has_video=True) rather than guessing.
+ from src.utils.mime import resolve_media_mime
recording.audio_path = filepath
- recording.mime_type = mimetypes.guess_type(filepath)[0] or 'video/mp4'
+ recording.mime_type = resolve_media_mime(filepath, has_video=True)
db.session.commit()
elif effective_video_retention:
# Video retention: keep original video, extract audio to temp for transcription only
@@ -1674,9 +1677,12 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_file
actual_content_type = audio_mime_type
actual_filename = os.path.basename(audio_filepath)
- # Keep original video file as the stored media
+ # Keep original video file as the stored media. Derive
+ # the MIME from the actual container (is_video branch →
+ # has_video=True) instead of guessing from extension.
+ from src.utils.mime import resolve_media_mime
recording.audio_path = filepath
- recording.mime_type = mimetypes.guess_type(filepath)[0] or 'video/mp4'
+ recording.mime_type = resolve_media_mime(filepath, has_video=True)
db.session.commit()
current_app.logger.info(f"Video retained at: {filepath}, temp audio extracted: {audio_filepath}")
except Exception as e:
diff --git a/src/utils/mime.py b/src/utils/mime.py
new file mode 100644
index 00000000..3bc501fb
--- /dev/null
+++ b/src/utils/mime.py
@@ -0,0 +1,133 @@
+"""Shared MIME-type helpers.
+
+Single source of truth for the MIME type of a stored media file. The pipeline
+already probes every file with ffprobe (``get_codec_info``), so we derive the
+MIME from the ACTUAL container + stream contents instead of guessing from the
+filename extension. Guessing is wrong for ambiguous containers — most visibly
+``.webm``, which src/app.py registers as ``audio/webm`` for in-app audio
+recordings, so ``mimetypes.guess_type`` reports audio/webm for EVERY ``.webm``
+even one carrying a video stream (which then hides the video player in the UI).
+
+Order of preference:
+ 1. ffprobe ``format_name`` + ``has_video`` (content truth).
+ 2. extension-based fallback, only when the probe is unavailable.
+"""
+
+import mimetypes
+import os
+
+
+# Extension fallback for files known to carry video, used only when a probe is
+# unavailable. Notably '.webm' (registered as audio/webm in src/app.py).
+_VIDEO_MIME_BY_EXT = {
+ '.webm': 'video/webm',
+ '.ogg': 'video/ogg',
+ '.ogv': 'video/ogg',
+ '.mkv': 'video/x-matroska',
+ '.mov': 'video/quicktime',
+ '.m4v': 'video/x-m4v',
+ '.ts': 'video/mp2t',
+ '.mts': 'video/mp2t',
+}
+
+
+def video_mime_for_path(path):
+ """Extension-based ``video/*`` MIME for a file known to retain video.
+
+ Fallback used when no probe is available. Prefer :func:`resolve_media_mime`,
+ which derives the type from the actual file contents.
+ """
+ guessed, _ = mimetypes.guess_type(path)
+ if guessed and guessed.startswith('video/'):
+ return guessed
+ ext = os.path.splitext(path)[1].lower()
+ return _VIDEO_MIME_BY_EXT.get(ext, 'video/mp4')
+
+
+def _mime_from_format(format_name, has_video, path=''):
+ """Map an ffprobe ``format_name`` (+ ``has_video``) to a MIME type.
+
+ ``format_name`` is a comma-separated list of names the demuxer matched
+ (e.g. ``'matroska,webm'``, ``'mov,mp4,m4a,3gp,3g2,mj2'``). Containers that
+ can hold either audio or video (webm/matroska, mp4, ogg, asf) pick the
+ video or audio MIME from ``has_video``. Returns ``None`` for an
+ unrecognised container so the caller can fall back.
+ """
+ fmt = (format_name or '').lower()
+ ext = os.path.splitext(path or '')[1].lower()
+
+ def matches(*names):
+ return any(n in fmt for n in names)
+
+ if matches('webm', 'matroska'):
+ # One demuxer covers both; the extension disambiguates webm vs mkv.
+ if has_video:
+ return 'video/x-matroska' if ext == '.mkv' else 'video/webm'
+ return 'audio/x-matroska' if ext == '.mkv' else 'audio/webm'
+ if matches('mp4', 'mov', 'm4a', '3gp', '3g2', 'mj2'):
+ return 'video/mp4' if has_video else 'audio/mp4'
+ if matches('ogg'):
+ return 'video/ogg' if has_video else 'audio/ogg'
+ if matches('asf'): # Windows Media (wmv / wma)
+ return 'video/x-ms-wmv' if has_video else 'audio/x-ms-wma'
+ if matches('mp3'):
+ return 'audio/mpeg'
+ if matches('flac'):
+ return 'audio/flac'
+ if matches('wav', 'wave'):
+ return 'audio/wav'
+ if matches('aiff', 'aif'):
+ return 'audio/aiff'
+ if matches('aac', 'adts'):
+ return 'audio/aac'
+ if matches('avi'):
+ return 'video/x-msvideo'
+ if matches('flv'):
+ return 'video/x-flv'
+ if matches('mpegts', 'mpeg-ts', 'mp2t'):
+ return 'video/mp2t'
+ return None
+
+
+def resolve_media_mime(path, codec_info=None, has_video=None, timeout=10):
+ """Authoritative MIME for a stored media file, derived from its contents.
+
+ Args:
+ path: the stored media file.
+ codec_info: a pre-fetched ``get_codec_info`` dict, if the caller has
+ one (avoids a second probe).
+ has_video: caller's authoritative video flag. Overrides the probe's
+ own ``has_video`` when provided (e.g. a retention branch that has
+ already decided the file is video). ``None`` = trust the probe.
+ timeout: ffprobe timeout when this function does its own probe.
+
+ Falls back to an extension-based guess only when no probe data is
+ available (probe failed / ffprobe missing).
+ """
+ fmt = None
+ hv = has_video
+ if codec_info:
+ fmt = codec_info.get('format_name')
+ if hv is None:
+ hv = bool(codec_info.get('has_video'))
+ if fmt is None:
+ try:
+ from src.utils.ffprobe import get_codec_info
+ info = get_codec_info(path, timeout=timeout)
+ if info:
+ fmt = info.get('format_name')
+ if hv is None:
+ hv = bool(info.get('has_video'))
+ except Exception:
+ pass
+
+ if fmt:
+ m = _mime_from_format(fmt, bool(hv), path)
+ if m:
+ return m
+
+ # No usable probe data — fall back to the filename.
+ if hv:
+ return video_mime_for_path(path)
+ guessed, _ = mimetypes.guess_type(path)
+ return guessed or 'application/octet-stream'
diff --git a/tests/test_inquire_mode.py b/tests/test_inquire_mode.py
index 7bb7f967..2ce0dacf 100644
--- a/tests/test_inquire_mode.py
+++ b/tests/test_inquire_mode.py
@@ -150,6 +150,36 @@ def test_api_imports():
assert callable(fn), f"{getattr(fn, '__name__', fn)} is not callable"
+def test_speaker_and_transcript_edits_reindex_inquire_chunks():
+ """Editing a transcript or applying speaker names must rebuild the Inquire
+ chunks; otherwise semantic search keeps answering from the stale pre-edit
+ text (e.g. 'SPEAKER_00' instead of the applied name)."""
+ import inspect as _inspect
+ from src.api import recordings as rec
+
+ assert hasattr(rec, 'reindex_recording_chunks_async'), "reindex helper missing"
+ us = _inspect.getsource(rec.update_speakers)
+ ut = _inspect.getsource(rec.update_transcript)
+ assert 'reindex_recording_chunks_async(recording_id)' in us, \
+ "update_speakers must reindex Inquire chunks after a speaker rename"
+ assert 'reindex_recording_chunks_async(recording_id)' in ut, \
+ "update_transcript must reindex Inquire chunks after a transcript edit"
+
+
+def test_reindex_is_noop_when_inquire_disabled():
+ """The reindex helper is a guarded no-op when Inquire mode is off, so it
+ never spawns work or errors on installs without an embedding backend."""
+ from unittest.mock import patch
+ from src.api import recordings as rec
+
+ with patch.object(rec, 'ENABLE_INQUIRE_MODE', False), \
+ patch.object(rec, 'process_recording_chunks') as pc, \
+ patch('threading.Thread') as th:
+ rec.reindex_recording_chunks_async(123)
+ pc.assert_not_called()
+ th.assert_not_called()
+
+
def main():
"""Run all tests (standalone, without pytest)."""
print("Starting Inquire Mode Tests...\n")
@@ -158,6 +188,8 @@ def main():
("Database Models", test_database_models),
("Chunking Functions", test_chunking_functions),
("API Imports", test_api_imports),
+ ("Edits Reindex Chunks", test_speaker_and_transcript_edits_reindex_inquire_chunks),
+ ("Reindex No-op When Disabled", test_reindex_is_noop_when_inquire_disabled),
]
all_passed = True
diff --git a/tests/test_video_passthrough.py b/tests/test_video_passthrough.py
index aeec7363..d28481ba 100644
--- a/tests/test_video_passthrough.py
+++ b/tests/test_video_passthrough.py
@@ -168,7 +168,9 @@ class TestProcessingMainPath(unittest.TestCase):
self.assertIn('if effective_video_retention:', passthrough_block,
"Passthrough branch should conditionally handle retention")
self.assertIn('recording.audio_path = filepath', passthrough_block)
- self.assertIn("mimetypes.guess_type(filepath)", passthrough_block)
+ # mime_type is derived from the actual container via the shared
+ # probe-driven resolver (corrects audio/webm-style mislabels).
+ self.assertIn('recording.mime_type = resolve_media_mime(filepath, has_video=True)', passthrough_block)
def test_video_passthrough_active_flag_set(self):
"""video_passthrough_active flag is computed from is_video and VIDEO_PASSTHROUGH_ASR."""
diff --git a/tests/test_video_retention.py b/tests/test_video_retention.py
index f672c05c..e597519f 100644
--- a/tests/test_video_retention.py
+++ b/tests/test_video_retention.py
@@ -104,8 +104,12 @@ class TestProcessingPipelineVideoRetention(unittest.TestCase):
self.assertIn('audio_filepath = None', self.content)
def test_video_mime_type_set_for_retention(self):
- """When retaining video, mime_type reflects actual video type."""
- self.assertIn("mimetypes.guess_type(filepath)[0] or 'video/mp4'", self.content)
+ """When retaining video, mime_type is derived from the file's actual
+ container via the shared probe-driven resolver (not a guess, which
+ mislabels ambiguous containers like .webm as audio/webm and hid the
+ video player in the UI)."""
+ self.assertIn('recording.mime_type = resolve_media_mime(filepath, has_video=True)', self.content)
+ self.assertNotIn("mimetypes.guess_type(filepath)[0] or 'video/mp4'", self.content)
def test_duration_uses_recording_audio_path(self):
"""Duration lookup uses recording.audio_path (always valid), not filepath."""
@@ -458,5 +462,87 @@ class TestVideoRetentionMatrix(unittest.TestCase):
"convert_if_needed must run after video extraction block")
+class TestVideoMimeHelper(unittest.TestCase):
+ """Behavioural tests for the shared video_mime_for_path helper.
+
+ Pins the actual bug: a .webm with video must resolve to video/webm even
+ though src/app.py registers .webm as audio/webm for in-app audio
+ recordings (which makes mimetypes.guess_type return audio/webm).
+ """
+
+ @classmethod
+ def setUpClass(cls):
+ # Import app first so its mimetypes.add_type('audio/webm', '.webm')
+ # registration is in effect — the exact condition that caused the bug.
+ import src.app # noqa: F401
+ from src.utils.mime import video_mime_for_path
+ cls.video_mime_for_path = staticmethod(video_mime_for_path)
+
+ def test_webm_with_video_resolves_to_video_webm(self):
+ # This is the regression: guess_type would say audio/webm here.
+ import mimetypes
+ self.assertEqual(mimetypes.guess_type('x.webm')[0], 'audio/webm')
+ self.assertEqual(self.video_mime_for_path('/data/uploads/x.webm'), 'video/webm')
+
+ def test_mp4_resolves_to_video_mp4(self):
+ self.assertEqual(self.video_mime_for_path('/data/uploads/clip.mp4'), 'video/mp4')
+
+ def test_known_video_containers(self):
+ cases = {
+ '/a/b.mkv': 'video/x-matroska',
+ '/a/b.mov': 'video/quicktime',
+ '/a/b.m4v': 'video/x-m4v',
+ '/a/b.ts': 'video/mp2t',
+ }
+ for path, expected in cases.items():
+ self.assertEqual(self.video_mime_for_path(path), expected, path)
+
+ def test_unknown_extension_defaults_to_video_mp4(self):
+ self.assertEqual(self.video_mime_for_path('/a/b.weirdext'), 'video/mp4')
+
+
+class TestProbeDrivenMime(unittest.TestCase):
+ """The probe-driven mapper: ffprobe format_name + has_video -> MIME.
+
+ This is the real architectural fix — derive the MIME from the file's
+ actual container/streams instead of guessing from the extension.
+ """
+
+ @classmethod
+ def setUpClass(cls):
+ from src.utils.mime import _mime_from_format
+ cls.f = staticmethod(_mime_from_format)
+
+ def test_webm_container_audio_vs_video(self):
+ # Same container, decided by has_video — the exact bug case.
+ self.assertEqual(self.f('matroska,webm', True, '/x.webm'), 'video/webm')
+ self.assertEqual(self.f('matroska,webm', False, '/x.webm'), 'audio/webm')
+
+ def test_matroska_vs_webm_by_extension(self):
+ self.assertEqual(self.f('matroska,webm', True, '/x.mkv'), 'video/x-matroska')
+
+ def test_mp4_family(self):
+ self.assertEqual(self.f('mov,mp4,m4a,3gp,3g2,mj2', True, '/x.mp4'), 'video/mp4')
+ self.assertEqual(self.f('mov,mp4,m4a,3gp,3g2,mj2', False, '/x.m4a'), 'audio/mp4')
+
+ def test_audio_only_containers(self):
+ self.assertEqual(self.f('mp3', False, '/x.mp3'), 'audio/mpeg')
+ self.assertEqual(self.f('flac', False, '/x.flac'), 'audio/flac')
+ self.assertEqual(self.f('wav', False, '/x.wav'), 'audio/wav')
+ self.assertEqual(self.f('ogg', False, '/x.ogg'), 'audio/ogg')
+
+ def test_video_only_containers(self):
+ self.assertEqual(self.f('avi', True, '/x.avi'), 'video/x-msvideo')
+ self.assertEqual(self.f('flv', True, '/x.flv'), 'video/x-flv')
+ self.assertEqual(self.f('mpegts', True, '/x.ts'), 'video/mp2t')
+
+ def test_asf_audio_vs_video(self):
+ self.assertEqual(self.f('asf', True, '/x.wmv'), 'video/x-ms-wmv')
+ self.assertEqual(self.f('asf', False, '/x.wma'), 'audio/x-ms-wma')
+
+ def test_unknown_container_returns_none(self):
+ self.assertIsNone(self.f('some_weird_format', False, '/x.bin'))
+
+
if __name__ == '__main__':
unittest.main(verbosity=2)