API Reference
Auto-generated documentation for the audify Python package.
CLI entry point (audify.cli)
Conversion factory (audify.convert)
Audiobook creator (audify.audiobook_creator)
Text-to-speech synthesizers (audify.text_to_speech)
REST API (audify.api.app)
Audify REST API
Exposes the core Audify functionality (TTS synthesis and LLM-powered audiobook creation) as a Docker-deployable FastAPI service.
Endpoints
GET /health – liveness probe GET /voices – list voices available from the configured TTS provider GET /providers – list all supported TTS providers POST /synthesize – convert an uploaded EPUB/PDF to MP3 (simple TTS) POST /audiobook – convert an uploaded EPUB/PDF to an M4B audiobook via LLM
- audify.api.app.health()
Liveness probe — always returns 200 when the server is up.
- Return type:
fastapi.responses.JSONResponse
- audify.api.app.list_providers()
Return all supported TTS provider names.
- Return type:
fastapi.responses.JSONResponse
- audify.api.app.list_voices(provider='kokoro', language='en')
Return available voices for provider.
Query parameters
- providerstr
One of the values returned by
GET /providers(default: the value of theTTS_PROVIDERenvironment variable, which defaults tokokoro).- languagestr
BCP-47 language code such as
en,es,fr(default:en).
- Parameters:
provider (str)
language (str)
- Return type:
fastapi.responses.JSONResponse
- audify.api.app.synthesize(background_tasks, file=fastapi.File, voice=fastapi.Form, language=fastapi.Form, tts_provider=fastapi.Form, translate=fastapi.Form)
Convert an uploaded EPUB or PDF file to an MP3 audio file.
The response is the MP3 file as a binary download.
- Parameters:
background_tasks (fastapi.background.BackgroundTasks)
file (fastapi.UploadFile)
voice (str)
language (str | None)
tts_provider (str)
translate (str | None)
- Return type:
fastapi.responses.FileResponse
- audify.api.app.create_audiobook(background_tasks, file=fastapi.File, voice=fastapi.Form, language=fastapi.Form, tts_provider=fastapi.Form, llm_model=fastapi.Form, llm_base_url=fastapi.Form, translate=fastapi.Form, max_chapters=fastapi.Form)
Convert an uploaded EPUB or PDF to an M4B audiobook using LLM script generation.
The response is the M4B audiobook file as a binary download.
- Parameters:
background_tasks (fastapi.background.BackgroundTasks)
file (fastapi.UploadFile)
voice (str)
language (str | None)
tts_provider (str)
llm_model (str)
llm_base_url (str)
translate (str | None)
max_chapters (int | None)
- Return type:
fastapi.responses.FileResponse
Readers
Domain interface (audify.domain.reader)
EPUB reader (audify.readers.ebook)
- class audify.readers.ebook.EpubReader(path, llm_config=None)[source]
Bases:
ReaderReader for EPUB ebook files, providing content extraction and chapter splitting.
This reader uses a combination of TOC-based grouping and legacy spine-item extraction to split an ebook into logical chapters, while filtering out non-chapter content like covers and copyright pages.
- Parameters:
path (str | Path)
llm_config (OllamaAPIConfig | CommercialAPIConfig | None)
- get_chapters()[source]
Get chapter content in spine order, grouped by TOC boundaries.
Uses the EPUB table of contents to merge spine items that belong to the same logical chapter. If no TOC is available or it doesn’t align with the spine, all valid documents are grouped into a single chapter.
- Return type:
list[str]
- extract_text(chapter)[source]
Extract plain text from a chapter’s HTML content.
- Parameters:
chapter (str)
- Return type:
str
PDF reader (audify.readers.pdf)
Text reader (audify.readers.text)
Prompt system
Task registry (audify.prompts.tasks)
Task configuration and registry for Audify prompt system.
- class audify.prompts.tasks.TaskConfig(name, prompt, requires_llm=True, llm_params=<factory>, output_structure='single')[source]
Bases:
objectConfiguration for a specific audio transformation task.
- Parameters:
name (str)
prompt (str)
requires_llm (bool)
llm_params (dict)
output_structure (str)
- name: str
- prompt: str
- requires_llm: bool = True
- llm_params: dict
- output_structure: str = 'single'
- class audify.prompts.tasks.TaskRegistry[source]
Bases:
objectRegistry of available audio transformation tasks.
- classmethod register(config)[source]
Register a new task configuration.
- Parameters:
config (TaskConfig) – The TaskConfig to register.
- Return type:
None
- classmethod get(name)[source]
Get a task configuration by name.
- Parameters:
name (str) – Task name to retrieve.
- Returns:
The TaskConfig if found, None otherwise.
- Return type:
TaskConfig | None
- classmethod list_tasks()[source]
List all registered task names.
- Returns:
Sorted list of registered task names.
- Return type:
list[str]
- classmethod get_all()[source]
Get all registered task configurations.
- Returns:
Dictionary of all registered tasks.
- Return type:
dict[str, TaskConfig]
Prompt manager (audify.prompts.manager)
Prompt manager for loading and managing prompts.
- class audify.prompts.manager.PromptManager[source]
Bases:
objectManages loading and resolving prompts from various sources.
- get_builtin_prompt(task_name)[source]
Load a built-in prompt by task name.
- Parameters:
task_name (str) – Name of the built-in task (e.g., “audiobook”, “podcast”).
- Returns:
The prompt text.
- Raises:
FileNotFoundError – If the built-in prompt file doesn’t exist.
- Return type:
str
- load_prompt_file(path)[source]
Load a custom prompt from a file path.
- Parameters:
path (str | Path) – Path to the prompt file.
- Returns:
The prompt text.
- Raises:
FileNotFoundError – If the prompt file doesn’t exist.
ValueError – If the prompt file is empty.
- Return type:
str
- get_prompt(task, prompt_file=None)[source]
Resolve the prompt for a given task.
Priority: prompt_file > task’s built-in prompt.
- Parameters:
task (str) – Task name (e.g., “audiobook”, “podcast”, “direct”).
prompt_file (str | Path | None) – Optional path to a custom prompt file.
- Returns:
The resolved prompt text. Empty string for “direct” task.
- Return type:
str
Utilities
TTS configuration (audify.utils.api_config)
Shared API configuration utilities for various external services.
This module consolidates API configuration classes to reduce code duplication across different modules that interact with external APIs.
- class audify.utils.api_config.APIConfig(base_url, timeout=30)[source]
Bases:
objectBase class for API configurations.
- Parameters:
base_url (str)
timeout (int)
- class audify.utils.api_config.KokoroAPIConfig(base_url=None, voice=None)[source]
Bases:
APIConfigConfiguration for Kokoro TTS API.
- Parameters:
base_url (str | None)
voice (str | None)
- property voices_url: str
URL for fetching available voices.
- property speech_url: str
URL for text-to-speech synthesis.
- class audify.utils.api_config.TTSAPIConfig(voice=None, language='en', timeout=60)[source]
Bases:
ABCAbstract base class for TTS API configurations.
This provides a common interface for different TTS providers (Kokoro, OpenAI, AWS Polly, Google Cloud TTS).
- Parameters:
voice (str | None)
language (str)
timeout (int)
- abstractmethod synthesize(text, output_path)[source]
Synthesize text to audio and save to output_path.
- Parameters:
text (str) – The text to synthesize.
output_path (Path) – Path where the audio file will be saved (WAV format).
- Returns:
True if synthesis was successful, False otherwise.
- Return type:
bool
- abstractmethod get_available_voices()[source]
Get list of available voices for this provider.
- Returns:
List of voice identifiers.
- Return type:
List[str]
- abstractmethod is_available()[source]
Check if the TTS service is available and properly configured.
- Returns:
True if service is available, False otherwise.
- Return type:
bool
- abstract property provider_name: str
Return the name of the TTS provider.
- property max_text_length: int
Maximum text length for a single synthesis request.
The unit (characters or bytes) is determined by
limit_unit. Defaults to 5000. Subclasses can override.
- property limit_unit: str
"chars"or"bytes".Providers whose APIs enforce a byte limit (e.g. Google Cloud TTS, AWS Polly) should override this to
"bytes"so the batching layer measures text size correctly for multi-byte UTF-8 content.- Type:
Unit for
max_text_length
- class audify.utils.api_config.KokoroTTSConfig(voice=None, language='en', base_url=None, timeout=60)[source]
Bases:
TTSAPIConfigTTS configuration for local Kokoro API.
- Parameters:
voice (str | None)
language (str)
base_url (str | None)
timeout (int)
- property provider_name: str
Return the name of the TTS provider.
- property voices_url: str
URL for fetching available voices.
- property speech_url: str
URL for text-to-speech synthesis.
- class audify.utils.api_config.OpenAITTSConfig(voice=None, language='en', api_key=None, model=None, timeout=60)[source]
Bases:
TTSAPIConfigTTS configuration for OpenAI TTS API.
- Parameters:
voice (str | None)
language (str)
api_key (str | None)
model (str | None)
timeout (int)
- AVAILABLE_VOICES = ['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer']
- property provider_name: str
Return the name of the TTS provider.
- property max_text_length: int
OpenAI TTS has a 4096-character limit per request.
- class audify.utils.api_config.AWSTTSConfig(voice=None, language='en', access_key_id=None, secret_access_key=None, region=None, engine=None, timeout=60)[source]
Bases:
TTSAPIConfigTTS configuration for AWS Polly.
- Parameters:
voice (str | None)
language (str)
access_key_id (str | None)
secret_access_key (str | None)
region (str | None)
engine (str | None)
timeout (int)
- NEURAL_VOICES = {'de': ['Vicki', 'Daniel'], 'en': ['Joanna', 'Matthew', 'Ivy', 'Kendra', 'Kimberly', 'Salli', 'Joey', 'Justin', 'Kevin', 'Ruth', 'Stephen'], 'es': ['Lupe', 'Pedro', 'Mia'], 'fr': ['Lea', 'Remi'], 'hi': ['Kajal'], 'it': ['Bianca', 'Adriano'], 'ja': ['Takumi', 'Kazuha', 'Tomoko'], 'pt': ['Camila', 'Thiago', 'Vitoria', 'Ricardo'], 'zh': ['Zhiyu']}
- property provider_name: str
Return the name of the TTS provider.
- property max_text_length: int
AWS Polly has a 3000-byte limit per synthesis request.
- property limit_unit: str
"chars"or"bytes".Providers whose APIs enforce a byte limit (e.g. Google Cloud TTS, AWS Polly) should override this to
"bytes"so the batching layer measures text size correctly for multi-byte UTF-8 content.- Type:
Unit for
max_text_length
- class audify.utils.api_config.GoogleTTSConfig(voice=None, language='en', credentials_path=None, timeout=60)[source]
Bases:
TTSAPIConfigTTS configuration for Google Cloud Text-to-Speech.
- Parameters:
voice (str | None)
language (str)
credentials_path (str | None)
timeout (int)
- NEURAL_VOICES = {'de': ['de-DE-Neural2-A', 'de-DE-Neural2-B', 'de-DE-Neural2-C', 'de-DE-Neural2-D', 'de-DE-Neural2-F'], 'en': ['en-US-Neural2-A', 'en-US-Neural2-C', 'en-US-Neural2-D', 'en-US-Neural2-E', 'en-US-Neural2-F', 'en-US-Neural2-G', 'en-US-Neural2-H', 'en-US-Neural2-I', 'en-US-Neural2-J'], 'es': ['es-ES-Neural2-A', 'es-ES-Neural2-B', 'es-ES-Neural2-C', 'es-ES-Neural2-D', 'es-ES-Neural2-E', 'es-ES-Neural2-F'], 'fr': ['fr-FR-Neural2-A', 'fr-FR-Neural2-B', 'fr-FR-Neural2-C', 'fr-FR-Neural2-D', 'fr-FR-Neural2-E'], 'hi': ['hi-IN-Neural2-A', 'hi-IN-Neural2-B', 'hi-IN-Neural2-C', 'hi-IN-Neural2-D'], 'it': ['it-IT-Neural2-A', 'it-IT-Neural2-B', 'it-IT-Neural2-C'], 'ja': ['ja-JP-Neural2-B', 'ja-JP-Neural2-C', 'ja-JP-Neural2-D'], 'pt': ['pt-BR-Neural2-A', 'pt-BR-Neural2-B', 'pt-BR-Neural2-C'], 'zh': ['cmn-CN-Neural2-A', 'cmn-CN-Neural2-B', 'cmn-CN-Neural2-C', 'cmn-CN-Neural2-D']}
- LANGUAGE_CODES = {'ar': 'ar-XA', 'de': 'de-DE', 'en': 'en-US', 'es': 'es-ES', 'fr': 'fr-FR', 'hi': 'hi-IN', 'it': 'it-IT', 'ja': 'ja-JP', 'ko': 'ko-KR', 'nl': 'nl-NL', 'pl': 'pl-PL', 'pt': 'pt-BR', 'ru': 'ru-RU', 'tr': 'tr-TR', 'zh': 'cmn-CN'}
- property provider_name: str
Return the name of the TTS provider.
- property max_text_length: int
Google Cloud TTS enforces a 5000-byte limit per request.
Use 4800 bytes to leave a safety margin for the space separators added when joining batched sentences.
- property limit_unit: str
"chars"or"bytes".Providers whose APIs enforce a byte limit (e.g. Google Cloud TTS, AWS Polly) should override this to
"bytes"so the batching layer measures text size correctly for multi-byte UTF-8 content.- Type:
Unit for
max_text_length
- class audify.utils.api_config.QwenTTSConfig(voice=None, language='en', base_url=None, timeout=60)[source]
Bases:
TTSAPIConfigTTS configuration for Qwen3-TTS API.
- Parameters:
voice (str | None)
language (str)
base_url (str | None)
timeout (int)
- property provider_name: str
Return the name of the TTS provider.
- property max_text_length: int
Qwen TTS maximum text length per request.
- property health_url: str
URL for health check.
- property tts_url: str
URL for text-to-speech synthesis.
- is_available()[source]
Check if Qwen-TTS API is reachable.
Uses retries to avoid false negatives under transient load.
- Return type:
bool
- audify.utils.api_config.get_tts_config(provider=None, voice=None, language='en', **kwargs)[source]
Factory function to get the appropriate TTS configuration.
- Parameters:
provider (str | None) – TTS provider name (“kokoro”, “openai”, “aws”, “google”, “qwen”). Defaults to DEFAULT_TTS_PROVIDER from environment.
voice (str | None) – Voice identifier for the provider.
language (str) – Language code (e.g., “en”, “es”, “fr”).
**kwargs – Additional provider-specific arguments.
- Returns:
TTSAPIConfig instance for the specified provider.
- Raises:
ValueError – If provider is not supported.
- Return type:
- class audify.utils.api_config.CommercialAPIConfig(model, api_key=None, timeout=600)[source]
Bases:
APIConfigConfiguration for commercial LLM APIs (DeepSeek, Claude, GPT-4, Gemini).
Uses LiteLLM to provide unified interface to commercial APIs. Model format: ‘api:provider/model’ (e.g., ‘api:deepseek-chat’) API keys are loaded from .keys file, api_keys module, or environment variables.
- Parameters:
model (str)
api_key (str | None)
timeout (int)
- MODEL_MAPPINGS = {'claude': 'anthropic/claude-3-5-sonnet-20241022', 'claude-opus': 'anthropic/claude-3-opus-20240229', 'claude-sonnet': 'anthropic/claude-3-5-sonnet-20241022', 'deepseek-chat': 'deepseek/deepseek-chat', 'deepseek-reasoner': 'deepseek/deepseek-reasoner', 'deepseekr1': 'deepseek/deepseek-reasoner', 'gemini': 'gemini/gemini-2.0-flash-exp', 'gemini-flash': 'gemini/gemini-2.0-flash-exp', 'gemini-pro': 'gemini/gemini-pro', 'gpt-4': 'openai/gpt-4-turbo-preview', 'gpt-4-turbo': 'openai/gpt-4-turbo-preview', 'gpt-4o': 'openai/gpt-4o'}
- generate(prompt=None, system_prompt=None, user_prompt=None, temperature=0.8, top_p=0.9, num_ctx=32768, repeat_penalty=1.05, seed=None, top_k=60, num_predict=4096)[source]
Generate text using commercial API via LiteLLM.
- Parameters:
prompt (str | None) – Legacy parameter for single user message (deprecated)
system_prompt (str | None) – System role message (instructions/context)
user_prompt (str | None) – User role message (actual content to process)
temperature (float) – Sampling temperature
top_p (float) – Nucleus sampling parameter
num_ctx (int) – Context window size (ignored for most commercial APIs)
repeat_penalty (float) – Penalty for repeating tokens (ignored for most)
seed (int | None) – Random seed for reproducibility
top_k (int) – Top-k sampling parameter (ignored for most)
num_predict (int) – Maximum tokens to generate
- Returns:
Generated text content
- Return type:
str
- class audify.utils.api_config.OllamaAPIConfig(base_url=None, model=None, timeout=600)[source]
Bases:
APIConfigConfiguration for Ollama LLM API.
- Parameters:
base_url (str | None)
model (str | None)
timeout (int)
- generate(prompt=None, system_prompt=None, user_prompt=None, temperature=0.8, top_p=0.9, num_ctx=32768, repeat_penalty=1.05, seed=None, top_k=60, num_predict=4096)[source]
Generate text using LiteLLM with Ollama.
- Parameters:
prompt (str | None) – Legacy parameter for single user message (deprecated)
system_prompt (str | None) – System role message (instructions/context)
user_prompt (str | None) – User role message (actual content to process)
temperature (float) – Sampling temperature
top_p (float) – Nucleus sampling parameter
num_ctx (int) – Context window size
repeat_penalty (float) – Penalty for repeating tokens
seed (int | None) – Random seed for reproducibility
top_k (int) – Top-k sampling parameter
num_predict (int) – Maximum tokens to generate
- Returns:
Generated text content
- Return type:
str
- class audify.utils.api_config.OllamaTranslationConfig(base_url=None, model=None, timeout=600)[source]
Bases:
OllamaAPIConfigConfiguration for Ollama translation API using LiteLLM.
- Parameters:
base_url (str | None)
model (str | None)
timeout (int)
Audio processing (audify.utils.audio)
Shared audio utilities for common audio processing operations.
This module consolidates audio operations that are repeated across different modules to reduce code duplication and provide consistent audio handling.
- class audify.utils.audio.AudioProcessor[source]
Bases:
objectUtility class for common audio processing operations.
- static get_duration(file_path)[source]
Get the duration of an audio file in seconds.
- Parameters:
file_path (str | Path) – Path to the audio file
- Returns:
Duration in seconds, or 0.0 if the file cannot be decoded
- Return type:
float
- static convert_wav_to_mp3(wav_path, bitrate='192k', remove_original=True)[source]
Convert a WAV file to MP3 format.
- Parameters:
wav_path (Path) – Path to the WAV file
bitrate (str) – MP3 bitrate (default: “192k”)
remove_original (bool) – Whether to remove the original WAV file
- Returns:
Path to the created MP3 file
- Raises:
FileNotFoundError – If the WAV file doesn’t exist
Exception – If conversion fails
- Return type:
Path
- static combine_audio_files(file_paths, output_path, output_format='wav', show_progress=True, description='Combining Audio')[source]
Combine multiple audio files into a single audio file.
- Parameters:
file_paths (List[Path]) – List of paths to audio files to combine
output_path (Path) – Path for the output combined file
output_format (str) – Output format (“wav”, “mp3”, “mp4”)
show_progress (bool) – Whether to show progress bar
description (str) – Description for progress bar
- Returns:
Combined AudioSegment
- Raises:
ValueError – If no valid audio files are found
- Return type:
pydub.AudioSegment
- static split_audio_by_duration(file_paths, max_duration_hours=14.0)[source]
Split a list of audio files into chunks based on total duration.
- Parameters:
file_paths (List[Path]) – List of audio file paths
max_duration_hours (float) – Maximum duration per chunk in hours. Defaults to 14h — the practical limit for M4B/MP4 playback across common audiobook players (the format itself can hold more, but ~15h is the conventional ceiling).
- Returns:
List of chunks, where each chunk is a list of file paths
- Return type:
List[List[Path]]
- static combine_wav_segments(temp_audio_files, output_wav_path, logger_instance=None)[source]
Combine a list of temporary WAV segment files into a single WAV output.
Each source file is deleted after being appended. This consolidates the duplicated combining loops that previously existed in both
_synthesize_kokoroand_synthesize_with_provider.- Parameters:
temp_audio_files (List[Path]) – Ordered list of WAV segment paths to combine.
output_wav_path (Path) – Destination WAV file path.
logger_instance – Optional logger; falls back to the module logger.
- Return type:
None
- static create_temp_audio_file(file_paths, output_prefix, output_format='mp4', temp_dir=None)[source]
Create a temporary audio file from multiple source files.
- Parameters:
file_paths (List[Path]) – List of audio file paths to combine
output_prefix (str) – Prefix for the temporary file name
output_format (str) – Format for the temporary file
temp_dir (Path | None) – Directory for temporary file (uses system temp if None)
- Returns:
Path to the created temporary file
- Return type:
Path
M4B builder (audify.utils.m4b_builder)
Shared M4B audiobook assembly utilities.
This module consolidates the FFmpeg-based M4B creation logic that was previously
duplicated between EpubSynthesizer and AudiobookCreator.
- audify.utils.m4b_builder.write_metadata_header(metadata_path)[source]
Write the standard FFmpeg metadata header to metadata_path.
- Parameters:
metadata_path (Path)
- Return type:
None
- audify.utils.m4b_builder.append_chapter_metadata(metadata_path, title, start_ms, duration_s)[source]
Append a single chapter entry to metadata_path.
- Parameters:
metadata_path (Path) – Path to the FFmpeg metadata file.
title (str) – Chapter title.
start_ms (int) – Chapter start time in milliseconds.
duration_s (float) – Chapter duration in seconds.
- Returns:
End time in milliseconds (= next chapter’s start time).
- Return type:
int
- audify.utils.m4b_builder.build_ffmpeg_command(input_m4b, metadata_path, output_m4b, cover_image=None)[source]
Build the FFmpeg command to assemble the final M4B file.
A temporary copy of the cover image is created (when provided) because FFmpeg may lock the source file on some systems.
- Parameters:
input_m4b (Path) – Temporary M4B with raw audio.
metadata_path (Path) – FFmpeg metadata file with chapter markers.
output_m4b (Path) – Destination M4B path.
cover_image (Path | None) – Optional cover image path.
- Returns:
(command_list, cover_temp_file)— caller is responsible for closing and deleting cover_temp_file aftersubprocess.run.- Return type:
Tuple[List[str], IO[bytes] | None]
- audify.utils.m4b_builder.run_ffmpeg(command)[source]
Execute command via
subprocess.run.- Raises:
subprocess.CalledProcessError – If FFmpeg exits with a non-zero code.
FileNotFoundError – If FFmpeg is not installed / not in PATH.
- Parameters:
command (List[str])
- Return type:
None
- audify.utils.m4b_builder.assemble_m4b(input_m4b, metadata_path, output_m4b, cover_image=None)[source]
High-level helper: build command, run FFmpeg, clean up temp cover.
After a successful run the input_m4b temp file is deleted.
- Parameters:
input_m4b (Path) – Temporary M4B with raw audio (deleted on success).
metadata_path (Path) – FFmpeg metadata file with chapter markers.
output_m4b (Path) – Destination M4B path.
cover_image (Path | None) – Optional cover image path.
- Return type:
None
Text utilities (audify.utils.text)
- audify.utils.text.contains_cjk(text)[source]
Check if text contains CJK (Chinese, Japanese, Korean) characters.
- Parameters:
text (str)
- Return type:
bool
- audify.utils.text.clean_text(text)[source]
Clean text for TTS: normalize whitespace, fix punctuation spacing.
Preserves content within brackets, parentheses, and quotes — only normalizes the whitespace around them. Removes bare << and >> markers that sometimes survive EPUB parsing.
- Parameters:
text (str)
- Return type:
str
- audify.utils.text.combine_small_sentences(sentences, min_length=10)[source]
- Parameters:
sentences (list[str])
min_length (int)
- Return type:
list[str]
- audify.utils.text.break_too_long_sentences(sentences, max_length=239)[source]
- Parameters:
sentences (list[str])
max_length (int)
- Return type:
list[str]
- audify.utils.text.break_text_into_sentences(text, max_length=5000, min_length=20)[source]
- Parameters:
text (str)
max_length (int)
min_length (int)
- Return type:
list[str]
- audify.utils.text.get_audio_duration(file_path)[source]
Get audio duration in seconds. Delegates to AudioProcessor.get_duration.
- Parameters:
file_path (str)
- Return type:
float