Skip to content

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

Python

Fix bulk delete cascade, file monitor stability cap, speaker snippet creation, and preserve speaker profiles by default

Murtaza Nasir12a6ef6bcf7a
diff --git a/config/env.asr.example b/config/env.asr.example
index a4d56d7e..4b81276e 100644
--- a/config/env.asr.example
+++ b/config/env.asr.example
@@ -165,6 +165,10 @@ AUTO_PROCESS_WATCH_DIR=/data/auto-process
# How often to check for new files (seconds)
AUTO_PROCESS_CHECK_INTERVAL=30
+# How long to wait (seconds) to confirm a file has stopped changing before processing.
+# Increase for slow network transfers (NFS, SMB). Default: 5
+# AUTO_PROCESS_STABILITY_TIME=5
+
# Default username for single_user mode (only used if AUTO_PROCESS_MODE=single_user)
# AUTO_PROCESS_DEFAULT_USERNAME=admin
@@ -187,6 +191,12 @@ DELETION_MODE=audio_only
# false: Only admins can delete recordings
USERS_CAN_DELETE=true
+# Delete speaker profiles when all their recordings are removed.
+# Default: false (speaker profiles and voice embeddings are preserved)
+# Set to true for privacy-sensitive deployments where biometric voice data
+# should not outlive the recordings it was derived from.
+# DELETE_ORPHANED_SPEAKERS=false
+
# --- Internal Sharing Settings ---
# Enable user-to-user sharing of recordings (works independently of groups)
ENABLE_INTERNAL_SHARING=false
diff --git a/config/env.transcription.example b/config/env.transcription.example
index 05c88919..5fb40286 100644
--- a/config/env.transcription.example
+++ b/config/env.transcription.example
@@ -229,6 +229,12 @@ ENABLE_PUBLIC_SHARING=true
# --- Permission Controls ---
USERS_CAN_DELETE=true
+# Delete speaker profiles when all their recordings are removed.
+# Default: false (speaker profiles and voice embeddings are preserved)
+# Set to true for privacy-sensitive deployments where biometric voice data
+# should not outlive the recordings it was derived from.
+# DELETE_ORPHANED_SPEAKERS=false
+
# =============================================================================
# BACKGROUND PROCESSING
# =============================================================================
diff --git a/config/env.whisper.example b/config/env.whisper.example
index b2296293..790e4739 100644
--- a/config/env.whisper.example
+++ b/config/env.whisper.example
@@ -162,6 +162,10 @@ AUTO_PROCESS_WATCH_DIR=/data/auto-process
# How often to check for new files (seconds)
AUTO_PROCESS_CHECK_INTERVAL=30
+# How long to wait (seconds) to confirm a file has stopped changing before processing.
+# Increase for slow network transfers (NFS, SMB). Default: 5
+# AUTO_PROCESS_STABILITY_TIME=5
+
# Default username for single_user mode (only used if AUTO_PROCESS_MODE=single_user)
# AUTO_PROCESS_DEFAULT_USERNAME=admin
@@ -184,6 +188,12 @@ DELETION_MODE=audio_only
# false: Only admins can delete recordings
USERS_CAN_DELETE=true
+# Delete speaker profiles when all their recordings are removed.
+# Default: false (speaker profiles and voice embeddings are preserved)
+# Set to true for privacy-sensitive deployments where biometric voice data
+# should not outlive the recordings it was derived from.
+# DELETE_ORPHANED_SPEAKERS=false
+
# --- Internal Sharing Settings ---
# Enable user-to-user sharing of recordings (works independently of groups)
ENABLE_INTERNAL_SHARING=false
diff --git a/config/env.whisperx.example b/config/env.whisperx.example
index 229c3c47..b0a564e1 100644
--- a/config/env.whisperx.example
+++ b/config/env.whisperx.example
@@ -160,6 +160,10 @@ AUTO_PROCESS_WATCH_DIR=/data/auto-process
# How often to check for new files (seconds)
AUTO_PROCESS_CHECK_INTERVAL=30
+# How long to wait (seconds) to confirm a file has stopped changing before processing.
+# Increase for slow network transfers (NFS, SMB). Default: 5
+# AUTO_PROCESS_STABILITY_TIME=5
+
# Default username for single_user mode (only used if AUTO_PROCESS_MODE=single_user)
# AUTO_PROCESS_DEFAULT_USERNAME=admin
@@ -182,6 +186,12 @@ DELETION_MODE=audio_only
# false: Only admins can delete recordings
USERS_CAN_DELETE=true
+# Delete speaker profiles when all their recordings are removed.
+# Default: false (speaker profiles and voice embeddings are preserved)
+# Set to true for privacy-sensitive deployments where biometric voice data
+# should not outlive the recordings it was derived from.
+# DELETE_ORPHANED_SPEAKERS=false
+
# --- Internal Sharing Settings ---
# Enable user-to-user sharing of recordings (works independently of groups)
ENABLE_INTERNAL_SHARING=false
diff --git a/src/api/recordings.py b/src/api/recordings.py
index 7691bf55..c3c301e1 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -2527,7 +2527,12 @@ def delete_recording(recording_id):
if chunk_count > 0:
current_app.logger.info(f"Deleting {chunk_count} transcript chunks with embeddings for recording {recording_id}")
- # Delete associated processing jobs (required because recording_id is NOT NULL)
+ # Delete associated records with NOT NULL recording_id constraints
+ from src.models.speaker_snippet import SpeakerSnippet
+ deleted_snippets = SpeakerSnippet.query.filter_by(recording_id=recording_id).delete()
+ if deleted_snippets > 0:
+ current_app.logger.info(f"Deleted {deleted_snippets} speaker snippets for recording {recording_id}")
+
from src.models.processing_job import ProcessingJob
deleted_jobs = ProcessingJob.query.filter_by(recording_id=recording_id).delete()
if deleted_jobs > 0:
@@ -3457,8 +3462,10 @@ def bulk_delete_recordings():
except Exception as e:
current_app.logger.error(f"Error deleting audio file {recording.audio_path}: {e}")
- # Delete associated processing jobs
+ # Delete associated records with NOT NULL recording_id constraints
from src.models import ProcessingJob
+ from src.models.speaker_snippet import SpeakerSnippet
+ SpeakerSnippet.query.filter_by(recording_id=recording_id).delete()
ProcessingJob.query.filter_by(recording_id=recording_id).delete()
# Delete the recording
diff --git a/src/file_monitor.py b/src/file_monitor.py
index ee7238ed..10f7b6ba 100644
--- a/src/file_monitor.py
+++ b/src/file_monitor.py
@@ -180,8 +180,9 @@ class FileMonitor:
continue
# Check if file is still being written (size stability check)
+ stability_time = int(os.environ.get('AUTO_PROCESS_STABILITY_TIME', '5'))
try:
- if not self._is_file_stable(file_path):
+ if not self._is_file_stable(file_path, stability_time):
continue
except FileNotFoundError:
# File might have been picked up by another worker after iterdir()
@@ -261,7 +262,7 @@ class FileMonitor:
initial_mtime = file_path.stat().st_mtime
# Wait a bit and check again
- time.sleep(min(stability_time, 2))
+ time.sleep(stability_time)
current_size = file_path.stat().st_size
current_mtime = file_path.stat().st_mtime
diff --git a/src/models/speaker_snippet.py b/src/models/speaker_snippet.py
index 1accbfc4..53d77793 100644
--- a/src/models/speaker_snippet.py
+++ b/src/models/speaker_snippet.py
@@ -25,7 +25,7 @@ class SpeakerSnippet(db.Model):
# Relationships
speaker = db.relationship('Speaker', backref=db.backref('snippets', lazy=True, cascade='all, delete-orphan'))
- recording = db.relationship('Recording', backref=db.backref('speaker_snippets', lazy=True))
+ recording = db.relationship('Recording', backref=db.backref('speaker_snippets', lazy=True, cascade='all, delete-orphan'))
def to_dict(self):
"""Convert model to dictionary representation."""
diff --git a/src/services/speaker_cleanup.py b/src/services/speaker_cleanup.py
index 7e6be6bc..80c147a9 100644
--- a/src/services/speaker_cleanup.py
+++ b/src/services/speaker_cleanup.py
@@ -3,8 +3,14 @@ Speaker cleanup service for managing orphaned speaker voice profiles.
This module provides automatic cleanup of speaker records when their associated
recordings are deleted through auto-deletion or manual deletion processes.
+
+By default, speaker profiles (including voice embeddings) are preserved even
+when all their recordings are deleted, since embeddings are aggregated and
+represent hours of manual identification work. Set DELETE_ORPHANED_SPEAKERS=true
+to enable automatic cleanup of speakers with no remaining recordings.
"""
+import os
import logging
import json
from datetime import datetime
@@ -19,6 +25,10 @@ def cleanup_orphaned_speakers(dry_run=False):
"""
Clean up speaker records that no longer have any associated recordings.
+ Only runs if DELETE_ORPHANED_SPEAKERS=true is set. By default, speaker
+ profiles are preserved because voice embeddings are aggregated values
+ that can't be reconstructed from recordings alone.
+
A speaker is considered orphaned when:
- It has no SpeakerSnippet records
- Its embeddings_history contains no valid recording references
@@ -35,6 +45,17 @@ def cleanup_orphaned_speakers(dry_run=False):
'orphaned_speakers': list of dict (if dry_run=True)
}
"""
+ delete_orphans = os.environ.get('DELETE_ORPHANED_SPEAKERS', 'false').lower() in ('true', '1', 'yes')
+
+ if not delete_orphans:
+ logger.debug("Speaker cleanup skipped (DELETE_ORPHANED_SPEAKERS is not enabled)")
+ return {
+ 'speakers_deleted': 0,
+ 'embeddings_removed': 0,
+ 'speakers_evaluated': 0,
+ 'orphaned_speakers': []
+ }
+
logger.info("Starting speaker cleanup process (dry_run=%s)", dry_run)
stats = {
diff --git a/src/services/speaker_snippets.py b/src/services/speaker_snippets.py
index 3196f2e9..3263a54a 100644
--- a/src/services/speaker_snippets.py
+++ b/src/services/speaker_snippets.py
@@ -15,13 +15,17 @@ import json
from src.database import db
from src.models import Speaker, SpeakerSnippet, Recording
+MAX_SNIPPETS_PER_SPEAKER = 7
+MAX_SNIPPETS_PER_RECORDING = 2
+
def create_speaker_snippets(recording_id, speaker_map):
"""
Extract and store representative snippets for each identified speaker.
This function is called after a user saves speaker identifications in a recording.
- It extracts 3-5 representative quotes per speaker for display in speaker profiles.
+ It extracts up to MAX_SNIPPETS_PER_RECORDING quotes per speaker from this recording,
+ and enforces a global cap of MAX_SNIPPETS_PER_SPEAKER by evicting the oldest.
Args:
recording_id: ID of the recording
@@ -40,19 +44,34 @@ def create_speaker_snippets(recording_id, speaker_map):
except (json.JSONDecodeError, TypeError):
return 0
- snippets_created = 0
+ # Build a reverse map: assigned name -> speaker_info
+ # After transcript is saved, segment['speaker'] contains the real name,
+ # not the original SPEAKER_XX label. We need to match by name too.
+ name_to_info = {}
+ for label, info in speaker_map.items():
+ name = info.get('name', '').strip()
+ if name and not name.startswith('SPEAKER_'):
+ name_to_info[name] = info
+
+ # Collect candidates per speaker: (speaker_obj, segment_idx, text, timestamp)
+ candidates = {} # speaker_id -> list of (segment_idx, text, timestamp)
for segment_idx, segment in enumerate(transcript):
- speaker_label = segment.get('speaker') # SPEAKER_00, SPEAKER_01, etc.
+ speaker_field = segment.get('speaker')
- if not speaker_label or speaker_label not in speaker_map:
+ if not speaker_field:
continue
- speaker_info = speaker_map[speaker_label]
- speaker_name = speaker_info.get('name')
+ # Try matching by original label first, then by assigned name
+ if speaker_field in speaker_map:
+ speaker_info = speaker_map[speaker_field]
+ speaker_name = speaker_info.get('name')
+ elif speaker_field in name_to_info:
+ speaker_name = speaker_field
+ else:
+ continue
if not speaker_name or speaker_name.startswith('SPEAKER_'):
- # Skip if not actually identified
continue
# Find the speaker in database
@@ -64,32 +83,50 @@ def create_speaker_snippets(recording_id, speaker_map):
if not speaker:
continue
- # Limit to 5 snippets per recording per speaker
- existing_count = SpeakerSnippet.query.filter_by(
- speaker_id=speaker.id,
- recording_id=recording_id
- ).count()
-
- if existing_count >= 5:
- continue
-
- # Get the text (limit to 200 chars)
text = segment.get('sentence', '').strip()
- if len(text) < 10: # Skip very short segments
+ if len(text) < 10:
continue
- text_snippet = text[:200]
-
- # Create snippet
- snippet = SpeakerSnippet(
- speaker_id=speaker.id,
- recording_id=recording_id,
- segment_index=segment_idx,
- text_snippet=text_snippet,
- timestamp=segment.get('start_time')
- )
- db.session.add(snippet)
- snippets_created += 1
+ if speaker.id not in candidates:
+ candidates[speaker.id] = []
+ candidates[speaker.id].append((segment_idx, text[:200], segment.get('start_time')))
+
+ # Delete existing snippets for this recording (re-save replaces them)
+ SpeakerSnippet.query.filter_by(recording_id=recording_id).delete()
+
+ snippets_created = 0
+
+ for speaker_id, segs in candidates.items():
+ # Pick up to MAX_SNIPPETS_PER_RECORDING spread across the transcript
+ if len(segs) <= MAX_SNIPPETS_PER_RECORDING:
+ chosen = segs
+ else:
+ # Evenly sample from the segments
+ step = len(segs) / MAX_SNIPPETS_PER_RECORDING
+ chosen = [segs[int(i * step)] for i in range(MAX_SNIPPETS_PER_RECORDING)]
+
+ for segment_idx, text_snippet, timestamp in chosen:
+ # Evict oldest if at global cap
+ global_count = SpeakerSnippet.query.filter_by(speaker_id=speaker_id).count()
+ if global_count >= MAX_SNIPPETS_PER_SPEAKER:
+ oldest = SpeakerSnippet.query.filter_by(speaker_id=speaker_id)\
+ .order_by(SpeakerSnippet.created_at.asc()).first()
+ if oldest:
+ db.session.delete(oldest)
+ db.session.flush()
+
+ snippet = SpeakerSnippet(
+ speaker_id=speaker_id,
+ recording_id=recording_id,
+ segment_index=segment_idx,
+ text_snippet=text_snippet,
+ timestamp=timestamp,
+ )
+ db.session.add(snippet)
+ snippets_created += 1
+
+ # Flush after each speaker batch to keep counts accurate
+ db.session.flush()
if snippets_created > 0:
db.session.commit()
diff --git a/tests/test_bugfixes.py b/tests/test_bugfixes.py
new file mode 100644
index 00000000..1737c1f4
--- /dev/null
+++ b/tests/test_bugfixes.py
@@ -0,0 +1,239 @@
+#!/usr/bin/env python3
+"""
+Tests for specific bug fixes.
+
+- Issue #230: Bulk delete crash when recordings have speaker_snippets
+- Issue #223: File monitor stability time env var
+"""
+
+import json
+import os
+import sys
+import time
+import tempfile
+from pathlib import Path
+from unittest.mock import patch, MagicMock
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from src.app import app, db
+from src.models import User, Recording
+from src.models.speaker_snippet import SpeakerSnippet
+
+# Disable CSRF for testing
+app.config['WTF_CSRF_ENABLED'] = False
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+def _get_or_create_user():
+ user = User.query.filter_by(username="bugfix_test_user").first()
+ if not user:
+ user = User(username="bugfix_test_user", email="[email protected]")
+ db.session.add(user)
+ db.session.commit()
+ return user
+
+
+def _create_recording_with_snippets(user):
+ """Create a recording that has speaker_snippet records attached."""
+ rec = Recording(
+ user_id=user.id,
+ title="Recording with snippets",
+ status="COMPLETED",
+ transcription=json.dumps([
+ {"speaker": "SPEAKER_00", "sentence": "Hello there."},
+ ]),
+ )
+ db.session.add(rec)
+ db.session.commit()
+
+ # We need a speaker to attach snippets to
+ from src.models import Speaker
+ speaker = Speaker.query.filter_by(user_id=user.id, name="BugfixTestSpeaker").first()
+ if not speaker:
+ speaker = Speaker(name="BugfixTestSpeaker", user_id=user.id)
+ db.session.add(speaker)
+ db.session.commit()
+
+ snippet = SpeakerSnippet(
+ speaker_id=speaker.id,
+ recording_id=rec.id,
+ segment_index=0,
+ text_snippet="Hello there.",
+ )
+ db.session.add(snippet)
+ db.session.commit()
+
+ return rec, speaker, snippet
+
+
+# ---------------------------------------------------------------------------
+# Issue #230: Deleting recordings with speaker_snippets
+# ---------------------------------------------------------------------------
+
+class TestIssue230BulkDeleteCascade:
+ """Verify that deleting a recording with speaker_snippets doesn't crash."""
+
+ def test_single_delete_with_snippets(self):
+ """Single DELETE /recording/<id> should succeed when snippets exist."""
+ with app.app_context():
+ user = _get_or_create_user()
+ rec, speaker, snippet = _create_recording_with_snippets(user)
+ rec_id = rec.id
+ snippet_id = snippet.id
+
+ with app.test_client() as client:
+ # Login
+ with client.session_transaction() as sess:
+ sess['_user_id'] = str(user.id)
+
+ resp = client.delete(f'/recording/{rec_id}')
+ assert resp.status_code == 200, f"Delete failed: {resp.get_json()}"
+ data = resp.get_json()
+ assert data.get('success') is True
+
+ # Verify snippet was also deleted
+ orphan = db.session.get(SpeakerSnippet, snippet_id)
+ assert orphan is None, "Speaker snippet should have been deleted with recording"
+
+ # Cleanup speaker
+ db.session.delete(speaker)
+ db.session.commit()
+
+ def test_bulk_delete_with_snippets(self):
+ """DELETE /api/recordings/bulk should succeed when snippets exist."""
+ with app.app_context():
+ user = _get_or_create_user()
+ rec, speaker, snippet = _create_recording_with_snippets(user)
+ rec_id = rec.id
+ snippet_id = snippet.id
+
+ with app.test_client() as client:
+ with client.session_transaction() as sess:
+ sess['_user_id'] = str(user.id)
+
+ resp = client.delete(
+ '/api/recordings/bulk',
+ json={'recording_ids': [rec_id]},
+ content_type='application/json',
+ )
+ assert resp.status_code == 200, f"Bulk delete failed: {resp.get_json()}"
+ data = resp.get_json()
+ assert data.get('success') is True
+ assert rec_id in data.get('deleted_ids', [])
+
+ # Verify snippet was also deleted
+ orphan = db.session.get(SpeakerSnippet, snippet_id)
+ assert orphan is None, "Speaker snippet should have been deleted with recording"
+
+ # Cleanup speaker
+ db.session.delete(speaker)
+ db.session.commit()
+
+ def test_bulk_delete_multiple_with_snippets(self):
+ """Bulk deleting multiple recordings (some with snippets) should succeed."""
+ with app.app_context():
+ user = _get_or_create_user()
+ rec1, speaker, snippet = _create_recording_with_snippets(user)
+ rec2 = Recording(user_id=user.id, title="No snippets", status="COMPLETED")
+ db.session.add(rec2)
+ db.session.commit()
+
+ rec1_id, rec2_id = rec1.id, rec2.id
+
+ with app.test_client() as client:
+ with client.session_transaction() as sess:
+ sess['_user_id'] = str(user.id)
+
+ resp = client.delete(
+ '/api/recordings/bulk',
+ json={'recording_ids': [rec1_id, rec2_id]},
+ content_type='application/json',
+ )
+ assert resp.status_code == 200, f"Bulk delete failed: {resp.get_json()}"
+ data = resp.get_json()
+ assert data.get('deleted_count') == 2
+
+ # Cleanup speaker
+ db.session.delete(speaker)
+ db.session.commit()
+
+
+# ---------------------------------------------------------------------------
+# Issue #223: File monitor stability time
+# ---------------------------------------------------------------------------
+
+class TestIssue223StabilityTime:
+ """Verify AUTO_PROCESS_STABILITY_TIME env var is respected."""
+
+ def test_default_stability_time(self):
+ """Without env var, stability_time defaults to 5."""
+ from src.file_monitor import FileMonitor
+ monitor = FileMonitor.__new__(FileMonitor)
+ monitor.logger = MagicMock()
+
+ with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as f:
+ f.write(b'fake audio data')
+ tmp_path = Path(f.name)
+
+ try:
+ with patch.dict(os.environ, {}, clear=False):
+ # Remove the env var if it exists
+ os.environ.pop('AUTO_PROCESS_STABILITY_TIME', None)
+ with patch('time.sleep') as mock_sleep:
+ monitor._is_file_stable(tmp_path)
+ mock_sleep.assert_called_once_with(5)
+ finally:
+ tmp_path.unlink(missing_ok=True)
+
+ def test_custom_stability_time(self):
+ """AUTO_PROCESS_STABILITY_TIME=15 should sleep for 15 seconds."""
+ from src.file_monitor import FileMonitor
+ monitor = FileMonitor.__new__(FileMonitor)
+ monitor.logger = MagicMock()
+
+ with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as f:
+ f.write(b'fake audio data')
+ tmp_path = Path(f.name)
+
+ try:
+ with patch.dict(os.environ, {'AUTO_PROCESS_STABILITY_TIME': '15'}):
+ with patch('time.sleep') as mock_sleep:
+ # _is_file_stable uses the default param, but the caller reads env
+ # So we test the caller path via _scan_user_directory indirectly
+ # or just call with explicit value
+ stability_time = int(os.environ.get('AUTO_PROCESS_STABILITY_TIME', '5'))
+ monitor._is_file_stable(tmp_path, stability_time)
+ mock_sleep.assert_called_once_with(15)
+ finally:
+ tmp_path.unlink(missing_ok=True)
+
+ def test_no_hardcoded_cap(self):
+ """Stability time should NOT be capped at 2 seconds anymore."""
+ from src.file_monitor import FileMonitor
+ monitor = FileMonitor.__new__(FileMonitor)
+ monitor.logger = MagicMock()
+
+ with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as f:
+ f.write(b'fake audio data')
+ tmp_path = Path(f.name)
+
+ try:
+ with patch('time.sleep') as mock_sleep:
+ monitor._is_file_stable(tmp_path, stability_time=30)
+ # Should sleep for 30, NOT min(30, 2) = 2
+ mock_sleep.assert_called_once_with(30)
+ finally:
+ tmp_path.unlink(missing_ok=True)
+
+
+# ---------------------------------------------------------------------------
+# Runner
+# ---------------------------------------------------------------------------
+
+if __name__ == "__main__":
+ import pytest
+ sys.exit(pytest.main([__file__, "-v"]))