mimosynth 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mimosynth/__init__.py +103 -0
- mimosynth/_version.py +24 -0
- mimosynth/api_contract.py +42 -0
- mimosynth/client.py +257 -0
- mimosynth/connection_config.py +157 -0
- mimosynth/constants.py +30 -0
- mimosynth/discovery.py +96 -0
- mimosynth/exceptions.py +72 -0
- mimosynth/py.typed +0 -0
- mimosynth/reference_audio.py +90 -0
- mimosynth/synthesis_config.py +71 -0
- mimosynth/synthesis_identity.py +69 -0
- mimosynth/synthesis_types.py +66 -0
- mimosynth/synthesizer.py +240 -0
- mimosynth-0.1.0.dist-info/METADATA +333 -0
- mimosynth-0.1.0.dist-info/RECORD +19 -0
- mimosynth-0.1.0.dist-info/WHEEL +5 -0
- mimosynth-0.1.0.dist-info/licenses/LICENSE +201 -0
- mimosynth-0.1.0.dist-info/top_level.txt +1 -0
mimosynth/__init__.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Public API for the request-centric Xiaomi MiMo TTS client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .api_contract import REQUEST_API_VERSION, RequestApiContract, request_api_contract
|
|
6
|
+
from .client import MimoClient
|
|
7
|
+
from .connection_config import ConnectionSettings, default_config_path, resolve_connection_settings
|
|
8
|
+
from .constants import (
|
|
9
|
+
API_KEY_ENV,
|
|
10
|
+
BASE_URL_ENV,
|
|
11
|
+
CONFIG_PATH_ENV,
|
|
12
|
+
DEFAULT_BASE_URL,
|
|
13
|
+
PRESET_MODEL,
|
|
14
|
+
PRESET_VOICES,
|
|
15
|
+
PROFILE_ENV,
|
|
16
|
+
SAMPLE_RATE,
|
|
17
|
+
TTS_MODELS,
|
|
18
|
+
VOICE_CLONE_MODEL,
|
|
19
|
+
VOICE_DESIGN_MODEL,
|
|
20
|
+
)
|
|
21
|
+
from .discovery import (
|
|
22
|
+
ModelCapabilities,
|
|
23
|
+
ModelDiscoveryResult,
|
|
24
|
+
VoiceCapabilities,
|
|
25
|
+
discover_models,
|
|
26
|
+
known_models,
|
|
27
|
+
)
|
|
28
|
+
from .exceptions import (
|
|
29
|
+
AuthenticationError,
|
|
30
|
+
BackendError,
|
|
31
|
+
BillingError,
|
|
32
|
+
ConfigurationError,
|
|
33
|
+
EmptyTextError,
|
|
34
|
+
InvalidModelError,
|
|
35
|
+
InvalidRequestError,
|
|
36
|
+
InvalidVoiceError,
|
|
37
|
+
MimoSynthError,
|
|
38
|
+
RateLimitError,
|
|
39
|
+
ServiceUnavailableError,
|
|
40
|
+
SynthesisInputTooLongError,
|
|
41
|
+
UnsupportedFeatureError,
|
|
42
|
+
)
|
|
43
|
+
from .reference_audio import ReferenceAudio
|
|
44
|
+
from .synthesis_config import SynthesisConfig
|
|
45
|
+
from .synthesis_identity import SynthesisIdentity, build_synthesis_identity
|
|
46
|
+
from .synthesis_types import RenderedSegment, RequestMeasure, SynthesisRequest, VoiceConditioning
|
|
47
|
+
from .synthesizer import MimoSynthesizer
|
|
48
|
+
|
|
49
|
+
try:
|
|
50
|
+
from ._version import __version__, __version_tuple__
|
|
51
|
+
except ImportError:
|
|
52
|
+
__version__ = "0.1.0"
|
|
53
|
+
__version_tuple__ = (0, 1, 0)
|
|
54
|
+
|
|
55
|
+
__all__ = [
|
|
56
|
+
"API_KEY_ENV",
|
|
57
|
+
"BASE_URL_ENV",
|
|
58
|
+
"CONFIG_PATH_ENV",
|
|
59
|
+
"PROFILE_ENV",
|
|
60
|
+
"ConnectionSettings",
|
|
61
|
+
"default_config_path",
|
|
62
|
+
"resolve_connection_settings",
|
|
63
|
+
"DEFAULT_BASE_URL",
|
|
64
|
+
"PRESET_MODEL",
|
|
65
|
+
"PRESET_VOICES",
|
|
66
|
+
"SAMPLE_RATE",
|
|
67
|
+
"TTS_MODELS",
|
|
68
|
+
"VOICE_CLONE_MODEL",
|
|
69
|
+
"VOICE_DESIGN_MODEL",
|
|
70
|
+
"REQUEST_API_VERSION",
|
|
71
|
+
"RequestApiContract",
|
|
72
|
+
"request_api_contract",
|
|
73
|
+
"MimoClient",
|
|
74
|
+
"ModelCapabilities",
|
|
75
|
+
"ModelDiscoveryResult",
|
|
76
|
+
"VoiceCapabilities",
|
|
77
|
+
"discover_models",
|
|
78
|
+
"known_models",
|
|
79
|
+
"MimoSynthError",
|
|
80
|
+
"ConfigurationError",
|
|
81
|
+
"InvalidRequestError",
|
|
82
|
+
"EmptyTextError",
|
|
83
|
+
"InvalidModelError",
|
|
84
|
+
"InvalidVoiceError",
|
|
85
|
+
"UnsupportedFeatureError",
|
|
86
|
+
"AuthenticationError",
|
|
87
|
+
"BillingError",
|
|
88
|
+
"RateLimitError",
|
|
89
|
+
"ServiceUnavailableError",
|
|
90
|
+
"BackendError",
|
|
91
|
+
"SynthesisInputTooLongError",
|
|
92
|
+
"ReferenceAudio",
|
|
93
|
+
"SynthesisConfig",
|
|
94
|
+
"SynthesisIdentity",
|
|
95
|
+
"build_synthesis_identity",
|
|
96
|
+
"SynthesisRequest",
|
|
97
|
+
"RequestMeasure",
|
|
98
|
+
"RenderedSegment",
|
|
99
|
+
"VoiceConditioning",
|
|
100
|
+
"MimoSynthesizer",
|
|
101
|
+
"__version__",
|
|
102
|
+
"__version_tuple__",
|
|
103
|
+
]
|
mimosynth/_version.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# file generated by vcs-versioning
|
|
2
|
+
# don't change, don't track in version control
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"__version__",
|
|
7
|
+
"__version_tuple__",
|
|
8
|
+
"version",
|
|
9
|
+
"version_tuple",
|
|
10
|
+
"__commit_id__",
|
|
11
|
+
"commit_id",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
version: str
|
|
15
|
+
__version__: str
|
|
16
|
+
__version_tuple__: tuple[int | str, ...]
|
|
17
|
+
version_tuple: tuple[int | str, ...]
|
|
18
|
+
commit_id: str | None
|
|
19
|
+
__commit_id__: str | None
|
|
20
|
+
|
|
21
|
+
__version__ = version = '0.1.0'
|
|
22
|
+
__version_tuple__ = version_tuple = (0, 1, 0)
|
|
23
|
+
|
|
24
|
+
__commit_id__ = commit_id = 'g4a1bc8f1b'
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Stable capability declaration for VoiceRender-style integrations."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
REQUEST_API_VERSION = 1
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True, slots=True)
|
|
11
|
+
class RequestApiContract:
|
|
12
|
+
version: int
|
|
13
|
+
request_type: str
|
|
14
|
+
result_type: str
|
|
15
|
+
synthesizer_type: str
|
|
16
|
+
synthesize_method: str
|
|
17
|
+
measurement_method: str
|
|
18
|
+
discovery_method: str
|
|
19
|
+
caller_owns_text_boundaries: bool
|
|
20
|
+
supports_named_voices: bool
|
|
21
|
+
supports_reference_voice: bool
|
|
22
|
+
supports_voice_design: bool
|
|
23
|
+
supports_request_measurement: bool
|
|
24
|
+
supports_streaming: bool
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def request_api_contract() -> RequestApiContract:
|
|
28
|
+
return RequestApiContract(
|
|
29
|
+
version=REQUEST_API_VERSION,
|
|
30
|
+
request_type="SynthesisRequest",
|
|
31
|
+
result_type="RenderedSegment",
|
|
32
|
+
synthesizer_type="MimoSynthesizer",
|
|
33
|
+
synthesize_method="synthesize",
|
|
34
|
+
measurement_method="measure_request",
|
|
35
|
+
discovery_method="discover_models",
|
|
36
|
+
caller_owns_text_boundaries=True,
|
|
37
|
+
supports_named_voices=True,
|
|
38
|
+
supports_reference_voice=True,
|
|
39
|
+
supports_voice_design=True,
|
|
40
|
+
supports_request_measurement=False,
|
|
41
|
+
supports_streaming=False,
|
|
42
|
+
)
|
mimosynth/client.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
"""Small HTTP transport for the Xiaomi MiMo API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import time
|
|
7
|
+
from collections.abc import Callable, Mapping
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
from .connection_config import resolve_connection_settings
|
|
14
|
+
from .exceptions import (
|
|
15
|
+
AuthenticationError,
|
|
16
|
+
BackendError,
|
|
17
|
+
BillingError,
|
|
18
|
+
RateLimitError,
|
|
19
|
+
ServiceUnavailableError,
|
|
20
|
+
SynthesisInputTooLongError,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
_RETRYABLE_STATUS = {408, 429, 500, 502, 503, 504}
|
|
24
|
+
_TOO_LONG_MARKERS = (
|
|
25
|
+
"context length",
|
|
26
|
+
"maximum context",
|
|
27
|
+
"max context",
|
|
28
|
+
"too long",
|
|
29
|
+
"maximum token",
|
|
30
|
+
"max token",
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _safe_error_message(response: httpx.Response) -> str:
|
|
35
|
+
try:
|
|
36
|
+
payload = response.json()
|
|
37
|
+
except Exception:
|
|
38
|
+
return response.text[:500] or f"HTTP {response.status_code}"
|
|
39
|
+
if isinstance(payload, Mapping):
|
|
40
|
+
error = payload.get("error")
|
|
41
|
+
if isinstance(error, Mapping):
|
|
42
|
+
message = error.get("message")
|
|
43
|
+
if isinstance(message, str) and message:
|
|
44
|
+
return message[:1000]
|
|
45
|
+
message = payload.get("message")
|
|
46
|
+
if isinstance(message, str) and message:
|
|
47
|
+
return message[:1000]
|
|
48
|
+
return f"HTTP {response.status_code}"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _request_id(response: httpx.Response) -> str | None:
|
|
52
|
+
for key in ("x-request-id", "request-id", "x-mi-request-id"):
|
|
53
|
+
value = response.headers.get(key)
|
|
54
|
+
if value:
|
|
55
|
+
return value
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _retry_after_seconds(response: httpx.Response) -> float | None:
|
|
60
|
+
value = response.headers.get("retry-after")
|
|
61
|
+
if value is None:
|
|
62
|
+
return None
|
|
63
|
+
try:
|
|
64
|
+
seconds = float(value)
|
|
65
|
+
except ValueError:
|
|
66
|
+
return None
|
|
67
|
+
return max(0.0, seconds)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class MimoClient:
|
|
71
|
+
"""Authenticated JSON client with bounded retry/backoff and safe errors."""
|
|
72
|
+
|
|
73
|
+
def __init__(
|
|
74
|
+
self,
|
|
75
|
+
*,
|
|
76
|
+
api_key: str | None = None,
|
|
77
|
+
base_url: str | None = None,
|
|
78
|
+
profile: str | None = None,
|
|
79
|
+
config_path: str | Path | None = None,
|
|
80
|
+
legacy_base_url: str | None = None,
|
|
81
|
+
connect_timeout: float = 10.0,
|
|
82
|
+
read_timeout: float = 120.0,
|
|
83
|
+
max_retries: int = 3,
|
|
84
|
+
retry_backoff: float = 0.5,
|
|
85
|
+
http_client: httpx.Client | None = None,
|
|
86
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
87
|
+
) -> None:
|
|
88
|
+
for name, value in (
|
|
89
|
+
("connect_timeout", connect_timeout),
|
|
90
|
+
("read_timeout", read_timeout),
|
|
91
|
+
("retry_backoff", retry_backoff),
|
|
92
|
+
):
|
|
93
|
+
if (
|
|
94
|
+
isinstance(value, bool)
|
|
95
|
+
or not isinstance(value, (int, float))
|
|
96
|
+
or not math.isfinite(value)
|
|
97
|
+
or (value < 0 if name == "retry_backoff" else value <= 0)
|
|
98
|
+
):
|
|
99
|
+
raise ValueError(f"Invalid {name}")
|
|
100
|
+
if isinstance(max_retries, bool) or not isinstance(max_retries, int) or max_retries < 0:
|
|
101
|
+
raise ValueError("Invalid max_retries")
|
|
102
|
+
settings = resolve_connection_settings(
|
|
103
|
+
api_key=api_key,
|
|
104
|
+
base_url=base_url,
|
|
105
|
+
profile=profile,
|
|
106
|
+
config_path=config_path,
|
|
107
|
+
legacy_base_url=legacy_base_url,
|
|
108
|
+
)
|
|
109
|
+
self._api_key = settings.api_key
|
|
110
|
+
self.base_url = settings.base_url
|
|
111
|
+
self.profile = settings.profile
|
|
112
|
+
self.config_path = settings.config_path
|
|
113
|
+
self.max_retries = max_retries
|
|
114
|
+
self.retry_backoff = retry_backoff
|
|
115
|
+
self._sleep = sleep
|
|
116
|
+
self._owns_client = http_client is None
|
|
117
|
+
self._client = http_client or httpx.Client(
|
|
118
|
+
timeout=httpx.Timeout(read_timeout, connect=connect_timeout),
|
|
119
|
+
headers={
|
|
120
|
+
"api-key": self._api_key,
|
|
121
|
+
"accept": "application/json",
|
|
122
|
+
"content-type": "application/json",
|
|
123
|
+
},
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
def close(self) -> None:
|
|
127
|
+
if self._owns_client:
|
|
128
|
+
self._client.close()
|
|
129
|
+
|
|
130
|
+
def __enter__(self) -> MimoClient:
|
|
131
|
+
return self
|
|
132
|
+
|
|
133
|
+
def __exit__(self, exc_type: object, exc: object, tb: object) -> None:
|
|
134
|
+
self.close()
|
|
135
|
+
|
|
136
|
+
def list_models(self) -> tuple[str, ...]:
|
|
137
|
+
payload = self._request_json("GET", "/models")
|
|
138
|
+
data = payload.get("data")
|
|
139
|
+
if not isinstance(data, list):
|
|
140
|
+
raise BackendError("MiMo /models response is missing data[]", stage="decode")
|
|
141
|
+
ids: list[str] = []
|
|
142
|
+
for item in data:
|
|
143
|
+
if isinstance(item, Mapping) and isinstance(item.get("id"), str):
|
|
144
|
+
ids.append(item["id"])
|
|
145
|
+
return tuple(ids)
|
|
146
|
+
|
|
147
|
+
def create_speech(self, payload: Mapping[str, Any]) -> dict[str, Any]:
|
|
148
|
+
return self._request_json("POST", "/chat/completions", json=dict(payload))
|
|
149
|
+
|
|
150
|
+
def _request_json(
|
|
151
|
+
self,
|
|
152
|
+
method: str,
|
|
153
|
+
path: str,
|
|
154
|
+
*,
|
|
155
|
+
json: Mapping[str, Any] | None = None,
|
|
156
|
+
) -> dict[str, Any]:
|
|
157
|
+
url = f"{self.base_url}{path}"
|
|
158
|
+
last_transport_error: Exception | None = None
|
|
159
|
+
for attempt in range(self.max_retries + 1):
|
|
160
|
+
try:
|
|
161
|
+
# Explicit per-request auth also makes injected MockTransport clients behave
|
|
162
|
+
# exactly like the internally-created client.
|
|
163
|
+
response = self._client.request(
|
|
164
|
+
method,
|
|
165
|
+
url,
|
|
166
|
+
json=json,
|
|
167
|
+
headers={"api-key": self._api_key},
|
|
168
|
+
)
|
|
169
|
+
except (httpx.TimeoutException, httpx.NetworkError) as exc:
|
|
170
|
+
last_transport_error = exc
|
|
171
|
+
if attempt >= self.max_retries:
|
|
172
|
+
raise ServiceUnavailableError(
|
|
173
|
+
"MiMo request failed after retries",
|
|
174
|
+
stage="transport",
|
|
175
|
+
details={"error_type": type(exc).__name__},
|
|
176
|
+
) from exc
|
|
177
|
+
self._sleep(self.retry_backoff * (2**attempt))
|
|
178
|
+
continue
|
|
179
|
+
|
|
180
|
+
if 200 <= response.status_code < 300:
|
|
181
|
+
try:
|
|
182
|
+
payload = response.json()
|
|
183
|
+
except ValueError as exc:
|
|
184
|
+
raise BackendError(
|
|
185
|
+
"MiMo returned invalid JSON",
|
|
186
|
+
stage="decode",
|
|
187
|
+
status_code=response.status_code,
|
|
188
|
+
request_id=_request_id(response),
|
|
189
|
+
) from exc
|
|
190
|
+
if not isinstance(payload, dict):
|
|
191
|
+
raise BackendError(
|
|
192
|
+
"MiMo JSON response must be an object",
|
|
193
|
+
stage="decode",
|
|
194
|
+
status_code=response.status_code,
|
|
195
|
+
request_id=_request_id(response),
|
|
196
|
+
)
|
|
197
|
+
return payload
|
|
198
|
+
|
|
199
|
+
message = _safe_error_message(response).replace(self._api_key, "[redacted]")
|
|
200
|
+
request_id = (_request_id(response) or "").replace(self._api_key, "[redacted]") or None
|
|
201
|
+
lowered = message.lower()
|
|
202
|
+
if response.status_code in {401, 403}:
|
|
203
|
+
raise AuthenticationError(
|
|
204
|
+
"MiMo rejected the API credentials",
|
|
205
|
+
stage="transport",
|
|
206
|
+
status_code=response.status_code,
|
|
207
|
+
request_id=request_id,
|
|
208
|
+
)
|
|
209
|
+
if response.status_code == 402:
|
|
210
|
+
raise BillingError(
|
|
211
|
+
message, stage="provider", status_code=402, request_id=request_id
|
|
212
|
+
)
|
|
213
|
+
if response.status_code == 400 and any(
|
|
214
|
+
marker in lowered for marker in _TOO_LONG_MARKERS
|
|
215
|
+
):
|
|
216
|
+
raise SynthesisInputTooLongError(
|
|
217
|
+
message,
|
|
218
|
+
stage="provider",
|
|
219
|
+
status_code=400,
|
|
220
|
+
request_id=request_id,
|
|
221
|
+
)
|
|
222
|
+
if response.status_code in _RETRYABLE_STATUS and attempt < self.max_retries:
|
|
223
|
+
delay = _retry_after_seconds(response)
|
|
224
|
+
if delay is None:
|
|
225
|
+
delay = self.retry_backoff * (2**attempt)
|
|
226
|
+
self._sleep(delay)
|
|
227
|
+
continue
|
|
228
|
+
if response.status_code == 429:
|
|
229
|
+
raise RateLimitError(
|
|
230
|
+
message,
|
|
231
|
+
stage="provider",
|
|
232
|
+
status_code=429,
|
|
233
|
+
request_id=request_id,
|
|
234
|
+
)
|
|
235
|
+
if response.status_code >= 500:
|
|
236
|
+
raise ServiceUnavailableError(
|
|
237
|
+
message,
|
|
238
|
+
stage="provider",
|
|
239
|
+
status_code=response.status_code,
|
|
240
|
+
request_id=request_id,
|
|
241
|
+
)
|
|
242
|
+
raise BackendError(
|
|
243
|
+
message,
|
|
244
|
+
stage="provider",
|
|
245
|
+
status_code=response.status_code,
|
|
246
|
+
request_id=request_id,
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
raise ServiceUnavailableError(
|
|
250
|
+
"MiMo request failed",
|
|
251
|
+
stage="transport",
|
|
252
|
+
details={
|
|
253
|
+
"error_type": type(last_transport_error).__name__
|
|
254
|
+
if last_transport_error is not None
|
|
255
|
+
else "unknown"
|
|
256
|
+
},
|
|
257
|
+
)
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""Persistent user connection profiles and local voice configuration."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import stat
|
|
7
|
+
import warnings
|
|
8
|
+
from collections.abc import Mapping
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from urllib.parse import urlparse
|
|
12
|
+
|
|
13
|
+
try:
|
|
14
|
+
import tomllib
|
|
15
|
+
except ModuleNotFoundError:
|
|
16
|
+
import tomli as tomllib
|
|
17
|
+
|
|
18
|
+
from .constants import API_KEY_ENV, BASE_URL_ENV, CONFIG_PATH_ENV, DEFAULT_BASE_URL, PROFILE_ENV
|
|
19
|
+
from .exceptions import AuthenticationError, ConfigurationError
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True, slots=True)
|
|
23
|
+
class ConnectionSettings:
|
|
24
|
+
api_key: str = field(repr=False)
|
|
25
|
+
base_url: str
|
|
26
|
+
profile: str | None = None
|
|
27
|
+
config_path: Path | None = None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def default_config_path(*, environ: Mapping[str, str] | None = None) -> Path:
|
|
31
|
+
env = os.environ if environ is None else environ
|
|
32
|
+
if env.get(CONFIG_PATH_ENV):
|
|
33
|
+
return Path(env[CONFIG_PATH_ENV]).expanduser()
|
|
34
|
+
if os.name == "nt" and env.get("APPDATA"):
|
|
35
|
+
return Path(env["APPDATA"]) / "mimosynth" / "config.toml"
|
|
36
|
+
if env.get("XDG_CONFIG_HOME"):
|
|
37
|
+
return Path(env["XDG_CONFIG_HOME"]) / "mimosynth" / "config.toml"
|
|
38
|
+
return Path(env.get("HOME", str(Path.home()))) / ".config" / "mimosynth" / "config.toml"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def load_config_file(path: Path) -> dict:
|
|
42
|
+
if not path.exists():
|
|
43
|
+
return {}
|
|
44
|
+
try:
|
|
45
|
+
with path.open("rb") as handle:
|
|
46
|
+
data = tomllib.load(handle)
|
|
47
|
+
except (OSError, ValueError) as exc:
|
|
48
|
+
raise ConfigurationError("Unable to read or parse mimosynth configuration") from exc
|
|
49
|
+
if type(data.get("version", 1)) is not int or data.get("version", 1) != 1:
|
|
50
|
+
raise ConfigurationError("Unsupported mimosynth config version")
|
|
51
|
+
if "default_profile" in data and (
|
|
52
|
+
not isinstance(data["default_profile"], str) or not data["default_profile"].strip()
|
|
53
|
+
):
|
|
54
|
+
raise ConfigurationError("default_profile must be a non-empty string")
|
|
55
|
+
profiles = data.get("profiles", {})
|
|
56
|
+
if not isinstance(profiles, dict):
|
|
57
|
+
raise ConfigurationError("profiles must be a TOML table")
|
|
58
|
+
if (
|
|
59
|
+
os.name == "posix"
|
|
60
|
+
and any(isinstance(v, dict) and "api_key" in v for v in profiles.values())
|
|
61
|
+
and stat.S_IMODE(path.stat().st_mode) & 0o077
|
|
62
|
+
):
|
|
63
|
+
warnings.warn(
|
|
64
|
+
"mimosynth configuration contains credentials and is accessible by group or others",
|
|
65
|
+
UserWarning,
|
|
66
|
+
stacklevel=2,
|
|
67
|
+
)
|
|
68
|
+
return data
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def config_path_for(
|
|
72
|
+
config_path: str | Path | None = None, *, environ: Mapping[str, str] | None = None
|
|
73
|
+
) -> Path:
|
|
74
|
+
return (
|
|
75
|
+
Path(config_path).expanduser()
|
|
76
|
+
if config_path is not None
|
|
77
|
+
else default_config_path(environ=environ)
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def resolve_connection_settings(
|
|
82
|
+
*,
|
|
83
|
+
api_key: str | None = None,
|
|
84
|
+
base_url: str | None = None,
|
|
85
|
+
profile: str | None = None,
|
|
86
|
+
config_path: str | Path | None = None,
|
|
87
|
+
legacy_base_url: str | None = None,
|
|
88
|
+
environ: Mapping[str, str] | None = None,
|
|
89
|
+
) -> ConnectionSettings:
|
|
90
|
+
env = os.environ if environ is None else environ
|
|
91
|
+
path = config_path_for(config_path, environ=env)
|
|
92
|
+
data = load_config_file(path)
|
|
93
|
+
selected = profile if profile is not None else env.get(PROFILE_ENV)
|
|
94
|
+
if selected is None:
|
|
95
|
+
selected = data.get("default_profile")
|
|
96
|
+
profile_data = {}
|
|
97
|
+
if selected is not None:
|
|
98
|
+
if not isinstance(selected, str) or not selected.strip():
|
|
99
|
+
raise ConfigurationError("profile must be a non-empty string")
|
|
100
|
+
profile_data = data.get("profiles", {}).get(selected)
|
|
101
|
+
if profile_data is None:
|
|
102
|
+
raise ConfigurationError("Selected mimosynth profile does not exist")
|
|
103
|
+
if not isinstance(profile_data, dict):
|
|
104
|
+
raise ConfigurationError("Selected mimosynth profile must be a table")
|
|
105
|
+
for setting in ("api_key", "base_url"):
|
|
106
|
+
if setting in profile_data and (
|
|
107
|
+
not isinstance(profile_data[setting], str) or not profile_data[setting].strip()
|
|
108
|
+
):
|
|
109
|
+
raise ConfigurationError(f"Profile {setting} must be a non-empty string")
|
|
110
|
+
key = api_key if api_key is not None else env.get(API_KEY_ENV)
|
|
111
|
+
if key is None:
|
|
112
|
+
key = profile_data.get("api_key")
|
|
113
|
+
if not isinstance(key, str) or not key.strip():
|
|
114
|
+
raise AuthenticationError(
|
|
115
|
+
"MiMo API key is required; pass api_key=, set MIMO_API_KEY, or configure a profile",
|
|
116
|
+
stage="configuration",
|
|
117
|
+
)
|
|
118
|
+
legacy = legacy_base_url if legacy_base_url != DEFAULT_BASE_URL else None
|
|
119
|
+
url = (
|
|
120
|
+
base_url
|
|
121
|
+
if base_url is not None
|
|
122
|
+
else legacy
|
|
123
|
+
if legacy is not None
|
|
124
|
+
else env.get(BASE_URL_ENV, profile_data.get("base_url", DEFAULT_BASE_URL))
|
|
125
|
+
)
|
|
126
|
+
if not isinstance(url, str) or not url.strip():
|
|
127
|
+
raise ConfigurationError("MiMo base URL must be a non-empty string")
|
|
128
|
+
url = url.strip().rstrip("/")
|
|
129
|
+
parsed = urlparse(url)
|
|
130
|
+
if (
|
|
131
|
+
parsed.scheme not in {"http", "https"}
|
|
132
|
+
or not parsed.hostname
|
|
133
|
+
or parsed.username
|
|
134
|
+
or parsed.password
|
|
135
|
+
or parsed.query
|
|
136
|
+
or parsed.fragment
|
|
137
|
+
):
|
|
138
|
+
raise ConfigurationError(
|
|
139
|
+
"MiMo base URL must be an HTTP(S) URL without credentials or query"
|
|
140
|
+
)
|
|
141
|
+
host = parsed.hostname.lower()
|
|
142
|
+
if parsed.scheme == "http" and host not in {"localhost", "127.0.0.1", "::1"}:
|
|
143
|
+
raise ConfigurationError("Remote MiMo base URLs must use HTTPS")
|
|
144
|
+
key = key.strip()
|
|
145
|
+
if (
|
|
146
|
+
host.startswith("token-plan-")
|
|
147
|
+
and host.endswith(".xiaomimimo.com")
|
|
148
|
+
and key.startswith("sk-")
|
|
149
|
+
):
|
|
150
|
+
raise ConfigurationError(
|
|
151
|
+
"Token Plan endpoint requires a Token Plan credential, not a pay-as-you-go key"
|
|
152
|
+
)
|
|
153
|
+
if host == "api.xiaomimimo.com" and key.startswith(("tp-", "ttp-")):
|
|
154
|
+
raise ConfigurationError(
|
|
155
|
+
"Token Plan credential requires a Token Plan endpoint, not the pay-as-you-go endpoint"
|
|
156
|
+
)
|
|
157
|
+
return ConnectionSettings(key, url, selected, path if path.is_file() else None)
|
mimosynth/constants.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""MiMo TTS constants and provider metadata."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
DEFAULT_BASE_URL = "https://api.xiaomimimo.com/v1"
|
|
6
|
+
API_KEY_ENV = "MIMO_API_KEY"
|
|
7
|
+
BASE_URL_ENV = "MIMO_BASE_URL"
|
|
8
|
+
PROFILE_ENV = "MIMO_PROFILE"
|
|
9
|
+
CONFIG_PATH_ENV = "MIMOSYNTH_CONFIG"
|
|
10
|
+
SAMPLE_RATE = 24_000
|
|
11
|
+
|
|
12
|
+
PRESET_MODEL = "mimo-v2.5-tts"
|
|
13
|
+
VOICE_CLONE_MODEL = "mimo-v2.5-tts-voiceclone"
|
|
14
|
+
VOICE_DESIGN_MODEL = "mimo-v2.5-tts-voicedesign"
|
|
15
|
+
TTS_MODELS = (PRESET_MODEL, VOICE_CLONE_MODEL, VOICE_DESIGN_MODEL)
|
|
16
|
+
|
|
17
|
+
PRESET_VOICES = (
|
|
18
|
+
"mimo_default",
|
|
19
|
+
"冰糖",
|
|
20
|
+
"茉莉",
|
|
21
|
+
"苏打",
|
|
22
|
+
"白桦",
|
|
23
|
+
"Mia",
|
|
24
|
+
"Chloe",
|
|
25
|
+
"Milo",
|
|
26
|
+
"Dean",
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
# Provider documentation says the converted Base64 string must not exceed 10 MB.
|
|
30
|
+
MAX_REFERENCE_BASE64_BYTES = 10_000_000
|