Skip to content

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

Python

Add native Tencent Cloud recording-file ASR connector

ZOLO01ecba587e4a
diff --git a/config/env.transcription.example b/config/env.transcription.example
index fe14c6bd..a289dd2b 100644
--- a/config/env.transcription.example
+++ b/config/env.transcription.example
@@ -1,6 +1,15 @@
# =============================================================================
# Transcription Connector Configuration
# =============================================================================
+# Tencent Cloud recording-file ASR (optional; not the real-time WebSocket API)
+# TRANSCRIPTION_CONNECTOR=tencent_asr
+# TENCENT_SECRET_ID=your-secret-id
+# TENCENT_SECRET_KEY=your-secret-key
+# TENCENT_ASR_MODEL=16k_zh_en_meeting
+# TENCENT_ASR_TIMEOUT=1800
+# TENCENT_ASR_POLL_INTERVAL=5
+# TENCENT_ASR_HOTWORD_ID=your-hotword-table-id
+# Files over 5 MiB require Speakr S3 storage; see docs/advanced/tencent-asr.md.
#
# Speakr supports multiple transcription providers through a connector-based
# architecture. This file documents all available configuration options.
diff --git a/docs/advanced/tencent-asr.md b/docs/advanced/tencent-asr.md
new file mode 100644
index 00000000..b6d42108
--- /dev/null
+++ b/docs/advanced/tencent-asr.md
@@ -0,0 +1,64 @@
+# Tencent Cloud recording-file ASR
+
+The `tencent_asr` connector uses Tencent's recording-file API directly; no ASR
+bridge container or local GPU is needed. Configure a separate text model as
+usual for summaries and chat.
+
+```env
+TRANSCRIPTION_CONNECTOR=tencent_asr
+TENCENT_SECRET_ID=your-secret-id
+TENCENT_SECRET_KEY=your-secret-key
+TENCENT_ASR_MODEL=16k_zh_en_meeting
+```
+
+Activate Tencent Cloud ASR and use credentials with `CreateRecTask` and
+`DescribeTaskStatus` permissions. Use a **recording-file recognition** package
+matching the engine, or enable the appropriate pay-as-you-go service. A real-time
+recognition package cannot pay for recording-file recognition. Keep credentials
+in your deployment's environment/secrets, never in source control. Audio is
+sent to Tencent; this is cloud transcription, not local inference.
+
+## Engines and recognition settings
+
+Supported engines are `16k_zh_en_meeting` (default) and `16k_zh_en_2.0`.
+The meeting engine requires provider-side speaker separation; switching the UI
+diarization toggle off still hides speaker labels in Speakr. Use `16k_zh_en_2.0`
+to disable provider-side separation too. Language is determined by the selected
+engine, not the UI language hint. Speaker count hints are not supported by these
+16 kHz engines. Segments include sentence timestamps and anonymous speaker labels;
+this does not identify people's names.
+
+Comma-separated UI hotwords are sent with weight 5 (up to 128 words, at most
+30 UTF-8 bytes each). Alternatively set `TENCENT_ASR_HOTWORD_ID` to a Tencent
+hotword table ID. Request hotwords take precedence. Optional
+`TENCENT_ASR_TIMEOUT=1800` and `TENCENT_ASR_POLL_INTERVAL=5` control polling
+in seconds (maximum timeout 10800).
+
+## Large files and storage
+
+Files up to 5 MiB are sent directly. Larger files use the existing Speakr S3
+backend: configure `S3_BUCKET_NAME`, `S3_REGION`, `S3_ENDPOINT_URL`,
+`S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY`. The endpoint and signed download
+URL must be reachable by Tencent over the public internet; a NAS-only address
+will not work. The bucket can remain private. This uses Speakr's existing
+S3-compatible client, not a separate COS SDK; verify your chosen storage
+provider's compatibility before relying on it. Local recording storage can
+remain selected (`FILE_STORAGE_BACKEND=local`).
+
+Staging objects use the `tencent-asr/` prefix and 24-hour signed URLs. They are
+deleted after a terminal task result. Configure a bucket lifecycle rule to
+expire this prefix after at least two days: timed-out tasks, interrupted
+workers, and uncertain submissions retain their objects so Tencent can finish
+downloading them. These objects contain audio; storage charges may apply.
+The API limits URL jobs to 1 GiB and five hours.
+
+## Failures and retries
+
+Transient polling failures retry the same task. **Submission is never retried
+by the connector.** Task IDs are logged and included in timeout errors. There
+is no automatic resume across worker restarts: check the Tencent ASR console
+before manually retrying a failed/timeout recording, since a new transcription
+can create another billable task. A network timeout during submission can mean
+Tencent accepted it even though no task ID reached Speakr.
+
+API reference: [CreateRecTask](https://cloud.tencent.com/document/api/1093/37823).
diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md
index f939c80c..3690efab 100644
--- a/docs/getting-started/installation.md
+++ b/docs/getting-started/installation.md
@@ -230,6 +230,14 @@ TRANSCRIPTION_MODEL=vibevoice
If your vLLM server requires authentication, also set `TRANSCRIPTION_API_KEY`. Configure the text generation model as described above for summaries and chat features.
+#### For Tencent Cloud ASR (Chinese and English Meetings)
+
+Use `TRANSCRIPTION_CONNECTOR=tencent_asr` with `TENCENT_SECRET_ID` and
+`TENCENT_SECRET_KEY`. This native connector supports Tencent recording-file
+recognition, timestamps, speaker labels and hotwords, without an ASR bridge
+container or local GPU. See the [Tencent ASR setup guide](../advanced/tencent-asr.md)
+for engines, large files, resource packages and retry limitations.
+
#### For AssemblyAI (Cloud-Based Diarization)
AssemblyAI is a cloud transcription provider with strong speaker diarization on long, multi-speaker recordings. It is not OpenAI-compatible (it uses its own asynchronous upload-and-poll API), so it has a dedicated connector. It ingests files up to 10 hours in a single job, so the app does not chunk for it. New accounts get free credits and no credit card is required to create an API key.
diff --git a/mkdocs.yml b/mkdocs.yml
index f342f2ea..b3cd4bab 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -193,8 +193,9 @@ nav:
- Advanced:
- Custom Connectors: advanced/custom-connectors.md
+ - Tencent Cloud ASR: advanced/tencent-asr.md
- Job Queue System: advanced/job-queue-system.md
- Troubleshooting: troubleshooting.md
- FAQ: faq.md
- - Roadmap: roadmap.md
\ No newline at end of file
+ - Roadmap: roadmap.md
diff --git a/src/services/transcription/connectors/__init__.py b/src/services/transcription/connectors/__init__.py
index ea0d98a9..9321c4b3 100644
--- a/src/services/transcription/connectors/__init__.py
+++ b/src/services/transcription/connectors/__init__.py
@@ -11,6 +11,7 @@ from .vibevoice import VibeVoiceTranscriptionConnector
from .alibaba_funasr import AlibabaFunASRConnector
from .mossland import MosslandTranscriptionConnector
from .openasr import OpenASRTranscriptionConnector
+from .tencent_asr import TencentASRConnector
__all__ = [
'OpenAIWhisperConnector',
@@ -22,4 +23,5 @@ __all__ = [
'AlibabaFunASRConnector',
'MosslandTranscriptionConnector',
'OpenASRTranscriptionConnector',
+ 'TencentASRConnector',
]
diff --git a/src/services/transcription/connectors/tencent_asr.py b/src/services/transcription/connectors/tencent_asr.py
new file mode 100644
index 00000000..c08e99d6
--- /dev/null
+++ b/src/services/transcription/connectors/tencent_asr.py
@@ -0,0 +1,240 @@
+"""Tencent Cloud recording-file ASR (TC3 signed submit-and-poll API)."""
+
+import base64
+import hashlib
+import hmac
+import io
+import json
+import logging
+import tempfile
+import time
+from datetime import datetime, timezone
+from pathlib import Path
+from uuid import uuid4
+
+import httpx
+
+from ..base import (BaseTranscriptionConnector, ConnectorSpecifications,
+ TranscriptionCapability, TranscriptionResponse, TranscriptionSegment)
+from ..exceptions import ConfigurationError, ProviderError, TranscriptionError
+
+logger = logging.getLogger(__name__)
+HOST = 'asr.tencentcloudapi.com'
+INLINE_LIMIT = 5 * 1024 * 1024
+FILE_LIMIT = 1024 * 1024 * 1024
+MODELS = ('16k_zh_en_meeting', '16k_zh_en_2.0')
+
+
+class TencentASRConnector(BaseTranscriptionConnector):
+ PROVIDER_NAME = 'tencent_asr'
+ CAPABILITIES = {TranscriptionCapability.DIARIZATION,
+ TranscriptionCapability.TIMESTAMPS, TranscriptionCapability.HOTWORDS}
+ SPECIFICATIONS = ConnectorSpecifications(
+ max_file_size_bytes=FILE_LIMIT, max_duration_seconds=18000,
+ handles_chunking_internally=True)
+
+ def _validate_config(self):
+ self.secret_id = self.config.get('secret_id', '').strip()
+ self.secret_key = self.config.get('secret_key', '').strip()
+ if not self.secret_id or not self.secret_key:
+ raise ConfigurationError('Tencent ASR requires TENCENT_SECRET_ID and TENCENT_SECRET_KEY')
+ self.model = self.config.get('model') or MODELS[0]
+ if self.model not in MODELS:
+ raise ConfigurationError('Tencent ASR supports: ' + ', '.join(MODELS))
+ try:
+ self.poll_timeout = float(self.config.get('timeout', 1800))
+ self.poll_interval = float(self.config.get('poll_interval', 5))
+ except (TypeError, ValueError):
+ raise ConfigurationError('Tencent timeout and poll interval must be positive numbers') from None
+ if not (0 < self.poll_interval <= self.poll_timeout <= 10800):
+ raise ConfigurationError('Tencent requires 0 < poll_interval <= timeout <= 10800 seconds')
+ self.hotword_id = self.config.get('hotword_id', '').strip()
+ self.default_diarize = self.config.get('diarize', True)
+
+ def _headers(self, action, body, timestamp):
+ date = datetime.fromtimestamp(timestamp, timezone.utc).strftime('%Y-%m-%d')
+ content_type = 'application/json; charset=utf-8'
+ canonical = ('POST\n/\n\n' + f'content-type:{content_type}\nhost:{HOST}\n'
+ + '\ncontent-type;host\n' + hashlib.sha256(body).hexdigest())
+ scope = date + '/asr/tc3_request'
+ message = f'TC3-HMAC-SHA256\n{timestamp}\n{scope}\n' + hashlib.sha256(canonical.encode()).hexdigest()
+ def sign(key, value):
+ return hmac.new(key, value.encode(), hashlib.sha256).digest()
+ key = sign(sign(sign(('TC3' + self.secret_key).encode(), date), 'asr'), 'tc3_request')
+ signature = hmac.new(key, message.encode(), hashlib.sha256).hexdigest()
+ return {
+ 'Authorization': f'TC3-HMAC-SHA256 Credential={self.secret_id}/{scope}, '
+ f'SignedHeaders=content-type;host, Signature={signature}',
+ 'Content-Type': content_type, 'Host': HOST,
+ 'X-TC-Action': action, 'X-TC-Version': '2019-06-14',
+ 'X-TC-Timestamp': str(timestamp),
+ }
+
+ def _call(self, client, action, payload):
+ body = json.dumps(payload, ensure_ascii=False, separators=(',', ':')).encode('utf-8')
+ response = client.post('https://' + HOST, content=body,
+ headers=self._headers(action, body, int(time.time())))
+ if response.status_code != 200:
+ raise ProviderError(f'Tencent {action}: HTTP {response.status_code}',
+ provider=self.PROVIDER_NAME, status_code=response.status_code)
+ try:
+ data = response.json()['Response']
+ if not isinstance(data, dict):
+ raise ValueError('Invalid envelope')
+ error = data.get('Error')
+ if error:
+ if not isinstance(error, dict):
+ raise ValueError('Invalid error')
+ code = str(error.get('Code', 'Unknown'))
+ hint = ''
+ if 'Amount' in code or 'ServiceIsolate' in code or 'UserNotRegistered' in code:
+ hint = ' Check activation and recording-file ASR quota for the selected engine; real-time packages do not apply.'
+ elif code.startswith(('AuthFailure', 'UnauthorizedOperation')):
+ hint = ' Check credentials, CAM permissions and system clock.'
+ raise ProviderError(f'Tencent {action}: {code}.{hint}', provider=self.PROVIDER_NAME,
+ status_code=429 if code.startswith('RequestLimitExceeded') else 400)
+ if not isinstance(data['Data'], dict):
+ raise ValueError('Invalid task data')
+ return data['Data']
+ except (KeyError, TypeError, ValueError):
+ # Never include response bodies, signed URLs or credentials in errors.
+ raise ProviderError(f'Tencent {action}: invalid JSON response', provider=self.PROVIDER_NAME) from None
+
+ def _parameters(self, request):
+ # Shared UI settings can still contain a model from the previous provider.
+ model = request.model if request.model in MODELS else self.model
+ params = {'EngineModelType': model, 'ChannelNum': 1, 'ResTextFormat': 3,
+ 'SpeakerDiarization': int(request.diarize or model == MODELS[0])}
+ if request.hotwords:
+ words = list(dict.fromkeys(w.strip() for w in request.hotwords.split(',') if w.strip()))
+ if len(words) > 128 or any(len(w) > 30 or len(w.encode('utf-8')) > 30 or '|' in w for w in words):
+ raise ConfigurationError('Tencent hotwords: at most 128 words, 30 UTF-8 bytes per word; no | characters')
+ if words:
+ params['HotwordList'] = ','.join(w + '|5' for w in words)
+ elif self.hotword_id:
+ params['HotwordId'] = self.hotword_id
+ return params
+
+ def _stage(self, path, request):
+ from src.services.storage import get_storage_service, parse_locator
+ storage = get_storage_service()
+ if not storage.s3:
+ raise ConfigurationError('Tencent audio over 5 MiB requires Speakr S3 storage with a publicly reachable endpoint')
+ key = 'tencent-asr/' + uuid4().hex + Path(request.filename).suffix
+ locator = parse_locator(storage.s3.build_locator(key))
+ try:
+ storage.s3.upload_local_file(path, key, content_type=request.mime_type or 'application/octet-stream')
+ url = storage.s3.presign_get_url(locator, expires_seconds=86400)
+ return storage.s3, locator, url
+ except Exception:
+ self._cleanup(storage.s3, locator)
+ raise TranscriptionError('Tencent ASR staging failed; check S3 configuration and permissions') from None
+
+ @staticmethod
+ def _cleanup(storage, locator):
+ try:
+ storage.delete(locator, missing_ok=True)
+ except Exception:
+ logger.warning('Tencent ASR staging cleanup failed; configure a tencent-asr/ bucket lifecycle rule')
+
+ def _poll(self, client, task_id):
+ deadline = time.monotonic() + self.poll_timeout
+ while time.monotonic() < deadline:
+ try:
+ data = self._call(client, 'DescribeTaskStatus', {'TaskId': task_id})
+ status = data.get('Status')
+ if status in (2, 3):
+ return data
+ if status not in (0, 1):
+ raise ProviderError(f'Tencent task {task_id}: unexpected status', provider=self.PROVIDER_NAME)
+ except httpx.TransportError:
+ pass # Polling is safe to retry; submission is not.
+ except ProviderError as exc:
+ if exc.status_code != 429 and not (exc.status_code and exc.status_code >= 500):
+ raise
+ time.sleep(min(self.poll_interval, max(0, deadline - time.monotonic())))
+ raise TranscriptionError(f'Tencent task {task_id}: polling timed out. The remote task may still be running; '
+ 'a new transcription submits a new billable task.')
+
+ def transcribe(self, request):
+ params = self._parameters(request)
+ storage = locator = None
+ submitted = terminal = False
+ try:
+ try:
+ request.audio_file.seek(0)
+ except (AttributeError, OSError, io.UnsupportedOperation):
+ pass
+ data = request.audio_file.read(INLINE_LIMIT + 1)
+ if not data:
+ raise TranscriptionError('Tencent ASR: empty audio file')
+ if len(data) <= INLINE_LIMIT:
+ params.update(SourceType=1, Data=base64.b64encode(data).decode(), DataLen=len(data))
+ else:
+ with tempfile.TemporaryDirectory(prefix='speakr_tencent_') as directory:
+ path = str(Path(directory) / 'audio')
+ size = len(data)
+ with open(path, 'wb') as output:
+ output.write(data)
+ while True:
+ chunk = request.audio_file.read(1024 * 1024)
+ if not chunk:
+ break
+ size += len(chunk)
+ if size > FILE_LIMIT:
+ raise TranscriptionError('Tencent ASR: audio exceeds 1 GiB URL limit')
+ output.write(chunk)
+ storage, locator, url = self._stage(path, request)
+ params.update(SourceType=0, Url=url)
+ with httpx.Client(timeout=httpx.Timeout(60, connect=15), follow_redirects=False) as client:
+ # Mark before POST: a transport failure can occur after acceptance.
+ submitted = True
+ try:
+ result = self._call(client, 'CreateRecTask', params)
+ except ProviderError as exc:
+ # A definite rejection cannot be downloading the staged object.
+ terminal = bool(exc.status_code and 400 <= exc.status_code < 500)
+ raise
+ task_id = result.get('TaskId')
+ if not isinstance(task_id, int) or isinstance(task_id, bool):
+ raise ProviderError('Tencent submit returned no task ID', provider=self.PROVIDER_NAME)
+ logger.info('Tencent ASR task submitted: %s', task_id)
+ result = self._poll(client, task_id)
+ terminal = True
+ if result['Status'] == 3:
+ raise TranscriptionError(f'Tencent task {task_id} failed; check the ASR console for details')
+ return self._parse_result(result, params['EngineModelType'], request.diarize)
+ except httpx.HTTPError:
+ raise TranscriptionError('Tencent ASR network error. Submission was not retried: check the ASR console '
+ 'before retrying to avoid duplicate charges.') from None
+ finally:
+ # On timeout or ambiguous POST failure, Tencent may still need the URL.
+ if storage and (terminal or not submitted):
+ self._cleanup(storage, locator)
+
+ def _parse_result(self, result, model, diarize):
+ segments = []
+ for item in result.get('ResultDetail') or []:
+ text = (item.get('FinalSentence') or '').strip()
+ if not text:
+ continue
+ speaker_id = item.get('SpeakerId')
+ speaker = f'SPEAKER_{speaker_id:02d}' if diarize and isinstance(speaker_id, int) and speaker_id >= 0 else None
+ segments.append(TranscriptionSegment(text=text, speaker=speaker,
+ start_time=item['StartMs'] / 1000 if item.get('StartMs') is not None else None,
+ end_time=item['EndMs'] / 1000 if item.get('EndMs') is not None else None))
+ return TranscriptionResponse(
+ text='\n'.join(s.text for s in segments) if segments else (result.get('Result') or ''),
+ segments=segments or None, speakers=sorted({s.speaker for s in segments if s.speaker}) or None,
+ duration=result.get('AudioDuration'), provider=self.PROVIDER_NAME, model=model,
+ raw_response=result)
+
+ def list_models(self):
+ return [{'id': model} for model in MODELS]
+
+ @classmethod
+ def get_config_schema(cls):
+ return {'type': 'object', 'required': ['secret_id', 'secret_key'], 'properties': {
+ 'secret_id': {'type': 'string'}, 'secret_key': {'type': 'string', 'writeOnly': True},
+ 'model': {'type': 'string', 'enum': list(MODELS), 'default': MODELS[0]},
+ 'hotword_id': {'type': 'string'}, 'timeout': {'type': 'number', 'default': 1800}}}
diff --git a/src/services/transcription/registry.py b/src/services/transcription/registry.py
index c423f4a2..8c9a1397 100644
--- a/src/services/transcription/registry.py
+++ b/src/services/transcription/registry.py
@@ -50,6 +50,7 @@ class ConnectorRegistry:
from .connectors.alibaba_funasr import AlibabaFunASRConnector
from .connectors.mossland import MosslandTranscriptionConnector
from .connectors.assemblyai import AssemblyAITranscriptionConnector
+ from .connectors.tencent_asr import TencentASRConnector
from .connectors.openasr import OpenASRTranscriptionConnector
self.register('openai_whisper', OpenAIWhisperConnector)
@@ -61,6 +62,7 @@ class ConnectorRegistry:
self.register('funasr', AlibabaFunASRConnector)
self.register('mossland', MosslandTranscriptionConnector)
self.register('assemblyai', AssemblyAITranscriptionConnector)
+ self.register('tencent_asr', TencentASRConnector)
self.register('openasr', OpenASRTranscriptionConnector)
def register(self, name: str, connector_class: Type[BaseTranscriptionConnector]):
@@ -352,6 +354,17 @@ class ConnectorRegistry:
'model': os.environ.get('TRANSCRIPTION_MODEL', 'moss-transcribe-diarize'),
}
+ elif connector_name == 'tencent_asr':
+ return {
+ 'secret_id': os.environ.get('TENCENT_SECRET_ID', ''),
+ 'secret_key': os.environ.get('TENCENT_SECRET_KEY', ''),
+ 'model': os.environ.get('TENCENT_ASR_MODEL', '16k_zh_en_meeting'),
+ 'timeout': os.environ.get('TENCENT_ASR_TIMEOUT', '1800'),
+ 'poll_interval': os.environ.get('TENCENT_ASR_POLL_INTERVAL', '5'),
+ 'hotword_id': os.environ.get('TENCENT_ASR_HOTWORD_ID', ''),
+ 'diarize': os.environ.get('ASR_DIARIZE', 'true').lower() == 'true',
+ }
+
elif connector_name == 'assemblyai':
# AssemblyAI's endpoint is fixed (api.assemblyai.com), so we do NOT
# read the shared TRANSCRIPTION_BASE_URL here: a stale value left
diff --git a/tests/test_tencent_asr.py b/tests/test_tencent_asr.py
new file mode 100644
index 00000000..27cb61ab
--- /dev/null
+++ b/tests/test_tencent_asr.py
@@ -0,0 +1,219 @@
+"""Tencent ASR contract tests. No credentials or external network required."""
+import io
+import json
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+import httpx
+import pytest
+
+from src.services.transcription.base import TranscriptionRequest
+from src.services.transcription.connectors import tencent_asr as mod
+from src.services.transcription.exceptions import ConfigurationError, ProviderError, TranscriptionError
+
+
+def connector():
+ return mod.TencentASRConnector({'secret_id': 'test-id', 'secret_key': 'test-secret',
+ 'poll_interval': .001, 'timeout': .05})
+
+
+def request(data=b'audio', **kwargs):
+ return TranscriptionRequest(audio_file=io.BytesIO(data), filename='test.wav', **kwargs)
+
+
+def transport(monkeypatch, responses):
+ calls = []
+ def handler(req):
+ calls.append((req.headers['X-TC-Action'], json.loads(req.content)))
+ value = responses.pop(0)
+ if isinstance(value, Exception):
+ raise value
+ if isinstance(value, int):
+ return httpx.Response(value)
+ return httpx.Response(200, json={'Response': value})
+ client = httpx.Client(transport=httpx.MockTransport(handler))
+ monkeypatch.setattr(mod.httpx, 'Client', lambda **kwargs: client)
+ return calls
+
+
+def test_submit_poll_parse_and_no_duplicate_submit(connector, monkeypatch):
+ calls = transport(monkeypatch, [
+ {'Data': {'TaskId': 42}}, 503, httpx.ReadTimeout('hidden'),
+ {'Error': {'Code': 'RequestLimitExceeded.UinLimitExceeded'}},
+ {'Data': {'Status': 1}},
+ {'Data': {'Status': 2, 'AudioDuration': 2.5, 'ResultDetail': [
+ {'FinalSentence': '你好', 'StartMs': 0, 'EndMs': 1200, 'SpeakerId': 0},
+ {'FinalSentence': '测试', 'StartMs': 1300, 'EndMs': 2500, 'SpeakerId': 1}]}}])
+ result = connector.transcribe(request(diarize=True, hotwords='志恒, Skill,志恒', model='whisper-1'))
+ assert [c[0] for c in calls].count('CreateRecTask') == 1
+ payload = calls[0][1]
+ assert payload['DataLen'] == 5 and payload['SourceType'] == 1
+ assert payload['EngineModelType'] == '16k_zh_en_meeting'
+ assert payload['HotwordList'] == '志恒|5,Skill|5'
+ assert result.text == '你好\n测试'
+ assert result.segments[0].start_time == 0
+ assert result.segments[0].end_time == 1.2
+ assert result.speakers == ['SPEAKER_00', 'SPEAKER_01']
+ assert result.duration == 2.5
+
+
+def test_off_toggle_and_model_override(connector):
+ req = request(diarize=False, model='16k_zh_en_2.0')
+ assert connector._parameters(req)['SpeakerDiarization'] == 0
+ result = connector._parse_result({'ResultDetail': [
+ {'FinalSentence': 'hello', 'SpeakerId': 0, 'StartMs': 0, 'EndMs': 10}]}, req.model, False)
+ assert result.speakers is None and not result.has_diarization()
+
+
[email protected]('config', [{}, {'secret_id': 'a'},
+ {'secret_id': 'a', 'secret_key': 'b', 'model': 'whisper'},
+ {'secret_id': 'a', 'secret_key': 'b', 'timeout': 'nan'},
+ {'secret_id': 'a', 'secret_key': 'b', 'poll_interval': 0}])
+def test_invalid_config(config):
+ with pytest.raises(ConfigurationError):
+ mod.TencentASRConnector(config)
+
+
[email protected]('words', ['a|100', '中' * 11, ','.join(str(i) for i in range(129))])
+def test_invalid_hotwords(connector, words):
+ with pytest.raises(ConfigurationError):
+ connector._parameters(request(hotwords=words))
+
+
+def test_quota_error_no_secrets(connector, monkeypatch):
+ calls = transport(monkeypatch, [{'Error': {'Code': 'FailedOperation.UserHasNoAmount',
+ 'Message': 'SECRET URL PRIVATE'}}])
+ with pytest.raises(ProviderError, match='recording-file ASR quota') as exc:
+ connector.transcribe(request())
+ assert 'SECRET' not in str(exc.value) and len(calls) == 1
+
+
+def test_submission_transport_failure_never_retries(connector, monkeypatch):
+ calls = transport(monkeypatch, [httpx.ReadTimeout('PRIVATE')])
+ with pytest.raises(TranscriptionError, match='not retried') as exc:
+ connector.transcribe(request())
+ assert len(calls) == 1 and 'PRIVATE' not in str(exc.value)
+
+
+def test_poll_deadline_retains_task_id(connector, monkeypatch):
+ monkeypatch.setattr(connector, '_call', lambda *args: {'Status': 1})
+ with pytest.raises(TranscriptionError, match='task 42: polling timed out'):
+ connector._poll(None, 42)
+
+
+def test_empty_audio_never_submits(connector, monkeypatch):
+ monkeypatch.setattr(connector, '_call', Mock(side_effect=AssertionError('network')))
+ with pytest.raises(TranscriptionError, match='empty'):
+ connector.transcribe(request(b''))
+
+
[email protected]('status', [2, 3])
+def test_large_file_uses_private_staging_and_cleans_terminal(connector, monkeypatch, status):
+ monkeypatch.setattr(mod, 'INLINE_LIMIT', 5)
+ storage = Mock()
+ locator = object()
+ def stage(path, req):
+ assert mod.Path(path).read_bytes() == b'123456'
+ return storage, locator, 'https://bucket/file?signed=PRIVATE'
+ monkeypatch.setattr(connector, '_stage', stage)
+ calls = transport(monkeypatch, [{'Data': {'TaskId': 42}}, {'Data': {'Status': status, 'Result': 'text'}}])
+ if status == 2:
+ assert connector.transcribe(request(b'123456')).text == 'text'
+ else:
+ with pytest.raises(TranscriptionError, match='task 42 failed'):
+ connector.transcribe(request(b'123456'))
+ assert calls[0][1]['SourceType'] == 0 and 'Data' not in calls[0][1]
+ storage.delete.assert_called_once_with(locator, missing_ok=True)
+
+
+def test_ambiguous_submission_preserves_staging(connector, monkeypatch):
+ monkeypatch.setattr(mod, 'INLINE_LIMIT', 5)
+ storage = Mock()
+ monkeypatch.setattr(connector, '_stage', lambda *args: (storage, object(), 'https://bucket/file'))
+ transport(monkeypatch, [httpx.ReadTimeout('private')])
+ with pytest.raises(TranscriptionError):
+ connector.transcribe(request(b'123456'))
+ storage.delete.assert_not_called()
+
+
+def test_staging_requires_s3(connector, monkeypatch):
+ import src.services.storage as module
+ monkeypatch.setattr(module, 'get_storage_service', lambda: SimpleNamespace(s3=None))
+ with pytest.raises(ConfigurationError, match='over 5 MiB'):
+ connector._stage('/unused', request())
+
+
+def test_registry_isolates_credentials_and_model(monkeypatch):
+ from src.services.transcription.registry import get_registry
+ monkeypatch.setenv('TENCENT_SECRET_ID', 'tencent-id')
+ monkeypatch.setenv('TENCENT_SECRET_KEY', 'tencent-key')
+ monkeypatch.setenv('TRANSCRIPTION_API_KEY', 'foreign')
+ monkeypatch.setenv('TRANSCRIPTION_MODEL', 'whisper-1')
+ monkeypatch.setenv('TRANSCRIPTION_BASE_URL', 'https://untrusted')
+ registry = get_registry()
+ config = registry._build_config_from_env('tencent_asr')
+ connector = registry.create_connector('tencent_asr', config)
+ assert connector.secret_id == 'tencent-id'
+ assert connector.secret_key == 'tencent-key'
+ assert connector.model == '16k_zh_en_meeting'
+ assert 'base_url' not in config
+
+
+def test_inline_boundary(connector, monkeypatch):
+ monkeypatch.setattr(mod, 'INLINE_LIMIT', 5)
+ monkeypatch.setattr(connector, '_stage', Mock(side_effect=AssertionError('unexpected staging')))
+ calls = transport(monkeypatch, [{'Data': {'TaskId': 42}}, {'Data': {'Status': 2, 'Result': 'ok'}}])
+ assert connector.transcribe(request(b'12345')).text == 'ok'
+ assert calls[0][1]['SourceType'] == 1
+
+
+def test_file_limit_before_upload(connector, monkeypatch):
+ monkeypatch.setattr(mod, 'INLINE_LIMIT', 5)
+ monkeypatch.setattr(mod, 'FILE_LIMIT', 10)
+ monkeypatch.setattr(connector, '_stage', Mock(side_effect=AssertionError('unexpected staging')))
+ with pytest.raises(TranscriptionError, match='exceeds'):
+ connector.transcribe(request(b'12345678901'))
+
+
+def test_staging_presigns_and_cleans_partial_failure(connector, monkeypatch, tmp_path):
+ import src.services.storage as module
+ backend = Mock()
+ backend.build_locator.return_value = 's3://bucket/tencent-asr/test.wav'
+ backend.presign_get_url.return_value = 'https://bucket/test?signed=PRIVATE'
+ monkeypatch.setattr(module, 'get_storage_service', lambda: SimpleNamespace(s3=backend))
+ path = tmp_path / 'audio'
+ path.write_bytes(b'audio')
+ actual_backend, locator, url = connector._stage(str(path), request())
+ assert actual_backend is backend and 'signed=' in url
+ assert backend.upload_local_file.call_args.args[1].startswith('tencent-asr/')
+ backend.presign_get_url.assert_called_once_with(locator, expires_seconds=86400)
+ backend.presign_get_url.side_effect = RuntimeError('PRIVATE')
+ with pytest.raises(TranscriptionError) as exc:
+ connector._stage(str(path), request())
+ assert 'PRIVATE' not in str(exc.value)
+ backend.delete.assert_called_once()
+
+
+def test_submission_rejection_removes_staging(connector, monkeypatch):
+ monkeypatch.setattr(mod, 'INLINE_LIMIT', 5)
+ storage = Mock()
+ monkeypatch.setattr(connector, '_stage', lambda *args: (storage, 'locator', 'https://bucket/file'))
+ transport(monkeypatch, [{'Error': {'Code': 'AuthFailure.SecretIdNotFound'}}])
+ with pytest.raises(ProviderError):
+ connector.transcribe(request(b'123456'))
+ storage.delete.assert_called_once_with('locator', missing_ok=True)
+
+
[email protected]('envelope', [[], {'Data': []}, {'Error': 'bad'}, {}])
+def test_malformed_response_is_safe(connector, monkeypatch, envelope):
+ transport(monkeypatch, [envelope])
+ with pytest.raises(ProviderError, match='invalid JSON'):
+ connector.transcribe(request())
+
+
+def test_unknown_speaker_not_fabricated(connector):
+ result = connector._parse_result({'ResultDetail': [
+ {'FinalSentence': 'one', 'SpeakerId': -1}, {'FinalSentence': 'two'}]}, mod.MODELS[0], True)
+ assert not result.has_diarization()
+ assert result.segments[0].start_time is None