deepak191z commited on
Commit
0c6ce6a
·
verified ·
1 Parent(s): 725ed7c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +255 -144
app.py CHANGED
@@ -1,28 +1,109 @@
1
- import spaces
2
- from kokoro import KModel, KPipeline
3
- import gradio as gr
4
- import os
5
- import random
6
  import torch
 
 
 
 
 
 
7
 
 
 
 
8
  IS_DUPLICATE = not os.getenv('SPACE_ID', '').startswith('hexgrad/')
9
  CHAR_LIMIT = None if IS_DUPLICATE else 5000
10
-
11
  CUDA_AVAILABLE = torch.cuda.is_available()
 
 
12
  models = {gpu: KModel().to('cuda' if gpu else 'cpu').eval() for gpu in [False] + ([True] if CUDA_AVAILABLE else [])}
13
  pipelines = {lang_code: KPipeline(lang_code=lang_code, model=False) for lang_code in 'ab'}
14
  pipelines['a'].g2p.lexicon.golds['kokoro'] = 'kˈOkəɹO'
15
  pipelines['b'].g2p.lexicon.golds['kokoro'] = 'kˈQkəɹQ'
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  @spaces.GPU(duration=30)
18
  def forward_gpu(ps, ref_s, speed):
19
  return models[True](ps, ref_s, speed)
20
 
21
- def generate_first(text, voice='af_heart', speed=1, use_gpu=CUDA_AVAILABLE):
 
 
22
  text = text if CHAR_LIMIT is None else text.strip()[:CHAR_LIMIT]
23
  pipeline = pipelines[voice[0]]
24
  pack = pipeline.load_voice(voice)
25
  use_gpu = use_gpu and CUDA_AVAILABLE
 
26
  for _, ps, _ in pipeline(text, voice, speed):
27
  ref_s = pack[len(ps)-1]
28
  try:
@@ -30,32 +111,31 @@ def generate_first(text, voice='af_heart', speed=1, use_gpu=CUDA_AVAILABLE):
30
  audio = forward_gpu(ps, ref_s, speed)
31
  else:
32
  audio = models[False](ps, ref_s, speed)
33
- except gr.exceptions.Error as e:
34
  if use_gpu:
35
- gr.Warning(str(e))
36
- gr.Info('Retrying with CPU. To avoid this error, change Hardware to CPU.')
37
  audio = models[False](ps, ref_s, speed)
38
  else:
39
- raise gr.Error(e)
 
40
  return (24000, audio.numpy()), ps
 
41
  return None, ''
42
 
43
- # Arena API
44
- def predict(text, voice='af_heart', speed=1):
45
- return generate_first(text, voice, speed, use_gpu=False)[0]
46
-
47
- def tokenize_first(text, voice='af_heart'):
48
  pipeline = pipelines[voice[0]]
49
  for _, ps, _ in pipeline(text, voice):
50
  return ps
51
  return ''
52
 
53
- def generate_all(text, voice='af_heart', speed=1, use_gpu=CUDA_AVAILABLE):
 
54
  text = text if CHAR_LIMIT is None else text.strip()[:CHAR_LIMIT]
55
  pipeline = pipelines[voice[0]]
56
  pack = pipeline.load_voice(voice)
57
  use_gpu = use_gpu and CUDA_AVAILABLE
58
- first = True
59
  for _, ps, _ in pipeline(text, voice, speed):
60
  ref_s = pack[len(ps)-1]
61
  try:
@@ -63,138 +143,169 @@ def generate_all(text, voice='af_heart', speed=1, use_gpu=CUDA_AVAILABLE):
63
  audio = forward_gpu(ps, ref_s, speed)
64
  else:
65
  audio = models[False](ps, ref_s, speed)
66
- except gr.exceptions.Error as e:
67
  if use_gpu:
68
- gr.Warning(str(e))
69
- gr.Info('Switching to CPU')
70
  audio = models[False](ps, ref_s, speed)
71
  else:
72
- raise gr.Error(e)
73
- yield 24000, audio.numpy()
74
- if first:
75
- first = False
76
- yield 24000, torch.zeros(1).numpy()
77
 
