|
| 1 | +import uuid |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | +import httpx |
| 5 | + |
| 6 | +from astrbot import logger |
| 7 | +from astrbot.core.utils.astrbot_path import get_astrbot_temp_path |
| 8 | + |
| 9 | +from ..entities import ProviderType |
| 10 | +from ..provider import TTSProvider |
| 11 | +from ..register import register_provider_adapter |
| 12 | + |
| 13 | +SUPPORTED_CONTAINER_OUTPUT_PREFIXES = ("mp3", "wav", "opus") |
| 14 | +RAW_AUDIO_OUTPUT_PREFIXES = ("pcm", "ulaw", "alaw") |
| 15 | + |
| 16 | + |
| 17 | +def _parse_optional_float( |
| 18 | + provider_config: dict, |
| 19 | + cfg_name: str, |
| 20 | +) -> float | None: |
| 21 | + value = provider_config.get(cfg_name, "") |
| 22 | + if value in ("", None): |
| 23 | + return None |
| 24 | + try: |
| 25 | + parsed = float(value) |
| 26 | + except (TypeError, ValueError) as exc: |
| 27 | + raise ValueError(f"{cfg_name} must be a number between 0 and 1.") from exc |
| 28 | + if not 0 <= parsed <= 1: |
| 29 | + raise ValueError(f"{cfg_name} must be between 0 and 1.") |
| 30 | + return parsed |
| 31 | + |
| 32 | + |
| 33 | +def _parse_bool(provider_config: dict, cfg_name: str) -> bool: |
| 34 | + value = provider_config[cfg_name] |
| 35 | + if isinstance(value, bool): |
| 36 | + return value |
| 37 | + if isinstance(value, int): |
| 38 | + return bool(value) |
| 39 | + if isinstance(value, str): |
| 40 | + normalized = value.strip().lower() |
| 41 | + if normalized in {"true", "1", "yes", "y", "on"}: |
| 42 | + return True |
| 43 | + if normalized in {"false", "0", "no", "n", "off"}: |
| 44 | + return False |
| 45 | + raise ValueError(f"{cfg_name} must be a boolean value.") |
| 46 | + |
| 47 | + |
| 48 | +def _normalize_timeout(value: int | str | None) -> int: |
| 49 | + if value in ("", None): |
| 50 | + return 20 |
| 51 | + try: |
| 52 | + timeout = int(value) |
| 53 | + except (TypeError, ValueError) as exc: |
| 54 | + raise ValueError("timeout must be a positive integer.") from exc |
| 55 | + if timeout <= 0: |
| 56 | + raise ValueError("timeout must be a positive integer.") |
| 57 | + return timeout |
| 58 | + |
| 59 | + |
| 60 | +def _validate_output_format(output_format: str) -> None: |
| 61 | + fmt = output_format.lower() |
| 62 | + if fmt.startswith(RAW_AUDIO_OUTPUT_PREFIXES): |
| 63 | + raise ValueError( |
| 64 | + "ElevenLabs raw audio output formats are not supported by this provider. " |
| 65 | + "Use an mp3, wav, or opus output format instead." |
| 66 | + ) |
| 67 | + if not fmt.startswith(SUPPORTED_CONTAINER_OUTPUT_PREFIXES): |
| 68 | + raise ValueError( |
| 69 | + "Unsupported ElevenLabs output format. " |
| 70 | + "Use an mp3, wav, or opus output format." |
| 71 | + ) |
| 72 | + |
| 73 | + |
| 74 | +@register_provider_adapter( |
| 75 | + "elevenlabs_tts_api", |
| 76 | + "ElevenLabs TTS API", |
| 77 | + provider_type=ProviderType.TEXT_TO_SPEECH, |
| 78 | +) |
| 79 | +class ProviderElevenLabsTTSAPI(TTSProvider): |
| 80 | + def __init__( |
| 81 | + self, |
| 82 | + provider_config: dict, |
| 83 | + provider_settings: dict, |
| 84 | + ) -> None: |
| 85 | + super().__init__(provider_config, provider_settings) |
| 86 | + self.api_key = provider_config.get("api_key", "") |
| 87 | + self.api_base = provider_config.get( |
| 88 | + "api_base", "https://api.elevenlabs.io/v1" |
| 89 | + ).removesuffix("/") |
| 90 | + self.voice_id = provider_config.get( |
| 91 | + "elevenlabs-tts-voice-id", "JBFqnCBsd6RMkjVDRZzb" |
| 92 | + ) |
| 93 | + self.model_id = provider_config.get("model", "eleven_multilingual_v2") |
| 94 | + self.set_model(self.model_id) |
| 95 | + self.output_format = provider_config.get( |
| 96 | + "elevenlabs-tts-output-format", "mp3_44100_128" |
| 97 | + ) |
| 98 | + _validate_output_format(self.output_format) |
| 99 | + |
| 100 | + # Only send explicitly configured voice settings so the API can apply defaults. |
| 101 | + self.voice_settings: dict = {} |
| 102 | + for key, cfg_name in ( |
| 103 | + ("stability", "elevenlabs-tts-stability"), |
| 104 | + ("similarity_boost", "elevenlabs-tts-similarity-boost"), |
| 105 | + ("style", "elevenlabs-tts-style"), |
| 106 | + ): |
| 107 | + value = _parse_optional_float(provider_config, cfg_name) |
| 108 | + if value is not None: |
| 109 | + self.voice_settings[key] = value |
| 110 | + if "elevenlabs-tts-use-speaker-boost" in provider_config: |
| 111 | + self.voice_settings["use_speaker_boost"] = _parse_bool( |
| 112 | + provider_config, |
| 113 | + "elevenlabs-tts-use-speaker-boost", |
| 114 | + ) |
| 115 | + |
| 116 | + timeout = _normalize_timeout(provider_config.get("timeout", 20)) |
| 117 | + |
| 118 | + proxy = provider_config.get("proxy", "") |
| 119 | + if proxy: |
| 120 | + logger.info(f"[ElevenLabs TTS] 使用代理: {proxy}") |
| 121 | + self.client = httpx.AsyncClient( |
| 122 | + timeout=timeout, |
| 123 | + proxy=proxy or None, |
| 124 | + trust_env=False, |
| 125 | + ) |
| 126 | + |
| 127 | + def _output_extension(self) -> str: |
| 128 | + """Infer the audio file extension from the configured output format.""" |
| 129 | + fmt = self.output_format.lower() |
| 130 | + if fmt.startswith("mp3"): |
| 131 | + return "mp3" |
| 132 | + if fmt.startswith("opus"): |
| 133 | + return "opus" |
| 134 | + if fmt.startswith("wav"): |
| 135 | + return "wav" |
| 136 | + return "mp3" |
| 137 | + |
| 138 | + async def get_audio(self, text: str) -> str: |
| 139 | + url = f"{self.api_base}/text-to-speech/{self.voice_id}" |
| 140 | + headers = { |
| 141 | + "xi-api-key": self.api_key, |
| 142 | + "Content-Type": "application/json", |
| 143 | + } |
| 144 | + payload: dict = { |
| 145 | + "text": text, |
| 146 | + "model_id": self.model_name, |
| 147 | + } |
| 148 | + if self.voice_settings: |
| 149 | + payload["voice_settings"] = self.voice_settings |
| 150 | + |
| 151 | + response = await self.client.post( |
| 152 | + url, |
| 153 | + headers=headers, |
| 154 | + params={"output_format": self.output_format}, |
| 155 | + json=payload, |
| 156 | + ) |
| 157 | + if response.status_code != 200: |
| 158 | + error_text = response.text[:1024] |
| 159 | + raise Exception( |
| 160 | + f"ElevenLabs TTS API 请求失败: {response.status_code}, {error_text}" |
| 161 | + ) |
| 162 | + |
| 163 | + temp_dir = Path(get_astrbot_temp_path()) |
| 164 | + temp_dir.mkdir(parents=True, exist_ok=True) |
| 165 | + path = ( |
| 166 | + temp_dir / f"elevenlabs_tts_api_{uuid.uuid4()}.{self._output_extension()}" |
| 167 | + ) |
| 168 | + path.write_bytes(response.content) |
| 169 | + return str(path) |
| 170 | + |
| 171 | + async def terminate(self): |
| 172 | + if self.client: |
| 173 | + await self.client.aclose() |
0 commit comments