-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkitten_reader.py
More file actions
516 lines (443 loc) · 16.3 KB
/
kitten_reader.py
File metadata and controls
516 lines (443 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
import os
import sys
import json
import time
import asyncio
import re
from pathlib import Path
from typing import List, Optional
import uvicorn
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse
from pydantic import BaseModel
try:
import kittentts
import soundfile as sf
import numpy as np
import httpx
from piper.voice import PiperVoice
except ImportError:
print("Brak wymaganych bibliotek. Zainstaluj je komendą: pip install kittentts soundfile numpy fastapi uvicorn piper-tts httpx")
app = FastAPI(title="Kitten Reader Pro")
# --- Konfiguracja ---
CACHE_BASE = Path(os.getenv("CACHE_DIR", "data/cache"))
CACHE_DIR = CACHE_BASE / "piper"
HF_CACHE = CACHE_BASE / "hf"
CACHE_DIR.mkdir(parents=True, exist_ok=True)
HF_CACHE.mkdir(parents=True, exist_ok=True)
# Ustawienie zmiennej HF HUB dla KittenTTS (jeśli nie jest jeszcze ustawiona w środowisku)
if not os.getenv("HUGGINGFACE_HUB_CACHE"):
os.environ["HUGGINGFACE_HUB_CACHE"] = str(HF_CACHE)
DEFAULT_MODEL = "KittenML/kitten-tts-mini-0.8"
DEFAULT_VOICE = "expr-voice-2-f"
# Globalne instancje modeli
tts_model: Optional[any] = None
piper_voices: dict = {}
# Konfiguracja Piper (Polski)
PIPER_MODELS = {
"pl-gosia": {
"url": "https://huggingface.co/rhasspy/piper-voices/resolve/main/pl/pl_PL/gosia/medium/pl_PL-gosia-medium.onnx",
"config": "https://huggingface.co/rhasspy/piper-voices/resolve/main/pl/pl_PL/gosia/medium/pl_PL-gosia-medium.onnx.json"
},
"pl-darkman": {
"url": "https://huggingface.co/rhasspy/piper-voices/resolve/main/pl/pl_PL/darkman/medium/pl_PL-darkman-medium.onnx",
"config": "https://huggingface.co/rhasspy/piper-voices/resolve/main/pl/pl_PL/darkman/medium/pl_PL-darkman-medium.onnx.json"
}
}
async def download_file(url: str, dest: Path):
if dest.exists(): return
print(f"Pobieranie: {url}...")
async with httpx.AsyncClient() as client:
resp = await client.get(url, follow_redirects=True)
resp.raise_for_status()
dest.write_bytes(resp.content)
def get_tts():
global tts_model
if tts_model is None:
print(f"Ładowanie modelu KittenTTS: {DEFAULT_MODEL}...")
# KittenTTS automatycznie korzysta z HUGGINGFACE_HUB_CACHE
tts_model = kittentts.KittenTTS(DEFAULT_MODEL)
return tts_model
async def get_piper_voice(name: str):
if name not in piper_voices:
info = PIPER_MODELS[name]
onnx_path = CACHE_DIR / f"{name}.onnx"
json_path = CACHE_DIR / f"{name}.onnx.json"
await download_file(info["url"], onnx_path)
await download_file(info["config"], json_path)
print(f"Ładowanie modelu Piper: {name}...")
piper_voices[name] = PiperVoice.load(str(onnx_path), config_path=str(json_path))
return piper_voices[name]
class ReadRequest(BaseModel):
text: str
voice: str = DEFAULT_VOICE
speed: float = 1.0
# --- UI HTML ---
HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Kitten Reader Pro - Twój osobisty lektor</title>
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600&display=swap" rel="stylesheet">
<style>
:root {
--primary: #ff6b6b;
--secondary: #4ecdc4;
--dark: #1a1a2e;
--glass: rgba(255, 255, 255, 0.05);
--glass-border: rgba(255, 255, 255, 0.1);
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'Outfit', sans-serif;
background: radial-gradient(circle at top right, #16213e, #1a1a2e);
color: #fff;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
overflow-x: hidden;
}
.container {
max-width: 900px;
width: 95%;
margin: 40px auto;
position: relative;
}
header {
text-align: center;
margin-bottom: 40px;
animation: fadeIn 1s ease-out;
}
h1 {
font-size: 3rem;
font-weight: 600;
background: linear-gradient(to right, var(--primary), var(--secondary));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
margin-bottom: 10px;
}
p.subtitle {
color: #888;
font-size: 1.1rem;
}
.glass-panel {
background: var(--glass);
backdrop-filter: blur(12px);
border: 1px solid var(--glass-border);
border-radius: 24px;
padding: 30px;
box-shadow: 0 8px 32px rgba(0,0,0,0.3);
margin-bottom: 20px;
}
textarea {
width: 100%;
height: 400px;
background: rgba(0,0,0,0.2);
border: 1px solid var(--glass-border);
border-radius: 16px;
color: #fff;
padding: 20px;
font-size: 1.1rem;
line-height: 1.6;
resize: none;
outline: none;
transition: border-color 0.3s;
font-family: inherit;
}
textarea:focus {
border-color: var(--secondary);
}
.controls {
display: flex;
gap: 15px;
margin-top: 20px;
flex-wrap: wrap;
align-items: center;
}
.setting {
display: flex;
flex-direction: column;
gap: 5px;
}
label {
font-size: 0.8rem;
text-transform: uppercase;
letter-spacing: 1px;
color: #aaa;
}
select, input {
background: #252545;
color: #fff;
border: 1px solid var(--glass-border);
padding: 8px 12px;
border-radius: 8px;
outline: none;
}
.play-btn {
background: linear-gradient(135deg, var(--primary), #ee5253);
color: #fff;
border: none;
padding: 12px 30px;
border-radius: 12px;
font-weight: 600;
font-size: 1.1rem;
cursor: pointer;
transition: all 0.3s;
display: flex;
align-items: center;
gap: 10px;
margin-left: auto;
position: relative;
overflow: hidden;
}
.play-btn:hover {
transform: scale(1.05);
box-shadow: 0 5px 15px rgba(255, 107, 107, 0.4);
}
.play-btn:active {
transform: scale(0.98);
}
.play-btn:disabled {
background: #444;
cursor: not-allowed;
transform: none;
}
#status {
margin-top: 20px;
text-align: center;
font-size: 0.9rem;
color: var(--secondary);
min-height: 1.2em;
}
.progress-bar {
width: 100%;
height: 4px;
background: rgba(255,255,255,0.1);
border-radius: 2px;
margin-top: 10px;
display: none;
}
.progress-fill {
height: 100%;
background: var(--secondary);
width: 0%;
transition: width 0.3s;
}
audio {
width: 100%;
margin-top: 20px;
height: 40px;
display: none;
}
/* Animations */
@keyframes fadeIn {
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
}
.loader {
width: 20px;
height: 20px;
border: 3px solid rgba(255,255,255,0.3);
border-radius: 50%;
border-top-color: #fff;
animation: spin 1s infinite linear;
display: none;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.floating-cat {
position: fixed;
bottom: 20px;
right: 20px;
font-size: 3rem;
opacity: 0.2;
pointer-events: none;
}
</style>
</head>
<body>
<div class="floating-cat">🐱</div>
<div class="container">
<header>
<h1>Kitten Reader Pro</h1>
<p class="subtitle">Wklej tekst, usiądź wygodnie i posłuchaj.</p>
</header>
<div class="glass-panel">
<textarea id="textInput" placeholder="Tutaj wklej swoje opowiadanie lub notatki..."></textarea>
<div class="controls">
<div class="setting">
<label>Głos</label>
<select id="voiceSelect">
<option value="pl-gosia">Gosia (Polski 🇵🇱)</option>
<option value="pl-darkman">Marek (Polski 🇵🇱)</option>
<option value="expr-voice-2-f">Zuzanna (Kitten - Angielski)</option>
<option value="expr-voice-3-m">Jakub (Kitten - Angielski)</option>
<option value="expr-voice-4-f">Julia (Kitten - Angielski)</option>
<option value="expr-voice-5-m">Marek (Kitten - Angielski)</option>
</select>
</div>
<div class="setting">
<label>Model</label>
<select id="modelSelect">
<option value="KittenML/kitten-tts-mini-0.8">Mini 0.8 (Najlepszy)</option>
<option value="KittenML/kitten-tts-micro-0.8">Micro 0.8 (Szybszy)</option>
</select>
</div>
<button class="play-btn" id="playBtn">
<div class="loader" id="loader"></div>
<span id="btnText">Czytaj tekst</span>
</button>
</div>
<div id="status">Gotowy do czytania.</div>
<div class="progress-bar" id="progressBar">
<div class="progress-fill" id="progressFill"></div>
</div>
<audio id="audioPlayer" controls></audio>
</div>
</div>
<script>
const playBtn = document.getElementById('playBtn');
const loader = document.getElementById('loader');
const btnText = document.getElementById('btnText');
const status = document.getElementById('status');
const textInput = document.getElementById('textInput');
const audioPlayer = document.getElementById('audioPlayer');
const progressFill = document.getElementById('progressFill');
const progressBar = document.getElementById('progressBar');
playBtn.addEventListener('click', async () => {
const text = textInput.value.trim();
if (!text) {
alert('Proszę najpierw wpisać lub wkleić tekst.');
return;
}
// UI State: Loading
playBtn.disabled = true;
loader.style.display = 'block';
btnText.innerText = 'Przetwarzanie...';
status.innerText = 'Inicjalizacja modelu i analiza tekstu...';
progressBar.style.display = 'block';
progressFill.style.width = '5%';
audioPlayer.style.display = 'none';
try {
const response = await fetch('/api/read', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
text: text,
voice: document.getElementById('voiceSelect').value,
model: document.getElementById('modelSelect').value
})
});
if (!response.ok) throw new Error('Błąd serwera przy generowaniu audio.');
// Obsługa dźwięku jako Blob
status.innerText = 'Generowanie mowy (to może chwilę potrwać dla długich tekstów)...';
progressFill.style.width = '50%';
const blob = await response.blob();
const url = URL.createObjectURL(blob);
audioPlayer.src = url;
audioPlayer.style.display = 'block';
progressFill.style.width = '100%';
status.innerText = 'Audio gotowe!';
audioPlayer.play();
} catch (err) {
console.error(err);
status.innerText = 'Błąd: ' + err.message;
} finally {
playBtn.disabled = false;
loader.style.display = 'none';
btnText.innerText = 'Czytaj tekst';
setTimeout(() => {
progressBar.style.display = 'none';
progressFill.style.width = '0%';
}, 3000);
}
});
</script>
</body>
</html>
"""
@app.get("/", response_class=HTMLResponse)
async def index():
return HTML_TEMPLATE
@app.post("/api/read")
async def read_text(req: ReadRequest):
text = req.text
if not text:
raise HTTPException(400, "Brak tekstu do czytania.")
try:
# 0. Wybór silnika (Piper vs Kitten)
is_piper = req.voice.startswith("pl-")
if is_piper:
tts = await get_piper_voice(req.voice)
sr = tts.config.sample_rate # Zwykle 22050 dla Piper
else:
tts = get_tts()
sr = 24000
# 1. Sanityzacja tekstu (pozbycie się trudnych znaków)
processed_text = text.replace('„', '"').replace('”', '"').replace('—', '-').replace('…', '...')
# 2. Podział tekstu na sensowne kawałki
initial_chunks = re.split(r'(?<=[.!?])\s+', processed_text)
mid_chunks = []
for c in initial_chunks:
mid_chunks.extend(c.split('\n'))
sentences = []
for c in mid_chunks:
c = c.strip()
if not c: continue
if len(c) > 200:
words = c.split(' ')
current_chunk = ""
for word in words:
if len(current_chunk) + len(word) + 1 > 200:
sentences.append(current_chunk.strip())
current_chunk = word
else:
current_chunk += " " + word
if current_chunk:
sentences.append(current_chunk.strip())
else:
sentences.append(c)
print(f"Generowanie mowy dla {len(sentences)} fragmentów silnikiem {'Piper' if is_piper else 'Kitten'}...")
all_audio = []
for i, s in enumerate(sentences):
if not s.strip(): continue
try:
if is_piper:
# Piper zwraca generator obiektów AudioChunk
chunk_list = []
for chunk in tts.synthesize(s):
chunk_list.append(chunk.audio_float_array)
if chunk_list:
all_audio.append(np.concatenate(chunk_list))
else:
audio = tts.generate(s, voice=req.voice)
all_audio.append(audio)
except Exception as e_inner:
print(f"Błąd przy fragmencie '{s[:30]}...': {e_inner}")
silence = np.zeros(int(sr * 0.5))
all_audio.append(silence)
# Połącz fragmenty audio
combined_audio = np.concatenate(all_audio)
# Zapisz do bufora RAM jako WAV
import io
buffer = io.BytesIO()
sf.write(buffer, combined_audio, sr, format='WAV')
buffer.seek(0)
return StreamingResponse(buffer, media_type="audio/wav")
except Exception as e:
print(f"Błąd TTS: {e}")
import traceback
traceback.print_exc()
raise HTTPException(500, f"Błąd generowania mowy: {str(e)}")
if __name__ == "__main__":
print("--- Kitten Reader Pro ---")
print("Aplikacja uruchomiona pod adresem: http://127.0.0.1:8001")
uvicorn.run(app, host="127.0.0.1", port=8001)