78
- with open('en.txt', 'r') as r:
79
- random_quotes = [line.strip() for line in r]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
- def get_random_quote():
82
- return random.choice(random_quotes)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
- def get_gatsby():
85
- with open('gatsby5k.md', 'r') as r:
86
- return r.read().strip()
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
- def get_frankenstein():
89
- with open('frankenstein5k.md', 'r') as r:
90
- return r.read().strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
- CHOICES = {
93
- '🇺🇸 🚺 Heart ❤️': 'af_heart',
94
- '🇺🇸 🚺 Bella 🔥': 'af_bella',
95
- '🇺🇸 🚺 Nicole 🎧': 'af_nicole',
96
- '🇺🇸 🚺 Aoede': 'af_aoede',
97
- '🇺🇸 🚺 Kore': 'af_kore',
98
- '🇺🇸 🚺 Sarah': 'af_sarah',
99
- '🇺🇸 🚺 Nova': 'af_nova',
100
- '🇺🇸 🚺 Sky': 'af_sky',
101
- '🇺🇸 🚺 Alloy': 'af_alloy',
102
- '🇺🇸 🚺 Jessica': 'af_jessica',
103
- '🇺🇸 🚺 River': 'af_river',
104
- '🇺🇸 🚹 Michael': 'am_michael',
105
- '🇺🇸 🚹 Fenrir': 'am_fenrir',
106
- '🇺🇸 🚹 Puck': 'am_puck',
107
- '🇺🇸 🚹 Echo': 'am_echo',
108
- '🇺🇸 🚹 Eric': 'am_eric',
109
- '🇺🇸 🚹 Liam': 'am_liam',
110
- '🇺🇸 🚹 Onyx': 'am_onyx',
111
- '🇺🇸 🚹 Santa': 'am_santa',
112
- '🇺🇸 🚹 Adam': 'am_adam',
113
- '���🇧 🚺 Emma': 'bf_emma',
114
- '🇬🇧 🚺 Isabella': 'bf_isabella',
115
- '🇬🇧 🚺 Alice': 'bf_alice',
116
- '🇬🇧 🚺 Lily': 'bf_lily',
117
- '🇬🇧 🚹 George': 'bm_george',
118
- '🇬🇧 🚹 Fable': 'bm_fable',
119
- '🇬🇧 🚹 Lewis': 'bm_lewis',
120
- '🇬🇧 🚹 Daniel': 'bm_daniel',
121
- }
122
- for v in CHOICES.values():
123
- pipelines[v[0]].load_voice(v)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
 
