bcci commited on
Commit
7fd0353
·
verified ·
1 Parent(s): 58c1307

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +210 -0
app.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import re
3
+ import wave
4
+ import struct
5
+
6
+ import numpy as np
7
+ import torch
8
+ from fastapi import FastAPI, HTTPException
9
+ from fastapi.responses import StreamingResponse, Response, HTMLResponse
10
+
11
+ from kokoro import KPipeline
12
+
13
+ app = FastAPI(title="Kokoro TTS FastAPI")
14
+
15
+ # ------------------------------------------------------------------------------
16
+ # Global Pipeline Instance
17
+ # ------------------------------------------------------------------------------
18
+ # Create one pipeline instance for the entire app.
19
+ pipeline = KPipeline(lang_code="a")
20
+
21
+
22
+ # ------------------------------------------------------------------------------
23
+ # Helper Functions
24
+ # ------------------------------------------------------------------------------
25
+
26
+ def generate_wav_header(sample_rate: int, num_channels: int, sample_width: int, data_size: int = 0x7FFFFFFF) -> bytes:
27
+ """
28
+ Generate a WAV header for streaming.
29
+ Since we don't know the final audio size, we set the data chunk size to a large dummy value.
30
+ This header is sent only once at the start of the stream.
31
+ """
32
+ bits_per_sample = sample_width * 8
33
+ byte_rate = sample_rate * num_channels * sample_width
34
+ block_align = num_channels * sample_width
35
+ # total file size = 36 + data_size (header is 44 bytes total)
36
+ total_size = 36 + data_size
37
+ header = struct.pack('<4sI4s', b'RIFF', total_size, b'WAVE')
38
+ fmt_chunk = struct.pack('<4sIHHIIHH', b'fmt ', 16, 1, num_channels, sample_rate, byte_rate, block_align, bits_per_sample)
39
+ data_chunk_header = struct.pack('<4sI', b'data', data_size)
40
+ return header + fmt_chunk + data_chunk_header
41
+
42
+
43
+ def custom_split_text(text: str) -> list:
44
+ """
45
+ Custom splitting: split text into chunks where each chunk doubles in size.
46
+ """
47
+ words = text.split()
48
+ chunks = []
49
+ chunk_size = 1
50
+ start = 0
51
+ while start < len(words):
52
+ end = start + chunk_size
53
+ chunk = " ".join(words[start:end])
54
+ chunks.append(chunk)
55
+ start = end
56
+ chunk_size *= 2 # double the chunk size for the next iteration
57
+ return chunks
58
+
59
+
60
+ def audio_tensor_to_pcm_bytes(audio_tensor: torch.Tensor) -> bytes:
61
+ """
62
+ Convert a torch.FloatTensor (with values in [-1, 1]) to raw 16-bit PCM bytes.
63
+ """
64
+ # Ensure tensor is on CPU and flatten if necessary.
65
+ audio_np = audio_tensor.cpu().numpy()
66
+ if audio_np.ndim > 1:
67
+ audio_np = audio_np.flatten()
68
+ # Scale to int16 range.
69
+ audio_int16 = np.int16(audio_np * 32767)
70
+ return audio_int16.tobytes()
71
+
72
+
73
+ # ------------------------------------------------------------------------------
74
+ # Endpoints
75
+ # ------------------------------------------------------------------------------
76
+
77
+ @app.get("/tts/streaming", summary="Streaming TTS")
78
+ def tts_streaming(text: str, voice: str = "af_heart", speed: float = 1.0):
79
+ """
80
+ Streaming TTS endpoint that returns a continuous WAV stream.
81
+
82
+ The endpoint first yields a WAV header (with a dummy length) then yields raw PCM data
83
+ for each text chunk as soon as it is generated.
84
+ """
85
+ # Split the input text using the custom doubling strategy.
86
+ chunks = custom_split_text(text)
87
+ sample_rate = 24000
88
+ num_channels = 1
89
+ sample_width = 2 # 16-bit PCM
90
+
91
+ def audio_generator():
92
+ # Yield the WAV header first.
93
+ header = generate_wav_header(sample_rate, num_channels, sample_width)
94
+ yield header
95
+ # Process and yield each chunk's PCM data.
96
+ for i, chunk in enumerate(chunks):
97
+ print(f"Processing chunk {i}: {chunk}") # Debugging
98
+ try:
99
+ results = list(pipeline(chunk, voice=voice, speed=speed, split_pattern=None))
100
+ for result in results:
101
+ if result.audio is not None:
102
+ print(f"Chunk {i}: Audio generated") # Debugging
103
+ pcm_bytes = audio_tensor_to_pcm_bytes(result.audio)
104
+ yield pcm_bytes
105
+ else:
106
+ print(f"Chunk {i}: No audio generated")
107
+ except Exception as e:
108
+ print(f"Error processing chunk {i}: {e}")
109
+
110
+ return StreamingResponse(
111
+ audio_generator(),
112
+ media_type="audio/wav",
113
+ headers={"Cache-Control": "no-cache"},
114
+ )
115
+
116
+
117
+ @app.get("/tts/full", summary="Full TTS")
118
+ def tts_full(text: str, voice: str = "af_heart", speed: float = 1.0):
119
+ """
120
+ Full TTS endpoint that synthesizes the entire text, concatenates the audio,
121
+ and returns a complete WAV file.
122
+ """
123
+ # Use newline-based splitting via the pipeline's split_pattern.
124
+ results = list(pipeline(text, voice=voice, speed=speed, split_pattern=r"\n+"))
125
+ audio_segments = []
126
+ for result in results:
127
+ if result.audio is not None:
128
+ audio_np = result.audio.cpu().numpy()
129
+ if audio_np.ndim > 1:
130
+ audio_np = audio_np.flatten()
131
+ audio_segments.append(audio_np)
132
+
133
+ if not audio_segments:
134
+ raise HTTPException(status_code=500, detail="No audio generated.")
135
+
136
+ # Concatenate all audio segments.
137
+ full_audio = np.concatenate(audio_segments)
138
+
139
+ # Write the concatenated audio to an in-memory WAV file.
140
+ sample_rate = 24000
141
+ num_channels = 1
142
+ sample_width = 2 # 16-bit PCM -> 2 bytes per sample
143
+ wav_io = io.BytesIO()
144
+ with wave.open(wav_io, "wb") as wav_file:
145
+ wav_file.setnchannels(num_channels)
146
+ wav_file.setsampwidth(sample_width)
147
+ wav_file.setframerate(sample_rate)
148
+ full_audio_int16 = np.int16(full_audio * 32767)
149
+ wav_file.writeframes(full_audio_int16.tobytes())
150
+ wav_io.seek(0)
151
+ return Response(content=wav_io.read(), media_type="audio/wav")
152
+
153
+
154
+ @app.get("/", response_class=HTMLResponse)
155
+ def index():
156
+ """
157
+ HTML demo page for Kokoro TTS.
158
+
159
+ This page provides a simple UI to enter text, choose a voice and speed,
160
+ and play synthesized audio from both the streaming and full endpoints.
161
+ """
162
+ return """
163
+ <!DOCTYPE html>
164
+ <html>
165
+ <head>
166
+ <title>Kokoro TTS Demo</title>
167
+ </head>
168
+ <body>
169
+ <h1>Kokoro TTS Demo</h1>
170
+ <textarea id="text" rows="4" cols="50" placeholder="Enter text here"></textarea><br>
171
+ <label for="voice">Voice:</label>
172
+ <input type="text" id="voice" value="af_heart"><br>
173
+ <label for="speed">Speed:</label>
174
+ <input type="number" step="0.1" id="speed" value="1.0"><br><br>
175
+ <button onclick="playStreaming()">Play Streaming TTS</button>
176
+ <button onclick="playFull()">Play Full TTS</button>
177
+ <br><br>
178
+ <audio id="audio" controls autoplay></audio>
179
+ <script>
180
+ function playStreaming() {
181
+ const text = document.getElementById('text').value;
182
+ const voice = document.getElementById('voice').value;
183
+ const speed = document.getElementById('speed').value;
184
+ const audio = document.getElementById('audio');
185
+ // Set the audio element's source to the streaming endpoint.
186
+ audio.src = `/tts/streaming?text=${encodeURIComponent(text)}&voice=${encodeURIComponent(voice)}&speed=${speed}`;
187
+ audio.play();
188
+ }
189
+ function playFull() {
190
+ const text = document.getElementById('text').value;
191
+ const voice = document.getElementById('voice').value;
192
+ const speed = document.getElementById('speed').value;
193
+ const audio = document.getElementById('audio');
194
+ // Set the audio element's source to the full TTS endpoint.
195
+ audio.src = `/tts/full?text=${encodeURIComponent(text)}&voice=${encodeURIComponent(voice)}&speed=${speed}`;
196
+ audio.play();
197
+ }
198
+ </script>
199
+ </body>
200
+ </html>
201
+ """
202
+
203
+
204
+ # ------------------------------------------------------------------------------
205
+ # Run with: uvicorn app:app --reload
206
+ # ------------------------------------------------------------------------------
207
+ if __name__ == "__main__":
208
+ import uvicorn
209
+
210
+ uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=True)