vocalize-cli 0.1.1__tar.gz

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.
@@ -0,0 +1,3 @@
1
+ # Copy this file to .env and fill in your key.
2
+ # Get a free key at https://elevenlabs.io/app/settings/api-keys
3
+ ELEVENLABS_API_KEY=your-api-key-here
@@ -0,0 +1,20 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ pull_request:
6
+
7
+ jobs:
8
+ test:
9
+ runs-on: ubuntu-latest
10
+ strategy:
11
+ matrix:
12
+ python-version: ["3.10", "3.12", "3.14"]
13
+ steps:
14
+ - uses: actions/checkout@v5
15
+ - uses: actions/setup-python@v6
16
+ with:
17
+ python-version: ${{ matrix.python-version }}
18
+ - run: pip install -e ".[dev,dotenv]"
19
+ - run: ruff check .
20
+ - run: pytest -v --cov=vocalize --cov=hooks --cov-report=term-missing
@@ -0,0 +1,13 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .pytest_cache/
4
+ .coverage
5
+ htmlcov/
6
+ .env
7
+ *.egg-info/
8
+ build/
9
+ dist/
10
+ .venv/
11
+ venv/
12
+ *.mp3
13
+ *.wav
@@ -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.
@@ -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,217 @@
1
+ # vocalize
2
+
3
+ [![CI](https://github.com/matthager12-collab/vocalize/actions/workflows/ci.yml/badge.svg)](https://github.com/matthager12-collab/vocalize/actions/workflows/ci.yml)
4
+
5
+ A command-line tool that turns text, markdown files, or piped stdin into
6
+ natural-sounding speech using the [ElevenLabs](https://elevenlabs.io) API —
7
+ plus a hook that wires it directly into [Claude Code](https://claude.com/claude-code),
8
+ so Claude's responses get read aloud automatically in your terminal or IDE.
9
+
10
+ ## Why this exists
11
+
12
+ Text-to-speech readers are good at *voices* and bad at *structure*. Point one
13
+ at a markdown report and it reads a table cell-by-cell, left to right, with
14
+ no sense of which row or column you're in — "Q1. 4.2 million. Q2. 5.1
15
+ million" instead of "for Q1, revenue is 4.2 million." Headings, bullet
16
+ lists, and inline code fare the same way: read exactly as typed, syntax and
17
+ all.
18
+
19
+ `vocalize` fixes the part of that problem that's actually fixable without a
20
+ vision model: a preprocessing pass (`vocalize/preprocess.py`) rewrites
21
+ markdown into short, declarative sentences *before* it ever reaches the TTS
22
+ API — tables become "for X, Y is Z" sentences, bullets become "First, ...
23
+ Second, ...", links keep their text and drop the URL, and fenced code blocks
24
+ are replaced with a spoken placeholder instead of being read character by
25
+ character. It's a text transform, so it's fully unit tested without any
26
+ API key or network access (see `tests/test_preprocess.py`).
27
+
28
+ ## Install
29
+
30
+ ```bash
31
+ pipx install vocalize-cli
32
+ ```
33
+
34
+ (or `uvx --from vocalize-cli vocalize` for a one-off run without installing
35
+ anything). The package is published on PyPI as `vocalize-cli`; the command
36
+ it installs is still `vocalize`.
37
+
38
+ For a from-source or dev install:
39
+
40
+ ```bash
41
+ git clone <this-repo>
42
+ cd vocalize
43
+ pip install -e .
44
+ ```
45
+
46
+ Get a free ElevenLabs API key at
47
+ [elevenlabs.io/app/settings/api-keys](https://elevenlabs.io/app/settings/api-keys)
48
+ (free tier: 10,000 characters/month, API access included, no commercial
49
+ license). Then either:
50
+
51
+ ```bash
52
+ export ELEVENLABS_API_KEY=your-key-here
53
+ ```
54
+
55
+ or copy `.env.example` to `.env` and fill it in (requires the optional
56
+ `python-dotenv` extra: `pip install -e ".[dotenv]"`).
57
+
58
+ ## Usage
59
+
60
+ ```bash
61
+ # Speak a string directly
62
+ vocalize speak "Hello, this is a test."
63
+
64
+ # Speak a markdown file — tables and formatting get flattened first
65
+ vocalize speak-file report.md
66
+
67
+ # Pipe anything in
68
+ cat notes.md | vocalize speak-file -
69
+
70
+ # List available voices and grab an ID
71
+ vocalize voices
72
+
73
+ # Use a specific voice/model, save without playing
74
+ vocalize speak-file report.md --voice <voice-id> --model eleven_flash_v2_5 \
75
+ --output out.mp3 --no-play
76
+
77
+ # Cap how much gets sent (handy for free-tier character budgets)
78
+ vocalize speak-file long-report.md --max-chars 2000
79
+
80
+ # Skip the markdown flattening entirely
81
+ vocalize speak "raw **markdown** stays raw" --raw
82
+ ```
83
+
84
+ Every synthesis result is cached on disk under `~/.cache/vocalize/`, keyed
85
+ by a hash of (text, voice, model, format) — re-running the same command
86
+ twice doesn't burn API quota twice.
87
+
88
+ ## Claude Code integration
89
+
90
+ The hook scripts ship in the git repository, not the PyPI package — clone
91
+ the repo to install the hook (it shells out to the `vocalize` command, so a
92
+ pipx-installed CLI plus a cloned repo works fine together).
93
+
94
+ `hooks/claude_stop_hook.py` is a [Claude Code Stop
95
+ hook](https://docs.claude.com/en/docs/claude-code/hooks): a script Claude
96
+ Code runs every time it finishes a response. This one reads the transcript,
97
+ pulls out Claude's last message, and pipes it through the same `vocalize`
98
+ CLI — so it works identically whether Claude Code is running in a bare
99
+ terminal or inside an IDE's integrated terminal (VS Code, Cursor, etc.),
100
+ since both use the same `~/.claude/settings.json` hook config.
101
+
102
+ **On-demand mode.** If you'd rather trigger speech yourself than have every
103
+ response spoken, skip the install and run the script with `--latest`. It
104
+ finds your most recent Claude Code response — in any session — and speaks
105
+ that one:
106
+
107
+ ```bash
108
+ python3 hooks/claude_stop_hook.py --latest
109
+ ```
110
+
111
+ Combine it with `VOCALIZE_MAX_CHARS` to control how much gets read.
112
+
113
+ To install it as an automatic hook instead:
114
+
115
+ ```bash
116
+ python3 hooks/install_hook.py
117
+ ```
118
+
119
+ This merges a `Stop` hook entry into `~/.claude/settings.json` (backing up
120
+ the existing file first) rather than overwriting your other hooks. Every
121
+ Claude Code response after that gets spoken aloud automatically. Uninstall
122
+ by removing the `vocalize` entry from the `Stop` array in that file.
123
+
124
+ By default the hook truncates each response to 500 characters before
125
+ speaking it (`DEFAULT_MAX_CHARS` in `claude_stop_hook.py`) — a Stop hook
126
+ fires after every turn, so a long response would burn through the
127
+ ElevenLabs free-tier quota fast. Override with `VOCALIZE_MAX_CHARS` in the
128
+ environment.
129
+
130
+ The hook looks up the `vocalize` binary on `PATH`, but Claude Code hooks
131
+ run in Claude Code's own environment, not your interactive shell — if
132
+ `vocalize` was installed into a virtualenv that isn't on that `PATH`, set
133
+ `VOCALIZE_BIN` to the full path (e.g. `/path/to/.venv/bin/vocalize`) to
134
+ point the hook at it directly.
135
+
136
+ ## How it's built
137
+
138
+ Four decisions shaped the design:
139
+
140
+ - **The markdown flattener is a pure function.** The hardest logic in the
141
+ project — deciding what a table, list, or code block should *sound* like —
142
+ takes a string and returns a string. No I/O, no client, no key. That's why
143
+ it has the deepest test coverage in the repo, including the edge cases
144
+ that bit during review: prose containing a stray `|`, single-dash GFM
145
+ separators, ragged rows, duplicate column names.
146
+ - **One code path for humans and hooks.** The Claude Code hook doesn't
147
+ reimplement synthesis; it shells out to the same `vocalize` CLI you'd
148
+ type by hand (with an `--` argv guard so a response starting with a
149
+ bullet isn't parsed as a flag). Anything the hook can do, you can
150
+ reproduce and debug from your own terminal.
151
+ - **The hook may fail; the session may not.** Every failure path in the
152
+ Stop hook logs one line to stderr and exits 0. A dead API key or a hung
153
+ request costs you the audio, never the coding session.
154
+ - **The cache is an optimization, never a failure source.** Synthesis
155
+ results are content-addressed on disk; an unreadable or unwritable cache
156
+ degrades to a fresh API call instead of an error.
157
+
158
+ ## Architecture
159
+
160
+ ```
161
+ vocalize/
162
+ __init__.py # package version
163
+ __main__.py # python -m vocalize entry point
164
+ preprocess.py # markdown -> speakable text (pure function, fully unit tested)
165
+ config.py # API key resolution: --api-key > $ELEVENLABS_API_KEY > .env
166
+ exceptions.py # VocalizeError / TTSRequestError
167
+ tts.py # ElevenLabs API wrapper + disk cache (client is injected, so
168
+ # it's mockable in tests without hitting the network)
169
+ audio.py # save to disk + play via the OS's native player
170
+ # (afplay / mpg123 / ffplay / PowerShell, whichever exists)
171
+ cli.py # click-based CLI wiring the above together
172
+ hooks/
173
+ claude_stop_hook.py # Claude Code Stop hook -> calls the vocalize CLI
174
+ install_hook.py # safely merges the hook into ~/.claude/settings.json
175
+ tests/ # pytest, all mocked — no API key needed to run these
176
+ ```
177
+
178
+ ## Testing
179
+
180
+ ```bash
181
+ pip install -e ".[dev]"
182
+ pytest
183
+ ```
184
+
185
+ All tests run offline: the ElevenLabs client is dependency-injected into
186
+ `tts.py`, so tests pass in a fake client instead of hitting the real API.
187
+
188
+ ## Known limitations
189
+
190
+ - **Charts and images aren't described.** Flattening markdown tables is a
191
+ text problem; a rendered chart is an image, and describing it well needs
192
+ a vision model in the loop, not a text transform. Out of scope for this
193
+ project, but a natural next step — pipe the image through a
194
+ vision-capable model first, feed its description into `vocalize` in
195
+ place of the chart.
196
+ - **Free tier is 10,000 characters/month** — plenty for reading a handful
197
+ of documents aloud, not for continuous use. `--max-chars` and the disk
198
+ cache both help stretch it.
199
+ - Table flattening handles standard GFM pipe tables; it doesn't attempt to
200
+ handle merged cells or nested tables (rare enough in practice that it
201
+ wasn't worth the complexity).
202
+ - **Windows playback is untested.** The PowerShell `SoundPlayer` fallback
203
+ only plays WAV, so the mp3 files this tool generates likely won't play
204
+ there. Use `--no-play` and open the saved file with whatever's on hand.
205
+ - **The disk cache under `~/.cache/vocalize` grows unbounded.** It's
206
+ content-addressed (keyed by a hash of text, voice, model, and format),
207
+ so it's always safe to delete some or all of it — nothing will break,
208
+ you'll just re-pay for a re-synthesized clip.
209
+ - **`--api-key` on the command line is visible to other local processes**
210
+ (anything that can run `ps`). Prefer the `ELEVENLABS_API_KEY` environment
211
+ variable or a `.env` file instead.
212
+ - `vocalize voices` lists only the first page of results from the
213
+ ElevenLabs API.
214
+
215
+ ## License
216
+
217
+ MIT
@@ -0,0 +1,146 @@
1
+ #!/usr/bin/env python3
2
+ """Speak Claude's last response aloud via vocalize. Two modes:
3
+
4
+ 1. As a Claude Code `Stop` hook. Claude Code invokes Stop hooks with a JSON
5
+ payload on stdin that includes `transcript_path` — the path to a JSONL
6
+ file of the conversation so far — and every response gets spoken.
7
+ 2. On demand, with `--latest`. Nothing is read from stdin; the script finds
8
+ the most recently written transcript under ~/.claude/projects and speaks
9
+ that response. Run it when you want speech instead of installing the
10
+ hook and getting it after every turn.
11
+
12
+ Either way it pulls the most recent assistant text message out of the
13
+ transcript and pipes it through the `vocalize` CLI (the same one used
14
+ directly from the command line), so there's exactly one code path for
15
+ "turn text into speech".
16
+
17
+ See hooks/install_hook.py to wire this into ~/.claude/settings.json, or
18
+ do it by hand — add to the "Stop" array:
19
+
20
+ {
21
+ "matcher": "",
22
+ "hooks": [{"type": "command", "command": "python3 /path/to/claude_stop_hook.py"}]
23
+ }
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import json
29
+ import os
30
+ import shutil
31
+ import subprocess
32
+ import sys
33
+ from pathlib import Path
34
+
35
+ # Keep spoken responses short by default — a Stop hook fires after every
36
+ # turn, and a long response would eat the ElevenLabs free-tier quota fast.
37
+ # Override with VOCALIZE_MAX_CHARS in the environment.
38
+ DEFAULT_MAX_CHARS = 500
39
+
40
+
41
+ def _extract_last_assistant_text(transcript_path: str) -> str:
42
+ last_text_parts: list[str] = []
43
+ try:
44
+ with open(transcript_path, "r", encoding="utf-8") as f:
45
+ lines = f.readlines()
46
+ except OSError:
47
+ return ""
48
+
49
+ for line in reversed(lines):
50
+ line = line.strip()
51
+ if not line:
52
+ continue
53
+ try:
54
+ entry = json.loads(line)
55
+ except json.JSONDecodeError:
56
+ continue
57
+
58
+ if entry.get("type") != "assistant":
59
+ continue
60
+
61
+ message = entry.get("message", {})
62
+ content = message.get("content", [])
63
+ if isinstance(content, str):
64
+ # Older / alternate transcript shapes store the whole message as
65
+ # a plain string rather than a list of content blocks.
66
+ if content:
67
+ last_text_parts.append(content)
68
+ else:
69
+ for block in content:
70
+ if isinstance(block, dict) and block.get("type") == "text":
71
+ text = block.get("text", "")
72
+ if text:
73
+ last_text_parts.append(text)
74
+
75
+ if last_text_parts:
76
+ break # got the most recent assistant turn; stop scanning
77
+
78
+ return "\n".join(last_text_parts)
79
+
80
+
81
+ def _find_latest_transcript(projects_dir=None) -> str | None:
82
+ """Most recently modified Claude Code transcript, or None if there are none.
83
+
84
+ Claude Code stores one directory per project under ~/.claude/projects,
85
+ each holding <session-id>.jsonl files, so newest mtime is "the session
86
+ you were just talking to".
87
+ """
88
+ base = Path(projects_dir) if projects_dir else Path.home() / ".claude" / "projects"
89
+ transcripts = list(base.glob("*/*.jsonl"))
90
+ if not transcripts:
91
+ return None
92
+ return str(max(transcripts, key=lambda p: p.stat().st_mtime))
93
+
94
+
95
+ def main() -> int:
96
+ if "--latest" in sys.argv[1:]:
97
+ # On-demand mode: no hook payload on stdin, so don't read it at all.
98
+ transcript_path = _find_latest_transcript()
99
+ else:
100
+ try:
101
+ payload = json.load(sys.stdin)
102
+ except json.JSONDecodeError:
103
+ payload = {}
104
+ transcript_path = payload.get("transcript_path")
105
+
106
+ if not transcript_path:
107
+ return 0 # nothing to do — don't block Claude Code on a hook error
108
+
109
+ text = _extract_last_assistant_text(transcript_path)
110
+ if not text.strip():
111
+ return 0
112
+
113
+ # VOCALIZE_BIN wins over PATH so a venv install still resolves when the
114
+ # hook runs from Claude Code's environment rather than your own shell.
115
+ vocalize_bin = os.environ.get("VOCALIZE_BIN") or shutil.which("vocalize")
116
+ if not vocalize_bin:
117
+ # Silently no-op rather than breaking the user's session if the
118
+ # tool isn't installed / not on PATH in this shell.
119
+ return 0
120
+
121
+ max_chars = os.environ.get("VOCALIZE_MAX_CHARS", str(DEFAULT_MAX_CHARS))
122
+
123
+ # Options first, then "--", then the text. Click treats any argv token
124
+ # starting with "-" as an option, so a reply that opens with a bullet
125
+ # ("- fixed the parser") or an arrow ("-> next") would otherwise make
126
+ # vocalize exit 2 with "No such option" and speak nothing. The "--"
127
+ # end-of-options separator makes the text unambiguously an argument.
128
+ try:
129
+ result = subprocess.run(
130
+ [vocalize_bin, "speak", "--max-chars", max_chars, "--play", "--", text],
131
+ timeout=60,
132
+ check=False,
133
+ )
134
+ if result.returncode != 0:
135
+ print(f"vocalize hook: vocalize exited {result.returncode}", file=sys.stderr)
136
+ except Exception as exc: # noqa: BLE001 — must not crash the Stop hook
137
+ # A speech failure should never break the coding session, so this
138
+ # still returns 0 — but it's logged to stderr rather than swallowed
139
+ # silently, so a broken hook is diagnosable.
140
+ print(f"vocalize hook: speech failed: {exc}", file=sys.stderr)
141
+
142
+ return 0
143
+
144
+
145
+ if __name__ == "__main__":
146
+ sys.exit(main())