125
- TOKEN_NOTE = '''
126
- 💡 Customize pronunciation with Markdown link syntax and /slashes/ like `[Kokoro](/kˈOkəɹO/)`
127
-
128
- 💬 To adjust intonation, try punctuation `;:,.!?—…"()“”` or stress `ˈ` and `ˌ`
129
-
130
- ⬇️ Lower stress `[1 level](-1)` or `[2 levels](-2)`
131
-
132
- ⬆️ Raise stress 1 level `[or](+2)` 2 levels (only works on less stressed, usually short words)
133
- '''
134
-
135
- with gr.Blocks() as generate_tab:
136
- out_audio = gr.Audio(label='Output Audio', interactive=False, streaming=False, autoplay=True)
137
- generate_btn = gr.Button('Generate', variant='primary')
138
- with gr.Accordion('Output Tokens', open=True):
139
- out_ps = gr.Textbox(interactive=False, show_label=False, info='Tokens used to generate the audio, up to 510 context length.')
140
- tokenize_btn = gr.Button('Tokenize', variant='secondary')
141
- gr.Markdown(TOKEN_NOTE)
142
- predict_btn = gr.Button('Predict', variant='secondary', visible=False)
143
-
144
- STREAM_NOTE = ['⚠️ There is an unknown Gradio bug that might yield no audio the first time you click `Stream`.']
145
- if CHAR_LIMIT is not None:
146
- STREAM_NOTE.append(f'✂️ Each stream is capped at {CHAR_LIMIT} characters.')
147
- STREAM_NOTE.append('🚀 Want more characters? You can [use Kokoro directly](https://huggingface.co/hexgrad/Kokoro-82M#usage) or duplicate this space:')
148
- STREAM_NOTE = '\n\n'.join(STREAM_NOTE)
149
-
150
- with gr.Blocks() as stream_tab:
151
- out_stream = gr.Audio(label='Output Audio Stream', interactive=False, streaming=True, autoplay=True)
152
- with gr.Row():
153
- stream_btn = gr.Button('Stream', variant='primary')
154
- stop_btn = gr.Button('Stop', variant='stop')
155
- with gr.Accordion('Note', open=True):
156
- gr.Markdown(STREAM_NOTE)
157
- gr.DuplicateButton()
158
-
159
- BANNER_TEXT = '''
160
- [***Kokoro*** **is an open-weight TTS model with 82 million parameters.**](https://huggingface.co/hexgrad/Kokoro-82M)
161
-
162
- As of January 31st, 2025, Kokoro was the most-liked [**TTS model**](https://huggingface.co/models?pipeline_tag=text-to-speech&sort=likes) and the most-liked [**TTS space**](https://huggingface.co/spaces?sort=likes&search=tts) on Hugging Face.
163
-
164
- This demo only showcases English, but you can directly use the model to access other languages.
165
- '''
166
- API_OPEN = os.getenv('SPACE_ID') != 'hexgrad/Kokoro-TTS'
167
- API_NAME = None if API_OPEN else False
168
- with gr.Blocks() as app:
169
- with gr.Row():
170
- gr.Markdown(BANNER_TEXT, container=True)
171
- with gr.Row():
172
- with gr.Column():
173
- text = gr.Textbox(label='Input Text', info=f"Up to ~500 characters per Generate, or {'∞' if CHAR_LIMIT is None else CHAR_LIMIT} characters per Stream")
174
- with gr.Row():
175
- voice = gr.Dropdown(list(CHOICES.items()), value='af_heart', label='Voice', info='Quality and availability vary by language')
176
- use_gpu = gr.Dropdown(
177
- [('ZeroGPU 🚀', True), ('CPU 🐌', False)],
178
- value=CUDA_AVAILABLE,
179
- label='Hardware',
180
- info='GPU is usually faster, but has a usage quota',
181
- interactive=CUDA_AVAILABLE
182
- )
183
- speed = gr.Slider(minimum=0.5, maximum=2, value=1, step=0.1, label='Speed')
184
- random_btn = gr.Button('🎲 Random Quote 💬', variant='secondary')
185
- with gr.Row():
186
- gatsby_btn = gr.Button('🥂 Gatsby 📕', variant='secondary')
187
- frankenstein_btn = gr.Button('💀 Frankenstein 📗', variant='secondary')
188
- with gr.Column():
189
- gr.TabbedInterface([generate_tab, stream_tab], ['Generate', 'Stream'])
190
- random_btn.click(fn=get_random_quote, inputs=[], outputs=[text], api_name=API_NAME)
191
- gatsby_btn.click(fn=get_gatsby, inputs=[], outputs=[text], api_name=API_NAME)
192
- frankenstein_btn.click(fn=get_frankenstein, inputs=[], outputs=[text], api_name=API_NAME)
193
- generate_btn.click(fn=generate_first, inputs=[text, voice, speed, use_gpu], outputs=[out_audio, out_ps], api_name=API_NAME)
194
- tokenize_btn.click(fn=tokenize_first, inputs=[text, voice], outputs=[out_ps], api_name=API_NAME)
195
- stream_event = stream_btn.click(fn=generate_all, inputs=[text, voice, speed, use_gpu], outputs=[out_stream], api_name=API_NAME)
196
- stop_btn.click(fn=None, cancels=stream_event)
197
- predict_btn.click(fn=predict, inputs=[text, voice, speed], outputs=[out_audio], api_name=API_NAME)
198
-
199
- if __name__ == '__main__':
200
- app.queue(api_open=API_OPEN).launch(show_api=API_OPEN, ssr_mode=True)
 
1
+ from fastapi import FastAPI, Query, HTTPException, BackgroundTasks
2
+ from fastapi.responses import StreamingResponse
3
+ from pydantic import BaseModel, Field
4
+ from typing import List, Dict, Optional, Tuple, Generator
 
5
  import torch
6
+ import os
7
+ import io
8
+ import numpy as np
9
+ from kokoro import KModel, KPipeline
10
+ import spaces
11
+ import time
12
 
13
+ app = FastAPI(title="Kokoro TTS API", description="API for Kokoro text-to-speech conversion")
14
+
15
+ # Constants
16
  IS_DUPLICATE = not os.getenv('SPACE_ID', '').startswith('hexgrad/')
17
  CHAR_LIMIT = None if IS_DUPLICATE else 5000
 
18
  CUDA_AVAILABLE = torch.cuda.is_available()
19
+
20
+ # Initialize models
21
  models = {gpu: KModel().to('cuda' if gpu else 'cpu').eval() for gpu in [False] + ([True] if CUDA_AVAILABLE else [])}
22
  pipelines = {lang_code: KPipeline(lang_code=lang_code, model=False) for lang_code in 'ab'}
23
  pipelines['a'].g2p.lexicon.golds['kokoro'] = 'kˈOkəɹO'
