AgriciDaniel/claude-blog / skills/blog-audio
blog-audio
VerifiedPaid Gemini TTS audio for a finished blog post: summary, full read-aloud, or two-speaker dialogue, with an MP3 and an HTML5 embed. Asks for explicit consent before the first paid call. Runs only on an explicit request: /blog audio, "generate audio for this blog post", "narrate this blog post", "audio version of this post", or "podcast version of this post". Not for general speech or dictation questions.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 13.9 KB |
| references/models.md | markdown | 1.4 KB |
| references/voices.md | markdown | 6.4 KB |
| scripts/__init__.py | script | 62 B |
| scripts/generate_audio.py | script | 32.8 KB |
| scripts/requirements.lock | other | 51.3 KB |
| scripts/requirements.txt | manifest | 499 B |
| scripts/run.py | script | 3.6 KB |
| scripts/runtime_paths.py | script | 2.6 KB |
| scripts/setup_environment.py | script | 6.1 KB |
scripts/generate_audio.py
View on GitHub#!/usr/bin/env python3
"""
Blog Audio Generator - Gemini TTS
Converts prepared text to speech using Google's Gemini TTS models.
The default model is flash38 (gemini-3.8-flash-tts). The 3.1 and 2.5 aliases
retain the generate_content compatibility path but are deprecated: Google's
deprecations page (https://ai.google.dev/gemini-api/docs/deprecations, checked
2026-10-12) lists gemini-3.1-flash-tts-preview, gemini-2.5-flash-preview-tts and
gemini-2.5-pro-preview-tts with a shutdown date of 2026-11-17 (the earliest
possible date). Using one prints a deprecation warning on stderr. The 3.8
aliases use unary WAV responses from the Interactions API.
Cost control: each chunk is one billed API call. A run that needs more than
--max-chunks chunks (default 12) is refused before any API call is made.
The API key is read only from GOOGLE_AI_API_KEY or GEMINI_API_KEY and is never
printed; error text passes through redact_secrets().
Usage:
python3 scripts/run.py generate_audio.py --text "Hello world" --voice Charon --json
python3 scripts/run.py generate_audio.py --text-file article.txt --voice Puck --voice2 Kore --json
python3 scripts/run.py generate_audio.py --text "Test" --dry-run --json
"""
import argparse
import base64
import binascii
import html
import io
import json
import mimetypes
import os
import re
import shutil
import subprocess
import sys
import struct
import tempfile
import wave
from datetime import datetime, timezone
from pathlib import Path
# All 30 Gemini TTS prebuilt voices
VOICES = {
"Zephyr": "Bright", "Puck": "Upbeat", "Charon": "Informative",
"Kore": "Firm", "Fenrir": "Excitable", "Leda": "Youthful",
"Orus": "Firm", "Aoede": "Breezy", "Callirrhoe": "Easy-going",
"Autonoe": "Bright", "Enceladus": "Breathy", "Iapetus": "Clear",
"Umbriel": "Easy-going", "Algieba": "Smooth", "Despina": "Smooth",
"Erinome": "Clear", "Algenib": "Gravelly", "Rasalgethi": "Informative",
"Laomedeia": "Upbeat", "Achernar": "Soft", "Alnilam": "Firm",
"Schedar": "Even", "Gacrux": "Mature", "Pulcherrima": "Forward",
"Achird": "Friendly", "Zubenelgenubi": "Casual", "Vindemiatrix": "Gentle",
"Sadachbia": "Lively", "Sadaltager": "Knowledgeable", "Sulafat": "Warm",
}
MODELS = {
"flash": "gemini-3.1-flash-tts-preview",
"flash31": "gemini-3.1-flash-tts-preview",
"flash38": "gemini-3.8-flash-tts",
"flash-lite38": "gemini-3.8-flash-lite-tts",
"legacy-flash25": "gemini-2.5-flash-preview-tts",
"pro": "gemini-2.5-pro-preview-tts",
"legacy-pro25": "gemini-2.5-pro-preview-tts",
}
DEFAULT_MODEL = "flash38"
DEFAULT_MAX_CHUNKS = 12
# Aliases that resolve to models Google lists for shutdown on 2026-11-17.
DEPRECATED_MODEL_ALIASES = frozenset(
{"flash", "flash31", "pro", "legacy-flash25", "legacy-pro25"}
)
DEPRECATED_SHUTDOWN_DATE = datetime(2026, 11, 17, tzinfo=timezone.utc)
API_KEY_ENV_VARS = ("GOOGLE_AI_API_KEY", "GEMINI_API_KEY")
# Audio constants (Gemini TTS output format)
SAMPLE_RATE = 24000 # 24kHz
SAMPLE_WIDTH = 2 # 16-bit (2 bytes per sample)
CHANNELS = 1 # Mono
# Cost per 1M tokens. Audio output tokens are billed at 25 tokens per second.
COST_PER_1M_OUTPUT = {
"flash": 20.0,
"flash31": 20.0,
"flash38": 9.0,
"flash-lite38": 6.0,
"legacy-flash25": 10.0,
"pro": 20.0,
"legacy-pro25": 20.0,
}
COST_PER_1M_INPUT = {
"flash": 1.0,
"flash31": 1.0,
"flash38": 0.50,
"flash-lite38": 0.50,
"legacy-flash25": 0.50,
"pro": 1.0,
"legacy-pro25": 1.0,
}
INTERACTIONS_WAV_MODELS = frozenset({"flash38", "flash-lite38"})
PRICE_CHANGE_2027 = datetime(2027, 1, 1, tzinfo=timezone.utc)
POST_2026_PRICES = {
"flash38": (1.0, 18.0),
"flash-lite38": (1.0, 12.0),
}
AUDIO_TOKENS_PER_SECOND = 25
MAX_INPUT_TOKENS = 8192
CHUNK_TARGET_TOKENS = 7800
MAX_TEXT_FILE_BYTES = 1_000_000
TEXT_FILE_EXTENSIONS = {
".csv",
".htm",
".html",
".log",
".markdown",
".md",
".rst",
".text",
".tsv",
".txt",
}
_REDACTIONS = (
(re.compile(
r"(?i)((?:x-goog-api-key|x-api-key|authorization)[\"']?\s*[:=]\s*[\"']?)"
r"(?:bearer\s+)?[^\s,;\"'<>}]+"
), r"\1[redacted]"),
(re.compile(
r"(?i)((?:\\*[\"'])(?:api[_-]?key|key|access_token|refresh_token|token)"
r"(?:\\*[\"'])\s*:\s*\\*[\"'])[^\"'\\]*"
), r"\1[redacted]"),
(re.compile(
r"(?i)((?:(?<![A-Za-z0-9])|(?<=%26)|(?<=%3F))(?:api[_-]?key|key|access_token|token)%3D)"
r"[^%&\s\"'<>]+"
), r"\1[redacted]"),
(re.compile(
r"(?i)((?<![A-Za-z0-9])(?:api[_-]?key|key|access_token|token)\s*=\s*)[^&\s\"'<>]+"
), r"\1[redacted]"),
(re.compile(r"(?i)\bBearer\s+[A-Za-z0-9._~+/=-]+"), "Bearer [redacted]"),
(re.compile(r"\bAIza[0-9A-Za-z_-]{35}"), "[redacted]"),
)
def redact_secrets(text, secrets=()) -> str:
"""Remove API keys and tokens from text before it reaches output.
Same coverage as blog-google's redactor: key=..., URL-encoded and HTML
escaped forms, JSON pairs, x-goog-api-key and Authorization headers, Bearer
tokens and bare AIza keys, plus any literal values passed in `secrets`.
"""
out = str(text)
for secret in secrets or ():
if secret and len(str(secret)) >= 4:
out = out.replace(str(secret), "[redacted]")
for pattern, replacement in _REDACTIONS:
out = pattern.sub(replacement, out)
return out
def get_api_key() -> str | None:
"""Return the Gemini API key from the environment only (never from args)."""
for name in API_KEY_ENV_VARS:
value = os.environ.get(name)
if value and value.strip():
return value.strip()
return None
def deprecation_warning(alias: str, now: datetime | None = None) -> str | None:
"""Warning text for an alias whose model Google lists for shutdown, else None."""
if alias not in DEPRECATED_MODEL_ALIASES:
return None
current = now or datetime.now(timezone.utc)
shutdown = DEPRECATED_SHUTDOWN_DATE.date().isoformat()
state = (
f"was scheduled to shut down on {shutdown} and may no longer work"
if current >= DEPRECATED_SHUTDOWN_DATE
else f"is scheduled to shut down on {shutdown} (earliest possible date)"
)
return (
f"Warning: model alias '{alias}' ({MODELS[alias]}) is deprecated and {state}. "
f"Use --model {DEFAULT_MODEL} ({MODELS[DEFAULT_MODEL]}) or flash-lite38."
)
def plan_chunks(text: str, voice2: str | None, model: str) -> list[str]:
"""Return the chunks a run would send, one billed API call each."""
if voice2 and model in INTERACTIONS_WAV_MODELS:
return split_38_dialogue_for_tts(text)
return split_text_for_tts(text)
def _path_contains_symlink(path: Path, root: Path) -> bool:
"""Return True if path or any existing parent below root is a symlink."""
current = path if path.exists() or path.is_symlink() else path.parent
current = current.absolute()
root = root.absolute()
while current != current.parent:
if current.is_symlink():
return True
if current == root:
return False
current = current.parent
return False
def _resolve_under_cwd(path_value: str, label: str, must_exist: bool) -> Path:
"""Resolve a path under the current working directory."""
root = Path.cwd().resolve()
candidate = Path(path_value).expanduser()
if not candidate.is_absolute():
candidate = root / candidate
if _path_contains_symlink(candidate, root):
raise ValueError(f"{label} must not use symlinks")
try:
resolved = candidate.resolve(strict=must_exist)
except FileNotFoundError as exc:
raise ValueError(f"{label} not found: {path_value}") from exc
try:
resolved.relative_to(root)
except ValueError as exc:
raise ValueError(f"Refusing {label} outside working directory: {path_value}") from exc
return resolved
def read_text_file(path_value: str) -> str:
"""Read a bounded text file from the current working directory."""
path = _resolve_under_cwd(path_value, "text file", must_exist=True)
if not path.is_file():
raise ValueError(f"Text file is not a regular file: {path_value}")
size = path.stat().st_size
if size > MAX_TEXT_FILE_BYTES:
raise ValueError(f"Text file exceeds {MAX_TEXT_FILE_BYTES} bytes: {path_value}")
mime_type, _ = mimetypes.guess_type(path.name)
is_text_mime = bool(mime_type and mime_type.startswith("text/"))
if path.suffix.lower() not in TEXT_FILE_EXTENSIONS and not is_text_mime:
raise ValueError("Text file must use a text extension or text MIME type")
return path.read_text(encoding="utf-8")
def resolve_output_path(path_value: str) -> Path:
"""Resolve a writable output path under the current working directory."""
return _resolve_under_cwd(path_value, "output path", must_exist=False)
def get_token_prices(
model: str, as_of: datetime | None = None
) -> tuple[float, float]:
"""Return input and output prices per million tokens for an alias."""
if model not in MODELS:
raise ValueError(f"Unknown TTS model alias: {model}")
effective_at = as_of or datetime.now(timezone.utc)
if effective_at.tzinfo is None:
effective_at = effective_at.replace(tzinfo=timezone.utc)
if model in POST_2026_PRICES and effective_at >= PRICE_CHANGE_2027:
return POST_2026_PRICES[model]
return COST_PER_1M_INPUT[model], COST_PER_1M_OUTPUT[model]
def estimate_cost(
text: str, model: str, as_of: datetime | None = None
) -> dict:
"""Estimate generation cost from text length."""
char_count = len(text)
input_tokens = char_count / 4 # rough: 1 token ~ 4 chars
# Output tokens scale with audio duration; ~150 words/min speech
word_count = len(text.split())
duration_minutes = word_count / 150
duration_seconds = duration_minutes * 60
# Rough output token estimate based on audio duration
output_tokens = duration_seconds * AUDIO_TOKENS_PER_SECOND
input_price, output_price = get_token_prices(model, as_of)
input_cost = (input_tokens / 1_000_000) * input_price
output_cost = (output_tokens / 1_000_000) * output_price
total_cost = input_cost + output_cost
return {
"input_tokens_est": int(input_tokens),
"output_tokens_est": int(output_tokens),
"duration_seconds_est": int(duration_seconds),
"duration_human_est": f"{int(duration_minutes)}:{int(duration_seconds % 60):02d}",
"cost_estimate": f"${total_cost:.3f}",
"chunk_count_est": len(split_text_for_tts(text)),
}
def estimate_input_tokens(text: str) -> int:
"""Estimate Gemini input tokens from text length."""
return max(1, int(len(text) / 4))
def split_text_for_tts(text: str, max_tokens: int = CHUNK_TARGET_TOKENS) -> list[str]:
"""Split long text into TTS-safe chunks without cutting words."""
if estimate_input_tokens(text) <= max_tokens:
return [text]
max_chars = max_tokens * 4
chunks = []
current = []
current_len = 0
paragraphs = [p.strip() for p in text.split("\n\n") if p.strip()]
for paragraph in paragraphs:
if len(paragraph) > max_chars:
words = paragraph.split()
for word in words:
word_len = len(word) + 1
if current and current_len + word_len > max_chars:
chunks.append(" ".join(current).strip())
current = []
current_len = 0
current.append(word)
current_len += word_len
continue
add_len = len(paragraph) + 2
if current and current_len + add_len > max_chars:
chunks.append("\n\n".join(current).strip())
current = []
current_len = 0
current.append(paragraph)
current_len += add_len
if current:
separator = "\n\n" if any("\n" in item for item in current) else " "
chunks.append(separator.join(current).strip())
return [chunk for chunk in chunks if chunk]
def pcm_to_wav(pcm_data: bytes, output_path: str):
"""Write raw PCM data as a WAV file."""
num_samples = len(pcm_data) // SAMPLE_WIDTH
data_size = num_samples * SAMPLE_WIDTH * CHANNELS
byte_rate = SAMPLE_RATE * CHANNELS * SAMPLE_WIDTH
block_align = CHANNELS * SAMPLE_WIDTH
with open(output_path, "wb") as f:
# RIFF header
f.write(b"RIFF")
f.write(struct.pack("<I", 36 + data_size))
f.write(b"WAVE")
# fmt chunk
f.write(b"fmt ")
f.write(struct.pack("<I", 16)) # chunk size
f.write(struct.pack("<H", 1)) # PCM format
f.write(struct.pack("<H", CHANNELS))
f.write(struct.pack("<I", SAMPLE_RATE))
f.write(struct.pack("<I", byte_rate))
f.write(struct.pack("<H", block_align))
f.write(struct.pack("<H", SAMPLE_WIDTH * 8))
# data chunk
f.write(b"data")
f.write(struct.pack("<I", data_size))
f.write(pcm_data)
def atomic_write_wav(pcm_data: bytes, output_path: Path) -> None:
"""Write a WAV file atomically."""
output_path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp_name = tempfile.mkstemp(
prefix=f".{output_path.stem}.",
suffix=".wav",
dir=str(output_path.parent),
)
os.close(fd)
tmp_path = Path(tmp_name)
try:
pcm_to_wav(pcm_data, str(tmp_path))
os.replace(tmp_path, output_path)
finally:
try:
if tmp_path.exists():
tmp_path.unlink()
except OSError:
pass
def wav_to_mp3(wav_path: Path, mp3_path: Path) -> bool:
"""Convert WAV to MP3 using FFmpeg. Returns True on success."""
if not shutil.which("ffmpeg"):
return False
fd, tmp_name = tempfile.mkstemp(
prefix=f".{mp3_path.stem}.",
suffix=".mp3",
dir=str(mp3_path.parent),
)
os.close(fd)
tmp_path = Path(tmp_name)
try:
subprocess.run(
["ffmpeg", "-y", "-i", wav_path, "-codec:a", "libmp3lame",
"-b:a", "192k", "-ar", "24000", "-ac", "1", str(tmp_path)],
check=True, capture_output=True,
)
os.replace(tmp_path, mp3_path)
return True
except subprocess.CalledProcessError:
return False
finally:
try:
if tmp_path.exists():
tmp_path.unlink()
except OSError:
pass
def extract_audio_data(response) -> bytes:
"""Extract raw PCM audio bytes from Gemini TTS response.
The SDK returns inline_data.data as bytes (raw PCM), not base64."""
data = response.candidates[0].content.parts[0].inline_data.data
if isinstance(data, bytes):
return data
# Fallback: if it's a base64 string (older SDK versions)
return base64.b64decode(data)
def extract_interaction_wav_pcm(interaction) -> bytes:
"""Decode and validate unary WAV output from a Gemini 3.8 interaction."""
output_audio = getattr(interaction, "output_audio", None)
data = getattr(output_audio, "data", None)
if not data:
raise ValueError("Gemini TTS response did not include output_audio.data")
mime_type = getattr(output_audio, "mime_type", None)
if mime_type:
normalized_mime = str(mime_type).split(";", 1)[0].strip().lower()
if normalized_mime not in {"audio/wav", "audio/wave", "audio/x-wav"}:
raise ValueError(
f"Gemini TTS returned {mime_type}; expected unary audio/wav"
)
if isinstance(data, bytes) and data.startswith(b"RIFF"):
wav_data = data
else:
try:
encoded = data.encode("ascii") if isinstance(data, str) else data
wav_data = base64.b64decode(encoded, validate=True)
except (
AttributeError,
binascii.Error,
TypeError,
UnicodeEncodeError,
ValueError,
) as exc:
raise ValueError("Gemini TTS returned invalid base64 WAV audio data") from exc
if not wav_data.startswith(b"RIFF") or wav_data[8:12] != b"WAVE":
raise ValueError("Gemini TTS response was not a RIFF WAV file")
try:
with wave.open(io.BytesIO(wav_data), "rb") as wav_file:
channels = wav_file.getnchannels()
sample_rate = wav_file.getframerate()
sample_width = wav_file.getsampwidth()
compression = wav_file.getcomptype()
frame_count = wav_file.getnframes()
pcm_data = wav_file.readframes(frame_count)
except (EOFError, wave.Error) as exc:
raise ValueError(f"Gemini TTS returned an invalid WAV file: {exc}") from exc
if compression != "NONE":
raise ValueError("Gemini TTS WAV must use uncompressed PCM audio")
if channels != CHANNELS:
raise ValueError(
f"Gemini TTS WAV must be mono; received {channels} channels"
)
if sample_rate != SAMPLE_RATE:
raise ValueError(
f"Gemini TTS WAV must use a 24000 Hz sample rate; received {sample_rate}"
)
if sample_width != SAMPLE_WIDTH:
raise ValueError(
f"Gemini TTS WAV must use 16-bit samples; received {sample_width * 8}-bit"
)
if frame_count <= 0 or not pcm_data:
raise ValueError("Gemini TTS WAV contained no audio frames")
expected_size = frame_count * channels * sample_width
if len(pcm_data) != expected_size:
raise ValueError("Gemini TTS WAV audio data was truncated")
return pcm_data
def _create_38_single_speaker_input(text: str) -> list[dict]:
"""Build exact-text input without inventing style metadata."""
return [
{
"type": "user_input",
"content": [{"type": "text", "text": text}],
}
]
_DIALOGUE_LINE = re.compile(r"^(Speaker1|Speaker2):\s*(\S(?:.*\S)?)\s*$")
def _parse_38_dialogue(text: str) -> list[tuple[str, str]]:
"""Parse only explicit Speaker1 and Speaker2 lines without guessing turns."""
turns: list[tuple[str, str]] = []
for line_number, raw_line in enumerate(text.splitlines(), start=1):
line = raw_line.strip()
if not line:
continue
match = _DIALOGUE_LINE.fullmatch(line)
if not match:
raise ValueError(
"Gemini 3.8 dialogue requires every non-empty line to use "
f"Speaker1: or Speaker2: with text; invalid line {line_number}"
)
turns.append((match.group(1), match.group(2)))
if not turns:
raise ValueError(
"Gemini 3.8 dialogue requires Speaker1: and Speaker2: transcript lines"
)
return turns
def _create_38_multi_speaker_input(text: str) -> list[dict]:
"""Build structured speaker annotations from validated dialogue labels."""
content = []
for speaker, spoken_text in _parse_38_dialogue(text):
content.append(
{
"type": "text",
"text": spoken_text,
"annotations": [
{"type": "speech_metadata", "speaker": speaker}
],
}
)
return [{"type": "user_input", "content": content}]
def split_38_dialogue_for_tts(
text: str, max_tokens: int = CHUNK_TARGET_TOKENS
) -> list[str]:
"""Split validated dialogue between turns while preserving speaker labels."""
turns = _parse_38_dialogue(text)
if {speaker for speaker, _ in turns} != {"Speaker1", "Speaker2"}:
raise ValueError(
"Gemini 3.8 dialogue requires both Speaker1: and Speaker2: turns"
)
chunks: list[str] = []
current: list[str] = []
for speaker, spoken_text in turns:
line = f"{speaker}: {spoken_text}"
if estimate_input_tokens(line) > max_tokens:
raise ValueError(
"Gemini 3.8 dialogue turn exceeds the safe input limit; "
"split that labeled turn without changing its speaker"
)
candidate = "\n".join([*current, line])
if current and estimate_input_tokens(candidate) > max_tokens:
chunks.append("\n".join(current))
current = [line]
else:
current.append(line)
if current:
chunks.append("\n".join(current))
return chunks
def _generate_38_single_speaker(
client, text: str, voice: str, model: str
) -> bytes:
interactions = getattr(client, "interactions", None)
if interactions is None or not callable(getattr(interactions, "create", None)):
raise RuntimeError(
"Gemini 3.8 TTS requires google-genai with the Interactions API"
)
interaction = interactions.create(
model=MODELS[model],
input=_create_38_single_speaker_input(text),
response_format={"type": "audio"},
generation_config={"speech_config": [{"voice": voice}]},
)
return extract_interaction_wav_pcm(interaction)
def _generate_38_multi_speaker(
client, text: str, voice1: str, voice2: str, model: str
) -> bytes:
interactions = getattr(client, "interactions", None)
if interactions is None or not callable(getattr(interactions, "create", None)):
raise RuntimeError(
"Gemini 3.8 TTS requires google-genai with the Interactions API"
)
interaction = interactions.create(
model=MODELS[model],
input=_create_38_multi_speaker_input(text),
response_format={"type": "audio"},
generation_config={
"speech_config": {
"speakers": [
{"speaker": "Speaker1", "voice": voice1},
{"speaker": "Speaker2", "voice": voice2},
]
}
},
)
return extract_interaction_wav_pcm(interaction)
def generate_single_speaker(client, text: str, voice: str, model: str) -> bytes:
"""Generate single-speaker PCM through the API required by the alias."""
if model in INTERACTIONS_WAV_MODELS:
return _generate_38_single_speaker(client, text, voice, model)
from google.genai import types
response = client.models.generate_content(
model=MODELS[model],
contents=text,
config=types.GenerateContentConfig(
response_modalities=["AUDIO"],
speech_config=types.SpeechConfig(
voice_config=types.VoiceConfig(
prebuilt_voice_config=types.PrebuiltVoiceConfig(
voice_name=voice
)
)
),
),
)
return extract_audio_data(response)
def generate_multi_speaker(client, text: str, voice1: str, voice2: str, model: str) -> bytes:
"""Generate two-speaker PCM through the API required by the alias."""
if model in INTERACTIONS_WAV_MODELS:
return _generate_38_multi_speaker(client, text, voice1, voice2, model)
from google.genai import types
response = client.models.generate_content(
model=MODELS[model],
contents=text,
config=types.GenerateContentConfig(
response_modalities=["AUDIO"],
speech_config=types.SpeechConfig(
multi_speaker_voice_config=types.MultiSpeakerVoiceConfig(
speaker_voice_configs=[
types.SpeakerVoiceConfig(
speaker="Speaker1",
voice_config=types.VoiceConfig(
prebuilt_voice_config=types.PrebuiltVoiceConfig(
voice_name=voice1
)
),
),
types.SpeakerVoiceConfig(
speaker="Speaker2",
voice_config=types.VoiceConfig(
prebuilt_voice_config=types.PrebuiltVoiceConfig(
voice_name=voice2
)
),
),
]
)
),
),
)
return extract_audio_data(response)
def generate_audio_chunks(
client, text: str, voice1: str, voice2: str, model: str
) -> tuple[bytes, int]:
"""Generate one or more TTS chunks and stitch the raw PCM bytes."""
chunks = plan_chunks(text, voice2, model)
audio_parts = []
for chunk in chunks:
if estimate_input_tokens(chunk) > MAX_INPUT_TOKENS:
raise ValueError("Prepared text chunk exceeds the 8,192 token TTS input limit")
if voice2:
audio_parts.append(generate_multi_speaker(client, chunk, voice1, voice2, model))
else:
audio_parts.append(generate_single_speaker(client, chunk, voice1, model))
return b"".join(audio_parts), len(chunks)
def output_result(data: dict, as_json: bool):
"""Print result in JSON or human-readable format."""
if as_json:
print(json.dumps(data, indent=2))
else:
if data["status"] == "success":
print(f"\n{'=' * 50}")
print(f" Audio generated successfully!")
print(f"{'=' * 50}")
print(f" File: {data['path']}")
print(f" Format: {data['format']}")
print(f" Duration: {data['duration_human']}")
print(f" Voice: {data['voice']}")
print(f" Model: {data['model']}")
print(f" Cost: ~{data['cost_estimate']}")
print(f"\n Embed HTML:")
print(f" {data['embed_html']}")
print(f"{'=' * 50}\n")
elif data["status"] == "dry_run":
print(f"\n Dry run estimate:")
print(f" Duration: ~{data['duration_human_est']}")
print(f" Cost: ~{data['cost_estimate']}")
print(f" Model: {data['model']}")
print(f" Voice: {data['voice']}")
else:
print(f"\n Error: {data.get('error', 'Unknown error')}")
def main():
parser = argparse.ArgumentParser(description="Generate audio from text using Gemini TTS")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--text", help="Text to convert to speech")
group.add_argument("--text-file", help="Path to text file")
parser.add_argument("--voice", default="Charon", help="Primary voice (default: Charon)")
parser.add_argument("--voice2", help="Second voice for dialogue mode")
parser.add_argument(
"--model", choices=sorted(MODELS), default=DEFAULT_MODEL,
help=(
f"TTS model alias (default: {DEFAULT_MODEL}). flash, flash31, pro, legacy-flash25 and "
"legacy-pro25 are deprecated; Google lists their models for shutdown on 2026-11-17."
),
)
parser.add_argument(
"--max-chunks", type=int, default=DEFAULT_MAX_CHUNKS,
help=(
f"Refuse runs that need more than this many chunks (default: {DEFAULT_MAX_CHUNKS}). "
"Each chunk is one billed API call."
),
)
parser.add_argument("--output", help="Output file path (default: auto-generated)")
parser.add_argument("--json", action="store_true", help="Output structured JSON")
parser.add_argument("--dry-run", action="store_true", help="Estimate cost without generating")
args = parser.parse_args()
if args.max_chunks < 1:
parser.error("--max-chunks must be at least 1")
deprecation = deprecation_warning(args.model)
if deprecation:
print(deprecation, file=sys.stderr)
# Validate voice names
for voice_arg in [args.voice, args.voice2]:
if voice_arg and voice_arg not in VOICES:
result = {"status": "error", "error": f"Unknown voice: {voice_arg}. Valid voices: {', '.join(sorted(VOICES.keys()))}"}
output_result(result, args.json)
return 1
# Read text
if args.text_file:
try:
text = read_text_file(args.text_file).strip()
except (OSError, UnicodeDecodeError, ValueError) as e:
result = {"status": "error", "error": f"Text file rejected: {e}"}
output_result(result, args.json)
return 1
else:
text = args.text.strip()
if not text:
result = {"status": "error", "error": "Empty text provided"}
output_result(result, args.json)
return 1
try:
planned_chunks = plan_chunks(text, args.voice2, args.model)
except ValueError as e:
output_result({"status": "error", "error": str(e)}, args.json)
return 1
chunk_count_planned = len(planned_chunks)
# Dry run - estimate only
if args.dry_run:
est = estimate_cost(text, args.model)
result = {
"status": "dry_run",
"max_chunks": args.max_chunks,
"over_chunk_cap": chunk_count_planned > args.max_chunks,
"deprecation_warning": deprecation,
"model": args.model,
"voice": args.voice,
"voice2": args.voice2,
"text_length": len(text),
"word_count": len(text.split()),
"input_tokens_est": estimate_input_tokens(text),
**est,
}
output_result(result, args.json)
return 0
if chunk_count_planned > args.max_chunks:
result = {
"status": "error",
"error": (
f"Refusing to run: this text needs {chunk_count_planned} chunks, which is about "
f"{chunk_count_planned} billed API calls, above --max-chunks {args.max_chunks}. "
"Shorten the text, or raise --max-chunks after checking the estimated cost "
"with --dry-run."
),
"chunk_count_est": chunk_count_planned,
"max_chunks": args.max_chunks,
}
output_result(result, args.json)
return 1
# Check API key (environment only, never a CLI argument)
api_key = get_api_key()
if not api_key:
result = {"status": "error", "error": "No API key. Set GOOGLE_AI_API_KEY or GEMINI_API_KEY in the environment. Get one at https://aistudio.google.com/apikey"}
output_result(result, args.json)
return 1
# Generate audio
try:
from google import genai
client = genai.Client(api_key=api_key)
if not args.json:
print(f"Generating audio ({args.model} model, voice: {args.voice})...")
pcm_data, chunk_count = generate_audio_chunks(
client, text, args.voice, args.voice2, args.model
)
except Exception as e:
result = {"status": "error", "error": f"Gemini TTS API error: {redact_secrets(f'{type(e).__name__}: {e}', [api_key])}"}
output_result(result, args.json)
return 1
# Calculate duration
num_samples = len(pcm_data) // SAMPLE_WIDTH
duration_seconds = num_samples / SAMPLE_RATE
duration_min = int(duration_seconds // 60)
duration_sec = int(duration_seconds % 60)
duration_human = f"{duration_min}:{duration_sec:02d}"
try:
# Determine output path
if args.output:
output_path = resolve_output_path(args.output)
else:
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
output_path = resolve_output_path(f"audio_{ts}.mp3")
# Write WAV, then convert to MP3
wav_path = resolve_output_path(str(output_path.with_suffix(".wav")))
atomic_write_wav(pcm_data, wav_path)
final_format = "wav"
final_path = wav_path
if output_path.suffix.lower() in (".mp3", ""):
mp3_path = resolve_output_path(str(output_path.with_suffix(".mp3")))
if wav_to_mp3(wav_path, mp3_path):
wav_path.unlink() # Remove generated WAV after MP3 succeeds
final_path = mp3_path
final_format = "mp3"
else:
if not args.json:
print(" Warning: FFmpeg not found. Output is WAV (install ffmpeg for MP3).")
final_path = wav_path
final_format = "wav"
elif output_path.suffix.lower() == ".wav":
final_path = wav_path
final_format = "wav"
except (OSError, ValueError) as e:
result = {"status": "error", "error": f"Output path rejected: {e}"}
output_result(result, args.json)
return 1
# Build embed HTML
rel_path = html.escape(final_path.relative_to(Path.cwd().resolve()).as_posix(), quote=True)
mime = "audio/mpeg" if final_format == "mp3" else "audio/wav"
embed_html = (
f'<audio controls preload="metadata">'
f'<source src="{rel_path}" type="{mime}">'
f'Your browser does not support the audio element.</audio>'
)
# Cost estimate
est = estimate_cost(text, args.model)
result = {
"status": "success",
"path": str(Path(final_path).resolve()),
"format": final_format,
"duration_seconds": int(duration_seconds),
"duration_human": duration_human,
"voice": args.voice,
"voice2": args.voice2,
"model": args.model,
"model_id": MODELS[args.model],
"chunk_count": chunk_count,
"deprecation_warning": deprecation,
"embed_html": embed_html,
"cost_estimate": est["cost_estimate"],
"timestamp": datetime.now(timezone.utc).isoformat(),
}
output_result(result, args.json)
return 0
if __name__ == "__main__":
sys.exit(main())
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack." | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |