- Python 100%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
|
All checks were successful
Checks / checks (push) Successful in 1m11s
Co-authored-by: Cursor <cursoragent@cursor.com> |
||
| .forgejo/workflows | ||
| examples | ||
| src/text2audiobook | ||
| tests | ||
| .gitignore | ||
| .pre-commit-config.yaml | ||
| .python-version | ||
| LICENSE | ||
| pyproject.toml | ||
| README.md | ||
| uv.lock | ||
text2audiobook
Turn a long document into a chaptered audiobook, read by a text-to-speech model that runs on your own machine. Nothing is uploaded anywhere.
The input is a Typst source or a PDF; the output is a single .m4b with one navigable
mark per chapter, a title, an author and cover art. A thesis of eighty pages takes about
six minutes to narrate and comes out a little over two hours long.
The difficulty is not the synthesis. It is that a written document is written for the eye: it carries code listings nobody wants read out letter by letter, figures that are only meaningful as captions, footnotes that interrupt a sentence, and running headers on every page. What this tool mostly does is decide what to say and what to leave out.
Requirements
- macOS on Apple Silicon for the synthesis, which runs on MLX. Extraction and assembly work anywhere.
- ffmpeg and ffprobe to assemble the book:
brew install ffmpeg - ImageMagick for the cover:
brew install imagemagick
Installation
uv sync
The first run downloads the voice model from Hugging Face, roughly 350 MB, and caches it.
Quick start
Describe the book in a TOML file:
[book]
title = "Evoluzione di una UI per agenti IA"
author = "Nicola Zambello"
language = "it"
source = "../tesi-laurea/thesis.typ"
cover = "../tesi-laurea/thesis.pdf"
Then build it:
uv run text2audiobook build book.toml
Or run the three stages one at a time, which is usually what you want the first time:
uv run text2audiobook text book.toml # extract the chapter texts, and read them
uv run text2audiobook speak book.toml # narrate them
uv run text2audiobook pack book.toml # assemble the .m4b
Each stage leaves its result under out/, so a run that is interrupted picks up where
it stopped, and a chapter already narrated is not narrated again. Delete a .wav to
have that one chapter redone.
Reading the extracted text before narrating is worth the minute it takes. Synthesis is by far the slowest step, and a word spelled in a way the model mispronounces is much cheaper to fix in the text than after two hours of audio.
To choose a voice, listen to a few of them:
uv run text2audiobook sample book.toml --voice im_nicola
uv run text2audiobook sample book.toml --voice im_nicola,if_sara
Which source to use
Give it the Typst source whenever you have it. The source still says what every piece of the document is, so a listing can be announced by its caption instead of read out, and a glossary footnote can be folded into the sentence that calls it.
A PDF has forgotten all of that, so the parts have to be told apart by how they look: body text is whatever size most of the document is set in, captions and notes are set smaller, note markers smaller still, and code sits in a monospaced face. Chapters come from the outline the authoring tool wrote, so a PDF must have bookmarks; without them there is nothing to cut chapters on.
On an 83-page thesis the PDF reader agrees with the Typst reader on 99.9% of words. What differs is worth knowing before you rely on it:
- A word the typesetter broke across two lines is mended, but whether the hyphen
belonged to the word cannot be known for certain.
Berners- Leekeeps its hyphen because of the capital;trade- offloses it and becomestradeoff, which sounds the same anyway. - A line of prose carrying a lot of inline code can be mistaken for a line of code and dropped.
- The cells of a table are ordinary text and get read in reading order, which rarely makes sense. The caption still announces the table.
- Cross-references come out better than from the source, because the PDF has resolved
them:
see Figure 3.1instead ofsee.
Configuration
Paths are resolved against the directory holding the configuration file. Everything
except [book] is optional; what follows are the defaults.
# Where chapter texts and per-chapter audio are kept between runs.
workdir = "out"
[book]
title = "..." # required, used as the album title
source = "..." # required, a .typ or .pdf file
author = ""
language = "en" # en or it
date = ""
cover = "" # a PDF; its first page becomes the cover art
output = "" # defaults to <workdir>/<title>.m4b
[text]
footnotes = "inline" # inline | drop
blocks = "announce" # announce | drop
block_names = ["listing", "figure", "diagram", "table"]
drop_blocks = [] # names announced nowhere, e.g. ["listing"]
drop_headings = [] # on top of the ones the language already drops
[voice]
model = "prince-canuma/Kokoro-82M"
voice = "" # defaults to the voice of the language
lang_code = "" # defaults to the first letter of the voice name
speed = 1.0
max_chars = 320
builtin_pronunciation = true
[pauses]
paragraph = 0.45 # seconds of silence after a paragraph
heading = 1.1 # after a heading, which is a landmark
sentence = 0.3 # where a paragraph had to be said in several pieces
[audio]
bitrate = "64k"
sample_rate = 24000
channels = 1
[pdf] # only read when the source is a PDF
header_margin = 0.09 # slice of the page height that is a running header
footer_margin = 0.05
body_tolerance = 0.04 # sizes within this of the common size are body text
small_band = [0.70, 0.98] # band holding captions and footnotes
marker_size = 0.68 # at or below this, digits are a note marker
paragraph_gap = 1.3 # multiple of the leading that starts a paragraph
drop_monospace = true # a monospaced face is code, and code is not read
drop_citations = true # [12] is a pointer to the bibliography, not words
Two kinds of substitution, and why they are not the same
This is the one thing worth understanding before configuring anything.
[text.replacements] rewrites the written text. Use it for forms a reader expands
out loud: v8 into "versione otto", npm into three spoken letters. Because it changes
the text, it also changes the chapter titles, which is usually what you want.
[text.replacements]
"\\bnpm\\b" = "N.P.M."
"\\bv8\\b" = "versione otto"
[voice.pronunciation] is applied only on the way to the model, and never to the
text on disk. Use it for phonetic respellings. Italian is the case that forces the
distinction: the phonemiser reads every word by Italian rules, so cache comes out as
"ca-che", helper loses its h and Markdown becomes something else entirely. The fix
is to spell them the way they sound, and the reason it cannot go in the text is that a
chapter called "LLM, Markdown e asincronicità" would then be filed under "Markdaun".
[voice.pronunciation]
"\\bMarkdown\\b" = "Markdaun"
"\\bcache\\b" = "chesh"
Spelling an acronym out is the trap that sits exactly on the border between the two.
Writing "\\bJS\\b" = "J.S." among the text replacements works in English and fails in
Italian, where the letter J is named "i lunga" and a speech recogniser fed the result
transcribes it as "Ilunga S". Letter names are pronunciation, not expansion, so the
Italian table respells JS as "gei esse" instead.
Italian ships with a table of about seventy technical English terms, so you rarely need
to add to it. Set builtin_pronunciation = false to start from nothing.
Order matters when one pattern is a prefix of another, so use a list of pairs instead of a table when you need to control it:
[voice]
pronunciation = [["\\bbundler\\b", "bandler"], ["\\bbundle\\b", "bandol"]]
Voices
The model encodes the language in the first letter of the voice name, which is where
lang_code comes from: a American English, b British English, e Spanish, f
French, h Hindi, i Italian, j Japanese, p Portuguese, z Chinese. The second
letter is f or m for the voice itself. See the
Kokoro voice list.
Naming several voices separated by commas averages their style, and a blend is read in
the language of its first voice. This matters more than it sounds, because the style
vector feeds Kokoro's duration predictor: it sets the rhythm and the pausing, not only
the timbre. The default for English is bm_george; the default for Italian is
im_nicola,if_sara,bm_george, and each name in it was added for a measured reason.
im_nicola alone speaks around 80 Hz and moves less than two semitones, a flat and
gravelly drone; if_sara lifts the blend to 138 Hz; bm_george is there for its
phrasing, because the Italian voices were trained on minutes rather than hours and
hardly pause at all — 59 breaks where the same chapter in English has 103 — and part of
that comes back in the average.
Avoid mixing an American voice into another language: am_michael reading Italian is so
heavily accented that a speech recogniser transcribes it as broken English.
Every division of a paragraph costs something, which is why max_chars should be left
as high as it safely goes. The two halves become separate utterances, each with its own
intonation and with a quarter of a second of silence before and half a second after,
which is why the narrator packs as many whole sentences into one piece as will fit and
cuts that padding back to pauses.sentence wherever a division was unavoidable.
English is chunked by the model itself, which packs words until the phonemes would pass
510 tokens and then splits at the best boundary it can find. Every other language is cut
into blocks of four hundred characters at full stops only, and whatever still exceeds 510
phoneme tokens after that is silently truncated. That is why max_chars exists for the
other languages: espeak produces about 1.1 phonemes per character of Italian and up to
1.6 in the worst sentence measured, so 320 characters is the largest block that can never
be cut off.
Adding a language
src/text2audiobook/languages.py holds one entry per language: the words a narrator
says for "Chapter" and "Figure", the headings that exist only on the page and are
skipped, the abbreviations that end in a full stop without ending a sentence, and the
phonetic respellings the phonemiser needs. Adding a language means adding one entry.
Development
uv sync --all-groups
uv run pre-commit install
uv run pytest
Linting and formatting are Ruff; the hooks run both plus the test suite before a commit.
The PDF tests run against tests/fixtures/doc.pdf, a two-page book kept in the
repository next to the Typst source it was built from. It is small but deliberately
awkward: an unnumbered preface, two chapters sharing a page, a running header, a
footnote, a hyphenated word, a block of code and two captions set at different sizes.
Rebuild it with typst compile tests/fixtures/doc.typ.
A note on how this was built
This project was written with the help of an AI coding assistant, from the first commit to this sentence. The design decisions, the empirical checks behind them and the final review are the author's; a good part of the code and of this document was drafted by a model and then read, corrected and tested.
The reason it is worth saying is that it changes what the test suite is for. The rules in here that look arbitrary, such as the phonetic respellings or the band of font sizes that marks a caption, were not reasoned out from a specification: they were measured on real documents, by synthesising the audio and transcribing it back, or by reading a PDF with the Typst source as the oracle. The tests record those measurements. Trust them rather than the plausibility of the code.