24
  pipelines['b'].g2p.lexicon.golds['kokoro'] = 'kˈQkəɹQ'
25
 
26
+ # Voice choices
27
+ CHOICES = {
28
+ '🇺🇸 🚺 Heart ❤️': 'af_heart',
29
+ '🇺🇸 🚺 Bella 🔥': 'af_bella',
30
+ '🇺🇸 🚺 Nicole 🎧': 'af_nicole',
31
+ '🇺🇸 🚺 Aoede': 'af_aoede',
32
+ '🇺🇸 🚺 Kore': 'af_kore',
33
+ '🇺🇸 🚺 Sarah': 'af_sarah',
34
+ '🇺🇸 🚺 Nova': 'af_nova',
35
+ '🇺🇸 🚺 Sky': 'af_sky',
36
+ '🇺🇸 🚺 Alloy': 'af_alloy',
37
+ '🇺🇸 🚺 Jessica': 'af_jessica',
38
+ '🇺🇸 🚺 River': 'af_river',
39
+ '🇺🇸 🚹 Michael': 'am_michael',
40
+ '🇺🇸 🚹 Fenrir': 'am_fenrir',
41
+ '🇺🇸 🚹 Puck': 'am_puck',
42
+ '🇺🇸 🚹 Echo': 'am_echo',
43
+ '🇺🇸 🚹 Eric': 'am_eric',
44
+ '🇺🇸 🚹 Liam': 'am_liam',
45
+ '🇺🇸 🚹 Onyx': 'am_onyx',
46
+ '🇺🇸 🚹 Santa': 'am_santa',
47
+ '🇺🇸 🚹 Adam': 'am_adam',
48
+ '🇬🇧 🚺 Emma': 'bf_emma',
49
+ '🇬🇧 🚺 Isabella': 'bf_isabella',
50
+ '🇬🇧 🚺 Alice': 'bf_alice',
51
+ '🇬🇧 🚺 Lily': 'bf_lily',
52
+ '🇬🇧 🚹 George': 'bm_george',
53
+ '🇬🇧 🚹 Fable': 'bm_fable',
54
+ '🇬🇧 🚹 Lewis': 'bm_lewis',
55
+ '🇬🇧 🚹 Daniel': 'bm_daniel',
56
+ }
57
+
58
+ # Load voices
59
+ for v in CHOICES.values():
60
+ pipelines[v[0]].load_voice(v)
61
+
62
+ # Sample text files
63
+ with open('en.txt', 'r') as r:
64
+ RANDOM_QUOTES = [line.strip() for line in r]
65
+
66
+ def get_gatsby():
67
+ with open('gatsby5k.md', 'r') as r:
68
+ return r.read().strip()
69
+
70
+ def get_frankenstein():
71
+ with open('frankenstein5k.md', 'r') as r:
72
+ return r.read().strip()
73
+
74
+ # Pydantic models
75
+ class TTSRequest(BaseModel):
76
+ text: str = Field(..., description="Text to convert to speech")
77
+ voice: str = Field("af_heart", description="Voice ID to use for TTS")
78
+ speed: float = Field(1.0, description="Speech speed factor (0.5 to 2.0)", ge=0.5, le=2.0)
79
+ use_gpu: bool = Field(CUDA_AVAILABLE, description="Whether to use GPU for inference")
80
+
81
+ class TextRequest(BaseModel):
82
+ text: str = Field(..., description="Text to tokenize")
83
+ voice: str = Field("af_heart", description="Voice ID to use for tokenization")
84
+
85
+ class Voice(BaseModel):
86
+ display_name: str
87
+ id: str
88
+ language: str
89
+ gender: str
90
+
91
+ class VoiceList(BaseModel):
92
+ voices: List[Voice]
93
+
94
+ # GPU wrapper function
95
  @spaces.GPU(duration=30)
96
  def forward_gpu(ps, ref_s, speed):
97
  return models[True](ps, ref_s, speed)
98
 
99
+ # Helper functions
100
+ def generate_first(text: str, voice: str = 'af_heart', speed: float = 1.0, use_gpu: bool = CUDA_AVAILABLE):
101
+ """Generate audio for the first sentence/segment of text"""
102
  text = text if CHAR_LIMIT is None else text.strip()[:CHAR_LIMIT]
103
  pipeline = pipelines[voice[0]]
104
  pack = pipeline.load_voice(voice)
105
  use_gpu = use_gpu and CUDA_AVAILABLE
