| 1 | """Alibaba Qwen TTS backend for narration audio generation.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import os |
| 6 | from pathlib import Path |
| 7 | |
| 8 | from tts_backends.backend_common import download_audio, post_json, read_api_key |
| 9 | |
| 10 | |
| 11 | DEFAULT_ENDPOINT = "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation" |
| 12 | DEFAULT_MODEL = "qwen3-tts-flash" |
| 13 | |
| 14 | |
| 15 | def output_extension() -> str: |
| 16 | return ".wav" |
| 17 | |
| 18 | |
| 19 | def read_qwen_api_key(env_name: str | None = None) -> str: |
| 20 | if env_name: |
| 21 | return read_api_key(env_name, label="Qwen/DashScope") |
| 22 | return read_api_key("QWEN_API_KEY", "DASHSCOPE_API_KEY", label="Qwen/DashScope") |
| 23 | |
| 24 | |
| 25 | def resolve_url(base_url: str | None = None) -> str: |
| 26 | base = (base_url or os.environ.get("QWEN_TTS_BASE_URL") or DEFAULT_ENDPOINT).rstrip("/") |
| 27 | if base.endswith("/generation"): |
| 28 | return base |
| 29 | return base + "/api/v1/services/aigc/multimodal-generation/generation" |
| 30 | |
| 31 | |
| 32 | def generate( |
| 33 | text: str, |
| 34 | output_path: Path, |
| 35 | *, |
| 36 | api_key: str, |
| 37 | voice_id: str, |
| 38 | model: str, |
| 39 | language_type: str, |
| 40 | instructions: str | None, |
| 41 | optimize_instructions: bool | None, |
| 42 | base_url: str | None, |
| 43 | ) -> None: |
| 44 | input_payload: dict[str, object] = { |
| 45 | "text": text, |
| 46 | "voice": voice_id, |
| 47 | } |
| 48 | if language_type: |
| 49 | input_payload["language_type"] = language_type |
| 50 | if instructions: |
| 51 | input_payload["instructions"] = instructions |
| 52 | if optimize_instructions is not None: |
| 53 | input_payload["optimize_instructions"] = optimize_instructions |
| 54 | |
| 55 | data = post_json( |
| 56 | resolve_url(base_url), |
| 57 | headers={"Authorization": f"Bearer {api_key}"}, |
| 58 | payload={ |
| 59 | "model": model, |
| 60 | "input": input_payload, |
| 61 | }, |
| 62 | timeout=180, |
| 63 | ) |
| 64 | audio = (data.get("output") or {}).get("audio") or {} |
| 65 | audio_url = audio.get("url") |
| 66 | if not audio_url: |
| 67 | raise RuntimeError(f"Qwen TTS response missing audio URL: {data}") |
| 68 | download_audio(audio_url, output_path) |
| 69 | |
| 70 | |
| 71 | def print_voices() -> None: |
| 72 | print("Qwen TTS voices are selected by voice.") |
| 73 | print("Use a system voice name or a cloned voice from Qwen voice cloning.") |
| 74 | print("Example system voice from Alibaba Cloud docs: Cherry") |
| 75 | |
| 76 |