Skip to content

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

Python

fix(funasr): fail fast on 4xx, honor per-request diarization, clean up staging

ikelvingo35513a0382e2
diff --git a/src/services/transcription/connectors/alibaba_funasr.py b/src/services/transcription/connectors/alibaba_funasr.py
index c7079661..88f7c8e0 100644
--- a/src/services/transcription/connectors/alibaba_funasr.py
+++ b/src/services/transcription/connectors/alibaba_funasr.py
@@ -188,6 +188,24 @@ class AlibabaFunASRConnector(BaseTranscriptionConnector):
logger.warning(f"Unknown task status: {task_status}")
time.sleep(self.poll_interval)
+ except httpx.HTTPStatusError as e:
+ status = e.response.status_code
+ # 4xx is terminal: a revoked key or bad request will never
+ # succeed on retry, so fail fast instead of burning the
+ # whole timeout window. 429 is transient, so it still
+ # retries (with a doubled backoff).
+ if 400 <= status < 500 and status != 429:
+ logger.error(f"FunASR task query rejected, status {status}")
+ raise ProviderError(
+ f"FunASR task query rejected, status {status}",
+ provider=self.PROVIDER_NAME,
+ status_code=status,
+ ) from e
+ logger.error(f"Task query error: {e}")
+ if attempt < max_attempts - 1:
+ time.sleep(self.poll_interval * (2 if status == 429 else 1))
+ else:
+ raise
except (httpx.HTTPError, ValueError) as e:
logger.error(f"Task query error: {e}")
if attempt < max_attempts - 1:
@@ -232,16 +250,28 @@ class AlibabaFunASRConnector(BaseTranscriptionConnector):
"FunASR requires file URL. Please upload file to S3 first."
)
- # Build parameters dict
+ # Build parameters dict. Per-request settings win over the
+ # env-derived defaults so the UI toggle is honored (the request
+ # always carries the resolved value, see processing.py).
parameters = {}
- if self.default_diarize:
+ diarize = bool(getattr(request, 'diarize', False)) or bool(self.default_diarize)
+ if diarize:
parameters['diarization_enabled'] = True
if self.disfluency_removal_enabled:
parameters['disfluency_removal_enabled'] = True
if self.timestamp_alignment_enabled:
parameters['timestamp_alignment_enabled'] = True
- if self.speaker_count:
- parameters['speaker_count'] = self.speaker_count
+
+ # Speaker count hint: prefer the request's speaker bounds, falling
+ # back to the configured default. FunASR takes a single count, so
+ # use max_speakers when given, else min_speakers.
+ speaker_count = self.speaker_count
+ if getattr(request, 'max_speakers', None) is not None:
+ speaker_count = request.max_speakers
+ elif getattr(request, 'min_speakers', None) is not None:
+ speaker_count = request.min_speakers
+ if speaker_count:
+ parameters['speaker_count'] = speaker_count
if self.vocabulary_id:
parameters['vocabulary_id'] = self.vocabulary_id
if self.language_hints:
@@ -577,18 +607,27 @@ def prepare_funasr_file_url(recording) -> tuple:
object_key = f"funasr/{recording.id}/{safe_filename}"
s3_locator = parse_locator(storage.s3.build_locator(object_key))
- if not storage.s3.exists(s3_locator):
- current_app.logger.info(
- "Uploading recording %s to FunASR staging object %s",
- recording.id,
+ # Track the staging key so the caller can clean it up after the run.
+ # Always re-upload: a replaced audio file must never re-sign a stale
+ # staging object left over from a previous run.
+ staging_keys = getattr(recording, '_funasr_staging_keys', None)
+ if staging_keys is None:
+ staging_keys = []
+ recording._funasr_staging_keys = staging_keys
+ if object_key not in staging_keys:
+ staging_keys.append(object_key)
+
+ current_app.logger.info(
+ "Uploading recording %s to FunASR staging object %s",
+ recording.id,
+ object_key,
+ )
+ with storage.materialize(locator_str) as materialized:
+ storage.s3.upload_local_file(
+ materialized.local_path,
object_key,
+ content_type=recording.mime_type or 'application/octet-stream',
)
- with storage.materialize(locator_str) as materialized:
- storage.s3.upload_local_file(
- materialized.local_path,
- object_key,
- content_type=recording.mime_type or 'application/octet-stream',
- )
url = storage.s3.presign_get_url(
s3_locator,
@@ -598,3 +637,30 @@ def prepare_funasr_file_url(recording) -> tuple:
current_app.logger.info(f"FunASR URL ready for recording {recording.id}")
return True, [url]
+
+
+def cleanup_funasr_staging(recording) -> None:
+ """Best-effort delete of FunASR staging objects created for a recording.
+
+ Deletes the objects uploaded to the ``funasr/{recording.id}/`` prefix so
+ the bucket does not grow without bound. Failures are logged and swallowed
+ so a cleanup hiccup never fails an otherwise-successful transcription.
+ """
+ from flask import current_app
+ from src.services.storage import get_storage_service
+ from src.services.storage.locator import parse_locator
+
+ storage = get_storage_service()
+ if not storage.s3:
+ return
+
+ staging_keys = getattr(recording, '_funasr_staging_keys', None) or []
+ for object_key in staging_keys:
+ try:
+ s3_locator = parse_locator(storage.s3.build_locator(object_key))
+ storage.s3.delete(s3_locator, missing_ok=True)
+ current_app.logger.info(f"Cleaned up FunASR staging object {object_key}")
+ except Exception as exc: # noqa: BLE001 - best effort only
+ current_app.logger.warning(
+ f"Failed to clean up FunASR staging object {object_key}: {exc}"
+ )
diff --git a/src/tasks/processing.py b/src/tasks/processing.py
index 4b0eb1c8..c654dfe8 100644
--- a/src/tasks/processing.py
+++ b/src/tasks/processing.py
@@ -1737,7 +1737,7 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_file
initial_prompt: Optional initial prompt to steer transcription
"""
from src.services.transcription import (
- get_connector, TranscriptionRequest, TranscriptionCapability
+ get_connector, get_registry, TranscriptionRequest, TranscriptionCapability
)
from src.utils.language import normalize_language_code
@@ -2038,16 +2038,22 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_file
current_app.logger.info(f"Chunked transcription completed: {len(transcription_text)} characters")
else:
# Build the transcription request for single file
+ funasr_active = bool(
+ recording
+ and get_registry().get_active_connector_name() == 'funasr'
+ )
+ if funasr_active:
+ from src.services.transcription.connectors.alibaba_funasr import (
+ cleanup_funasr_staging,
+ prepare_funasr_file_url,
+ )
with open(actual_filepath, 'rb') as audio_file:
# FunASR requires an externally reachable object URL.
extra_options = {}
- if recording:
- from src.services.transcription import get_registry
- if get_registry().get_active_connector_name() == 'funasr':
- from src.services.transcription.connectors.alibaba_funasr import prepare_funasr_file_url
- success, urls = prepare_funasr_file_url(recording)
- if success and urls:
- extra_options['funasr_file_urls'] = urls
+ if funasr_active:
+ success, urls = prepare_funasr_file_url(recording)
+ if success and urls:
+ extra_options['funasr_file_urls'] = urls
request = TranscriptionRequest(
audio_file=audio_file,
@@ -2068,7 +2074,14 @@ def transcribe_with_connector(app_context, recording_id, filepath, original_file
should_diarize,
language,
)
- response = connector.transcribe(request)
+ try:
+ response = connector.transcribe(request)
+ finally:
+ # FunASR staging objects are only needed while
+ # the async task can reach them; delete them as
+ # soon as the run finishes, success or failure.
+ if funasr_active:
+ cleanup_funasr_staging(recording)
# Store the result
if response.segments and response.has_diarization():
diff --git a/tests/test_funasr.py b/tests/test_funasr.py
index f378686c..efadee22 100644
--- a/tests/test_funasr.py
+++ b/tests/test_funasr.py
@@ -298,6 +298,197 @@ def test_prepare_audio_signs_directly_for_configured_intranet_endpoint():
)
+def test_poll_4xx_is_terminal_and_not_retried():
+ """A 4xx response during polling (e.g. revoked key) must raise immediately."""
+ from httpx import HTTPStatusError, Request, Response
+
+ client = MagicMock()
+ client.__enter__.return_value = client
+ client.__exit__.return_value = False
+
+ def _raise_for_status():
+ resp = Response(401, request=Request('GET', 'https://dashscope.aliyuncs.com/tasks/x'))
+ raise HTTPStatusError('401 Unauthorized', request=resp.request, response=resp)
+
+ resp = MagicMock(status_code=401)
+ resp.raise_for_status.side_effect = _raise_for_status
+ client.get.return_value = resp
+
+ connector = AlibabaFunASRConnector({
+ 'base_url': 'https://dashscope.aliyuncs.com/api/v1',
+ 'api_key': 'sk-test',
+ 'timeout': 30,
+ 'poll_interval': 10,
+ })
+
+ with patch('httpx.Client', return_value=client), patch('time.sleep') as sleep:
+ with pytest.raises(ProviderError) as exc_info:
+ connector._poll_task_result('task-1', {'Authorization': 'Bearer sk-test'})
+
+ assert exc_info.value.status_code == 401
+ assert client.get.call_count == 1
+ sleep.assert_not_called()
+
+
+def test_transcribe_honors_request_diarize_and_speaker_count():
+ """Per-request diarize / speaker bounds must reach the FunASR payload."""
+ captured = {}
+
+ def _fake_post(url, **kwargs):
+ if 'json' in kwargs:
+ captured['payload'] = kwargs['json']
+ resp = MagicMock()
+ resp.status_code = 200
+ resp.text = '{}'
+ resp.json.return_value = {
+ 'output': {
+ 'task_id': 'tid',
+ 'task_status': 'SUCCEEDED',
+ 'results': [{
+ 'subtask_status': 'SUCCEEDED',
+ 'transcription_url': 'https://signed.example/result.json',
+ }],
+ }
+ }
+ resp.raise_for_status.return_value = None
+ return resp
+
+ connector = AlibabaFunASRConnector(
+ config={'base_url': 'https://dashscope.aliyuncs.com/api/v1', 'api_key': 'sk-test'}
+ )
+ req = TranscriptionRequest(
+ audio_file=io.BytesIO(b'x'),
+ filename='x.mp3',
+ diarize=True,
+ min_speakers=2,
+ max_speakers=4,
+ extra_options={'funasr_file_urls': ['https://signed.example/x.mp3']},
+ )
+
+ with patch('httpx.Client') as client_cls:
+ client_instance = MagicMock()
+ client_instance.__enter__.return_value = client_instance
+ client_instance.__exit__.return_value = False
+ client_instance.post = MagicMock(side_effect=_fake_post)
+ client_instance.get = MagicMock(side_effect=_fake_post)
+ client_cls.return_value = client_instance
+
+ connector.transcribe(req)
+
+ params = captured['payload'].get('parameters', {})
+ assert params.get('diarization_enabled') is True
+ assert params.get('speaker_count') == 4
+
+
+def test_transcribe_falls_back_to_config_defaults():
+ """When the request carries no speaker bounds, config default is used."""
+ captured = {}
+
+ def _fake_post(url, **kwargs):
+ if 'json' in kwargs:
+ captured['payload'] = kwargs['json']
+ resp = MagicMock()
+ resp.status_code = 200
+ resp.text = '{}'
+ resp.json.return_value = {
+ 'output': {
+ 'task_id': 'tid',
+ 'task_status': 'SUCCEEDED',
+ 'results': [{
+ 'subtask_status': 'SUCCEEDED',
+ 'transcription_url': 'https://signed.example/result.json',
+ }],
+ }
+ }
+ resp.raise_for_status.return_value = None
+ return resp
+
+ connector = AlibabaFunASRConnector(
+ config={
+ 'base_url': 'https://dashscope.aliyuncs.com/api/v1',
+ 'api_key': 'sk-test',
+ 'diarize': True,
+ 'speaker_count': 3,
+ }
+ )
+ req = TranscriptionRequest(
+ audio_file=io.BytesIO(b'x'),
+ filename='x.mp3',
+ extra_options={'funasr_file_urls': ['https://signed.example/x.mp3']},
+ )
+
+ with patch('httpx.Client') as client_cls:
+ client_instance = MagicMock()
+ client_instance.__enter__.return_value = client_instance
+ client_instance.__exit__.return_value = False
+ client_instance.post = MagicMock(side_effect=_fake_post)
+ client_instance.get = MagicMock(side_effect=_fake_post)
+ client_cls.return_value = client_instance
+
+ connector.transcribe(req)
+
+ params = captured['payload'].get('parameters', {})
+ assert params.get('diarization_enabled') is True
+ assert params.get('speaker_count') == 3
+
+
+def test_cleanup_funasr_staging_deletes_staged_keys():
+ """Staging keys recorded during prepare are deleted by cleanup."""
+ from src.services.transcription.connectors.alibaba_funasr import cleanup_funasr_staging
+
+ s3 = MagicMock()
+ s3.build_locator.return_value = 's3://bucket/funasr/1/source.wav'
+ storage = MagicMock(s3=s3)
+ recording = SimpleNamespace(
+ id=1,
+ _funasr_staging_keys=['funasr/1/source.wav'],
+ )
+
+ with Flask(__name__).app_context(), patch(
+ 'src.services.storage.get_storage_service', return_value=storage
+ ):
+ cleanup_funasr_staging(recording)
+
+ s3.delete.assert_called_once()
+ assert s3.delete.call_args.args[0].raw == 's3://bucket/funasr/1/source.wav'
+
+
+def test_cleanup_funasr_staging_noop_without_keys():
+ """Cleanup with no recorded staging keys must not touch storage."""
+ from src.services.transcription.connectors.alibaba_funasr import cleanup_funasr_staging
+
+ s3 = MagicMock()
+ storage = MagicMock(s3=s3)
+ recording = SimpleNamespace(id=1)
+
+ with Flask(__name__).app_context(), patch(
+ 'src.services.storage.get_storage_service', return_value=storage
+ ):
+ cleanup_funasr_staging(recording)
+
+ s3.delete.assert_not_called()
+
+
+def test_prepare_local_audio_always_reuploads_staging():
+ """A replaced audio file must never re-sign a stale staging object."""
+ storage = _fake_storage()
+ recording = SimpleNamespace(
+ id=1,
+ audio_path='local://recordings/source.wav',
+ original_filename='source.wav',
+ mime_type='audio/wav',
+ )
+
+ with Flask(__name__).app_context(), patch(
+ 'src.services.storage.get_storage_service', return_value=storage
+ ):
+ success, urls = prepare_funasr_file_url(recording)
+
+ assert success is True
+ storage.s3.upload_local_file.assert_called_once()
+ assert recording._funasr_staging_keys == ['funasr/1/source.wav']
+
+
if __name__ == '__main__':
test_transcription_request_has_no_file_urls_field()
test_transcription_request_extra_options_pass_through()