106
+
107
  for _, ps, _ in pipeline(text, voice, speed):
108
  ref_s = pack[len(ps)-1]
109
  try:
 
111
  audio = forward_gpu(ps, ref_s, speed)
112
  else:
113
  audio = models[False](ps, ref_s, speed)
114
+ except Exception as e:
115
  if use_gpu:
116
+ # Fallback to CPU
 
117
  audio = models[False](ps, ref_s, speed)
118
  else:
119
+ raise HTTPException(status_code=500, detail=str(e))
120
+
121
  return (24000, audio.numpy()), ps
122
+
123
  return None, ''
124
 
125
+ def tokenize_first(text: str, voice: str = 'af_heart'):
126
+ """Tokenize the first sentence/segment of text"""
 
 
 
127
  pipeline = pipelines[voice[0]]
128
  for _, ps, _ in pipeline(text, voice):
129
  return ps
130
  return ''
131
 
132
+ def generate_all(text: str, voice: str = 'af_heart', speed: float = 1.0, use_gpu: bool = CUDA_AVAILABLE) -> Generator:
133
+ """Generate audio for all segments of text"""
134
  text = text if CHAR_LIMIT is None else text.strip()[:CHAR_LIMIT]
135
  pipeline = pipelines[voice[0]]
136
  pack = pipeline.load_voice(voice)
137
  use_gpu = use_gpu and CUDA_AVAILABLE
138
+
139
  for _, ps, _ in pipeline(text, voice, speed):
140
  ref_s = pack[len(ps)-1]
141
  try:
 
143
  audio = forward_gpu(ps, ref_s, speed)
144
  else:
145
  audio = models[False](ps, ref_s, speed)
146
+ except Exception as e:
147
  if use_gpu:
148
+ # Fallback to CPU
 
149
  audio = models[False](ps, ref_s, speed)
150
  else:
151
+ raise HTTPException(status_code=500, detail=str(e))
152
+
153
+ yield audio.numpy()
 
 
154
 
155
+ def create_wav(audio_data, sample_rate=24000):
156
+ """Convert numpy array to WAV bytes"""
157
+ import wave
158
+ import struct
159
+
160
+ wav_io = io.BytesIO()
161
+ with wave.open(wav_io, 'wb') as wav_file:
162
+ wav_file.setnchannels(1) # Mono
163
+ wav_file.setsampwidth(2) # 16-bit
164
+ wav_file.setframerate(sample_rate)
165
+
166
+ # Convert float32 to int16
167
+ audio_data = (audio_data * 32767).astype(np.int16)
168
+ wav_file.writeframes(audio_data.tobytes())
169
+
170
+ wav_io.seek(0)
171
+ return wav_io.read()
172
 
173
+ def stream_wav_chunks(audio_chunks, sample_rate=24000):
174
+ """Stream WAV chunks as they're generated"""
175
+ # Write WAV header first
176
+ header_io = io.BytesIO()
177
+ with wave.open(header_io, 'wb') as wav_file:
178
+ wav_file.setnchannels(1) # Mono
179
+ wav_file.setsampwidth(2) # 16-bit
180
+ wav_file.setframerate(sample_rate)
181
+ # We don't know the total frames yet
182
+ wav_file.writeframes(b'')
183
+
184
+ # Get header bytes
185
+ header_io.seek(0)
186
+ header_bytes = header_io.read(44) # WAV header is 44 bytes
187
+ yield header_bytes
188
+
189
+ # Stream audio chunks
190
+ for chunk in audio_chunks:
191
+ # Convert float32 to int16
192
+ audio_data = (chunk * 32767).astype(np.int16)
193
+ yield audio_data.tobytes()
194
+ time.sleep(0.1) # Small delay to avoid overwhelming the client
195
 
196
+ # API Routes
197
+ @app.get("/", tags=["Info"])
198
+ async def root():
199
+ """API root with basic information"""
200
+ return {
201
+ "message": "Kokoro TTS API",
202
+ "description": "Convert text to speech using Kokoro TTS model",
203
+ "endpoints": {
204
+ "GET /voices": "List available voices",
205
+ "POST /tts": "Convert text to speech",
206
+ "POST /tokenize": "Tokenize text",
207
+ "GET /stream": "Stream audio from text",
208
+ "GET /samples": "Get sample texts"
209
+ }
210
+ }
211
 
