Skip to content

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

Python

Voice training commits separately from the save it follows and rolls back as a whole on failure (the label map is still kept); a savepoint was tried and dropped because it holds the SQLite write lock through training

Murtaza Nasir7308b9a5f734
diff --git a/src/services/speaker.py b/src/services/speaker.py
index 377b261d..55ef2cfe 100644
--- a/src/services/speaker.py
+++ b/src/services/speaker.py
@@ -89,23 +89,39 @@ def update_voice_profiles(recording, label_to_name, user, seconds_by_key=None):
measured before the rename (None when the transcript has no timing).
Both save routes and API v1 call this. Returns
(samples_stored, snippets_created). Never raises.
+
+ Commits: the caller's changes first, so they stand on their own, then the
+ training, which is rolled back as a whole if it fails partway.
+ (A savepoint would hold SQLite's write lock through the training and
+ collide with background writers.)
"""
from src.services.speaker_snippets import create_speaker_snippets
- from src.services.voice_profiles import apply_names_to_profiles
+ from src.services.voice_profiles import apply_names_to_profiles, record_label_names
stored = 0
snippets_created = 0
- try:
- # Runs even when nothing was named: a save that only merged speakers
- # away must still drop the merged labels' samples.
- if recording.speaker_embeddings:
+ # Runs even when nothing was named: a save that only merged speakers
+ # away must still drop the merged labels' samples.
+ if recording.speaker_embeddings:
+ db.session.commit()
+ try:
stats = apply_names_to_profiles(recording, label_to_name or {}, seconds_by_key, user)
+ db.session.commit()
stored = stats['stored']
if stats['rejected'] or stats['skipped_short']:
current_app.logger.info(
f"Recording {recording.id}: {stats['rejected']} voice samples kept out as unlike "
f"the named person, {stats['skipped_short']} skipped for too little speech")
- db.session.flush()
+ except Exception as e:
+ db.session.rollback()
+ current_app.logger.error(f"Error updating voice profiles: {e}", exc_info=True)
+ try:
+ record_label_names(recording, label_to_name or {})
+ db.session.commit()
+ except Exception as e2:
+ db.session.rollback()
+ current_app.logger.error(f"Error saving the speaker label map: {e2}", exc_info=True)
+ try:
if not label_to_name:
return stored, 0
snippets_created = create_speaker_snippets(
@@ -113,7 +129,7 @@ def update_voice_profiles(recording, label_to_name, user, seconds_by_key=None):
if snippets_created > 0:
current_app.logger.info(f"Created {snippets_created} speaker snippets")
except Exception as e:
- current_app.logger.error(f"Error updating voice profiles: {e}", exc_info=True)
+ current_app.logger.error(f"Error creating speaker snippets: {e}", exc_info=True)
return stored, snippets_created
diff --git a/src/services/voice_profiles.py b/src/services/voice_profiles.py
index cd66e738..bf307e55 100644
--- a/src/services/voice_profiles.py
+++ b/src/services/voice_profiles.py
@@ -645,6 +645,27 @@ def auto_label_threshold(setting, space_id):
# ------------------------------------------------------ applying names
+def _labels_for(key, embeddings, label_map):
+ """The diarization labels a speaker value in the transcript stands for."""
+ if key in embeddings:
+ return [key]
+ return [lab for lab, name in label_map.items() if name == key and lab in embeddings]
+
+
+def record_label_names(recording, key_to_name):
+ """Update only the recording's label map with the names given in a save.
+
+ Used when training fails, so the map still follows the transcript and a
+ later correction can reach the embedding. Does not commit.
+ """
+ embeddings = load_embeddings(recording)
+ label_map = dict(recording.speaker_label_map or {})
+ for key, name in key_to_name.items():
+ for label in _labels_for(key, embeddings, label_map):
+ label_map[label] = name
+ recording.speaker_label_map = label_map or None
+
+
def apply_names_to_profiles(recording, key_to_name, seconds_by_key, user, source='confirmed'):
"""Train voice profiles from the names given in one save.
@@ -667,14 +688,9 @@ def apply_names_to_profiles(recording, key_to_name, seconds_by_key, user, source
embeddings = load_embeddings(recording)
label_map = dict(recording.speaker_label_map or {})
- def labels_for(key):
- if key in embeddings:
- return [key]
- return [lab for lab, name in label_map.items() if name == key and lab in embeddings]
-
touched = set()
for key, name in key_to_name.items():
- for label in labels_for(key):
+ for label in _labels_for(key, embeddings, label_map):
label_map[label] = name
if not embeddings.get(label):
continue
diff --git a/tests/test_review_fixes.py b/tests/test_review_fixes.py
index c1d486fd..34dfb93c 100644
--- a/tests/test_review_fixes.py
+++ b/tests/test_review_fixes.py
@@ -346,3 +346,31 @@ def test_vectorised_calibration_matches_the_pairwise_definition(ctx):
finally:
db.session.query(SpeakerVoiceSample).filter_by(user_id=user.id).delete()
db.session.commit()
+
+
+# ------------------------------------------------ 7. failed training is undone
+
+def test_failed_training_is_rolled_back_and_the_rename_still_saves(ctx):
+ user = _user()
+ rec = _recording(user, {"SPEAKER_00": person(), "SPEAKER_01": person()})
+ real_record = vp.record_sample
+ calls = []
+
+ def fail_second(*args, **kwargs):
+ calls.append(1)
+ if len(calls) == 2:
+ raise RuntimeError("simulated failure after the first sample was flushed")
+ return real_record(*args, **kwargs)
+
+ with patch.object(vp, "record_sample", side_effect=fail_second):
+ _save_names(user, rec, {"SPEAKER_00": "Fay", "SPEAKER_01": "Gus"})
+
+ assert len(calls) == 2
+ rec = db.session.get(Recording, rec.id)
+ assert {s["speaker"] for s in json.loads(rec.transcription)} == {"Fay", "Gus"}
+ assert _samples(user, rec) == {}
+ # The map still follows the transcript, so the next save can train.
+ assert rec.speaker_label_map == {"SPEAKER_00": "Fay", "SPEAKER_01": "Gus"}
+
+ _save_names(user, rec, {"Fay": "Fay", "Gus": "Gus"})
+ assert set(_samples(user, rec)) == {"SPEAKER_00", "SPEAKER_01"}