├── lue
├── py.typed
├── tts
│ ├── __init__.py
│ ├── edge_tts.py
│ ├── base.py
│ └── kokoro_tts.py
├── __init__.py
├── keys_default.json
├── keys_vim.json
├── config.py
├── guide.txt
├── tts_manager.py
├── progress_manager.py
├── input_handler.py
├── __main__.py
├── audio.py
└── timing_calculator.py
├── images
├── lue-icon.png
└── lue-screenshot.gif
├── MANIFEST.in
├── requirements.txt
├── pyproject.toml
├── .gitignore
├── README.md
├── DEVELOPER.md
├── VOICES.md
└── LICENSE
/lue/py.typed:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/images/lue-icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/superstarryeyes/lue/HEAD/images/lue-icon.png
--------------------------------------------------------------------------------
/images/lue-screenshot.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/superstarryeyes/lue/HEAD/images/lue-screenshot.gif
--------------------------------------------------------------------------------
/lue/tts/__init__.py:
--------------------------------------------------------------------------------
1 | """Text-to-speech models for the Lue eBook reader."""
2 |
3 | from .base import TTSBase
4 |
5 | __all__ = ['TTSBase']
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include README.md
2 | include LICENSE
3 | include requirements.txt
4 | include DEVELOPER.md
5 | include VOICES.md
6 | recursive-include lue *.py
7 | recursive-include lue *.typed
8 | recursive-include lue *.txt
9 | recursive-include lue *.json
--------------------------------------------------------------------------------
/lue/__init__.py:
--------------------------------------------------------------------------------
1 | """
2 | Lue - Terminal eBook Reader with Text-to-Speech
3 |
4 | Multi-format support for EPUB, PDF, TXT, DOCX, HTML, RTF, and Markdown
5 | with modular TTS system featuring Edge TTS (default) and Kokoro TTS (local/offline).
6 | Rich terminal UI with smart persistence and cross-platform support.
7 | """
8 |
9 | __version__ = "0.4.0"
10 | __author__ = "Starry Eyes"
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | # Core dependencies
2 | python-docx>=1.2.0
3 | striprtf>=0.0.29
4 | rich>=14.1.0
5 | PyMuPDF>=1.26.3
6 | Markdown>=3.8.2
7 | platformdirs>=4.3.8
8 |
9 | # Default TTS model
10 | edge-tts>=7.2.7
11 |
12 | ## Optional TTS models (uncomment to enable)
13 | ## For Kokoro TTS, also install PyTorch for your platform:
14 | ## CPU: pip install torch torchvision torchaudio
15 | ## CUDA: pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
16 | # kokoro>=0.9.4
17 | # soundfile>=0.13.1
18 | # huggingface-hub>=0.34.4
--------------------------------------------------------------------------------
/lue/keys_default.json:
--------------------------------------------------------------------------------
1 | {
2 | "navigation": {
3 | "next_paragraph": "l",
4 | "prev_paragraph": "h",
5 | "next_sentence": "k",
6 | "prev_sentence": "j",
7 | "scroll_page_up": "i",
8 | "scroll_page_down": "m",
9 | "scroll_up": "u",
10 | "scroll_down": "n",
11 | "move_to_top_visible": "t",
12 | "move_to_beginning": "y",
13 | "move_to_end": "b"
14 | },
15 | "tts_controls": {
16 | "play_pause": "p",
17 | "decrease_speed": ",",
18 | "increase_speed": ".",
19 | "toggle_sentence_highlight": "s",
20 | "toggle_word_highlight": "w"
21 | },
22 | "display_controls": {
23 | "toggle_auto_scroll": "a",
24 | "cycle_ui_complexity": "v"
25 | },
26 | "application": {
27 | "quit": "q",
28 | "toggle_recent_menu": "r",
29 | "select_menu_item": "\n"
30 | }
31 | }
--------------------------------------------------------------------------------
/lue/keys_vim.json:
--------------------------------------------------------------------------------
1 | {
2 | "navigation": {
3 | "next_paragraph": "j",
4 | "prev_paragraph": "k",
5 | "next_sentence": ")",
6 | "prev_sentence": "(",
7 | "scroll_page_up": "\u0002",
8 | "scroll_page_down": "\u0006",
9 | "scroll_up": "\u0015",
10 | "scroll_down": "\u0004",
11 | "move_to_top_visible": "H",
12 | "move_to_beginning": "g",
13 | "move_to_end": "G"
14 | },
15 | "tts_controls": {
16 | "play_pause": "p",
17 | "decrease_speed": ",",
18 | "increase_speed": ".",
19 | "toggle_sentence_highlight": "s",
20 | "toggle_word_highlight": "w"
21 | },
22 | "display_controls": {
23 | "toggle_auto_scroll": "a",
24 | "cycle_ui_complexity": "v"
25 | },
26 | "application": {
27 | "quit": "q",
28 | "toggle_recent_menu": "r",
29 | "select_menu_item": "\n"
30 | }
31 | }
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = ["setuptools>=61.0", "wheel"]
3 | build-backend = "setuptools.build_meta"
4 |
5 | [project]
6 | name = "lue-reader"
7 | version = "0.4.0"
8 | description = "A terminal-based eBook reader with modular text-to-speech capabilities and multi-format support"
9 | readme = "README.md"
10 | license = {text = "GPL-3.0-or-later"}
11 | authors = [
12 | {name = "Starry Eyes"}
13 | ]
14 | classifiers = [
15 | "Development Status :: 4 - Beta",
16 | "Intended Audience :: End Users/Desktop",
17 | "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
18 | "Operating System :: OS Independent",
19 | "Programming Language :: Python :: 3",
20 | "Programming Language :: Python :: 3.10",
21 | "Programming Language :: Python :: 3.11",
22 | "Programming Language :: Python :: 3.12",
23 | "Topic :: Multimedia :: Sound/Audio :: Speech",
24 | "Topic :: Text Processing",
25 | "Environment :: Console",
26 | ]
27 | requires-python = ">=3.10"
28 | dependencies = [
29 | "python-docx>=1.2.0",
30 | "striprtf>=0.0.29",
31 | "rich>=14.1.0",
32 | "PyMuPDF>=1.26.3",
33 | "Markdown>=3.8.2",
34 | "platformdirs>=4.3.8",
35 | "edge-tts>=7.2.0",
36 | ]
37 |
38 | [project.optional-dependencies]
39 | kokoro = [
40 | "kokoro>=0.9.4",
41 | "soundfile>=0.13.1",
42 | "huggingface-hub>=0.34.4",
43 | ]
44 |
45 | [project.scripts]
46 | lue = "lue.__main__:cli"
47 |
48 | [project.urls]
49 | Homepage = "https://github.com/superstarryeyes/lue"
50 | Repository = "https://github.com/superstarryeyes/lue"
51 | Issues = "https://github.com/superstarryeyes/lue/issues"
52 |
53 | [tool.setuptools.packages.find]
54 | include = ["lue*"]
55 |
56 | [tool.setuptools.package-data]
57 | lue = ["py.typed", "guide.txt", "*.json"]
--------------------------------------------------------------------------------
/lue/config.py:
--------------------------------------------------------------------------------
1 | """Configuration settings for the Lue eBook reader."""
2 |
3 | import os
4 | from platformdirs import user_data_dir, user_cache_dir
5 |
6 | # Default TTS model
7 | DEFAULT_TTS_MODEL = "edge"
8 |
9 | # Default voices for TTS models
10 | TTS_VOICES = {
11 | "edge": "en-US-JennyNeural",
12 | "kokoro": "af_heart",
13 | }
14 |
15 | # Language codes for TTS models that require them
16 | TTS_LANGUAGE_CODES = {
17 | "kokoro": "a", # a=English, e=Spanish, j=Japanese, etc.
18 | }
19 |
20 | # TTS model-specific seconds of overlap between sentences (overrides default OVERLAP_SECONDS if specified)
21 | TTS_OVERLAP_SECONDS = {
22 | "kokoro": 0.6,
23 | }
24 |
25 | # Audio processing settings
26 | AUDIO_DATA_DIR = user_cache_dir("lue")
27 | os.makedirs(AUDIO_DATA_DIR, exist_ok=True)
28 | AUDIO_BUFFERS = [os.path.join(AUDIO_DATA_DIR, f"buffer_{i}") for i in range(6)]
29 | MAX_QUEUE_SIZE = 4
30 | OVERLAP_SECONDS = 0.5 # Seconds of overlap between sentences
31 |
32 | # Progress tracking settings
33 | PROGRESS_FILE_DIR = user_data_dir("lue")
34 | os.makedirs(PROGRESS_FILE_DIR, exist_ok=True)
35 |
36 | # General settings
37 | SHOW_ERRORS_ON_EXIT = True
38 |
39 | # PDF parsing settings
40 | PDF_FILTERS_ENABLED = False # You can also enable this with the --filter or -f command-line option
41 | PDF_FILTER_HEADERS = True # Filter headers in top margin of pages
42 | PDF_FILTER_FOOTNOTES = True # Filter page numbers and footnotes in bottom margin of pages
43 |
44 | # PDF filtering thresholds (only used when respective filters are enabled)
45 | PDF_HEADER_MARGIN = 0.1 # Top 10% of page considered header area
46 | PDF_FOOTNOTE_MARGIN = 0.1 # Bottom 10% of page considered footnote area
47 |
48 | # UI settings
49 | SMOOTH_SCROLLING_ENABLED = True # Enable smooth scrolling for keyboard navigation
50 | UI_COMPLEXITY_MODE = 2 # 0=minimal (text only), 1=medium (top bar only), 2=full (default)
51 |
52 | # Highlighting settings
53 | SENTENCE_HIGHLIGHTING_ENABLED = True # Enable sentence-level highlighting
54 | WORD_HIGHLIGHT_MODE = 1 # 0=off, 1=normal highlighting, 2=standout highlighting
55 |
56 | # Keyboard settings
57 | # Can be set to "default", "vim", or a path to a custom keyboard shortcuts JSON file
58 | CUSTOM_KEYBOARD_SHORTCUTS = "default"
59 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # Distribution / packaging
7 | .Python
8 | build/
9 | develop-eggs/
10 | dist/
11 | downloads/
12 | eggs/
13 | .eggs/
14 | lib/
15 | lib64/
16 | parts/
17 | sdist/
18 | var/
19 | wheels/
20 | pip-wheel-metadata/
21 | share/python-wheels/
22 | *.egg-info/
23 | .installed.cfg
24 | *.egg
25 | MANIFEST
26 |
27 | # PyInstaller
28 | *.spec
29 |
30 | # Installer logs
31 | pip-log.txt
32 | pip-delete-this-directory.txt
33 |
34 | # Unit test / coverage reports
35 | htmlcov/
36 | .tox/
37 | .nox/
38 | .coverage
39 | .coverage.*
40 | .cache
41 | nosetests.xml
42 | coverage.xml
43 | *.cover
44 | *.py,cover
45 | .hypothesis/
46 | .pytest_cache/
47 | cover/
48 |
49 | # Translations
50 | *.mo
51 | *.pot
52 |
53 | # Django stuff:
54 | *.log
55 | local_settings.py
56 | db.sqlite3
57 | db.sqlite3-journal
58 |
59 | # Flask stuff:
60 | instance/
61 | .webassets-cache
62 |
63 | # Scrapy stuff:
64 | .scrapy
65 |
66 | # Sphinx documentation
67 | docs/_build/
68 |
69 | # PyBuilder
70 | .pybuilder/
71 | target/
72 |
73 | # Jupyter Notebook
74 | .ipynb_checkpoints
75 |
76 | # IPython
77 | profile_default/
78 | ipython_config.py
79 |
80 | # pyenv
81 | .python-version
82 |
83 | # pipenv
84 | Pipfile.lock
85 |
86 | # poetry
87 | poetry.lock
88 |
89 | # pdm
90 | .pdm.toml
91 |
92 | # PEP 582
93 | __pypackages__/
94 |
95 | # Celery stuff
96 | celerybeat-schedule
97 | celerybeat.pid
98 |
99 | # SageMath parsed files
100 | *.sage.py
101 |
102 | # Environments
103 | .env
104 | .venv
105 | env/
106 | venv/
107 | ENV/
108 | env.bak/
109 | venv.bak/
110 |
111 | # Spyder project settings
112 | .spyderproject
113 | .spyproject
114 |
115 | # Rope project settings
116 | .ropeproject
117 |
118 | # mkdocs documentation
119 | /site
120 |
121 | # mypy
122 | .mypy_cache/
123 | .dmypy.json
124 | dmypy.json
125 |
126 | # Pyre type checker
127 | .pyre/
128 |
129 | # pytype static type analyzer
130 | .pytype/
131 |
132 | # Cython debug symbols
133 | cython_debug/
134 |
135 | # PyCharm
136 | .idea/
137 |
138 | # macOS
139 | .DS_Store
140 | .AppleDouble
141 | .LSOverride
142 |
143 | # Windows
144 | Thumbs.db
145 | ehthumbs.db
146 | Desktop.ini
147 |
148 | # Linux
149 | *~
150 |
151 | # Application data
152 | data/
153 | *.mp3
154 | *.wav
155 |
156 | # IDE
157 | .vscode/
158 | *.swp
159 | *.swo
160 |
161 | # Logs
162 | *.log
163 |
--------------------------------------------------------------------------------
/lue/guide.txt:
--------------------------------------------------------------------------------
1 | Chapter 1: Introduction
2 |
3 | Welcome to Lue, your terminal-based eBook reader with modular text-to-speech support. This document is designed to let you practice navigating your book while hearing instructions read aloud.
4 |
5 |
6 | Chapter 2: Reading Controls
7 |
8 | Now let’s test sentence-level navigation. Press "j" to return to the previous sentence. Press "k" to jump to the next sentence. If you want to jump to the top visible sentence on the screen, press "t" key. Press "h" to go back to the previous paragraph. Press "l" to move to the next paragraph. You can pause and resume the text-to-speech model with "p", Lue remembers exactly where you were.
9 |
10 |
11 | Chapter 3: Page and Scroll Controls
12 |
13 | You can scroll through the book without losing the highlighted sentence being read. Do that by pressing "i" to move page up, and "m" to move page down. For smaller adjustments, use "u" to scroll up or "n" to scroll down a row. Navigating with these keys, the mouse wheel, or a trackpad automatically switches Lue to manual mode. In this mode, pressing "a", returns you back to the highlighted sentence and reactivates auto-scroll mode. Auto-scroll works seamlessly with TTS, keeping your reading flow smooth and uninterrupted. "y" takes you to the beginning, and "b" takes you to the end of the book.
14 |
15 |
16 | Chapter 4: Mouse Actions
17 |
18 | If your terminal supports mouse input, you can click on any sentence to jump to it instantly. Use the mouse wheel or trackpad to scroll through the text, or click on the progress bar to skip directly to that position in the book.
19 |
20 |
21 | Chapter 5: Speed Adjustment
22 |
23 | Lue allows you to adjust the text-to-speech playback speed to match your listening preference. You can increase the speed up to 3x faster. To increase the playback speed, press the period key. Each press will increase the speed incrementally. To decrease the playback speed, press the comma key. Each press will decrease the speed back down to the normal 1x speed.
24 |
25 |
26 | Chapter 6: Highlighting Controls
27 |
28 | There are two levels of text highlighting to help you follow along with the narration: sentence-level highlighting and word-level highlighting. To toggle sentence highlighting on or off, press the "s" key. To toggle word highlighting on or off, press the "w" key. You can use both highlighting modes simultaneously, or disable either one based on your preference.
29 |
30 |
31 | Chapter 7: Ending the Session
32 |
33 | When you are ready to stop reading, press "q" to quit. Your place and your reading mode will be saved automatically, so you can resume later without losing your spot.
34 |
35 |
36 | Enjoy your reading!
--------------------------------------------------------------------------------
/lue/tts_manager.py:
--------------------------------------------------------------------------------
1 | """TTS model discovery and management for the Lue eBook reader."""
2 |
3 | import importlib
4 | import inspect
5 | import logging
6 | from pathlib import Path
7 | from rich.console import Console
8 | from .tts.base import TTSBase
9 | from . import config
10 |
11 |
12 | class TTSManager:
13 | """
14 | Discovers, loads, and manages available TTS models.
15 |
16 | This class automatically discovers TTS models in the tts/ directory
17 | and provides a unified interface for creating model instances.
18 | """
19 |
20 | def __init__(self):
21 | """Initialize the TTS manager and discover available models."""
22 | self._models = {}
23 | self._discover_models()
24 |
25 | def _discover_models(self):
26 | """
27 | Dynamically discover TTS models from the tts/ directory.
28 |
29 | Looks for Python files matching the pattern '*_tts.py' and attempts
30 | to load classes that inherit from TTSBase.
31 | """
32 | tts_dir = Path(__file__).parent / "tts"
33 | for file_path in tts_dir.glob("*_tts.py"):
34 | module_name = file_path.stem
35 | try:
36 | module = importlib.import_module(f".tts.{module_name}", package="lue")
37 | for name, obj in inspect.getmembers(module, inspect.isclass):
38 | if (issubclass(obj, TTSBase) and
39 | not inspect.isabstract(obj) and
40 | obj is not TTSBase):
41 | model_name = module_name.replace("_tts", "")
42 | self._models[model_name] = obj
43 | logging.info(f"Discovered TTS model: {model_name}")
44 | break
45 | except Exception as e:
46 | logging.error(f"Failed to load TTS module {module_name}: {e}", exc_info=True)
47 |
48 | def get_available_tts_names(self) -> list[str]:
49 | """
50 | Get a list of available TTS model names.
51 |
52 | Returns:
53 | list[str]: Sorted list of model names, with the default model first.
54 | """
55 | names = sorted(self._models.keys())
56 | # Prioritize the default TTS model
57 | default_model = get_default_tts_model_name(names)
58 | if default_model in names:
59 | names.remove(default_model)
60 | names.insert(0, default_model)
61 | return names
62 |
63 | def create_model(self, name: str, console: Console, voice: str = None, lang: str = None) -> TTSBase | None:
64 | """
65 | Create an instance of the specified TTS model.
66 |
67 | Args:
68 | name: Name of the TTS model to create
69 | console: Rich console instance for user feedback
70 | voice: Optional voice for the TTS model
71 | lang: Optional language for the TTS model
72 |
73 | Returns:
74 | TTSBase: Model instance, or None if model not found
75 | """
76 | model_class = self._models.get(name)
77 | if model_class:
78 | return model_class(console, voice=voice, lang=lang)
79 | logging.error(f"TTS model '{name}' not found.")
80 | return None
81 |
82 |
83 | def get_default_tts_model_name(available_models: list[str]) -> str:
84 | """
85 | Determine the default TTS model name from the available list.
86 |
87 | Uses the model specified in config.py, falling back to the first available
88 | model if the configured one is not found.
89 |
90 | Args:
91 | available_models: List of available model names
92 |
93 | Returns:
94 | str: Name of the default TTS model
95 | """
96 | if config.DEFAULT_TTS_MODEL in available_models:
97 | return config.DEFAULT_TTS_MODEL
98 | return available_models[0] if available_models else ""
--------------------------------------------------------------------------------
/lue/tts/edge_tts.py:
--------------------------------------------------------------------------------
1 | import os
2 | import asyncio
3 | import logging
4 | from rich.console import Console
5 |
6 | from .base import TTSBase
7 | from .. import config
8 |
9 | class EdgeTTS(TTSBase):
10 | """TTS implementation for Microsoft Edge's online TTS service."""
11 |
12 | @property
13 | def name(self) -> str:
14 | return "edge"
15 |
16 | @property
17 | def output_format(self) -> str:
18 | return "mp3"
19 |
20 | def __init__(self, console: Console, voice: str = None, lang: str = None):
21 | super().__init__(console, voice, lang)
22 | self.edge_tts = None
23 | if self.voice is None:
24 | self.voice = config.TTS_VOICES.get(self.name)
25 |
26 | async def initialize(self) -> bool:
27 | """Checks if the edge-tts library is available."""
28 | try:
29 | import edge_tts
30 | self.edge_tts = edge_tts
31 | self.initialized = True
32 | self.console.print("[green]Edge TTS model is available.[/green]")
33 | return True
34 | except ImportError:
35 | self.console.print("[bold red]Error: 'edge-tts' package not found.[/bold red]")
36 | self.console.print("[yellow]Please run 'pip install edge-tts' to use this TTS model.[/yellow]")
37 | logging.error("'edge-tts' is not installed.")
38 | return False
39 |
40 | async def get_raw_timing_data(self, text: str, output_path: str):
41 | """
42 | Get raw word timing data from Edge TTS.
43 |
44 | Returns:
45 | List of (word, start_time, end_time) tuples with raw timing data from Edge TTS
46 | """
47 | if not self.initialized:
48 | raise RuntimeError("Edge TTS has not been initialized.")
49 |
50 | try:
51 | communicate = self.edge_tts.Communicate(text, self.voice, boundary="WordBoundary")
52 |
53 | # Collect word timing information
54 | word_timings = []
55 | audio_chunks = []
56 |
57 | async for chunk in communicate.stream():
58 | if chunk['type'] == 'WordBoundary':
59 | # Convert from 100-nanosecond units to seconds
60 | start_time = chunk['offset'] / 10000000.0
61 | end_time = (chunk['offset'] + chunk['duration']) / 10000000.0
62 | word_timings.append((chunk['text'], start_time, end_time))
63 | elif chunk['type'] == 'audio':
64 | audio_chunks.append(chunk['data'])
65 |
66 | # Save audio to file
67 | with open(output_path, 'wb') as f:
68 | for chunk in audio_chunks:
69 | f.write(chunk)
70 |
71 | return word_timings
72 |
73 | except Exception as e:
74 | logging.error(f"Edge TTS audio generation failed for text: '{text[:50]}...'", exc_info=True)
75 | raise e
76 |
77 | async def generate_audio_with_timing(self, text: str, output_path: str):
78 | """
79 | Generate audio with timing using the centralized timing calculator.
80 |
81 | This method leverages Edge TTS's precise word boundary information
82 | through get_raw_timing_data() and processes it with the timing calculator.
83 | """
84 | # Get raw timing data (which also generates the audio)
85 | raw_timings = await self.get_raw_timing_data(text, output_path)
86 |
87 | # Get actual audio duration
88 | try:
89 | from .. import audio
90 | except ImportError:
91 | import sys
92 | import os
93 | sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
94 | import audio
95 | duration = await audio.get_audio_duration(output_path)
96 |
97 | # Process timing data using the centralized calculator
98 | try:
99 | from ..timing_calculator import process_tts_timing_data
100 | except ImportError:
101 | import sys
102 | import os
103 | sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
104 | import timing_calculator
105 | process_tts_timing_data = timing_calculator.process_tts_timing_data
106 | return process_tts_timing_data(text, raw_timings, duration)
107 |
108 | async def generate_audio(self, text: str, output_path: str):
109 | """Generates audio from text using edge-tts and saves it to a file."""
110 | if not self.initialized:
111 | raise RuntimeError("Edge TTS has not been initialized.")
112 | try:
113 | communicate = self.edge_tts.Communicate(text, self.voice)
114 | await communicate.save(output_path)
115 | except Exception as e:
116 | logging.error(f"Edge TTS audio generation failed for text: '{text[:50]}...'", exc_info=True)
117 | raise e
118 |
119 | async def warm_up(self):
120 | """Warms up the TTS model by making a short request."""
121 | if not self.initialized:
122 | return
123 |
124 | self.console.print("[bold cyan]Warming up the Edge TTS model...[/bold cyan]")
125 | warmup_file = os.path.join(config.AUDIO_DATA_DIR, f".warmup_edge.{self.output_format}")
126 | try:
127 | await self.generate_audio("Ready.", warmup_file)
128 | self.console.print("[green]Edge TTS model is ready.[/green]")
129 | except Exception as e:
130 | self.console.print(f"[bold yellow]Warning: Edge model warm-up failed.[/bold yellow]")
131 | self.console.print(f"[yellow]This may indicate a network issue or an invalid voice name: {self.voice}[/yellow]")
132 | logging.warning(f"Edge TTS model warm-up failed: {e}", exc_info=True)
133 | finally:
134 | if os.path.exists(warmup_file):
135 | try:
136 | os.remove(warmup_file)
137 | except OSError:
138 | pass
--------------------------------------------------------------------------------
/lue/tts/base.py:
--------------------------------------------------------------------------------
1 | """Abstract base class for TTS models in the Lue eBook reader."""
2 |
3 | from abc import ABC, abstractmethod
4 | from rich.console import Console
5 |
6 |
7 | class TTSBase(ABC):
8 | """
9 | Abstract base class for all TTS models.
10 |
11 | This class defines the interface that all TTS models must implement
12 | to be compatible with the Lue eBook reader.
13 | """
14 |
15 | def __init__(self, console: Console, voice: str = None, lang: str = None):
16 | """
17 | Initialize the TTS model.
18 |
19 | Args:
20 | console: Rich console instance for user feedback
21 | voice: Optional voice for the TTS model
22 | lang: Optional language for the TTS model
23 | """
24 | self.console = console
25 | self.voice = voice
26 | self.lang = lang
27 | self.initialized = False
28 |
29 | @property
30 | @abstractmethod
31 | def name(self) -> str:
32 | """
33 | Get the unique identifier for this TTS model.
34 |
35 | Returns:
36 | str: Model name (e.g., 'edge', 'kokoro')
37 | """
38 | pass
39 |
40 | @property
41 | @abstractmethod
42 | def output_format(self) -> str:
43 | """
44 | Get the audio format this model produces.
45 |
46 | Returns:
47 | str: File extension without dot (e.g., 'mp3', 'wav')
48 | """
49 | pass
50 |
51 | @abstractmethod
52 | async def initialize(self) -> bool:
53 | """
54 | Initialize the TTS model asynchronously.
55 |
56 | This method should:
57 | - Check for required dependencies
58 | - Load models if necessary
59 | - Handle ImportErrors gracefully
60 | - Set self.initialized = True on success
61 |
62 | Returns:
63 | bool: True if initialization succeeded, False otherwise
64 | """
65 | pass
66 |
67 | @abstractmethod
68 | async def generate_audio(self, text: str, output_path: str):
69 | """
70 | Generate audio from text and save to file.
71 |
72 | Args:
73 | text: Text to convert to speech
74 | output_path: Full path where audio file should be saved
75 |
76 | Raises:
77 | RuntimeError: If model is not initialized
78 | Exception: If audio generation fails
79 | """
80 | pass
81 |
82 | async def generate_audio_with_timing(self, text: str, output_path: str):
83 | """
84 | Generate audio from text and save to file, returning processed timing information.
85 |
86 | This method now uses the centralized timing calculator to process timing data.
87 | TTS implementations should override get_raw_timing_data() to provide engine-specific
88 | timing information, while this method handles all the processing and adjustments.
89 |
90 | Args:
91 | text: Text to convert to speech
92 | output_path: Full path where audio file should be saved
93 |
94 | Returns:
95 | dict: Processed timing information containing:
96 | - word_timings: List of (word, start_time, end_time) tuples
97 | - speech_duration: Duration of speech content
98 | - total_duration: Total audio duration
99 | - word_mapping: Mapping from original words to TTS timings
100 |
101 | Raises:
102 | RuntimeError: If model is not initialized
103 | Exception: If audio generation fails
104 | """
105 | # Generate audio first
106 | await self.generate_audio(text, output_path)
107 |
108 | # Get raw timing data from the TTS implementation
109 | raw_timings = await self.get_raw_timing_data(text, output_path)
110 |
111 | # Get actual audio duration
112 | try:
113 | from .. import audio
114 | except ImportError:
115 | # Handle case when running tests or imports from different context
116 | import sys
117 | import os
118 | sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
119 | import audio
120 | duration = await audio.get_audio_duration(output_path)
121 |
122 | # Process timing data using the centralized calculator
123 | try:
124 | from ..timing_calculator import process_tts_timing_data
125 | except ImportError:
126 | # Handle case when running tests or imports from different context
127 | import sys
128 | import os
129 | sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
130 | import timing_calculator
131 | process_tts_timing_data = timing_calculator.process_tts_timing_data
132 | return process_tts_timing_data(text, raw_timings, duration)
133 |
134 | async def get_raw_timing_data(self, text: str, output_path: str):
135 | """
136 | Get raw timing data from the TTS engine.
137 |
138 | This method should be overridden by TTS implementations that can provide
139 | precise timing information. The default implementation returns empty list,
140 | which will cause the timing calculator to estimate timings.
141 |
142 | Args:
143 | text: Text that was converted to speech
144 | output_path: Path to the generated audio file
145 |
146 | Returns:
147 | List of (word, start_time, end_time) tuples with raw timing data from TTS engine,
148 | or empty list if no timing data is available
149 | """
150 | return []
151 |
152 | async def warm_up(self):
153 | """
154 | Warm up the model to reduce initial latency.
155 |
156 | This is called once after initialization to prepare the model
157 | for faster subsequent audio generation.
158 | """
159 | pass
160 |
161 | def get_overlap_seconds(self) -> float | None:
162 | """
163 | Get the TTS-specific overlap seconds for this model.
164 |
165 | Returns:
166 | float: Overlap seconds specific to this TTS model, or None to use default
167 | """
168 | from .. import config
169 | return config.TTS_OVERLAP_SECONDS.get(self.name)
--------------------------------------------------------------------------------
/lue/progress_manager.py:
--------------------------------------------------------------------------------
1 | """Reading progress management for the Lue eBook reader."""
2 |
3 | import os
4 | import json
5 | import re
6 | import glob
7 | from . import config
8 |
9 |
10 | def get_progress_file_path(book_title):
11 | """
12 | Generate the file path for storing reading progress.
13 |
14 | Args:
15 | book_title: Title of the book
16 |
17 | Returns:
18 | str: Full path to the progress file
19 | """
20 | safe_title = re.sub(r'[^A-Za-z0-9]+', '', book_title)
21 | return os.path.join(config.PROGRESS_FILE_DIR, f"{safe_title}.progress.json")
22 |
23 | def load_progress(progress_file):
24 | """
25 | Load basic reading progress from file.
26 |
27 | Args:
28 | progress_file: Path to the progress file
29 |
30 | Returns:
31 | tuple: (chapter_idx, paragraph_idx, sentence_idx)
32 | """
33 | if os.path.exists(progress_file):
34 | with open(progress_file, 'r', encoding='utf-8') as f:
35 | try:
36 | data = json.load(f)
37 | return data.get("c", 0), data.get("p", 0), data.get("s", 0)
38 | except json.JSONDecodeError:
39 | return 0, 0, 0
40 | return 0, 0, 0
41 |
42 | def load_extended_progress(progress_file):
43 | """
44 | Load extended reading progress including UI state.
45 |
46 | Args:
47 | progress_file: Path to the progress file
48 |
49 | Returns:
50 | dict: Progress data with reading position and UI state
51 | """
52 | default_progress = {
53 | "c": 0, "p": 0, "s": 0,
54 | "scroll_offset": 0,
55 | "tts_enabled": True,
56 | "auto_scroll_enabled": True,
57 | "manual_scroll_anchor": None,
58 | "playback_speed": 1.0
59 | }
60 |
61 | if not os.path.exists(progress_file):
62 | return default_progress
63 |
64 | try:
65 | with open(progress_file, 'r', encoding='utf-8') as f:
66 | data = json.load(f)
67 | return {
68 | "c": data.get("c", 0),
69 | "p": data.get("p", 0),
70 | "s": data.get("s", 0),
71 | "scroll_offset": data.get("scroll_offset", 0),
72 | "tts_enabled": data.get("tts_enabled", True),
73 | "auto_scroll_enabled": data.get("auto_scroll_enabled", True),
74 | "manual_scroll_anchor": data.get("manual_scroll_anchor", None),
75 | "playback_speed": data.get("playback_speed", 1.0)
76 | }
77 | except (json.JSONDecodeError, IOError):
78 | return default_progress
79 |
80 | def save_progress(progress_file, chapter_idx, paragraph_idx, sentence_idx):
81 | """
82 | Save basic reading progress to file.
83 |
84 | Args:
85 | progress_file: Path to the progress file
86 | chapter_idx: Current chapter index
87 | paragraph_idx: Current paragraph index
88 | sentence_idx: Current sentence index
89 | """
90 | progress = {"c": chapter_idx, "p": paragraph_idx, "s": sentence_idx}
91 | with open(progress_file, 'w', encoding='utf-8') as f:
92 | json.dump(progress, f, indent=2)
93 |
94 | def save_extended_progress(progress_file, chapter_idx, paragraph_idx, sentence_idx,
95 | scroll_offset, tts_enabled, auto_scroll_enabled, manual_scroll_anchor=None, original_file_path=None, playback_speed=1.0, percentage=0.0):
96 | """
97 | Save extended reading progress including UI state.
98 |
99 | Args:
100 | progress_file: Path to the progress file
101 | chapter_idx: Current chapter index
102 | paragraph_idx: Current paragraph index
103 | sentence_idx: Current sentence index
104 | scroll_offset: Current scroll position
105 | tts_enabled: Whether TTS is enabled
106 | auto_scroll_enabled: Whether auto-scroll is enabled
107 | manual_scroll_anchor: Manual scroll anchor position (optional)
108 | original_file_path: Original path to the eBook file (optional)
109 | playback_speed: Audio playback speed
110 | percentage: Completion percentage (0.0 to 100.0)
111 | """
112 | progress = {
113 | "c": chapter_idx,
114 | "p": paragraph_idx,
115 | "s": sentence_idx,
116 | "scroll_offset": float(scroll_offset),
117 | "tts_enabled": bool(tts_enabled),
118 | "auto_scroll_enabled": bool(auto_scroll_enabled),
119 | "playback_speed": float(playback_speed),
120 | "completion_percentage": float(percentage)
121 | }
122 | if manual_scroll_anchor:
123 | progress["manual_scroll_anchor"] = manual_scroll_anchor
124 | if original_file_path:
125 | progress["original_file_path"] = original_file_path
126 |
127 | # Save percentage if provided (default to 0.0 if not in args, but we will add it to args)
128 | # Note: The function signature will be updated in the next step to include percentage.
129 | # For now, we'll just add it if passed in kwargs or update the signature.
130 | # Actually, I should update the signature in the same edit.
131 |
132 | with open(progress_file, 'w', encoding='utf-8') as f:
133 | json.dump(progress, f, indent=2)
134 |
135 | def get_recent_books(limit=5):
136 | """
137 | Get a list of recently read books.
138 |
139 | Args:
140 | limit: Maximum number of books to return
141 |
142 | Returns:
143 | list: List of dicts containing title, path, and percentage
144 | """
145 | progress_files = glob.glob(os.path.join(config.PROGRESS_FILE_DIR, "*.progress.json"))
146 |
147 | # Sort by modification time (newest first)
148 | progress_files.sort(key=os.path.getmtime, reverse=True)
149 |
150 | recent_books = []
151 | for pf in progress_files:
152 | if len(recent_books) >= limit:
153 | break
154 |
155 | try:
156 | with open(pf, 'r', encoding='utf-8') as f:
157 | data = json.load(f)
158 |
159 | original_path = data.get("original_file_path")
160 | if not original_path or not os.path.exists(original_path):
161 | continue
162 |
163 | # Derive title from filename if not stored (we don't store title currently, so use filename)
164 | title = os.path.basename(original_path)
165 | # Remove extension
166 | title = os.path.splitext(title)[0]
167 |
168 | percentage = data.get("completion_percentage", 0.0)
169 |
170 | recent_books.append({
171 | "title": title,
172 | "path": original_path,
173 | "percentage": percentage
174 | })
175 |
176 | except (json.JSONDecodeError, IOError):
177 | continue
178 |
179 | return recent_books
180 |
181 | def validate_and_set_progress(chapters, progress_file, c, p, s):
182 | """
183 | Validate reading progress against document structure.
184 |
185 | Args:
186 | chapters: Document chapters structure
187 | progress_file: Path to progress file (for cleanup if invalid)
188 | c: Chapter index to validate
189 | p: Paragraph index to validate
190 | s: Sentence index to validate
191 |
192 | Returns:
193 | tuple: Valid (chapter_idx, paragraph_idx, sentence_idx)
194 | """
195 | try:
196 | paragraph = chapters[c][p]
197 | sentences = re.split(r'(?<=[.!?])\s+', paragraph)
198 | _ = sentences[s] # Test if sentence exists
199 | return c, p, s
200 | except IndexError:
201 | # Invalid progress, reset to beginning
202 | if os.path.exists(progress_file):
203 | os.remove(progress_file)
204 | return 0, 0, 0
205 |
206 | def find_most_recent_book():
207 | """
208 | Find the most recently updated progress file and return the original file path.
209 |
210 | Returns:
211 | str or None: Path to the most recently read book, or None if no books found
212 | """
213 | progress_files = glob.glob(os.path.join(config.PROGRESS_FILE_DIR, "*.progress.json"))
214 |
215 | if not progress_files:
216 | return None
217 |
218 | # Find the most recently modified progress file
219 | most_recent_file = max(progress_files, key=os.path.getmtime)
220 |
221 | try:
222 | with open(most_recent_file, 'r', encoding='utf-8') as f:
223 | data = json.load(f)
224 | original_path = data.get("original_file_path")
225 |
226 | # Check if the original file still exists
227 | if original_path and os.path.exists(original_path):
228 | return original_path
229 |
230 | except (json.JSONDecodeError, IOError):
231 | pass
232 |
233 | return None
--------------------------------------------------------------------------------
/lue/input_handler.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import select
3 | import asyncio
4 | import subprocess
5 | import json
6 | import os
7 |
8 | # Default keyboard shortcuts
9 | DEFAULT_KEYBOARD_SHORTCUTS = {
10 | "navigation": {
11 | "next_paragraph": "l",
12 | "prev_paragraph": "h",
13 | "next_sentence": "k",
14 | "prev_sentence": "j",
15 | "scroll_page_up": "i",
16 | "scroll_page_down": "m",
17 | "scroll_up": "u",
18 | "scroll_down": "n",
19 | "move_to_top_visible": "t",
20 | "move_to_beginning": "y",
21 | "move_to_end": "b"
22 | },
23 | "tts_controls": {
24 | "play_pause": "p",
25 | "decrease_speed": ",",
26 | "increase_speed": ".",
27 | "toggle_sentence_highlight": "s",
28 | "toggle_word_highlight": "w"
29 | },
30 | "display_controls": {
31 | "toggle_auto_scroll": "a",
32 | "cycle_ui_complexity": "v"
33 | },
34 | "application": {
35 | "quit": "q"
36 | }
37 | }
38 |
39 | # Global variable to store loaded keyboard shortcuts
40 | KEYBOARD_SHORTCUTS = DEFAULT_KEYBOARD_SHORTCUTS
41 |
42 | def load_keyboard_shortcuts(file_path=None):
43 | """Load keyboard shortcuts from a JSON file or use defaults.
44 |
45 | If file_path is None, the function will attempt to load from the default locations.
46 | """
47 | global KEYBOARD_SHORTCUTS
48 |
49 | # If no file path provided, use the default file
50 | if not file_path:
51 | file_path = os.path.join(os.path.dirname(__file__), 'keys_default.json')
52 |
53 | try:
54 | with open(file_path, 'r') as f:
55 | KEYBOARD_SHORTCUTS = json.load(f)
56 | except Exception:
57 | # Fallback to default shortcuts if file cannot be loaded
58 | KEYBOARD_SHORTCUTS = DEFAULT_KEYBOARD_SHORTCUTS
59 |
60 | def process_input(reader):
61 | """Process user input from stdin."""
62 | try:
63 | if select.select([sys.stdin], [], [], 0)[0]:
64 | data = sys.stdin.read(1)
65 |
66 | if not data:
67 | return
68 |
69 | if data == '\x1b':
70 | reader.mouse_sequence_buffer = data
71 | reader.mouse_sequence_active = True
72 | return
73 | elif reader.mouse_sequence_active:
74 | reader.mouse_sequence_buffer += data
75 |
76 | if reader.mouse_sequence_buffer.startswith('\x1b[<') and (data == 'M' or data == 'm'):
77 | sequence = reader.mouse_sequence_buffer
78 | reader.mouse_sequence_buffer = ''
79 | reader.mouse_sequence_active = False
80 |
81 | if len(sequence) > 3:
82 | mouse_part = sequence[3:]
83 | if mouse_part.endswith('M') or mouse_part.endswith('m'):
84 | try:
85 | parts = mouse_part[:-1].split(';')
86 | if len(parts) >= 3:
87 | button = int(parts[0])
88 | x_pos = int(parts[1])
89 | y_pos = int(parts[2])
90 |
91 | if mouse_part.endswith('M'):
92 | if button == 0:
93 | if reader._is_click_on_progress_bar(x_pos, y_pos):
94 | if reader._handle_progress_bar_click(x_pos, y_pos):
95 | return
96 |
97 | if not reader._is_click_on_text(x_pos, y_pos):
98 | return
99 |
100 | # Cancel any pending restart task before killing audio
101 | if hasattr(reader, 'pending_restart_task') and reader.pending_restart_task and not reader.pending_restart_task.done():
102 | reader.pending_restart_task.cancel()
103 |
104 | _kill_audio_immediately(reader)
105 | reader.loop.call_soon_threadsafe(reader._post_command_sync, ('click_jump', (x_pos, y_pos)))
106 | elif button == 64:
107 | if reader.auto_scroll_enabled:
108 | reader.auto_scroll_enabled = False
109 | reader.loop.call_soon_threadsafe(reader._post_command_sync, 'wheel_scroll_up')
110 | elif button == 65:
111 | if reader.auto_scroll_enabled:
112 | reader.auto_scroll_enabled = False
113 | reader.loop.call_soon_threadsafe(reader._post_command_sync, 'wheel_scroll_down')
114 | return
115 | except (ValueError, IndexError):
116 | pass
117 | return
118 |
119 | elif reader.mouse_sequence_buffer.startswith('\x1b[') and len(reader.mouse_sequence_buffer) >= 3 and data in 'ABCD':
120 | sequence = reader.mouse_sequence_buffer
121 | reader.mouse_sequence_buffer = ''
122 | reader.mouse_sequence_active = False
123 |
124 | if reader.show_recent_menu:
125 | return
126 |
127 | _kill_audio_immediately(reader)
128 | cmd = None
129 | if data == 'C':
130 | cmd = 'next_sentence'
131 | elif data == 'D':
132 | cmd = 'prev_sentence'
133 | elif data == 'B':
134 | cmd = 'next_paragraph'
135 | elif data == 'A':
136 | cmd = 'prev_paragraph'
137 |
138 | if cmd:
139 | reader.loop.call_soon_threadsafe(reader._post_command_sync, cmd)
140 | return
141 |
142 | return
143 |
144 | reader.mouse_sequence_buffer = ''
145 | reader.mouse_sequence_active = False
146 |
147 | # Get keyboard shortcuts
148 | nav_shortcuts = KEYBOARD_SHORTCUTS.get("navigation", {})
149 | tts_shortcuts = KEYBOARD_SHORTCUTS.get("tts_controls", {})
150 | display_shortcuts = KEYBOARD_SHORTCUTS.get("display_controls", {})
151 | app_shortcuts = KEYBOARD_SHORTCUTS.get("application", {})
152 |
153 | # Map input data to commands using loaded shortcuts
154 | if data == app_shortcuts.get("quit", "q"):
155 | reader.running = False
156 | reader.command_received_event.set()
157 | return
158 |
159 | cmd = None
160 | if data == app_shortcuts.get("toggle_recent_menu", "r"):
161 | cmd = 'toggle_recent_menu'
162 | elif data == app_shortcuts.get("select_menu_item", "\n") or data == '\r':
163 | cmd = 'select_menu_item'
164 | elif data == tts_shortcuts.get("play_pause", "p"):
165 | cmd = 'pause'
166 | elif data == nav_shortcuts.get("prev_paragraph", "h"):
167 | cmd = 'prev_paragraph'
168 | elif data == nav_shortcuts.get("prev_sentence", "j"):
169 | cmd = 'prev_sentence'
170 | elif data == nav_shortcuts.get("next_sentence", "k"):
171 | cmd = 'next_sentence'
172 | elif data == nav_shortcuts.get("next_paragraph", "l"):
173 | cmd = 'next_paragraph'
174 | elif data == nav_shortcuts.get("scroll_page_up", "i"):
175 | cmd = 'scroll_page_up'
176 | elif data == nav_shortcuts.get("scroll_page_down", "m"):
177 | cmd = 'scroll_page_down'
178 | elif data == nav_shortcuts.get("scroll_up", "u"):
179 | cmd = 'scroll_up'
180 | elif data == nav_shortcuts.get("scroll_down", "n"):
181 | cmd = 'scroll_down'
182 | elif data == display_shortcuts.get("toggle_auto_scroll", "a"):
183 | cmd = 'toggle_auto_scroll'
184 | elif data == nav_shortcuts.get("move_to_top_visible", "t"):
185 | cmd = 'move_to_top_visible'
186 | elif data == nav_shortcuts.get("move_to_beginning", "y"):
187 | cmd = 'move_to_beginning'
188 | elif data == nav_shortcuts.get("move_to_end", "b"):
189 | cmd = 'move_to_end'
190 | elif data == tts_shortcuts.get("decrease_speed", ","):
191 | cmd = 'decrease_speed'
192 | elif data == tts_shortcuts.get("increase_speed", "."):
193 | cmd = 'increase_speed'
194 | elif data == tts_shortcuts.get("toggle_sentence_highlight", "s"):
195 | cmd = 'toggle_sentence_highlight'
196 | elif data == tts_shortcuts.get("toggle_word_highlight", "w"):
197 | cmd = 'toggle_word_highlight'
198 | elif data == display_shortcuts.get("cycle_ui_complexity", "v"):
199 | cmd = 'cycle_ui_complexity'
200 |
201 | if cmd:
202 | reader.loop.call_soon_threadsafe(reader._post_command_sync, cmd)
203 |
204 | except Exception:
205 | pass
206 |
207 | def _kill_audio_immediately(reader):
208 | """Kill audio playback immediately."""
209 | for process in reader.playback_processes[:]:
210 | try:
211 | process.kill()
212 | except (ProcessLookupError, AttributeError):
213 | pass
214 | try:
215 | subprocess.run(['pkill', '-f', 'ffplay'], check=False,
216 | stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
217 | except (subprocess.CalledProcessError, FileNotFoundError):
218 | pass
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |

4 |
5 | ### Lue - Terminal eBook Reader with Text-to-Speech
6 | [](https://www.gnu.org/licenses/gpl-3.0)
7 | [](https://www.python.org/downloads/)
8 | [-86c9fa)](https://github.com/superstarryeyes/lue)
9 | [](https://github.com/superstarryeyes/lue)
10 | [](https://discord.gg/z8sE2gnMNk)
11 |
12 | [Features](#-features) • [Quick Start](#-quick-start-macos-and-linux) • [Installation](#-installation-macos-linux-and-windows) • [Usage](#-usage) • [Customize](#️-customize) • [Development](#-development)
13 |
14 |

15 |
16 |
17 |
18 | ---
19 |
20 | ## ✨ Features
21 |
22 | | **Feature** | **Description** |
23 | | --------------------------------------- | ---------------------------------------------------------------------------------------------- |
24 | | **📖 Multi-Format Support** | Support for EPUB, PDF, TXT, DOCX, DOC, HTML, RTF, and Markdown with seamless format detection |
25 | | **👄 Modular TTS System** | Edge TTS (default) and Kokoro TTS (local/offline) with extensible architecture for new models |
26 | | **🌍 Cross-Platform & Multilingual** | Full support for macOS, Linux, Windows (via WSL) with 100+ languages and consistent global experience |
27 | | **🎛️ Speed Adjustment** | Adjust text-to-speech playback speed from 1x to 3x for personalized listening experience |
28 | | **🎯 Auto-Scroll & Precise Word Highlighting** | Automatic scrolling and word-level highlighting synchronized with actual speech, improving focus and concentration |
29 | | **💾 Smart Persistence** | Automatic progress saving, state restoration, and cross-session continuity for seamless reading|
30 | | **⚡️ Fast Navigation** | Intuitive shortcuts, flexible controls, mouse support and optional smooth scrolling for efficient book navigation |
31 | | **⚙️ Extensive Customization** | Fully customizable keyboard layouts (including Vim-style bindings), adjustable UI elements, colors, and display modes|
32 |
33 | ---
34 |
35 | ## 🚀 Quick Start (macOS and Linux)
36 |
37 | > **Want to try Lue right away?** Follow these simple steps:
38 |
39 | ```bash
40 | # 1. Install FFmpeg (required for audio processing)
41 | # macOS
42 | brew install ffmpeg
43 | # Ubuntu/Debian
44 | sudo apt install ffmpeg
45 |
46 | # 2. Install the latest version from PyPI
47 | pip install lue-reader
48 |
49 | # 3. Practice using Lue with the navigation guide
50 | lue --guide
51 |
52 | # 4. Start reading!
53 | lue path/to/your/book.epub
54 | ```
55 |
56 | > **📝 Note:** Quick start uses Edge TTS (requires internet). For offline capabilities, see [full installation](#-installation-macos-linux-and-windows).
57 |
58 | ---
59 |
60 | ## 📦 Installation (macOS, Linux and Windows)
61 |
62 | ### Prerequisites
63 |
64 | #### Core Requirements
65 | - **FFmpeg** - Audio processing (required)
66 |
67 | #### Optional Dependencies
68 | - **espeak** - Kokoro TTS support
69 |
70 | #### macOS (Homebrew)
71 | ```bash
72 | brew install ffmpeg
73 | # Optional
74 | brew install espeak
75 | ```
76 |
77 | #### Ubuntu/Debian
78 | ```bash
79 | sudo apt update && sudo apt install ffmpeg
80 | # Optional
81 | sudo apt install espeak
82 | ```
83 |
84 | #### Arch Linux (AUR)
85 | ```bash
86 | # Using yay
87 | yay -S lue-reader-git
88 |
89 | # Or using paru
90 | paru -S lue-reader-git
91 | ```
92 |
93 | #### Windows
94 | ```bash
95 | # 1. Install WSL
96 | # Open PowerShell as Administrator:
97 | wsl --install
98 |
99 | # 2. Restart your PC if prompted, then launch Ubuntu from Start Menu
100 |
101 | # 3. Inside Ubuntu terminal:
102 | sudo apt update && sudo apt upgrade -y
103 | sudo apt install ffmpeg python3 python3-pip -y
104 | # Optional
105 | sudo apt install espeak
106 | ```
107 |
108 | ### Install Lue
109 |
110 | #### Standard Installation
111 |
112 | ```bash
113 | # 1. Clone repository
114 | git clone https://github.com/superstarryeyes/lue.git
115 | cd lue
116 |
117 | # 2. Install dependencies
118 | pip install -r requirements.txt
119 |
120 | # 3. Install Lue
121 | pip install .
122 | ```
123 |
124 | #### Enable Kokoro TTS (Optional)
125 |
126 | For local/offline TTS capabilities:
127 |
128 | ```bash
129 | # 1. Edit requirements.txt - uncomment Kokoro packages:
130 | kokoro>=0.9.4
131 | soundfile>=0.13.1
132 | huggingface-hub>=0.34.4
133 |
134 | # 2. Install PyTorch
135 | # CPU version:
136 | pip install torch torchvision torchaudio
137 | # GPU version (CUDA):
138 | pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
139 |
140 | # 3. Install updated requirements
141 | pip install -r requirements.txt
142 |
143 | # 4. Install Lue
144 | pip install .
145 | ```
146 |
147 | ---
148 |
149 | ## 💻 Usage
150 |
151 | ### Basic Commands
152 |
153 | ```bash
154 | # Start with default TTS
155 | lue path/to/your/book.epub
156 |
157 | # Launch without arguments to open the last book you were reading
158 | lue
159 |
160 | # Practice Lue default keys with the navigation guide
161 | lue --guide
162 |
163 | # View available command line options
164 | lue --help
165 |
166 | # Use specific TTS model (edge/kokoro/none)
167 | lue --tts kokoro path/to/your/book.epub
168 |
169 | # Use a specific voice (full list at VOICES.md)
170 | lue --voice "en-US-AriaNeural" path/to/your/book.epub
171 |
172 | # Set the speech speed (e.g., 1.5x)
173 | lue --speed 1.5 path/to/your/book.epub
174 |
175 | # Specify a language code if needed
176 | lue --lang a path/to/your/book.epub
177 |
178 | # Seconds of overlap between sentences
179 | lue --over 0.2 path/to/your/book.epub
180 |
181 | # Enable PDF cleaning filter (removes page numbers, headers and footnotes, default: 10% (0.1) from both bottom and top of the page)
182 | lue --filter path/to/your/book.pdf
183 |
184 | # Set custom PDF filter margins (0.0-1.0, where 0.1 = 10% of page)
185 | lue --filter 0.15 path/to/your/book.pdf # Both margins to 15%
186 | lue --filter 0.12 0.20 path/to/your/book.pdf # Header 12%, footnote 20%
187 |
188 | # Use the Vim keyboard layout
189 | lue --keys vim path/to/your/book.epub
190 |
191 | ```
192 |
193 | ### Keyboard Controls (Default)
194 |
195 |
196 |
197 | | **Key Binding** | **Action Description** |
198 | | --------------------------------------- | ---------------------------------------------------------------------------------------------- |
199 | | `q` | Quit the application and save current reading progress automatically |
200 | | `p` | Pause or resume the text-to-speech audio playback |
201 | | `a` | Toggle auto-scroll mode to automatically advance during TTS playback |
202 | | `t` | Select and highlight the top sentence of the current visible page |
203 | | `h` / `l` | Move the reading line to the previous or next paragraph in the document |
204 | | `j` / `k` | Move the reading line to the previous or next sentence in the document |
205 | | `i` / `m` | Jump up or down by full pages for rapid navigation through longer documents |
206 | | `u` / `n` | Scroll up or down by smaller increments for fine-grained position control |
207 | | `y` / `b` | Jump directly to the beginning or end of the document for quick navigation |
208 | | `r` | Open the recent books menu to quickly switch between 5 last read books |
209 | | `,` / `.` | Decrease or increase text-to-speech playback speed (1x to 3x) |
210 | | `s` / `w` | Toggle sentence highlighting or word highlighting on/off |
211 | | `v` | Cycle through UI complexity modes (Minimal, Medium, Full) |
212 |
213 |
214 |
215 | ### Mouse Controls
216 |
217 | - **🖱️ Click** - Jump to sentence
218 | - **🔄 Scroll** - Navigate content
219 | - **📍 Progress bar click** - Jump to position
220 |
221 | ## ⚙️ Customize
222 |
223 | ### UI Modes
224 |
225 | Lue offers three UI complexity modes that you can cycle through using the `v` key or set as your default in the [config.py](lue/config.py) file:
226 |
227 | - **Mode 0 (Minimal)** - Clean text-only display with no borders or UI elements
228 | - **Mode 1 (Medium)** - Displays a top title bar with progress information and borders
229 | - **Mode 2 (Full)** - Full UI with both top title bar and bottom control information
230 |
231 | Additionally, Lue provides customizable word-level and sentence-level highlighting that can be adjusted to suit your reading preferences. You can cycle through different highlighting modes using the `w` and `s` keys. These highlighting settings can also be configured as defaults in the [config.py](lue/config.py) file.
232 |
233 | ### Keyboard Layouts
234 |
235 | Lue comes with two built-in keyboard layouts that can be set using -k/--key command line option or set as your default in the [config.py](lue/config.py) file. You can create your own keyboard layout by copying and modifying one of the existing layout files:
236 |
237 | - **Default Layout** - [keys_default.json](lue/keys_default.json) - Standard keyboard layout
238 | - **Vim Layout** - [keys_vim.json](lue/keys_vim.json) - Vim-style keyboard layout
239 | - **Custom Layout** - Customize your own navigation keys by creating your own keyboard layout json file
240 |
241 | ### Color Themes
242 |
243 | Lue allows you to customize the color theme, visual icons/symbols and all ui elements of the interface by modifying the classes in [ui.py](lue/ui.py). Create your own theme or choose one of the three themes that come with the default installation.
244 |
245 | - **Default Theme** - The default colorful theme with various colors for different UI elements
246 | - **Black Theme** - A dark monochrome theme that's suitable for bright backgrounds
247 | - **White Theme** - A light monochrome theme that's suitable for dark backgrounds
248 |
249 | ---
250 |
251 | ## 🧩 Development
252 |
253 | > **Interested in extending Lue?**
254 |
255 | Check out the [Developer Guide](DEVELOPER.md) for instructions on adding new TTS models and contributing to the project.
256 |
257 | ### Data Storage
258 |
259 | **Reading Progress:**
260 | - **macOS:** `~/Library/Application Support/lue/`
261 | - **Linux:** `~/.local/share/lue/`
262 | - **Windows (WSL):** `~/.local/share/lue/` (within WSL filesystem)
263 |
264 | **Error Logs:**
265 | - **macOS:** `~/Library/Logs/lue/error.log`
266 | - **Linux:** `~/.cache/lue/log/error.log`
267 | - **Windows (WSL):** `~/.cache/lue/log/error.log` (within WSL filesystem)
268 |
269 | ---
270 |
271 | ## 🛠️ Contributing
272 |
273 | Contributions are welcome! Please feel free to submit a Pull Request.
274 |
275 | Join our Discord community for discussions, support and collaboration for creating modules for new TTS models!
276 |
277 | [](https://discord.gg/z8sE2gnMNk)
278 |
279 | ---
280 |
281 | ## 📄 License
282 |
283 | This project is licensed under the **GPL-3.0-or-later License** - see the [LICENSE](LICENSE) file for details.
284 |
285 | ---
286 |
287 |
288 |
289 |

290 |
291 | *Made with 💖 for CLI enthusiasts and bookworms*
292 |
293 | **⭐ Star this repo** if you find it useful!
294 |
295 |
296 |
--------------------------------------------------------------------------------
/lue/tts/kokoro_tts.py:
--------------------------------------------------------------------------------
1 | import os
2 | import platform
3 | import warnings
4 | import asyncio
5 | import logging
6 | import re
7 | from rich.console import Console
8 |
9 | from .base import TTSBase
10 | from .. import config
11 |
12 | warnings.filterwarnings("ignore")
13 | os.environ["HF_HUB_DISABLE_TELEMETRY"] = "1"
14 | os.environ["HF_HUB_ETAG_TIMEOUT"] = "10"
15 | os.environ["HF_HUB_DOWNLOAD_TIMEOUT"] = "10"
16 |
17 |
18 | class KokoroTTS(TTSBase):
19 | """TTS implementation for Kokoro TTS."""
20 |
21 | @property
22 | def name(self) -> str:
23 | return "kokoro"
24 |
25 | @property
26 | def output_format(self) -> str:
27 | return "wav"
28 |
29 | def __init__(self, console: Console, voice: str = None, lang: str = None):
30 | super().__init__(console, voice, lang)
31 | self.pipeline = None
32 | self.np = None
33 | self.sf = None
34 |
35 | if self.voice is None:
36 | self.voice = config.TTS_VOICES.get(self.name)
37 |
38 | if self.lang is None:
39 | self.lang = config.TTS_LANGUAGE_CODES.get(self.name)
40 |
41 | def _patch_hf_downloader(self):
42 | """Patches hf_hub_download to show download progress messages."""
43 | try:
44 | if hasattr(self.huggingface_hub, "_patched_by_lue"):
45 | return
46 |
47 | original_hf_hub_download = self.huggingface_hub.hf_hub_download
48 |
49 | def tracked_hf_hub_download(*args, **kwargs):
50 | try:
51 | local_kwargs = dict(kwargs)
52 | local_kwargs["local_files_only"] = True
53 | original_hf_hub_download(*args, **local_kwargs)
54 | except Exception:
55 | repo_id = kwargs.get("repo_id", "")
56 | filename = kwargs.get("filename", "")
57 | msg = f"[bold yellow]Downloading model '{filename}' from Hugging Face ({repo_id}). This may take a while...[/bold yellow]"
58 | self.console.print(msg)
59 | return original_hf_hub_download(*args, **kwargs)
60 |
61 | self.huggingface_hub.hf_hub_download = tracked_hf_hub_download
62 | self.huggingface_hub._patched_by_lue = True
63 | except Exception as e:
64 | logging.warning(f"Failed to patch Hugging Face downloader: {e}")
65 |
66 | async def initialize(self) -> bool:
67 | """Initializes the Kokoro TTS pipeline asynchronously."""
68 | try:
69 | import numpy
70 | import soundfile as sf
71 | from kokoro import KPipeline
72 | import huggingface_hub
73 |
74 | self.np = numpy
75 | self.sf = sf
76 | self.KPipeline = KPipeline
77 | self.huggingface_hub = huggingface_hub
78 | except SystemExit:
79 | self.console.print("[bold red]Error: The TTS library exited unexpectedly during import.[/bold red]")
80 | self.console.print("[yellow]This can happen if a required dependency is missing or misconfigured.[/yellow]")
81 | logging.error("SystemExit was called during Kokoro TTS import.")
82 | return False
83 | except ImportError as e:
84 | package = str(e).split("'")[1]
85 | self.console.print(f"[bold red]Error: '{package}' package not found.[/bold red]")
86 | self.console.print(f"[yellow]Please ensure torch, kokoro, soundfile, etc. are installed to use this TTS model.[/yellow]")
87 | logging.error(f"'{package}' is not installed for Kokoro TTS.")
88 | return False
89 |
90 | self._patch_hf_downloader()
91 | loop = asyncio.get_running_loop()
92 |
93 | def _blocking_init():
94 | gpu_msg, use_gpu = self._get_gpu_acceleration()
95 | pipeline, error_msg, device_used = None, None, None
96 |
97 | if use_gpu:
98 | device_to_try = "mps" if platform.system() == "Darwin" else "cuda"
99 | try:
100 | pipeline = self.KPipeline(repo_id="hexgrad/Kokoro-82M", device=device_to_try, lang_code=self.lang)
101 | device_used = device_to_try
102 | except Exception as gpu_error:
103 | error_msg = f"Failed to initialize on GPU ({device_to_try}): {gpu_error}"
104 |
105 | if pipeline is None:
106 | try:
107 | pipeline = self.KPipeline(repo_id="hexgrad/Kokoro-82M", device="cpu", lang_code=self.lang)
108 | device_used = "cpu"
109 | except Exception as cpu_error:
110 | error_msg = f"Failed to initialize on CPU: {cpu_error}"
111 |
112 | return pipeline, (gpu_msg, error_msg), device_used
113 |
114 | try:
115 | pipeline, (gpu_msg, error_details), device_used = await loop.run_in_executor(None, _blocking_init)
116 | self.console.print(f"[cyan]GPU Check: {gpu_msg}[/cyan]")
117 |
118 | if pipeline:
119 | self.pipeline = pipeline
120 | self.console.print(f"[green]Kokoro TTS model initialized successfully on {device_used}.[/green]")
121 | self.initialized = True
122 | return True
123 | else:
124 | self.console.print(f"[bold red]Kokoro initialization failed.[/bold red]")
125 | if error_details:
126 | self.console.print(f"[red]Error details: {error_details}[/red]")
127 | logging.error(f"Kokoro initialization failed: {error_details}")
128 | return False
129 | except Exception as e:
130 | self.console.print(f"[bold red]An unexpected error occurred during Kokoro's async initialization: {e}[/bold red]")
131 | logging.error("Kokoro async initialization failed.", exc_info=True)
132 | return False
133 |
134 | async def warm_up(self):
135 | """Performs a short TTS generation to load the model into memory."""
136 | if not self.initialized:
137 | return
138 |
139 | self.console.print("[bold cyan]Warming up the Kokoro TTS model... (this may take a minute)[/bold cyan]")
140 | warmup_file = os.path.join(config.AUDIO_DATA_DIR, f".warmup_kokoro.{self.output_format}")
141 |
142 | try:
143 | await self.generate_audio("Ready.", warmup_file)
144 | self.console.print("[green]Kokoro TTS model is ready.[/green]")
145 | except Exception as e:
146 | self.console.print(f"[bold yellow]Warning: Kokoro model warm-up failed.[/bold yellow]")
147 | logging.warning(f"Kokoro TTS warm-up failed: {e}", exc_info=True)
148 | finally:
149 | if os.path.exists(warmup_file):
150 | try:
151 | os.remove(warmup_file)
152 | except OSError:
153 | pass
154 |
155 | def _get_gpu_acceleration(self):
156 | """Checks for available GPU acceleration."""
157 | try:
158 | import torch
159 | if torch.cuda.is_available():
160 | return "NVIDIA CUDA GPU available.", True
161 | if torch.backends.mps.is_available() and platform.system() == "Darwin":
162 | return "Apple Metal (MPS) GPU available.", True
163 | return "No compatible GPU found. Using CPU.", False
164 | except ImportError:
165 | return "PyTorch not found. Using CPU.", False
166 | except Exception as e:
167 | return f"Error checking for GPU ({e}). Using CPU.", False
168 |
169 | async def get_raw_timing_data(self, text: str, output_path: str):
170 | """
171 | Get raw word timing data from Kokoro TTS.
172 |
173 | Returns:
174 | List of (word, start_time, end_time) tuples with raw timing data from Kokoro TTS
175 | """
176 | if not self.initialized or not self.pipeline:
177 | raise RuntimeError("Kokoro TTS has not been initialized.")
178 |
179 | def _blocking_generate():
180 | try:
181 | # Generate audio with timing information
182 | results = list(self.pipeline(text, voice=self.voice, split_pattern=None))
183 |
184 | if results:
185 | # Concatenate all audio segments
186 | audio_segments = [result.audio for result in results]
187 | full_audio = self.np.concatenate(audio_segments)
188 | self.sf.write(output_path, full_audio, 24000)
189 |
190 | # Extract precise timing information from tokens
191 | word_timings = []
192 |
193 | # Process each result to extract word-level timing
194 | for result in results:
195 | if hasattr(result, 'tokens') and result.tokens:
196 | # Extract timing from tokens
197 | for token in result.tokens:
198 | # Skip punctuation tokens for word timing
199 | if token.tag in ['.', ',', '!', '?', ':', ';']:
200 | continue
201 |
202 | # Use the actual text and timing from the token
203 | word = token.text
204 | start_time = token.start_ts
205 | end_time = token.end_ts
206 |
207 | # Filter out None values which can cause errors in timing calculations
208 | if start_time is not None and end_time is not None:
209 | # Only include tokens that contain alphanumeric characters
210 | # This ensures consistency with the timing calculator and UI
211 | if re.search(r'[a-zA-Z0-9]', word):
212 | word_timings.append((word, start_time, end_time))
213 |
214 | return word_timings
215 | else:
216 | self.sf.write(output_path, self.np.array([], dtype=self.np.float32), 24000)
217 | return []
218 | except Exception as e:
219 | logging.error(f"Error during Kokoro audio generation for text '{text[:50]}...': {e}", exc_info=True)
220 | raise e
221 |
222 | loop = asyncio.get_running_loop()
223 | return await loop.run_in_executor(None, _blocking_generate)
224 |
225 | async def generate_audio_with_timing(self, text: str, output_path: str):
226 | """
227 | Generate audio with timing using the centralized timing calculator.
228 |
229 | This method leverages Kokoro TTS's token-level timing information
230 | through get_raw_timing_data() and processes it with the timing calculator.
231 | """
232 | # Get raw timing data (which also generates the audio)
233 | raw_timings = await self.get_raw_timing_data(text, output_path)
234 |
235 | # Get actual audio duration
236 | try:
237 | from .. import audio
238 | except ImportError:
239 | import sys
240 | import os
241 | sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
242 | import audio
243 | duration = await audio.get_audio_duration(output_path)
244 |
245 | # Process timing data using the centralized calculator
246 | try:
247 | from ..timing_calculator import process_tts_timing_data
248 | except ImportError:
249 | import sys
250 | import os
251 | sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
252 | import timing_calculator
253 | process_tts_timing_data = timing_calculator.process_tts_timing_data
254 | return process_tts_timing_data(text, raw_timings, duration)
255 |
256 | async def generate_audio(self, text: str, output_path: str):
257 | """Generates audio from text using Kokoro in a separate thread."""
258 | if not self.initialized or not self.pipeline:
259 | raise RuntimeError("Kokoro TTS has not been initialized.")
260 |
261 | def _blocking_generate():
262 | try:
263 | audio_segments = [result.audio for result in self.pipeline(text, voice=self.voice, split_pattern=None)]
264 | if audio_segments:
265 | full_audio = self.np.concatenate(audio_segments)
266 | self.sf.write(output_path, full_audio, 24000)
267 | else:
268 | self.sf.write(output_path, self.np.array([], dtype=self.np.float32), 24000)
269 | except Exception as e:
270 | logging.error(f"Error during Kokoro audio generation for text '{text[:50]}...': {e}", exc_info=True)
271 | raise e
272 |
273 | loop = asyncio.get_running_loop()
274 | await loop.run_in_executor(None, _blocking_generate)
--------------------------------------------------------------------------------
/DEVELOPER.md:
--------------------------------------------------------------------------------
1 | # Lue - Developer Guide: Adding a New TTS Model
2 |
3 | Lue is designed to automatically discover and use any TTS model that adheres to a specific "contract." To add a new model, you only need to create one Python file and edit the configuration.
4 |
5 | The process is:
6 | 1. Create a new file in `lue/tts/` named `yourtts_tts.py`. The filename has to end with `_tts.py`.
7 | 2. Implement a class inside that file that inherits from `TTSBase`.
8 | 3. Add the model's dependencies to `requirements.txt`.
9 | 4. Add a default voice for the model in `config.py`'s `TTS_VOICES` dictionary.
10 | 5. If the model requires a language code, add a default to `config.py`'s `TTS_LANGUAGE_CODES` dictionary.
11 |
12 | ### The `TTSBase` Contract
13 |
14 | Your new class must implement the following properties and methods. The `Lue` application relies on this exact structure to function correctly.
15 |
16 | - `__init__(self, console: Console, voice: str = None, lang: str = None):`
17 | - **Purpose:** The constructor for your TTS model.
18 | - **Rules:** It must accept `console`, `voice`, and `lang` and pass them to the base class constructor: `super().__init__(console, voice, lang)`. The `voice` and `lang` values are passed from the command-line arguments (`--voice` and `--lang`). Not all TTS models support language selection; if yours doesn't, you can simply ignore the `lang` parameter.
19 |
20 | - `@property name(self) -> str:`
21 | - **Purpose:** A unique, lowercase identifier for the model.
22 | - **Rules:** Must match the filename (e.g., if the file is `yourtts_tts.py`, this must return `"yourtts"`). This is used for command-line arguments and configuration keys.
23 |
24 | - `@property output_format(self) -> str:`
25 | - **Purpose:** The audio format the model produces.
26 | - **Rules:** Must be `"mp3"` or `"wav"`. This tells the audio pipeline how to process the output files.
27 |
28 | - `async def initialize(self) -> bool:`
29 | - **Purpose:** Prepare the model. This is where you should handle imports, check for API keys, and load models.
30 | - **Rules:**
31 | - It **must** be asynchronous.
32 | - It **must** gracefully handle a missing dependency by wrapping imports in a `try...except ImportError` block and returning `False`.
33 | - It **must** return `True` on success and `False` on failure.
34 | - For long-running tasks (like downloading models), use `self.console.print()` to give the user feedback.
35 | - If model loading is a blocking operation, it **must** be run in a separate thread to avoid freezing the UI (see template).
36 |
37 | - `async def generate_audio(self, text: str, output_path: str):`
38 | - **Purpose:** The core function that converts a string of text into an audio file.
39 | - **Rules:**
40 | - It **must** be asynchronous.
41 | - It **must** save the generated audio to the exact `output_path` provided. The audio pipeline depends on this file existing after the method completes.
42 | - Like `initialize`, any blocking TTS generation code **must** be run in a separate thread.
43 |
44 | ### Word-Level Timing (Optional Advanced Feature)
45 |
46 | Lue supports word-level highlighting during audio playback, which provides a better reading experience by highlighting each word as it's spoken. The timing logic has been centralized in `lue/timing_calculator.py` to simplify TTS implementations.
47 |
48 | To support word-level highlighting, your TTS model should override the `get_raw_timing_data` method from the `TTSBase` class:
49 |
50 | - `async def get_raw_timing_data(self, text: str, output_path: str):`
51 | - **Purpose:** Extract raw word timing data from your TTS engine and generate the audio file.
52 | - **Return Value:** A list of `(word, start_time, end_time)` tuples with raw timing data from your TTS engine
53 | - **Implementation Guidelines:**
54 | - Generate the audio file and save it to `output_path`
55 | - Extract timing data directly from your TTS engine's output
56 | - Return the raw timing data without any processing or adjustments
57 | - The centralized timing calculator will handle all processing, continuity adjustments, and word mapping
58 | - If your TTS engine doesn't provide timing data, return an empty list `[]`
59 |
60 | The base class `generate_audio_with_timing()` method automatically:
61 | - Calls your `get_raw_timing_data()` method
62 | - Processes the raw timing data using the centralized timing calculator
63 | - Returns a structured dictionary with processed timing information
64 | - Handles fallback estimation if no raw timing data is available
65 |
66 | Example implementation pattern:
67 |
68 | ```python
69 | async def get_raw_timing_data(self, text: str, output_path: str):
70 | """
71 | Extract raw word timing data from the TTS engine.
72 | """
73 | # Generate audio and extract raw timing from the TTS engine
74 | result = self.tts_engine.synthesize_with_timing(text, voice=self.voice)
75 |
76 | # Save audio to file
77 | with open(output_path, 'wb') as f:
78 | f.write(result.audio_data)
79 |
80 | # Extract raw word timings from engine results (no processing needed)
81 | word_timings = []
82 | for word_info in result.word_timings:
83 | word_timings.append((
84 | word_info.text, # The actual word text
85 | word_info.start, # Start time in seconds (raw from engine)
86 | word_info.end # End time in seconds (raw from engine)
87 | ))
88 |
89 | # Return raw timing data - the timing calculator will handle all processing
90 | return word_timings
91 | ```
92 |
93 | **Note:** You don't need to implement `generate_audio_with_timing()` unless you have special requirements. The base class implementation automatically uses your `get_raw_timing_data()` method and processes the results through the centralized timing calculator.
94 |
95 | ### Code Template
96 |
97 | Use this template for your `lue/tts/yourtts_tts.py` file. It includes the required structure and best practices for handling errors and blocking operations.
98 |
99 | ```python
100 | # lue/tts/yourtts_tts.py
101 | import os
102 | import asyncio
103 | import logging
104 | from rich.console import Console
105 |
106 | # TODO: Import any other libraries your TTS model needs.
107 |
108 | from .base import TTSBase
109 | from .. import config
110 |
111 | class YourTTSTTS(TTSBase):
112 | """
113 | A brief description of your TTS model and what it does.
114 | """
115 |
116 | @property
117 | def name(self) -> str:
118 | # Must match the filename: yourtts_tts.py -> "yourtts"
119 | return "yourtts"
120 |
121 | @property
122 | def output_format(self) -> str:
123 | # The audio format your model produces ("mp3" or "wav")
124 | return "mp3"
125 |
126 | def __init__(self, console: Console, voice: str = None, lang: str = None):
127 | super().__init__(console, voice, lang)
128 | self.client = None # Example: an API client or model object
129 |
130 | # If the user doesn't provide a voice via --voice, use the default from config.py
131 | if self.voice is None:
132 | self.voice = config.TTS_VOICES.get(self.name)
133 |
134 | # If the user doesn't provide a language via --lang, use the default from config.py
135 | # Only use self.lang if your TTS model actually supports it.
136 | if self.lang is None:
137 | self.lang = config.TTS_LANGUAGE_CODES.get(self.name)
138 |
139 | async def initialize(self) -> bool:
140 | """
141 | Prepare the model. Check dependencies, load models, etc.
142 | """
143 | # 1. Check for dependencies and handle failure gracefully.
144 | try:
145 | # TODO: Import the actual TTS library here.
146 | # from your_tts_library import YourTTSClient
147 | pass # Replace with actual import
148 | except ImportError:
149 | self.console.print("[bold red]Error: 'your_tts_library' package not found.[/bold red]")
150 | self.console.print("[yellow]Please install it with 'pip install your_tts_library'[/yellow]")
151 | logging.error("'your_tts_library' is not installed.")
152 | return False
153 |
154 | # 2. For heavy/blocking setup tasks (like downloading or loading a large model),
155 | # run them in a separate thread to keep the UI responsive.
156 | loop = asyncio.get_running_loop()
157 | try:
158 | self.console.print("[cyan]Initializing YourTTS model... (this may take a moment)[/cyan]")
159 |
160 | # This is a synchronous function to do the heavy lifting.
161 | def _blocking_init():
162 | # TODO: Replace with your actual model loading logic.
163 | # For example, check for API keys or load a model using self.lang
164 | # client = YourTTSClient(api_key=os.environ.get("YOURTTS_API_KEY"), language=self.lang)
165 | # return client
166 | return True # Return the client/model object on success
167 |
168 | # Run the blocking function in an executor.
169 | self.client = await loop.run_in_executor(None, _blocking_init)
170 |
171 | if not self.client:
172 | self.console.print("[bold red]YourTTS initialization failed. Check logs for details.[/bold red]")
173 | return False
174 |
175 | self.initialized = True
176 | self.console.print("[green]YourTTS model initialized successfully.[/green]")
177 | return True
178 | except Exception as e:
179 | self.console.print(f"[bold red]An unexpected error occurred during YourTTS initialization: {e}[/bold red]")
180 | logging.error("YourTTS async initialization failed.", exc_info=True)
181 | return False
182 |
183 | async def generate_audio(self, text: str, output_path: str):
184 | """
185 | Generate audio from text and save it to the given path.
186 | """
187 | if not self.initialized or not self.client:
188 | raise RuntimeError("YourTTS has not been initialized.")
189 |
190 | # This is a synchronous function to do the audio generation.
191 | def _blocking_generate():
192 | try:
193 | # TODO: Replace with your library's actual audio generation call.
194 | # Use self.voice, which was set in __init__
195 | # The final audio MUST be saved to the `output_path`.
196 | # audio_data = self.client.generate(text=text, voice=self.voice)
197 | # with open(output_path, "wb") as f:
198 | # f.write(audio_data)
199 | pass # Replace with actual generation
200 | except Exception as e:
201 | logging.error(f"Error during YourTTS audio generation: {e}", exc_info=True)
202 | raise e
203 |
204 | # Run the blocking generation in a separate thread.
205 | loop = asyncio.get_running_loop()
206 | await loop.run_in_executor(None, _blocking_generate)
207 |
208 | # Optional: Implement word-level timing for better highlighting accuracy
209 | async def get_raw_timing_data(self, text: str, output_path: str):
210 | """
211 | Extract raw word timing data from your TTS engine.
212 |
213 | This method is optional but recommended for better word highlighting accuracy.
214 | If not implemented, the base class will use fallback estimation.
215 |
216 | Returns:
217 | List of (word, start_time, end_time) tuples with raw timing data from TTS engine,
218 | or empty list if no timing data is available
219 | """
220 | # TODO: Implement actual timing extraction from your TTS engine
221 | # The example below shows the structure but should be replaced with
222 | # actual implementation based on your TTS engine's capabilities.
223 |
224 | # This is a synchronous function to do the audio generation with timing.
225 | def _blocking_generate():
226 | try:
227 | # TODO: Replace with your library's actual audio generation call that provides timing.
228 | # Use self.voice, which was set in __init__
229 | # The final audio MUST be saved to the `output_path`.
230 |
231 | # Example with a hypothetical TTS engine that provides timing:
232 | # result = self.client.generate_with_timing(text=text, voice=self.voice)
233 | # with open(output_path, "wb") as f:
234 | # f.write(result.audio_data)
235 |
236 | # Extract raw timing data from your TTS engine
237 | # word_timings = []
238 | # for word_info in result.word_timings:
239 | # word_timings.append((
240 | # word_info.text, # The actual word text
241 | # word_info.start, # Start time in seconds (raw from engine)
242 | # word_info.end # End time in seconds (raw from engine)
243 | # ))
244 | # return word_timings
245 |
246 | # If your TTS engine doesn't provide timing, fall back to regular generation
247 | # and return empty list (the timing calculator will estimate)
248 | # TODO: Replace with actual generation
249 | pass # Replace with actual generation
250 | return [] # Return empty list if no timing available
251 |
252 | except Exception as e:
253 | logging.error(f"Error during YourTTS audio generation: {e}", exc_info=True)
254 | raise e
255 |
256 | # Run the blocking generation in a separate thread.
257 | loop = asyncio.get_running_loop()
258 | return await loop.run_in_executor(None, _blocking_generate)
259 |
260 | ```
--------------------------------------------------------------------------------
/lue/__main__.py:
--------------------------------------------------------------------------------
1 | """Main entry point for the Lue eBook reader application."""
2 |
3 | import asyncio
4 | import sys
5 | import termios
6 | import tty
7 | import subprocess
8 | import argparse
9 | import os
10 | import platform
11 | import platformdirs
12 | import logging
13 | try:
14 | from importlib.resources import files
15 | except ImportError:
16 | # Fallback for Python < 3.9
17 | from importlib_resources import files
18 | from rich.console import Console
19 | from .reader import Lue
20 | from . import config, progress_manager, input_handler
21 | from .tts_manager import TTSManager, get_default_tts_model_name
22 |
23 | def get_keyboard_shortcuts_file(keys_arg):
24 | """Resolve the keyboard shortcuts file path from the command line argument."""
25 | # If it's a direct file path that exists, use it
26 | if os.path.isfile(keys_arg):
27 | return keys_arg
28 |
29 | # If it's a preset name, look for keys_{name}.json in the lue directory
30 | preset_file = os.path.join(os.path.dirname(__file__), f'keys_{keys_arg}.json')
31 | if os.path.isfile(preset_file):
32 | return preset_file
33 |
34 | # If it's the special "default" name, use keys_default.json
35 | if keys_arg == "default":
36 | default_file = os.path.join(os.path.dirname(__file__), 'keys_default.json')
37 | if os.path.isfile(default_file):
38 | return default_file
39 |
40 | # Fallback to default
41 | return os.path.join(os.path.dirname(__file__), 'keys_default.json')
42 |
43 | def get_guide_file_path():
44 | """Get the path to the guide file, creating a temporary file if needed for packaged installs."""
45 | import tempfile
46 |
47 | try:
48 | # Try to get the guide from the package data first (for pip installs)
49 | try:
50 | guide_file = files('lue') / 'guide.txt'
51 | guide_content = guide_file.read_text(encoding='utf-8')
52 |
53 | # Create a temporary file with a user-friendly name
54 | temp_dir = tempfile.gettempdir()
55 | temp_path = os.path.join(temp_dir, "Lue Navigation Guide.txt")
56 |
57 | with open(temp_path, 'w', encoding='utf-8') as temp_file:
58 | temp_file.write(guide_content)
59 |
60 | return temp_path
61 |
62 | except (FileNotFoundError, ModuleNotFoundError):
63 | # Fallback to local file (for development)
64 | guide_path = os.path.join(os.path.dirname(__file__), 'guide.txt')
65 | if os.path.exists(guide_path):
66 | return guide_path
67 | else:
68 | return None
69 |
70 | except Exception:
71 | return None
72 |
73 | def setup_logging():
74 | """Set up file-based logging for the application."""
75 | log_dir = platformdirs.user_log_dir(appname="lue", appauthor=False)
76 | os.makedirs(log_dir, exist_ok=True)
77 | log_file = os.path.join(log_dir, "error.log")
78 |
79 | logging.basicConfig(
80 | level=logging.INFO,
81 | format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
82 | filename=log_file,
83 | filemode='a',
84 | force=True,
85 | )
86 | logging.info("Application starting")
87 |
88 | def setup_environment():
89 | """Set environment variables for TTS models."""
90 | os.environ["HF_HUB_DISABLE_TELEMETRY"] = "1"
91 | os.environ["HF_HUB_ETAG_TIMEOUT"] = "10"
92 | os.environ["HF_HUB_DOWNLOAD_TIMEOUT"] = "10"
93 | os.environ["HF_HUB_DISABLE_SYMLINKS_WARNING"] = "1"
94 | if platform.system() == "Darwin" and platform.processor() == "arm":
95 | os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
96 |
97 | def preprocess_filter_args(args):
98 | """Preprocess arguments to handle --filter with space-separated values."""
99 | processed_args = []
100 | i = 0
101 | while i < len(args):
102 | arg = args[i]
103 | if arg in ['--filter', '-f']:
104 | # Found filter argument
105 | processed_args.append(arg)
106 | i += 1
107 |
108 | # Collect numeric values that follow
109 | filter_values = []
110 | while i < len(args):
111 | try:
112 | # Try to parse as float
113 | float(args[i])
114 | filter_values.append(args[i])
115 | i += 1
116 | if len(filter_values) >= 2: # Max 2 values
117 | break
118 | except ValueError:
119 | # Not a number, stop collecting
120 | break
121 |
122 | # Join the values and add as a single argument
123 | if filter_values:
124 | processed_args.append(' '.join(filter_values))
125 | else:
126 | # No values provided, add empty string
127 | processed_args.append('')
128 | else:
129 | processed_args.append(arg)
130 | i += 1
131 |
132 | return processed_args
133 |
134 | async def main():
135 | # Preprocess arguments to handle filter syntax
136 | preprocessed_args = preprocess_filter_args(sys.argv[1:])
137 |
138 | tts_manager = TTSManager()
139 | available_tts = tts_manager.get_available_tts_names()
140 | default_tts = get_default_tts_model_name(available_tts)
141 |
142 | parser = argparse.ArgumentParser(
143 | description="A terminal-based eBook reader with TTS",
144 | add_help=False # Disable automatic help to add custom one
145 | )
146 |
147 | parser.add_argument(
148 | '-h', '--help',
149 | action='help',
150 | help='Show this help message and exit'
151 | )
152 |
153 | parser.add_argument(
154 | '-g', '--guide',
155 | action='store_true',
156 | help='Open the keyboard shortcuts navigation guide'
157 | )
158 |
159 | parser.add_argument("file_path", nargs='?', help="Path to the eBook file (.epub, .pdf, .txt, etc.). If not provided, opens the last book you were reading.")
160 | parser.add_argument(
161 | "-f",
162 | "--filter",
163 | nargs='?',
164 | const='',
165 | help="Enable PDF text cleaning filters. Usage: --filter (defaults), --filter 0.15 (both margins), --filter 0.12 0.20 (header, footnote)",
166 | )
167 |
168 | parser.add_argument(
169 | "-o", "--over", type=float, help="Seconds of overlap between sentences"
170 | )
171 |
172 | parser.add_argument(
173 | "-k", "--keys",
174 | help="Keyboard configuration. Use a preset name (vim, default) or a path to a JSON file. Default: default",
175 | default="default"
176 | )
177 |
178 | if available_tts:
179 | # Add "none" option to available TTS choices
180 | tts_choices = ["none"] + available_tts
181 | parser.add_argument(
182 | "-t",
183 | "--tts",
184 | choices=tts_choices,
185 | default=default_tts,
186 | help=f"Select the Text-to-Speech model. Use 'none' to disable TTS (default: {default_tts})",
187 | )
188 | parser.add_argument(
189 | "-v",
190 | "--voice",
191 | help="Specify the voice for the TTS model",
192 | )
193 | parser.add_argument(
194 | "-s",
195 | "--speed",
196 | type=float,
197 | default=1.0,
198 | help="Set the speech speed (default: 1.0)",
199 | )
200 | parser.add_argument(
201 | "-l",
202 | "--lang",
203 | help="Specify the language for the TTS model",
204 | )
205 | args = parser.parse_args(preprocessed_args)
206 |
207 | # Initialize console early for printing messages
208 | console = Console()
209 |
210 | # Handle guide argument - open guide file in Lue app
211 | if args.guide:
212 | guide_path = get_guide_file_path()
213 | if guide_path:
214 | console.print("[green]Opening navigation guide...[/green]")
215 | args.file_path = guide_path
216 | else:
217 | console.print("[red]Guide file not found.[/red]")
218 | sys.exit(1)
219 | # Handle the case when no file is provided - try to open the last book
220 | elif not args.file_path:
221 | last_book_path = progress_manager.find_most_recent_book()
222 | if last_book_path:
223 | console.print(f"[green]Opening last book: {os.path.basename(last_book_path)}[/green]")
224 | args.file_path = last_book_path
225 | else:
226 | console.print("[red]No file specified and no previous books found.[/red]")
227 | console.print("Please provide a file path as an argument.")
228 | parser.print_help()
229 | sys.exit(1)
230 | else:
231 | # Convert relative path to absolute path for consistency
232 | args.file_path = os.path.abspath(args.file_path)
233 |
234 | if args.over is not None:
235 | config.OVERLAP_SECONDS = args.over
236 |
237 | # Handle PDF filter settings
238 | if args.filter is not None:
239 | config.PDF_FILTERS_ENABLED = True
240 |
241 | if args.filter == '':
242 | # Just --filter with no values, use defaults
243 | pass
244 | else:
245 | # Parse the filter values
246 | try:
247 | filter_values = [float(x.strip()) for x in args.filter.split() if x.strip()]
248 |
249 | if len(filter_values) == 1:
250 | # One number provided - set both margins to this value
251 | config.PDF_HEADER_MARGIN = filter_values[0]
252 | config.PDF_FOOTNOTE_MARGIN = filter_values[0]
253 | elif len(filter_values) == 2:
254 | # Two numbers provided - set header and footnote margins separately
255 | config.PDF_HEADER_MARGIN = filter_values[0]
256 | config.PDF_FOOTNOTE_MARGIN = filter_values[1]
257 | elif len(filter_values) > 2:
258 | console.print("[red]Error: --filter accepts at most 2 values (header margin, footnote margin)[/red]")
259 | sys.exit(1)
260 | except ValueError:
261 | console.print(f"[red]Error: Invalid filter values '{args.filter}'. Expected float numbers.[/red]")
262 | sys.exit(1)
263 |
264 | setup_environment()
265 | setup_logging()
266 |
267 |
268 | for tool in ['ffprobe', 'ffplay', 'ffmpeg']:
269 | try:
270 | subprocess.run([tool, '-version'], check=True, text=True,
271 | stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
272 | except (subprocess.CalledProcessError, FileNotFoundError):
273 | console.print(f"\n[bold red]Error: {tool} not found.[/bold red] "
274 | "Please install FFmpeg and ensure it's in your system's PATH.")
275 | logging.error(f"Required tool '{tool}' not found. FFmpeg may not be installed.")
276 | sys.exit(1)
277 |
278 | # Resolve keyboard shortcuts file
279 | # Prioritize command-line argument if explicitly provided (not the default)
280 | if args.keys != "default":
281 | # User explicitly provided a keys argument
282 | keyboard_shortcuts_file = get_keyboard_shortcuts_file(args.keys)
283 | elif config.CUSTOM_KEYBOARD_SHORTCUTS and config.CUSTOM_KEYBOARD_SHORTCUTS != "default":
284 | # Use the config value if it's not the default
285 | keyboard_shortcuts_file = get_keyboard_shortcuts_file(config.CUSTOM_KEYBOARD_SHORTCUTS)
286 | else:
287 | # Fall back to default
288 | keyboard_shortcuts_file = get_keyboard_shortcuts_file("default")
289 |
290 | # Load keyboard shortcuts
291 | input_handler.load_keyboard_shortcuts(keyboard_shortcuts_file)
292 |
293 | tts_instance = None
294 | if available_tts and hasattr(args, 'tts') and args.tts and args.tts != "none":
295 | voice = args.voice if hasattr(args, 'voice') else None
296 | lang = args.lang if hasattr(args, 'lang') else None
297 | tts_instance = tts_manager.create_model(args.tts, console, voice=voice, lang=lang)
298 |
299 | reader = Lue(args.file_path, tts_model=tts_instance, overlap=args.over)
300 | if hasattr(args, 'speed'):
301 | reader.playback_speed = args.speed
302 |
303 | # Hide cursor, enable mouse tracking
304 | sys.stdout.write('\033[?1000h\033[?1006h\033[?25l')
305 | sys.stdout.flush()
306 |
307 | fd = sys.stdin.fileno()
308 | old_settings = termios.tcgetattr(fd)
309 | temp_guide_file = None
310 |
311 | # Check if we're using a temporary guide file
312 | if args.guide and args.file_path and "Lue Navigation Guide.txt" in args.file_path:
313 | temp_guide_file = args.file_path
314 |
315 | try:
316 | tty.setcbreak(sys.stdin.fileno())
317 |
318 | initialized = await reader.initialize_tts()
319 | if not initialized and hasattr(args, 'tts') and args.tts and args.tts != "none":
320 | console.print(f"[bold yellow]Warning: TTS model '{args.tts}' "
321 | "failed to initialize and has been disabled.[/bold yellow]")
322 |
323 | await reader.run()
324 |
325 | finally:
326 | sys.stdout.write('\033[?1000l\033[?1006l\033[?25h')
327 | sys.stdout.flush()
328 | if fd is not None and old_settings is not None:
329 | termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
330 |
331 | # Clean up temporary guide file if it was created
332 | if temp_guide_file:
333 | try:
334 | os.unlink(temp_guide_file)
335 | except (OSError, FileNotFoundError):
336 | pass
337 |
338 | def cli():
339 | """Synchronous entry point for the command-line interface."""
340 | try:
341 | asyncio.run(main())
342 | except (KeyboardInterrupt, SystemExit):
343 | pass
344 | except Exception as e:
345 | logging.critical(f"Fatal error in application startup: {e}", exc_info=True)
346 |
347 | if __name__ == "__main__":
348 | cli()
349 |
--------------------------------------------------------------------------------
/lue/audio.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import os
3 | import re
4 | import subprocess
5 | import logging
6 | from . import config, content_parser
7 |
8 | # This pattern is used to both clean text for TTS and detect sentence fragments.
9 | ABBREVIATION_PATTERN = r'\b(Mr|Mrs|Ms|Dr|Prof|Rev|Hon|Jr|Sr|Cpl|Sgt|Gen|Col|Capt|Lt|Pvt|vs|viz|Co|Inc|Ltd|Corp|St|Ave|Blvd)\.'
10 | INITIAL_PATTERN = r'\b([A-Z])\.(?=\s[A-Z])'
11 |
12 |
13 | # Word mapping functionality moved to timing_calculator.py
14 | # Import it here for backward compatibility
15 | from .timing_calculator import create_word_mapping as _create_word_mapping
16 |
17 |
18 | def clean_tts_text(text: str) -> str:
19 | """
20 | Removes periods from specific English abbreviations and single initials
21 | to prevent unnatural pauses in TTS engines. Also removes loose punctuation
22 | marks that are not connected to any word.
23 | """
24 | # Remove periods from abbreviations and initials
25 | text = re.sub(ABBREVIATION_PATTERN, r'\1', text)
26 | text = re.sub(INITIAL_PATTERN, r'\1 ', text)
27 |
28 | # Remove loose punctuation marks that are standalone (not connected to words)
29 | # This pattern matches punctuation that is surrounded by whitespace or at string boundaries
30 | text = re.sub(r'(?:^|\s)[.,:;!?]+(?=\s|$)', ' ', text)
31 |
32 | # Remove standalone dashes that are followed by quotation marks
33 | # This prevents TTS engines from reading "-" as "dash" in cases like: -"
34 | text = re.sub(r'(?:^|\s)-(?=")', ' ', text)
35 |
36 | # Clean up any extra whitespace that might result from removing punctuation
37 | text = re.sub(r'\s+', ' ', text).strip()
38 |
39 | return text
40 |
41 | async def stop_and_clear_audio(reader):
42 | """Stop audio playback and clear the audio queue."""
43 | tasks_to_cancel = []
44 | for task in [reader.producer_task, reader.player_task]:
45 | if task and not task.done():
46 | task.cancel()
47 | tasks_to_cancel.append(task)
48 | if tasks_to_cancel:
49 | await asyncio.gather(*tasks_to_cancel, return_exceptions=True)
50 |
51 | reader.producer_task = None
52 | reader.player_task = None
53 |
54 | processes_to_kill = reader.playback_processes.copy()
55 | reader.playback_processes.clear()
56 | for process in processes_to_kill:
57 | try:
58 | if process.returncode is None:
59 | process.terminate()
60 | try: await asyncio.wait_for(process.wait(), timeout=0.2)
61 | except asyncio.TimeoutError:
62 | process.kill()
63 | await asyncio.wait_for(process.wait(), timeout=0.1)
64 | except (ProcessLookupError, AttributeError, asyncio.TimeoutError): pass
65 |
66 | try:
67 | pkill_proc = await asyncio.create_subprocess_exec('pkill', '-9', '-f', 'ffplay.*buffer_', stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
68 | await asyncio.wait_for(pkill_proc.wait(), timeout=0.3)
69 | except (FileNotFoundError, asyncio.TimeoutError): pass
70 |
71 | while not reader.audio_queue.empty():
72 | try:
73 | reader.audio_queue.get_nowait()
74 | reader.audio_queue.task_done()
75 | except asyncio.QueueEmpty: break
76 |
77 | await asyncio.sleep(0.1)
78 |
79 | # More aggressive cleanup with longer delays for file system operations
80 | for buf_base in config.AUDIO_BUFFERS:
81 | for ext in ['.mp3', '.wav']:
82 | buf = f"{buf_base}{ext}"
83 | for attempt in range(5): # Increased attempts
84 | try:
85 | if os.path.exists(buf):
86 | os.remove(buf)
87 | break
88 | except OSError:
89 | if attempt < 4:
90 | await asyncio.sleep(0.1) # Longer delay
91 |
92 |
93 |
94 | await asyncio.sleep(0.2) # Longer final delay
95 |
96 |
97 |
98 | async def get_audio_duration(file_path):
99 | """Get the duration of an audio file."""
100 | command = ['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1', file_path]
101 | process = await asyncio.create_subprocess_exec(*command, stdout=asyncio.subprocess.PIPE, stderr=subprocess.DEVNULL)
102 | stdout, _ = await process.communicate()
103 | if process.returncode != 0: return None
104 | try: return float(stdout.decode().strip())
105 | except (ValueError, TypeError): return None
106 |
107 | async def play_from_current_position(reader):
108 | """Start the audio producer and player loops."""
109 | if not reader.is_paused and reader.running and reader.tts_model:
110 | # Cancel existing tasks and wait for them to complete
111 | for task in [reader.producer_task, reader.player_task]:
112 | if task and not task.done():
113 | task.cancel()
114 | try:
115 | await asyncio.wait_for(task, timeout=2.0)
116 | except (asyncio.CancelledError, asyncio.TimeoutError):
117 | pass
118 |
119 | # Ensure tasks are properly cleaned up
120 | reader.producer_task = None
121 | reader.player_task = None
122 |
123 | # Small delay to ensure cleanup is complete
124 | await asyncio.sleep(0.05)
125 |
126 | reader.producer_task = asyncio.create_task(_producer_loop(reader))
127 | reader.player_task = asyncio.create_task(_player_loop(reader))
128 |
129 | async def _producer_loop(reader):
130 | """Producer loop to generate audio files."""
131 | if not reader.tts_model or not reader.tts_model.initialized:
132 | try: await asyncio.wait_for(reader.audio_queue.put(None), timeout=0.5)
133 | except (asyncio.TimeoutError, asyncio.CancelledError): pass
134 | return
135 |
136 | producer_pos = (reader.chapter_idx, reader.paragraph_idx, reader.sentence_idx)
137 | buffer_index = 0
138 | try:
139 | while reader.running:
140 | if reader.audio_queue.full():
141 | await asyncio.sleep(0.1)
142 | continue
143 | try:
144 | c, p, s = producer_pos
145 | sentences = content_parser.split_into_sentences(reader.chapters[c][p])
146 | text = sentences[s]
147 | except IndexError: break
148 | if not text or not text.strip():
149 | next_pos = reader._advance_position(producer_pos, wrap=False)
150 | if not next_pos: break
151 | producer_pos = next_pos
152 | continue
153 |
154 | # --- Start of fragment merging logic ---
155 | merged = False
156 | # Heuristic: if a "sentence" is just an abbreviation, it might be a fragment.
157 | # We check if the entire text matches common abbreviation patterns.
158 | is_abbrev_fragment = re.fullmatch(ABBREVIATION_PATTERN, text.strip())
159 |
160 | if is_abbrev_fragment and s + 1 < len(sentences):
161 | text += " " + sentences[s+1]
162 | merged = True
163 | # --- End of fragment merging logic ---
164 |
165 | # Preserve original text for UI display and timing calculation
166 | original_text = text
167 |
168 | output_format = reader.tts_model.output_format
169 | output_filename = f"{config.AUDIO_BUFFERS[buffer_index]}.{output_format}"
170 |
171 | try:
172 | if not reader.running: break
173 |
174 | for attempt in range(3):
175 | try:
176 | if os.path.exists(output_filename): os.remove(output_filename)
177 | break
178 | except OSError:
179 | if attempt < 2: await asyncio.sleep(0.05)
180 |
181 | # Create sanitized version for TTS
182 | sanitized_text = content_parser.sanitize_text_for_tts(original_text)
183 |
184 | timing_info = None
185 |
186 | # Use the timing-aware method if available
187 | if hasattr(reader.tts_model, 'generate_audio_with_timing'):
188 | try:
189 | timing_info = await reader.tts_model.generate_audio_with_timing(sanitized_text, output_filename)
190 | except Exception as e:
191 | # If timing generation fails, fall back to generating without it
192 | logging.error(f"TTS timing generation failed for text '{original_text[:50]}...' (sanitized: '{sanitized_text[:50]}...'): {e}")
193 | await reader.tts_model.generate_audio(sanitized_text, output_filename)
194 | else:
195 | # Fallback to regular method
196 | await reader.tts_model.generate_audio(sanitized_text, output_filename)
197 |
198 | # Always get the actual duration from the file
199 | duration = await get_audio_duration(output_filename)
200 |
201 | if not reader.running: break
202 |
203 | # If no timing info was generated, create a fallback structure
204 | # Pass original_text to timing calculator for proper word mapping
205 | if timing_info is None:
206 | from .timing_calculator import process_tts_timing_data
207 | timing_info = process_tts_timing_data(original_text, [], duration)
208 |
209 | await asyncio.wait_for(reader.audio_queue.put((output_filename, *producer_pos, duration, timing_info)), timeout=1.0)
210 |
211 | next_pos = reader._advance_position(producer_pos, wrap=False)
212 | if merged:
213 | # If we merged two sentences, we must advance the position an extra time.
214 | if next_pos:
215 | next_pos = reader._advance_position(next_pos, wrap=False)
216 |
217 | if not next_pos: break
218 | producer_pos = next_pos
219 | buffer_index = (buffer_index + 1) % len(config.AUDIO_BUFFERS)
220 | except asyncio.CancelledError: break
221 | except Exception as e:
222 | if reader.running:
223 | # Include both original and sanitized text in error logging
224 | try:
225 | sanitized_for_log = content_parser.sanitize_text_for_tts(original_text) if 'original_text' in locals() else 'N/A'
226 | original_for_log = original_text if 'original_text' in locals() else 'N/A'
227 | logging.error(f"TTS Error in producer: {e}\nOriginal text: '{original_for_log[:100]}...'\nSanitized text: '{sanitized_for_log[:100]}...'", exc_info=True)
228 | except:
229 | logging.error(f"TTS Error in producer: {e}", exc_info=True)
230 | await asyncio.sleep(2)
231 | continue
232 | except asyncio.CancelledError: pass
233 | finally:
234 | try: await asyncio.wait_for(reader.audio_queue.put(None), timeout=0.5)
235 | except (asyncio.TimeoutError, asyncio.CancelledError): pass
236 |
237 | async def _player_loop(reader):
238 | """Player loop to play audio files."""
239 | try:
240 | while reader.running:
241 | try:
242 | item = await asyncio.wait_for(reader.audio_queue.get(), timeout=1.0)
243 | if item is None:
244 | reader.audio_queue.task_done()
245 | if reader.active_playback_tasks:
246 | await asyncio.gather(*reader.active_playback_tasks, return_exceptions=True)
247 | reader.playback_finished_event.set()
248 | break
249 | # Unpack the queue item
250 | audio_file, c, p, s, duration, timing_data = item
251 | if isinstance(timing_data, dict):
252 | timing_info = timing_data
253 | else:
254 | # Old format, timing_data is word_timings
255 | timing_info = {"word_timings": timing_data, "speech_duration": duration, "total_duration": duration}
256 |
257 | word_timings = timing_info.get("word_timings", [])
258 |
259 | if not os.path.exists(audio_file):
260 | reader.audio_queue.task_done()
261 | continue
262 | if duration is None or duration <= 0:
263 | reader.audio_queue.task_done()
264 | continue
265 | try:
266 | # Post a command to the main loop to handle the state transition atomically
267 | reader.loop.call_soon_threadsafe(
268 | reader._post_command_sync,
269 | ('_new_sentence_started', (c, p, s, duration, timing_data))
270 | )
271 | except RuntimeError:
272 | reader.audio_queue.task_done()
273 | break
274 | try:
275 | # Build ffplay command with speed control using atempo filter
276 | cmd = ['ffplay', '-nodisp', '-autoexit', '-loglevel', 'error']
277 |
278 | # Add atempo filter if speed is not 1.0
279 | if abs(reader.playback_speed - 1.0) > 0.01:
280 | # atempo filter has limitations: must be between 0.5 and 2.0
281 | # For speeds outside this range, we chain multiple atempo filters
282 | speed = reader.playback_speed
283 | filters = []
284 |
285 | while speed > 2.0:
286 | filters.append('atempo=2.0')
287 | speed /= 2.0
288 | while speed < 0.5:
289 | filters.append('atempo=0.5')
290 | speed /= 0.5
291 | if abs(speed - 1.0) > 0.01:
292 | filters.append(f'atempo={speed:.3f}')
293 |
294 | if filters:
295 | filter_chain = ','.join(filters)
296 | cmd.extend(['-af', filter_chain])
297 |
298 | cmd.append(audio_file)
299 | process = await asyncio.create_subprocess_exec(*cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
300 | reader.playback_processes.append(process)
301 | except Exception:
302 | reader.audio_queue.task_done()
303 | continue
304 |
305 | async def await_and_remove(proc, file):
306 | task = asyncio.current_task()
307 | try:
308 | await proc.wait()
309 | except Exception: pass
310 | finally:
311 | try:
312 | if proc in reader.playback_processes: reader.playback_processes.remove(proc)
313 | except ValueError: pass
314 | for attempt in range(3):
315 | try:
316 | if os.path.exists(file): os.remove(file)
317 | break
318 | except OSError:
319 | if attempt < 2: await asyncio.sleep(0.05)
320 | if task in reader.active_playback_tasks:
321 | reader.active_playback_tasks.remove(task)
322 |
323 | playback_task = asyncio.create_task(await_and_remove(process, audio_file))
324 | reader.active_playback_tasks.append(playback_task)
325 |
326 | # Calculate dynamic overlap based on playback speed
327 | # Overlap should decrease as speed increases, reaching 0 at 3.00x speed and beyond
328 | base_overlap = config.OVERLAP_SECONDS
329 | if reader.tts_model and hasattr(reader.tts_model, 'get_overlap_seconds'):
330 | tts_overlap = reader.tts_model.get_overlap_seconds()
331 | if tts_overlap is not None:
332 | base_overlap = tts_overlap
333 |
334 | # Apply speed-based overlap reduction
335 | # At 1.0x speed: full overlap
336 | # At 3.00x speed and above: 0 overlap
337 | # Linear decrease between 1.0x and 3.0x
338 | speed = reader.playback_speed
339 | if speed >= 3.0:
340 | overlap_seconds = 0.0
341 | else:
342 | # Calculate overlap as a linear function decreasing from base_overlap to 0
343 | # as speed increases from 1.0 to 3.0
344 | overlap_factor = max(0.0, min(1.0, (3.0 - speed) / (3.0 - 1.0)))
345 | overlap_seconds = base_overlap * overlap_factor
346 |
347 | # Adjust duration for playback speed
348 | actual_duration = duration / speed
349 |
350 | await asyncio.sleep(max(0.1, actual_duration - overlap_seconds))
351 | reader.audio_queue.task_done()
352 | except asyncio.TimeoutError:
353 | if not reader.running: break
354 | continue
355 | except asyncio.CancelledError: break
356 | except asyncio.CancelledError: pass
357 | finally:
358 | for process in reader.playback_processes.copy():
359 | try:
360 | if process.returncode is None: process.terminate()
361 | except (ProcessLookupError, AttributeError): pass
--------------------------------------------------------------------------------
/VOICES.md:
--------------------------------------------------------------------------------
1 | # Lue - Voices and Languages Guide
2 |
3 | This document explains the speakers and languages included in the Edge and Kokoro TTS models, which are part of Lue’s default installation.
4 |
5 | ***
6 |
7 | ## Configuration
8 |
9 | To configure voices and languages, edit the `lue/config.py` file:
10 |
11 | ```python
12 | # Voice settings
13 | TTS_VOICES = {
14 | "edge": "en-US-JennyNeural", # Default Edge voice
15 | "kokoro": "af_heart", # Default Kokoro voice
16 | }
17 |
18 | # Language settings for TTS models
19 | TTS_LANGUAGE_CODES = {
20 | "kokoro": "a", # Language code for Kokoro TTS
21 | }
22 | ```
23 |
24 | ***
25 |
26 | ## Supported Languages and Codes
27 |
28 | ### Edge Model Language Codes
29 |
30 | You don't need to specify language code for the Edge TTS model. Edge indicates the language in standard locale codes (e.g., `en-US`, `fr-FR`, `ja-JP`) within the speaker name. See the full list of Edge voices below.
31 |
32 | ### Kokoro Model Language Codes
33 |
34 | When using Kokoro, make sure the `lang_code` matches your selected voice. For more detailed information, refer to Kokoro TTS documentation: https://github.com/hexgrad/kokoro.
35 |
36 | | Language | Code | Notes |
37 | | :--- | :--- | :--- |
38 | | **American English** | `a` | Default language |
39 | | **British English** | `b` | |
40 | | **Spanish** | `e` | espeak-ng `es` fallback |
41 | | **French** | `f` | espeak-ng `fr-fr` fallback |
42 | | **Hindi** | `h` | espeak-ng `hi` fallback |
43 | | **Italian** | `i` | espeak-ng `it` fallback |
44 | | **Brazilian Portuguese**| `p` | espeak-ng `pt-br` fallback |
45 | | **Japanese** | `j` | Requires `pip install misaki[ja]` |
46 | | **Mandarin Chinese** | `z` | Requires `pip install misaki[zh]` |
47 |
48 | ***
49 |
50 | ## Available Voices by Language
51 |
52 | ### Edge Voices
53 |
54 | Edge TTS provides a wide variety of voices across many languages. Always include the full language code, country code, and voice name exactly as shown (e.g., en-US-JennyNeural):
55 |
56 | #### Afrikaans (South Africa)
57 |
58 | * af-ZA-AdriNeural (Female)
59 | * af-ZA-WillemNeural (Male)
60 |
61 | #### Albanian (Albania)
62 |
63 | * sq-AL-AnilaNeural (Female)
64 | * sq-AL-IlirNeural (Male)
65 |
66 | #### Amharic (Ethiopia)
67 |
68 | * am-ET-AmehaNeural (Male)
69 | * am-ET-MekdesNeural (Female)
70 |
71 | #### Arabic
72 |
73 | * ar-DZ-AminaNeural (Female) - Algeria
74 | * ar-DZ-IsmaelNeural (Male) - Algeria
75 | * ar-BH-AliNeural (Male) - Bahrain
76 | * ar-BH-LailaNeural (Female) - Bahrain
77 | * ar-EG-SalmaNeural (Female) - Egypt
78 | * ar-EG-ShakirNeural (Male) - Egypt
79 | * ar-IQ-BasselNeural (Male) - Iraq
80 | * ar-IQ-RanaNeural (Female) - Iraq
81 | * ar-JO-SanaNeural (Female) - Jordan
82 | * ar-JO-TaimNeural (Male) - Jordan
83 | * ar-KW-FahedNeural (Male) - Kuwait
84 | * ar-KW-NouraNeural (Female) - Kuwait
85 | * ar-LB-LaylaNeural (Female) - Lebanon
86 | * ar-LB-RamiNeural (Male) - Lebanon
87 | * ar-LY-ImanNeural (Female) - Libya
88 | * ar-LY-OmarNeural (Male) - Libya
89 | * ar-MA-JamalNeural (Male) - Morocco
90 | * ar-MA-MounaNeural (Female) - Morocco
91 | * ar-OM-AbdullahNeural (Male) - Oman
92 | * ar-OM-AyshaNeural (Female) - Oman
93 | * ar-QA-AmalNeural (Female) - Qatar
94 | * ar-QA-MoazNeural (Male) - Qatar
95 | * ar-SA-HamedNeural (Male) - Saudi Arabia
96 | * ar-SA-ZariyahNeural (Female) - Saudi Arabia
97 | * ar-SY-AmanyNeural (Female) - Syria
98 | * ar-SY-LaithNeural (Male) - Syria
99 | * ar-TN-HediNeural (Male) - Tunisia
100 | * ar-TN-ReemNeural (Female) - Tunisia
101 | * ar-AE-FatimaNeural (Female) - United Arab Emirates
102 | * ar-AE-HamdanNeural (Male) - United Arab Emirates
103 | * ar-YE-MaryamNeural (Female) - Yemen
104 | * ar-YE-SalehNeural (Male) - Yemen
105 |
106 | #### Azerbaijani (Azerbaijan)
107 |
108 | * az-AZ-BabekNeural (Male)
109 | * az-AZ-BanuNeural (Female)
110 |
111 | #### Bengali
112 |
113 | * bn-BD-NabanitaNeural (Female) - Bangladesh
114 | * bn-BD-PradeepNeural (Male) - Bangladesh
115 | * bn-IN-BashkarNeural (Male) - India
116 | * bn-IN-TanishaaNeural (Female) - India
117 |
118 | #### Bosnian (Bosnia and Herzegovina)
119 |
120 | * bs-BA-GoranNeural (Male)
121 | * bs-BA-VesnaNeural (Female)
122 |
123 | #### Bulgarian (Bulgaria)
124 |
125 | * bg-BG-BorislavNeural (Male)
126 | * bg-BG-KalinaNeural (Female)
127 |
128 | #### Burmese (Myanmar)
129 |
130 | * my-MM-NilarNeural (Female)
131 | * my-MM-ThihaNeural (Male)
132 |
133 | #### Catalan (Spain)
134 |
135 | * ca-ES-EnricNeural (Male)
136 | * ca-ES-JoanaNeural (Female)
137 |
138 | #### Chinese
139 |
140 | * zh-HK-HiuGaaiNeural (Female) - Hong Kong
141 | * zh-HK-HiuMaanNeural (Female) - Hong Kong
142 | * zh-HK-WanLungNeural (Male) - Hong Kong
143 | * zh-CN-XiaoxiaoNeural (Female) - Mandarin
144 | * zh-CN-XiaoyiNeural (Female) - Mandarin
145 | * zh-CN-YunjianNeural (Male) - Mandarin
146 | * zh-CN-YunxiNeural (Male) - Mandarin
147 | * zh-CN-YunxiaNeural (Male) - Mandarin
148 | * zh-CN-YunyangNeural (Male) - Mandarin
149 | * zh-CN-liaoning-XiaobeiNeural (Female) - Liaoning
150 | * zh-TW-HsiaoChenNeural (Female) - Taiwanese Mandarin
151 | * zh-TW-YunJheNeural (Male) - Taiwanese Mandarin
152 | * zh-TW-HsiaoYuNeural (Female) - Taiwanese Mandarin
153 | * zh-CN-shaanxi-XiaoniNeural (Female) - Shaanxi
154 |
155 | #### Croatian (Croatia)
156 |
157 | * hr-HR-GabrijelaNeural (Female)
158 | * hr-HR-SreckoNeural (Male)
159 |
160 | #### Czech (Czech Republic)
161 |
162 | * cs-CZ-AntoninNeural (Male)
163 | * cs-CZ-VlastaNeural (Female)
164 |
165 | #### Danish (Denmark)
166 |
167 | * da-DK-ChristelNeural (Female)
168 | * da-DK-JeppeNeural (Male)
169 |
170 | #### Dutch
171 |
172 | * nl-BE-ArnaudNeural (Male) - Belgium
173 | * nl-BE-DenaNeural (Female) - Belgium
174 | * nl-NL-ColetteNeural (Female) - Netherlands
175 | * nl-NL-FennaNeural (Female) - Netherlands
176 | * nl-NL-MaartenNeural (Male) - Netherlands
177 |
178 | #### English
179 |
180 | * en-AU-NatashaNeural (Female) - Australia
181 | * en-AU-WilliamNeural (Male) - Australia
182 | * en-CA-ClaraNeural (Female) - Canada
183 | * en-CA-LiamNeural (Male) - Canada
184 | * en-HK-SamNeural (Male) - Hong Kong
185 | * en-HK-YanNeural (Female) - Hong Kong
186 | * en-IN-NeerjaNeural (Female) - India
187 | * en-IN-PrabhatNeural (Male) - India
188 | * en-IE-ConnorNeural (Male) - Ireland
189 | * en-IE-EmilyNeural (Female) - Ireland
190 | * en-KE-AsiliaNeural (Female) - Kenya
191 | * en-KE-ChilembaNeural (Male) - Kenya
192 | * en-NZ-MitchellNeural (Male) - New Zealand
193 | * en-NZ-MollyNeural (Female) - New Zealand
194 | * en-NG-AbeoNeural (Male) - Nigeria
195 | * en-NG-EzinneNeural (Female) - Nigeria
196 | * en-PH-JamesNeural (Male) - Philippines
197 | * en-PH-RosaNeural (Female) - Philippines
198 | * en-SG-LunaNeural (Female) - Singapore
199 | * en-SG-WayneNeural (Male) - Singapore
200 | * en-ZA-LeahNeural (Female) - South Africa
201 | * en-ZA-LukeNeural (Male) - South Africa
202 | * en-TZ-ElimuNeural (Male) - Tanzania
203 | * en-TZ-ImaniNeural (Female) - Tanzania
204 | * en-GB-LibbyNeural (Female) - United Kingdom
205 | * en-GB-MaisieNeural (Female) - United Kingdom
206 | * en-GB-RyanNeural (Male) - United Kingdom
207 | * en-GB-SoniaNeural (Female) - United Kingdom
208 | * en-GB-ThomasNeural (Male) - United Kingdom
209 | * en-US-AriaNeural (Female) - United States
210 | * en-US-AnaNeural (Female) - United States
211 | * en-US-ChristopherNeural (Male) - United States
212 | * en-US-EricNeural (Male) - United States
213 | * en-US-GuyNeural (Male) - United States
214 | * **en-US-JennyNeural** (Female) - Default US English voice
215 | * en-US-MichelleNeural (Female) - United States
216 | * en-US-RogerNeural (Male) - United States
217 | * en-US-SteffanNeural (Male) - United States
218 |
219 | #### Estonian (Estonia)
220 |
221 | * et-EE-AnuNeural (Female)
222 | * et-EE-KertNeural (Male)
223 |
224 | #### Filipino (Philippines)
225 |
226 | * fil-PH-AngeloNeural (Male)
227 | * fil-PH-BlessicaNeural (Female)
228 |
229 | #### Finnish (Finland)
230 |
231 | * fi-FI-HarriNeural (Male)
232 | * fi-FI-NooraNeural (Female)
233 |
234 | #### French
235 |
236 | * fr-BE-CharlineNeural (Female) - Belgium
237 | * fr-BE-GerardNeural (Male) - Belgium
238 | * fr-CA-AntoineNeural (Male) - Canada
239 | * fr-CA-JeanNeural (Male) - Canada
240 | * fr-CA-SylvieNeural (Female) - Canada
241 | * fr-FR-DeniseNeural (Female) - France
242 | * fr-FR-EloiseNeural (Female) - France
243 | * fr-FR-HenriNeural (Male) - France
244 | * fr-CH-ArianeNeural (Female) - Switzerland
245 | * fr-CH-FabriceNeural (Male) - Switzerland
246 |
247 | #### Galician (Spain)
248 |
249 | * gl-ES-RoiNeural (Male)
250 | * gl-ES-SabelaNeural (Female)
251 |
252 | #### Georgian (Georgia)
253 |
254 | * ka-GE-EkaNeural (Female)
255 | * ka-GE-GiorgiNeural (Male)
256 |
257 | #### German
258 |
259 | * de-AT-IngridNeural (Female) - Austria
260 | * de-AT-JonasNeural (Male) - Austria
261 | * de-DE-AmalaNeural (Female) - Germany
262 | * de-DE-ConradNeural (Male) - Germany
263 | * de-DE-KatjaNeural (Female) - Germany
264 | * de-DE-KillianNeural (Male) - Germany
265 | * de-CH-JanNeural (Male) - Switzerland
266 | * de-CH-LeniNeural (Female) - Switzerland
267 |
268 | #### Greek (Greece)
269 |
270 | * el-GR-AthinaNeural (Female)
271 | * el-GR-NestorasNeural (Male)
272 |
273 | #### Gujarati (India)
274 |
275 | * gu-IN-DhwaniNeural (Female)
276 | * gu-IN-NiranjanNeural (Male)
277 |
278 | #### Hebrew (Israel)
279 |
280 | * he-IL-AvriNeural (Male)
281 | * he-IL-HilaNeural (Female)
282 |
283 | #### Hindi (India)
284 |
285 | * hi-IN-MadhurNeural (Male)
286 | * hi-IN-SwaraNeural (Female)
287 |
288 | #### Hungarian (Hungary)
289 |
290 | * hu-HU-NoemiNeural (Female)
291 | * hu-HU-TamasNeural (Male)
292 |
293 | #### Icelandic (Iceland)
294 |
295 | * is-IS-GudrunNeural (Female)
296 | * is-IS-GunnarNeural (Male)
297 |
298 | #### Indonesian (Indonesia)
299 |
300 | * id-ID-ArdiNeural (Male)
301 | * id-ID-GadisNeural (Female)
302 |
303 | #### Irish (Ireland)
304 |
305 | * ga-IE-ColmNeural (Male)
306 | * ga-IE-OrlaNeural (Female)
307 |
308 | #### Italian (Italy)
309 |
310 | * it-IT-DiegoNeural (Male)
311 | * it-IT-ElsaNeural (Female)
312 | * it-IT-IsabellaNeural (Female)
313 |
314 | #### Japanese (Japan)
315 |
316 | * ja-JP-KeitaNeural (Male)
317 | * ja-JP-NanamiNeural (Female)
318 |
319 | #### Javanese (Indonesia)
320 |
321 | * jv-ID-DimasNeural (Male)
322 | * jv-ID-SitiNeural (Female)
323 |
324 | #### Kannada (India)
325 |
326 | * kn-IN-GaganNeural (Male)
327 | * kn-IN-SapnaNeural (Female)
328 |
329 | #### Kazakh (Kazakhstan)
330 |
331 | * kk-KZ-AigulNeural (Female)
332 | * kk-KZ-DauletNeural (Male)
333 |
334 | #### Khmer (Cambodia)
335 |
336 | * km-KH-PisethNeural (Male)
337 | * km-KH-SreymomNeural (Female)
338 |
339 | #### Korean (Korea)
340 |
341 | * ko-KR-InJoonNeural (Male)
342 | * ko-KR-SunHiNeural (Female)
343 |
344 | #### Lao (Laos)
345 |
346 | * lo-LA-ChanthavongNeural (Male)
347 | * lo-LA-KeomanyNeural (Female)
348 |
349 | #### Latvian (Latvia)
350 |
351 | * lv-LV-EveritaNeural (Female)
352 | * lv-LV-NilsNeural (Male)
353 |
354 | #### Lithuanian (Lithuania)
355 |
356 | * lt-LT-LeonasNeural (Male)
357 | * lt-LT-OnaNeural (Female)
358 |
359 | #### Macedonian (North Macedonia)
360 |
361 | * mk-MK-AleksandarNeural (Male)
362 | * mk-MK-MarijaNeural (Female)
363 |
364 | #### Malay (Malaysia)
365 |
366 | * ms-MY-OsmanNeural (Male)
367 | * ms-MY-YasminNeural (Female)
368 |
369 | #### Malayalam (India)
370 |
371 | * ml-IN-MidhunNeural (Male)
372 | * ml-IN-SobhanaNeural (Female)
373 |
374 | #### Maltese (Malta)
375 |
376 | * mt-MT-GraceNeural (Female)
377 | * mt-MT-JosephNeural (Male)
378 |
379 | #### Marathi (India)
380 |
381 | * mr-IN-AarohiNeural (Female)
382 | * mr-IN-ManoharNeural (Male)
383 |
384 | #### Mongolian (Mongolia)
385 |
386 | * mn-MN-BataaNeural (Male)
387 | * mn-MN-YesuiNeural (Female)
388 |
389 | #### Nepali (Nepal)
390 |
391 | * ne-NP-HemkalaNeural (Female)
392 | * ne-NP-SagarNeural (Male)
393 |
394 | #### Norwegian (Bokmål, Norway)
395 |
396 | * nb-NO-FinnNeural (Male)
397 | * nb-NO-PernilleNeural (Female)
398 |
399 | #### Pashto (Afghanistan)
400 |
401 | * ps-AF-GulNawazNeural (Male)
402 | * ps-AF-LatifaNeural (Female)
403 |
404 | #### Persian (Iran)
405 |
406 | * fa-IR-DilaraNeural (Female)
407 | * fa-IR-FaridNeural (Male)
408 |
409 | #### Polish (Poland)
410 |
411 | * pl-PL-MarekNeural (Male)
412 | * pl-PL-ZofiaNeural (Female)
413 |
414 | #### Portuguese
415 |
416 | * pt-BR-AntonioNeural (Male) - Brazil
417 | * pt-BR-FranciscaNeural (Female) - Brazil
418 | * pt-PT-DuarteNeural (Male) - Portugal
419 | * pt-PT-RaquelNeural (Female) - Portugal
420 |
421 | #### Romanian (Romania)
422 |
423 | * ro-RO-AlinaNeural (Female)
424 | * ro-RO-EmilNeural (Male)
425 |
426 | #### Russian (Russia)
427 |
428 | * ru-RU-DmitryNeural (Male)
429 | * ru-RU-SvetlanaNeural (Female)
430 |
431 | #### Serbian (Serbia)
432 |
433 | * sr-RS-NicholasNeural (Male)
434 | * sr-RS-SophieNeural (Female)
435 |
436 | #### Sinhala (Sri Lanka)
437 |
438 | * si-LK-SameeraNeural (Male)
439 | * si-LK-ThiliniNeural (Female)
440 |
441 | #### Slovak (Slovakia)
442 |
443 | * sk-SK-LukasNeural (Male)
444 | * sk-SK-ViktoriaNeural (Female)
445 |
446 | #### Slovenian (Slovenia)
447 |
448 | * sl-SI-PetraNeural (Female)
449 | * sl-SI-RokNeural (Male)
450 |
451 | #### Somali (Somalia)
452 |
453 | * so-SO-MuuseNeural (Male)
454 | * so-SO-UbaxNeural (Female)
455 |
456 | #### Spanish
457 |
458 | * es-AR-ElenaNeural (Female) - Argentina
459 | * es-AR-TomasNeural (Male) - Argentina
460 | * es-BO-MarceloNeural (Male) - Bolivia
461 | * es-BO-SofiaNeural (Female) - Bolivia
462 | * es-CL-CatalinaNeural (Female) - Chile
463 | * es-CL-LorenzoNeural (Male) - Chile
464 | * es-CO-GonzaloNeural (Male) - Colombia
465 | * es-CO-SalomeNeural (Female) - Colombia
466 | * es-CR-JuanNeural (Male) - Costa Rica
467 | * es-CR-MariaNeural (Female) - Costa Rica
468 | * es-CU-BelkysNeural (Female) - Cuba
469 | * es-CU-ManuelNeural (Male) - Cuba
470 | * es-DO-EmilioNeural (Male) - Dominican Republic
471 | * es-DO-RamonaNeural (Female) - Dominican Republic
472 | * es-EC-AndreaNeural (Female) - Ecuador
473 | * es-EC-LuisNeural (Male) - Ecuador
474 | * es-SV-LorenaNeural (Female) - El Salvador
475 | * es-SV-RodrigoNeural (Male) - El Salvador
476 | * es-GQ-JavierNeural (Male) - Equatorial Guinea
477 | * es-GQ-TeresaNeural (Female) - Equatorial Guinea
478 | * es-GT-AndresNeural (Male) - Guatemala
479 | * es-GT-MartaNeural (Female) - Guatemala
480 | * es-HN-CarlosNeural (Male) - Honduras
481 | * es-HN-KarlaNeural (Female) - Honduras
482 | * es-MX-DaliaNeural (Female) - Mexico
483 | * es-MX-JorgeNeural (Male) - Mexico
484 | * es-NI-FedericoNeural (Male) - Nicaragua
485 | * es-NI-YolandaNeural (Female) - Nicaragua
486 | * es-PA-MargaritaNeural (Female) - Panama
487 | * es-PA-RobertoNeural (Male) - Panama
488 | * es-PY-MarioNeural (Male) - Paraguay
489 | * es-PY-TaniaNeural (Female) - Paraguay
490 | * es-PE-AlexNeural (Male) - Peru
491 | * es-PE-CamilaNeural (Female) - Peru
492 | * es-PR-KarinaNeural (Female) - Puerto Rico
493 | * es-PR-VictorNeural (Male) - Puerto Rico
494 | * es-ES-AlvaroNeural (Male) - Spain
495 | * es-ES-ElviraNeural (Female) - Spain
496 | * es-US-AlonsoNeural (Male) - United States
497 | * es-US-PalomaNeural (Female) - United States
498 | * es-UY-MateoNeural (Male) - Uruguay
499 | * es-UY-ValentinaNeural (Female) - Uruguay
500 | * es-VE-PaolaNeural (Female) - Venezuela
501 | * es-VE-SebastianNeural (Male) - Venezuela
502 |
503 | #### Sundanese (Indonesia)
504 |
505 | * su-ID-JajangNeural (Male)
506 | * su-ID-TutiNeural (Female)
507 |
508 | #### Swahili
509 |
510 | * sw-KE-RafikiNeural (Male) - Kenya
511 | * sw-KE-ZuriNeural (Female) - Kenya
512 | * sw-TZ-DaudiNeural (Male) - Tanzania
513 | * sw-TZ-RehemaNeural (Female) - Tanzania
514 |
515 | #### Swedish (Sweden)
516 |
517 | * sv-SE-MattiasNeural (Male)
518 | * sv-SE-SofieNeural (Female)
519 |
520 | #### Tamil
521 |
522 | * ta-IN-PallaviNeural (Female) - India
523 | * ta-IN-ValluvarNeural (Male) - India
524 | * ta-MY-KaniNeural (Female) - Malaysia
525 | * ta-MY-SuryaNeural (Male) - Malaysia
526 | * ta-SG-AnbuNeural (Male) - Singapore
527 | * ta-SG-VenbaNeural (Female) - Singapore
528 | * ta-LK-KumarNeural (Male) - Sri Lanka
529 | * ta-LK-SaranyaNeural (Female) - Sri Lanka
530 |
531 | #### Telugu (India)
532 |
533 | * te-IN-MohanNeural (Male)
534 | * te-IN-ShrutiNeural (Female)
535 |
536 | #### Thai (Thailand)
537 |
538 | * th-TH-NiwatNeural (Male)
539 | * th-TH-PremwadeeNeural (Female)
540 |
541 | #### Turkish (Turkey)
542 |
543 | * tr-TR-AhmetNeural (Male)
544 | * tr-TR-EmelNeural (Female)
545 |
546 | #### Ukrainian (Ukraine)
547 |
548 | * uk-UA-OstapNeural (Male)
549 | * uk-UA-PolinaNeural (Female)
550 |
551 | #### Urdu
552 |
553 | * ur-IN-GulNeural (Female) - India
554 | * ur-IN-SalmanNeural (Male) - India
555 | * ur-PK-AsadNeural (Male) - Pakistan
556 | * ur-PK-UzmaNeural (Female) - Pakistan
557 |
558 | #### Uzbek (Uzbekistan)
559 |
560 | * uz-UZ-MadinaNeural (Female)
561 | * uz-UZ-SardorNeural (Male)
562 |
563 | #### Vietnamese (Vietnam)
564 |
565 | * vi-VN-HoaiMyNeural (Female)
566 | * vi-VN-NamMinhNeural (Male)
567 |
568 | #### Welsh (United Kingdom)
569 |
570 | * cy-GB-AledNeural (Male)
571 | * cy-GB-NiaNeural (Female)
572 |
573 | #### Zulu (South Africa)
574 |
575 | * zu-ZA-ThandoNeural (Female)
576 | * zu-ZA-ThembaNeural (Male)
577 |
578 | ***
579 |
580 | ### Kokoro Voices
581 |
582 | #### American English (`lang_code='a'`)
583 |
584 | * **af_heart** (Female)
585 | * af_alloy (Female)
586 | * af_aoede (Female)
587 | * af_bella (Female)
588 | * af_jessica (Female)
589 | * af_kore (Female)
590 | * af_nicole (Female)
591 | * af_nova (Female)
592 | * af_river (Female)
593 | * af_sarah (Female)
594 | * af_sky (Female)
595 | * am_adam (Male)
596 | * am_echo (Male)
597 | * am_eric (Male)
598 | * am_fenrir (Male)
599 | * am_liam (Male)
600 | * am_michael (Male)
601 | * am_onyx (Male)
602 | * am_puck (Male)
603 | * am_santa (Male)
604 |
605 | #### British English (`lang_code='b'`)
606 |
607 | * bf_alice (Female)
608 | * bf_emma (Female)
609 | * bf_isabella (Female)
610 | * bf_lily (Female)
611 | * bm_daniel (Male)
612 | * bm_fable (Male)
613 | * bm_george (Male)
614 | * bm_lewis (Male)
615 |
616 | #### Japanese (`lang_code='j'`)
617 |
618 | * jf_alpha (Female)
619 | * jf_gongitsune (Female)
620 | * jf_nezumi (Female)
621 | * jf_tebukuro (Female)
622 | * jm_kumo (Male)
623 |
624 | #### Mandarin Chinese (`lang_code='z'`)
625 |
626 | * zf_xiaobei (Female)
627 | * zf_xiaoni (Female)
628 | * zf_xiaoxiao (Female)
629 | * zf_xiaoyi (Female)
630 | * zm_yunjian (Male)
631 | * zm_yunxi (Male)
632 | * zm_yunxia (Male)
633 | * zm_yunyang (Male)
634 |
635 | #### Spanish (`lang_code='e'`)
636 |
637 | * ef_dora (Female)
638 | * em_alex (Male)
639 | * em_santa (Male)
640 |
641 | #### French (`lang_code='f'`)
642 |
643 | * ff_siwis (Female)
644 |
645 | #### Hindi (`lang_code='h'`)
646 |
647 | * hf_alpha (Female)
648 | * hf_beta (Female)
649 | * hm_omega (Male)
650 | * hm_psi (Male)
651 |
652 | #### Italian (`lang_code='i'`)
653 |
654 | * if_sara (Female)
655 | * im_nicola (Male)
656 |
657 | #### Brazilian Portuguese (`lang_code='p'`)
658 |
659 | * pf_dora (Female)
660 | * pm_alex (Male)
661 | * pm_santa (Male)
662 |
--------------------------------------------------------------------------------
/lue/timing_calculator.py:
--------------------------------------------------------------------------------
1 | """
2 | Word-level timing calculation module for the Lue eBook reader.
3 | """
4 |
5 | import logging
6 | import re
7 | import string
8 | from typing import List, Tuple, Optional, Dict, Any
9 |
10 | def _sanitize_word(word: str) -> str:
11 | """
12 | Sanitize a word by stripping all non-alphanumeric characters and converting to lowercase.
13 |
14 | This function is used for case-insensitive word comparison by removing punctuation
15 | and other special characters, leaving only letters and numbers.
16 |
17 | Args:
18 | word: The word to sanitize
19 |
20 | Returns:
21 | Sanitized word containing only lowercase alphanumeric characters
22 | """
23 | if not word:
24 | return ""
25 |
26 | # Strip all non-alphanumeric characters
27 | sanitized = re.sub(r'[^a-zA-Z0-9]', '', word)
28 |
29 | # Convert to lowercase for case-insensitive comparison
30 | return sanitized.lower()
31 |
32 |
33 | def _get_highlightable_words(text: str) -> list[str]:
34 | """
35 | Get list of words that should be considered for timing.
36 |
37 | This function filters out tokens that contain only punctuation/non-alphanumeric
38 | characters, which should not be counted as words for timing purposes.
39 | Strips punctuation (including commas from em dash replacement) for counting.
40 |
41 | Args:
42 | text: The text to process
43 |
44 | Returns:
45 | List of cleaned words that should be timed
46 | """
47 | # Split on whitespace to get tokens
48 | tokens = text.split()
49 |
50 | # Strip punctuation from tokens and filter out pure punctuation
51 | words = []
52 | for token in tokens:
53 | cleaned = token.strip(string.punctuation)
54 | if cleaned: # Only include non-empty cleaned tokens
55 | words.append(cleaned)
56 |
57 | return words
58 |
59 |
60 | def _extract_core_word(token: str) -> str:
61 | """
62 | Extract the core word from a token by removing surrounding punctuation.
63 |
64 | This function is more robust than simple strip() as it handles nested
65 | punctuation and preserves internal punctuation like contractions.
66 |
67 | Args:
68 | token: The token to process
69 |
70 | Returns:
71 | The core word without surrounding punctuation
72 | """
73 | if not token:
74 | return token
75 |
76 | # Remove leading punctuation
77 | start = 0
78 | while start < len(token) and not token[start].isalnum():
79 | start += 1
80 |
81 | # Remove trailing punctuation
82 | end = len(token) - 1
83 | while end >= start and not token[end].isalnum():
84 | end -= 1
85 |
86 | if start <= end:
87 | return token[start:end + 1]
88 | else:
89 | return ""
90 |
91 |
92 | def create_word_mapping(original_words: List[str], tts_word_timings: List[Tuple[str, float, float]]) -> Optional[List[int]]:
93 | """
94 | Create a mapping from original word indices to TTS word timing indices.
95 | This handles cases where TTS combines words or processes punctuation differently.
96 |
97 | Uses sanitized word comparison with fuzzy matching to handle:
98 | - Punctuation differences between original and TTS text
99 | - Case differences
100 | - Word combining/splitting by TTS engines
101 | - Punctuation-only tokens
102 |
103 | Args:
104 | original_words: List of words from the original text
105 | tts_word_timings: List of (word, start_time, end_time) tuples from TTS
106 |
107 | Returns:
108 | List where index i contains the TTS timing index for original word i,
109 | or None if no valid mapping can be created.
110 | """
111 | # Handle edge cases: empty inputs
112 | if not original_words or not tts_word_timings:
113 | logging.debug("create_word_mapping: Empty input - original_words or tts_word_timings is empty")
114 | return None
115 |
116 | # Extract just the text from TTS timings
117 | tts_words = [word for word, _, _ in tts_word_timings]
118 |
119 | # Sanitize both original and TTS words for comparison
120 | orig_sanitized = [_sanitize_word(word) for word in original_words]
121 | tts_sanitized = [_sanitize_word(word) for word in tts_words]
122 |
123 | # If counts match and sanitized words match, create simple 1:1 mapping
124 | if len(original_words) == len(tts_words):
125 | # Check if sanitized versions match
126 | if orig_sanitized == tts_sanitized:
127 | logging.debug(f"create_word_mapping: Perfect 1:1 match with {len(original_words)} words")
128 | return list(range(len(original_words)))
129 |
130 | # Create enhanced mapping algorithm with fuzzy matching
131 | mapping = []
132 | tts_index = 0
133 |
134 | logging.debug(f"create_word_mapping: Mapping {len(original_words)} original words to {len(tts_words)} TTS words")
135 |
136 | for orig_index, orig_word in enumerate(original_words):
137 | # Handle edge case: exhausted TTS words
138 | if tts_index >= len(tts_words):
139 | # Map remaining original words to the last TTS word
140 | last_tts_index = max(0, len(tts_words) - 1)
141 | mapping.append(last_tts_index)
142 | logging.debug(f"create_word_mapping: Word {orig_index} '{orig_word}' -> TTS {last_tts_index} (exhausted TTS words)")
143 | continue
144 |
145 | orig_sanitized_word = orig_sanitized[orig_index]
146 |
147 | # Handle punctuation-only tokens by mapping to previous word
148 | if not orig_sanitized_word:
149 | # Map punctuation to the previous word's timing, or first TTS word if this is the first original word
150 | if mapping:
151 | prev_mapping = mapping[-1]
152 | mapping.append(prev_mapping)
153 | logging.debug(f"create_word_mapping: Word {orig_index} '{orig_word}' (punctuation-only) -> TTS {prev_mapping} (previous)")
154 | else:
155 | mapping.append(0)
156 | logging.debug(f"create_word_mapping: Word {orig_index} '{orig_word}' (punctuation-only) -> TTS 0 (first)")
157 | continue
158 |
159 | # Find the best matching TTS word using fuzzy matching with scoring
160 | best_match_index = None
161 | best_match_score = 0
162 |
163 | # Look ahead up to 5 positions to find best TTS word match
164 | search_range = min(len(tts_words), tts_index + 5)
165 |
166 | for search_idx in range(tts_index, search_range):
167 | tts_sanitized_word = tts_sanitized[search_idx]
168 |
169 | # Skip empty TTS words (shouldn't happen but handle gracefully)
170 | if not tts_sanitized_word:
171 | continue
172 |
173 | # Calculate match score using fuzzy matching
174 | score = 0
175 |
176 | # Perfect match: sanitized words are identical (score = 100)
177 | if orig_sanitized_word == tts_sanitized_word:
178 | score = 100
179 | # Original word contained in TTS word (score = 80)
180 | elif orig_sanitized_word in tts_sanitized_word:
181 | score = 80
182 | # TTS word contained in original word (score = 60)
183 | elif tts_sanitized_word in orig_sanitized_word:
184 | score = 60
185 | # Similar words using heuristic matching (score = 40)
186 | elif _words_similar(orig_sanitized_word, tts_sanitized_word):
187 | score = 40
188 |
189 | # Update best match if this score is higher
190 | if score > best_match_score:
191 | best_match_score = score
192 | best_match_index = search_idx
193 |
194 | # If we found a perfect match, no need to search further
195 | if score == 100:
196 | break
197 |
198 | # Handle edge case: no matches found
199 | if best_match_index is None or best_match_score == 0:
200 | # No good match found, use current TTS index as fallback
201 | mapping.append(tts_index)
202 | logging.debug(f"create_word_mapping: Word {orig_index} '{orig_word}' -> TTS {tts_index} (no match, fallback)")
203 | tts_index += 1
204 | else:
205 | # Found a match, use it
206 | mapping.append(best_match_index)
207 | logging.debug(f"create_word_mapping: Word {orig_index} '{orig_word}' -> TTS {best_match_index} '{tts_words[best_match_index]}' (score={best_match_score})")
208 |
209 | # Advance tts_index if we found a good match and it's not too far ahead
210 | # This prevents skipping too many TTS words at once
211 | if best_match_index <= tts_index + 2:
212 | tts_index = best_match_index + 1
213 |
214 | # Handle edge case: mismatched counts - log warning
215 | if len(original_words) != len(tts_words):
216 | logging.debug(f"create_word_mapping: Word count mismatch - {len(original_words)} original vs {len(tts_words)} TTS")
217 |
218 | return mapping
219 |
220 |
221 | def _words_similar(word1: str, word2: str) -> bool:
222 | """
223 | Check if two words are similar (for handling slight differences in tokenization).
224 |
225 | Args:
226 | word1: First word to compare
227 | word2: Second word to compare
228 |
229 | Returns:
230 | True if words are similar, False otherwise
231 | """
232 | if not word1 or not word2:
233 | return False
234 |
235 | # Check if one word is a substring of the other with small differences
236 | if len(word1) >= 3 and len(word2) >= 3:
237 | if word1 in word2 or word2 in word1:
238 | return True
239 |
240 | # Check for common prefixes/suffixes
241 | if len(word1) >= 4 and len(word2) >= 4:
242 | if (word1[:3] == word2[:3] and abs(len(word1) - len(word2)) <= 2):
243 | return True
244 |
245 | return False
246 |
247 |
248 | def adjust_word_timings_for_continuity(word_timings: List[Tuple[str, float, float]]) -> List[Tuple[str, float, float]]:
249 | """
250 | Adjust word timings to ensure continuity and handle timing inconsistencies.
251 |
252 | Args:
253 | word_timings: List of (word, start_time, end_time) tuples
254 |
255 | Returns:
256 | Adjusted list of (word, start_time, end_time) tuples
257 | """
258 | if len(word_timings) <= 1:
259 | return word_timings
260 |
261 | adjusted_word_timings = []
262 |
263 | # First pass: fix any obviously broken timings
264 | cleaned_timings = []
265 | for i, (word, start_time, end_time) in enumerate(word_timings):
266 | # Skip entries with None values
267 | if start_time is None or end_time is None:
268 | cleaned_timings.append((word, start_time, end_time))
269 | continue
270 |
271 | # Fix backwards timings
272 | if end_time < start_time:
273 | # Swap them or use a small duration
274 | if start_time > 0:
275 | end_time = start_time + 0.1
276 | else:
277 | start_time, end_time = end_time, start_time + 0.1
278 |
279 | # Ensure minimum duration
280 | if end_time - start_time < 0.05: # Minimum 50ms
281 | end_time = start_time + 0.05
282 |
283 | cleaned_timings.append((word, start_time, end_time))
284 |
285 | # Second pass: ensure continuity
286 | for i in range(len(cleaned_timings)):
287 | word, start_time, end_time = cleaned_timings[i]
288 |
289 | # Skip entries with None values
290 | if start_time is None or end_time is None:
291 | adjusted_word_timings.append((word, start_time, end_time))
292 | continue
293 |
294 | # For all words except the last one, adjust end time for continuity
295 | if i < len(cleaned_timings) - 1:
296 | next_word, next_start_time, next_end_time = cleaned_timings[i + 1]
297 |
298 | # Only adjust if next start time is valid
299 | if next_start_time is not None:
300 | # If there's a gap, extend current word to fill it
301 | if next_start_time > end_time:
302 | adjusted_end_time = next_start_time
303 | # If there's overlap, split the difference
304 | elif next_start_time < end_time:
305 | adjusted_end_time = (end_time + next_start_time) / 2
306 | else:
307 | adjusted_end_time = end_time
308 | else:
309 | adjusted_end_time = end_time
310 | else:
311 | # For the last word, keep the original end time
312 | adjusted_end_time = end_time
313 |
314 | adjusted_word_timings.append((word, start_time, adjusted_end_time))
315 |
316 | return adjusted_word_timings
317 |
318 |
319 | def calculate_speech_duration(word_timings: List[Tuple[str, float, float]]) -> float:
320 | """
321 | Calculate the total speech duration from word timings.
322 |
323 | Args:
324 | word_timings: List of (word, start_time, end_time) tuples
325 |
326 | Returns:
327 | Speech duration in seconds
328 | """
329 | if not word_timings:
330 | return 0.0
331 |
332 | return max([end for _, _, end in word_timings])
333 |
334 |
335 | def estimate_word_timings_from_duration(text: str, total_duration: float) -> List[Tuple[str, float, float]]:
336 | """
337 | Estimate word timings based on word count and total duration.
338 | This is a fallback when TTS doesn't provide precise timing information.
339 |
340 | Args:
341 | text: The text that was spoken
342 | total_duration: Total duration of the audio in seconds
343 |
344 | Returns:
345 | List of (word, start_time, end_time) tuples
346 | """
347 | # Use the improved word filtering function
348 | words = _get_highlightable_words(text)
349 | if not words:
350 | return []
351 |
352 | # If we couldn't get duration, estimate 0.3 seconds per word
353 | if total_duration is None or total_duration <= 0:
354 | total_duration = len(words) * 0.3
355 |
356 | time_per_word = total_duration / len(words)
357 | word_timings = []
358 |
359 | for i, word in enumerate(words):
360 | start_time = i * time_per_word
361 | end_time = (i + 1) * time_per_word
362 | word_timings.append((word, start_time, end_time))
363 |
364 | return word_timings
365 |
366 |
367 | def process_tts_timing_data(
368 | original_text: str,
369 | raw_word_timings: List[Tuple[str, float, float]],
370 | total_duration: Optional[float] = None
371 | ) -> Dict[str, Any]:
372 | """
373 | Process raw timing data from TTS into a standardized format with all necessary
374 | calculations and adjustments applied.
375 |
376 | Args:
377 | original_text: The original text that was spoken
378 | raw_word_timings: Raw word timings from TTS engine
379 | total_duration: Total audio duration (optional, will be calculated if not provided)
380 |
381 | Returns:
382 | Dictionary containing:
383 | - word_timings: Adjusted word timings
384 | - speech_duration: Duration of speech content
385 | - total_duration: Total audio duration
386 | - word_mapping: Mapping from original words to TTS timings
387 | """
388 | try:
389 | # If no raw timings provided, estimate from duration
390 | if not raw_word_timings:
391 | if total_duration is None:
392 | logging.warning("No timing data and no duration provided, using fallback estimation")
393 | total_duration = len(original_text.split()) * 0.3
394 |
395 | word_timings = estimate_word_timings_from_duration(original_text, total_duration)
396 | speech_duration = total_duration
397 | else:
398 | # Log raw timing data for debugging
399 | logging.debug(f"Processing {len(raw_word_timings)} raw timing entries for text: '{original_text[:50]}...'")
400 |
401 | # Adjust raw timings for continuity
402 | word_timings = adjust_word_timings_for_continuity(raw_word_timings)
403 | speech_duration = calculate_speech_duration(word_timings)
404 |
405 | # Create word mapping using the improved word filtering
406 | original_words = _get_highlightable_words(original_text)
407 | word_mapping = create_word_mapping(original_words, word_timings)
408 |
409 | # Log mapping information for debugging
410 | if word_mapping:
411 | logging.debug(f"Created word mapping: {len(original_words)} original words -> {len(word_timings)} TTS timings")
412 | if len(original_words) != len(word_timings):
413 | logging.debug(f"Word count mismatch - Original: {original_words}, TTS: {[w for w, _, _ in word_timings]}")
414 |
415 | # Use provided total_duration or fall back to speech_duration
416 | final_total_duration = total_duration if total_duration is not None else speech_duration
417 |
418 | return {
419 | "word_timings": word_timings,
420 | "speech_duration": speech_duration,
421 | "total_duration": final_total_duration,
422 | "word_mapping": word_mapping
423 | }
424 |
425 | except Exception as e:
426 | logging.error(f"Error processing TTS timing data: {e}", exc_info=True)
427 | # Return fallback data
428 | # Use the improved word filtering function
429 | fallback_words = _get_highlightable_words(original_text)
430 | fallback_duration = len(fallback_words) * 0.3
431 | fallback_timings = estimate_word_timings_from_duration(original_text, fallback_duration)
432 |
433 | return {
434 | "word_timings": fallback_timings,
435 | "speech_duration": fallback_duration,
436 | "total_duration": fallback_duration,
437 | "word_mapping": create_word_mapping(fallback_words, fallback_timings)
438 | }
439 |
440 |
441 | def validate_timing_data(timing_data: Dict[str, Any]) -> bool:
442 | """
443 | Validate that timing data contains all required fields and is properly formatted.
444 |
445 | Args:
446 | timing_data: Dictionary containing timing information
447 |
448 | Returns:
449 | True if valid, False otherwise
450 | """
451 | required_fields = ["word_timings", "speech_duration", "total_duration"]
452 |
453 | for field in required_fields:
454 | if field not in timing_data:
455 | return False
456 |
457 | word_timings = timing_data["word_timings"]
458 | if not isinstance(word_timings, list):
459 | return False
460 |
461 | # Check that each timing entry is properly formatted
462 | for timing in word_timings:
463 | if not isinstance(timing, tuple) or len(timing) != 3:
464 | return False
465 | word, start_time, end_time = timing
466 | if not isinstance(word, str):
467 | return False
468 | # Allow None values for start_time and end_time, but if they're not None, they should be numbers
469 | if start_time is not None and not isinstance(start_time, (int, float)):
470 | return False
471 | if end_time is not None and not isinstance(end_time, (int, float)):
472 | return False
473 | # If both are numbers, check the relationship
474 | if isinstance(start_time, (int, float)) and isinstance(end_time, (int, float)) and start_time < 0:
475 | return False
476 | if (isinstance(start_time, (int, float)) and isinstance(end_time, (int, float)) and
477 | end_time < start_time):
478 | return False
479 |
480 | return True
481 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------