|
| 1 | +import base64 |
| 2 | +import uuid |
| 3 | +from pathlib import Path |
| 4 | +from urllib.parse import urlparse |
| 5 | + |
| 6 | +import httpx |
| 7 | + |
| 8 | +from astrbot import logger |
| 9 | +from astrbot.core.utils.astrbot_path import get_astrbot_temp_path |
| 10 | +from astrbot.core.utils.io import download_file |
| 11 | +from astrbot.core.utils.tencent_record_helper import ( |
| 12 | + convert_to_pcm_wav, |
| 13 | + tencent_silk_to_wav, |
| 14 | +) |
| 15 | + |
| 16 | +DEFAULT_MIMO_API_BASE = "https://api.xiaomimimo.com/v1" |
| 17 | +DEFAULT_MIMO_TTS_MODEL = "mimo-v2-tts" |
| 18 | +DEFAULT_MIMO_TTS_VOICE = "mimo_default" |
| 19 | +DEFAULT_MIMO_TTS_SEED_TEXT = "Hello, MiMo, have you had lunch?" |
| 20 | +DEFAULT_MIMO_STT_MODEL = "mimo-v2-omni" |
| 21 | +DEFAULT_MIMO_STT_SYSTEM_PROMPT = ( |
| 22 | + "You are a speech transcription assistant. " |
| 23 | + "Transcribe the spoken content from the audio exactly and return only the transcription text." |
| 24 | +) |
| 25 | +DEFAULT_MIMO_STT_USER_PROMPT = ( |
| 26 | + "Please transcribe the content of the audio and return only the transcription text." |
| 27 | +) |
| 28 | + |
| 29 | + |
| 30 | +class MiMoAPIError(Exception): |
| 31 | + pass |
| 32 | + |
| 33 | + |
| 34 | +def normalize_timeout(timeout: int | str | None) -> int | None: |
| 35 | + if timeout in (None, ""): |
| 36 | + return None |
| 37 | + if isinstance(timeout, str): |
| 38 | + return int(timeout) |
| 39 | + return timeout |
| 40 | + |
| 41 | + |
| 42 | +def build_headers(api_key: str) -> dict[str, str]: |
| 43 | + headers = {"Content-Type": "application/json"} |
| 44 | + if api_key: |
| 45 | + headers["Authorization"] = f"Bearer {api_key}" |
| 46 | + return headers |
| 47 | + |
| 48 | + |
| 49 | +def get_temp_dir() -> Path: |
| 50 | + temp_dir = Path(get_astrbot_temp_path()) |
| 51 | + temp_dir.mkdir(parents=True, exist_ok=True) |
| 52 | + return temp_dir |
| 53 | + |
| 54 | + |
| 55 | +def create_http_client(timeout: int | None, proxy: str) -> httpx.AsyncClient: |
| 56 | + client_kwargs: dict[str, object] = { |
| 57 | + "timeout": timeout, |
| 58 | + "follow_redirects": True, |
| 59 | + } |
| 60 | + if proxy: |
| 61 | + logger.info("[MiMo API] Using proxy: %s", proxy) |
| 62 | + client_kwargs["proxy"] = proxy |
| 63 | + return httpx.AsyncClient(**client_kwargs) |
| 64 | + |
| 65 | + |
| 66 | +def build_api_url(api_base: str) -> str: |
| 67 | + normalized_api_base = api_base.rstrip("/") |
| 68 | + if normalized_api_base.endswith("/chat/completions"): |
| 69 | + return normalized_api_base |
| 70 | + return normalized_api_base + "/chat/completions" |
| 71 | + |
| 72 | + |
| 73 | +async def _detect_audio_format(file_path: Path) -> str | None: |
| 74 | + silk_header = b"SILK" |
| 75 | + amr_header = b"#!AMR" |
| 76 | + |
| 77 | + try: |
| 78 | + with file_path.open("rb") as file: |
| 79 | + file_header = file.read(8) |
| 80 | + except FileNotFoundError: |
| 81 | + return None |
| 82 | + |
| 83 | + if silk_header in file_header: |
| 84 | + return "silk" |
| 85 | + if amr_header in file_header: |
| 86 | + return "amr" |
| 87 | + return None |
| 88 | + |
| 89 | + |
| 90 | +async def prepare_audio_input(audio_source: str) -> tuple[str, list[Path]]: |
| 91 | + cleanup_paths: list[Path] = [] |
| 92 | + source_path = Path(audio_source) |
| 93 | + is_remote = audio_source.startswith(("http://", "https://")) |
| 94 | + is_tencent = "multimedia.nt.qq.com.cn" in audio_source if is_remote else False |
| 95 | + |
| 96 | + if is_remote: |
| 97 | + parsed_url = urlparse(audio_source) |
| 98 | + suffix = Path(parsed_url.path).suffix or ".input" |
| 99 | + download_path = get_temp_dir() / f"mimo_audio_{uuid.uuid4().hex[:8]}{suffix}" |
| 100 | + await download_file(audio_source, str(download_path)) |
| 101 | + source_path = download_path |
| 102 | + cleanup_paths.append(download_path) |
| 103 | + |
| 104 | + if not source_path.exists(): |
| 105 | + raise FileNotFoundError(f"File does not exist: {source_path}") |
| 106 | + |
| 107 | + if source_path.suffix.lower() in {".amr", ".silk"} or is_tencent: |
| 108 | + file_format = await _detect_audio_format(source_path) |
| 109 | + if file_format in {"silk", "amr"}: |
| 110 | + converted_path = get_temp_dir() / f"mimo_audio_{uuid.uuid4().hex[:8]}.wav" |
| 111 | + cleanup_paths.append(converted_path) |
| 112 | + if file_format == "silk": |
| 113 | + logger.info("Converting silk file to wav for MiMo STT...") |
| 114 | + await tencent_silk_to_wav(str(source_path), str(converted_path)) |
| 115 | + else: |
| 116 | + logger.info("Converting amr file to wav for MiMo STT...") |
| 117 | + await convert_to_pcm_wav(str(source_path), str(converted_path)) |
| 118 | + source_path = converted_path |
| 119 | + |
| 120 | + encoded_audio = base64.b64encode(source_path.read_bytes()).decode("utf-8") |
| 121 | + return encoded_audio, cleanup_paths |
| 122 | + |
| 123 | + |
| 124 | +def cleanup_files(paths: list[Path]) -> None: |
| 125 | + for path in paths: |
| 126 | + try: |
| 127 | + path.unlink(missing_ok=True) |
| 128 | + except Exception as exc: |
| 129 | + logger.warning("Failed to remove temporary MiMo file %s: %s", path, exc) |
0 commit comments