Hassan-16 commited on
Commit
fa5c1e1
ยท
verified ยท
1 Parent(s): 0774a70

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +120 -31
app.py CHANGED
@@ -1,19 +1,23 @@
1
  from kokoro import KModel, KPipeline
2
  import gradio as gr
3
  import os
4
- import random
5
  import torch
6
  import logging
7
-
8
- # Configuration
9
- VOICE_DIR = "model/voices"
10
- OUTPUT_DIR = "output_audio"
11
- TEXT = "Hello, this is a test of the Kokoro TTS system."
12
 
13
  # Configure logging
14
  logging.basicConfig(level=logging.INFO)
15
  logger = logging.getLogger(__name__)
16
 
 
 
 
 
 
 
 
 
 
17
  # Device setup
18
  CUDA_AVAILABLE = torch.cuda.is_available()
19
  device = "cuda" if CUDA_AVAILABLE else "cpu"
@@ -35,10 +39,9 @@ try:
35
  except AttributeError as e:
36
  logger.warning(f"Could not set custom pronunciations: {e}")
37
 
38
- # Core functions for voice generation
39
  def forward_gpu(text, voice_path, speed):
40
  pipeline = pipelines[voice_path[0]]
41
- pipeline.model = models[True] # Use GPU model
42
  generator = pipeline(text, voice=voice_path, speed=speed)
43
  for _, _, audio in generator:
44
  return audio
@@ -55,52 +58,138 @@ def generate_first(text, voice="af_bella.pt", speed=1, use_gpu=CUDA_AVAILABLE):
55
  if use_gpu:
56
  audio = forward_gpu(text, voice_path, speed)
57
  else:
58
- pipeline.model = models[False]
59
  generator = pipeline(text, voice=voice_path, speed=speed)
60
  for _, ps, audio in generator:
61
  return (24000, audio.numpy()), ps
62
  except gr.exceptions.Error as e:
63
  if use_gpu:
64
  gr.Warning(str(e))
65
- pipeline.model = models[False]
 
66
  generator = pipeline(text, voice=voice_path, speed=speed)
67
- for _, ps, audio in generator:
68
- return (24000, audio.numpy()), ps
69
-
70
  else:
71
  raise gr.Error(e)
72
  return None, ""
73
 
74
- # Load available voices
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  def load_voice_choices():
76
- if not os.path.exists(VOICE_DIR):
77
- os.makedirs(VOICE_DIR)
78
  voice_files = [f for f in os.listdir(VOICE_DIR) if f.endswith('.pt')]
79
- choices = {voice_file: voice_file for voice_file in voice_files}
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  return choices
81
 
82
  CHOICES = load_voice_choices()
83
 
 
 
 
 
 
 
 
 
 
84
  if not CHOICES:
85
  logger.warning("No voice files found in VOICE_DIR. Adding a placeholder.")
86
- CHOICES = {"Bella": "af_bella.pt"}
87
 
88
  TOKEN_NOTE = '''
89
  ๐Ÿ’ก Customize pronunciation with Markdown link syntax and /slashes/ like [Kokoro](/kหˆOkษ™ษนO/)
90
- โฌ†๏ธ Adjust stress levels using special notations.
 
 
 
 
 
91
  '''
92
 
93
- # Gradio Interface
94
- with gr.Blocks() as app:
 
 
 
 
 
 
 
 
 
 
95
  with gr.Row():
96
- text = gr.Textbox(label="Input Text", value=TEXT)
97
- voice = gr.Dropdown(list(CHOICES.values()), label="Voice", value=list(CHOICES.values())[0])
98
- speed = gr.Slider(0.5, 2, value=1, label="Speed")
99
- output_audio = gr.Audio(label="Output Audio", interactive=False)
100
- generate_btn = gr.Button("Generate")
101
-
102
- generate_btn.click(fn=generate_first, inputs=[text, voice, speed], outputs=[output_audio])
103
 
104
- # Run the app
105
- if __name__ == "__main__":
106
- app.launch(server_name="0.0.0.0", server_port=7860)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from kokoro import KModel, KPipeline
2
  import gradio as gr
3
  import os
 
4
  import torch
5
  import logging
6
+ import soundfile as sf
 
 
 
 
7
 
8
  # Configure logging
9
  logging.basicConfig(level=logging.INFO)
10
  logger = logging.getLogger(__name__)
11
 
