vocalize-cli 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
vocalize/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ """vocalize: a text-to-speech CLI built on the ElevenLabs API.
2
+
3
+ Converts plain text, markdown, or piped stdin into natural-sounding
4
+ speech, with a preprocessing pass that flattens markdown tables and
5
+ formatting into something that actually sounds good spoken aloud
6
+ (most TTS tools just read a table's raw cell text left to right,
7
+ which is close to useless).
8
+ """
9
+
10
+ __version__ = "0.1.1"
vocalize/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import run
2
+
3
+ if __name__ == "__main__":
4
+ run()
vocalize/audio.py ADDED
@@ -0,0 +1,71 @@
1
+ """Save audio to disk and play it through whatever the OS has on hand.
2
+
3
+ Deliberately avoids pulling in a heavy playback dependency (pydub /
4
+ simpleaudio / ffmpeg-python) — this just shells out to a system
5
+ player that's virtually always already installed, and fails with a
6
+ clear message if none is found.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import platform
12
+ import shutil
13
+ import subprocess
14
+ from pathlib import Path
15
+
16
+ from .exceptions import AudioPlaybackError, NoAudioPlayerError
17
+
18
+ _CANDIDATES = {
19
+ "Darwin": [["afplay"]],
20
+ "Linux": [["mpg123"], ["ffplay", "-nodisp", "-autoexit"], ["cvlc", "--play-and-exit"]],
21
+ }
22
+
23
+
24
+ def save(audio: bytes, path: Path) -> Path:
25
+ try:
26
+ path.parent.mkdir(parents=True, exist_ok=True)
27
+ path.write_bytes(audio)
28
+ except OSError as exc:
29
+ raise AudioPlaybackError(f"Could not save audio to {path}: {exc}") from exc
30
+ return path
31
+
32
+
33
+ def play(path: Path) -> None:
34
+ system = platform.system()
35
+
36
+ if system == "Windows":
37
+ # SoundPlayer only handles WAV, so mp3 playback on Windows likely
38
+ # fails cleanly rather than actually playing. Windows support is
39
+ # untested — treat it as a known limitation.
40
+ path_str = str(path).replace("'", "''")
41
+ cmd = [
42
+ "powershell",
43
+ "-c",
44
+ f"(New-Object Media.SoundPlayer '{path_str}').PlaySync();",
45
+ ]
46
+ try:
47
+ subprocess.run(cmd, check=True)
48
+ except (subprocess.CalledProcessError, OSError) as exc:
49
+ raise AudioPlaybackError(
50
+ f"powershell failed to play the audio: {exc}. "
51
+ f"The file is still saved at {path} — open it manually."
52
+ ) from exc
53
+ return
54
+
55
+ for candidate in _CANDIDATES.get(system, []):
56
+ exe = candidate[0]
57
+ if shutil.which(exe):
58
+ try:
59
+ subprocess.run([*candidate, str(path)], check=True)
60
+ except (subprocess.CalledProcessError, OSError) as exc:
61
+ raise AudioPlaybackError(
62
+ f"{exe} failed to play the audio: {exc}. "
63
+ f"The file is still saved at {path} — open it manually."
64
+ ) from exc
65
+ return
66
+
67
+ raise NoAudioPlayerError(
68
+ f"No supported audio player found for {system}. "
69
+ f"Install one of: {', '.join(c[0] for c in _CANDIDATES.get(system, []))} "
70
+ f"— or open the saved file manually: {path}"
71
+ )
vocalize/cli.py ADDED
@@ -0,0 +1,110 @@
1
+ """Command-line interface for vocalize.
2
+
3
+ vocalize speak "some text" --play
4
+ vocalize speak-file report.md --play
5
+ cat notes.md | vocalize speak-file - --play
6
+ vocalize voices
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ import click
15
+
16
+ from . import __version__
17
+ from .audio import play as play_audio
18
+ from .audio import save as save_audio
19
+ from .config import DEFAULT_MODEL, DEFAULT_VOICE, Settings, resolve_api_key
20
+ from .exceptions import TTSRequestError, VocalizeError
21
+ from .preprocess import flatten_markdown, truncate_for_budget
22
+ from .tts import DEFAULT_CACHE_DIR, build_client, list_voices, synthesize
23
+
24
+
25
+ def _common_options(f):
26
+ f = click.option("--api-key", default=None, help="ElevenLabs API key (overrides env/.env).")(f)
27
+ f = click.option("--voice", "voice_id", default=DEFAULT_VOICE, show_default=True, help="Voice ID to use.")(f)
28
+ f = click.option("--model", "model_id", default=DEFAULT_MODEL, show_default=True, help="ElevenLabs model ID.")(f)
29
+ f = click.option("-o", "--output", "output_path", type=click.Path(path_type=Path), default=None,
30
+ help="Save the generated audio to this path (default: "
31
+ "~/.cache/vocalize/last.mp3, overwritten each run).")(f)
32
+ f = click.option("--play/--no-play", default=True, help="Play the audio after generating it.")(f)
33
+ f = click.option("--raw", is_flag=True, help="Skip markdown flattening; speak the text verbatim.")(f)
34
+ f = click.option("--max-chars", type=int, default=None, help="Truncate input to this many characters first.")(f)
35
+ return f
36
+
37
+
38
+ @click.group()
39
+ @click.version_option(__version__, prog_name="vocalize")
40
+ def main() -> None:
41
+ """Turn text, markdown, or piped stdin into speech via ElevenLabs."""
42
+
43
+
44
+ def _run_tts(raw_text: str, *, api_key, voice_id, model_id, output_path, play, raw, max_chars) -> None:
45
+ text = raw_text if raw else flatten_markdown(raw_text)
46
+ text, truncated = truncate_for_budget(text, max_chars)
47
+ if truncated:
48
+ click.echo(f"Note: input truncated to {max_chars} characters.", err=True)
49
+
50
+ if not text.strip():
51
+ raise TTSRequestError("Nothing to speak: input text is empty.")
52
+
53
+ key = resolve_api_key(api_key)
54
+ client = build_client(key)
55
+ settings = Settings(voice_id=voice_id, model_id=model_id)
56
+
57
+ click.echo(f"Requesting {len(text)} characters of audio from ElevenLabs...", err=True)
58
+ audio = synthesize(client, text, settings)
59
+
60
+ dest = output_path or (DEFAULT_CACHE_DIR / "last.mp3")
61
+ save_audio(audio, dest)
62
+ click.echo(f"Saved audio to {dest}", err=True)
63
+
64
+ if play:
65
+ play_audio(dest)
66
+
67
+
68
+ @main.command()
69
+ @click.argument("text")
70
+ @_common_options
71
+ def speak(text, api_key, voice_id, model_id, output_path, play, raw, max_chars) -> None:
72
+ """Speak TEXT directly."""
73
+ _run_tts(text, api_key=api_key, voice_id=voice_id, model_id=model_id,
74
+ output_path=output_path, play=play, raw=raw, max_chars=max_chars)
75
+
76
+
77
+ @main.command("speak-file")
78
+ @click.argument("path", type=click.File("r", encoding="utf-8"))
79
+ @_common_options
80
+ def speak_file(path, api_key, voice_id, model_id, output_path, play, raw, max_chars) -> None:
81
+ """Speak the contents of PATH (a markdown/text file), or "-" for stdin."""
82
+ try:
83
+ raw_text = path.read()
84
+ except UnicodeDecodeError as exc:
85
+ raise click.FileError(getattr(path, "name", "input"), hint="file is not valid UTF-8 text") from exc
86
+ _run_tts(raw_text, api_key=api_key, voice_id=voice_id, model_id=model_id,
87
+ output_path=output_path, play=play, raw=raw, max_chars=max_chars)
88
+
89
+
90
+ @main.command()
91
+ @click.option("--api-key", default=None)
92
+ def voices(api_key) -> None:
93
+ """List available ElevenLabs voices and their IDs."""
94
+ key = resolve_api_key(api_key)
95
+ client = build_client(key)
96
+ for v in list_voices(client):
97
+ click.echo(f"{v['id']}\t{v['name']}")
98
+
99
+
100
+ def run() -> None:
101
+ """Entry point that turns our VocalizeError family into clean CLI errors."""
102
+ try:
103
+ main()
104
+ except VocalizeError as exc:
105
+ click.echo(f"Error: {exc}", err=True)
106
+ sys.exit(1)
107
+
108
+
109
+ if __name__ == "__main__":
110
+ run()
vocalize/config.py ADDED
@@ -0,0 +1,55 @@
1
+ """Configuration loading: API key resolution and defaults.
2
+
3
+ Resolution order (first one found wins):
4
+ 1. --api-key flag passed explicitly on the CLI
5
+ 2. ELEVENLABS_API_KEY environment variable
6
+ 3. A .env file in the current directory (loaded via python-dotenv,
7
+ if it's installed — this is an optional dependency)
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ from dataclasses import dataclass
14
+ from pathlib import Path
15
+
16
+ from .exceptions import MissingAPIKeyError
17
+
18
+ DEFAULT_VOICE = "21m00Tcm4TlvDq8ikWAM" # "Rachel" — a stock ElevenLabs voice
19
+ DEFAULT_MODEL = "eleven_multilingual_v2"
20
+ DEFAULT_OUTPUT_FORMAT = "mp3_44100_128"
21
+
22
+
23
+ def _load_dotenv_if_present() -> None:
24
+ try:
25
+ from dotenv import load_dotenv # type: ignore
26
+ except ImportError:
27
+ return
28
+ # Explicit path, not dotenv's default search: bare load_dotenv() walks
29
+ # up from the install directory, so a console-script install would miss
30
+ # the user's project .env and could pick up an unrelated one.
31
+ load_dotenv(dotenv_path=Path.cwd() / ".env")
32
+
33
+
34
+ def resolve_api_key(explicit: str | None = None) -> str:
35
+ """Find an API key from --api-key, the environment, or .env.
36
+
37
+ Raises MissingAPIKeyError if none is found.
38
+ """
39
+ if explicit:
40
+ return explicit
41
+
42
+ _load_dotenv_if_present()
43
+
44
+ key = os.environ.get("ELEVENLABS_API_KEY")
45
+ if key:
46
+ return key
47
+
48
+ raise MissingAPIKeyError()
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class Settings:
53
+ voice_id: str = DEFAULT_VOICE
54
+ model_id: str = DEFAULT_MODEL
55
+ output_format: str = DEFAULT_OUTPUT_FORMAT
vocalize/exceptions.py ADDED
@@ -0,0 +1,29 @@
1
+ """Custom exceptions for vocalize."""
2
+
3
+
4
+ class VocalizeError(Exception):
5
+ """Base class for all vocalize errors."""
6
+
7
+
8
+ class MissingAPIKeyError(VocalizeError):
9
+ """Raised when no ElevenLabs API key can be found."""
10
+
11
+ def __init__(self) -> None:
12
+ super().__init__(
13
+ "No ElevenLabs API key found. Set the ELEVENLABS_API_KEY "
14
+ "environment variable, add it to a .env file, or pass "
15
+ "--api-key on the command line. Get a free key at "
16
+ "https://elevenlabs.io/app/settings/api-keys"
17
+ )
18
+
19
+
20
+ class TTSRequestError(VocalizeError):
21
+ """Raised when the ElevenLabs API call itself fails."""
22
+
23
+
24
+ class NoAudioPlayerError(VocalizeError):
25
+ """Raised when no supported system audio player can be found."""
26
+
27
+
28
+ class AudioPlaybackError(VocalizeError):
29
+ """Raised when saving or playing audio fails at the OS/subprocess level."""
vocalize/preprocess.py ADDED
@@ -0,0 +1,195 @@
1
+ """Turn markdown into text that sounds sensible when spoken aloud.
2
+
3
+ Most TTS tools read a markdown table cell-by-cell, left to right,
4
+ which turns a table into a stream of disconnected numbers ("Q1. 4.2
5
+ million. Q2. 5.1 million...") with no sense of what row or column
6
+ you're in. This module rewrites tables, lists, headers, links, and
7
+ code as short declarative sentences before the text ever reaches the
8
+ TTS API — the same trick a person reading a table aloud to someone
9
+ else would use instinctively.
10
+
11
+ Everything here is pure text-in, text-out, so it's fully unit
12
+ testable without an API key or network access.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import re
18
+
19
+ # One dash per column is legal GitHub-flavored markdown ("| - | - |").
20
+ _TABLE_SEPARATOR_RE = re.compile(r"^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$")
21
+ _HEADING_RE = re.compile(r"^(#{1,6})\s+(.*)")
22
+ _BULLET_RE = re.compile(r"^\s*[-*+]\s+(.*)")
23
+ _NUMBERED_RE = re.compile(r"^\s*(\d+)[.)]\s+(.*)")
24
+ _FENCE_RE = re.compile(r"^\s*```")
25
+ _LINK_RE = re.compile(r"\[([^\]]+)\]\(([^)]+)\)")
26
+ _IMAGE_RE = re.compile(r"!\[([^\]]*)\]\(([^)]+)\)")
27
+ _BOLD_ITALIC_RE = re.compile(r"(\*\*\*|___)(.+?)\1")
28
+ _BOLD_RE = re.compile(r"(\*\*|__)(.+?)\1")
29
+ _ITALIC_RE = re.compile(r"(\*|_)(.+?)\1")
30
+ _INLINE_CODE_RE = re.compile(r"`([^`]+)`")
31
+
32
+ # Real Claude Code responses are mostly code blocks. Announcing both ends of
33
+ # every one of them filled the whole spoken budget with bookkeeping, so it's
34
+ # one short mention per block, and consecutive blocks share a single mention.
35
+ _CODE_PLACEHOLDER = "Skipping a code block."
36
+
37
+
38
+ def _split_table_row(line: str) -> list[str]:
39
+ row = line.strip()
40
+ row = row.removeprefix("|")
41
+ row = row.removesuffix("|")
42
+ return [cell.strip() for cell in row.split("|")]
43
+
44
+
45
+ def _is_table_start(lines: list[str], i: int) -> bool:
46
+ if i + 1 >= len(lines):
47
+ return False
48
+ header, sep = lines[i], lines[i + 1]
49
+ if "|" not in header or not _TABLE_SEPARATOR_RE.match(sep):
50
+ return False
51
+ # Prose containing a stray "|" above a horizontal rule looks like a
52
+ # header + separator pair, so insist the column counts line up too.
53
+ return len(_split_table_row(header)) == len(_split_table_row(sep))
54
+
55
+
56
+ def _flatten_table(lines: list[str], start: int) -> tuple[str, int]:
57
+ """Convert a markdown table starting at `start` into spoken prose.
58
+
59
+ Returns (spoken_text, index_of_first_line_after_table).
60
+ """
61
+ headers = _split_table_row(lines[start])
62
+ i = start + 2 # skip header + separator row
63
+ rows: list[list[str]] = []
64
+ while i < len(lines) and "|" in lines[i] and lines[i].strip():
65
+ rows.append(_split_table_row(lines[i]))
66
+ i += 1
67
+
68
+ if not rows:
69
+ return "", i
70
+
71
+ noun = "row" if len(rows) == 1 else "rows"
72
+ sentences = [f"Table with {len(rows)} {noun}."]
73
+ for row in rows:
74
+ label = row[0] if row else ""
75
+ parts = []
76
+ # Walk by index, not dict(zip(...)): ragged rows and repeated
77
+ # header names would otherwise lose cells without a word.
78
+ for idx, value in enumerate(row):
79
+ if idx == 0:
80
+ continue # already spoken as the row's label
81
+ if not value:
82
+ continue
83
+ header = headers[idx] if idx < len(headers) else f"column {idx + 1}"
84
+ parts.append(f"{header} is {value}")
85
+ if parts:
86
+ sentences.append(f"For {label}: " + "; ".join(parts) + ".")
87
+ else:
88
+ sentences.append(f"{label}.")
89
+
90
+ return " ".join(sentences), i
91
+
92
+
93
+ def _strip_inline_markdown(text: str) -> str:
94
+ text = _IMAGE_RE.sub(lambda m: m.group(1) or "image", text)
95
+ text = _LINK_RE.sub(lambda m: m.group(1), text)
96
+ text = _BOLD_ITALIC_RE.sub(lambda m: m.group(2), text)
97
+ text = _BOLD_RE.sub(lambda m: m.group(2), text)
98
+ text = _ITALIC_RE.sub(lambda m: m.group(2), text)
99
+ text = _INLINE_CODE_RE.sub(lambda m: m.group(1), text)
100
+ return text
101
+
102
+
103
+ def flatten_markdown(text: str) -> str:
104
+ """Rewrite markdown as plain, speakable prose.
105
+
106
+ - Tables become short "for X, Y is Z" sentences per row.
107
+ - Headings become their own sentence (so there's a natural pause).
108
+ - Bullet/numbered lists become "First, ... Next, ... Finally, ...".
109
+ - Fenced code blocks become one short spoken placeholder each, and
110
+ back-to-back blocks collapse into a single mention — reading code
111
+ character-by-character out loud helps no one, and neither does
112
+ announcing six code blocks in a row.
113
+ - Links, images, bold/italic markers, and inline code ticks are
114
+ stripped down to their readable text.
115
+ """
116
+ lines = text.splitlines()
117
+ out: list[str] = []
118
+ in_code_block = False
119
+ list_ordinal = 0
120
+ ordinals = [
121
+ "First", "Second", "Third", "Fourth", "Fifth",
122
+ "Sixth", "Seventh", "Eighth", "Ninth", "Tenth",
123
+ ]
124
+
125
+ i = 0
126
+ while i < len(lines):
127
+ line = lines[i]
128
+
129
+ if _FENCE_RE.match(line):
130
+ in_code_block = not in_code_block
131
+ if in_code_block:
132
+ last = next((s for s in reversed(out) if s), None)
133
+ if last != _CODE_PLACEHOLDER:
134
+ out.append(_CODE_PLACEHOLDER)
135
+ i += 1
136
+ continue
137
+
138
+ if in_code_block:
139
+ # Skip the raw code itself — it isn't worth speaking.
140
+ i += 1
141
+ continue
142
+
143
+ if not line.strip():
144
+ list_ordinal = 0
145
+ i += 1
146
+ continue
147
+
148
+ if _is_table_start(lines, i):
149
+ spoken, i = _flatten_table(lines, i)
150
+ out.append(spoken)
151
+ continue
152
+
153
+ heading_match = _HEADING_RE.match(line)
154
+ if heading_match:
155
+ out.append(_strip_inline_markdown(heading_match.group(2)).strip() + ".")
156
+ list_ordinal = 0
157
+ i += 1
158
+ continue
159
+
160
+ bullet_match = _BULLET_RE.match(line)
161
+ if bullet_match:
162
+ word = ordinals[list_ordinal] if list_ordinal < len(ordinals) else "Next"
163
+ out.append(f"{word}, {_strip_inline_markdown(bullet_match.group(1)).strip()}.")
164
+ list_ordinal += 1
165
+ i += 1
166
+ continue
167
+
168
+ numbered_match = _NUMBERED_RE.match(line)
169
+ if numbered_match:
170
+ out.append(
171
+ f"Item {numbered_match.group(1)}: "
172
+ f"{_strip_inline_markdown(numbered_match.group(2)).strip()}."
173
+ )
174
+ i += 1
175
+ continue
176
+
177
+ out.append(_strip_inline_markdown(line).strip())
178
+ list_ordinal = 0
179
+ i += 1
180
+
181
+ spoken = " ".join(s for s in out if s)
182
+ spoken = re.sub(r"\s+", " ", spoken).strip()
183
+ return spoken
184
+
185
+
186
+ def truncate_for_budget(text: str, max_chars: int | None) -> tuple[str, bool]:
187
+ """Truncate to max_chars, returning (text, was_truncated).
188
+
189
+ Useful for keeping a free-tier ElevenLabs quota from being blown
190
+ through by one long document.
191
+ """
192
+ if max_chars is None or len(text) <= max_chars:
193
+ return text, False
194
+ cut = text[:max_chars].rsplit(" ", 1)[0]
195
+ return cut + "... (truncated)", True
vocalize/tts.py ADDED
@@ -0,0 +1,107 @@
1
+ """Thin wrapper around the ElevenLabs text-to-speech API.
2
+
3
+ Kept deliberately small and dependency-injected (the client is passed
4
+ in) so it's easy to unit test with a fake/mock client — no network
5
+ access or real API key needed to test the logic in this file.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ from pathlib import Path
12
+
13
+ from .config import Settings
14
+ from .exceptions import TTSRequestError
15
+
16
+ DEFAULT_CACHE_DIR = Path.home() / ".cache" / "vocalize"
17
+
18
+ # The SDK's own default is 240s, far beyond the Stop hook's 60s subprocess
19
+ # timeout — a hung request would otherwise outlive the hook that spawned it.
20
+ REQUEST_TIMEOUT_SECONDS = 30
21
+
22
+
23
+ def _cache_key(text: str, settings: Settings) -> str:
24
+ payload = f"{settings.voice_id}|{settings.model_id}|{settings.output_format}|{text}"
25
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()
26
+
27
+
28
+ def synthesize(
29
+ client,
30
+ text: str,
31
+ settings: Settings,
32
+ *,
33
+ cache_dir: Path | None = DEFAULT_CACHE_DIR,
34
+ ) -> bytes:
35
+ """Convert `text` to audio bytes via the ElevenLabs client.
36
+
37
+ `client` is expected to expose `.text_to_speech.convert(...)`
38
+ returning an iterable of bytes chunks (this matches the official
39
+ `elevenlabs` SDK's ElevenLabs client) — but any object with that
40
+ shape works, which is what makes this testable with a stub.
41
+
42
+ Results are cached on disk by a hash of (text, voice, model,
43
+ format), so re-running the same request — e.g. re-reading the
44
+ same document twice — doesn't burn API quota twice.
45
+ """
46
+ if not text.strip():
47
+ raise TTSRequestError("Nothing to speak: input text is empty.")
48
+
49
+ cache_path = None
50
+ if cache_dir is not None:
51
+ cache_path = cache_dir / f"{_cache_key(text, settings)}.mp3"
52
+ # The cache is an optimization, never a failure source: an
53
+ # unreadable entry is just a miss.
54
+ try:
55
+ if cache_path.exists():
56
+ return cache_path.read_bytes()
57
+ except OSError:
58
+ pass
59
+
60
+ try:
61
+ chunks = client.text_to_speech.convert(
62
+ text=text,
63
+ voice_id=settings.voice_id,
64
+ model_id=settings.model_id,
65
+ output_format=settings.output_format,
66
+ )
67
+ audio = b"".join(chunks) if not isinstance(chunks, (bytes, bytearray)) else bytes(chunks)
68
+ except Exception as exc:
69
+ raise TTSRequestError(f"ElevenLabs API request failed: {exc}") from exc
70
+
71
+ if not audio:
72
+ raise TTSRequestError("ElevenLabs API returned no audio data.")
73
+
74
+ if cache_path is not None:
75
+ # Never discard a paid API response because the cache dir is
76
+ # read-only — the caller's save path does the real persistence.
77
+ try:
78
+ cache_path.parent.mkdir(parents=True, exist_ok=True)
79
+ cache_path.write_bytes(audio)
80
+ except OSError:
81
+ pass
82
+
83
+ return audio
84
+
85
+
86
+ def list_voices(client) -> list[dict]:
87
+ """Return a simplified [{"id": ..., "name": ...}, ...] list of voices."""
88
+ try:
89
+ response = client.voices.search()
90
+ except Exception as exc:
91
+ raise TTSRequestError(f"Could not list voices: {exc}") from exc
92
+
93
+ voices = getattr(response, "voices", response)
94
+ return [
95
+ {"id": getattr(v, "voice_id", getattr(v, "id", None)), "name": getattr(v, "name", "?")}
96
+ for v in voices
97
+ ]
98
+
99
+
100
+ def build_client(api_key: str):
101
+ """Construct the real ElevenLabs SDK client. Imported lazily so the
102
+ rest of the package (and its tests) don't require the `elevenlabs`
103
+ package to be installed just to run unit tests against pure logic.
104
+ """
105
+ from elevenlabs.client import ElevenLabs
106
+
107
+ return ElevenLabs(api_key=api_key, timeout=REQUEST_TIMEOUT_SECONDS)
@@ -0,0 +1,249 @@
1
+ Metadata-Version: 2.5
2
+ Name: vocalize-cli
3
+ Version: 0.1.1
4
+ Summary: A CLI that turns text, markdown, or piped stdin into speech via the ElevenLabs API, with markdown-table-aware preprocessing.
5
+ Project-URL: Homepage, https://github.com/matthager12-collab/vocalize
6
+ Project-URL: Repository, https://github.com/matthager12-collab/vocalize
7
+ Author: Mat
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: claude-code,cli,elevenlabs,markdown,text-to-speech
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
20
+ Requires-Python: >=3.10
21
+ Requires-Dist: click>=8.1
22
+ Requires-Dist: elevenlabs>=2.0
23
+ Provides-Extra: dev
24
+ Requires-Dist: build; extra == 'dev'
25
+ Requires-Dist: pytest-cov>=4.0; extra == 'dev'
26
+ Requires-Dist: pytest>=7.0; extra == 'dev'
27
+ Requires-Dist: ruff; extra == 'dev'
28
+ Requires-Dist: twine; extra == 'dev'
29
+ Provides-Extra: dotenv
30
+ Requires-Dist: python-dotenv>=1.0; extra == 'dotenv'
31
+ Description-Content-Type: text/markdown
32
+
33
+ # vocalize
34
+
35
+ [![CI](https://github.com/matthager12-collab/vocalize/actions/workflows/ci.yml/badge.svg)](https://github.com/matthager12-collab/vocalize/actions/workflows/ci.yml)
36
+
37
+ A command-line tool that turns text, markdown files, or piped stdin into
38
+ natural-sounding speech using the [ElevenLabs](https://elevenlabs.io) API —
39
+ plus a hook that wires it directly into [Claude Code](https://claude.com/claude-code),
40
+ so Claude's responses get read aloud automatically in your terminal or IDE.
41
+
42
+ ## Why this exists
43
+
44
+ Text-to-speech readers are good at *voices* and bad at *structure*. Point one
45
+ at a markdown report and it reads a table cell-by-cell, left to right, with
46
+ no sense of which row or column you're in — "Q1. 4.2 million. Q2. 5.1
47
+ million" instead of "for Q1, revenue is 4.2 million." Headings, bullet
48
+ lists, and inline code fare the same way: read exactly as typed, syntax and
49
+ all.
50
+
51
+ `vocalize` fixes the part of that problem that's actually fixable without a
52
+ vision model: a preprocessing pass (`vocalize/preprocess.py`) rewrites
53
+ markdown into short, declarative sentences *before* it ever reaches the TTS
54
+ API — tables become "for X, Y is Z" sentences, bullets become "First, ...
55
+ Second, ...", links keep their text and drop the URL, and fenced code blocks
56
+ are replaced with a spoken placeholder instead of being read character by
57
+ character. It's a text transform, so it's fully unit tested without any
58
+ API key or network access (see `tests/test_preprocess.py`).
59
+
60
+ ## Install
61
+
62
+ ```bash
63
+ pipx install vocalize-cli
64
+ ```
65
+
66
+ (or `uvx --from vocalize-cli vocalize` for a one-off run without installing
67
+ anything). The package is published on PyPI as `vocalize-cli`; the command
68
+ it installs is still `vocalize`.
69
+
70
+ For a from-source or dev install:
71
+
72
+ ```bash
73
+ git clone <this-repo>
74
+ cd vocalize
75
+ pip install -e .
76
+ ```
77
+
78
+ Get a free ElevenLabs API key at
79
+ [elevenlabs.io/app/settings/api-keys](https://elevenlabs.io/app/settings/api-keys)
80
+ (free tier: 10,000 characters/month, API access included, no commercial
81
+ license). Then either:
82
+
83
+ ```bash
84
+ export ELEVENLABS_API_KEY=your-key-here
85
+ ```
86
+
87
+ or copy `.env.example` to `.env` and fill it in (requires the optional
88
+ `python-dotenv` extra: `pip install -e ".[dotenv]"`).
89
+
90
+ ## Usage
91
+
92
+ ```bash
93
+ # Speak a string directly
94
+ vocalize speak "Hello, this is a test."
95
+
96
+ # Speak a markdown file — tables and formatting get flattened first
97
+ vocalize speak-file report.md
98
+
99
+ # Pipe anything in
100
+ cat notes.md | vocalize speak-file -
101
+
102
+ # List available voices and grab an ID
103
+ vocalize voices
104
+
105
+ # Use a specific voice/model, save without playing
106
+ vocalize speak-file report.md --voice <voice-id> --model eleven_flash_v2_5 \
107
+ --output out.mp3 --no-play
108
+
109
+ # Cap how much gets sent (handy for free-tier character budgets)
110
+ vocalize speak-file long-report.md --max-chars 2000
111
+
112
+ # Skip the markdown flattening entirely
113
+ vocalize speak "raw **markdown** stays raw" --raw
114
+ ```
115
+
116
+ Every synthesis result is cached on disk under `~/.cache/vocalize/`, keyed
117
+ by a hash of (text, voice, model, format) — re-running the same command
118
+ twice doesn't burn API quota twice.
119
+
120
+ ## Claude Code integration
121
+
122
+ The hook scripts ship in the git repository, not the PyPI package — clone
123
+ the repo to install the hook (it shells out to the `vocalize` command, so a
124
+ pipx-installed CLI plus a cloned repo works fine together).
125
+
126
+ `hooks/claude_stop_hook.py` is a [Claude Code Stop
127
+ hook](https://docs.claude.com/en/docs/claude-code/hooks): a script Claude
128
+ Code runs every time it finishes a response. This one reads the transcript,
129
+ pulls out Claude's last message, and pipes it through the same `vocalize`
130
+ CLI — so it works identically whether Claude Code is running in a bare
131
+ terminal or inside an IDE's integrated terminal (VS Code, Cursor, etc.),
132
+ since both use the same `~/.claude/settings.json` hook config.
133
+
134
+ **On-demand mode.** If you'd rather trigger speech yourself than have every
135
+ response spoken, skip the install and run the script with `--latest`. It
136
+ finds your most recent Claude Code response — in any session — and speaks
137
+ that one:
138
+
139
+ ```bash
140
+ python3 hooks/claude_stop_hook.py --latest
141
+ ```
142
+
143
+ Combine it with `VOCALIZE_MAX_CHARS` to control how much gets read.
144
+
145
+ To install it as an automatic hook instead:
146
+
147
+ ```bash
148
+ python3 hooks/install_hook.py
149
+ ```
150
+
151
+ This merges a `Stop` hook entry into `~/.claude/settings.json` (backing up
152
+ the existing file first) rather than overwriting your other hooks. Every
153
+ Claude Code response after that gets spoken aloud automatically. Uninstall
154
+ by removing the `vocalize` entry from the `Stop` array in that file.
155
+
156
+ By default the hook truncates each response to 500 characters before
157
+ speaking it (`DEFAULT_MAX_CHARS` in `claude_stop_hook.py`) — a Stop hook
158
+ fires after every turn, so a long response would burn through the
159
+ ElevenLabs free-tier quota fast. Override with `VOCALIZE_MAX_CHARS` in the
160
+ environment.
161
+
162
+ The hook looks up the `vocalize` binary on `PATH`, but Claude Code hooks
163
+ run in Claude Code's own environment, not your interactive shell — if
164
+ `vocalize` was installed into a virtualenv that isn't on that `PATH`, set
165
+ `VOCALIZE_BIN` to the full path (e.g. `/path/to/.venv/bin/vocalize`) to
166
+ point the hook at it directly.
167
+
168
+ ## How it's built
169
+
170
+ Four decisions shaped the design:
171
+
172
+ - **The markdown flattener is a pure function.** The hardest logic in the
173
+ project — deciding what a table, list, or code block should *sound* like —
174
+ takes a string and returns a string. No I/O, no client, no key. That's why
175
+ it has the deepest test coverage in the repo, including the edge cases
176
+ that bit during review: prose containing a stray `|`, single-dash GFM
177
+ separators, ragged rows, duplicate column names.
178
+ - **One code path for humans and hooks.** The Claude Code hook doesn't
179
+ reimplement synthesis; it shells out to the same `vocalize` CLI you'd
180
+ type by hand (with an `--` argv guard so a response starting with a
181
+ bullet isn't parsed as a flag). Anything the hook can do, you can
182
+ reproduce and debug from your own terminal.
183
+ - **The hook may fail; the session may not.** Every failure path in the
184
+ Stop hook logs one line to stderr and exits 0. A dead API key or a hung
185
+ request costs you the audio, never the coding session.
186
+ - **The cache is an optimization, never a failure source.** Synthesis
187
+ results are content-addressed on disk; an unreadable or unwritable cache
188
+ degrades to a fresh API call instead of an error.
189
+
190
+ ## Architecture
191
+
192
+ ```
193
+ vocalize/
194
+ __init__.py # package version
195
+ __main__.py # python -m vocalize entry point
196
+ preprocess.py # markdown -> speakable text (pure function, fully unit tested)
197
+ config.py # API key resolution: --api-key > $ELEVENLABS_API_KEY > .env
198
+ exceptions.py # VocalizeError / TTSRequestError
199
+ tts.py # ElevenLabs API wrapper + disk cache (client is injected, so
200
+ # it's mockable in tests without hitting the network)
201
+ audio.py # save to disk + play via the OS's native player
202
+ # (afplay / mpg123 / ffplay / PowerShell, whichever exists)
203
+ cli.py # click-based CLI wiring the above together
204
+ hooks/
205
+ claude_stop_hook.py # Claude Code Stop hook -> calls the vocalize CLI
206
+ install_hook.py # safely merges the hook into ~/.claude/settings.json
207
+ tests/ # pytest, all mocked — no API key needed to run these
208
+ ```
209
+
210
+ ## Testing
211
+
212
+ ```bash
213
+ pip install -e ".[dev]"
214
+ pytest
215
+ ```
216
+
217
+ All tests run offline: the ElevenLabs client is dependency-injected into
218
+ `tts.py`, so tests pass in a fake client instead of hitting the real API.
219
+
220
+ ## Known limitations
221
+
222
+ - **Charts and images aren't described.** Flattening markdown tables is a
223
+ text problem; a rendered chart is an image, and describing it well needs
224
+ a vision model in the loop, not a text transform. Out of scope for this
225
+ project, but a natural next step — pipe the image through a
226
+ vision-capable model first, feed its description into `vocalize` in
227
+ place of the chart.
228
+ - **Free tier is 10,000 characters/month** — plenty for reading a handful
229
+ of documents aloud, not for continuous use. `--max-chars` and the disk
230
+ cache both help stretch it.
231
+ - Table flattening handles standard GFM pipe tables; it doesn't attempt to
232
+ handle merged cells or nested tables (rare enough in practice that it
233
+ wasn't worth the complexity).
234
+ - **Windows playback is untested.** The PowerShell `SoundPlayer` fallback
235
+ only plays WAV, so the mp3 files this tool generates likely won't play
236
+ there. Use `--no-play` and open the saved file with whatever's on hand.
237
+ - **The disk cache under `~/.cache/vocalize` grows unbounded.** It's
238
+ content-addressed (keyed by a hash of text, voice, model, and format),
239
+ so it's always safe to delete some or all of it — nothing will break,
240
+ you'll just re-pay for a re-synthesized clip.
241
+ - **`--api-key` on the command line is visible to other local processes**
242
+ (anything that can run `ps`). Prefer the `ELEVENLABS_API_KEY` environment
243
+ variable or a `.env` file instead.
244
+ - `vocalize voices` lists only the first page of results from the
245
+ ElevenLabs API.
246
+
247
+ ## License
248
+
249
+ MIT
@@ -0,0 +1,13 @@
1
+ vocalize/__init__.py,sha256=Jg8z92RR2rJb5Ynq8DENuI56B5kLviRc1qqaXdKSYx4,385
2
+ vocalize/__main__.py,sha256=3U77Eu21mJ-LY27RG-JEnpbh6Z63wGOom4i-EoLtUcY,59
3
+ vocalize/audio.py,sha256=69ZICXC39HK_YThQ4pOF9BB2UU55PSFqPjMUsLLYefI,2435
4
+ vocalize/cli.py,sha256=FXF6IHPWyKDK9HjubSd62JYW4_UCpb7mXVGbubp6TjU,4156
5
+ vocalize/config.py,sha256=nroeTvy4_YX6fLLrpGC-lFJHTKp9xlWb02dSwOxXmzQ,1570
6
+ vocalize/exceptions.py,sha256=RlWiLUfFjAOXGvqNgxYxTWRSHmsOk5WP225XBCU0rrA,884
7
+ vocalize/preprocess.py,sha256=dc7_lsHYg8GD-r96UiVt8xn5JkOGAgCTovSDEQq86UU,7028
8
+ vocalize/tts.py,sha256=VB5-F4HSar2FLIPQEMMIfn0VdOq-BR3VqwlVzMlkM8k,3706
9
+ vocalize_cli-0.1.1.dist-info/METADATA,sha256=BJ6zwQ9ZZhD0ckk97b70YFKMLWoZogTfcO7hxiQZzJ0,10335
10
+ vocalize_cli-0.1.1.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
11
+ vocalize_cli-0.1.1.dist-info/entry_points.txt,sha256=YGjS-M7KnLEoUE-77AbtU1QiVYa4qksmBJL1MRBDZA0,46
12
+ vocalize_cli-0.1.1.dist-info/licenses/LICENSE,sha256=yCYTCxMZWkE-ARTs1NnfsD06fDpU7uDLUMgscQj3oI8,1060
13
+ vocalize_cli-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ vocalize = vocalize.cli:run
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mat
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.