Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Clear CI warning backlog: return-bool tests, \s escape, Query.get() deprecation
Murtaza Nasir04ba4ce4ea5b
diff --git a/src/api/recordings.py b/src/api/recordings.pyindex e0b7d572..41b5c2a1 100644--- a/src/api/recordings.py+++ b/src/api/recordings.py@@ -1822,7 +1822,7 @@ def get_recordings_paginated():if not is_owner:# This is a shared recording - get owner info and share permissions- owner = User.query.get(recording.user_id)+ owner = db.session.get(User, recording.user_id)rec_dict['owner_username'] = owner.username if owner else "Unknown"rec_dict['is_shared'] = True# Don't show outgoing share count for recordings you don't own@@ -3239,7 +3239,7 @@ def get_recording_detail(recording_id):# Add sharing-related fieldsif not is_owner:# This is a shared recording - get owner info and share permissions- owner = User.query.get(recording.user_id)+ owner = db.session.get(User, recording.user_id)rec_dict['owner_username'] = owner.username if owner else "Unknown"rec_dict['is_shared'] = True# Don't show outgoing share count for recordings you don't owndiff --git a/src/file_exporter.py b/src/file_exporter.pyindex deff627a..f6832aac 100644--- a/src/file_exporter.py+++ b/src/file_exporter.py@@ -224,10 +224,11 @@ def get_user_export_template(user, recording=None):ExportTemplate object or None"""from src.models import ExportTemplate+ from src.database import db# 1. Check folder's export templateif recording and recording.folder and recording.folder.export_template_id:- template = ExportTemplate.query.get(recording.folder.export_template_id)+ template = db.session.get(ExportTemplate, recording.folder.export_template_id)if template:return template@@ -235,7 +236,7 @@ def get_user_export_template(user, recording=None):if recording and recording.tags:for tag in recording.tags:if tag.export_template_id:- template = ExportTemplate.query.get(tag.export_template_id)+ template = db.session.get(ExportTemplate, tag.export_template_id)if template:return templatediff --git a/src/services/speaker_cleanup.py b/src/services/speaker_cleanup.pyindex 80c147a9..25ceb7d7 100644--- a/src/services/speaker_cleanup.py+++ b/src/services/speaker_cleanup.py@@ -83,7 +83,7 @@ def cleanup_orphaned_speakers(dry_run=False):if dry_run:# Report what would be deletedfor speaker_id in orphaned_speaker_ids:- speaker = Speaker.query.get(speaker_id)+ speaker = db.session.get(Speaker, speaker_id)if speaker:stats['orphaned_speakers'].append({'id': speaker.id,@@ -95,7 +95,7 @@ def cleanup_orphaned_speakers(dry_run=False):else:# Actually delete orphaned speakersfor speaker_id in orphaned_speaker_ids:- speaker = Speaker.query.get(speaker_id)+ speaker = db.session.get(Speaker, speaker_id)if speaker:logger.debug("Deleting orphaned speaker: id=%d, name='%s', user_id=%d, embedding_count=%d",diff --git a/src/services/speaker_snippets.py b/src/services/speaker_snippets.pyindex 3263a54a..4743132d 100644--- a/src/services/speaker_snippets.py+++ b/src/services/speaker_snippets.py@@ -35,7 +35,7 @@ def create_speaker_snippets(recording_id, speaker_map):Returns:int: Number of snippets created"""- recording = Recording.query.get(recording_id)+ recording = db.session.get(Recording, recording_id)if not recording or not recording.transcription:return 0@@ -150,7 +150,7 @@ def _generate_dynamic_snippets(speaker_id, limit=3):[{'recording_id': 123, 'start_time': 45.2, 'duration': 3.5, ...}, ...]"""# Get the speaker- speaker = Speaker.query.get(speaker_id)+ speaker = db.session.get(Speaker, speaker_id)if not speaker:return []diff --git a/src/tasks/processing.py b/src/tasks/processing.pyindex 371ba0f9..03d6d1ed 100644--- a/src/tasks/processing.py+++ b/src/tasks/processing.py@@ -1956,7 +1956,7 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_fileupdate_speaker_profiles_from_recording)- user = User.query.get(recording.user_id)+ user = db.session.get(User, recording.user_id)if user and user.auto_speaker_labelling:current_app.logger.info(f"Applying auto speaker labelling for recording {recording.id}")speaker_map = apply_auto_speaker_labels(recording, user)@@ -1981,7 +1981,7 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_file# Check if auto-summarization is disabled (admin setting or user preference)admin_setting = SystemSetting.get_setting('disable_auto_summarization', False)admin_disabled = admin_setting if isinstance(admin_setting, bool) else str(admin_setting).lower() == 'true'- user = User.query.get(recording.user_id)+ user = db.session.get(User, recording.user_id)user_disabled = user and user.auto_summarization is Falsewill_auto_summarize = not admin_disabled and not user_disableddiff --git a/tests/test_api_v1_speakers.py b/tests/test_api_v1_speakers.pyindex 2b616c92..8eaa964a 100644--- a/tests/test_api_v1_speakers.py+++ b/tests/test_api_v1_speakers.py@@ -132,7 +132,6 @@ def test_assign_no_auth():resp = client.put(f"/api/v1/recordings/{rec.id}/speakers/assign",json={"speaker_map": {}})assert resp.status_code in (302, 401), f"Expected 302/401, got {resp.status_code}"- return Truefinally:_cleanup(rec)if cu:@@ -150,7 +149,6 @@ def test_assign_recording_not_found():headers={"X-API-Token": token},json={"speaker_map": {}})assert resp.status_code == 404, f"Expected 404, got {resp.status_code}"- return Truefinally:_cleanup(token_rec)if cu:@@ -170,7 +168,6 @@ def test_assign_wrong_user_recording():headers={"X-API-Token": token},json={"speaker_map": {"SPEAKER_00": "Alice"}})assert resp.status_code == 403, f"Expected 403, got {resp.status_code}"- return Truefinally:_cleanup(rec, token_rec)if cu:@@ -193,7 +190,6 @@ def test_assign_missing_speaker_map():assert resp.status_code == 400, f"Expected 400, got {resp.status_code}"body = resp.get_json()assert "speaker_map" in body.get("error", "").lower(), f"Unexpected error: {body}"- return Truefinally:_cleanup(rec, token_rec)if cu:@@ -212,7 +208,6 @@ def test_assign_invalid_speaker_map_type():headers={"X-API-Token": token},json={"speaker_map": "not a dict"})assert resp.status_code == 400, f"Expected 400, got {resp.status_code}"- return Truefinally:_cleanup(rec, token_rec)if cu:@@ -241,7 +236,6 @@ def test_assign_string_value_json_transcript():segments = json.loads(rec.transcription)assert segments[0]["speaker"] == "Alice"assert segments[1]["speaker"] == "Bob"- return Truefinally:_cleanup(rec, token_rec)if cu:@@ -265,7 +259,6 @@ def test_assign_object_value_with_name():db.session.refresh(rec)segments = json.loads(rec.transcription)assert segments[0]["speaker"] == "Alice"- return Truefinally:_cleanup(rec, token_rec)if cu:@@ -289,7 +282,6 @@ def test_assign_is_me_flag_with_user_name():db.session.refresh(rec)segments = json.loads(rec.transcription)assert segments[0]["speaker"] == "Test User", f"Got {segments[0]['speaker']}"- return Truefinally:_cleanup(rec, token_rec)if cu:@@ -316,7 +308,6 @@ def test_assign_is_me_flag_without_user_name():db.session.refresh(rec)segments = json.loads(rec.transcription)assert segments[0]["speaker"] == "Me", f"Got {segments[0]['speaker']}"- return Truefinally:_cleanup(rec, token_rec)if cu:@@ -339,7 +330,6 @@ def test_assign_plain_text_transcript():assert "[Alice]" in rec.transcriptionassert "[Bob]" in rec.transcriptionassert "[SPEAKER_00]" not in rec.transcription- return Truefinally:_cleanup(rec, token_rec)if cu:@@ -363,7 +353,6 @@ def test_assign_speaker_xx_filtered_from_participants():participants = body["recording"]["participants"]assert "SPEAKER_01" not in participants, f"SPEAKER_01 should be filtered: {participants}"assert "Alice" in participants- return Truefinally:_cleanup(rec, token_rec)if cu:@@ -384,7 +373,6 @@ def test_assign_invalid_value_type():assert resp.status_code == 400, f"Expected 400, got {resp.status_code}"body = resp.get_json()assert "invalid value type" in body.get("error", "").lower(), f"Unexpected: {body}"- return Truefinally:_cleanup(rec, token_rec)if cu:@@ -409,7 +397,6 @@ def test_assign_empty_speaker_map():db.session.refresh(rec)segments = json.loads(rec.transcription)assert segments[0]["speaker"] == "SPEAKER_00"- return Truefinally:_cleanup(rec, token_rec)if cu:@@ -437,7 +424,6 @@ def test_assign_regenerate_summary():body = resp.get_json()assert body.get("summary_queued") is Truemock_jq.enqueue.assert_called_once()- return Truefinally:_cleanup(rec, token_rec)if cu:@@ -468,7 +454,6 @@ def test_assign_embeddings_updated():body = resp.get_json()assert body.get("embeddings_updated") >= 1, f"embeddings_updated: {body}"mock_update.assert_called()- return Truefinally:_cleanup(rec, speaker, token_rec)if cu:@@ -488,7 +473,6 @@ def test_assign_no_transcription():json={"speaker_map": {"SPEAKER_00": "Alice"}})# Should succeed (or at least not 500)assert resp.status_code in (200, 400), f"Expected 200/400, got {resp.status_code}"- return Truefinally:_cleanup(rec, token_rec)if cu:@@ -510,7 +494,6 @@ def test_assign_whitespace_name_trimmed():db.session.refresh(rec)segments = json.loads(rec.transcription)assert segments[0]["speaker"] == "Alice", f"Name not trimmed: '{segments[0]['speaker']}'"- return Truefinally:_cleanup(rec, token_rec)if cu:@@ -531,7 +514,6 @@ def test_identify_no_auth():try:resp = client.post(f"/api/v1/recordings/{rec.id}/speakers/identify")assert resp.status_code in (302, 401), f"Expected 302/401, got {resp.status_code}"- return Truefinally:_cleanup(rec)if cu:@@ -548,7 +530,6 @@ def test_identify_recording_not_found():resp = client.post("/api/v1/recordings/999999/speakers/identify",headers={"X-API-Token": token})assert resp.status_code == 404, f"Expected 404, got {resp.status_code}"- return Truefinally:_cleanup(token_rec)if cu:@@ -567,7 +548,6 @@ def test_identify_wrong_user_recording():resp = client.post(f"/api/v1/recordings/{rec.id}/speakers/identify",headers={"X-API-Token": token})assert resp.status_code == 403, f"Expected 403, got {resp.status_code}"- return Truefinally:_cleanup(rec, token_rec)if cu:@@ -587,7 +567,6 @@ def test_identify_no_transcription():resp = client.post(f"/api/v1/recordings/{rec.id}/speakers/identify",headers={"X-API-Token": token})assert resp.status_code == 400, f"Expected 400, got {resp.status_code}"- return Truefinally:_cleanup(rec, token_rec)if cu:@@ -605,7 +584,6 @@ def test_identify_non_json_transcription():resp = client.post(f"/api/v1/recordings/{rec.id}/speakers/identify",headers={"X-API-Token": token})assert resp.status_code == 400, f"Expected 400, got {resp.status_code}"- return Truefinally:_cleanup(rec, token_rec)if cu:@@ -623,7 +601,6 @@ def test_identify_json_but_not_list():resp = client.post(f"/api/v1/recordings/{rec.id}/speakers/identify",headers={"X-API-Token": token})assert resp.status_code == 400, f"Expected 400, got {resp.status_code}"- return Truefinally:_cleanup(rec, token_rec)if cu:@@ -658,7 +635,6 @@ def test_identify_happy_path():sm = body.get("speaker_map", {})assert sm.get("SPEAKER_00") == "Alice"assert sm.get("SPEAKER_01") == "Bob"- return Truefinally:_cleanup(rec, token_rec)if cu:@@ -691,7 +667,6 @@ def test_identify_post_processing_unknown_values():sm = body.get("speaker_map", {})assert sm.get("SPEAKER_00") == "", f"Expected empty, got {sm.get('SPEAKER_00')}"assert sm.get("SPEAKER_01") == "", f"Expected empty, got {sm.get('SPEAKER_01')}"- return Truefinally:_cleanup(rec, token_rec)if cu:@@ -710,7 +685,6 @@ def test_identify_no_speakers_in_transcript():resp = client.post(f"/api/v1/recordings/{rec.id}/speakers/identify",headers={"X-API-Token": token})assert resp.status_code == 400, f"Expected 400, got {resp.status_code}"- return Truefinally:_cleanup(rec, token_rec)if cu:@@ -732,7 +706,6 @@ def test_identify_llm_error():resp = client.post(f"/api/v1/recordings/{rec.id}/speakers/identify",headers={"X-API-Token": token})assert resp.status_code == 500, f"Expected 500, got {resp.status_code}"- return Truefinally:_cleanup(rec, token_rec)if cu:@@ -751,7 +724,6 @@ def test_auto_summarization_no_auth():resp = client.put("/api/v1/settings/auto-summarization",json={"enabled": True})assert resp.status_code in (302, 401), f"Expected 302/401, got {resp.status_code}"- return Truedef test_auto_summarization_missing_enabled():@@ -767,7 +739,6 @@ def test_auto_summarization_missing_enabled():assert resp.status_code == 400, f"Expected 400, got {resp.status_code}"body = resp.get_json()assert "enabled" in body.get("error", "").lower(), f"Unexpected: {body}"- return Truefinally:_cleanup(token_rec)if cu:@@ -786,7 +757,6 @@ def test_auto_summarization_invalid_json():"Content-Type": "application/json"},data="not valid json")assert resp.status_code == 400, f"Expected 400, got {resp.status_code}"- return Truefinally:_cleanup(token_rec)if cu:@@ -810,7 +780,6 @@ def test_auto_summarization_enable():assert body.get("auto_summarization") is Truedb.session.refresh(user)assert user.auto_summarization is True- return Truefinally:_cleanup(token_rec)if cu:@@ -834,7 +803,6 @@ def test_auto_summarization_disable():assert body.get("auto_summarization") is Falsedb.session.refresh(user)assert user.auto_summarization is False- return Truefinally:_cleanup(token_rec)if cu:@@ -860,7 +828,6 @@ def test_regression_get_speakers_list():body = resp.get_json()names = [s["name"] for s in body.get("speakers", [])]assert "Regression Speaker" in names, f"Speaker not found: {names}"- return Truefinally:_cleanup(speaker, token_rec)if cu:@@ -882,7 +849,6 @@ def test_regression_get_recording_speakers():body = resp.get_json()labels = [s["label"] for s in body.get("speakers", [])]assert "SPEAKER_00" in labels and "SPEAKER_01" in labels, f"Labels: {labels}"- return Truefinally:_cleanup(rec, token_rec)if cu:@@ -943,15 +909,12 @@ def main():for test_fn in ALL_TESTS:name = test_fn.__name__+ # Tests assert (raising on failure) and no longer `return True`, so a+ # clean call == pass; any exception == fail. Mirrors pytest semantics.try:- result = test_fn()- if result:- print(f" PASS {name}")- passed += 1- else:- print(f" FAIL {name} (returned False)")- failed += 1- errors.append(name)+ test_fn()+ print(f" PASS {name}")+ passed += 1except Exception as e:print(f" ERROR {name}: {e}")failed += 1diff --git a/tests/test_inquire_mode.py b/tests/test_inquire_mode.pyindex 3d78978e..7bb7f967 100644--- a/tests/test_inquire_mode.py+++ b/tests/test_inquire_mode.py@@ -66,14 +66,14 @@ def test_database_models():try:# The rows must be retrievable and carry the data we stored.- stored_chunk = TranscriptChunk.query.get(chunk.id)+ stored_chunk = db.session.get(TranscriptChunk, chunk.id)assert stored_chunk is not Noneassert stored_chunk.recording_id == recording.idassert stored_chunk.user_id == user.idassert stored_chunk.content == "This is a test transcription chunk."assert stored_chunk.speaker_name == "Test Speaker"- stored_session = InquireSession.query.get(session.id)+ stored_session = db.session.get(InquireSession, session.id)assert stored_session is not Noneassert stored_session.user_id == user.idassert stored_session.session_name == "Test Session"@@ -127,13 +127,6 @@ def test_chunking_functions():else:assert embeddings == [], "no embedding backend -> documented empty-list contract"- if embeddings[0] is not None:- serialized = serialize_embedding(embeddings[0])- assert serialized is not None- deserialized = deserialize_embedding(serialized)- assert deserialized is not None- assert len(deserialized) > 0-def test_api_imports():"""The inquire-mode endpoint functions must be importable and callable."""diff --git a/tests/test_mistral_connector.py b/tests/test_mistral_connector.pyindex 38dc5732..ea93152c 100644--- a/tests/test_mistral_connector.py+++ b/tests/test_mistral_connector.py@@ -281,7 +281,7 @@ def test_hotwords_splitting():run_test("Single word produces one-item list", t6)def t7():- """Each item must match ^[^,\s]+$ per Mistral spec."""+ r"""Each item must match ^[^,\s]+$ per Mistral spec."""result = split_hotwords("hello world, foo bar, baz")for item in result:assert re.match(r'^[^,\s]+$', item), f"'{item}' contains comma or whitespace"diff --git a/tests/test_sso.py b/tests/test_sso.pyindex 8fd2a0f2..03bc5a43 100644--- a/tests/test_sso.py+++ b/tests/test_sso.py@@ -463,7 +463,7 @@ def test_require_verified_email_on_rejects_unverified_link(cleanup_users):sso.create_or_update_sso_user(claims)db.session.expire_all()# The existing account was NOT hijacked.- refreshed = User.query.get(existing.id)+ refreshed = db.session.get(User, existing.id)assert refreshed.sso_subject is None