12
+ # Configuration
13
+ VOICE_DIR = os.path.join(os.path.dirname(__file__), "voices")
14
+ OUTPUT_DIR = os.path.join(os.path.dirname(__file__), "output_audio")
15
+ TEXT = "Hello, this is a test of the Kokoro TTS system."
16
+
17
+ # Ensure directories exist
18
+ os.makedirs(VOICE_DIR, exist_ok=True)
19
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
20
+
21
  # Device setup
22
  CUDA_AVAILABLE = torch.cuda.is_available()
23
  device = "cuda" if CUDA_AVAILABLE else "cpu"
 
39
  except AttributeError as e:
40
  logger.warning(f"Could not set custom pronunciations: {e}")
41
 
 
42
  def forward_gpu(text, voice_path, speed):
43
  pipeline = pipelines[voice_path[0]]
44
+ pipeline.model = models[True] # Switch to GPU model
45
  generator = pipeline(text, voice=voice_path, speed=speed)
46
  for _, _, audio in generator:
47
  return audio
 
58
  if use_gpu:
59
  audio = forward_gpu(text, voice_path, speed)
60
  else:
61
+ pipeline.model = models[False] # Ensure CPU model is used
62
  generator = pipeline(text, voice=voice_path, speed=speed)
63
  for _, ps, audio in generator:
64
  return (24000, audio.numpy()), ps
65
  except gr.exceptions.Error as e:
66
  if use_gpu:
67
  gr.Warning(str(e))
68
+ gr.Info("Retrying with CPU. To avoid this error, change Hardware to CPU.")
69
+ pipeline.model = models[False] # Switch to CPU model
70
  generator = pipeline(text, voice=voice_path, speed=speed)
71
+ for _, ps, audio in generator:
72
+ return (24000, audio.numpy()), ps
 
73
  else:
74
  raise gr.Error(e)
75
  return None, ""
76
 
77
+ def predict(text, voice="af_bella.pt", speed=1):
78
+ return generate_first(text, voice, speed, use_gpu=False)[0]
79
+
80
+ def tokenize_first(text, voice="af_bella.pt"):
81
+ voice_path = os.path.join(VOICE_DIR, voice)
82
+ if not os.path.exists(voice_path):
83
+ raise FileNotFoundError(f"Voice file not found: {voice_path}")
84
+
85
+ pipeline = pipelines[voice[0]]
86
+ generator = pipeline(text, voice=voice_path)
87
+ for _, ps, _ in generator:
88
+ return ps
89
+ return ""
90
+
91
+ def generate_all(text, voice="af_bella.pt", speed=1, use_gpu=CUDA_AVAILABLE):
92
+ voice_path = os.path.join(VOICE_DIR, voice)
93
+ if not os.path.exists(voice_path):
94
+ raise FileNotFoundError(f"Voice file not found: {voice_path}")
95
+
96
+ pipeline = pipelines[voice[0]]
97
+ use_gpu = use_gpu and CUDA_AVAILABLE
98
+ first = True
99
+ if use_gpu:
100
+ pipeline.model = models[True] # Switch to GPU model
101
+ else:
102
+ pipeline.model = models[False] # Switch to CPU model
103
+ generator = pipeline(text, voice=voice_path, speed=speed)
104
+ for _, _, audio in generator:
105
+ yield 24000, audio.numpy()
106
+ if first:
107
+ first = False
108
+ yield 24000, torch.zeros(1).numpy()
109
+
110
+ # Dynamically load all .pt voice files from VOICE_DIR
111
  def load_voice_choices():
 
 
112
  voice_files = [f for f in os.listdir(VOICE_DIR) if f.endswith('.pt')]
113
+ choices = {}
114
+ for voice_file in voice_files:
115
+ prefix = voice_file[:2]
116
+ if prefix == 'af':
117
+ label = f"๐Ÿ‡บ๐Ÿ‡ธ ๐Ÿšบ {voice_file[3:-3].capitalize()}"
118
+ elif prefix == 'am':
119
+ label = f"๐Ÿ‡บ๐Ÿ‡ธ ๐Ÿšน {voice_file[3:-3].capitalize()}"
120
+ elif prefix == 'bf':
121
+ label = f"๐Ÿ‡ฌ๐Ÿ‡ง ๐Ÿšบ {voice_file[3:-3].capitalize()}"
122
+ elif prefix == 'bm':
123
+ label = f"๐Ÿ‡ฌ๐Ÿ‡ง ๐Ÿšน {voice_file[3:-3].capitalize()}"
124
+ else:
125
+ label = f"Unknown {voice_file[:-3]}"
126
+ choices[label] = voice_file
127
  return choices
