diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2577e4b5..74af5aef 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -114,15 +114,25 @@ Remember that most TTS services require credentials to work and thus you must br ```bash POLLY_REGION= -POLLY_AWS_ID= -POLLY_AWS_KEY= +POLLY_AWS_KEY_ID= +POLLY_AWS_ACCESS_KEY= -MICROSOFT_KEY= +MICROSOFT_TOKEN= +MICROSOFT_REGION= GOOGLE_SA_PATH=.secrets/google.json +GOOGLE_SA_FILE_B64= WATSON_API_KEY= -WATSON_API_URL= +WATSON_REGION= +WATSON_INSTANCE_ID= + +ELEVENLABS_API_KEY= +WITAI_TOKEN= +PLAYHT_API_KEY= +PLAYHT_USER_ID= +UPLIFTAI_KEY= +MODELSLAB_API_KEY= ``` For PicoTTS you also need to install the package for your system. Check the documentation for how to do that. @@ -148,7 +158,7 @@ You don't actually need to run tests for all services if you don't want to. Sinc ```Python source .secrets/.env && \ - export POLLY_REGION POLLY_AWS_ID POLLY_AWS_KEY && \ + export POLLY_REGION POLLY_AWS_KEY_ID POLLY_AWS_ACCESS_KEY && \ pytest tests/engines/test_polly.py ``` diff --git a/README.md b/README.md index 39c32da5..78078d97 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,7 @@ _TTS-Wrapper_ simplifies using text-to-speech APIs by providing a unified interf - eSpeak-NG - Play.HT - UpliftAI +- ModelsLab - OpenAI - AVSynth (macOS only) - SAPI (Windows only) @@ -63,6 +64,7 @@ _TTS-Wrapper_ simplifies using text-to-speech APIs by providing a unified interf | ElevenLabs | Linux/MacOS/Windows| Online | No* | Yes | Yes | Yes | Full | | Play.HT | Linux/MacOS/Windows| Online | No* | No** | Yes | Yes | Basic | | UpliftAI | Linux/MacOS/Windows| Online | No* | No** | Yes | Yes | Basic | +| ModelsLab | Linux/MacOS/Windows| Online | No* | No** | Yes | Yes | Basic | | OpenAI | Linux/MacOS/Windows| Online | No | No | Yes | Yes | Basic | | Wit.Ai | Linux/MacOS/Windows| Online | No* | No** | Yes | Yes | Basic | | eSpeak | Linux/MacOS | Offline | Yes | No** | Yes | Yes | Basic | @@ -271,6 +273,13 @@ from tts_wrapper import UpliftAIClient client = UpliftAIClient(api_key="api_key") ``` +#### ModelsLab + +```python +from tts_wrapper import ModelsLabClient +client = ModelsLabClient(api_key="your_modelslab_api_key") +``` + #### UWP ```python @@ -930,6 +939,9 @@ Example structure (do NOT commit actual credentials): "Microsoft": { "token": "your-subscription-key", "region": "your-region" + }, + "ModelsLab": { + "api_key": "your-modelslab-api-key" } } ``` @@ -971,6 +983,11 @@ Example structure (do NOT commit actual credentials): - [Create a new app and get token](https://wit.ai/docs/quickstart) - [Wit.ai Documentation](https://wit.ai/docs) +#### ModelsLab +- [Create a ModelsLab account](https://modelslab.com/) +- [Get your API key](https://docs.modelslab.com/) +- [ModelsLab TTS Documentation](https://docs.modelslab.com/voice-cloning/text-to-speech) + ## License This project is licensed under the [MIT License](./LICENSE). diff --git a/pyproject.toml b/pyproject.toml index a3a793bc..2149b541 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,7 +8,7 @@ authors = [ ] license = "MIT" readme = "README.md" -keywords = ["tts", "text-to-speech", "speech synthesis", "polly", "sapi", "mms", "gTTS", "witai", "elevenlabs", "playht", "upliftai", "sherpaonnx"] +keywords = ["tts", "text-to-speech", "speech synthesis", "polly", "sapi", "mms", "gTTS", "witai", "elevenlabs", "playht", "upliftai", "sherpaonnx", "modelslab"] requires-python = ">=3.10,<3.14" dependencies = [ @@ -47,6 +47,7 @@ sherpaonnx = [ "sherpa-onnx>=1.10.17,<1.11.7", ] # Pin to 1.11.x for better Windows wheel support across Python versions playht = [] # No additional dependencies needed as we use requests which is in core dependencies +modelslab = [] # No additional dependencies needed as we use requests which is in core dependencies googletrans = ["gTTS>=2.5.2"] mp3 = [ "pymp3>=0.2.0; python_version < '3.13'", diff --git a/tests/test_tts_engines.py b/tests/test_tts_engines.py index e6fc2670..539c4ab4 100644 --- a/tests/test_tts_engines.py +++ b/tests/test_tts_engines.py @@ -11,6 +11,7 @@ GoogleClient, GoogleTransClient, MicrosoftClient, + ModelsLabClient, OpenAIClient, PlayHTClient, PollyClient, @@ -39,6 +40,7 @@ "playht": PlayHTClient, "openai": OpenAIClient, "upliftai": UpliftAIClient, + "modelslab": ModelsLabClient, } # Add AVSynth only on macOS @@ -146,6 +148,8 @@ def check_credentials(service): client = AVSynthClient() elif service == "openai": client = OpenAIClient(api_key=os.getenv("OPENAI_API_KEY")) + elif service == "modelslab": + client = ModelsLabClient(api_key=os.getenv("MODELSLAB_API_KEY")) else: # Unknown service or not available on this platform VALID_CREDENTIALS[service] = False @@ -209,6 +213,8 @@ def create_tts_client(service): return AVSynthClient() if service == "openai": return OpenAIClient(api_key=os.getenv("OPENAI_API_KEY")) + if service == "modelslab": + return ModelsLabClient(api_key=os.getenv("MODELSLAB_API_KEY")) msg = f"Unknown service or not available on this platform: {service}" raise ValueError(msg) diff --git a/tts_wrapper/engines/__init__.py b/tts_wrapper/engines/__init__.py index 921b984a..42bbd3df 100644 --- a/tts_wrapper/engines/__init__.py +++ b/tts_wrapper/engines/__init__.py @@ -4,6 +4,7 @@ from .elevenlabs import * from .espeak import * from .google import * +from .modelslab import * from .googletrans import * from .microsoft import * from .openai import * diff --git a/tts_wrapper/engines/modelslab/__init__.py b/tts_wrapper/engines/modelslab/__init__.py new file mode 100644 index 00000000..c9a315ce --- /dev/null +++ b/tts_wrapper/engines/modelslab/__init__.py @@ -0,0 +1,5 @@ +"""ModelsLab TTS engine for tts-wrapper.""" + +from .client import ModelsLabClient + +__all__ = ["ModelsLabClient"] diff --git a/tts_wrapper/engines/modelslab/client.py b/tts_wrapper/engines/modelslab/client.py new file mode 100644 index 00000000..52321b38 --- /dev/null +++ b/tts_wrapper/engines/modelslab/client.py @@ -0,0 +1,298 @@ +"""ModelsLab TTS client implementation.""" + +from __future__ import annotations + +import logging +import os +import re +import time +from typing import TYPE_CHECKING, Any, Callable + +import requests + +from tts_wrapper.engines.modelslab.ssml import ModelsLabSSML +from tts_wrapper.ssml import AbstractSSMLNode +from tts_wrapper.tts import AbstractTTS + +if TYPE_CHECKING: + from collections.abc import Generator + from pathlib import Path + + +class ModelsLabClient(AbstractTTS): + """ + ModelsLab TTS client implementation. + + Uses the ModelsLab Voice API to generate speech from text. + Supports multiple voices and languages, with optional emotion tags. + + API docs: https://docs.modelslab.com/voice-cloning/text-to-speech + """ + + API_URL = "https://modelslab.com/api/v6/voice/text_to_speech" + + # Voices that support emotion tags (English only) + EMOTION_VOICES = { + "tara", "leah", "jess", "mia", "zoe", # female + "leo", "dan", "zac", # male + } + + # All available voices with metadata + _VOICES = [ + {"id": "madison", "name": "Madison", "gender": "Female", "language_codes": ["en"]}, + {"id": "tara", "name": "Tara", "gender": "Female", "language_codes": ["en"]}, + {"id": "leah", "name": "Leah", "gender": "Female", "language_codes": ["en"]}, + {"id": "jess", "name": "Jess", "gender": "Female", "language_codes": ["en"]}, + {"id": "mia", "name": "Mia", "gender": "Female", "language_codes": ["en"]}, + {"id": "zoe", "name": "Zoe", "gender": "Female", "language_codes": ["en"]}, + {"id": "leo", "name": "Leo", "gender": "Male", "language_codes": ["en"]}, + {"id": "dan", "name": "Dan", "gender": "Male", "language_codes": ["en"]}, + {"id": "zac", "name": "Zac", "gender": "Male", "language_codes": ["en"]}, + ] + + def __init__( + self, + api_key: str | None = None, + voice: str = "madison", + language: str = "american english", + speed: float = 1.0, + ) -> None: + """ + Initialize the ModelsLab TTS client. + + Args: + api_key: ModelsLab API key. If None, uses MODELSLAB_API_KEY env var. + voice: Voice ID to use. Default is "madison". + language: Language descriptor. Default is "american english". + speed: Speech speed multiplier (default 1.0). + """ + super().__init__() + + self.api_key = api_key or os.environ.get("MODELSLAB_API_KEY") + if not self.api_key: + msg = ( + "ModelsLab API key is required. Provide it as an argument " + "or set the MODELSLAB_API_KEY environment variable." + ) + raise ValueError(msg) + + self.ssml = ModelsLabSSML() # type: ignore[assignment] + self.language = language + self.speed = speed + + self.voice_id = None # type: ignore[assignment] + self.set_voice(voice) + + logging.debug("Initialized ModelsLab TTS client with voice %s", voice) + + def connect(self, event_name: str, callback: Callable) -> None: + """Connect a callback function to an event.""" + super().connect(event_name, callback) + + def _get_voices(self) -> list[dict[str, Any]]: + """Return available ModelsLab voices.""" + return self._VOICES + + def check_credentials(self) -> bool: + """ + Check if the provided API key is valid. + + Returns: + True if credentials are valid, False otherwise. + """ + try: + resp = requests.post( + self.API_URL, + json={"key": self.api_key, "prompt": "test", "voice_id": "madison"}, + timeout=10, + ) + # A 401/403 means bad key; 200/422 means key was accepted + return resp.status_code not in (401, 403) + except Exception as exc: + logging.error("Failed to validate ModelsLab credentials: %s", exc) + return False + + def set_voice(self, voice_id: str, lang: str | None = None) -> None: + """ + Set the voice for synthesis. + + Args: + voice_id: Voice identifier (e.g. "madison", "leo"). + lang: Language code (updates self.language when provided). + """ + available = [v["id"] for v in self._VOICES] + if voice_id not in available: + msg = f"Invalid voice '{voice_id}'. Available voices: {', '.join(available)}" + raise ValueError(msg) + self.voice_id = voice_id # type: ignore[assignment] + if lang: + self.language = lang + logging.debug("Set ModelsLab voice to %s", voice_id) + + def _is_ssml(self, text: str) -> bool: + """Return True if the text looks like SSML.""" + stripped = text.strip() + return stripped.startswith("") and stripped.endswith("") + + def synth_to_bytes(self, text: Any, voice_id: str | None = None) -> bytes: + """ + Synthesize text to raw audio bytes. + + The ModelsLab API may respond with either inline audio bytes or + a URL pointing to the generated audio file. Both cases are handled. + + Args: + text: Text (or SSML) to synthesise. + voice_id: Override voice for this call only. + + Returns: + Raw WAV/MP3 audio bytes. + """ + voice = voice_id or self.voice_id + + try: + text_str = str(text) + except Exception as exc: + logging.error("Could not convert text to str: %s", exc) + text_str = "" + + # Strip SSML tags if present (ModelsLab uses plain text) + if self._is_ssml(text_str): + text_str = re.sub(r"<[^>]+>", "", text_str).strip() + + # Resolve speed from property overrides; base class defaults rate to "" + rate = self.get_property("rate") + speed = float(rate) if rate else self.speed + + payload: dict[str, Any] = { + "key": self.api_key, + "prompt": text_str, + "language": self.language, + "voice_id": voice, + "speed": speed, + "emotion": False, + } + + try: + resp = requests.post(self.API_URL, json=payload, timeout=60) + resp.raise_for_status() + data = resp.json() + except Exception as exc: + logging.error("ModelsLab synthesis request failed: %s", exc) + return b"" + + status = data.get("status") + + if status == "error": + logging.error("ModelsLab API error: %s", data.get("message", data)) + return b"" + + # Handle async generation — poll until complete + if status == "processing": + audio_url = self._poll_for_url(data) + elif status == "success": + outputs = data.get("output", []) + audio_url = outputs[0] if outputs else None + else: + logging.error("Unexpected ModelsLab status: %s", status) + return b"" + + if not audio_url: + logging.error("ModelsLab returned no audio URL") + return b"" + + return self._download_audio(audio_url) + + def _poll_for_url( + self, + initial_response: dict[str, Any], + max_retries: int = 20, + poll_interval: float = 2.0, + ) -> str | None: + """ + Poll the ModelsLab API until the audio is ready. + + Args: + initial_response: The initial response dict that had status=processing. + max_retries: Maximum number of polling attempts. + poll_interval: Seconds to wait between polls. + + Returns: + Audio URL string or None on failure. + """ + fetch_url = initial_response.get("fetch_result") or initial_response.get("link") + if not fetch_url: + logging.error("No fetch URL in processing response: %s", initial_response) + return None + + for attempt in range(max_retries): + time.sleep(poll_interval) + try: + resp = requests.post( + fetch_url, + json={"key": self.api_key}, + timeout=30, + ) + resp.raise_for_status() + data = resp.json() + if data.get("status") == "success": + outputs = data.get("output", []) + return outputs[0] if outputs else None + if data.get("status") == "error": + logging.error("ModelsLab poll error: %s", data.get("message")) + return None + logging.debug("ModelsLab still processing (attempt %d/%d)", attempt + 1, max_retries) + except Exception as exc: + logging.warning("ModelsLab poll attempt %d failed: %s", attempt + 1, exc) + + logging.error("ModelsLab audio generation timed out after %d attempts", max_retries) + return None + + def _download_audio(self, url: str) -> bytes: + """Download audio from URL and return bytes.""" + try: + resp = requests.get(url, timeout=60) + resp.raise_for_status() + return resp.content + except Exception as exc: + logging.error("Failed to download ModelsLab audio from %s: %s", url, exc) + return b"" + + def synth_to_bytestream( + self, text: Any, voice_id: str | None = None + ) -> Generator[bytes, None, None]: + """ + Synthesise text and yield audio in chunks. + + ModelsLab does not offer a native streaming API, so audio is fetched + in full then yielded in 4 KB chunks. + + Args: + text: Text to synthesise. + voice_id: Optional voice override. + + Yields: + Byte chunks of audio data. + """ + audio = self.synth_to_bytes(text, voice_id=voice_id) + if not audio: + yield b"" + return + chunk_size = 4096 + for i in range(0, len(audio), chunk_size): + yield audio[i : i + chunk_size] + + def synth( + self, + text: str | AbstractSSMLNode, + output_file: str | Path, + output_format: str = "wav", + voice_id: str | None = None, + format: str | None = None, + ) -> None: + """Synthesise text and save to a file.""" + super().synth(text, output_file, output_format, voice_id, format) + + def set_property(self, property_name: str, value: float | str) -> None: + """Set a synthesis property (rate/volume/pitch).""" + super().set_property(property_name, value) diff --git a/tts_wrapper/engines/modelslab/ssml.py b/tts_wrapper/engines/modelslab/ssml.py new file mode 100644 index 00000000..52265aa7 --- /dev/null +++ b/tts_wrapper/engines/modelslab/ssml.py @@ -0,0 +1,53 @@ +"""SSML handling for ModelsLab TTS engine.""" + +from __future__ import annotations + +from typing import Any + +from tts_wrapper.ssml import AbstractSSMLNode, BaseSSMLRoot + + +class ModelsLabSSML(BaseSSMLRoot): + """ + SSML implementation for ModelsLab TTS. + + ModelsLab doesn't support SSML, so this class strips SSML tags + and returns plain text. + """ + + def __init__(self) -> None: + """Initialize the ModelsLab SSML handler.""" + super().__init__() + + def add(self, node: AbstractSSMLNode | str) -> AbstractSSMLNode: + """Add a node to the SSML tree.""" + return super().add(node) + + def add_text(self, text: str) -> AbstractSSMLNode: + """Add a text node to the SSML tree.""" + return self.add(text) + + def to_string(self) -> str: + """Convert SSML to plain text by stripping all tags.""" + return str(self) + + def clear_ssml(self) -> None: + """Clear all SSML nodes.""" + self.children: list[AbstractSSMLNode] = [] + + def construct_prosody( + self, + text: str, + rate: Any = None, + volume: Any = None, + pitch: Any = None, + range: Any = None, + ) -> str: + """ + Construct a prosody element. + + ModelsLab uses the speed parameter instead of SSML prosody. + Returns plain text; rate is handled via the speed parameter in the client. + """ + _ = rate, volume, pitch, range + return text diff --git a/uv.lock b/uv.lock index 487d017d..d9de6743 100644 --- a/uv.lock +++ b/uv.lock @@ -1247,7 +1247,7 @@ requires-dist = [ { name = "websocket-client", marker = "extra == 'watson'" }, { name = "winrt-runtime", marker = "sys_platform == 'win32' and extra == 'uwp'", specifier = ">=2.0.1" }, ] -provides-extras = ["avsynth", "controlaudio", "elevenlabs", "espeak", "google", "googletrans", "microsoft", "mp3", "openai", "playht", "polly", "sapi", "sherpaonnx", "uwp", "watson", "witai"] +provides-extras = ["avsynth", "controlaudio", "elevenlabs", "espeak", "google", "googletrans", "microsoft", "modelslab", "mp3", "openai", "playht", "polly", "sapi", "sherpaonnx", "uwp", "watson", "witai"] [package.metadata.requires-dev] dev = [