├── docker ├── .swp ├── run.sh ├── entrypoint.sh ├── Dockerfile ├── docker-compose-v2.yml ├── docker-compose-v1.yml └── DOCKER.md ├── .gitignore ├── doki ├── samples └── welcome.wav ├── kokorodoki ├── src ├── main.py ├── config.py ├── input_hander.py ├── client.py ├── utils.py ├── models.py ├── run.py └── gui.py ├── requirements.txt ├── test_subtitle.srt ├── generate_kokorodoki_service.sh ├── example_subtitles.srt ├── SRT_USAGE.md ├── test_srt_parsing.py ├── windows.md ├── README.MD └── LICENSE /docker/.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eel-brah/kokorodoki/HEAD/docker/.swp -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | tests 2 | .kokorodoki_history 3 | __pycache__ 4 | req.txt 5 | custom_shortcut 6 | -------------------------------------------------------------------------------- /doki: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | ~/.venvs/kdvenv/bin/python3.12 ~/.local/bin/kdoki/src/client.py "$@" 3 | -------------------------------------------------------------------------------- /samples/welcome.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eel-brah/kokorodoki/HEAD/samples/welcome.wav -------------------------------------------------------------------------------- /kokorodoki: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | ~/.venvs/kdvenv/bin/python3.12 ~/.local/bin/kdoki/src/main.py "$@" 3 | -------------------------------------------------------------------------------- /docker/run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | export UIDD=$(id -u) 4 | export XDG_RUNTIME_DIR="/run/user/$UIDD" 5 | export WAYLAND_DISPLAY="wayland-0" 6 | export DISPLAY=${DISPLAY:-:0} 7 | 8 | docker compose up "$@" 9 | -------------------------------------------------------------------------------- /docker/entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | echo "Starting..." 5 | echo "TTY: $(tty)" 6 | 7 | if [ "$SKIP_STARTUP_MSG" != "1" ]; then 8 | /root/.local/bin/kdoki/kokorodoki -t "Starting..." 9 | fi 10 | 11 | exec /root/.local/bin/kdoki/kokorodoki "$@" 12 | -------------------------------------------------------------------------------- /src/main.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | from input_hander import Args, parse_args 4 | from utils import init_completer, init_history 5 | 6 | 7 | def main(): 8 | """Main entry point.""" 9 | args: Args = parse_args() 10 | 11 | init_completer() 12 | init_history(args.history_off) 13 | 14 | from run import start 15 | 16 | start(args) 17 | 18 | 19 | if __name__ == "__main__": 20 | sys.exit(main()) 21 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | kokoro==0.9.2 --index-url https://pypi.org/simple 2 | sounddevice==0.5.1 3 | soundfile==0.13.1 4 | rich==14.0.0 5 | nltk==3.9.1 6 | librosa==0.11.0 7 | ttkbootstrap==1.12.0 8 | easyocr==1.7.2 9 | cn2an==0.5.23 10 | fugashi==1.5.1 11 | jaconv==0.4.0 12 | jieba==0.42.1 13 | mojimoji==0.0.13 14 | ordered-set==4.1.0 15 | proces==0.1.7 16 | pyopenjtalk==0.4.1 17 | pypinyin==0.55.0 18 | unidic-lite==1.0.8 19 | PyAutoGUI==0.9.54 20 | -------------------------------------------------------------------------------- /test_subtitle.srt: -------------------------------------------------------------------------------- 1 | 1 2 | 00:00:00,000 --> 00:00:03,000 3 | Hello and welcome to our demonstration. 4 | 5 | 2 6 | 00:00:04,000 --> 00:00:07,500 7 | This is how SRT subtitles work with timed audio generation. 8 | 9 | 3 10 | 00:00:08,500 --> 00:00:12,000 11 | Each subtitle entry will be spoken at the correct time. 12 | 13 | 4 14 | 00:00:13,000 --> 00:00:16,500 15 | Perfect for creating synchronized audio content. 16 | 17 | 5 18 | 00:00:17,500 --> 00:00:20,000 19 | Thank you for listening! 20 | -------------------------------------------------------------------------------- /generate_kokorodoki_service.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | HOME_DIR="$HOME" 4 | 5 | DISPLAY_VAR="${DISPLAY:-:0}" 6 | 7 | WORKING_DIR="$HOME_DIR/.local/bin/kdoki/src" 8 | PYTHON_EXEC="$HOME_DIR/.venvs/kdvenv/bin/python3.12" 9 | MAIN_SCRIPT="$WORKING_DIR/main.py" 10 | SERVICE_PATH="$HOME_DIR/.config/systemd/user/kokorodoki.service" 11 | 12 | mkdir -p "$(dirname "$SERVICE_PATH")" 13 | 14 | cat > "$SERVICE_PATH" < 00:00:04,000 3 | Welcome to KokoroDoki's new SRT subtitle feature! 4 | 5 | 2 6 | 00:00:05,000 --> 00:00:10,500 7 | This powerful enhancement allows you to generate 8 | perfectly timed audio from subtitle files. 9 | 10 | 3 11 | 00:00:12,500 --> 00:00:17,000 12 | Each subtitle entry is processed individually 13 | and placed at its exact timestamp. 14 | 15 | 4 16 | 00:00:18,000 --> 00:00:22,000 17 | You can now create synchronized voiceovers 18 | for videos, presentations, and more. 19 | 20 | 5 21 | 00:00:22,500 --> 00:00:27,000 22 | The generated audio maintains perfect timing 23 | with your original subtitles. 24 | 25 | 6 26 | 00:00:29,000 --> 00:00:33,500 27 | This opens up new possibilities for 28 | content creation and accessibility. 29 | 30 | 7 31 | 00:00:34,500 --> 00:00:38,500 32 | Try it out with your own SRT files 33 | and experience the synchronization! 34 | 35 | 8 36 | 00:00:39,000 --> 00:00:41,000 37 | Thank you for using KokoroDoki! 38 | -------------------------------------------------------------------------------- /docker/docker-compose-v2.yml: -------------------------------------------------------------------------------- 1 | x-kdoki-base: &kdoki-base 2 | build: 3 | context: .. 4 | dockerfile: docker/Dockerfile 5 | runtime: nvidia 6 | devices: 7 | - /dev/snd:/dev/snd 8 | - nvidia.com/gpu=all 9 | volumes: 10 | - /etc/asound.conf:/etc/asound.conf:ro 11 | - /usr/share/alsa:/usr/share/alsa:ro 12 | - ${XDG_RUNTIME_DIR}/pulse/native:${XDG_RUNTIME_DIR}/pulse/native 13 | environment: 14 | - PULSE_SERVER=unix:${XDG_RUNTIME_DIR}/pulse/native 15 | - XDG_RUNTIME_DIR=${XDG_RUNTIME_DIR} 16 | 17 | services: 18 | kdoki: 19 | <<: *kdoki-base 20 | tty: true 21 | stdin_open: true 22 | 23 | kdoki_daemon: 24 | <<: *kdoki-base 25 | ports: 26 | - "6155:5561" 27 | command: ["--daemon"] 28 | 29 | kdoki_gui: 30 | <<: *kdoki-base 31 | volumes: 32 | - /tmp/.X11-unix:/tmp/.X11-unix 33 | - ${XDG_RUNTIME_DIR}/${WAYLAND_DISPLAY}:${XDG_RUNTIME_DIR}/${WAYLAND_DISPLAY} 34 | environment: 35 | - DISPLAY=${DISPLAY} 36 | - WAYLAND_DISPLAY=${WAYLAND_DISPLAY} 37 | - XDG_RUNTIME_DIR=${XDG_RUNTIME_DIR} 38 | - QT_QPA_PLATFORM=wayland 39 | - GDK_BACKEND=wayland,x11 40 | command: ["--gui"] 41 | 42 | kdoki_gen: 43 | <<: *kdoki-base 44 | volumes: 45 | - ./input:/input 46 | - ./output:/output 47 | command: ["-f", "/input/${INPUT_FILE}", "-o", "/output/${OUTPUT_FILE}"] 48 | environment: 49 | - INPUT_FILE=${INPUT_FILE} 50 | - OUTPUT_FILE=${OUTPUT_FILE} 51 | - SKIP_STARTUP_MSG=1 52 | -------------------------------------------------------------------------------- /docker/docker-compose-v1.yml: -------------------------------------------------------------------------------- 1 | x-kdoki-base: &kdoki-base 2 | build: 3 | context: .. 4 | dockerfile: docker/Dockerfile 5 | runtime: nvidia 6 | deploy: 7 | resources: 8 | reservations: 9 | devices: 10 | - capabilities: [gpu] 11 | devices: 12 | - /dev/snd:/dev/snd 13 | volumes: 14 | - /etc/asound.conf:/etc/asound.conf:ro 15 | - /usr/share/alsa:/usr/share/alsa:ro 16 | - ${XDG_RUNTIME_DIR}/pulse/native:${XDG_RUNTIME_DIR}/pulse/native 17 | environment: 18 | - PULSE_SERVER=unix:${XDG_RUNTIME_DIR}/pulse/native 19 | - XDG_RUNTIME_DIR=${XDG_RUNTIME_DIR} 20 | 21 | services: 22 | kdoki: 23 | <<: *kdoki-base 24 | tty: true 25 | stdin_open: true 26 | 27 | kdoki_daemon: 28 | <<: *kdoki-base 29 | ports: 30 | - "6155:5561" 31 | command: ["--daemon"] 32 | 33 | kdoki_gui: 34 | <<: *kdoki-base 35 | volumes: 36 | - /tmp/.X11-unix:/tmp/.X11-unix 37 | - ${XDG_RUNTIME_DIR}/${WAYLAND_DISPLAY}:${XDG_RUNTIME_DIR}/${WAYLAND_DISPLAY} 38 | environment: 39 | - DISPLAY=${DISPLAY} 40 | - WAYLAND_DISPLAY=${WAYLAND_DISPLAY} 41 | - XDG_RUNTIME_DIR=${XDG_RUNTIME_DIR} 42 | - QT_QPA_PLATFORM=wayland 43 | - GDK_BACKEND=wayland,x11 44 | command: ["--gui"] 45 | 46 | kdoki_gen: 47 | <<: *kdoki-base 48 | volumes: 49 | - ./input:/input 50 | - ./output:/output 51 | command: ["-f", "/input/${INPUT_FILE}", "-o", "/output/${OUTPUT_FILE}"] 52 | environment: 53 | - INPUT_FILE=${INPUT_FILE} 54 | - OUTPUT_FILE=${OUTPUT_FILE} 55 | - SKIP_STARTUP_MSG=1 56 | -------------------------------------------------------------------------------- /SRT_USAGE.md: -------------------------------------------------------------------------------- 1 | # SRT Subtitle Support in KokoroDoki 2 | 3 | ## Overview 4 | 5 | KokoroDoki now supports generating timed audio from SRT subtitle files. This feature allows you to create perfectly synchronized audio content that matches subtitle timestamps. SRT files are automatically detected based on the `.srt` file extension. 6 | 7 | ## Usage 8 | 9 | ### Basic Usage 10 | ```bash 11 | # Generate timed audio from SRT file (auto-detected) 12 | kokorodoki -f subtitles.srt -o synchronized_audio.wav 13 | ``` 14 | 15 | ### With Custom Voice and Language 16 | ```bash 17 | # American English with heart voice 18 | kokorodoki -f subtitles.srt -l a -v af_heart -o output.wav 19 | 20 | # British English with lily voice 21 | kokorodoki -f subtitles.srt -l b -v bf_lily -o british_audio.wav 22 | ``` 23 | 24 | ## SRT File Format 25 | 26 | SRT files should follow the standard format: 27 | ``` 28 | 1 29 | 00:00:00,000 --> 00:00:03,000 30 | First subtitle text goes here. 31 | 32 | 2 33 | 00:00:04,000 --> 00:00:07,500 34 | Second subtitle with multiple lines 35 | can span across several lines. 36 | 37 | 3 38 | 00:00:08,500 --> 00:00:12,000 39 | Third subtitle entry. 40 | ``` 41 | 42 | ## Features 43 | 44 | - **Automatic Detection**: SRT files are automatically detected by `.srt` extension 45 | - **Perfect Timing**: Audio is generated at exact subtitle timestamps 46 | - **Multi-line Support**: Subtitles spanning multiple lines are handled correctly 47 | - **Flexible Duration**: Adapts to different subtitle timing patterns 48 | - **Voice Options**: Use any available voice and language combination 49 | 50 | ## Example Files 51 | 52 | - `test_subtitle.srt` - Simple 5-entry example 53 | - `example_subtitles.srt` - More comprehensive 8-entry demonstration 54 | 55 | ## Technical Details 56 | 57 | - Generated audio maintains silence between subtitle entries 58 | - Long subtitles are automatically split into sentences for better processing 59 | - Audio duration matches the longest subtitle timestamp 60 | - Stereo output format is used for compatibility 61 | 62 | ## Limitations 63 | 64 | - SRT files must use the standard format (index, timestamp, text) 65 | - The `--all` flag is not supported with SRT files (use single voice) 66 | - Output format is always WAV 67 | - Files must have `.srt` extension to be detected as SRT files 68 | 69 | ## Troubleshooting 70 | 71 | If you encounter issues: 72 | 1. Verify your SRT file follows the standard format 73 | 2. Check that timestamps are in HH:MM:SS,mmm format 74 | 3. Ensure the SRT file is UTF-8 encoded 75 | 4. Make sure each entry has an index, timestamp, and text 76 | -------------------------------------------------------------------------------- /test_srt_parsing.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Simple test for SRT parsing functionality without dependencies""" 3 | 4 | import re 5 | from dataclasses import dataclass 6 | from typing import List 7 | 8 | 9 | @dataclass 10 | class SRTEntry: 11 | """Represents a single SRT subtitle entry""" 12 | index: int 13 | start_time: float # in seconds 14 | end_time: float # in seconds 15 | text: str 16 | 17 | 18 | def parse_srt_timestamp(timestamp: str) -> float: 19 | """Parse SRT timestamp format (HH:MM:SS,mmm) to seconds""" 20 | # Replace comma with dot for milliseconds 21 | timestamp = timestamp.replace(',', '.') 22 | parts = timestamp.split(':') 23 | hours = int(parts[0]) 24 | minutes = int(parts[1]) 25 | seconds_ms = float(parts[2]) 26 | 27 | return hours * 3600 + minutes * 60 + seconds_ms 28 | 29 | 30 | def parse_srt_file(file_path: str) -> List[SRTEntry]: 31 | """Parse an SRT subtitle file and return a list of SRTEntry objects""" 32 | entries = [] 33 | 34 | with open(file_path, 'r', encoding='utf-8') as f: 35 | content = f.read().strip() 36 | 37 | # Split by double newlines to separate entries 38 | blocks = re.split(r'\n\s*\n', content) 39 | 40 | for block in blocks: 41 | lines = block.strip().split('\n') 42 | if len(lines) < 3: 43 | continue 44 | 45 | try: 46 | # Parse index 47 | index = int(lines[0]) 48 | 49 | # Parse timestamp line 50 | timestamp_line = lines[1] 51 | timestamp_match = re.match(r'(\d{2}:\d{2}:\d{2},\d{3})\s*-->\s*(\d{2}:\d{2}:\d{2},\d{3})', timestamp_line) 52 | if not timestamp_match: 53 | continue 54 | 55 | start_time = parse_srt_timestamp(timestamp_match.group(1)) 56 | end_time = parse_srt_timestamp(timestamp_match.group(2)) 57 | 58 | # Join text lines (in case subtitle spans multiple lines) 59 | text = '\n'.join(lines[2:]).strip() 60 | 61 | entries.append(SRTEntry(index, start_time, end_time, text)) 62 | 63 | except (ValueError, IndexError): 64 | # Skip malformed entries 65 | continue 66 | 67 | return entries 68 | 69 | 70 | if __name__ == "__main__": 71 | # Test the SRT parsing function 72 | try: 73 | entries = parse_srt_file('test_subtitle.srt') 74 | print(f'Successfully parsed {len(entries)} SRT entries:') 75 | print() 76 | 77 | for entry in entries: 78 | print(f'Entry {entry.index}:') 79 | print(f' Time: {entry.start_time:.1f}s - {entry.end_time:.1f}s (duration: {entry.end_time - entry.start_time:.1f}s)') 80 | print(f' Text: "{entry.text}"') 81 | print() 82 | 83 | print("✅ SRT parsing test completed successfully!") 84 | 85 | except Exception as e: 86 | print(f"❌ Error testing SRT parsing: {e}") 87 | -------------------------------------------------------------------------------- /docker/DOCKER.md: -------------------------------------------------------------------------------- 1 | # KokoroDoki Docker Setup 2 | 3 | ## Prerequisites 4 | 5 | * **NVIDIA GPU Drivers** 6 | Ensure that your system has a compatible NVIDIA driver installed. 7 | 8 | Run the following command to verify: 9 | 10 | ```bash 11 | nvidia-smi 12 | ``` 13 | 14 | Make sure the reported **CUDA Version** is **≥ 12.8**. 15 | 16 | * **Docker** 17 | Install Docker if it isn't already installed: 18 | [https://docs.docker.com/get-docker/](https://docs.docker.com/get-docker/) 19 | 20 | ## Setup 21 | 22 | ### 1. Install NVIDIA Container Toolkit 23 | 24 | Follow the official installation and configuration guides: 25 | 26 | * **Installation**: 27 | [NVIDIA Container Toolkit Installation Guide](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html) 28 | 29 | * **Configuration**: 30 | [Configuration Guide](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html#configuration) 31 | 32 | ### 2. Verify NVIDIA Container Runtime 33 | 34 | Run a sample workload to test your setup: 35 | [NVIDIA Sample Workload Guide](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/sample-workload.html) 36 | 37 | 38 | If you encounter the error like this: 39 | ``` 40 | Failed to initialize NVML: Unknown Error 41 | ``` 42 | 43 | This workaround may help: 44 | 👉 [GitHub Issue #381 - Comment](https://github.com/NVIDIA/nvidia-container-toolkit/issues/381#issuecomment-1970824522) 45 | 46 | After applying the workaround, run the following command to verify it's working: 47 | ```bash 48 | docker run --rm --runtime=nvidia --device=nvidia.com/gpu=all ubuntu nvidia-smi 49 | ``` 50 | 51 | ## Docker Compose Configuration 52 | 53 | Depending on whether you applied the NVML fix mentioned above: 54 | 55 | * **If you applied the fix**: 56 | 57 | ```bash 58 | cp docker-compose-v2.yml docker-compose.yml 59 | chmod +x run.sh 60 | ``` 61 | 62 | * **Otherwise**: 63 | 64 | ```bash 65 | cp docker-compose-v1.yml docker-compose.yml 66 | chmod +x run.sh 67 | ``` 68 | 69 | ## Running the Application 70 | 71 | ### Console Mode 72 | 73 | ```bash 74 | docker compose build kdoki 75 | ./run.sh kdoki -d 76 | docker attach 77 | ``` 78 | 79 | ### GUI Mode 80 | 81 | Make X server available to Docker: 82 | ```bash 83 | xhost +local:docker 84 | ``` 85 | 86 | Then run: 87 | ```bash 88 | docker compose build kdoki_gui 89 | ./run.sh kdoki_gui 90 | ``` 91 | 92 | ### Daemon Mode 93 | 94 | ```bash 95 | python3 -m venv mvenv 96 | source mvenv/bin/activate 97 | pip install rich nltk 98 | 99 | docker compose build kdoki_daemon 100 | ./run.sh kdoki_daemon 101 | ``` 102 | 103 | You can send clipboard content to the daemon using `src/client.py` (port `6155`): 104 | 105 | Example: 106 | 107 | 1. Copy some text like: 108 | ``` 109 | This is a test. 110 | ``` 111 | 112 | 2. Run: 113 | ```bash 114 | source mvenv/bin/activate 115 | python3 src/client.py --port 6155 116 | python3 src/client.py -h 117 | ``` 118 | 119 | ### Generate an Audio File from Text 120 | 121 | Place the text you want to convert into input/input.txt. 122 | Use the following command to generate the output file: 123 | ```bash 124 | INPUT_FILE=input.txt OUTPUT_FILE=output.wav ./run.sh kdoki_gen 125 | ``` 126 | This will produce the audio file at: output/output.wav 127 | -------------------------------------------------------------------------------- /windows.md: -------------------------------------------------------------------------------- 1 | # Kokorodoki – Windows Setup Guide 2 | 3 | This guide walks you through setting up **Kokorodoki** on **Windows**. 4 | 5 | --- 6 | 7 | ## Prerequisites 8 | 9 | ### 1. Install Python 3.12 10 | 11 | * Download: [https://www.python.org/downloads/release/python-3120/](https://www.python.org/downloads/release/python-3120/) 12 | * During installation, **make sure to check**: `Add Python to PATH` 13 | 14 | ### 2. Install Git for Windows 15 | 16 | * Download: [https://git-scm.com/downloads](https://git-scm.com/downloads) 17 | 18 | ### 3. Install eSpeak NG 19 | 20 | * Download the `.exe` installer from: 21 | [https://github.com/espeak-ng/espeak-ng/releases](https://github.com/espeak-ng/espeak-ng/releases) 22 | 23 | ### 4. C++ Development Tools 24 | 25 | * Download: [Visual Studio Community](https://visualstudio.microsoft.com/vs/community/) 26 | * Run the Visual Studio Installer: The installer will open after download 27 | * In the "Workloads" tab: Check “Desktop development with C++” 28 | * Click “Install” 29 | 30 | 31 | ## GPU Acceleration (CUDA Support) 32 | 33 | If you have an NVIDIA GPU and want faster performance: 34 | 35 | Install the **CUDA Toolkit**: 36 | [https://developer.nvidia.com/cuda-downloads](https://developer.nvidia.com/cuda-downloads) 37 | 38 | 39 | ## Installation 40 | 41 | You can use **PowerShell** or **Git Bash**. The steps below use **Git Bash**: 42 | 43 | ```bash 44 | # Navigate to your home directory 45 | cd 46 | 47 | # Clone the repository 48 | git clone https://github.com/eel-brah/kokorodoki kdoki 49 | 50 | # Create and activate a virtual environment 51 | python -m venv kdvenv 52 | source kdvenv/Scripts/activate # Use kdvenv\Scripts\activate.ps1 on PowerShell 53 | 54 | # Install dependencies 55 | pip install -r kdoki/requirements.txt 56 | pip install pyreadline3 pyperclip 57 | 58 | # Run the application 59 | python kdoki/src/main.py 60 | ``` 61 | 62 | > The first run may take some time as it downloads the AI model. 63 | 64 | ### Running with CUDA 65 | 66 | If you installed CUDA but it using CPU by default, run: 67 | 68 | ```bash 69 | python kdoki/src/main.py --device cuda 70 | ``` 71 | 72 | If it fails, see the troubleshooting section below. 73 | 74 | 75 | ## Daemon Mode on Windows 76 | 77 | Since Windows doesn't support systemd, you can simulate daemon mode using a `.bat` file: 78 | 79 | ```bat 80 | @echo off 81 | call path\to\kdvenv\Scripts\activate 82 | python path\to\kdoki\src\main.py --daemon 83 | ``` 84 | 85 | Then use **Task Scheduler**: 86 | 87 | * Create a scheduled task 88 | * Run the daemon script at login or bind it to a hotkey 89 | 90 | --- 91 | 92 | ## Keyboard Shortcuts (with AutoHotkey) 93 | 94 | 1. Install AutoHotkey: [https://www.autohotkey.com/](https://www.autohotkey.com/) 95 | 96 | 2. Create a script file (e.g., `kdoki.ahk`): 97 | 98 | For example: 99 | 100 | ```ahk 101 | ; Ctrl+Alt+A to send 102 | ^!a::Run, C:\path\to\kdvenv\Scripts\python.exe C:\path\to\kdoki\src\client.py 103 | 104 | ; Ctrl+Alt+P to pause 105 | ^!p::Run, C:\path\to\kdvenv\Scripts\python.exe C:\path\to\kdoki\src\client.py --pause 106 | 107 | ; Ctrl+Alt+R to resume 108 | ^!r::Run, C:\path\to\kdvenv\Scripts\python.exe C:\path\to\kdoki\src\client.py --resume 109 | 110 | ; Ctrl+Alt+S to stop 111 | ^!s::Run, C:\path\to\kdvenv\Scripts\python.exe C:\path\to\kdoki\src\client.py --stop 112 | 113 | ; Ctrl+Alt+N for next 114 | ^!n::Run, C:\path\to\kdvenv\Scripts\python.exe C:\path\to\kdoki\src\client.py --next 115 | 116 | ; Ctrl+Alt+B for previous 117 | ^!b::Run, C:\path\to\kdvenv\Scripts\python.exe C:\path\to\kdoki\src\client.py --back 118 | ``` 119 | 120 | 3. Run the script to enable global hotkeys. 121 | 122 | --- 123 | 124 | ## ⚠️ Troubleshooting 125 | 126 | Check your Torch (PyTorch) configuration: 127 | 128 | ```python 129 | import torch 130 | print(torch.__version__) 131 | print(torch.version.cuda) 132 | print(torch.cuda.is_available()) 133 | ``` 134 | 135 | If CUDA is not available, reinstall PyTorch with GPU support: 136 | 137 | ```bash 138 | pip uninstall torch -y 139 | pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121 140 | ``` 141 | 142 | Then try running Kokorodoki with CUDA: 143 | 144 | ```bash 145 | python kdoki/src/main.py --device cuda 146 | ``` 147 | 148 | You're all set! 🚀 149 | -------------------------------------------------------------------------------- /src/input_hander.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import sys 3 | from dataclasses import dataclass 4 | from typing import Optional 5 | 6 | from config import ( 7 | DEFAULT_LANGUAGE, 8 | DEFAULT_SPEED, 9 | DEFAULT_THEME, 10 | DEFAULT_VOICE, 11 | MAX_SPEED, 12 | MIN_SPEED, 13 | PORT, 14 | console, 15 | ) 16 | from utils import ( 17 | display_languages, 18 | display_themes, 19 | display_voices, 20 | get_gui_themes, 21 | get_language_map, 22 | get_voices, 23 | save_history, 24 | ) 25 | 26 | 27 | @dataclass 28 | class Args: 29 | language: str 30 | voice: str 31 | speed: float 32 | history_off: bool 33 | device: Optional[str] 34 | input_text: Optional[str] 35 | output_file: Optional[str] 36 | all_voices: bool 37 | setup: bool 38 | daemon: bool 39 | port: int 40 | gui: bool 41 | theme: int 42 | verbose: bool 43 | ctrl_c: bool 44 | is_srt_file: bool 45 | 46 | 47 | def parse_args() -> Args: 48 | """Parse command-line arguments""" 49 | parser = argparse.ArgumentParser( 50 | prog="kokorodoki", 51 | description="Real-time TTS with Kokoro-82M.", 52 | ) 53 | 54 | parser.add_argument( 55 | "--list-languages", 56 | "--list_languages", 57 | action="store_true", 58 | help="List available languages", 59 | ) 60 | parser.add_argument( 61 | "--list-voices", 62 | "--list_voices", 63 | type=str, 64 | nargs="?", 65 | const=None, 66 | default=False, 67 | help="List available voices. Optionally provide a language to filter by.", 68 | ) 69 | parser.add_argument( 70 | "--themes", 71 | action="store_true", 72 | help="Show the available gui themes", 73 | ) 74 | 75 | parser.add_argument( 76 | "--language", 77 | "-l", 78 | type=str, 79 | default=DEFAULT_LANGUAGE, 80 | help=f"Initial language code (default: '{DEFAULT_LANGUAGE}' for American English)", 81 | ) 82 | parser.add_argument( 83 | "--voice", 84 | "-v", 85 | type=str, 86 | default=DEFAULT_VOICE, 87 | help=f"Initial voice (default: '{DEFAULT_VOICE}')", 88 | ) 89 | parser.add_argument( 90 | "--speed", 91 | "-s", 92 | type=float, 93 | default=DEFAULT_SPEED, 94 | help=f"Initial speed (default: {DEFAULT_SPEED}, range: {MIN_SPEED}-{MAX_SPEED})", 95 | ) 96 | parser.add_argument( 97 | "--device", 98 | type=str, 99 | default=None, 100 | choices=["cuda", "cpu"], 101 | help=( 102 | "Set the device for computation ('cuda' for GPU or 'cpu'). " 103 | "Default: Auto-selects 'cuda' if available, otherwise falls back to 'cpu'. " 104 | "If 'cuda' is specified but unavailable, raises an error." 105 | ), 106 | ) 107 | 108 | parser.add_argument( 109 | "--history-off", 110 | "--history_off", 111 | action="store_true", 112 | help="Disable the saving of history", 113 | ) 114 | parser.add_argument( 115 | "--verbose", 116 | "-V", 117 | action="store_true", 118 | help="Print what is being done", 119 | ) 120 | parser.add_argument( 121 | "--ctrl_c_off", 122 | "-c", 123 | action="store_true", 124 | help="Make Ctrl+C not end playback", 125 | ) 126 | 127 | parser.add_argument( 128 | "--all", 129 | action="store_true", 130 | help="Read a text/file with all the available voices (only valid when --text or --file is used)", 131 | ) 132 | input_group = parser.add_mutually_exclusive_group() 133 | input_group.add_argument( 134 | "--text", 135 | "-t", 136 | default=None, 137 | type=str, 138 | help="Supply text", 139 | ) 140 | input_group.add_argument( 141 | "--file", 142 | "-f", 143 | default=None, 144 | type=str, 145 | help="Supply path to a text file or SRT subtitle file (SRT files detected automatically)", 146 | ) 147 | parser.add_argument( 148 | "--output", 149 | "-o", 150 | type=str, 151 | default=None, 152 | help="Output file path (only valid when --text or --file is used)", 153 | ) 154 | parser.add_argument( 155 | "--setup", 156 | action="store_true", 157 | help="Download the models and exit (useful for first-time setup)", 158 | ) 159 | parser.add_argument( 160 | "--daemon", 161 | action="store_true", 162 | help="Daemon mode", 163 | ) 164 | parser.add_argument( 165 | "--port", type=int, default=PORT, help=f"Choose a port number (default: {PORT})" 166 | ) 167 | parser.add_argument( 168 | "--gui", 169 | "-g", 170 | action="store_true", 171 | help="Gui mode", 172 | ) 173 | parser.add_argument( 174 | "--theme", 175 | type=int, 176 | default=DEFAULT_THEME, 177 | help=f"Choose a theme number (default: {get_gui_themes()[DEFAULT_THEME]}, use --themes to get list of themes)", 178 | ) 179 | 180 | args = parser.parse_args() 181 | 182 | # Display lists if requested 183 | if args.list_languages: 184 | display_languages() 185 | sys.exit(0) 186 | 187 | if args.list_voices is not False: 188 | display_voices(args.list_voices) 189 | sys.exit(0) 190 | 191 | if args.themes: 192 | display_themes() 193 | sys.exit(0) 194 | 195 | # Validate modes 196 | selected_mode = sum( 197 | [args.gui, args.daemon, (args.text is not None or args.file is not None)] 198 | ) 199 | if selected_mode not in (0, 1): 200 | console.print( 201 | "[bold red]Error:[/] Only one mode (Console, GUI, Daemon, or CLI) can be selected." 202 | ) 203 | sys.exit(0) 204 | if args.theme != DEFAULT_THEME and not args.gui: 205 | console.print( 206 | "[bold yellow]Warning:[/] Invalid use of --theme without --gui or -g" 207 | ) 208 | if selected_mode == 1 and (args.verbose or args.ctrl_c_off or args.history_off): 209 | console.print( 210 | "[bold yellow]Warning:[/] Invalid use of verbose, ctrl_c_off, or history_off with mode other than Console." 211 | ) 212 | if args.port != PORT and not args.daemon: 213 | console.print("[bold yellow]Warning:[/] Invalid use of --port without --daemon") 214 | 215 | # Validate inputs 216 | languages = get_language_map() 217 | voices = get_voices() 218 | 219 | if args.language not in languages: 220 | console.print(f"[bold red]Error:[/] Invalid language '{args.language}'") 221 | display_languages() 222 | sys.exit(1) 223 | 224 | if args.voice not in voices: 225 | console.print(f"[bold red]Error:[/] Invalid voice '{args.voice}'") 226 | display_voices() 227 | sys.exit(1) 228 | if not args.all and not args.voice.startswith(args.language): 229 | console.print( 230 | f"[bold red]Error:[/] Voice '{args.voice}' is not made for language '{get_language_map()[args.language]}'" 231 | ) 232 | display_voices() 233 | sys.exit(1) 234 | 235 | if not MIN_SPEED <= args.speed <= MAX_SPEED: 236 | console.print( 237 | f"[bold red]Error:[/] Speed must be between {MIN_SPEED} and {MAX_SPEED}" 238 | ) 239 | sys.exit(1) 240 | 241 | if args.theme not in get_gui_themes(): 242 | console.print("[bold red]Error:[/] Invalid theme") 243 | display_themes() 244 | sys.exit(1) 245 | 246 | if not 0 <= args.port <= 65535: 247 | console.print( 248 | f"[bold red]Error:[/] Port {args.port} is out of valid range (0-65535)." 249 | ) 250 | sys.exit(1) 251 | 252 | if args.output is not None and not args.output.endswith(".wav"): 253 | console.print("[bold red]Error:[/] The output file name should end with .wav") 254 | sys.exit(1) 255 | 256 | # Validate that output or all isn't used without input 257 | if args.output is not None and args.all: 258 | console.print("[bold red]Error:[/] --output/-o can't be used with --all") 259 | sys.exit(1) 260 | if args.output is not None and args.text is None and args.file is None: 261 | console.print( 262 | "[bold red]Error:[/] --output/-o can only be used with --text or --file" 263 | ) 264 | sys.exit(1) 265 | if args.all and args.text is None and args.file is None: 266 | console.print( 267 | "[bold red]Error:[/] --all can only be used with --text or --file" 268 | ) 269 | sys.exit(1) 270 | 271 | # Handle input 272 | input_text = None 273 | is_srt_file = False 274 | if args.file is not None: 275 | if not args.file.strip(): 276 | console.print("[bold red]Error:[/] File path cannot be empty") 277 | sys.exit(1) 278 | 279 | # Check if it's an SRT file based on extension 280 | is_srt_file = args.file.lower().endswith(('.srt', '.SRT')) 281 | 282 | # Validate SRT files can't be used with --all 283 | if is_srt_file and args.all: 284 | console.print("[bold red]Error:[/] --all cannot be used with SRT files") 285 | sys.exit(1) 286 | 287 | try: 288 | # Validate file exists and is readable 289 | with open(args.file, "r", encoding="utf-8") as f: 290 | if is_srt_file: 291 | # Just validate SRT file is readable, don't load content 292 | f.read() 293 | input_text = args.file # Store file path for SRT files 294 | else: 295 | # Load content for text files 296 | input_text = f.read() 297 | except Exception as e: 298 | file_type = "SRT file" if is_srt_file else "file" 299 | console.print(f"[bold red]Error reading {file_type}:[/] {e}") 300 | sys.exit(1) 301 | elif args.text is not None: 302 | if not args.text.strip(): 303 | console.print("[bold red]Error:[/] Text cannot be empty") 304 | sys.exit(1) 305 | input_text = args.text 306 | 307 | return Args( 308 | args.language, 309 | args.voice, 310 | args.speed, 311 | args.history_off, 312 | args.device, 313 | input_text, 314 | args.output, 315 | args.all, 316 | args.setup, 317 | args.daemon, 318 | args.port, 319 | args.gui, 320 | args.theme, 321 | args.verbose, 322 | args.ctrl_c_off, 323 | is_srt_file, 324 | ) 325 | 326 | 327 | def get_input(history_off: bool, prompt="> ") -> str: 328 | user_input = input(prompt).strip() 329 | save_history(history_off) 330 | return user_input 331 | -------------------------------------------------------------------------------- /src/client.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | import platform 4 | import socket 5 | import subprocess 6 | import sys 7 | from enum import Enum 8 | from typing import Optional, Tuple 9 | import pyautogui 10 | 11 | if platform.system() == "Windows": 12 | import pyperclip 13 | 14 | from config import DEFAULT_LANGUAGE, HOST, MAX_SPEED, MIN_SPEED, PORT 15 | from utils import display_languages, display_voices, get_language_map, get_voices 16 | 17 | 18 | class Action(Enum): 19 | NONE = 0 20 | STOP = 1 21 | PAUSE = 2 22 | RESUME = 3 23 | NEXT = 4 24 | BACK = 5 25 | EXIT = 6 26 | 27 | 28 | ACTION_MAPPING = { 29 | "stop": Action.STOP, 30 | "pause": Action.PAUSE, 31 | "resume": Action.RESUME, 32 | "next": Action.NEXT, 33 | "back": Action.BACK, 34 | "exit": Action.EXIT, 35 | } 36 | 37 | ACTION_COMMANDS = { 38 | Action.EXIT: "!exit", 39 | Action.STOP: "!stop", 40 | Action.PAUSE: "!pause", 41 | Action.RESUME: "!resume", 42 | Action.NEXT: "!next", 43 | Action.BACK: "!back", 44 | } 45 | 46 | 47 | def get_clipboard() -> Optional[str | bytes]: 48 | """Get clipboard content, supporting Windows, X11, and Wayland""" 49 | 50 | if platform.system() == "Windows": 51 | # On Windows use pyperclip 52 | try: 53 | return pyperclip.paste() 54 | except pyperclip.PyperclipException as e: 55 | print(f"Error reading clipboard on Windows: {e}") 56 | return None 57 | 58 | is_wayland = os.environ.get("WAYLAND_DISPLAY") is not None 59 | 60 | if is_wayland: 61 | try: 62 | try: 63 | result = subprocess.run( 64 | ["wl-paste", "--no-newline"], 65 | capture_output=True, 66 | text=True, 67 | check=True, 68 | ) 69 | return result.stdout 70 | except UnicodeDecodeError: 71 | result = subprocess.run( 72 | ["wl-paste", "--type", "image/png"], 73 | capture_output=True, 74 | check=True, 75 | ) 76 | return result.stdout 77 | except subprocess.CalledProcessError as e: 78 | print(f"Error reading Wayland clipboard: {e}") 79 | print(f"Command returned {e.returncode}") 80 | print(f"Error output: {e.stderr}") 81 | return None 82 | except FileNotFoundError: 83 | print("Error: wl-paste is not installed. Please install wl-clipboard.") 84 | return None 85 | except Exception as e: 86 | print(f"Unexpected error on Wayland: {e}") 87 | return None 88 | else: 89 | try: 90 | try: 91 | result = subprocess.run( 92 | ["xclip", "-selection", "clipboard", "-o"], 93 | capture_output=True, 94 | text=True, 95 | check=True, 96 | ) 97 | return result.stdout.strip() 98 | except subprocess.CalledProcessError: 99 | result = subprocess.run( 100 | ["xclip", "-selection", "clipboard", "-t", "image/png", "-o"], 101 | capture_output=True, 102 | check=True, 103 | ) 104 | return result.stdout 105 | except subprocess.CalledProcessError as e: 106 | print(f"Error reading X11 clipboard: {e}") 107 | print(f"Command returned {e.returncode}") 108 | print(f"Error output: {e.stderr}") 109 | return None 110 | except FileNotFoundError: 111 | print("Error: xclip is not installed. Please install it first.") 112 | return None 113 | except Exception as e: 114 | print(f"Unexpected error on X11: {e}") 115 | return None 116 | 117 | 118 | def send_clipboard(perform_ctrl_c: bool) -> None: 119 | """Send clipboard content""" 120 | if perform_ctrl_c: 121 | try: 122 | pyautogui.hotkey("ctrl", "c") 123 | except KeyboardInterrupt: 124 | pass 125 | clipboard_content = get_clipboard() 126 | if clipboard_content is not None: 127 | with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket: 128 | client_socket.connect((HOST, PORT)) 129 | if isinstance(clipboard_content, bytes): 130 | client_socket.sendall(b"IMAGE:" + clipboard_content) 131 | else: 132 | client_socket.sendall(b"TEXT:" + clipboard_content.encode()) 133 | 134 | 135 | def send_action(action: str) -> None: 136 | """Send action""" 137 | with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket: 138 | client_socket.connect((HOST, PORT)) 139 | client_socket.sendall(action.encode()) 140 | 141 | 142 | def send_speed(speed: float) -> None: 143 | """Send new speed""" 144 | with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket: 145 | client_socket.connect((HOST, PORT)) 146 | client_socket.sendall(f"!speed {speed}".encode()) 147 | 148 | 149 | def send_language(language: str) -> None: 150 | """Send new language""" 151 | with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket: 152 | client_socket.connect((HOST, PORT)) 153 | client_socket.sendall(f"!lang {language}".encode()) 154 | 155 | 156 | def send_voice(voice: str) -> None: 157 | """Send new voice""" 158 | with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket: 159 | client_socket.connect((HOST, PORT)) 160 | client_socket.sendall(f"!voice {voice}".encode()) 161 | 162 | 163 | def parse_args() -> ( 164 | Tuple[Action, Optional[float], Optional[str], Optional[str], bool, bool] 165 | ): 166 | """Parse command-line arguments""" 167 | parser = argparse.ArgumentParser( 168 | description="Interact with kokorodoki daemon", 169 | ) 170 | 171 | global PORT 172 | 173 | parser.add_argument( 174 | "--ctrl-c", 175 | "-c", 176 | action="store_true", 177 | help="Perform Ctrl+C before reading clipboard", 178 | ) 179 | parser.add_argument( 180 | "--port", type=int, default=PORT, help=f"Choose a port number (default: {PORT})" 181 | ) 182 | parser.add_argument( 183 | "--status", 184 | action="store_true", 185 | help="Get current settings", 186 | ) 187 | parser.add_argument( 188 | "--language", 189 | "-l", 190 | type=str, 191 | help=f"Change language ('{DEFAULT_LANGUAGE}' for American English)", 192 | ) 193 | parser.add_argument( 194 | "--voice", 195 | "-v", 196 | type=str, 197 | help="Change voice", 198 | ) 199 | parser.add_argument( 200 | "--speed", 201 | "-s", 202 | type=float, 203 | help=f"Change speed (range: {MIN_SPEED}-{MAX_SPEED})", 204 | ) 205 | parser.add_argument( 206 | "--list-languages", 207 | "--list_languages", 208 | action="store_true", 209 | help="List available languages", 210 | ) 211 | parser.add_argument( 212 | "--list-voices", 213 | "--list_voices", 214 | type=str, 215 | nargs="?", 216 | const=None, 217 | default=False, 218 | help="List available voices. Optionally provide a language to filter by.", 219 | ) 220 | input_group = parser.add_mutually_exclusive_group() 221 | input_group.add_argument( 222 | "--stop", 223 | action="store_true", 224 | help="Stop reading", 225 | ) 226 | input_group.add_argument( 227 | "--pause", 228 | action="store_true", 229 | help="Pause reading", 230 | ) 231 | input_group.add_argument( 232 | "--resume", 233 | action="store_true", 234 | help="Resume reading", 235 | ) 236 | input_group.add_argument( 237 | "--next", 238 | action="store_true", 239 | help="Skip a sentence", 240 | ) 241 | input_group.add_argument( 242 | "--back", 243 | action="store_true", 244 | help="Back one sentence", 245 | ) 246 | input_group.add_argument( 247 | "--exit", 248 | action="store_true", 249 | help="Stop reading", 250 | ) 251 | 252 | args = parser.parse_args() 253 | 254 | if args.list_languages: 255 | display_languages() 256 | sys.exit(0) 257 | 258 | if args.list_voices is not False: 259 | display_voices(args.list_voices) 260 | sys.exit(0) 261 | 262 | languages = get_language_map() 263 | voices = get_voices() 264 | 265 | if args.language is None and args.voice is not None: 266 | args.language = args.voice[0] 267 | elif args.language is not None and args.language not in languages: 268 | print(f"Error: Invalid language '{args.language}'") 269 | display_languages() 270 | sys.exit(1) 271 | 272 | if args.voice is not None: 273 | if args.voice not in voices: 274 | print(f"Error: Invalid voice '{args.voice}'") 275 | display_voices() 276 | sys.exit(1) 277 | if not args.voice.startswith(args.language): 278 | print( 279 | f"Error: Voice '{args.voice}' is not made for language '{get_language_map()[args.language]}'" 280 | ) 281 | display_voices() 282 | sys.exit(1) 283 | 284 | if args.speed is not None and not MIN_SPEED <= args.speed <= MAX_SPEED: 285 | print(f"Error: Speed must be between {MIN_SPEED} and {MAX_SPEED}") 286 | sys.exit(1) 287 | 288 | action = next( 289 | (ACTION_MAPPING[flag] for flag in ACTION_MAPPING if getattr(args, flag, False)), 290 | Action.NONE, 291 | ) 292 | 293 | PORT = args.port 294 | return (action, args.speed, args.language, args.voice, args.status, args.ctrl_c) 295 | 296 | 297 | def send( 298 | action: Action, 299 | speed: Optional[float], 300 | language: Optional[str], 301 | voice: Optional[str], 302 | status: bool, 303 | perform_ctrl_c: bool, 304 | ) -> None: 305 | "Send commands or clipboard." 306 | if action in ACTION_COMMANDS: 307 | send_action(ACTION_COMMANDS[action]) 308 | return 309 | 310 | if speed is None and voice is None and language is None and not status: 311 | send_clipboard(perform_ctrl_c) 312 | return 313 | 314 | if language is not None: 315 | send_language(language) 316 | if speed is not None: 317 | send_speed(speed) 318 | if voice is not None: 319 | send_voice(voice) 320 | if status: 321 | send_action("!status") 322 | 323 | 324 | def main(): 325 | """Main entry point.""" 326 | # action, speed, language, voice, status, perform_ctrl_c = parse_args() 327 | send(*parse_args()) 328 | 329 | 330 | if __name__ == "__main__": 331 | main() 332 | -------------------------------------------------------------------------------- /src/utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | import platform 3 | import re 4 | from dataclasses import dataclass 5 | from datetime import timedelta 6 | from typing import Dict, List, Optional 7 | 8 | if platform.system() == "Windows": 9 | import pyreadline3 as readline 10 | else: 11 | import readline 12 | 13 | from nltk import sent_tokenize 14 | from rich import box 15 | from rich.table import Table 16 | 17 | from config import COMMANDS, HISTORY_FILE, HISTORY_LIMIT, console 18 | 19 | 20 | def get_language_map() -> Dict[str, str]: 21 | """Return the available languages""" 22 | return { 23 | "a": "American English", 24 | "b": "British English", 25 | "e": "Spanish", 26 | "f": "French", 27 | "h": "Hindi", 28 | "i": "Italian", 29 | "p": "Brazilian Portuguese", 30 | "j": "Japanese", 31 | "z": "Mandarin Chinese", 32 | } 33 | 34 | 35 | def get_easyocr_language_map() -> Dict[str, str]: 36 | """Return the available languages for EasyOCR""" 37 | return { 38 | "a": "en", 39 | "b": "en", 40 | "e": "es", 41 | "f": "fr", 42 | "h": "hi", 43 | "i": "it", 44 | "p": "pt", 45 | "j": "ja", 46 | "z": "ch_sim", 47 | } 48 | 49 | 50 | def get_voices() -> List[str]: 51 | """Return the available voices""" 52 | return [ 53 | "af_alloy", 54 | "af_aoede", 55 | "af_bella", 56 | "af_heart", 57 | "af_jessica", 58 | "af_kore", 59 | "af_nicole", 60 | "af_nova", 61 | "af_river", 62 | "af_sarah", 63 | "af_sky", 64 | "am_adam", 65 | "am_echo", 66 | "am_eric", 67 | "am_fenrir", 68 | "am_liam", 69 | "am_michael", 70 | "am_onyx", 71 | "am_puck", 72 | "am_santa", 73 | "bf_alice", 74 | "bf_emma", 75 | "bf_isabella", 76 | "bf_lily", 77 | "bm_daniel", 78 | "bm_fable", 79 | "bm_george", 80 | "bm_lewis", 81 | "ef_dora", 82 | "em_alex", 83 | "em_santa", 84 | "ff_siwis", 85 | "hf_alpha", 86 | "hf_beta", 87 | "hm_omega", 88 | "hm_psi", 89 | "if_sara", 90 | "im_nicola", 91 | "jf_alpha", 92 | "jf_gongitsune", 93 | "jf_nezumi", 94 | "jf_tebukuro", 95 | "jm_kumo", 96 | "pf_dora", 97 | "pm_alex", 98 | "pm_santa", 99 | "zf_xiaobei", 100 | "zf_xiaoni", 101 | "zf_xiaoxiao", 102 | "zf_xiaoyi", 103 | "zm_yunjian", 104 | "zm_yunxi", 105 | "zm_yunxia", 106 | "zm_yunyang", 107 | ] 108 | 109 | 110 | def get_gui_themes() -> Dict[int, str]: 111 | """Return the available gui themes""" 112 | return { 113 | # Dark themes 114 | 1: "darkly", 115 | 2: "cyborg", 116 | 3: "solar", 117 | 4: "vapor", 118 | # Light themes 119 | 5: "cosmo", 120 | 6: "pulse", 121 | 7: "morph", 122 | } 123 | 124 | 125 | def display_themes() -> None: 126 | """Display available gui themes""" 127 | themes = get_gui_themes() 128 | table = Table(title="Available Themes", box=box.ROUNDED) 129 | table.add_column("Number", style="cyan") 130 | table.add_column("Theme", style="green") 131 | table.add_column("Style", style="green") 132 | 133 | for number, name in themes.items(): 134 | table.add_row(str(number), name, "Dark" if 1 <= number <= 4 else "Light") 135 | 136 | console.print(table) 137 | 138 | 139 | def get_nltk_language_map() -> Dict[str, str]: 140 | """Return available languages in nltk""" 141 | return { 142 | "a": "english", 143 | "b": "english", 144 | "e": "spanish", 145 | "f": "french", 146 | "i": "italian", 147 | "p": "portuguese", 148 | } 149 | 150 | 151 | def get_nltk_language(language_code: str) -> str: 152 | return next( 153 | ( 154 | lang 155 | for code, lang in get_nltk_language_map().items() 156 | if code == language_code 157 | ), 158 | "english", 159 | ) 160 | 161 | 162 | def display_languages() -> None: 163 | """Display available languages in a formatted table.""" 164 | languages = get_language_map() 165 | table = Table(title="Available Languages", box=box.ROUNDED) 166 | table.add_column("Code", style="cyan") 167 | table.add_column("Language", style="green") 168 | 169 | for code, name in languages.items(): 170 | table.add_row(code, name) 171 | 172 | console.print(table) 173 | 174 | 175 | def display_voices(language=None) -> None: 176 | """Display available voices in a formatted table.""" 177 | voices = get_voices() 178 | table = Table(title="Available Voices", box=box.ROUNDED) 179 | table.add_column("Voice ID", style="cyan") 180 | table.add_column("Prefix", style="yellow") 181 | 182 | if language not in get_language_map() and language is not None: 183 | console.print(f"[bold red]Error:[/] Invalid language '{language}'") 184 | display_languages() 185 | return 186 | 187 | for voice in voices: 188 | prefix, _ = voice.split("_", 1) 189 | if language is None or language == prefix[0]: 190 | prefix_desc = { 191 | "a": "American", 192 | "b": "British", 193 | "e": "Spanish", 194 | "f": "French", 195 | "h": "Hindi", 196 | "i": "Italian", 197 | "p": "Portuguese", 198 | "j": "Japanese", 199 | "z": "Mandarin", 200 | }.get(prefix[0], "Unknown") 201 | gender = "Female" if prefix[1] == "f" else "Male" 202 | table.add_row(voice, f"{prefix_desc} {gender}") 203 | 204 | console.print(table) 205 | 206 | 207 | def display_status(language: str, voice: str, speed: float) -> None: 208 | """Display current settings.""" 209 | console.print("[green]Currently:[/]") 210 | console.print(f" Language: [cyan]{get_language_map()[language]}[/]") 211 | console.print(f" Voice: [cyan]{voice}[/]") 212 | console.print(f" Speed: [cyan]{speed}[/]") 213 | 214 | 215 | def format_status(language: str, voice: str, speed: float) -> str: 216 | """Return current settings as a formatted string.""" 217 | status_lines = [ 218 | f"Current language: {get_language_map()[language]}.", 219 | f"Current voice: {voice}.", 220 | f"Current speed: {speed}.", 221 | ] 222 | return "\n".join(status_lines) 223 | 224 | 225 | def display_help() -> None: 226 | """Display help information for available commands.""" 227 | table = Table( 228 | title="[bold]Command Help[/bold]", 229 | box=box.ROUNDED, 230 | title_style="bold magenta", 231 | header_style="bold white", 232 | ) 233 | table.add_column("Command", style="cyan", width=20) 234 | table.add_column("Description", style="green") 235 | table.add_column("Example", style="yellow") 236 | 237 | command_groups = [ 238 | { 239 | "group": "Playback Control", 240 | "commands": [ 241 | ("!stop, !s", "Stop current playback", "!stop"), 242 | ("!pause, !p", "Pause playback", "!pause"), 243 | ("!resume, !r", "Resume playback", "!resume"), 244 | ("!next, !n", "Skip to next sentence", "!next"), 245 | ("!back, !b", "Go to previous sentence", "!back"), 246 | ], 247 | }, 248 | { 249 | "group": "Audio Settings", 250 | "commands": [ 251 | ("!lang ", "Change language", "!lang b"), 252 | ("!voice ", "Change voice", "!voice af_bella"), 253 | ("!speed ", "Set playback speed (0.5-2.0)", "!speed 1.5"), 254 | ], 255 | }, 256 | { 257 | "group": "Information", 258 | "commands": [ 259 | ("!list_langs", "List available languages", "!list_langs"), 260 | ( 261 | "!list_voices", 262 | "List available voices for current language", 263 | "!list_voices", 264 | ), 265 | ( 266 | "!list_all_voices", 267 | "List voices for all languages", 268 | "!list_all_voices", 269 | ), 270 | ("!status", "Show current settings", "!status"), 271 | ], 272 | }, 273 | { 274 | "group": "Interface", 275 | "commands": [ 276 | ("!clear", "Clear the screen", "!clear"), 277 | ("!clear_history", "Clear command history", "!clear_history"), 278 | ("!verbose", "Toggle verbose mode", "!verbose"), 279 | ("!ctrlc", "Change the effect of Ctrl+C", "!ctrlc"), 280 | ("!help, !h", "Show this help message", "!help"), 281 | ("!quit, !q", "Exit the program", "!quit"), 282 | ], 283 | }, 284 | ] 285 | 286 | for group in command_groups: 287 | table.add_row( 288 | f"[bold underline]{group['group']}[/]", "", "", style="bold green" 289 | ) 290 | for cmd, desc, example in group["commands"]: 291 | table.add_row(cmd, desc, example) 292 | 293 | console.print(table) 294 | console.print( 295 | "[italic dim]Tip: Use commands with aliases (e.g., !s for !stop) for faster input.[/]\n" 296 | ) 297 | 298 | 299 | def clear_history() -> None: 300 | readline.clear_history() 301 | if platform.system() != "Windows": 302 | try: 303 | readline.write_history_file(HISTORY_FILE) 304 | except IOError: 305 | pass 306 | console.print("[bold yellow]History cleared.[/]") 307 | 308 | 309 | def save_history(history_off: bool) -> None: 310 | if platform.system() == "Windows": 311 | return 312 | if not history_off: 313 | try: 314 | readline.write_history_file(HISTORY_FILE) 315 | except IOError: 316 | console.print("[bold red]Error saving history file.[/]") 317 | 318 | 319 | def init_history(history_off: bool) -> None: 320 | """Load history file and set the limit""" 321 | if platform.system() == "Windows": 322 | return 323 | if not history_off: 324 | if os.path.exists(HISTORY_FILE): 325 | try: 326 | readline.read_history_file(HISTORY_FILE) 327 | except IOError: 328 | pass 329 | readline.set_history_length(HISTORY_LIMIT) 330 | 331 | 332 | def init_completer() -> None: 333 | if platform.system() == "Windows": 334 | return 335 | readline.parse_and_bind("tab: complete") 336 | readline.set_completer(completer) 337 | readline.set_completer_delims("") 338 | readline.parse_and_bind("set completion-ignore-case on") 339 | 340 | 341 | def completer(text: str, state: int) -> Optional[str]: 342 | """Auto-complete function for readline.""" 343 | if platform.system() == "Windows": 344 | return None 345 | options = [cmd for cmd in COMMANDS if cmd.startswith(text)] 346 | return options[state] if state < len(options) else None 347 | 348 | 349 | def split_by_words(chunk: str, max_len: int) -> List[str]: 350 | """Split a chunk into smaller chunks by words, ensuring each is <= max_len""" 351 | 352 | if len(chunk) <= max_len: 353 | return [chunk] 354 | 355 | chunks = [] 356 | current_chunk = "" 357 | 358 | words = chunk.split(" ") 359 | for word in words: 360 | if len(current_chunk) + len(word) + (1 if current_chunk else 0) > max_len: 361 | if current_chunk: 362 | chunks.append(current_chunk) 363 | current_chunk = word 364 | else: 365 | # If word itself is too long 366 | while len(word) > max_len: 367 | chunks.append(word[:max_len]) 368 | word = word[max_len:] 369 | current_chunk = word 370 | else: 371 | current_chunk += (" " if current_chunk else "") + word 372 | if current_chunk: 373 | chunks.append(current_chunk) 374 | 375 | return chunks 376 | 377 | 378 | def split_long_sentence(sentence: str, max_len=350, min_len=50) -> List[str]: 379 | """Split a sentence into chunks of <= max_len""" 380 | if len(sentence) <= max_len: 381 | return [sentence] 382 | 383 | chunks = [] 384 | 385 | # Split by newline 386 | chunk = sentence 387 | if len(chunk) <= max_len: 388 | chunks.append(chunk) 389 | else: 390 | # Split by "[,;]\s" 391 | split_points = [m.start() for m in re.finditer(r"[,;]\s", chunk)] 392 | if split_points: 393 | last_pos = 0 394 | for pos in split_points: 395 | next_pos = pos + 2 396 | segment = chunk[last_pos:next_pos] 397 | if len(segment) > max_len: 398 | # For too long segments 399 | chunks.extend(split_by_words(segment, max_len)) 400 | elif len(segment) < min_len and last_pos > 0: 401 | # Merge short segment with previous chunk 402 | chunks[-1] += segment 403 | else: 404 | chunks.append(segment) 405 | last_pos = next_pos 406 | # Handle remaining text 407 | if last_pos < len(chunk): 408 | chunks.extend(split_by_words(chunk[last_pos:], max_len)) 409 | else: 410 | chunks.extend(split_by_words(chunk, max_len)) 411 | 412 | for i, chunk in enumerate(chunks): 413 | if len(chunk) > max_len: 414 | chunks[i : i + 1] = split_by_words(chunk, max_len) 415 | return [chunk for chunk in chunks if chunk] 416 | 417 | 418 | def merge_short_sentences(sentences: list[str], min_len=50, max_len=300) -> list[str]: 419 | """Merge those shorter than min_len with the next sentence""" 420 | if not sentences: 421 | return [] 422 | 423 | result = [] 424 | current_sentence = sentences[0] 425 | 426 | for i in range(1, len(sentences)): 427 | if len(current_sentence) < min_len and len(sentences[i]) < max_len: 428 | current_sentence += sentences[i] 429 | else: 430 | result.append(current_sentence) 431 | current_sentence = sentences[i] 432 | 433 | if current_sentence: 434 | result.append(current_sentence) 435 | 436 | return result 437 | 438 | 439 | def split_text_to_sentences(text: str, language: str) -> List[str]: 440 | """Tokenize text into sentences""" 441 | sentences = sent_tokenize(text, language=language) 442 | 443 | new_sentences = [] 444 | for sentence in sentences: 445 | if len(sentence) > 350: 446 | new_sentences.extend(split_long_sentence(sentence, max_len=350)) 447 | else: 448 | new_sentences.extend([sentence]) 449 | 450 | # new_sentences = merge_short_sentences(new_sentences, min_len=50, max_len=300) 451 | return new_sentences 452 | 453 | 454 | @dataclass 455 | class SRTEntry: 456 | """Represents a single SRT subtitle entry""" 457 | index: int 458 | start_time: float # in seconds 459 | end_time: float # in seconds 460 | text: str 461 | 462 | 463 | def parse_srt_timestamp(timestamp: str) -> float: 464 | """Parse SRT timestamp format (HH:MM:SS,mmm) to seconds""" 465 | # Replace comma with dot for milliseconds 466 | timestamp = timestamp.replace(',', '.') 467 | parts = timestamp.split(':') 468 | hours = int(parts[0]) 469 | minutes = int(parts[1]) 470 | seconds_ms = float(parts[2]) 471 | 472 | return hours * 3600 + minutes * 60 + seconds_ms 473 | 474 | 475 | def parse_srt_file(file_path: str) -> List[SRTEntry]: 476 | """Parse an SRT subtitle file and return a list of SRTEntry objects""" 477 | entries = [] 478 | 479 | with open(file_path, 'r', encoding='utf-8') as f: 480 | content = f.read().strip() 481 | 482 | # Split by double newlines to separate entries 483 | blocks = re.split(r'\n\s*\n', content) 484 | 485 | for block in blocks: 486 | lines = block.strip().split('\n') 487 | if len(lines) < 3: 488 | continue 489 | 490 | try: 491 | # Parse index 492 | index = int(lines[0]) 493 | 494 | # Parse timestamp line 495 | timestamp_line = lines[1] 496 | timestamp_match = re.match(r'(\d{2}:\d{2}:\d{2},\d{3})\s*-->\s*(\d{2}:\d{2}:\d{2},\d{3})', timestamp_line) 497 | if not timestamp_match: 498 | continue 499 | 500 | start_time = parse_srt_timestamp(timestamp_match.group(1)) 501 | end_time = parse_srt_timestamp(timestamp_match.group(2)) 502 | 503 | # Join text lines (in case subtitle spans multiple lines) 504 | text = '\n'.join(lines[2:]).strip() 505 | 506 | entries.append(SRTEntry(index, start_time, end_time, text)) 507 | 508 | except (ValueError, IndexError): 509 | # Skip malformed entries 510 | continue 511 | 512 | return entries 513 | -------------------------------------------------------------------------------- /README.MD: -------------------------------------------------------------------------------- 1 | # KokoroDoki: Real-Time Text-to-Speech (TTS) 2 | 3 | **KokoroDoki** is a real-time Text-to-Speech application supporting multiple languages and voices. It runs locally on your laptop, utilizing either the CPU or leverage CUDA for GPU acceleration. 4 | 5 | Powered by [Kokoro-82M](https://huggingface.co/hexgrad/Kokoro-82M) an open-weight TTS model that delivers high-quality, natural-sounding speech, it rivals larger models while remaining lightweight and highly responsive. 6 | 7 | Whether you need to listen to articles, generating audio files, or just want text spoken back in real time, KokoroDoki has you covered—featuring Console, GUI, CLI, and Daemon modes to suit any workflow. 8 | 9 | 🎧 [Voice Demo - af_heart](samples/welcome.wav) 10 | 11 | https://github.com/user-attachments/assets/103b6bd0-0010-4c3d-a373-cf4b218a05a0 12 | 13 | --- 14 | 15 | ## 📁 Table of Contents 16 | 17 | * [Features](#features) 18 | * [🌐 Language & Voice Availability](#-language--voice-availability) 19 | * [Setup](#-setup) 20 | 21 | * [Requirements](#requirements) 22 | * [Setup Instructions](#setup-instructions) 23 | 24 | * [Windows / Docker](#0-windows-or-docker) 25 | * [Dependencies](#1-dependencies) 26 | * [Install CUDA Toolkit](#2-install-cuda-toolkit) 27 | * [Installation](#3-installation) 28 | * [Integrate with systemd](#4-integrate-with-systemd) 29 | * [Optional: Language Support Packages](#5-optional-language-support-packages) 30 | * [Usage](#usage) 31 | * [Examples](#examples) 32 | * [Command-Line Arguments](#command-line-arguments) 33 | * [1/4. Console Mode (Interactive Terminal)](#14-%EF%B8%8F-console-mode-interactive-terminal) 34 | * [2/4. GUI Mode](#24-%EF%B8%8F-gui-mode) 35 | * [3/4. Daemon Mode (Background Service)](#34-%EF%B8%8F-daemon-mode-background-service) 36 | * [4/4. CLI Mode (One-Shot)](#44--cli-mode-one-shot) 37 | * [Core Dependencies](#core-dRequirementsependencies) 38 | * [Contribute](#-contribute) 39 | * [License](#-license) 40 | 41 | --- 42 | 43 | ## Features 44 | 45 | * **🌍 Multilingual Support** 46 | Supports English (US/UK), Spanish, French, Hindi, Italian, Brazilian Portuguese, Japanese, Mandarin Chinese. 47 | 48 | * **🗣️ Diverse Voice Selection** 49 | Switch between a range of expressive voices. 50 | 51 | * **🎛️ Interactive Playback Control** 52 | Pause, resume, skip, rewind, or change voice/language on the fly. 53 | 54 | * **🗌 Clipboard Monitoring (Daemon Mode)** 55 | Automatically speak out any copied text. 56 | 57 | * **📂 Export to WAV** 58 | Save generated audio for offline use or editing. 59 | 60 | * **🎬 SRT Subtitle Support** 61 | Generate timed audio from SRT subtitle files with perfect synchronization. 62 | 63 | * **📟 Console Mode** 64 | An interactive terminal mode with commands to control playback, switch voices/languages, and more. 65 | 66 | * **🖥️ GUI Mode** 67 | A GUI with support for multiple themes and sentence highlighting. 68 | 69 | * **🛠️ Daemon** 70 | Runs as a background service. Accepts commands/text from client.py. 71 | 72 | * **\ CLI Modes** 73 | One-shot text-to-speech conversion from input text or file. 74 | 75 | * **⚡ Fast & Real-time** 76 | Designed for low-latency performance with quick response and smooth voice output. 77 | 78 | * **🧠 CPU & GPU** 79 | Supports CPU and CUDA-based acceleration. 80 | 81 | > ⚠️ **Note:** While CPU mode is supported, performance is significantly better with CUDA-enabled GPUs. Without CUDA, real-time responsiveness and speed may be reduced. 82 | 83 | 84 | ### Floating Tool Bar 85 | 86 | 💡 Check out [floatingtoolbar](https://github.com/markd89/floatingtoolbar) by [markd89](https://github.com/markd89) — a Python/Qt GUI alternative to hotkeys for Daemon Mode. 87 | 88 | 89 | ## 🌐 Language & Voice Availability 90 | 91 | | Language | Voices | 92 | | -------------------- | ------ | 93 | | American English | 20 | 94 | | British English | 8 | 95 | | Spanish | 3 | 96 | | French | 1 | 97 | | Hindi | 4 | 98 | | Italian | 2 | 99 | | Brazilian Portuguese | 3 | 100 | | Japanese | 5 | 101 | | Mandarin Chinese | 8 | 102 | 103 | --- 104 | 105 | ## 🚀 Setup 106 | 107 | ### Requirements 108 | 109 | Make sure you have the following installed (see below for a guide): 110 | 111 | * **Python**: 3.12 112 | * **CUDA Toolkit**: [cuda-toolkit](https://developer.nvidia.com/cuda-toolkit) 113 | * **Audio & Voice Tools**: `portaudio`, `espeak` 114 | * **Build Tools**: `python3.12-dev`, `python3.12-virtualenv` 115 | * **Python interface to the Tcl/Tk GUI toolkit**: `python3.12-tkinter` 116 | * **Clipboard Support (for Daemon Mode)**: `xclip` or `wl-clipboard` for Wayland 117 | 118 | ### Setup Instructions 119 | 120 | #### 0. Windows or Docker 121 | 122 | > For Windows instructions, see [windows.md](windows.md). 123 | > For Docker, see [docker.md](docker/DOCKER.md). 124 | 125 | #### 1. Dependencies 126 | 127 | **For Debian-based/Ubuntu systems:** 128 | 129 | ```bash 130 | sudo apt update && sudo apt install -y \ 131 | python3.12 python3.12-dev python3.12-venv python3.12-tk \ 132 | portaudio19-dev espeak wl-clipboard 133 | ``` 134 | 135 | **For Fedora/RHEL/CentOS systems:** 136 | 137 | ```bash 138 | sudo dnf install -y \ 139 | python3.12 python3.12-devel python3-virtualenv python3.12-tkinter \ 140 | portaudio espeak wl-clipboard 141 | ``` 142 | 143 | #### 2. Install CUDA Toolkit 144 | 145 | Follow the official guide to install the [CUDA Toolkit](https://developer.nvidia.com/cuda-toolkit) compatible with your GPU and OS. 146 | 147 | 148 | #### 3. Installation 149 | 150 | ```bash 151 | 152 | # Clone the repository 153 | cd ~/.local/bin 154 | git clone https://github.com/eel-brah/kokorodoki kdoki 155 | 156 | # Set up a virtual environment 157 | mkdir -p ~/.venvs 158 | cd ~/.venvs 159 | python3.12 -m venv kdvenv 160 | source kdvenv/bin/activate 161 | 162 | # Install Python requirements 163 | pip install -r ~/.local/bin/kdoki/requirements.txt 164 | 165 | # Exit the virtual environment 166 | deactivate 167 | 168 | # Copy the wrapper 169 | cp ~/.local/bin/kdoki/kokorodoki ~/.local/bin 170 | chmod +x ~/.local/bin/kokorodoki 171 | 172 | # Copy the wrapper for the client (Daemon mode) 173 | cp ~/.local/bin/kdoki/doki ~/.local/bin 174 | chmod +x ~/.local/bin/doki 175 | ``` 176 | 177 | #### 4. Integrate with systemd 178 | 179 | ```bash 180 | # Integrate with systemd for better control (Daemon mode) 181 | chmod +x generate_kokorodoki_service.sh 182 | ./generate_kokorodoki_service.sh 183 | 184 | systemctl --user daemon-reload 185 | systemctl --user enable kokorodoki.service 186 | systemctl --user start kokorodoki.service 187 | systemctl --user status kokorodoki.service 188 | 189 | # To test it: 190 | # Copy some text like "Integrate with systemd for better control" 191 | # Then run: 192 | doki 193 | 194 | # Create custom shortcuts for more convenience experience 195 | 196 | # Send from clipboard 197 | ~/.venvs/kdvenv/bin/python3.12 ~/.local/bin/kdoki/src/client.py 198 | 199 | # To trigger Ctrl+C before sending clipboard (No need to copy text manually) 200 | ~/.venvs/kdvenv/bin/python3.12 ~/.local/bin/kdoki/src/client.py -c 201 | 202 | # Stop playback 203 | ~/.venvs/kdvenv/bin/python3.12 ~/.local/bin/kdoki/src/client.py --stop 204 | 205 | # Pause playback 206 | ~/.venvs/kdvenv/bin/python3.12 ~/.local/bin/kdoki/src/client.py --pause 207 | 208 | # Resume playback 209 | ~/.venvs/kdvenv/bin/python3.12 ~/.local/bin/kdoki/src/client.py --resume 210 | 211 | # Skip to next sentence 212 | ~/.venvs/kdvenv/bin/python3.12 ~/.local/bin/kdoki/src/client.py --next 213 | 214 | # Go back a sentence 215 | ~/.venvs/kdvenv/bin/python3.12 ~/.local/bin/kdoki/src/client.py --back 216 | ``` 217 | 218 | #### 5. Optional: Language Support Packages 219 | 220 | ```bash 221 | # For Japanese 222 | pip install pyopenjtalk 223 | 224 | # For Mandarin Chinese 225 | pip install ordered_set pypinyin jieba cn2an 226 | ``` 227 | 228 | 229 | ## Usage 230 | 231 | ### Examples 232 | 233 | ```bash 234 | # Launch with default mode (Console mode) and default settings 235 | kokorodoki 236 | 237 | # The first run may take some time as it downloads the AI model. 238 | 239 | # OR, if you didn't follow the setup steps above: 240 | # Use the path to your virtual environment and the path to where you cloned 241 | /path/to/venv/bin/python3.12 /path/to/kokorodoki/src/main.py 242 | 243 | # Show help 244 | kokorodoki -h 245 | 246 | # List available voices 247 | kokorodoki --list-voices 248 | 249 | # Choose your settings – Spanish, voice ef_dora, with 1.2x speed 250 | kokorodoki -l e -v ef_dora -s 1.2 251 | 252 | # Launch GUI mode 253 | kokorodoki --gui 254 | 255 | # Launch daemon mode 256 | kokorodoki --daemon 257 | 258 | # Copy some text to clipboard, then run: 259 | doki 260 | 261 | # Change voice 262 | doki -v af_sky 263 | 264 | # Copy text again and play with: 265 | doki 266 | 267 | # Generate and save audio to a file 268 | kokorodoki -l b -v bf_lily -t "Generate audio file" -o output.wav 269 | 270 | # Generate timed audio from SRT subtitle file (auto-detected) 271 | kokorodoki -f subtitles.srt -o timed_audio.wav 272 | 273 | ``` 274 | 275 | ### Command-Line Arguments 276 | 277 | #### Info 278 | 279 | * `--list-languages` Show all supported languages. 280 | * `--list-voices [LANG]` Show all available voices. Optionally filter by language. 281 | * `--themes` Show available GUI themes. 282 | 283 | #### Configuration 284 | 285 | * `--language`, `-l` Set the initial language (e.g., `a` for American English). 286 | * `--voice`, `-v` Set the initial voice (e.g., `af_heart`). 287 | * `--speed`, `-s` Set the initial speed (range: 0.5 to 2.0). 288 | 289 | #### Modes 290 | 291 | * `--gui`, `-g` Run in GUI mode. 292 | * `--daemon` Run in daemon mode. 293 | * `--text`, `-t` Supply a text string for CLI mode. 294 | * `--file`, `-f` Supply a text file or SRT subtitle file (SRT files detected automatically). 295 | * `--output`, `-o` Specify output `.wav` file path. 296 | * `--all` Test all voices for the selected language (only with `--text` or text files). 297 | 298 | #### Other Options 299 | 300 | * `--device` Set the computation device (`cuda` or `cpu`). 301 | * `--port` Set the port for daemon mode (default: `5561`). 302 | * `--theme` Set GUI theme (default: `darkly`). 303 | * `--history-off` Disable saving command history. 304 | * `--verbose`, `-V` Enable verbose output. 305 | * `--ctrl_c_off`, `-c` Disable Ctrl+C from stopping playback. 306 | 307 | ### 1/4. 🖥️ Console Mode (Interactive Terminal) 308 | 309 | Run an interactive terminal interface for real-time TTS, featuring playback control and input history. 310 | 311 | ```bash 312 | kokorodoki 313 | 314 | > Hello world! # Read this line 315 | > !help # Show help 316 | > !lang b # Switch to British English 317 | > !voice bf_emma # Use a specific voice 318 | > !speed 1.5 # Adjust speed 319 | > !pause # Pause playback 320 | > !resume # Resume 321 | > !quit # Exit 322 | 323 | ``` 324 | 325 | #### Available Commands 326 | 327 | 🎵 Playback Control 328 | | Command | Description | Example | 329 | |------------------|------------------------|-------------| 330 | | `!stop`, `!s` | Stop current playback | `!stop` | 331 | | `!pause`, `!p` | Pause playback | `!pause` | 332 | | `!resume`, `!r` | Resume playback | `!resume` | 333 | | `!next`, `!n` | Skip to next sentence | `!next` | 334 | | `!back`, `!b` | Go to previous sentence| `!back` | 335 | 336 | 🎚️ Audio Settings 337 | | Command | Description | Example | 338 | |------------------------|----------------------------------|-----------------------| 339 | | `!lang ` | Change language | `!lang b` | 340 | | `!voice ` | Change voice | `!voice af_bella` | 341 | | `!speed ` | Set playback speed (0.5–2.0) | `!speed 1.5` | 342 | 343 | 🧠 Information 344 | | Command | Description | Example | 345 | |--------------------|--------------------------------------------|--------------------| 346 | | `!list_langs` | List available languages | `!list_langs` | 347 | | `!list_voices` | List voices for the current language | `!list_voices` | 348 | | `!list_all_voices` | List voices for all languages | `!list_all_voices` | 349 | | `!status` | Show current settings | `!status` | 350 | 351 | 🛠 Interface 352 | | Command | Description | Example | 353 | |---------------------|-----------------------------------------|--------------------| 354 | | `!clear` | Clear the screen | `!clear` | 355 | | `!clear_history` | Clear command history | `!clear_history` | 356 | | `!verbose` | Toggle verbose mode | `!verbose` | 357 | | `!ctrlc` | Change behavior of Ctrl+C | `!ctrlc` | 358 | | `!help`, `!h` | Show this help message | `!help` | 359 | | `!quit`, `!q` | Exit the program | `!quit` | 360 | 361 | 362 | 363 | ### 2/4. 🖌️ GUI Mode 364 | 365 | Launch a graphical interface. 366 | 367 | ```bash 368 | kokorodoki --gui 369 | ``` 370 | 371 | Themes: 372 | 1. darkly 373 | 2. cyborg 374 | 3. solar 375 | 4. vapor 376 | 377 | Use `--theme ` to set it. 378 | 379 | 380 | ### 3/4. 🛠️ Daemon Mode (Background Service) 381 | 382 | Runs in the background and receives text or commands via `client.py`. 383 | 384 | ```bash 385 | kokorodoki --daemon 386 | ``` 387 | 388 | To send a text, copy the desired text and run `client.py` or `doki` 389 | 390 | ```bash 391 | ~/.venvs/kdvenv/bin/python3.12 ~/.local/bin/kdoki/src/client.py 392 | 393 | or 394 | 395 | doki 396 | ``` 397 | 398 | Pause and resume playback 399 | ```bash 400 | doki --pause 401 | doki --resume 402 | ``` 403 | 404 | #### 🧾 Client Arguments & Daemon Commands 405 | 406 | ```bash 407 | # Playback Controls 408 | --stop Stop reading 409 | --pause Pause reading 410 | --resume Resume reading 411 | --next Skip a sentence 412 | --back Go back one sentence 413 | --status Get current settings 414 | --exit Stop reading 415 | 416 | # Change settings 417 | --language, -l Change language ('a' for American English) 418 | --voice, -v Change voice 419 | --speed, -s Change speed (range: 0.5-2.0) 420 | 421 | # Info 422 | --list-languages List available languages 423 | --list-voices [LANG] List available voices, optionally filtered by language 424 | 425 | # Config 426 | --port If you run kokorodoki daemon mode in a different port, use this option to specify it 427 | --ctrl-c To trigger Ctrl+C before sending clipboard 428 | ``` 429 | 430 | #### Recommended: Use with `systemd` for Better Control 431 | 432 | See the ['Integrate with systemd'](#integrate-with-systemd) section in the installation guide above for steps. 433 | 434 | #### Recommended: Create Custom Shortcuts 435 | 436 | To improve your experience, it's recommended to create custom keyboard shortcuts for frequently used commands. 437 | 438 | Below are some useful commands you can bind to shortcuts: 439 | 440 | ```bash 441 | # Send from clipboard 442 | ~/.venvs/kdvenv/bin/python3.12 ~/.local/bin/kdoki/src/client.py 443 | 444 | # Stop playback 445 | ~/.venvs/kdvenv/bin/python3.12 ~/.local/bin/kdoki/src/client.py --stop 446 | 447 | # Pause playback 448 | ~/.venvs/kdvenv/bin/python3.12 ~/.local/bin/kdoki/src/client.py --pause 449 | 450 | # Resume playback 451 | ~/.venvs/kdvenv/bin/python3.12 ~/.local/bin/kdoki/src/client.py --resume 452 | 453 | # Skip to next sentence 454 | ~/.venvs/kdvenv/bin/python3.12 ~/.local/bin/kdoki/src/client.py --next 455 | 456 | # Go back a sentence 457 | ~/.venvs/kdvenv/bin/python3.12 ~/.local/bin/kdoki/src/client.py --back 458 | ``` 459 | 460 | You can assign these to keyboard shortcuts using your desktop environment’s keyboard settings (e.g., GNOME → Settings → Keyboard → Custom Shortcuts). 461 | 462 | 463 | ### 4/4. ⚡ CLI Mode (One-Shot) 464 | 465 | Use the command-line interface for quick, one-off tasks: 466 | 467 | ```bash 468 | # Speak text 469 | python src/main.py --text "Hello, world!" 470 | # Speak text from a file and save the audio to a file 471 | python src/main.py --file input.txt --output out.wav 472 | # Generate timed audio from SRT subtitle file (auto-detected) 473 | python src/main.py --file subtitles.srt --output timed_audio.wav 474 | # Speak using all available voices of a specific language 475 | python src/main.py -l a --text "All voices" --all 476 | ``` 477 | 478 | #### 🎬 SRT Subtitle Support 479 | 480 | KokoroDoki now supports SRT subtitle files for generating timed audio. This feature allows you to: 481 | 482 | - **Perfect Timing**: Generate audio that matches subtitle timestamps exactly 483 | - **Professional Content**: Create synchronized voiceovers for videos 484 | - **Accessibility**: Convert subtitled content into audio format 485 | 486 | **SRT File Format Example:** 487 | ```srt 488 | 1 489 | 00:00:00,000 --> 00:00:03,000 490 | Hello and welcome to our demonstration. 491 | 492 | 2 493 | 00:00:04,000 --> 00:00:07,500 494 | This is how SRT subtitles work with timed audio. 495 | 496 | 3 497 | 00:00:08,500 --> 00:00:12,000 498 | Each subtitle entry will be spoken at the correct time. 499 | ``` 500 | 501 | **Usage:** 502 | ```bash 503 | # Generate timed audio from SRT file (auto-detected) 504 | kokorodoki -f subtitles.srt -o synchronized_audio.wav 505 | 506 | # With custom voice and language 507 | kokorodoki -f subtitles.srt -l a -v af_heart -o output.wav 508 | ``` 509 | 510 | 511 | ## Core Dependencies 512 | 513 | * `nltk` – Sentence parsing 514 | * `torch`, `numpy`, `librosa` – Audio processing 515 | * `sounddevice`, `soundfile` – Audio playback 516 | * [`kokoro`](https://huggingface.co/hexgrad/Kokoro-82M) – The TTS model 517 | * `tkinter`, `ttkbootstrap` – GUI theming 518 | * `rich` – Fancy CLI output 519 | * `socket` - For Daemon and Client communication 520 | 521 | 522 | ## 🤝 Contribute 523 | 524 | 1. Fork the repo 525 | 2. Create a new branch 526 | 3. Make your changes 527 | 4. Open a pull request 528 | 529 | Bug reports and feature requests are welcome on GitHub Issues. 530 | 531 | 532 | ## 📜 License 533 | This project is licensed under the [GNU General Public License v3.0 (GPLv3)](LICENSE). 534 | 535 | You are free to use, modify, and distribute this software under the terms of the GPLv3. 536 | 537 | -------------------------------------------------------------------------------- /src/models.py: -------------------------------------------------------------------------------- 1 | import queue 2 | import sys 3 | import threading 4 | import time 5 | from typing import Optional 6 | 7 | import librosa 8 | import numpy as np 9 | import sounddevice as sd 10 | import soundfile as sf 11 | import torch 12 | from kokoro import KPipeline 13 | from rich.progress import ( 14 | BarColumn, 15 | Progress, 16 | SpinnerColumn, 17 | TextColumn, 18 | TimeElapsedColumn, 19 | ) 20 | 21 | from config import MAX_SPEED, MIN_SPEED, REPO_ID, SAMPLE_RATE, console 22 | from utils import get_language_map, get_nltk_language, get_voices, parse_srt_file, split_text_to_sentences 23 | 24 | 25 | class TTSPlayer: 26 | """Class to handle TTS generation and playback.""" 27 | 28 | def __init__( 29 | self, 30 | pipeline: KPipeline, 31 | language: str, 32 | voice: str, 33 | speed: float, 34 | verbose: bool, 35 | ctrlc: bool = True, 36 | ): 37 | self.pipeline = pipeline 38 | self.language = language 39 | self.nltk_language = get_nltk_language(self.language) 40 | self.voice = voice 41 | self.speed = speed 42 | self.verbose = verbose 43 | self.languages = get_language_map() 44 | self.voices = get_voices() 45 | self.audio_queue = queue.Queue() 46 | self.stop_event = threading.Event() 47 | self.skip = threading.Event() 48 | self.back = threading.Event() 49 | self.lock = threading.Lock() 50 | self.back_number = 0 51 | self.audio_player = None 52 | self.ctrlc = not ctrlc 53 | self.print_complete = True 54 | 55 | def change_language(self, new_lang: str, device: Optional[str]) -> bool: 56 | """Change the language and reinitialize the pipeline.""" 57 | if new_lang in self.languages: 58 | self.language = new_lang 59 | self.pipeline = KPipeline( 60 | lang_code=self.language, repo_id=REPO_ID, device=device 61 | ) 62 | if not self.voice.startswith(new_lang): 63 | self.change_voice( 64 | next(voice for voice in get_voices() if voice.startswith(new_lang)) 65 | ) 66 | self.nltk_language = get_nltk_language(self.language) 67 | return True 68 | return False 69 | 70 | def change_voice(self, new_voice: str) -> bool: 71 | """Change the voice.""" 72 | if new_voice in self.voices: 73 | self.voice = new_voice 74 | return True 75 | return False 76 | 77 | def change_speed(self, new_speed: float) -> bool: 78 | """Change the speech speed.""" 79 | if MIN_SPEED <= new_speed <= MAX_SPEED: 80 | self.speed = new_speed 81 | return True 82 | return False 83 | 84 | def trim_silence(self, audio, threshold=0.003): 85 | """Trim silence from the beginning and end of an audio chunk.""" 86 | # Convert to absolute values to handle negative amplitudes 87 | abs_audio = np.abs(audio) 88 | # Find indices where amplitude exceeds threshold 89 | non_silent = np.where(abs_audio > threshold)[0] 90 | 91 | if len(non_silent) == 0: 92 | return audio 93 | 94 | # Trim the audio 95 | start_idx = non_silent[0] 96 | end_idx = non_silent[-1] + 1 97 | return audio[start_idx:end_idx] 98 | 99 | def generate_audio(self, text: str | list) -> None: 100 | """Generate audio chunks and put them in the queue.""" 101 | try: 102 | sentences = [text] if isinstance(text, str) else text 103 | for sentence in sentences: 104 | generator = self.pipeline( 105 | sentence, voice=self.voice, speed=self.speed, split_pattern=None 106 | ) 107 | 108 | for result in generator: 109 | if self.stop_event.is_set(): 110 | self.audio_queue.put(None) 111 | return 112 | 113 | if result.audio is not None: 114 | audio = result.audio.numpy() 115 | if self.verbose: 116 | console.print( 117 | f"[dim]Generated: {result.graphemes[:30]}...[/]" 118 | ) 119 | # Trim silence for smooth reading 120 | trimed_audio, _ = librosa.effects.trim(audio, top_db=60) 121 | # trimed_audio = self.trim_silence(audio, threshold=0.001) 122 | self.audio_queue.put(trimed_audio) 123 | 124 | self.audio_queue.put(None) # Signal end of generation 125 | except Exception as e: 126 | console.print(f"[bold red]Generation error:[/] {str(e)}") 127 | self.audio_queue.put(None) # Ensure playback thread exits 128 | 129 | def generate_audio_file(self, text: list | str, output_file="Output.wav") -> None: 130 | """Generate audio file""" 131 | try: 132 | with Progress( 133 | SpinnerColumn("dots", style="yellow", speed=0.8), 134 | TextColumn("[bold yellow]{task.description}"), 135 | BarColumn(pulse_style="yellow", complete_style="blue"), 136 | TimeElapsedColumn(), 137 | ) as progress: 138 | 139 | task = progress.add_task( 140 | f"[bold yellow]Generating {output_file}", 141 | total=None, 142 | ) 143 | 144 | sentences = [text] if isinstance(text, str) else text 145 | audio_chunks = [] 146 | for sentence in sentences: 147 | generator = self.pipeline( 148 | sentence, voice=self.voice, speed=self.speed, split_pattern=None 149 | ) 150 | 151 | for result in generator: 152 | trimed_audio, _ = librosa.effects.trim( 153 | result.audio.numpy(), top_db=70 154 | ) 155 | audio_chunks.append(self.to_stereo(trimed_audio)) 156 | 157 | full_audio = np.concatenate(audio_chunks, axis=0) 158 | sf.write(output_file, full_audio, SAMPLE_RATE, format="WAV") 159 | 160 | progress.update( 161 | task, 162 | completed=1, 163 | total=1, 164 | description=f"[bold green]Saved to {output_file}[/]", 165 | ) 166 | 167 | except KeyboardInterrupt: 168 | console.print("\n[bold yellow]Exiting...[/]") 169 | sys.exit() 170 | except Exception as e: 171 | console.print(f"[bold red]Generation error:[/] {str(e)}") 172 | 173 | def generate_srt_timed_audio(self, srt_file: str, output_file="Output.wav") -> None: 174 | """Generate timed audio based on SRT subtitle file""" 175 | try: 176 | # Parse SRT file 177 | srt_entries = parse_srt_file(srt_file) 178 | if not srt_entries: 179 | console.print("[bold red]Error:[/] No valid entries found in SRT file") 180 | return 181 | 182 | with Progress( 183 | SpinnerColumn("dots", style="yellow", speed=0.8), 184 | TextColumn("[bold yellow]{task.description}"), 185 | BarColumn(pulse_style="yellow", complete_style="blue"), 186 | TimeElapsedColumn(), 187 | ) as progress: 188 | 189 | task = progress.add_task( 190 | f"[bold yellow]Generating timed audio from SRT", 191 | total=len(srt_entries), 192 | ) 193 | 194 | # Calculate total duration needed 195 | total_duration = max(entry.end_time for entry in srt_entries) 196 | total_samples = int(total_duration * SAMPLE_RATE) 197 | 198 | # Initialize stereo audio array with silence 199 | full_audio = np.zeros((total_samples, 2)) 200 | 201 | for i, entry in enumerate(srt_entries): 202 | # Split text into sentences for better processing 203 | sentences = split_text_to_sentences(entry.text, self.nltk_language) 204 | 205 | # Generate audio for this entry 206 | entry_audio_chunks = [] 207 | for sentence in sentences: 208 | generator = self.pipeline( 209 | sentence, voice=self.voice, speed=self.speed, split_pattern=None 210 | ) 211 | 212 | for result in generator: 213 | if result.audio is not None: 214 | trimmed_audio, _ = librosa.effects.trim( 215 | result.audio.numpy(), top_db=70 216 | ) 217 | entry_audio_chunks.append(self.to_stereo(trimmed_audio)) 218 | 219 | if entry_audio_chunks: 220 | # Concatenate all audio for this entry 221 | entry_audio = np.concatenate(entry_audio_chunks, axis=0) 222 | 223 | # Calculate timing 224 | start_sample = int(entry.start_time * SAMPLE_RATE) 225 | entry_duration = entry.end_time - entry.start_time 226 | target_samples = int(entry_duration * SAMPLE_RATE) 227 | 228 | # Ensure we don't exceed the target duration 229 | if len(entry_audio) > target_samples: 230 | # If audio is too long, truncate it 231 | entry_audio = entry_audio[:target_samples] 232 | 233 | # Calculate end sample 234 | end_sample = start_sample + len(entry_audio) 235 | 236 | # Make sure we don't exceed the total audio length 237 | if end_sample > len(full_audio): 238 | end_sample = len(full_audio) 239 | entry_audio = entry_audio[:end_sample - start_sample] 240 | 241 | # Place audio at the correct timing 242 | if start_sample < len(full_audio): 243 | full_audio[start_sample:end_sample] = entry_audio 244 | 245 | progress.update(task, advance=1) 246 | 247 | # Save the final audio 248 | sf.write(output_file, full_audio, SAMPLE_RATE, format="WAV") 249 | 250 | progress.update( 251 | task, 252 | completed=len(srt_entries), 253 | description=f"[bold green]Saved timed audio to {output_file}[/]", 254 | ) 255 | 256 | except KeyboardInterrupt: 257 | console.print("\n[bold yellow]Exiting...[/]") 258 | sys.exit() 259 | except Exception as e: 260 | console.print(f"[bold red]SRT generation error:[/] {str(e)}") 261 | 262 | def to_stereo(self, chunk): 263 | """Convert mono chunk to stereo""" 264 | if chunk.ndim == 1: 265 | return np.stack([chunk, chunk], axis=1) 266 | if chunk.ndim == 2 and chunk.shape[1] == 2: 267 | return chunk 268 | raise ValueError( 269 | f"Unsupported chunk shape: {chunk.shape}. Expected 1D (mono) or 2D (stereo)." 270 | ) 271 | 272 | def play_audio(self, gui_highlight=None) -> None: 273 | """Play audio chunks from the queue.""" 274 | try: 275 | if self.audio_player is None: 276 | self.audio_player = AudioPlayer(SAMPLE_RATE) 277 | audio_chunks = [] 278 | audio_size = 0 279 | self.back_number = 0 280 | self.print_complete = True 281 | while not self.stop_event.is_set(): 282 | self.skip.clear() 283 | self.back.clear() 284 | with self.lock: 285 | back_number = self.back_number = min(self.back_number, audio_size) 286 | if back_number > 0 and audio_size > 0: 287 | audio = audio_chunks[audio_size - back_number] 288 | else: 289 | audio = self.audio_queue.get() 290 | if audio is None: 291 | break 292 | 293 | audio_chunks.append(audio) 294 | audio_size += 1 295 | 296 | if self.verbose: 297 | console.print("[dim]Playing chunk...[/dim]") 298 | 299 | self.audio_player.play(audio) 300 | if gui_highlight is not None: 301 | gui_highlight.queue.put( 302 | (gui_highlight.highlight, (audio_size - (back_number or 1),)) 303 | ) 304 | while self.audio_player.is_playing: 305 | if self.stop_event.is_set(): 306 | self.audio_player.stop() 307 | return 308 | elif self.skip.is_set(): 309 | self.audio_player.stop() 310 | break 311 | elif self.back.is_set(): 312 | self.audio_player.stop() 313 | break 314 | time.sleep(0.2) 315 | 316 | with self.lock: 317 | if not self.back.is_set() and self.back_number > 0: 318 | self.back_number -= 1 319 | if self.back_number == 0: 320 | self.audio_queue.task_done() 321 | if gui_highlight is not None: 322 | gui_highlight.queue.put(gui_highlight.remove_highlight) 323 | self.audio_player.stop() 324 | if self.print_complete is True: 325 | console.print("[green]Playback complete.[/]\n") 326 | except Exception as e: 327 | console.print(f"[dim]Playback thread error: {e}[/dim]") 328 | 329 | def skip_sentence(self) -> None: 330 | self.skip.set() 331 | 332 | def back_sentence(self) -> None: 333 | self.back_number += 1 334 | self.back.set() 335 | 336 | def stop_playback(self, printm=True) -> None: 337 | """Stop ongoing generation and playback.""" 338 | self.stop_event.set() 339 | 340 | with self.audio_queue.mutex: 341 | self.audio_queue.queue.clear() 342 | 343 | if printm: 344 | console.print("\n[yellow]Playback stopped.[/]\n") 345 | 346 | def pause_playback(self) -> None: 347 | """Pause playback.""" 348 | self.audio_player.pause() 349 | 350 | def resume_playback(self) -> None: 351 | """Resume playback.""" 352 | self.audio_player.resume() 353 | 354 | def speak(self, text: str | list, console_mode=True, gui_highlight=None) -> None: 355 | """Start TTS generation and playback in separate threads.""" 356 | 357 | self.stop_event.clear() 358 | 359 | # Make sure the queue is empty 360 | with self.audio_queue.mutex: 361 | self.audio_queue.queue.clear() 362 | 363 | gen_thread = threading.Thread( 364 | target=self.generate_audio, args=(text,), daemon=True 365 | ) 366 | play_thread = threading.Thread( 367 | target=self.play_audio, args=(gui_highlight,), daemon=True 368 | ) 369 | 370 | try: 371 | # Start generation thread 372 | gen_thread.start() 373 | 374 | # Start playback thread 375 | play_thread.start() 376 | 377 | # Wait for playback to complete 378 | play_thread.join() 379 | gen_thread.join() 380 | except KeyboardInterrupt: 381 | if console_mode and self.ctrlc: 382 | self.stop_playback(False) 383 | console.print("\n[bold yellow]Interrupted. Type !q to exit.[/]") 384 | gen_thread.join() 385 | play_thread.join() 386 | elif console_mode: 387 | # self.stop_playback(False) 388 | self.print_complete = False 389 | console.print("\n[bold yellow]Type !p to pause.[/]") 390 | else: 391 | console.print("\n[bold yellow]Exiting...[/]") 392 | self.stop_playback(False) 393 | gen_thread.join() 394 | play_thread.join() 395 | sys.exit() 396 | 397 | 398 | class AudioPlayer: 399 | def __init__(self, samplerate): 400 | self.samplerate = samplerate 401 | self.current_frame = 0 402 | self.playing = True 403 | self.event = threading.Event() 404 | self.lock = threading.Lock() 405 | self.current_audio = None 406 | self.stream = sd.OutputStream( 407 | samplerate=self.samplerate, 408 | channels=2, 409 | callback=self._callback, 410 | finished_callback=self._finished_callback, 411 | ) 412 | self.stream.start() 413 | 414 | def _callback(self, outdata, frames, time, status): 415 | with self.lock: 416 | if not self.playing or self.current_audio is None: 417 | outdata.fill(0) 418 | return 419 | 420 | chunksize = min(len(self.current_audio) - self.current_frame, frames) 421 | 422 | if len(self.current_audio.shape) == 1: 423 | # Mono audio: copy to all output channels 424 | for channel in range(outdata.shape[1]): 425 | outdata[:chunksize, channel] = self.current_audio[ 426 | self.current_frame : self.current_frame + chunksize 427 | ] 428 | else: 429 | # Stereo or multi-channel: copy up to available channels 430 | channels = min(self.current_audio.shape[1], outdata.shape[1]) 431 | outdata[:chunksize, :channels] = self.current_audio[ 432 | self.current_frame : self.current_frame + chunksize, :channels 433 | ] 434 | 435 | if chunksize < frames: 436 | outdata[chunksize:] = 0 437 | self.current_audio = None 438 | self.event.set() 439 | 440 | self.current_frame += chunksize 441 | 442 | def _finished_callback(self): 443 | """Called when stream is stopped""" 444 | self.event.set() 445 | 446 | def play(self, audio, blocking=False) -> None: 447 | """Start playback of a single audio clip""" 448 | with self.lock: 449 | self.current_audio = audio 450 | self.current_frame = 0 451 | self.playing = True 452 | 453 | if blocking: 454 | self.event.clear() 455 | self.event.wait() 456 | 457 | def resume(self) -> None: 458 | """Resume playback""" 459 | with self.lock: 460 | self.playing = True 461 | 462 | def pause(self) -> None: 463 | """Pause playback""" 464 | with self.lock: 465 | self.playing = False 466 | 467 | def stop(self) -> None: 468 | """Stop playback and clear current audio""" 469 | with self.lock: 470 | self.playing = False 471 | self.current_frame = 0 472 | self.current_audio = None 473 | self.event.set() 474 | 475 | @property 476 | def is_playing(self) -> bool: 477 | """Check if audio is actively playing""" 478 | with self.lock: 479 | return self.current_audio is not None 480 | 481 | def __del__(self): 482 | """Cleanup when object is destroyed""" 483 | if hasattr(self, "stream"): 484 | self.stream.stop() 485 | self.stream.close() 486 | -------------------------------------------------------------------------------- /src/run.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import sys 3 | import threading 4 | import time 5 | import warnings 6 | from typing import Optional 7 | 8 | from config import ( 9 | DEFAULT_LANGUAGE, 10 | DEFAULT_SPEED, 11 | DEFAULT_VOICE, 12 | HOST, 13 | MAX_SPEED, 14 | TIMEOUT, 15 | MIN_SPEED, 16 | PORT, 17 | PROMPT, 18 | REPO_ID, 19 | SAMPLE_RATE, 20 | console, 21 | ) 22 | 23 | with console.status( 24 | "[yellow]Initializing Kokoro...[/]", 25 | spinner="dots", 26 | spinner_style="yellow", 27 | speed=0.8, 28 | ): 29 | # Ignoring the following warnings: 30 | # 1. RNN dropout warning (UserWarning) - Expected behavior when dropout > 0 with num_layers=1 31 | # 2. weight_norm deprecation (FutureWarning) - Still functional, will update when PyTorch removes it 32 | # These are safe to suppress as they don't affect model behavior. 33 | warnings.filterwarnings( 34 | "ignore", 35 | message="dropout option adds dropout after all but last recurrent layer", 36 | category=UserWarning, 37 | module="torch.nn.modules.rnn", 38 | ) 39 | warnings.filterwarnings( 40 | "ignore", 41 | message=r"`torch\.nn\.utils\.weight_norm` is deprecated", 42 | category=FutureWarning, 43 | module="torch.nn.utils.weight_norm", 44 | ) 45 | from kokoro import KPipeline 46 | console.print("[bold green]Kokoro initialized!") 47 | 48 | import easyocr 49 | import nltk 50 | 51 | from input_hander import Args, get_input 52 | from models import TTSPlayer 53 | from utils import ( 54 | clear_history, 55 | display_help, 56 | display_languages, 57 | display_status, 58 | display_voices, 59 | format_status, 60 | get_easyocr_language_map, 61 | get_language_map, 62 | get_voices, 63 | split_text_to_sentences, 64 | ) 65 | 66 | running_threads = 1 67 | 68 | def start(args: Args) -> None: 69 | """Initialize and run""" 70 | try: 71 | with console.status( 72 | "[yellow]Initializing Kokoro pipeline...[/]", 73 | spinner="dots", 74 | spinner_style="yellow", 75 | speed=0.8, 76 | ): 77 | # Initialize TTS pipeline 78 | pipeline = KPipeline( 79 | lang_code=args.language, repo_id=REPO_ID, device=args.device 80 | ) 81 | console.print("[bold green]Kokoro pipeline initialized!") 82 | 83 | # Download nltk tokenizers if not found 84 | try: 85 | nltk.data.find("tokenizers/punkt") 86 | nltk.data.find("tokenizers/punkt_tab") 87 | except LookupError: 88 | with console.status( 89 | "[yellow]Download nltk tokenizers...[/]", 90 | spinner="dots", 91 | spinner_style="yellow", 92 | speed=0.8, 93 | ): 94 | nltk.download("punkt", quiet=True) 95 | nltk.download("punkt_tab", quiet=True) 96 | console.print("[bold green]Downloading nltk tokenizers finished!") 97 | 98 | # audio_warmup() 99 | 100 | if args.setup: 101 | return 102 | elif args.daemon: 103 | easyocr_lang = [ 104 | lang 105 | for code, lang in get_easyocr_language_map().items() 106 | if code == args.language 107 | ] 108 | 109 | image_reader = easyocr.Reader(easyocr_lang) 110 | run_daemon( 111 | pipeline, 112 | args.language, 113 | args.voice, 114 | args.speed, 115 | args.device, 116 | args.verbose, 117 | args.port, 118 | image_reader, 119 | ) 120 | elif args.gui: 121 | from gui import run_gui 122 | 123 | easyocr_lang = [ 124 | lang 125 | for code, lang in get_easyocr_language_map().items() 126 | if code == args.language 127 | ] 128 | 129 | image_reader = easyocr.Reader(easyocr_lang) 130 | run_gui( 131 | pipeline, 132 | args.language, 133 | args.voice, 134 | args.speed, 135 | args.device, 136 | args.theme, 137 | image_reader, 138 | ) 139 | elif args.all_voices and args.input_text: 140 | run_with_all( 141 | pipeline, args.language, args.speed, args.verbose, args.input_text 142 | ) 143 | elif args.input_text and args.is_srt_file: 144 | run_srt_cli( 145 | pipeline, 146 | args.language, 147 | args.voice, 148 | args.speed, 149 | args.verbose, 150 | args.input_text, # This contains the SRT file path 151 | args.output_file, 152 | ) 153 | elif args.input_text: 154 | run_cli( 155 | pipeline, 156 | args.language, 157 | args.voice, 158 | args.speed, 159 | args.verbose, 160 | args.input_text, 161 | args.output_file, 162 | ) 163 | else: 164 | run_console( 165 | pipeline, 166 | args.language, 167 | args.voice, 168 | args.speed, 169 | args.verbose, 170 | args.history_off, 171 | args.device, 172 | args.ctrl_c, 173 | PROMPT, 174 | ) 175 | except KeyboardInterrupt: 176 | console.print("\n[bold yellow]Terminated[/]") 177 | except EOFError: 178 | console.print("\n") 179 | except Exception as e: 180 | console.print(f"[bold red]Error:[/] {str(e)}") 181 | 182 | 183 | def speak_thread(clipboard_data: str, player: TTSPlayer) -> None: 184 | """Player speak wrapper""" 185 | try: 186 | player.speak(clipboard_data, console_mode=False) 187 | except Exception as e: 188 | print(f"Error in thread: {str(e)}") 189 | 190 | 191 | def run_daemon( 192 | pipeline: KPipeline, 193 | language: str, 194 | voice: str, 195 | speed: float, 196 | device: Optional[str], 197 | verbose: bool, 198 | port: int, 199 | image_reader: easyocr.Reader, 200 | ) -> None: 201 | """Start daemon mode""" 202 | current_thread = None 203 | player = TTSPlayer(pipeline, language, voice, speed, verbose) 204 | 205 | try: 206 | with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket: 207 | server_socket.bind((HOST, port)) 208 | server_socket.listen(1) 209 | print(f"Listening on {HOST}:{port}...") 210 | 211 | while True: 212 | conn, addr = server_socket.accept() 213 | with conn: 214 | print(f"Connected by {addr}") 215 | 216 | # Read all 217 | data = b"" 218 | while True: 219 | chunk = conn.recv(4096) 220 | if not chunk: 221 | break 222 | data += chunk 223 | 224 | if data.startswith(b"IMAGE:"): 225 | results = image_reader.readtext(data[6:]) 226 | clipboard_data = "" 227 | clipboard_data = " ".join( 228 | text for _, text, _ in results if text 229 | ).strip() 230 | if not clipboard_data: 231 | continue 232 | elif data.startswith(b"TEXT:"): 233 | clipboard_data = data[5:].decode() 234 | else: 235 | clipboard_data = data.decode() 236 | 237 | print(f"Received {clipboard_data[:20]}...") 238 | 239 | # Handle commands 240 | if clipboard_data.startswith("!"): 241 | parts = clipboard_data.split(maxsplit=1) 242 | cmd = parts[0].lower() 243 | arg = parts[1] if len(parts) > 1 else "" 244 | 245 | if cmd == "!lang": 246 | if player.change_language(arg, device): 247 | print(f"Language changed to: {player.languages[arg]}") 248 | 249 | easyocr_lang = [ 250 | lang 251 | for code, lang in get_easyocr_language_map().items() 252 | if code == arg 253 | ] 254 | image_reader = easyocr.Reader(easyocr_lang) 255 | else: 256 | print("Invalid language code.") 257 | 258 | elif cmd == "!voice": 259 | if player.change_voice(arg): 260 | print(f"Voice changed to: {arg}") 261 | else: 262 | print("Invalid voice.") 263 | 264 | elif cmd == "!speed": 265 | try: 266 | new_speed = float(arg) 267 | if player.change_speed(new_speed): 268 | print(f"Speed changed to: {new_speed}") 269 | else: 270 | print( 271 | f"Speed must be between {MIN_SPEED} and {MAX_SPEED}" 272 | ) 273 | except ValueError: 274 | print("Invalid speed value") 275 | 276 | elif cmd == "!pause": 277 | player.pause_playback() 278 | elif cmd == "!resume": 279 | player.resume_playback() 280 | elif cmd == "!back": 281 | player.back_sentence() 282 | elif cmd == "!next": 283 | player.skip_sentence() 284 | elif cmd in ("!stop", "!exit", "!status"): 285 | if current_thread is not None and current_thread.is_alive(): 286 | print("Stopping previous playback...") 287 | player.stop_playback() 288 | current_thread.join() 289 | if cmd == "!exit": 290 | print("Exiting...") 291 | if current_thread is not None and current_thread.is_alive(): 292 | print("Stopping previous playback...") 293 | player.stop_playback() 294 | current_thread.join() 295 | sys.exit(0) 296 | if cmd == "!status": 297 | status_str = format_status( 298 | player.language, player.voice, player.speed 299 | ) 300 | current_thread = threading.Thread( 301 | target=speak_thread, 302 | args=(status_str, player), 303 | ) 304 | current_thread.daemon = True 305 | current_thread.start() 306 | else: 307 | if current_thread is not None and current_thread.is_alive(): 308 | print("Stopping previous playback...") 309 | player.stop_playback() 310 | current_thread.join() 311 | sentences = split_text_to_sentences( 312 | clipboard_data, player.nltk_language 313 | ) 314 | current_thread = threading.Thread( 315 | target=speak_thread, 316 | args=(sentences, player), 317 | ) 318 | current_thread.daemon = True 319 | current_thread.start() 320 | print("Started new playback thread") 321 | 322 | except KeyboardInterrupt: 323 | print("Exiting...") 324 | if current_thread is not None and current_thread.is_alive(): 325 | player.stop_playback() 326 | current_thread.join(timeout=1) 327 | sys.exit() 328 | except Exception as e: 329 | print(f"Error: {str(e)}") 330 | if current_thread is not None and current_thread.is_alive(): 331 | player.stop_playback() 332 | current_thread.join(timeout=1) 333 | try: 334 | if "Address already in use" in str(e): 335 | print(f"Error: Port {port} is already in use.") 336 | print("This could be due to:") 337 | print(" - Another instance of this program running.") 338 | print(f" - A different process using port {port}.") 339 | print("To resolve this:") 340 | print( 341 | " - Check for and terminate any other instances of this program." 342 | ) 343 | print( 344 | " - Alternatively, use a different port with the --port option (e.g., --port 9911)." 345 | ) 346 | run_cli( 347 | pipeline, 348 | DEFAULT_LANGUAGE, 349 | DEFAULT_VOICE, 350 | DEFAULT_SPEED, 351 | False, 352 | f"Error: {str(e)[:40]}. for more info see logs. Exiting.", 353 | None, 354 | ) 355 | except Exception as e: 356 | pass 357 | 358 | 359 | def run_with_all( 360 | pipeline: KPipeline, 361 | language: str, 362 | speed: float, 363 | verbose: bool, 364 | input_text: str, 365 | ) -> None: 366 | """Run with all available voices""" 367 | console.print( 368 | f"\n[bold blue]Reading with all available {get_language_map()[language]} voices[/]\n" 369 | ) 370 | target_voices = [voice for voice in get_voices() if voice.startswith(language)] 371 | 372 | player = TTSPlayer(pipeline, language, target_voices[0], speed, verbose) 373 | sentences = split_text_to_sentences(input_text, player.nltk_language) 374 | try: 375 | for voice in target_voices: 376 | player.change_voice(voice) 377 | console.print(f"[cyan]{voice} speaking:[/] {input_text[:30]}") 378 | player.speak(sentences, console_mode=False) 379 | except KeyboardInterrupt: 380 | console.print("[bold yellow]Exiting...[/]") 381 | global running_threads 382 | if threading.active_count() > running_threads: 383 | player.stop_playback(False) 384 | start_time = time.time() 385 | while threading.active_count() > running_threads and (time.time() - start_time) < TIMEOUT: 386 | time.sleep(0.1) 387 | if threading.active_count() > running_threads: 388 | console.print("[red]Warning: Threads still active after timeout, proceeding anyway.[/]") 389 | running_threads += 1 390 | sys.exit() 391 | 392 | 393 | def run_cli( 394 | pipeline: KPipeline, 395 | language: str, 396 | voice: str, 397 | speed: float, 398 | verbose: bool, 399 | input_text: str, 400 | output_file: Optional[str], 401 | ) -> None: 402 | """Generate audio""" 403 | player = TTSPlayer(pipeline, language, voice, speed, verbose) 404 | sentences = split_text_to_sentences(input_text, player.nltk_language) 405 | if output_file is None: 406 | try: 407 | with console.status( 408 | f"[cyan]Speaking:[/] {input_text[:30]}...", spinner_style="cyan" 409 | ): 410 | player.speak(sentences, console_mode=False) 411 | except KeyboardInterrupt: 412 | console.print("[bold yellow]Exiting...[/]") 413 | global running_threads 414 | if threading.active_count() > running_threads: 415 | player.stop_playback(False) 416 | start_time = time.time() 417 | while threading.active_count() > running_threads and (time.time() - start_time) < TIMEOUT: 418 | time.sleep(0.1) 419 | if threading.active_count() > running_threads: 420 | console.print("[red]Warning: Threads still active after timeout, proceeding anyway.[/]") 421 | running_threads += 1 422 | sys.exit() 423 | else: 424 | player.generate_audio_file(sentences, output_file=output_file) 425 | 426 | 427 | def run_srt_cli( 428 | pipeline: KPipeline, 429 | language: str, 430 | voice: str, 431 | speed: float, 432 | verbose: bool, 433 | srt_file: str, 434 | output_file: Optional[str], 435 | ) -> None: 436 | """Generate timed audio from SRT file""" 437 | player = TTSPlayer(pipeline, language, voice, speed, verbose) 438 | 439 | if output_file is None: 440 | output_file = "srt_output.wav" 441 | 442 | try: 443 | console.print(f"[cyan]Processing SRT file:[/] {srt_file}") 444 | player.generate_srt_timed_audio(srt_file, output_file=output_file) 445 | console.print(f"[bold green]✓ Timed audio saved to:[/] {output_file}") 446 | except KeyboardInterrupt: 447 | console.print("[bold yellow]Exiting...[/]") 448 | sys.exit() 449 | except Exception as e: 450 | console.print(f"[bold red]Error processing SRT file:[/] {str(e)}") 451 | sys.exit(1) 452 | 453 | 454 | def run_console( 455 | pipeline: KPipeline, 456 | language: str, 457 | voice: str, 458 | speed: float, 459 | verbose: bool, 460 | history_off: bool, 461 | device: Optional[str], 462 | ctrlc: bool, 463 | prompt="> ", 464 | ) -> None: 465 | """Run an interactive TTS session with dynamic settings.""" 466 | 467 | player = TTSPlayer(pipeline, language, voice, speed, verbose, ctrlc) 468 | 469 | console.rule("[bold green]Interactive TTS started[/]") 470 | display_help() 471 | 472 | # Display starting configuration 473 | console.print("[green]Starting with:[/]") 474 | console.print(f" Language: [cyan]{get_language_map()[language]}[/]") 475 | console.print(f" Voice: [cyan]{voice}[/]") 476 | console.print(f" Speed: [cyan]{speed}[/]") 477 | global running_threads 478 | while True: 479 | try: 480 | user_input = get_input(history_off, prompt) 481 | if not user_input: 482 | continue 483 | 484 | # Handle commands 485 | if user_input.startswith("!"): 486 | parts = user_input.split(maxsplit=1) 487 | cmd = parts[0].lower() 488 | arg = parts[1] if len(parts) > 1 else "" 489 | 490 | if cmd == "!lang": 491 | if player.change_language(arg, device): 492 | console.print( 493 | f"[green]Language changed to:[/] {player.languages[arg]}" 494 | ) 495 | else: 496 | console.print("[red]Invalid language code.[/]") 497 | display_languages() 498 | 499 | elif cmd == "!voice": 500 | if player.change_voice(arg): 501 | console.print(f"[green]Voice changed to:[/] {arg}") 502 | else: 503 | console.print("[red]Invalid voice.[/]") 504 | console.print("Use !list_voices to see options.") 505 | 506 | elif cmd == "!speed": 507 | try: 508 | new_speed = float(arg) 509 | if player.change_speed(new_speed): 510 | console.print(f"[green]Speed changed to:[/] {new_speed}") 511 | else: 512 | console.print( 513 | f"[red]Speed must be between {MIN_SPEED} and {MAX_SPEED}[/]" 514 | ) 515 | except ValueError: 516 | console.print("[red]Invalid speed value[/]") 517 | 518 | elif cmd in ("!s", "!stop"): 519 | player.stop_playback() 520 | 521 | elif cmd in ("!p", "!pause"): 522 | player.pause_playback() 523 | 524 | elif cmd in ("!r", "!resume"): 525 | player.resume_playback() 526 | 527 | elif cmd in ("!b", "!back"): 528 | player.back_sentence() 529 | 530 | elif cmd in ("!n", "!next"): 531 | player.skip_sentence() 532 | 533 | elif cmd == "!list_langs": 534 | display_languages() 535 | 536 | elif cmd == "!list_voices": 537 | display_voices(player.language) 538 | 539 | elif cmd == "!list_all_voices": 540 | display_voices() 541 | 542 | elif cmd in ("!help", "!h"): 543 | display_help() 544 | 545 | elif cmd in ("!quit", "!q"): 546 | console.print("[bold yellow]Exiting...[/]") 547 | if threading.active_count() > running_threads: 548 | player.stop_playback(False) 549 | start_time = time.time() 550 | while threading.active_count() > running_threads and (time.time() - start_time) < TIMEOUT: 551 | time.sleep(0.1) 552 | if threading.active_count() > running_threads: 553 | console.print("[red]Warning: Threads still active after timeout, proceeding anyway.[/]") 554 | running_threads += 1 555 | break 556 | 557 | elif cmd == "!clear": 558 | print("\033[H\033[J", end="") 559 | 560 | elif cmd == "!clear_history": 561 | clear_history() 562 | 563 | elif cmd == "!ctrlc": 564 | player.ctrlc = not player.ctrlc 565 | if player.ctrlc: 566 | console.print("[green]Ctrl+C ends the playback") 567 | else: 568 | console.print("[green]Ctrl+C gives a new line") 569 | 570 | elif cmd in ("!status", "!h"): 571 | display_status(player.language, player.voice, player.speed) 572 | 573 | elif cmd == "!verbose": 574 | player.verbose = not player.verbose 575 | else: 576 | console.print(f"[red]Unknown command: {cmd}[/]") 577 | console.print("Type !help for available commands.") 578 | 579 | continue 580 | 581 | # Stop if previous playback still running 582 | if threading.active_count() > running_threads: 583 | player.stop_playback(False) 584 | start_time = time.time() 585 | while threading.active_count() > running_threads and (time.time() - start_time) < TIMEOUT: 586 | time.sleep(0.1) 587 | if threading.active_count() > running_threads: 588 | console.print("[red]Warning: Threads still active after timeout, proceeding anyway.[/]") 589 | running_threads += 1 590 | 591 | sentences = split_text_to_sentences(user_input, player.nltk_language) 592 | with console.status( 593 | f"[cyan]Speaking:[/] {user_input[:30]}...", spinner_style="cyan" 594 | ): 595 | player.speak(sentences) 596 | 597 | except KeyboardInterrupt: 598 | if player.ctrlc: 599 | player.stop_playback(False) 600 | console.print("\n[bold yellow]Interrupted. Type !q to exit.[/]") 601 | else: 602 | player.print_complete = False 603 | console.print("\n[bold yellow]Type !p to pause.[/]") 604 | except EOFError: 605 | console.print("\n[bold yellow]Type !q to exit.[/]") 606 | except Exception as e: 607 | console.print(f"[bold red]Error:[/] {str(e)}") 608 | -------------------------------------------------------------------------------- /src/gui.py: -------------------------------------------------------------------------------- 1 | import os 2 | import queue 3 | import signal 4 | import threading 5 | import tkinter as tk 6 | from tkinter import messagebox 7 | from typing import Dict, Optional 8 | 9 | import easyocr 10 | import ttkbootstrap as ttk 11 | from kokoro import KPipeline 12 | from ttkbootstrap.tooltip import ToolTip 13 | 14 | from config import MAX_SPEED, MIN_SPEED, TITLE, VERSION, WINDOW_SIZE 15 | from models import TTSPlayer 16 | from utils import ( 17 | get_easyocr_language_map, 18 | get_gui_themes, 19 | get_language_map, 20 | get_nltk_language, 21 | get_nltk_language_map, 22 | get_voices, 23 | split_text_to_sentences, 24 | ) 25 | 26 | 27 | class Gui: 28 | def __init__( 29 | self, 30 | root: ttk.Window, 31 | pipeline: KPipeline, 32 | language: str, 33 | voice: str, 34 | speed: float, 35 | device: Optional[str], 36 | image_reader: easyocr.Reader, 37 | dark_theme: bool, 38 | ): 39 | self.root = root 40 | self.dark_theme = dark_theme 41 | self.languages = [lang for _, lang in get_language_map().items()] 42 | self.voices = get_voices() 43 | self.current_language_code = language 44 | self.current_language = get_language_map()[language] 45 | self.current_voice = voice 46 | self.speed = speed 47 | self.device = device 48 | self.pipeline = pipeline 49 | self.player = TTSPlayer( 50 | self.pipeline, self.current_language, self.current_voice, self.speed, False 51 | ) 52 | self.current_thread = None 53 | self.speech_paused = False 54 | self.prev_text = "" 55 | self.prev_sentences = [] 56 | self.nltk_language = get_nltk_language(self.current_language_code) 57 | self.sentence_indices = [] 58 | 59 | self.reader = image_reader 60 | 61 | self.queue = queue.Queue() 62 | self.root.after(100, self.process_queue) 63 | 64 | self.default_font = "Segoe UI" 65 | self.is_speaking = False 66 | 67 | self._color_cache = {} 68 | 69 | self.create_widgets() 70 | 71 | self.default_bg = self.text_area.cget("background") 72 | self.default_fg = self.text_area.cget("foreground") 73 | self.default_cursor = self.text_area.cget("cursor") 74 | self.text_area.tag_config( 75 | "highlight", background="#3a86ff", foreground="#ffffff" 76 | ) 77 | 78 | def process_queue(self) -> None: 79 | try: 80 | while True: 81 | item = self.queue.get_nowait() 82 | if isinstance(item, tuple): 83 | func, args = item 84 | func(*args) 85 | else: 86 | func = item 87 | func() 88 | except queue.Empty: 89 | pass 90 | self.root.after(100, self.process_queue) 91 | 92 | def change_speed(self, event) -> None: 93 | """Change speed""" 94 | speed = self.speed_scale.get() 95 | self.speed = speed 96 | self.player.change_speed(speed) 97 | self.speed_label.config(text=f"{speed:.1f}x") 98 | self.status_label.config(text=f"Speed set to: {self.speed:.2f}x") 99 | 100 | def change_voice(self, *args) -> None: 101 | """Change voice""" 102 | self.current_voice = self.voice_var.get() 103 | self.player.change_voice(self.current_voice) 104 | self.status_label.config(text=f"Voice set to: {self.current_voice}") 105 | 106 | def change_lang(self, event, voice_menu: ttk.Combobox) -> None: 107 | """Change language and update voice menu""" 108 | self.current_language = self.lang_var.get() 109 | self.current_language_code = next( 110 | code 111 | for code, lang in get_language_map().items() 112 | if lang == self.current_language 113 | ) 114 | self.player.change_language(self.current_language_code, self.device) 115 | self.status_label.config(text=f"Language set to: {self.current_language}") 116 | 117 | easyocr_lang = [ 118 | lang 119 | for code, lang in get_easyocr_language_map().items() 120 | if code == self.current_language_code 121 | ] 122 | self.reader = easyocr.Reader(easyocr_lang) 123 | 124 | self.nltk_language = get_nltk_language(self.current_language_code) 125 | 126 | # Update voice menu 127 | if not self.current_voice.startswith(self.current_language_code): 128 | voice_menu["values"] = [ 129 | voice 130 | for voice in self.voices 131 | if voice.startswith(self.current_language_code) 132 | ] 133 | self.voice_var.set(voice_menu["values"][0]) 134 | self.current_voice = self.voice_var.get() 135 | 136 | def play_speech(self) -> None: 137 | """Play or resume if it was paused""" 138 | text = self.text_area.get("1.0", tk.END).strip() 139 | 140 | if self.prev_text == text and self.speech_paused is True: 141 | self.speech_paused = False 142 | self.resume_speech() 143 | else: 144 | self.text_area.delete("1.0", tk.END) 145 | self.text_area.insert("1.0", text) 146 | self.prev_text = text 147 | self.prev_sentences = split_text_to_sentences(text, self.nltk_language) 148 | if self.current_thread is not None and self.current_thread.is_alive(): 149 | self.player.stop_playback() 150 | self.current_thread.join() 151 | self.current_thread = threading.Thread( 152 | target=self.speak_thread, args=(self.prev_sentences,), daemon=True 153 | ) 154 | self.current_thread.start() 155 | self.calculate_sentence_indices() 156 | self.status_label.config(text="Playback: started") 157 | 158 | def speak_thread(self, text: str) -> None: 159 | """Player speak wrapper""" 160 | try: 161 | self.queue.put( 162 | lambda: self.text_area.config( 163 | state="disabled", 164 | background=self.darken_color(self.default_bg), 165 | foreground=self.darken_color(self.default_fg), 166 | cursor="arrow", 167 | ) 168 | ) 169 | self.player.speak(text, console_mode=False, gui_highlight=self) 170 | self.queue.put( 171 | lambda: self.text_area.config( 172 | state="normal", 173 | background=self.default_bg, 174 | foreground=self.default_fg, 175 | cursor=self.default_cursor, 176 | ) 177 | ) 178 | except Exception as e: 179 | print(f"Error in thread: {str(e)}") 180 | 181 | def pause_speech(self) -> None: 182 | """Pause speech""" 183 | self.speech_paused = True 184 | self.text_area.config( 185 | state="normal", 186 | background=self.default_bg, 187 | foreground=self.default_fg, 188 | cursor=self.default_cursor, 189 | ) 190 | self.player.pause_playback() 191 | self.status_label.config(text="Playback: paused") 192 | 193 | def resume_speech(self) -> None: 194 | """Resume speech""" 195 | self.text_area.config( 196 | state="disabled", 197 | background=self.darken_color(self.default_bg), 198 | foreground=self.darken_color(self.default_fg), 199 | cursor="arrow", 200 | ) 201 | self.player.resume_playback() 202 | self.status_label.config(text="Playback: resumed") 203 | 204 | def darken_color(self, color, factor=0.8) -> str: 205 | """Darken a color by a given factor""" 206 | cache_key = (color, factor) 207 | if cache_key in self._color_cache: 208 | return self._color_cache[cache_key] 209 | rgb = self.root.winfo_rgb(color) 210 | darkened = tuple(int(c * factor / 65535 * 255) for c in rgb[:3]) 211 | result = f"#{darkened[0]:02x}{darkened[1]:02x}{darkened[2]:02x}" 212 | self._color_cache[cache_key] = result 213 | return result 214 | 215 | def calculate_sentence_indices(self) -> None: 216 | """Calculate start and end indices for each sentence.""" 217 | self.sentence_indices.clear() 218 | current_pos = 0 219 | text_content = self.prev_text 220 | 221 | for sentence in self.prev_sentences: 222 | start_pos = text_content.find(sentence, current_pos) 223 | if start_pos == -1: 224 | continue 225 | 226 | # Calculate line and column for start index 227 | text_before = text_content[:start_pos] 228 | start_line = text_before.count("\n") + 1 229 | start_char = ( 230 | start_pos - text_before.rfind("\n") - 1 231 | if text_before.rfind("\n") != -1 232 | else start_pos 233 | ) 234 | 235 | # Calculate end position 236 | end_pos = start_pos + len(sentence) 237 | text_before_end = text_content[:end_pos] 238 | end_line = text_before_end.count("\n") + 1 239 | end_char = ( 240 | end_pos - text_before_end.rfind("\n") - 1 241 | if text_before_end.rfind("\n") != -1 242 | else end_pos 243 | ) 244 | 245 | self.sentence_indices.append( 246 | {"start": f"{start_line}.{start_char}", "end": f"{end_line}.{end_char}"} 247 | ) 248 | current_pos = end_pos 249 | 250 | def remove_highlight(self) -> None: 251 | """Remove highlight""" 252 | self.text_area.tag_remove("highlight", "1.0", tk.END) 253 | 254 | def highlight(self, sentence: int) -> None: 255 | """Highlight a sentence""" 256 | if not self.sentence_indices: 257 | return 258 | 259 | self.text_area.tag_remove("highlight", "1.0", tk.END) 260 | indices = self.sentence_indices[sentence % len(self.prev_sentences)] 261 | self.text_area.tag_add("highlight", indices["start"], indices["end"]) 262 | self.text_area.see(indices["start"]) 263 | 264 | def skip_sentence(self) -> None: 265 | """Skip a sentence""" 266 | self.player.skip_sentence() 267 | self.status_label.config(text="Playback: to the next sentence") 268 | 269 | def back_sentence(self) -> None: 270 | """Back a sentence""" 271 | self.player.back_sentence() 272 | self.status_label.config(text="Playback: back one sentence") 273 | 274 | def create_widgets(self) -> None: 275 | """Create widgets""" 276 | # Main frame 277 | container = ttk.Frame(self.root, padding=15) 278 | container.grid(row=0, column=0, sticky="nsew") 279 | container.columnconfigure(0, weight=1) 280 | container.rowconfigure(1, weight=1) 281 | 282 | self.add_title(container) 283 | self.add_text_area(container) 284 | self.add_control_panel(container) 285 | self.add_status_bar(container) 286 | 287 | def add_title(self, container): 288 | """Add Title and subtitle""" 289 | title_frame = ttk.Frame(container) 290 | title_frame.grid(row=0, column=0, sticky="ew", pady=(0, 15)) 291 | title_frame.columnconfigure(2, weight=1) 292 | 293 | style = "light" if self.dark_theme else "dark" 294 | title_label = ttk.Label( 295 | title_frame, 296 | text="KokoroDoki", 297 | font=(self.default_font, 18, "bold"), 298 | bootstyle=style, 299 | ) 300 | title_label.grid(row=0, column=0, sticky="w") 301 | 302 | style = "secondary" if self.dark_theme else "default" 303 | subtitle_label = ttk.Label( 304 | title_frame, 305 | text="Text-to-Speech Reader", 306 | font=(self.default_font, 10), 307 | bootstyle="secondary", 308 | ) 309 | subtitle_label.grid(row=0, column=1, sticky="w", padx=10, pady=5) 310 | 311 | def add_status_bar(self, container): 312 | """Create status bar""" 313 | status_frame = ttk.Frame(container) 314 | status_frame.grid(row=3, column=0, sticky="ew", pady=(10, 0)) 315 | status_frame.columnconfigure(1, weight=1) 316 | 317 | self.status_label = ttk.Label( 318 | status_frame, 319 | text="Ready", 320 | font=(self.default_font, 9), 321 | bootstyle="info", 322 | ) 323 | self.status_label.grid(row=0, column=0, sticky="w") 324 | 325 | version_label = ttk.Label( 326 | status_frame, 327 | text=VERSION, 328 | font=(self.default_font, 9), 329 | bootstyle="secondary", 330 | ) 331 | version_label.grid(row=0, column=2, sticky="e") 332 | 333 | def choose_file(self): 334 | try: 335 | file_path = tk.filedialog.askopenfilename( 336 | title="Select a Text file of an image", 337 | filetypes=[("All files", "*.*"), ("Text files", "*.txt")], 338 | ) 339 | if file_path: 340 | self.file_path_var.set(f"File: {file_path}") 341 | try: 342 | image_extensions = [ 343 | ".png", 344 | ".jpg", 345 | ".jpeg", 346 | ".webp", 347 | ".bmp", 348 | ".tiff", 349 | ".tif", 350 | ] 351 | _, file_ext = os.path.splitext(file_path.lower()) 352 | 353 | if file_ext in image_extensions: 354 | self.text_area.delete(1.0, tk.END) 355 | results = self.reader.readtext(file_path) 356 | image_text = "" 357 | image_text = " ".join( 358 | text for _, text, _ in results if text 359 | ).strip() 360 | 361 | self.text_area.insert( 362 | tk.END, 363 | image_text, 364 | ) 365 | else: 366 | with open(file_path, "r", encoding="utf-8") as file: 367 | self.text_area.delete(1.0, tk.END) 368 | self.text_area.insert(tk.END, file.read()) 369 | except Exception as e: 370 | self.text_area.delete(1.0, tk.END) 371 | self.text_area.insert(tk.END, f"Error reading file: {str(e)}") 372 | except Exception as e: 373 | print(f"An error occurred: {e}") 374 | 375 | def add_text_area(self, container): 376 | """Create text area""" 377 | text_frame = ttk.LabelFrame(container, text="Text Content", padding=10) 378 | text_frame.grid(row=1, column=0, sticky="nsew", pady=10) 379 | text_frame.columnconfigure(0, weight=1) 380 | text_frame.rowconfigure(0, weight=1) 381 | 382 | # Text area 383 | self.text_area = tk.Text( 384 | text_frame, 385 | height=15, 386 | wrap="word", 387 | font=(self.default_font, 12), 388 | borderwidth=0, 389 | ) 390 | self.text_area.grid(row=0, column=0, sticky="nsew") 391 | 392 | # Scrollbar 393 | text_scroll = ttk.Scrollbar(text_frame, command=self.text_area.yview) 394 | text_scroll.grid(row=0, column=1, sticky="ns") 395 | self.text_area.configure(yscrollcommand=text_scroll.set) 396 | 397 | # File selector 398 | button_frame = ttk.Frame(text_frame) 399 | button_frame.grid(row=1, column=0, columnspan=2, sticky="ew", pady=5) 400 | button_frame.columnconfigure(1, weight=1) 401 | 402 | choose_button = ttk.Button( 403 | button_frame, text="Choose File", command=self.choose_file 404 | ) 405 | choose_button.grid(row=0, column=0, sticky="w", padx=(0, 10)) 406 | 407 | # Create a StringVar to hold the file path 408 | self.file_path_var = tk.StringVar() 409 | self.file_path_var.set("No file or image selected") 410 | 411 | # Entry to display the file path 412 | file_path_display = ttk.Entry( 413 | button_frame, 414 | textvariable=self.file_path_var, 415 | state="readonly", 416 | ) 417 | file_path_display.grid(row=0, column=1, sticky="ew") 418 | 419 | # Add placeholder text 420 | self.add_place_holder() 421 | 422 | def add_place_holder(self): 423 | """Add placeholder text""" 424 | placeholder = "Type or select a file..." 425 | self.text_area.insert("1.0", placeholder) 426 | self.text_area.tag_add("placeholder", "1.0", "end") 427 | self.text_area.tag_config("placeholder", foreground="gray") 428 | 429 | def clear_placeholder(event): 430 | if self.text_area.tag_ranges("placeholder"): 431 | self.text_area.delete("1.0", "end") 432 | self.text_area.tag_remove("placeholder", "1.0", "end") 433 | 434 | def restore_placeholder(event): 435 | if not self.text_area.get("1.0", "end-1c"): 436 | self.text_area.insert("1.0", placeholder) 437 | self.text_area.tag_add("placeholder", "1.0", "end") 438 | self.text_area.tag_config("placeholder", foreground="gray") 439 | 440 | self.text_area.bind("", clear_placeholder) 441 | self.text_area.bind("", restore_placeholder) 442 | # self.text_area.bind("", lambda e: clear_placeholder(e) if self.text_area.get("1.0", "end-1c") == placeholder else None) 443 | 444 | def add_control_panel(self, container): 445 | """Create control panel""" 446 | control_panel = ttk.LabelFrame(container, text="Control Panel", padding=10) 447 | control_panel.grid(row=2, column=0, sticky="ew", padx=10, pady=10) 448 | control_panel.columnconfigure(0, weight=1) 449 | 450 | # Playback controls section 451 | playback_frame = ttk.Frame(control_panel) 452 | playback_frame.grid(row=0, column=0, sticky="ew", pady=5) 453 | playback_frame.columnconfigure(0, weight=1) 454 | 455 | # Buttons frame 456 | buttons_frame = ttk.Frame(playback_frame) 457 | buttons_frame.grid(row=0, column=0, pady=10) 458 | buttons_frame.columnconfigure((0, 1, 2, 3), weight=1) 459 | 460 | prev_btn = ttk.Button( 461 | buttons_frame, 462 | text="⏮", 463 | command=self.back_sentence, 464 | bootstyle="info-outline", 465 | width=8, 466 | ) 467 | prev_btn.grid(row=0, column=0, padx=5) 468 | ToolTip(prev_btn, text="Prev", bootstyle="info") 469 | 470 | play_btn = ttk.Button( 471 | buttons_frame, 472 | text="▶", 473 | command=self.play_speech, 474 | bootstyle="success-outline", 475 | width=8, 476 | ) 477 | play_btn.grid(row=0, column=1, padx=5) 478 | ToolTip(play_btn, text="Play/Resume", bootstyle="success") 479 | 480 | stop_btn = ttk.Button( 481 | buttons_frame, 482 | text="⏹", 483 | command=self.pause_speech, 484 | bootstyle="danger-outline", 485 | width=8, 486 | ) 487 | stop_btn.grid(row=0, column=2, padx=5) 488 | ToolTip(stop_btn, text="Pause", bootstyle="danger") 489 | 490 | next_btn = ttk.Button( 491 | buttons_frame, 492 | text="⏭", 493 | command=self.skip_sentence, 494 | bootstyle="info-outline", 495 | width=8, 496 | ) 497 | next_btn.grid(row=0, column=3, padx=5) 498 | ToolTip(next_btn, text="Next", bootstyle="info") 499 | 500 | # Settings section 501 | settings_frame = ttk.Frame(control_panel) 502 | settings_frame.grid(row=1, column=0, sticky="ew", pady=10) 503 | settings_frame.columnconfigure((0, 1, 2), weight=1) 504 | 505 | # Language dropdown 506 | lang_frame = ttk.Frame(settings_frame) 507 | lang_frame.grid(row=0, column=0, sticky="ew", padx=5) 508 | lang_frame.columnconfigure(1, weight=1) 509 | 510 | lang_label = ttk.Label( 511 | lang_frame, text="Language:", font=(self.default_font, 12) 512 | ) 513 | lang_label.grid(row=0, column=0, sticky="w", padx=(0, 5)) 514 | 515 | self.lang_var = tk.StringVar(value=self.current_language) 516 | lang_menu = ttk.Combobox( 517 | lang_frame, 518 | textvariable=self.lang_var, 519 | values=self.languages, 520 | state="readonly", 521 | width=12, 522 | style="primary", 523 | ) 524 | lang_menu.grid(row=0, column=1, sticky="ew") 525 | # lang_menu.bind("<>", self.change_lang) 526 | lang_menu.bind( 527 | "<>", lambda event: self.change_lang(event, voice_menu) 528 | ) 529 | 530 | # Voice dropdown 531 | voice_frame = ttk.Frame(settings_frame) 532 | voice_frame.grid(row=0, column=1, sticky="ew", padx=5) 533 | voice_frame.columnconfigure(1, weight=1) 534 | 535 | voice_label = ttk.Label( 536 | voice_frame, text="Voice:", font=(self.default_font, 12) 537 | ) 538 | voice_label.grid(row=0, column=0, sticky="w", padx=(0, 5)) 539 | 540 | self.voice_var = tk.StringVar(value=self.current_voice) 541 | voice_menu = ttk.Combobox( 542 | voice_frame, 543 | textvariable=self.voice_var, 544 | values=[ 545 | voice 546 | for voice in self.voices 547 | if voice.startswith(self.current_language_code) 548 | ], 549 | state="readonly", 550 | width=12, 551 | style="primary", 552 | ) 553 | voice_menu.grid(row=0, column=1, sticky="ew") 554 | voice_menu.bind("<>", self.change_voice) 555 | 556 | # Speed control 557 | speed_frame = ttk.Frame(settings_frame) 558 | speed_frame.grid(row=0, column=2, sticky="ew", padx=5) 559 | speed_frame.columnconfigure(1, weight=1) 560 | 561 | speed_label = ttk.Label( 562 | speed_frame, text="Speed:", font=(self.default_font, 12) 563 | ) 564 | speed_label.grid(row=0, column=0, sticky="w", padx=(0, 5)) 565 | 566 | speed_container = ttk.Frame(speed_frame) 567 | speed_container.grid(row=0, column=1, sticky="ew") 568 | speed_container.columnconfigure(0, weight=1) 569 | 570 | self.speed_scale = ttk.Scale( 571 | speed_container, 572 | from_=0.5, 573 | to=2.0, 574 | value=self.speed, 575 | bootstyle="info", 576 | command=self.change_speed, 577 | ) 578 | self.speed_scale.grid(row=0, column=0, sticky="ew", pady=(0, 5)) 579 | 580 | speed_labels = ttk.Frame(speed_container) 581 | speed_labels.grid(row=1, column=0, sticky="ew") 582 | speed_labels.columnconfigure(1, weight=1) 583 | 584 | min_label = ttk.Label( 585 | speed_labels, 586 | text=f"{MIN_SPEED:.1f}x", 587 | font=(self.default_font, 8), 588 | bootstyle="secondary", 589 | ) 590 | min_label.grid(row=0, column=0, sticky="w") 591 | 592 | self.speed_label = ttk.Label( 593 | speed_labels, 594 | text=f"{self.speed:.1f}x", 595 | font=(self.default_font, 9, "bold"), 596 | bootstyle="primary", 597 | ) 598 | self.speed_label.grid(row=0, column=1) 599 | 600 | max_label = ttk.Label( 601 | speed_labels, 602 | text=f"{MAX_SPEED:.1f}x", 603 | font=(self.default_font, 8), 604 | bootstyle="secondary", 605 | ) 606 | max_label.grid(row=0, column=2, sticky="e") 607 | 608 | def close(self): 609 | if self.current_thread is not None and self.current_thread.is_alive(): 610 | self.player.stop_playback() 611 | self.current_thread.join() 612 | 613 | 614 | def setup_signal_handler(root, app): 615 | """Set up a signal handler for SIGINT (Ctrl+C) to close the Tkinter window.""" 616 | 617 | def signal_handler(sig, frame): 618 | print("\nClosing...") 619 | app.close() 620 | root.after(0, root.destroy) 621 | 622 | signal.signal(signal.SIGINT, signal_handler) 623 | 624 | 625 | def run_gui( 626 | pipeline: KPipeline, 627 | language: str, 628 | voice: str, 629 | speed: float, 630 | device: Optional[str], 631 | theme: int, 632 | image_reader: easyocr.Reader, 633 | ) -> None: 634 | """Start gui mode""" 635 | try: 636 | root = ttk.Window(themename=get_gui_themes()[theme]) 637 | root.title(TITLE) 638 | root.geometry(WINDOW_SIZE) 639 | root.resizable(True, True) 640 | root.columnconfigure(0, weight=1) 641 | root.rowconfigure(0, weight=1) 642 | 643 | # Check if it is a Dark or Light theme 644 | dark_theme = 1 <= theme <= 4 645 | app = Gui( 646 | root, pipeline, language, voice, speed, device, image_reader, dark_theme 647 | ) 648 | 649 | def on_closing(): 650 | if messagebox.askokcancel("Quit", "Do you want to quit?"): 651 | print("Exiting...") 652 | app.close() 653 | root.destroy() 654 | 655 | root.protocol("WM_DELETE_WINDOW", on_closing) 656 | 657 | setup_signal_handler(root, app) 658 | 659 | root.mainloop() 660 | 661 | except Exception as e: 662 | print(f"An error occurred: {e}") 663 | messagebox.showerror("Error", f"Application failed to start: {e}") 664 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------