Update app.py
Browse files
app.py
CHANGED
|
@@ -2,23 +2,20 @@ import gradio as gr
|
|
| 2 |
import os
|
| 3 |
import tempfile
|
| 4 |
import soundfile as sf
|
| 5 |
-
from huggingface_hub import hf_hub_download
|
| 6 |
import numpy as np
|
| 7 |
import re
|
| 8 |
import time
|
| 9 |
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 10 |
import gc
|
| 11 |
-
import onnxruntime as ort
|
| 12 |
|
| 13 |
# Fix for OpenMP duplicate library error
|
| 14 |
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'
|
| 15 |
|
| 16 |
-
#
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
KittenTTS = None
|
| 22 |
|
| 23 |
class KittenTTSGradio:
|
| 24 |
def __init__(self):
|
|
@@ -29,109 +26,37 @@ class KittenTTSGradio:
|
|
| 29 |
'expr-voice-4-m', 'expr-voice-4-f', 'expr-voice-5-m', 'expr-voice-5-f'
|
| 30 |
]
|
| 31 |
self.max_workers = max(1, os.cpu_count() - 1) if os.cpu_count() else 2
|
| 32 |
-
self.
|
|
|
|
| 33 |
|
| 34 |
-
def
|
| 35 |
-
"""
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
# Download config file
|
| 39 |
-
config_path = hf_hub_download(
|
| 40 |
-
repo_id=repo_id,
|
| 41 |
-
filename="config.json",
|
| 42 |
-
cache_dir="./models"
|
| 43 |
-
)
|
| 44 |
-
|
| 45 |
-
# Read config to get file names
|
| 46 |
-
import json
|
| 47 |
-
with open(config_path, 'r') as f:
|
| 48 |
-
config = json.load(f)
|
| 49 |
-
|
| 50 |
-
# Download model file
|
| 51 |
-
model_filename = config.get("model_file", "kitten_tts_mini_v0_1.onnx")
|
| 52 |
-
model_path = hf_hub_download(
|
| 53 |
-
repo_id=repo_id,
|
| 54 |
-
filename=model_filename,
|
| 55 |
-
cache_dir="./models"
|
| 56 |
-
)
|
| 57 |
-
|
| 58 |
-
# Download voices file
|
| 59 |
-
voices_filename = config.get("voices", "voices.npz")
|
| 60 |
-
voices_path = hf_hub_download(
|
| 61 |
-
repo_id=repo_id,
|
| 62 |
-
filename=voices_filename,
|
| 63 |
-
cache_dir="./models"
|
| 64 |
-
)
|
| 65 |
-
|
| 66 |
-
print(f"Model files downloaded: {model_path}, {voices_path}")
|
| 67 |
-
return model_path, voices_path
|
| 68 |
|
| 69 |
def load_model(self):
|
| 70 |
-
"""Load the TTS model
|
|
|
|
|
|
|
|
|
|
| 71 |
try:
|
| 72 |
print("Loading KittenTTS model...")
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
try:
|
| 78 |
-
self.model = KittenTTS("KittenML/kitten-tts-mini-0.1")
|
| 79 |
-
print("Model loaded successfully using KittenTTS library")
|
| 80 |
-
return
|
| 81 |
-
except Exception as e:
|
| 82 |
-
print(f"Standard loading failed: {e}")
|
| 83 |
-
|
| 84 |
-
# Method 2: Manual download and loading
|
| 85 |
-
try:
|
| 86 |
-
model_path, voices_path = self.download_model_files("KittenML/kitten-tts-mini-0.1")
|
| 87 |
-
|
| 88 |
-
# If KittenTTS is available, try to use it with local files
|
| 89 |
-
if KittenTTS:
|
| 90 |
-
# This might not work depending on the KittenTTS implementation
|
| 91 |
-
# but worth trying
|
| 92 |
-
self.model = KittenTTS(model_path)
|
| 93 |
-
else:
|
| 94 |
-
# Fallback: Create a simple wrapper
|
| 95 |
-
self.model = self.create_simple_model(model_path, voices_path)
|
| 96 |
-
|
| 97 |
-
print("Model loaded successfully using downloaded files")
|
| 98 |
-
|
| 99 |
-
except Exception as e:
|
| 100 |
-
print(f"Manual loading failed: {e}")
|
| 101 |
-
|
| 102 |
-
# Method 3: Try the nano model as fallback
|
| 103 |
-
if KittenTTS:
|
| 104 |
-
try:
|
| 105 |
-
self.model = KittenTTS("KittenML/kitten-tts-nano-0.2")
|
| 106 |
-
print("Loaded nano model as fallback")
|
| 107 |
-
return
|
| 108 |
-
except Exception as e:
|
| 109 |
-
print(f"Nano model loading failed: {e}")
|
| 110 |
-
|
| 111 |
-
raise Exception("All model loading methods failed")
|
| 112 |
-
|
| 113 |
except Exception as e:
|
| 114 |
-
print(f"
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
# This is a placeholder - actual implementation would need
|
| 126 |
-
# to match the ONNX model's input/output format
|
| 127 |
-
# For now, generate a simple sine wave as placeholder
|
| 128 |
-
duration = len(text.split()) * 0.5 # Rough estimate
|
| 129 |
-
sample_rate = 24000
|
| 130 |
-
t = np.linspace(0, duration, int(sample_rate * duration))
|
| 131 |
-
audio = np.sin(2 * np.pi * 440 * t) * 0.3 # 440 Hz sine wave
|
| 132 |
-
return audio
|
| 133 |
-
|
| 134 |
-
return SimpleKittenTTS(model_path, voices_path)
|
| 135 |
|
| 136 |
def split_into_sentences(self, text):
|
| 137 |
"""Split text into sentences"""
|
|
@@ -174,6 +99,9 @@ class KittenTTSGradio:
|
|
| 174 |
|
| 175 |
def safe_generate_audio(self, text, voice, speed):
|
| 176 |
"""Generate audio with fallback strategies"""
|
|
|
|
|
|
|
|
|
|
| 177 |
if not self.model:
|
| 178 |
raise Exception("Model not loaded")
|
| 179 |
|
|
@@ -212,8 +140,11 @@ class KittenTTSGradio:
|
|
| 212 |
|
| 213 |
def convert_text_to_speech(self, text, voice, speed, use_multithreading, progress=gr.Progress()):
|
| 214 |
"""Main conversion function for Gradio"""
|
| 215 |
-
|
| 216 |
-
|
|
|
|
|
|
|
|
|
|
| 217 |
|
| 218 |
if not text or not text.strip():
|
| 219 |
raise gr.Error("Please enter some text to convert.")
|
|
@@ -300,9 +231,10 @@ class KittenTTSGradio:
|
|
| 300 |
except Exception as e:
|
| 301 |
raise gr.Error(f"Conversion failed: {str(e)}")
|
| 302 |
|
| 303 |
-
# Initialize the app
|
| 304 |
-
print("Initializing KittenTTS...")
|
| 305 |
app = KittenTTSGradio()
|
|
|
|
| 306 |
|
| 307 |
# Create Gradio interface
|
| 308 |
def create_interface():
|
|
@@ -310,10 +242,15 @@ def create_interface():
|
|
| 310 |
gr.Markdown("""
|
| 311 |
# ποΈ KittenTTS Text-to-Speech Converter
|
| 312 |
|
| 313 |
-
Convert text to natural-sounding speech using KittenTTS
|
| 314 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 315 |
|
| 316 |
-
**Note:**
|
| 317 |
""")
|
| 318 |
|
| 319 |
with gr.Row():
|
|
@@ -322,7 +259,8 @@ def create_interface():
|
|
| 322 |
label="Text to Convert",
|
| 323 |
placeholder="Enter your text here or upload a file...",
|
| 324 |
lines=10,
|
| 325 |
-
max_lines=20
|
|
|
|
| 326 |
)
|
| 327 |
|
| 328 |
with gr.Row():
|
|
@@ -331,6 +269,8 @@ def create_interface():
|
|
| 331 |
file_types=[".txt"],
|
| 332 |
type="filepath"
|
| 333 |
)
|
|
|
|
|
|
|
| 334 |
|
| 335 |
# File upload handler
|
| 336 |
def load_file(file_path):
|
|
@@ -348,11 +288,20 @@ def create_interface():
|
|
| 348 |
return f"Error loading file: {str(e)}"
|
| 349 |
return ""
|
| 350 |
|
|
|
|
|
|
|
|
|
|
| 351 |
file_upload.change(
|
| 352 |
fn=load_file,
|
| 353 |
inputs=[file_upload],
|
| 354 |
outputs=[text_input]
|
| 355 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 356 |
|
| 357 |
with gr.Column(scale=1):
|
| 358 |
voice_dropdown = gr.Dropdown(
|
|
@@ -384,17 +333,16 @@ def create_interface():
|
|
| 384 |
)
|
| 385 |
|
| 386 |
with gr.Row():
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
)
|
| 398 |
|
| 399 |
# Examples
|
| 400 |
gr.Examples(
|
|
@@ -416,19 +364,34 @@ def create_interface():
|
|
| 416 |
|
| 417 |
gr.Markdown("""
|
| 418 |
---
|
| 419 |
-
### π
|
| 420 |
-
-
|
| 421 |
-
-
|
| 422 |
-
-
|
| 423 |
-
-
|
| 424 |
-
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 425 |
""")
|
| 426 |
|
| 427 |
return demo
|
| 428 |
|
| 429 |
# Create and launch the interface
|
|
|
|
|
|
|
|
|
|
|
|
|
| 430 |
if __name__ == "__main__":
|
| 431 |
-
demo = create_interface()
|
| 432 |
demo.queue(max_size=5)
|
| 433 |
demo.launch(
|
| 434 |
share=False,
|
|
|
|
| 2 |
import os
|
| 3 |
import tempfile
|
| 4 |
import soundfile as sf
|
|
|
|
| 5 |
import numpy as np
|
| 6 |
import re
|
| 7 |
import time
|
| 8 |
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 9 |
import gc
|
|
|
|
| 10 |
|
| 11 |
# Fix for OpenMP duplicate library error
|
| 12 |
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'
|
| 13 |
|
| 14 |
+
# Force CPU usage for ONNX Runtime to avoid GPU issues
|
| 15 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
|
| 16 |
+
|
| 17 |
+
# Import KittenTTS
|
| 18 |
+
from kittentts import KittenTTS
|
|
|
|
| 19 |
|
| 20 |
class KittenTTSGradio:
|
| 21 |
def __init__(self):
|
|
|
|
| 26 |
'expr-voice-4-m', 'expr-voice-4-f', 'expr-voice-5-m', 'expr-voice-5-f'
|
| 27 |
]
|
| 28 |
self.max_workers = max(1, os.cpu_count() - 1) if os.cpu_count() else 2
|
| 29 |
+
self.model_loaded = False
|
| 30 |
+
# Don't load model in __init__, do it on first use
|
| 31 |
|
| 32 |
+
def ensure_model_loaded(self):
|
| 33 |
+
"""Ensure model is loaded before use"""
|
| 34 |
+
if not self.model_loaded:
|
| 35 |
+
self.load_model()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
def load_model(self):
|
| 38 |
+
"""Load the TTS model"""
|
| 39 |
+
if self.model_loaded:
|
| 40 |
+
return
|
| 41 |
+
|
| 42 |
try:
|
| 43 |
print("Loading KittenTTS model...")
|
| 44 |
+
# Try the mini model first
|
| 45 |
+
self.model = KittenTTS("KittenML/kitten-tts-mini-0.1")
|
| 46 |
+
self.model_loaded = True
|
| 47 |
+
print("Model loaded successfully!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
except Exception as e:
|
| 49 |
+
print(f"Failed to load mini model: {e}")
|
| 50 |
+
# Try the nano model as fallback
|
| 51 |
+
try:
|
| 52 |
+
print("Trying nano model as fallback...")
|
| 53 |
+
self.model = KittenTTS("KittenML/kitten-tts-nano-0.2")
|
| 54 |
+
self.model_loaded = True
|
| 55 |
+
print("Nano model loaded successfully!")
|
| 56 |
+
except Exception as e2:
|
| 57 |
+
print(f"Failed to load nano model: {e2}")
|
| 58 |
+
self.model_loaded = False
|
| 59 |
+
raise Exception("Failed to load any KittenTTS model")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
def split_into_sentences(self, text):
|
| 62 |
"""Split text into sentences"""
|
|
|
|
| 99 |
|
| 100 |
def safe_generate_audio(self, text, voice, speed):
|
| 101 |
"""Generate audio with fallback strategies"""
|
| 102 |
+
# Ensure model is loaded
|
| 103 |
+
self.ensure_model_loaded()
|
| 104 |
+
|
| 105 |
if not self.model:
|
| 106 |
raise Exception("Model not loaded")
|
| 107 |
|
|
|
|
| 140 |
|
| 141 |
def convert_text_to_speech(self, text, voice, speed, use_multithreading, progress=gr.Progress()):
|
| 142 |
"""Main conversion function for Gradio"""
|
| 143 |
+
# Ensure model is loaded
|
| 144 |
+
try:
|
| 145 |
+
self.ensure_model_loaded()
|
| 146 |
+
except Exception as e:
|
| 147 |
+
raise gr.Error(f"Failed to load model: {str(e)}")
|
| 148 |
|
| 149 |
if not text or not text.strip():
|
| 150 |
raise gr.Error("Please enter some text to convert.")
|
|
|
|
| 231 |
except Exception as e:
|
| 232 |
raise gr.Error(f"Conversion failed: {str(e)}")
|
| 233 |
|
| 234 |
+
# Initialize the app - don't load model yet
|
| 235 |
+
print("Initializing KittenTTS app...")
|
| 236 |
app = KittenTTSGradio()
|
| 237 |
+
print("App initialized, model will load on first use")
|
| 238 |
|
| 239 |
# Create Gradio interface
|
| 240 |
def create_interface():
|
|
|
|
| 242 |
gr.Markdown("""
|
| 243 |
# ποΈ KittenTTS Text-to-Speech Converter
|
| 244 |
|
| 245 |
+
Convert text to natural-sounding speech using KittenTTS - a lightweight TTS model that runs on CPU.
|
| 246 |
+
|
| 247 |
+
**Features:**
|
| 248 |
+
- 8 different voice options (male and female)
|
| 249 |
+
- Adjustable speech speed
|
| 250 |
+
- Sentence-by-sentence processing for better quality
|
| 251 |
+
- Multithreading support for faster processing
|
| 252 |
|
| 253 |
+
**Note:** The model will load on first use (~170MB download).
|
| 254 |
""")
|
| 255 |
|
| 256 |
with gr.Row():
|
|
|
|
| 259 |
label="Text to Convert",
|
| 260 |
placeholder="Enter your text here or upload a file...",
|
| 261 |
lines=10,
|
| 262 |
+
max_lines=20,
|
| 263 |
+
value="" # Start with empty text
|
| 264 |
)
|
| 265 |
|
| 266 |
with gr.Row():
|
|
|
|
| 269 |
file_types=[".txt"],
|
| 270 |
type="filepath"
|
| 271 |
)
|
| 272 |
+
|
| 273 |
+
clear_btn = gr.Button("Clear Text", size="sm")
|
| 274 |
|
| 275 |
# File upload handler
|
| 276 |
def load_file(file_path):
|
|
|
|
| 288 |
return f"Error loading file: {str(e)}"
|
| 289 |
return ""
|
| 290 |
|
| 291 |
+
def clear_text():
|
| 292 |
+
return ""
|
| 293 |
+
|
| 294 |
file_upload.change(
|
| 295 |
fn=load_file,
|
| 296 |
inputs=[file_upload],
|
| 297 |
outputs=[text_input]
|
| 298 |
)
|
| 299 |
+
|
| 300 |
+
clear_btn.click(
|
| 301 |
+
fn=clear_text,
|
| 302 |
+
inputs=[],
|
| 303 |
+
outputs=[text_input]
|
| 304 |
+
)
|
| 305 |
|
| 306 |
with gr.Column(scale=1):
|
| 307 |
voice_dropdown = gr.Dropdown(
|
|
|
|
| 333 |
)
|
| 334 |
|
| 335 |
with gr.Row():
|
| 336 |
+
with gr.Column():
|
| 337 |
+
audio_output = gr.Audio(
|
| 338 |
+
label="Generated Audio",
|
| 339 |
+
type="filepath",
|
| 340 |
+
autoplay=False
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
status_output = gr.Markdown(
|
| 344 |
+
value="Ready to convert text to speech."
|
| 345 |
+
)
|
|
|
|
| 346 |
|
| 347 |
# Examples
|
| 348 |
gr.Examples(
|
|
|
|
| 364 |
|
| 365 |
gr.Markdown("""
|
| 366 |
---
|
| 367 |
+
### π Tips:
|
| 368 |
+
- **Chunk Size**: Set to 1 for maximum quality (processes each sentence separately). Increase for faster processing of long texts.
|
| 369 |
+
- **Trade-offs**: Larger chunks = faster processing but may have less natural pauses between sentences
|
| 370 |
+
- Processing time depends on text length, chunk size, and multithreading setting
|
| 371 |
+
- Each voice has different characteristics - try them out!
|
| 372 |
+
- The model runs entirely on CPU - no GPU required
|
| 373 |
+
- First conversion will take longer as the model loads
|
| 374 |
+
|
| 375 |
+
### π Available Voices:
|
| 376 |
+
- **expr-voice-2-m/f**: Expressive male/female voices
|
| 377 |
+
- **expr-voice-3-m/f**: Natural male/female voices
|
| 378 |
+
- **expr-voice-4-m/f**: Clear male/female voices
|
| 379 |
+
- **expr-voice-5-m/f**: Warm male/female voices
|
| 380 |
+
|
| 381 |
+
### βοΈ Chunk Size Guide:
|
| 382 |
+
- **1 sentence**: Best quality, natural pauses (recommended for short texts)
|
| 383 |
+
- **2-3 sentences**: Good balance of speed and quality
|
| 384 |
+
- **5+ sentences**: Faster processing for long texts (may sound more continuous)
|
| 385 |
""")
|
| 386 |
|
| 387 |
return demo
|
| 388 |
|
| 389 |
# Create and launch the interface
|
| 390 |
+
print("Creating Gradio interface...")
|
| 391 |
+
demo = create_interface()
|
| 392 |
+
print("Launching app...")
|
| 393 |
+
|
| 394 |
if __name__ == "__main__":
|
|
|
|
| 395 |
demo.queue(max_size=5)
|
| 396 |
demo.launch(
|
| 397 |
share=False,
|