128
 
129
  CHOICES = load_voice_choices()
130
 
131
+ # Log available voices
132
+ for label, voice_path in CHOICES.items():
133
+ full_path = os.path.join(VOICE_DIR, voice_path)
134
+ if not os.path.exists(full_path):
135
+ logger.warning(f"Voice file not found: {full_path}")
136
+ else:
137
+ logger.info(f"Loaded voice: {label} ({voice_path})")
138
+
139
+ # If no voices are found, add a default fallback
140
  if not CHOICES:
141
  logger.warning("No voice files found in VOICE_DIR. Adding a placeholder.")
142
+ CHOICES = {"๐Ÿ‡บ๐Ÿ‡ธ ๐Ÿšบ Bella ๐Ÿ”ฅ": "af_bella.pt"}
143
 
144
  TOKEN_NOTE = '''
145
  ๐Ÿ’ก Customize pronunciation with Markdown link syntax and /slashes/ like [Kokoro](/kหˆOkษ™ษนO/)
146
+
147
+ ๐Ÿ’ฌ To adjust intonation, try punctuation ;:,.!?โ€”โ€ฆ"()โ€œโ€ or stress หˆ and หŒ
148
+
149
+ โฌ‡๏ธ Lower stress [1 level](-1) or [2 levels](-2)
150
+
151
+ โฌ†๏ธ Raise stress 1 level [or](+2) 2 levels (only works on less stressed, usually short words)
152
  '''
153
 
154
+ with gr.Blocks() as generate_tab:
155
+ out_audio = gr.Audio(label="Output Audio", interactive=False, streaming=False, autoplay=True)
156
+ generate_btn = gr.Button("Generate", variant="primary")
157
+ with gr.Accordion("Output Tokens", open=True):
158
+ out_ps = gr ััƒั‚ัŒTextbox(interactive=False, show_label=False,
159
+ info="Tokens used to generate the audio, up to 510 context length.")
160
+ tokenize_btn = gr.Button("Tokenize", variant="secondary")
161
+ gr.Markdown(TOKEN_NOTE)
162
+ predict_btn = gr.Button("Predict", variant="secondary", visible=False)
163
+
164
+ with gr.Blocks() as stream_tab:
165
+ out_stream = gr.Audio(label="Output Audio Stream", interactive=False, streaming=True, autoplay=True)
166
  with gr.Row():
167
+ stream_btn = gr.Button("Stream", variant="primary")
168
+ stop_btn = gr.Button("Stop", variant="stop")
169
+ with gr.Accordion("Note", open=True):
170
+ gr.Markdown("โš ๏ธ There is an unknown Gradio bug that might yield no audio the first time you click Stream.")
171
+ gr.DuplicateButton()
 
 
172
 
173
+ with gr.Blocks() as app:
174
+ with gr.Row():
175
+ with gr.Column():
176
+ text = gr.Textbox(label="Input Text", info="Arbitrarily many characters supported")
177
+ with gr.Row():
178
+ voice = gr.Dropdown(list(CHOICES.items()), value="af_bella.pt" if "af_bella.pt" in CHOICES.values() else list(CHOICES.values())[0], label="Voice",
179
+ info="Quality and availability vary by language")
180
+ use_gpu = gr.Dropdown(
181
+ [("GPU ๐Ÿš€", True), ("CPU ๐ŸŒ", False)],
182
+ value=CUDA_AVAILABLE,
183
+ label="Hardware",
184
+ info="GPU is usually faster, but may require CUDA support",
185
+ interactive=CUDA_AVAILABLE
186
+ )
187
+ speed = gr.Slider(minimum=0.5, maximum=2, value=1, step=0.1, label="Speed")
188
+ with gr.Column():
189
+ gr.TabbedInterface([generate_tab, stream_tab], ["Generate", "Stream"])
190
+ generate_btn.click(fn=generate_first, inputs=[text, voice, speed, use_gpu],
191
+ outputs=[out_audio, out_ps])
192
+ tokenize_btn.click(fn=tokenize_first, inputs=[text, voice], outputs=[out_ps])
193
+ stream_event = stream_btn.click(fn=generate_all, inputs=[text, voice, speed, use_gpu], outputs=[out_stream])
194
+ stop_btn.click(fn=None, cancels=[stream_event])
195
+ predict_btn.click(fn=predict, inputs=[text, voice, speed], outputs=[out_audio])