Download utils/tts_mimo.py from PerrinT/office: direct link, hf CLI and curl.
- Browser
- Download file 2.33 kB
-
https://huggingface.co/spaces/PerrinT/office/resolve/main/utils/tts_mimo.py
- Command line
-
hf download hf://spaces/PerrinT/office/utils/tts_mimo.py
-
curl -L -o tts_mimo.py https://huggingface.co/spaces/PerrinT/office/resolve/main/utils/tts_mimo.py
2.33 kB
| import base64 | |
| import os | |
| import streamlit as st | |
| from openai import OpenAI | |
| def get_mimo_tts_client(): | |
| """获取 mimo TTS 客户端(复用同一套密钥)""" | |
| api_key = os.getenv("MIMO_API_KEY") | |
| base_url = os.getenv("MIMO_BASE_URL") | |
| if not api_key: | |
| try: | |
| api_key = st.secrets["MIMO_API_KEY"] | |
| except Exception: | |
| pass | |
| if not base_url: | |
| try: | |
| base_url = st.secrets["MIMO_BASE_URL"] | |
| except Exception: | |
| base_url = "https://api.xiaomimimo.com/v1" | |
| if not api_key: | |
| return None | |
| return OpenAI(api_key=api_key, base_url=base_url) | |
| # mimo-v2.5-tts 预置音色列表 | |
| PRESET_VOICES = { | |
| "冰糖": {"id": "冰糖", "lang": "中文", "gender": "女性"}, | |
| "茉莉": {"id": "茉莉", "lang": "中文", "gender": "女性"}, | |
| "苏打": {"id": "苏打", "lang": "中文", "gender": "男性"}, | |
| "白桦": {"id": "白桦", "lang": "中文", "gender": "男性"}, | |
| "Mia": {"id": "Mia", "lang": "英文", "gender": "女性"}, | |
| "Chloe": {"id": "Chloe", "lang": "英文", "gender": "女性"}, | |
| "Milo": {"id": "Milo", "lang": "英文", "gender": "男性"}, | |
| "Dean": {"id": "Dean", "lang": "英文", "gender": "男性"}, | |
| } | |
| def text_to_speech( | |
| text: str, | |
| voice: str = "冰糖", | |
| style: str = "", | |
| ) -> bytes: | |
| """调用 mimo-v2.5-tts 模型生成语音 | |
| Args: | |
| text: 要合成的文本(放在 assistant 消息中) | |
| voice: 预置音色名称 | |
| style: 风格指令(放在 user 消息中,可选) | |
| Returns: | |
| WAV 格式的音频字节数据 | |
| """ | |
| client = get_mimo_tts_client() | |
| if not client: | |
| raise RuntimeError("未配置 MIMO API Key") | |
| messages = [] | |
| # user 消息:风格指令(可选) | |
| if style: | |
| messages.append({"role": "user", "content": style}) | |
| else: | |
| messages.append({"role": "user", "content": ""}) | |
| # assistant 消息:要合成的目标文本 | |
| messages.append({"role": "assistant", "content": text}) | |
| completion = client.chat.completions.create( | |
| model="mimo-v2.5-tts", | |
| messages=messages, | |
| audio={"format": "wav", "voice": voice}, | |
| ) | |
| message = completion.choices[0].message | |
| audio_bytes = base64.b64decode(message.audio.data) | |
| return audio_bytes | |