212
+ @app.get("/voices", response_model=VoiceList, tags=["Voices"])
213
+ async def list_voices():
214
+ """List all available voices"""
215
+ voice_list = []
216
+ for display_name, voice_id in CHOICES.items():
217
+ # Parse display name format: "🇺🇸 🚺 Heart ❤️"
218
+ parts = display_name.split()
219
+ language = "US English" if "🇺🇸" in display_name else "UK English"
220
+ gender = "Female" if "🚺" in display_name else "Male"
221
+
222
+ voice_list.append(Voice(
223
+ display_name=display_name,
224
+ id=voice_id,
225
+ language=language,
226
+ gender=gender
227
+ ))
228
+
229
+ return VoiceList(voices=voice_list)
230
 
231
+ @app.post("/tts", tags=["Text-to-Speech"])
232
+ async def text_to_speech(request: TTSRequest):
233
+ """Convert text to speech"""
234
+ if request.voice not in CHOICES.values():
235
+ raise HTTPException(status_code=400, detail=f"Voice '{request.voice}' not found. Use /voices to see available options.")
236
+
237
+ result, _ = generate_first(request.text, request.voice, request.speed, request.use_gpu)
238
+ if result is None:
239
+ raise HTTPException(status_code=500, detail="Failed to generate audio")
240
+
241
+ sample_rate, audio_data = result
242
+ wav_bytes = create_wav(audio_data, sample_rate)
243
+
244
+ return StreamingResponse(
245
+ io.BytesIO(wav_bytes),
246
+ media_type="audio/wav",
247
+ headers={"Content-Disposition": f"attachment; filename=tts_{request.voice}.wav"}
248
+ )
249
+
250
+ @app.post("/tokenize", tags=["Text Processing"])
251
+ async def tokenize_text(request: TextRequest):
252
+ """Tokenize input text"""
253
+ if request.voice not in CHOICES.values():
254
+ raise HTTPException(status_code=400, detail=f"Voice '{request.voice}' not found. Use /voices to see available options.")
255
+
256
+ tokens = tokenize_first(request.text, request.voice)
257
+ return {"text": request.text, "tokens": tokens}
258
+
259
+ @app.get("/stream", tags=["Text-to-Speech"])
260
+ async def stream_tts(
261
+ text: str = Query(..., description="Text to convert to speech"),
262
+ voice: str = Query("af_heart", description="Voice ID"),
263
+ speed: float = Query(1.0, description="Speech speed", ge=0.5, le=2.0),
264
+ use_gpu: bool = Query(CUDA_AVAILABLE, description="Use GPU for inference")
265
+ ):
266
+ """Stream audio from text as it's generated"""
267
+ if voice not in CHOICES.values():
268
+ raise HTTPException(status_code=400, detail=f"Voice '{voice}' not found. Use /voices to see available options.")
269
+
270
+ # Limit text if needed
271
+ if CHAR_LIMIT is not None:
272
+ text = text.strip()[:CHAR_LIMIT]
273
+
274
+ # Create generator for audio chunks
275
+ audio_chunks = generate_all(text, voice, speed, use_gpu)
276
+
277
+ # Stream as WAV
278
+ return StreamingResponse(
279
+ stream_wav_chunks(audio_chunks),
280
+ media_type="audio/wav",
281
+ headers={"Content-Disposition": f"attachment; filename=stream_{voice}.wav"}
282
+ )
283
+
284
+ @app.get("/samples", tags=["Sample Text"])
285
+ async def get_samples():
286
+ """Get sample texts"""
287
+ import random
288
+
289
+ return {
290
+ "random_quote": random.choice(RANDOM_QUOTES),
291
+ "gatsby_excerpt": get_gatsby()[:200] + "...", # First 200 chars
292
+ "frankenstein_excerpt": get_frankenstein()[:200] + "..." # First 200 chars
293
+ }
294
+
295
+ @app.get("/sample/{sample_type}", tags=["Sample Text"])
296
+ async def get_sample(sample_type: str):
297
+ """Get a specific sample text"""
298
+ import random
299
+
300
+ if sample_type == "random":
301
+ return {"text": random.choice(RANDOM_QUOTES)}
302
+ elif sample_type == "gatsby":
303
+ return {"text": get_gatsby()}
304
+ elif sample_type == "frankenstein":
305
+ return {"text": get_frankenstein()}
306
+ else:
307
+ raise HTTPException(status_code=404, detail=f"Sample type '{sample_type}' not found")
308
 
309
+ if __name__ == "__main__":
310
+ import uvicorn
311
+ uvicorn.run("app:app", host="0.0.0.0", port=8000, reload=True)