|
| 1 | +"""A say-style ElevenLabs text-to-speech CLI. |
| 2 | +
|
| 3 | +Reads text from a positional argument, a file, or stdin, synthesizes speech with |
| 4 | +the ElevenLabs API, and either plays it through the speakers with ``ffplay`` or |
| 5 | +writes the audio to a file. The API key comes from ``ELEVENLABS_API_KEY``; there |
| 6 | +is no embedded key and no silent fallback. |
| 7 | +""" |
| 8 | + |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +import argparse |
| 12 | +import os |
| 13 | +import subprocess |
| 14 | +import sys |
| 15 | +import tempfile |
| 16 | +from dataclasses import dataclass |
| 17 | +from pathlib import Path |
| 18 | + |
| 19 | +from elevenlabs import ElevenLabs |
| 20 | +from elevenlabs.core import ApiError |
| 21 | + |
| 22 | +# Rachel is a stable ElevenLabs premade voice that is available on every account, |
| 23 | +# so it is a safe default for a `say` replacement. |
| 24 | +# https://elevenlabs.io/docs/api-reference/voices/get |
| 25 | +DEFAULT_VOICE_ID = "21m00Tcm4TlvDq8ikWAM" |
| 26 | +DEFAULT_MODEL_ID = "eleven_flash_v2_5" |
| 27 | +DEFAULT_OUTPUT_FORMAT = "mp3_44100_128" |
| 28 | + |
| 29 | +API_KEY_ENV = "ELEVENLABS_API_KEY" |
| 30 | + |
| 31 | + |
| 32 | +class SayError(Exception): |
| 33 | + """An operator-facing failure with an actionable message.""" |
| 34 | + |
| 35 | + |
| 36 | +@dataclass(frozen=True) |
| 37 | +class CliArgs: |
| 38 | + text: str | None |
| 39 | + file: Path | None |
| 40 | + output: Path | None |
| 41 | + voice: str |
| 42 | + model: str |
| 43 | + output_format: str |
| 44 | + |
| 45 | + |
| 46 | +def parse_args(argv: list[str] | None = None) -> CliArgs: |
| 47 | + parser = argparse.ArgumentParser( |
| 48 | + prog="elevenlabs-say", |
| 49 | + description="Synthesize speech with ElevenLabs and play it or save it to a file.", |
| 50 | + ) |
| 51 | + _ = parser.add_argument( |
| 52 | + "text", |
| 53 | + nargs="?", |
| 54 | + default=None, |
| 55 | + help="Text to speak. Omit to read from --file or stdin.", |
| 56 | + ) |
| 57 | + _ = parser.add_argument( |
| 58 | + "-f", |
| 59 | + "--file", |
| 60 | + type=Path, |
| 61 | + default=None, |
| 62 | + help="Read text from this file instead of the positional argument.", |
| 63 | + ) |
| 64 | + _ = parser.add_argument( |
| 65 | + "-o", |
| 66 | + "--output", |
| 67 | + type=Path, |
| 68 | + default=None, |
| 69 | + help="Write audio to this file instead of playing it.", |
| 70 | + ) |
| 71 | + _ = parser.add_argument( |
| 72 | + "--voice", |
| 73 | + default=DEFAULT_VOICE_ID, |
| 74 | + help=( |
| 75 | + "Voice name or id. A value that matches a voice name is resolved to " |
| 76 | + f"its id; otherwise it is used verbatim. Defaults to Rachel ({DEFAULT_VOICE_ID})." |
| 77 | + ), |
| 78 | + ) |
| 79 | + _ = parser.add_argument( |
| 80 | + "--model", |
| 81 | + default=DEFAULT_MODEL_ID, |
| 82 | + help=f"Model id. Defaults to {DEFAULT_MODEL_ID}.", |
| 83 | + ) |
| 84 | + _ = parser.add_argument( |
| 85 | + "--format", |
| 86 | + dest="output_format", |
| 87 | + default=DEFAULT_OUTPUT_FORMAT, |
| 88 | + help=f"Output audio format. Defaults to {DEFAULT_OUTPUT_FORMAT}.", |
| 89 | + ) |
| 90 | + namespace = parser.parse_args(argv) |
| 91 | + |
| 92 | + text: str | None = namespace.text |
| 93 | + file: Path | None = namespace.file |
| 94 | + output: Path | None = namespace.output |
| 95 | + voice: str = namespace.voice |
| 96 | + model: str = namespace.model |
| 97 | + output_format: str = namespace.output_format |
| 98 | + |
| 99 | + return CliArgs( |
| 100 | + text=text, |
| 101 | + file=file, |
| 102 | + output=output, |
| 103 | + voice=voice, |
| 104 | + model=model, |
| 105 | + output_format=output_format, |
| 106 | + ) |
| 107 | + |
| 108 | + |
| 109 | +def read_text(args: CliArgs) -> str: |
| 110 | + """Resolve the text to speak: positional arg, then --file, then stdin.""" |
| 111 | + if args.text is not None: |
| 112 | + source = args.text |
| 113 | + elif args.file is not None: |
| 114 | + try: |
| 115 | + source = args.file.read_text(encoding="utf-8") |
| 116 | + except OSError as exc: |
| 117 | + raise SayError(f"cannot read text file {args.file}: {exc}") from exc |
| 118 | + elif not sys.stdin.isatty(): |
| 119 | + source = sys.stdin.read() |
| 120 | + else: |
| 121 | + raise SayError( |
| 122 | + "no text to speak: pass TEXT, use --file PATH, or pipe text on stdin" |
| 123 | + ) |
| 124 | + |
| 125 | + text = source.strip() |
| 126 | + if not text: |
| 127 | + raise SayError("no text to speak: the resolved text is empty") |
| 128 | + return text |
| 129 | + |
| 130 | + |
| 131 | +def make_client() -> ElevenLabs: |
| 132 | + if not os.environ.get(API_KEY_ENV): |
| 133 | + raise SayError( |
| 134 | + f"{API_KEY_ENV} is not set; export your ElevenLabs API key, " |
| 135 | + f"for example: export {API_KEY_ENV}=sk_..." |
| 136 | + ) |
| 137 | + return ElevenLabs() |
| 138 | + |
| 139 | + |
| 140 | +def resolve_voice_id(client: ElevenLabs, voice: str) -> str: |
| 141 | + """Treat ``voice`` as a name first; fall back to using it as an id verbatim. |
| 142 | +
|
| 143 | + ElevenLabs voice ids are opaque 20-character tokens, so a human-typed name |
| 144 | + almost never collides with an id. Searching by name keeps the CLI usable with |
| 145 | + friendly voice names while still accepting a raw id. |
| 146 | + """ |
| 147 | + try: |
| 148 | + response = client.voices.search(search=voice) |
| 149 | + except ApiError as exc: |
| 150 | + raise SayError(format_api_error("resolve voice", exc)) from exc |
| 151 | + |
| 152 | + for candidate in response.voices: |
| 153 | + if candidate.name is not None and candidate.name.casefold() == voice.casefold(): |
| 154 | + return candidate.voice_id |
| 155 | + |
| 156 | + # No name match: use the supplied value as a literal voice id. |
| 157 | + return voice |
| 158 | + |
| 159 | + |
| 160 | +def synthesize(client: ElevenLabs, text: str, args: CliArgs, voice_id: str) -> bytes: |
| 161 | + try: |
| 162 | + chunks = client.text_to_speech.convert( |
| 163 | + voice_id=voice_id, |
| 164 | + text=text, |
| 165 | + model_id=args.model, |
| 166 | + output_format=args.output_format, |
| 167 | + ) |
| 168 | + return b"".join(chunks) |
| 169 | + except ApiError as exc: |
| 170 | + raise SayError(format_api_error("synthesize speech", exc)) from exc |
| 171 | + |
| 172 | + |
| 173 | +def format_api_error(action: str, exc: ApiError) -> str: |
| 174 | + if exc.status_code is not None: |
| 175 | + return f"failed to {action}: ElevenLabs API returned status {exc.status_code}: {exc.body}" |
| 176 | + return f"failed to {action}: {exc.body}" |
| 177 | + |
| 178 | + |
| 179 | +def write_output(audio: bytes, output: Path) -> None: |
| 180 | + try: |
| 181 | + _ = output.write_bytes(audio) |
| 182 | + except OSError as exc: |
| 183 | + raise SayError(f"cannot write audio to {output}: {exc}") from exc |
| 184 | + |
| 185 | + |
| 186 | +def play(audio: bytes) -> None: |
| 187 | + """Play MP3 bytes through the speakers with ``ffplay``. |
| 188 | +
|
| 189 | + ``ffplay`` is provided by ``ffmpeg``, which the Nix wrapper puts on PATH. It |
| 190 | + is the cross-platform, Nix-pinnable counterpart to macOS ``afplay``. |
| 191 | + """ |
| 192 | + with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as handle: |
| 193 | + temp_path = Path(handle.name) |
| 194 | + _ = handle.write(audio) |
| 195 | + try: |
| 196 | + completed = subprocess.run( |
| 197 | + [ |
| 198 | + "ffplay", |
| 199 | + "-nodisp", |
| 200 | + "-autoexit", |
| 201 | + "-loglevel", |
| 202 | + "error", |
| 203 | + str(temp_path), |
| 204 | + ], |
| 205 | + check=False, |
| 206 | + ) |
| 207 | + if completed.returncode != 0: |
| 208 | + raise SayError(f"ffplay exited with status {completed.returncode}") |
| 209 | + except FileNotFoundError as exc: |
| 210 | + raise SayError( |
| 211 | + "ffplay was not found on PATH; install ffmpeg to play audio, " |
| 212 | + "or use --output PATH to save the audio instead" |
| 213 | + ) from exc |
| 214 | + finally: |
| 215 | + temp_path.unlink(missing_ok=True) |
| 216 | + |
| 217 | + |
| 218 | +def run(args: CliArgs) -> None: |
| 219 | + text = read_text(args) |
| 220 | + client = make_client() |
| 221 | + voice_id = resolve_voice_id(client, args.voice) |
| 222 | + audio = synthesize(client, text, args, voice_id) |
| 223 | + |
| 224 | + if args.output is not None: |
| 225 | + write_output(audio, args.output) |
| 226 | + print(f"wrote {args.output}", file=sys.stderr) |
| 227 | + else: |
| 228 | + play(audio) |
| 229 | + |
| 230 | + |
| 231 | +def main() -> None: |
| 232 | + args = parse_args() |
| 233 | + try: |
| 234 | + run(args) |
| 235 | + except SayError as exc: |
| 236 | + print(f"elevenlabs-say: {exc}", file=sys.stderr) |
| 237 | + raise SystemExit(1) from exc |
0 commit comments