Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
feat: add MOSS-Transcribe-Diarize connector (Mossland API) (#330)
siva-sub2f7d5871b40d
diff --git a/README.md b/README.mdindex a1586d80..118c7958 100644--- a/README.md+++ b/README.md@@ -149,6 +149,7 @@ Speakr uses a **connector-based architecture** that auto-detects your transcript| **WhisperX ASR** | GPU container | Yes (best quality) | Yes || **Mistral Voxtral** | Just API key | Yes (built-in) | No || **VibeVoice ASR** | Self-hosted (vLLM) | Yes (built-in) | No |+| **MOSI/Mossland MOSS** | Hosted API key | Yes (built-in) | No || **AssemblyAI** | Just API key | Yes (built-in) | No || **Legacy Whisper** | Just API key | No | No |@@ -178,6 +179,15 @@ TRANSCRIPTION_CONNECTOR=vibevoiceTRANSCRIPTION_BASE_URL=http://your-vllm-server:8000TRANSCRIPTION_MODEL=vibevoice```+Requires [VibeVoice](https://huggingface.co/microsoft/VibeVoice-ASR) served via vLLM with GPU.++**MOSI/Mossland MOSS (hosted multi-speaker transcription):**+```bash+TRANSCRIPTION_CONNECTOR=mossland+TRANSCRIPTION_API_KEY=your-mosi-api-key+TRANSCRIPTION_MODEL=moss-transcribe-diarize+```+Create a key in the [MOSI API Key console](https://studio.mosi.cn/app/api-keys). The connector keeps long recordings in one provider task so speaker labels remain consistent, and it resumes stalled SSE jobs through task polling without submitting a duplicate. This connector uploads recordings to the third-party MOSI/Mossland service at `api.mosi.cn`; audio is not processed entirely on your self-hosted Speakr instance.**AssemblyAI (cloud diarization, long multi-speaker meetings):**```bash@@ -185,7 +195,6 @@ TRANSCRIPTION_CONNECTOR=assemblyaiTRANSCRIPTION_API_KEY=your-assemblyai-key```Handles multi-hour, multi-speaker files in a single job. New accounts get free credits with no card required.-Requires [VibeVoice](https://huggingface.co/microsoft/VibeVoice-ASR) served via vLLM with GPU.> **PyTorch 2.6 Users:** If you encounter a "Weights only load failed" error with WhisperX, add `TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD=true` to your ASR container. See [troubleshooting](https://murtaza-nasir.github.io/speakr/troubleshooting#pytorch-26-weights-loading-error-whisperx-asr-service) for details.diff --git a/config/env.transcription.example b/config/env.transcription.exampleindex 82942d85..94b33533 100644--- a/config/env.transcription.example+++ b/config/env.transcription.example@@ -62,7 +62,7 @@ GPT5_VERBOSITY=medium# =============================================================================# CONNECTOR SELECTION (Auto-detected if not set)# =============================================================================-# Options: openai_whisper, openai_transcribe, asr_endpoint, mistral, vibevoice, assemblyai+# Options: openai_whisper, openai_transcribe, asr_endpoint, mistral, vibevoice, mossland, assemblyai# Leave empty to auto-detect based on other settings# TRANSCRIPTION_CONNECTOR=@@ -162,6 +162,28 @@ TRANSCRIPTION_MODEL=gpt-4o-transcribe-diarize# If your vLLM server requires authentication:# TRANSCRIPTION_API_KEY=your_api_key+# =============================================================================+# MOSI / MOSSLAND MOSS CONFIGURATION (Hosted Cloud API)+# =============================================================================+# MOSS provides single-speaker transcription and multi-speaker diarization.+# Diarized audio stays in one provider task so speaker identities remain stable;+# Speakr app-level chunking is disabled for this connector. The connector uses+# SSE first, then resumes a stalled SSE task through the documented task API.+# It sends one fixed 131072-token output ceiling for long-form transcription.+#+# Privacy: recordings are uploaded to the third-party MOSI/Mossland service at+# api.mosi.cn. They are not processed entirely on your self-hosted Speakr host.+# Create an API key at https://studio.mosi.cn/app/api-keys.+#+# TRANSCRIPTION_CONNECTOR=mossland+# TRANSCRIPTION_API_KEY=your_mosi_api_key+# TRANSCRIPTION_MODEL=moss-transcribe-diarize+# Available transcription models are read on demand from GET /v1/models; the+# two documented model IDs remain available if model discovery is offline.+#+# Optional API-compatible proxy or alternate endpoint:+# TRANSCRIPTION_BASE_URL=https://api.mosi.cn+# =============================================================================# ASSEMBLYAI CONFIGURATION (Cloud)# =============================================================================@@ -206,6 +228,7 @@ TRANSCRIPTION_MODEL=gpt-4o-transcribe-diarize# For openai_transcribe/asr_endpoint/mistral: These settings are IGNORED (connector handles it)# For openai_whisper: These settings control chunking behavior# For vibevoice: App chunks files >58 min into ~50 min pieces automatically+# For mossland: App chunking is disabled to preserve speaker identity across long audio# ENABLE_CHUNKING=false # Uncomment to disable chunking for openai_whisper@@ -249,6 +272,11 @@ CHUNK_OVERLAP_SECONDS=3# TRANSCRIPTION_CONNECTOR=vibevoice# TRANSCRIPTION_BASE_URL=http://your-vllm-server:8000# TRANSCRIPTION_MODEL=vibevoice+#+# --- MOSI/Mossland MOSS (hosted diarization) ---+# TRANSCRIPTION_CONNECTOR=mossland+# TRANSCRIPTION_API_KEY=your_mosi_api_key+# TRANSCRIPTION_MODEL=moss-transcribe-diarize# =============================================================================# APPLICATION SETTINGSdiff --git a/src/services/transcription/connectors/__init__.py b/src/services/transcription/connectors/__init__.pyindex b04d7714..d8018c95 100644--- a/src/services/transcription/connectors/__init__.py+++ b/src/services/transcription/connectors/__init__.py@@ -8,6 +8,7 @@ from .asr_endpoint import ASREndpointConnectorfrom .azure_openai_transcribe import AzureOpenAITranscribeConnectorfrom .mistral import MistralTranscriptionConnectorfrom .vibevoice import VibeVoiceTranscriptionConnector+from .mossland import MosslandTranscriptionConnector__all__ = ['OpenAIWhisperConnector',@@ -16,4 +17,5 @@ __all__ = ['AzureOpenAITranscribeConnector','MistralTranscriptionConnector','VibeVoiceTranscriptionConnector',+ 'MosslandTranscriptionConnector',]diff --git a/src/services/transcription/connectors/mossland.py b/src/services/transcription/connectors/mossland.pynew file mode 100644index 00000000..d0659262--- /dev/null+++ b/src/services/transcription/connectors/mossland.py@@ -0,0 +1,372 @@+"""MOSS transcription through the hosted MOSI/Mossland API.++Recordings sent through this connector leave the self-hosted Speakr instance+and are processed by the third-party service at api.mosi.cn.+"""++import json+import logging+import time+from typing import Any++import httpx++from ..base import (+ BaseTranscriptionConnector, ConnectorSpecifications, TranscriptionCapability,+ TranscriptionRequest, TranscriptionResponse, TranscriptionSegment,+)+from ..exceptions import ConfigurationError, ProviderError, TranscriptionError++logger = logging.getLogger(__name__)++_DEFAULT_BASE_URL = "https://api.mosi.cn"+_DEFAULT_MODEL = "moss-transcribe-diarize"+_STREAMING_VERSION = "v20260410-streamparam-20260703"+_DIARIZE_VERSION = "moss-transcribe-diarize-20260325"+_SAMPLING_PARAMS = json.dumps({"max_new_tokens": 131072, "temperature": 0})+_SAFE_ASYNC_FALLBACK_STATUSES = frozenset({400, 404, 405})+_MODELS: dict[str, dict[str, Any]] = {+ "moss-transcribe-diarize": {+ "diarize": True, "streaming_version": _STREAMING_VERSION,+ "async_version": _DIARIZE_VERSION,+ "description": "Multi-speaker transcription with diarization and timestamps",+ },+ "moss-transcribe": {"diarize": False, "description": "Single-speaker transcription"},+}+++class _StreamInterrupted(TranscriptionError):+ def __init__(self, message: str, task_id: str | None = None):+ super().__init__(message)+ self.task_id = task_id+++class MosslandTranscriptionConnector(BaseTranscriptionConnector):+ """Use MOSI streaming and recover stalled jobs through task polling."""++ CAPABILITIES: set[TranscriptionCapability] = {+ TranscriptionCapability.DIARIZATION,+ TranscriptionCapability.TIMESTAMPS,+ TranscriptionCapability.LANGUAGE_DETECTION,+ TranscriptionCapability.HOTWORDS,+ }+ PROVIDER_NAME = "mossland"++ # Any declared hard limit makes Speakr chunk before it checks this flag.+ # Leave limits unset so one MOSI task retains speaker identity end to end.+ SPECIFICATIONS = ConnectorSpecifications(+ max_file_size_bytes=None, max_duration_seconds=None,+ handles_chunking_internally=True, recommended_chunk_seconds=0,+ )++ def __init__(self, config: dict[str, Any]):+ self.api_key = (config.get("api_key") or "").strip()+ self.base_url = (config.get("base_url") or _DEFAULT_BASE_URL).strip().rstrip("/")+ self.model = (config.get("model") or _DEFAULT_MODEL).strip()+ self.poll_interval = float(config.get("poll_interval", 5.0))+ self.poll_timeout = float(config.get("poll_timeout", 7200.0))+ self.stream_read_timeout = float(config.get("stream_read_timeout", 180.0))+ super().__init__(config)+ if not self._model_info(self.model)["diarize"]:+ self.CAPABILITIES = self.CAPABILITIES - {TranscriptionCapability.DIARIZATION}++ def _validate_config(self) -> None:+ if not self.api_key:+ raise ConfigurationError("api_key is required (set TRANSCRIPTION_API_KEY)")+ if not self.model.startswith("moss-transcribe"):+ raise ConfigurationError(+ "Mossland model must be a transcription model returned by GET /v1/models"+ )++ def _client(self) -> httpx.Client:+ timeout = httpx.Timeout(+ connect=120.0, read=self.stream_read_timeout, write=300.0, pool=120.0+ )+ return httpx.Client(+ base_url=self.base_url, timeout=timeout,+ headers={+ "Authorization": f"Bearer {self.api_key}",+ "User-Agent": "Speakr/1.0 (https://github.com/murtaza-nasir/speakr)",+ },+ )++ @staticmethod+ def _read_audio(request: TranscriptionRequest) -> bytes:+ if hasattr(request.audio_file, "seek"):+ request.audio_file.seek(0)+ data = request.audio_file.read()+ if not data:+ raise TranscriptionError("Mossland: empty audio file")+ return data++ def _effective_mossland_model(self, request: TranscriptionRequest) -> str:+ model = self._effective_model(request) or self.model+ if model.startswith("moss-transcribe"):+ return model+ logger.warning("Ignoring non-transcription model %r; using %r", model, self.model)+ return self.model++ @staticmethod+ def _model_info(model: str) -> dict[str, Any]:+ if model in _MODELS:+ return _MODELS[model]+ diarize = "diarize" in model.lower()+ return {+ "diarize": diarize,+ "streaming_version": _STREAMING_VERSION if diarize else None,+ "async_version": _DIARIZE_VERSION if diarize else None,+ "description": model,+ }++ def _form_data(+ self, request: TranscriptionRequest, model: str, mode: str+ ) -> dict[str, str]:+ info = self._model_info(model)+ data = {"model": model, "response_format": "json"}+ if info["diarize"]:+ data.update(diarize="true", sampling_params=_SAMPLING_PARAMS)+ if version := info.get(f"{mode}_version"):+ data["version"] = version+ if mode in ("streaming", "async"):+ data["stream" if mode == "streaming" else "async"] = "true"+ if request.hotwords:+ data["hotwords"] = request.hotwords+ return data++ @staticmethod+ def _files(request: TranscriptionRequest, audio: bytes) -> dict:+ return {"file": (request.filename or "audio", audio, request.mime_type or "audio/mpeg")}++ @staticmethod+ def _segments(raw_segments: list[dict[str, Any]]) -> list[TranscriptionSegment]:+ result = []+ for raw in raw_segments:+ text = (raw.get("text") or "").strip()+ if text:+ result.append(TranscriptionSegment(+ text=text, speaker=raw.get("speaker") or None,+ start_time=float(raw.get("start", 0) or 0),+ end_time=float(raw.get("end", 0) or 0),+ ))+ return result++ @classmethod+ def _result(+ cls, text: str, segments: list[TranscriptionSegment], model: str,+ raw: dict[str, Any] | None = None,+ ) -> TranscriptionResponse:+ text = text or " ".join(segment.text for segment in segments)+ speakers = sorted({segment.speaker for segment in segments if segment.speaker})+ metadata = raw or {}+ return TranscriptionResponse(+ text=text, segments=segments or None, speakers=speakers or None,+ language=metadata.get("language"), duration=metadata.get("duration"),+ provider=cls.PROVIDER_NAME, model=model, raw_response=raw,+ )++ @classmethod+ def _api_error(cls, label: str, response: httpx.Response) -> ProviderError:+ return ProviderError(+ f"Mossland {label} failed ({response.status_code}): {response.text[:300]}",+ provider=cls.PROVIDER_NAME, status_code=response.status_code,+ )++ def _transcribe_primary(+ self, client: httpx.Client, request: TranscriptionRequest,+ audio: bytes, model: str,+ ) -> TranscriptionResponse:+ if not self._model_info(model)["diarize"]:+ response = client.post(+ "/v1/audio/transcriptions", files=self._files(request, audio),+ data=self._form_data(request, model, "sync"),+ )+ if response.status_code != 200:+ raise self._api_error("transcription", response)+ payload = response.json()+ return self._result(+ payload.get("text") or "", self._segments(payload.get("segments") or []),+ model, payload,+ )++ segments, deltas = [], []+ text, task_id = "", None+ try:+ with client.stream(+ "POST", "/v1/audio/transcriptions",+ files=self._files(request, audio),+ data=self._form_data(request, model, "streaming"),+ ) as response:+ if response.status_code != 200:+ response.read()+ raise self._api_error("streaming", response)+ for line in response.iter_lines():+ if not line.startswith("data:"):+ continue+ value = line[5:].strip()+ if not value or value == "[DONE]":+ continue+ try:+ event = json.loads(value)+ except json.JSONDecodeError:+ logger.debug("Ignoring malformed Mossland SSE event")+ continue+ kind = event.get("type")+ if kind == "task.created":+ task_id = event.get("task_id") or event.get("id") or task_id+ elif kind == "transcript.segment.done":+ segments.extend(self._segments([event]))+ elif kind == "transcript.text.delta":+ deltas.append(event.get("delta") or "")+ elif kind == "transcript.text.done":+ text = event.get("text") or text+ except httpx.HTTPError as error:+ raise _StreamInterrupted(f"Mossland SSE interrupted: {error}", task_id) from error++ text = text or "".join(deltas)+ if text or segments:+ return self._result(text, segments, model)+ if task_id:+ raise _StreamInterrupted("Mossland SSE ended before transcript", task_id)+ raise TranscriptionError("Mossland streaming returned no transcript or task id")++ @staticmethod+ def _sleep_for_poll(delay: float, deadline: float) -> None:+ remaining = deadline - time.monotonic()+ if remaining > 0:+ time.sleep(min(max(0.0, delay), remaining))++ def _poll_task(+ self, client: httpx.Client, task_id: str, model: str,+ retry_after: float | None = None,+ ) -> TranscriptionResponse:+ deadline = time.monotonic() + self.poll_timeout+ paths = [f"/v1/audio/transcriptions/{task_id}", f"/v1/audio/tasks/{task_id}"]+ path_index = 0+ delay = self.poll_interval if retry_after is None else float(retry_after)+ while True:+ try:+ response = client.get(paths[path_index], timeout=30.0)+ except httpx.HTTPError as error:+ if time.monotonic() >= deadline:+ raise TranscriptionError(f"Mossland task {task_id} unreachable") from error+ logger.warning("Mossland poll transport error; retrying: %s", error)+ self._sleep_for_poll(delay, deadline)+ continue+ if response.status_code in (404, 405) and path_index == 0:+ path_index = 1+ continue+ if response.status_code == 429 or response.status_code >= 500:+ if time.monotonic() >= deadline:+ raise TranscriptionError(f"Mossland task {task_id} did not recover")+ self._sleep_for_poll(delay, deadline)+ continue+ if response.status_code != 200:+ raise self._api_error("poll", response)++ payload = response.json()+ status = (payload.get("status") or "").upper()+ if status in ("SUCCESS", "COMPLETED"):+ return self._result(+ payload.get("text") or "", self._segments(payload.get("segments") or []),+ model, payload,+ )+ if status in ("FAILED", "ERROR"):+ detail = payload.get("error") or payload.get("message") or status+ if isinstance(detail, dict):+ detail = detail.get("error_msg") or detail.get("message") or str(detail)+ raise TranscriptionError(f"Mossland task failed: {detail}")+ if time.monotonic() >= deadline:+ raise TranscriptionError(+ f"Mossland transcription timed out after {self.poll_timeout:.0f}s "+ f"(task {task_id} still {status or 'pending'})"+ )+ if payload.get("retry_after") is not None:+ delay = float(payload["retry_after"])+ self._sleep_for_poll(delay, deadline)++ def _transcribe_async(+ self, client: httpx.Client, request: TranscriptionRequest,+ audio: bytes, model: str,+ ) -> TranscriptionResponse:+ # Never retry this POST: an ambiguous retry can create a second billable task.+ response = client.post(+ "/v1/audio/transcriptions", files=self._files(request, audio),+ data=self._form_data(request, model, "async"),+ )+ if response.status_code not in (200, 201):+ raise self._api_error("async submit", response)+ payload = response.json()+ segments = self._segments(payload.get("segments") or [])+ status = (payload.get("status") or "").upper()+ if status in ("SUCCESS", "COMPLETED") and (payload.get("text") or segments):+ return self._result(payload.get("text") or "", segments, model, payload)+ task_id = payload.get("task_id") or payload.get("id")+ if not task_id:+ if payload.get("text") or segments:+ return self._result(payload.get("text") or "", segments, model, payload)+ raise ProviderError("Mossland async submit returned no task id", self.PROVIDER_NAME)+ return self._poll_task(client, task_id, model, payload.get("retry_after"))++ def transcribe(self, request: TranscriptionRequest) -> TranscriptionResponse:+ audio = self._read_audio(request)+ model = self._effective_mossland_model(request)+ try:+ with self._client() as client:+ try:+ return self._transcribe_primary(client, request, audio, model)+ except _StreamInterrupted as error:+ if error.task_id:+ logger.warning("Mossland SSE stalled; polling task %s", error.task_id)+ return self._poll_task(client, error.task_id, model)+ raise TranscriptionError(+ "Mossland SSE failed before returning a task id; not resubmitting "+ "to avoid a duplicate billable task"+ ) from error+ except ProviderError as error:+ safe = error.status_code in _SAFE_ASYNC_FALLBACK_STATUSES+ if self._model_info(model)["diarize"] and safe:+ logger.warning("Mossland SSE rejected; using async fallback")+ return self._transcribe_async(client, request, audio, model)+ raise+ except (ProviderError, TranscriptionError):+ raise+ except Exception as error:+ logger.error("Mossland transcription failed: %s", error)+ raise TranscriptionError(f"Mossland transcription failed: {error}") from error++ def health_check(self) -> bool:+ return bool(self.api_key)++ def list_models(self) -> list[dict[str, str]]:+ """Discover models on demand; use documented models while offline."""+ try:+ with self._client() as client:+ response = client.get("/v1/models", timeout=15.0)+ response.raise_for_status()+ models = [+ {"id": item["id"], "label": item["id"],+ "owned_by": item.get("owned_by", "MOSI")}+ for item in response.json().get("data", [])+ if (item.get("id") or "").startswith("moss-transcribe")+ ]+ if models:+ return models+ except (httpx.HTTPError, ValueError, TypeError) as error:+ logger.warning("Mossland GET /v1/models failed; using fallback: %s", error)+ return [+ {"id": model, "label": model, "description": info["description"]}+ for model, info in _MODELS.items()+ ]++ @classmethod+ def get_config_schema(cls) -> dict[str, Any]:+ return {+ "type": "object", "required": ["api_key"],+ "properties": {+ "api_key": {"type": "string", "description": "MOSI/Mossland API key"},+ "base_url": {"type": "string", "default": _DEFAULT_BASE_URL,+ "description": "MOSI/Mossland API base URL"},+ "model": {"type": "string", "default": _DEFAULT_MODEL,+ "description": "Model returned by MOSI GET /v1/models"},+ },+ }diff --git a/src/services/transcription/registry.py b/src/services/transcription/registry.pyindex 05e3d4d2..20a0df4a 100644--- a/src/services/transcription/registry.py+++ b/src/services/transcription/registry.py@@ -47,6 +47,7 @@ class ConnectorRegistry:from .connectors.azure_openai_transcribe import AzureOpenAITranscribeConnectorfrom .connectors.mistral import MistralTranscriptionConnectorfrom .connectors.vibevoice import VibeVoiceTranscriptionConnector+ from .connectors.mossland import MosslandTranscriptionConnectorfrom .connectors.assemblyai import AssemblyAITranscriptionConnectorself.register('openai_whisper', OpenAIWhisperConnector)@@ -55,6 +56,7 @@ class ConnectorRegistry:self.register('azure_openai_transcribe', AzureOpenAITranscribeConnector)self.register('mistral', MistralTranscriptionConnector)self.register('vibevoice', VibeVoiceTranscriptionConnector)+ self.register('mossland', MosslandTranscriptionConnector)self.register('assemblyai', AssemblyAITranscriptionConnector)def register(self, name: str, connector_class: Type[BaseTranscriptionConnector]):@@ -291,6 +293,17 @@ class ConnectorRegistry:'api_key': os.environ.get('TRANSCRIPTION_API_KEY', ''),}+ elif connector_name == 'mossland':+ base_url = os.environ.get('TRANSCRIPTION_BASE_URL', '')+ if base_url:+ base_url = base_url.split('#')[0].strip()++ return {+ 'api_key': os.environ.get('TRANSCRIPTION_API_KEY', ''),+ 'base_url': base_url or 'https://api.mosi.cn',+ 'model': os.environ.get('TRANSCRIPTION_MODEL', 'moss-transcribe-diarize'),+ }+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 leftdiff --git a/tests/test_mossland_connector.py b/tests/test_mossland_connector.pynew file mode 100644index 00000000..79f470ab--- /dev/null+++ b/tests/test_mossland_connector.py@@ -0,0 +1,298 @@+"""Contract and recovery tests for the MOSI/Mossland connector."""++import io+from unittest.mock import patch++import httpx+import pytest++from src.services.transcription.base import TranscriptionCapability, TranscriptionRequest+from src.services.transcription.connectors.mossland import MosslandTranscriptionConnector+from src.services.transcription.exceptions import ConfigurationError, TranscriptionError+++class _Response:+ def __init__(self, status_code=200, payload=None, text="", lines=None):+ self.status_code = status_code+ self._payload = payload or {}+ self.text = text+ self._lines = lines or []++ def __enter__(self):+ return self++ def __exit__(self, *args):+ return False++ def json(self):+ return self._payload++ def read(self):+ return self.text.encode()++ def iter_lines(self):+ for item in self._lines:+ if isinstance(item, Exception):+ raise item+ yield item++ def raise_for_status(self):+ if self.status_code >= 400:+ request = httpx.Request("GET", "https://api.mosi.cn/v1/models")+ response = httpx.Response(self.status_code, request=request)+ raise httpx.HTTPStatusError(self.text, request=request, response=response)+++class _Client:+ def __init__(self, stream_response=None, posts=None, gets=None, stream_error=None):+ self.stream_response = stream_response+ self.posts = list(posts or [])+ self.gets = list(gets or [])+ self.stream_error = stream_error+ self.calls = []++ def __enter__(self):+ return self++ def __exit__(self, *args):+ return False++ def stream(self, method, path, **kwargs):+ self.calls.append(("stream", path, kwargs))+ if self.stream_error:+ raise self.stream_error+ return self.stream_response++ def post(self, path, **kwargs):+ self.calls.append(("post", path, kwargs))+ return self.posts.pop(0)++ def get(self, path, **kwargs):+ self.calls.append(("get", path, kwargs))+ item = self.gets.pop(0)+ if isinstance(item, Exception):+ raise item+ return item+++def _connector(**config):+ values = {"api_key": "test-key", "poll_interval": 0}+ values.update(config)+ return MosslandTranscriptionConnector(values)+++def _request(**values):+ values.setdefault("audio_file", io.BytesIO(b"audio-bytes"))+ values.setdefault("filename", "meeting.wav")+ values.setdefault("mime_type", "audio/wav")+ return TranscriptionRequest(**values)+++def _success(text="One two"):+ return _Response(payload={+ "status": "SUCCESS",+ "text": text,+ "duration": 2.0,+ "segments": [+ {"speaker": "S01", "text": "One", "start": 0, "end": 1},+ {"speaker": "S02", "text": "two", "start": 1, "end": 2},+ ],+ })+++def test_constructor_does_not_touch_network():+ with patch("src.services.transcription.connectors.mossland.httpx.Client") as client:+ connector = _connector()+ client.assert_not_called()+ assert connector.model == "moss-transcribe-diarize"+++def test_long_form_specs_disable_speakr_chunking(monkeypatch):+ from src.audio_chunking import get_effective_chunking_config++ connector = _connector()+ specs = connector.specifications+ assert specs.handles_chunking_internally is True+ assert specs.max_duration_seconds is None+ assert specs.max_file_size_bytes is None+ assert specs.recommended_chunk_seconds == 0+ monkeypatch.setenv("ENABLE_CHUNKING", "true")+ monkeypatch.setenv("CHUNK_LIMIT", "20MB")+ effective = get_effective_chunking_config(specs)+ assert effective.enabled is False+ assert effective.source == "connector_internal"++ with pytest.raises(ConfigurationError, match="transcription model"):+ _connector(model="moss-tts")+ with pytest.raises(ConfigurationError, match="api_key"):+ MosslandTranscriptionConnector({"api_key": ""})+++def test_sse_primary_uses_contract_and_parses_events():+ stream = _Response(lines=[+ 'data: {"type":"task.created","task_id":"task-1"}',+ 'data: {"type":"transcript.text.delta","delta":"Hello "}',+ 'data: {"type":"transcript.segment.done","speaker":"S01","text":"Hello","start":0,"end":1.5}',+ 'data: {"type":"transcript.text.done","text":"Hello there"}',+ "data: [DONE]",+ ])+ client = _Client(stream_response=stream)+ connector = _connector()++ with patch.object(connector, "_client", return_value=client):+ result = connector.transcribe(_request(hotwords="Speakr, MOSI"))++ assert result.text == "Hello there"+ assert result.speakers == ["S01"]+ _, path, kwargs = client.calls[0]+ assert path == "/v1/audio/transcriptions"+ assert kwargs["data"]["version"] == "v20260410-streamparam-20260703"+ assert kwargs["data"]["stream"] == "true"+ assert kwargs["data"]["response_format"] == "json"+ assert kwargs["data"]["hotwords"] == "Speakr, MOSI"+ assert '"max_new_tokens": 131072' in kwargs["data"]["sampling_params"]+++def test_stalled_sse_resumes_existing_task_without_duplicate_post():+ timeout = httpx.ReadTimeout(+ "stalled", request=httpx.Request("POST", "https://api.mosi.cn/v1/audio/transcriptions")+ )+ client = _Client(+ stream_response=_Response(lines=[+ 'data: {"type":"task.created","task_id":"task-existing"}',+ timeout,+ ]),+ gets=[+ _Response(status_code=404),+ _Response(payload={"status": "PROCESSING", "retry_after": 0}),+ _success("Recovered"),+ ],+ )+ connector = _connector()++ with patch.object(connector, "_client", return_value=client):+ result = connector.transcribe(_request())++ assert result.text == "Recovered"+ assert not [call for call in client.calls if call[0] == "post"]+ assert [call[1] for call in client.calls if call[0] == "get"] == [+ "/v1/audio/transcriptions/task-existing",+ "/v1/audio/tasks/task-existing",+ "/v1/audio/tasks/task-existing",+ ]+++def test_safe_sse_rejection_uses_one_async_submission():+ client = _Client(+ stream_response=_Response(status_code=400, text="stream unsupported"),+ posts=[_Response(payload={"task_id": "task-2", "status": "PENDING", "retry_after": 0})],+ gets=[_Response(status_code=404), _success()],+ )+ connector = _connector()++ with patch.object(connector, "_client", return_value=client):+ result = connector.transcribe(_request())++ assert result.text == "One two"+ posts = [call for call in client.calls if call[0] == "post"]+ assert len(posts) == 1+ assert posts[0][2]["data"]["async"] == "true"+ assert posts[0][2]["data"]["version"] == "moss-transcribe-diarize-20260325"+++def test_stream_failure_without_task_id_is_not_resubmitted():+ timeout = httpx.ReadTimeout(+ "stalled", request=httpx.Request("POST", "https://api.mosi.cn/v1/audio/transcriptions")+ )+ client = _Client(stream_error=timeout)+ connector = _connector()++ with patch.object(connector, "_client", return_value=client):+ with pytest.raises(TranscriptionError, match="not resubmitting"):+ connector.transcribe(_request())+ assert not [call for call in client.calls if call[0] == "post"]+++def test_poll_recovers_from_transport_and_server_errors():+ connection_error = httpx.ConnectError(+ "offline", request=httpx.Request("GET", "https://api.mosi.cn/task")+ )+ client = _Client(gets=[+ connection_error,+ _Response(status_code=503),+ _success("Eventually completed"),+ ])+ connector = _connector()++ result = connector._poll_task(client, "task-retry", connector.model, retry_after=0)++ assert result.text == "Eventually completed"+ assert len([call for call in client.calls if call[0] == "get"]) == 3+++def test_poll_timeout_is_terminal():+ client = _Client(gets=[_Response(payload={"status": "PROCESSING"})])+ connector = _connector(poll_timeout=0)++ with pytest.raises(TranscriptionError, match="timed out"):+ connector._poll_task(client, "task-timeout", connector.model, retry_after=0)+++def test_standard_model_uses_synchronous_json_contract():+ client = _Client(posts=[_Response(payload={"text": "plain transcript"})])+ connector = _connector(model="moss-transcribe")++ with patch.object(connector, "_client", return_value=client):+ result = connector.transcribe(_request())++ assert result.text == "plain transcript"+ assert connector.supports(TranscriptionCapability.DIARIZATION) is False+ assert [call[0] for call in client.calls] == ["post"]+ data = client.calls[0][2]["data"]+ assert data["model"] == "moss-transcribe"+ assert "stream" not in data and "version" not in data+ assert "sampling_params" not in data+++def test_models_are_discovered_on_demand_and_filtered():+ client = _Client(gets=[_Response(payload={"data": [+ {"id": "moss-transcribe", "owned_by": "OpenMOSS-Team"},+ {"id": "moss-transcribe-diarize", "owned_by": "OpenMOSS-Team"},+ {"id": "moss-tts", "owned_by": "OpenMOSS-Team"},+ ]})])+ connector = _connector()++ with patch.object(connector, "_client", return_value=client):+ models = connector.list_models()++ assert [model["id"] for model in models] == [+ "moss-transcribe", "moss-transcribe-diarize"+ ]+ assert client.calls[0][1] == "/v1/models"+++def test_model_discovery_failure_uses_static_fallback():+ error = httpx.ConnectError(+ "offline", request=httpx.Request("GET", "https://api.mosi.cn/v1/models")+ )+ connector = _connector()+ with patch.object(connector, "_client", return_value=_Client(gets=[error])):+ models = connector.list_models()+ assert {model["id"] for model in models} == {+ "moss-transcribe", "moss-transcribe-diarize"+ }+++def test_registry_maps_shared_environment_variables(monkeypatch):+ from src.services.transcription.registry import ConnectorRegistry++ monkeypatch.setenv("TRANSCRIPTION_API_KEY", "env-key")+ monkeypatch.setenv("TRANSCRIPTION_BASE_URL", "https://proxy.example/v1 # proxy")+ monkeypatch.setenv("TRANSCRIPTION_MODEL", "moss-transcribe")+ registry = object.__new__(ConnectorRegistry)++ assert registry._build_config_from_env("mossland") == {+ "api_key": "env-key",+ "base_url": "https://proxy.example/v1",+ "model": "moss-transcribe",+ }