Randriamiandry commited on
Commit
50a4e0d
·
1 Parent(s): 3c0026e

fix clone, stream

Browse files
Files changed (3) hide show
  1. Dockerfile +1 -10
  2. app.py +90 -115
  3. static/index.html +298 -270
Dockerfile CHANGED
@@ -1,16 +1,7 @@
1
  FROM python:3.11-slim
2
-
3
- ENV PYTHONDONTWRITEBYTECODE=1
4
- ENV PYTHONUNBUFFERED=1
5
-
6
- WORKDIR /app
7
-
8
- # Installer ffmpeg
9
  RUN apt-get update && apt-get install -y ffmpeg && rm -rf /var/lib/apt/lists/*
10
-
11
  COPY requirements.txt .
12
  RUN pip install --no-cache-dir -r requirements.txt
13
-
14
  COPY . .
15
-
16
  CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
 
1
  FROM python:3.11-slim
 
 
 
 
 
 
 
2
  RUN apt-get update && apt-get install -y ffmpeg && rm -rf /var/lib/apt/lists/*
3
+ WORKDIR /app
4
  COPY requirements.txt .
5
  RUN pip install --no-cache-dir -r requirements.txt
 
6
  COPY . .
 
7
  CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
app.py CHANGED
@@ -1,90 +1,72 @@
1
  import io
2
  import os
3
  import tempfile
 
4
  import numpy as np
5
  from fastapi import FastAPI, HTTPException, UploadFile, File, Form
6
- from fastapi.responses import Response, FileResponse
7
  from fastapi.staticfiles import StaticFiles
8
  from pydantic import BaseModel
9
- from pocket_tts import TTSModel
10
  import scipy.io.wavfile
11
  from pydub import AudioSegment
12
 
13
- # ------------------------------------------------------------
14
- # Authentification Hugging Face (pour le clonage)
15
- # ------------------------------------------------------------
16
  HF_TOKEN = os.environ.get("HF_TOKEN")
 
 
 
 
 
17
  if HF_TOKEN:
18
  from huggingface_hub import login
19
  login(token=HF_TOKEN)
20
- print("✅ Authentifié Hugging Face")
21
  else:
22
- print("⚠️ Aucun token HF trouvé. Le clonage peut échouer.")
23
-
24
- # ------------------------------------------------------------
25
- # Application FastAPI
26
- # ------------------------------------------------------------
27
- app = FastAPI(
28
- title="API Pocket TTS",
29
- description="Synthèse vocale et clonage de voix – version complète",
30
- version="2.2"
31
- )
32
-
33
- # ------------------------------------------------------------
34
- # Chargement du modèle (avec support clonage)
35
- # ------------------------------------------------------------
36
- print("Chargement du modèle Pocket TTS...")
37
  try:
38
- tts_model = TTSModel.from_pretrained(
39
- "kyutai/pocket-tts",
40
- use_auth_token=HF_TOKEN if HF_TOKEN else True
 
 
41
  )
 
42
  except Exception as e:
43
- print(f"Fallback à load_model: {e}")
44
- tts_model = TTSModel.load_model()
45
 
46
- print(f"Taux échantillonnage: {tts_model.sample_rate} Hz")
47
- print("Modèle prêt.")
48
 
49
- # Dictionnaire des voix (intégrées + clonées)
50
  voices = {}
51
 
52
- # Voix intégrées (liste complète issue du modèle)
53
- builtin_voices = [
54
- "cosette", "marius", "javert", "alba", "jean", "anna", "vera",
55
- "fantine", "charles", "paul", "eponine", "azelma", "george",
56
- "mary", "jane", "michael", "eve", "bill_boerst", "peter_yearsley",
57
- "stuart_bell", "caro_davy", "giovanni", "lola", "juergen",
58
- "rafael", "estelle"
59
- ]
60
-
61
- for vname in builtin_voices:
62
  try:
63
- voices[vname] = tts_model.get_state_for_audio_prompt(vname)
64
- print(f"✓ Voix intégrée: {vname}")
65
  except Exception as e:
66
- print(f"✗ Erreur {vname}: {e}")
67
 
68
- print(f"{len(voices)} voix disponibles (intégrées).")
 
69
 
70
- # ------------------------------------------------------------
71
- # Fichiers statiques (interface HTML)
72
- # ------------------------------------------------------------
73
  app.mount("/static", StaticFiles(directory="static"), name="static")
74
 
75
- # ------------------------------------------------------------
76
- # Routes
77
- # ------------------------------------------------------------
78
  @app.get("/")
79
  async def root():
80
  return {
81
- "message": "API Pocket TTS opérationnelle",
82
- "endpoints": {
83
- "/demo": "interface HTML",
84
- "/tts": "POST synthèse vocale",
85
- "/clone-voice": "POST clonage (fichier audio + nom)",
86
- "/voices": "GET liste des voix"
87
- }
88
  }
89
 
90
  @app.get("/demo")
@@ -94,93 +76,86 @@ async def demo():
94
  class TTSRequest(BaseModel):
95
  text: str
96
  voice_name: str = "alba"
 
 
 
 
 
 
97
 
98
  @app.post("/tts")
99
  async def generate_speech(request: TTSRequest):
 
100
  text = request.text.strip()
101
  if not text:
102
  raise HTTPException(400, "Texte vide")
 
103
  if request.voice_name not in voices:
104
  available = ", ".join(voices.keys())
105
  raise HTTPException(400, f"Voix inconnue. Disponibles: {available}")
106
 
107
  try:
108
  voice_state = voices[request.voice_name]
109
- audio_tensor = tts_model.generate_audio(voice_state, text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  except Exception as e:
111
- raise HTTPException(500, f"Erreur génération: {e}")
112
-
113
- # Conversion flottant -> int16 avec mise à l'échelle
114
- audio_np = audio_tensor.numpy()
115
- if audio_np.dtype in (np.float32, np.float64):
116
- audio_np = np.clip(audio_np, -1.0, 1.0)
117
- audio_np = (audio_np * 32767).astype(np.int16)
118
- else:
119
- audio_np = audio_np.astype(np.int16)
120
-
121
- buffer = io.BytesIO()
122
- scipy.io.wavfile.write(buffer, tts_model.sample_rate, audio_np)
123
- buffer.seek(0)
124
-
125
- return Response(
126
- content=buffer.read(),
127
- media_type="audio/wav",
128
- headers={"Content-Disposition": "attachment; filename=speech.wav"}
129
- )
130
 
131
  @app.post("/clone-voice")
132
- async def clone_voice(
133
- audio_file: UploadFile = File(...),
134
- voice_name: str = Form(...)
135
- ):
136
  if voice_name in voices:
137
  raise HTTPException(400, f"La voix '{voice_name}' existe déjà.")
138
- if not audio_file.filename.lower().endswith(('.wav', '.mp3', '.m4a', '.ogg', '.flac')):
139
- raise HTTPException(400, "Format non supporté. Utilisez WAV, MP3, M4A, OGG ou FLAC.")
 
 
 
 
140
 
141
- tmp_input = None
142
- tmp_wav = None
143
  try:
144
- # Sauvegarde du fichier original
145
- with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(audio_file.filename)[1]) as f:
146
- content = await audio_file.read()
147
- f.write(content)
148
- tmp_input = f.name
149
-
150
- # Conversion en WAV PCM (mono, 24kHz) via pydub
151
- audio = AudioSegment.from_file(tmp_input)
152
- audio = audio.set_channels(1).set_frame_rate(24000) # 24kHz attendu par Pocket TTS
153
- with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:
154
- tmp_wav = f.name
155
- audio.export(tmp_wav, format="wav")
156
-
157
- # Clonage
158
- voice_state = tts_model.get_state_for_audio_prompt(tmp_wav)
159
  voices[voice_name] = voice_state
160
-
161
- return {
162
- "message": f"Voix '{voice_name}' clonée avec succès.",
163
- "voice_name": voice_name,
164
- "total_voices": len(voices)
165
- }
166
-
167
  except Exception as e:
168
  raise HTTPException(500, f"Erreur clonage: {str(e)}")
169
  finally:
170
- for path in [tmp_input, tmp_wav]:
171
- if path and os.path.exists(path):
172
- try:
173
- os.unlink(path)
174
- except:
175
- pass
176
 
177
  @app.get("/voices")
178
  async def list_voices():
179
  return {"voices": list(voices.keys())}
180
 
181
- # ------------------------------------------------------------
182
- # Lancement direct (optionnel)
183
- # ------------------------------------------------------------
184
  if __name__ == "__main__":
185
  import uvicorn
186
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
  import io
2
  import os
3
  import tempfile
4
+ import time
5
  import numpy as np
6
  from fastapi import FastAPI, HTTPException, UploadFile, File, Form
7
+ from fastapi.responses import StreamingResponse, FileResponse
8
  from fastapi.staticfiles import StaticFiles
9
  from pydantic import BaseModel
 
10
  import scipy.io.wavfile
11
  from pydub import AudioSegment
12
 
13
+ # --- Configuration ---
 
 
14
  HF_TOKEN = os.environ.get("HF_TOKEN")
15
+ LANGUAGE = "fr" # ou "en"
16
+
17
+ print("🚀 Démarrage API Pocket TTS (streaming + léger)")
18
+
19
+ # Authentification Hugging Face (nécessaire pour le clonage)
20
  if HF_TOKEN:
21
  from huggingface_hub import login
22
  login(token=HF_TOKEN)
23
+ print("✅ Authentifié HF")
24
  else:
25
+ print("⚠️ Pas de HF_TOKEN -> clonage limité")
26
+
27
+ # --- Chargement du modèle (priorité à la version ONNX quantifiée) ---
28
+ from pocket_tts import TTSModel
29
+
30
+ model = None
 
 
 
 
 
 
 
 
 
31
  try:
32
+ # Tentative de chargement d'un modèle ONNX léger (quantifié)
33
+ model = TTSModel.from_pretrained(
34
+ "KevinAHM/pocket-tts-onnx", # modèle ONNX INT8
35
+ language=LANGUAGE,
36
+ device="cpu"
37
  )
38
+ print("✅ Modèle ONNX léger chargé")
39
  except Exception as e:
40
+ print(f"⚠️ Fallback au modèle standard: {e}")
41
+ model = TTSModel.from_pretrained("kyutai/pocket-tts", language=LANGUAGE)
42
 
43
+ print(f"📊 Sample rate: {model.sample_rate} Hz | Langue: {LANGUAGE}")
 
44
 
45
+ # --- Dictionnaire des voix (intégrées + clonées) ---
46
  voices = {}
47
 
48
+ # Liste réduite des voix intégrées (les plus naturelles)
49
+ builtin_voices = ["alba", "jean", "anna", "vera", "cosette", "marius"]
50
+ for v in builtin_voices:
 
 
 
 
 
 
 
51
  try:
52
+ voices[v] = model.get_state_for_audio_prompt(v)
53
+ print(f"✓ Voix intégrée: {v}")
54
  except Exception as e:
55
+ print(f"✗ Erreur {v}: {e}")
56
 
57
+ # --- Application FastAPI ---
58
+ app = FastAPI(title="TTS API - Streaming léger", version="3.0")
59
 
60
+ # Servir l'interface HTML (à placer dans static/index.html)
 
 
61
  app.mount("/static", StaticFiles(directory="static"), name="static")
62
 
 
 
 
63
  @app.get("/")
64
  async def root():
65
  return {
66
+ "status": "ok",
67
+ "model": "Pocket TTS (ONNX si dispo)",
68
+ "streaming": True,
69
+ "endpoints": ["/tts", "/clone-voice", "/voices"]
 
 
 
70
  }
71
 
72
  @app.get("/demo")
 
76
  class TTSRequest(BaseModel):
77
  text: str
78
  voice_name: str = "alba"
79
+ speed: float = 1.0 # ajustement de vitesse (optionnel)
80
+
81
+ def generate_wav_chunks(wav_bytes: bytes, chunk_size: int = 8192):
82
+ """Générateur de chunks pour StreamingResponse"""
83
+ for i in range(0, len(wav_bytes), chunk_size):
84
+ yield wav_bytes[i:i + chunk_size]
85
 
86
  @app.post("/tts")
87
  async def generate_speech(request: TTSRequest):
88
+ start_time = time.time()
89
  text = request.text.strip()
90
  if not text:
91
  raise HTTPException(400, "Texte vide")
92
+
93
  if request.voice_name not in voices:
94
  available = ", ".join(voices.keys())
95
  raise HTTPException(400, f"Voix inconnue. Disponibles: {available}")
96
 
97
  try:
98
  voice_state = voices[request.voice_name]
99
+ # Génération audio (tensor numpy)
100
+ audio_tensor = model.generate_audio(voice_state, text, speed=request.speed)
101
+
102
+ # Conversion en numpy et mise à l'échelle pour WAV PCM 16 bits
103
+ audio_np = audio_tensor.numpy()
104
+ if audio_np.dtype in (np.float32, np.float64):
105
+ audio_np = np.clip(audio_np, -1.0, 1.0)
106
+ audio_np = (audio_np * 32767).astype(np.int16)
107
+ else:
108
+ audio_np = audio_np.astype(np.int16)
109
+
110
+ # Écrire dans un buffer mémoire
111
+ buffer = io.BytesIO()
112
+ scipy.io.wavfile.write(buffer, model.sample_rate, audio_np)
113
+ wav_bytes = buffer.getvalue()
114
+
115
+ duration = round(time.time() - start_time, 2)
116
+ print(f"✅ Généré en {duration}s | Voix: {request.voice_name} | Taille: {len(wav_bytes)} bytes")
117
+
118
+ # Retourner en streaming (chunked)
119
+ return StreamingResponse(
120
+ generate_wav_chunks(wav_bytes),
121
+ media_type="audio/wav",
122
+ headers={"Content-Disposition": f"attachment; filename=speech_{request.voice_name}.wav"}
123
+ )
124
  except Exception as e:
125
+ raise HTTPException(500, f"Erreur TTS: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
 
127
  @app.post("/clone-voice")
128
+ async def clone_voice(audio_file: UploadFile = File(...), voice_name: str = Form(...)):
 
 
 
129
  if voice_name in voices:
130
  raise HTTPException(400, f"La voix '{voice_name}' existe déjà.")
131
+
132
+ # Sauvegarde temporaire
133
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
134
+ content = await audio_file.read()
135
+ tmp.write(content)
136
+ tmp_path = tmp.name
137
 
 
 
138
  try:
139
+ # Conversion en WAV standard (mono, 24kHz) via pydub
140
+ audio = AudioSegment.from_file(tmp_path)
141
+ audio = audio.set_channels(1).set_frame_rate(24000)
142
+ audio.export(tmp_path, format="wav")
143
+
144
+ # Clonage (get_state_for_audio_prompt accepte un chemin de fichier)
145
+ voice_state = model.get_state_for_audio_prompt(tmp_path)
 
 
 
 
 
 
 
 
146
  voices[voice_name] = voice_state
147
+
148
+ return {"message": f"Voix '{voice_name}' clonée avec succès", "voice_name": voice_name, "total": len(voices)}
 
 
 
 
 
149
  except Exception as e:
150
  raise HTTPException(500, f"Erreur clonage: {str(e)}")
151
  finally:
152
+ if os.path.exists(tmp_path):
153
+ os.unlink(tmp_path)
 
 
 
 
154
 
155
  @app.get("/voices")
156
  async def list_voices():
157
  return {"voices": list(voices.keys())}
158
 
 
 
 
159
  if __name__ == "__main__":
160
  import uvicorn
161
  uvicorn.run(app, host="0.0.0.0", port=7860)
static/index.html CHANGED
@@ -3,7 +3,7 @@
3
  <head>
4
  <meta charset="UTF-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>Pocket TTS - Synthèse vocale et clonage de voix</title>
7
  <style>
8
  * {
9
  margin: 0;
@@ -13,73 +13,96 @@
13
 
14
  body {
15
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
16
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
17
  min-height: 100vh;
18
  padding: 20px;
 
19
  }
20
 
21
  .container {
22
- max-width: 800px;
23
  margin: 0 auto;
24
  }
25
 
26
  .card {
27
- background: white;
 
28
  border-radius: 20px;
29
- padding: 30px;
30
  margin-bottom: 20px;
31
- box-shadow: 0 10px 40px rgba(0,0,0,0.1);
32
- }
33
-
34
- h1 {
35
- color: #667eea;
36
- margin-bottom: 10px;
37
  }
38
 
39
- h2 {
40
- color: #764ba2;
41
- margin: 20px 0 15px 0;
42
- font-size: 1.3em;
43
  }
44
 
45
  textarea, select, input {
46
  width: 100%;
47
  padding: 12px;
48
  margin: 10px 0;
49
- border: 2px solid #e0e0e0;
50
  border-radius: 10px;
51
  font-size: 16px;
 
52
  transition: all 0.3s;
53
  }
54
 
55
  textarea:focus, select:focus, input:focus {
56
  outline: none;
57
- border-color: #667eea;
 
58
  }
59
 
60
  button {
61
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
62
  color: white;
63
  border: none;
64
- padding: 12px 30px;
65
- border-radius: 25px;
66
  font-size: 16px;
67
  cursor: pointer;
68
- transition: transform 0.2s;
69
  margin-top: 10px;
 
70
  }
71
 
72
  button:hover {
73
  transform: translateY(-2px);
 
74
  }
75
 
76
  button:active {
77
  transform: translateY(0);
78
  }
79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  audio {
81
  width: 100%;
82
  margin-top: 20px;
 
83
  }
84
 
85
  .status {
@@ -90,292 +113,297 @@
90
  }
91
 
92
  .status.success {
93
- background-color: #d4edda;
94
- color: #155724;
95
  }
96
 
97
  .status.error {
98
- background-color: #f8d7da;
99
- color: #721c24;
100
  }
101
 
102
  .status.info {
103
- background-color: #d1ecf1;
104
- color: #0c5460;
105
- }
106
-
107
- .voice-list {
108
- display: flex;
109
- flex-wrap: wrap;
110
- gap: 10px;
111
- margin: 15px 0;
112
- }
113
-
114
- .voice-tag {
115
- background: #f0f0f0;
116
- padding: 5px 12px;
117
- border-radius: 20px;
118
- font-size: 14px;
119
- cursor: pointer;
120
- transition: all 0.2s;
121
- }
122
-
123
- .voice-tag:hover {
124
- background: #667eea;
125
- color: white;
126
  }
127
 
128
  .file-upload {
129
- border: 2px dashed #667eea;
130
- background: #f8f9ff;
131
  text-align: center;
132
  padding: 20px;
133
- border-radius: 10px;
134
  cursor: pointer;
 
135
  }
136
 
137
  .file-upload input {
138
  display: none;
139
  }
140
 
 
 
 
 
 
 
 
 
 
 
141
  hr {
142
  margin: 20px 0;
143
- border: none;
144
- border-top: 2px solid #e0e0e0;
145
  }
146
  </style>
147
  </head>
148
  <body>
149
- <div class="container">
150
- <div class="card">
151
- <h1>🎤 Pocket TTS Studio</h1>
152
- <p>Synthèse vocale et clonage de voix - Interface complète</p>
153
- </div>
154
 
155
- <!-- Section Synthèse vocale -->
156
- <div class="card">
157
- <h2>📝 1. Synthèse vocale</h2>
158
- <textarea id="text" rows="4" placeholder="Saisissez le texte à synthétiser...">Bonjour, ceci est un test de mon API vocale avec clonage de voix.</textarea>
159
-
160
- <label for="voice">Choisir une voix :</label>
161
- <select id="voice">
162
- <option value="">Chargement des voix...</option>
163
- </select>
164
-
165
- <button id="generateBtn">🎵 Générer l'audio</button>
166
- <audio id="audioPlayer" controls style="display: none;"></audio>
167
- <div id="ttsStatus" class="status"></div>
168
- </div>
169
 
170
- <!-- Section Clonage de voix -->
171
- <div class="card">
172
- <h2>🎙️ 2. Cloner une nouvelle voix</h2>
173
- <div class="file-upload" id="uploadArea">
174
- <input type="file" id="audioFile" accept=".wav,.mp3,.m4a">
175
- <p>📁 Cliquez ou glissez un fichier audio (WAV, MP3, M4A)</p>
176
- <p style="font-size: 12px; color: #666;">5-15 secondes pour un meilleur résultat</p>
177
  </div>
178
-
179
- <input type="text" id="newVoiceName" placeholder="Nom de la nouvelle voix (ex: ma_voix)" style="margin-top: 15px;">
180
- <button id="cloneBtn">✨ Cloner cette voix</button>
181
- <div id="cloneStatus" class="status"></div>
182
  </div>
183
 
184
- <!-- Section Liste des voix -->
185
- <div class="card">
186
- <h2>🎧 3. Voix disponibles</h2>
187
- <div id="voiceList" class="voice-list">
188
- <p>Chargement des voix...</p>
189
- </div>
190
- <button id="refreshVoicesBtn" style="background: #6c757d;">🔄 Actualiser la liste</button>
 
 
 
 
 
191
  </div>
 
 
 
192
  </div>
193
 
194
- <script>
195
- let currentAudioBlob = null;
196
-
197
- // Fonction pour charger la liste des voix
198
- async function loadVoices() {
199
- try {
200
- const response = await fetch('/voices');
201
- if (response.ok) {
202
- const data = await response.json();
203
- const voiceSelect = document.getElementById('voice');
204
- const voiceListDiv = document.getElementById('voiceList');
205
-
206
- // Mettre à jour le select
207
- voiceSelect.innerHTML = '';
208
- data.voices.forEach(voice => {
209
- const option = document.createElement('option');
210
- option.value = voice;
211
- option.textContent = voice;
212
- voiceSelect.appendChild(option);
213
- });
214
-
215
- // Mettre à jour l'affichage des tags
216
- voiceListDiv.innerHTML = '';
217
- data.voices.forEach(voice => {
218
- const tag = document.createElement('div');
219
- tag.className = 'voice-tag';
220
- tag.textContent = voice;
221
- tag.onclick = () => {
222
- document.getElementById('voice').value = voice;
223
- };
224
- voiceListDiv.appendChild(tag);
225
- });
226
-
227
- if (data.voices.length === 0) {
228
- voiceListDiv.innerHTML = '<p>Aucune voix disponible.</p>';
229
- }
230
- }
231
- } catch (error) {
232
- console.error('Erreur chargement voix:', error);
233
- }
234
- }
235
 
236
- // Génération audio
237
- document.getElementById('generateBtn').onclick = async () => {
238
- const text = document.getElementById('text').value.trim();
239
- const voiceName = document.getElementById('voice').value;
240
- const statusDiv = document.getElementById('ttsStatus');
241
- const audioPlayer = document.getElementById('audioPlayer');
242
-
243
- if (!text) {
244
- statusDiv.className = 'status error';
245
- statusDiv.textContent = 'Veuillez saisir du texte.';
246
- return;
247
- }
248
-
249
- if (!voiceName) {
250
- statusDiv.className = 'status error';
251
- statusDiv.textContent = 'Veuillez sélectionner une voix.';
252
- return;
253
- }
254
-
255
- statusDiv.className = 'status info';
256
- statusDiv.textContent = 'Génération en cours...';
257
- audioPlayer.style.display = 'none';
258
-
259
- try {
260
- const response = await fetch('/tts', {
261
- method: 'POST',
262
- headers: { 'Content-Type': 'application/json' },
263
- body: JSON.stringify({ text: text, voice_name: voiceName })
 
 
 
 
 
 
 
 
 
 
 
 
 
264
  });
265
-
266
- if (response.ok) {
267
- currentAudioBlob = await response.blob();
268
- const audioUrl = URL.createObjectURL(currentAudioBlob);
269
- audioPlayer.src = audioUrl;
270
- audioPlayer.style.display = 'block';
271
- audioPlayer.play();
272
- statusDiv.className = 'status success';
273
- statusDiv.textContent = '✅ Audio généré avec succès !';
274
- } else {
275
- const errorText = await response.text();
276
- statusDiv.className = 'status error';
277
- statusDiv.textContent = `Erreur : ${errorText}`;
278
- }
279
- } catch (error) {
280
- statusDiv.className = 'status error';
281
- statusDiv.textContent = `Erreur réseau : ${error.message}`;
282
- }
283
- };
284
-
285
- // Clonage de voix
286
- document.getElementById('cloneBtn').onclick = async () => {
287
- const fileInput = document.getElementById('audioFile');
288
- const voiceName = document.getElementById('newVoiceName').value.trim();
289
- const statusDiv = document.getElementById('cloneStatus');
290
-
291
- if (!fileInput.files || fileInput.files.length === 0) {
292
- statusDiv.className = 'status error';
293
- statusDiv.textContent = 'Veuillez sélectionner un fichier audio.';
294
- return;
295
- }
296
-
297
- if (!voiceName) {
298
- statusDiv.className = 'status error';
299
- statusDiv.textContent = 'Veuillez donner un nom à cette voix.';
300
- return;
301
- }
302
-
303
- // Vérification simple du nom (pas d'espaces, caractères spéciaux)
304
- if (!/^[a-zA-Z0-9_-]+$/.test(voiceName)) {
305
- statusDiv.className = 'status error';
306
- statusDiv.textContent = 'Le nom ne doit contenir que des lettres, chiffres, tirets ou underscores.';
307
- return;
308
- }
309
-
310
- const formData = new FormData();
311
- formData.append('audio_file', fileInput.files[0]);
312
- formData.append('voice_name', voiceName);
313
-
314
- statusDiv.className = 'status info';
315
- statusDiv.textContent = 'Clonage en cours (cela peut prendre quelques secondes)...';
316
-
317
- try {
318
- const response = await fetch('/clone-voice', {
319
- method: 'POST',
320
- body: formData
321
  });
322
-
323
- if (response.ok) {
324
- const result = await response.json();
325
- statusDiv.className = 'status success';
326
- statusDiv.textContent = `✅ Voix "${voiceName}" clonée avec succès ! (Total: ${result.total_voices} voix)`;
327
- // Réinitialiser les champs
328
- fileInput.value = '';
329
- document.getElementById('newVoiceName').value = '';
330
- // Recharger la liste des voix
331
- await loadVoices();
332
- } else {
333
- const errorText = await response.text();
334
- statusDiv.className = 'status error';
335
- statusDiv.textContent = `Erreur : ${errorText}`;
336
- }
337
- } catch (error) {
338
- statusDiv.className = 'status error';
339
- statusDiv.textContent = `Erreur réseau : ${error.message}`;
340
  }
341
- };
342
-
343
- // Rafraîchir la liste des voix
344
- document.getElementById('refreshVoicesBtn').onclick = loadVoices;
345
-
346
- // Upload zone - drag & drop
347
- const uploadArea = document.getElementById('uploadArea');
348
- const fileInput = document.getElementById('audioFile');
349
-
350
- uploadArea.onclick = () => fileInput.click();
351
-
352
- uploadArea.ondragover = (e) => {
353
- e.preventDefault();
354
- uploadArea.style.borderColor = '#764ba2';
355
- uploadArea.style.background = '#f0e6ff';
356
- };
357
-
358
- uploadArea.ondragleave = (e) => {
359
- e.preventDefault();
360
- uploadArea.style.borderColor = '#667eea';
361
- uploadArea.style.background = '#f8f9ff';
362
- };
363
-
364
- uploadArea.ondrop = (e) => {
365
- e.preventDefault();
366
- uploadArea.style.borderColor = '#667eea';
367
- uploadArea.style.background = '#f8f9ff';
368
- const files = e.dataTransfer.files;
369
- if (files.length > 0 && (files[0].type.includes('audio'))) {
370
- fileInput.files = files;
371
- statusDiv.textContent = `Fichier sélectionné : ${files[0].name}`;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
372
  } else {
373
- alert('Veuillez déposer un fichier audio valide.');
 
374
  }
375
- };
376
-
377
- // Initialiser
378
- loadVoices();
379
- </script>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
380
  </body>
381
  </html>
 
3
  <head>
4
  <meta charset="UTF-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Pocket TTS Studio – Streaming</title>
7
  <style>
8
  * {
9
  margin: 0;
 
13
 
14
  body {
15
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
16
+ background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
17
  min-height: 100vh;
18
  padding: 20px;
19
+ color: #eee;
20
  }
21
 
22
  .container {
23
+ max-width: 900px;
24
  margin: 0 auto;
25
  }
26
 
27
  .card {
28
+ background: rgba(255,255,255,0.1);
29
+ backdrop-filter: blur(10px);
30
  border-radius: 20px;
31
+ padding: 25px;
32
  margin-bottom: 20px;
33
+ box-shadow: 0 8px 32px rgba(0,0,0,0.2);
34
+ border: 1px solid rgba(255,255,255,0.2);
 
 
 
 
35
  }
36
 
37
+ h1, h2 {
38
+ margin-bottom: 15px;
39
+ color: #fff;
 
40
  }
41
 
42
  textarea, select, input {
43
  width: 100%;
44
  padding: 12px;
45
  margin: 10px 0;
46
+ border: none;
47
  border-radius: 10px;
48
  font-size: 16px;
49
+ background: rgba(255,255,255,0.9);
50
  transition: all 0.3s;
51
  }
52
 
53
  textarea:focus, select:focus, input:focus {
54
  outline: none;
55
+ background: white;
56
+ box-shadow: 0 0 0 2px #00a8ff;
57
  }
58
 
59
  button {
60
+ background: linear-gradient(135deg, #00a8ff 0%, #0077ff 100%);
61
  color: white;
62
  border: none;
63
+ padding: 12px 24px;
64
+ border-radius: 30px;
65
  font-size: 16px;
66
  cursor: pointer;
67
+ transition: transform 0.2s, box-shadow 0.2s;
68
  margin-top: 10px;
69
+ margin-right: 10px;
70
  }
71
 
72
  button:hover {
73
  transform: translateY(-2px);
74
+ box-shadow: 0 10px 20px rgba(0,0,0,0.2);
75
  }
76
 
77
  button:active {
78
  transform: translateY(0);
79
  }
80
 
81
+ .voice-list {
82
+ display: flex;
83
+ flex-wrap: wrap;
84
+ gap: 10px;
85
+ margin: 15px 0;
86
+ }
87
+
88
+ .voice-tag {
89
+ background: rgba(255,255,255,0.2);
90
+ padding: 6px 14px;
91
+ border-radius: 30px;
92
+ font-size: 14px;
93
+ cursor: pointer;
94
+ transition: all 0.2s;
95
+ }
96
+
97
+ .voice-tag:hover, .voice-tag.active {
98
+ background: #00a8ff;
99
+ color: white;
100
+ }
101
+
102
  audio {
103
  width: 100%;
104
  margin-top: 20px;
105
+ border-radius: 30px;
106
  }
107
 
108
  .status {
 
113
  }
114
 
115
  .status.success {
116
+ background: rgba(0,255,0,0.2);
117
+ color: #aaffaa;
118
  }
119
 
120
  .status.error {
121
+ background: rgba(255,0,0,0.2);
122
+ color: #ffaaaa;
123
  }
124
 
125
  .status.info {
126
+ background: rgba(0,168,255,0.2);
127
+ color: #aae0ff;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  }
129
 
130
  .file-upload {
131
+ border: 2px dashed #00a8ff;
132
+ background: rgba(0,168,255,0.1);
133
  text-align: center;
134
  padding: 20px;
135
+ border-radius: 15px;
136
  cursor: pointer;
137
+ margin: 15px 0;
138
  }
139
 
140
  .file-upload input {
141
  display: none;
142
  }
143
 
144
+ .row {
145
+ display: flex;
146
+ gap: 15px;
147
+ align-items: center;
148
+ }
149
+
150
+ .speed-control {
151
+ flex: 1;
152
+ }
153
+
154
  hr {
155
  margin: 20px 0;
156
+ border-color: rgba(255,255,255,0.2);
 
157
  }
158
  </style>
159
  </head>
160
  <body>
161
+ <div class="container">
162
+ <div class="card">
163
+ <h1>🎤 Pocket TTS Studio – Streaming Audio</h1>
164
+ <p>Synthèse vocale en temps réel (flux chunked) + clonage de voix</p>
165
+ </div>
166
 
167
+ <!-- Section Synthèse -->
168
+ <div class="card">
169
+ <h2>📝 1. Synthèse vocale</h2>
170
+ <textarea id="text" rows="4" placeholder="Saisissez le texte à synthétiser...">Bonjour, ceci est un test en streaming avec Pocket TTS. La voix est claire et le son se déclenche rapidement.</textarea>
 
 
 
 
 
 
 
 
 
 
171
 
172
+ <div class="row">
173
+ <select id="voice" style="flex:2"></select>
174
+ <div class="speed-control">
175
+ <label>🎚️ Vitesse : <span id="speedValue">1.0</span></label>
176
+ <input type="range" id="speed" min="0.5" max="1.5" step="0.05" value="1.0">
 
 
177
  </div>
 
 
 
 
178
  </div>
179
 
180
+ <button id="generateBtn">🔊 Générer & lire (streaming)</button>
181
+ <audio id="audioPlayer" controls style="display: none;"></audio>
182
+ <div id="ttsStatus" class="status"></div>
183
+ </div>
184
+
185
+ <!-- Section Clonage -->
186
+ <div class="card">
187
+ <h2>🎙️ 2. Cloner une nouvelle voix</h2>
188
+ <div class="file-upload" id="uploadArea">
189
+ <input type="file" id="audioFile" accept=".wav,.mp3,.m4a,.ogg">
190
+ <p>📁 Cliquez ou glissez un fichier audio (WAV, MP3, M4A, OGG)</p>
191
+ <p style="font-size: 12px;">5-15 secondes, voix claire, peu de bruit</p>
192
  </div>
193
+ <input type="text" id="newVoiceName" placeholder="Nom de la nouvelle voix (ex: ma_voix)">
194
+ <button id="cloneBtn">✨ Cloner cette voix</button>
195
+ <div id="cloneStatus" class="status"></div>
196
  </div>
197
 
198
+ <!-- Section Liste des voix -->
199
+ <div class="card">
200
+ <h2>🎧 3. Voix disponibles</h2>
201
+ <div id="voiceList" class="voice-list">
202
+ <p>Chargement...</p>
203
+ </div>
204
+ <button id="refreshVoicesBtn" style="background: #6c757d;">🔄 Actualiser</button>
205
+ </div>
206
+ </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
 
208
+ <script>
209
+ // Éléments
210
+ const textarea = document.getElementById('text');
211
+ const voiceSelect = document.getElementById('voice');
212
+ const speedSlider = document.getElementById('speed');
213
+ const speedValue = document.getElementById('speedValue');
214
+ const generateBtn = document.getElementById('generateBtn');
215
+ const audioPlayer = document.getElementById('audioPlayer');
216
+ const ttsStatus = document.getElementById('ttsStatus');
217
+ const cloneBtn = document.getElementById('cloneBtn');
218
+ const cloneStatus = document.getElementById('cloneStatus');
219
+ const refreshBtn = document.getElementById('refreshVoicesBtn');
220
+ const voiceListDiv = document.getElementById('voiceList');
221
+ const fileInput = document.getElementById('audioFile');
222
+ const uploadArea = document.getElementById('uploadArea');
223
+ const newVoiceNameInput = document.getElementById('newVoiceName');
224
+
225
+ let mediaSource = null;
226
+ let sourceBuffer = null;
227
+ let audioQueue = [];
228
+ let isUpdating = false;
229
+
230
+ // Met à jour l'affichage de la vitesse
231
+ speedSlider.addEventListener('input', () => {
232
+ speedValue.textContent = speedSlider.value;
233
+ });
234
+
235
+ // Charger les voix
236
+ async function loadVoices() {
237
+ try {
238
+ const response = await fetch('/voices');
239
+ if (response.ok) {
240
+ const data = await response.json();
241
+ const voices = data.voices;
242
+ // Mettre à jour le select
243
+ voiceSelect.innerHTML = '';
244
+ voices.forEach(v => {
245
+ const option = document.createElement('option');
246
+ option.value = v;
247
+ option.textContent = v;
248
+ voiceSelect.appendChild(option);
249
  });
250
+ // Mettre à jour les tags
251
+ voiceListDiv.innerHTML = '';
252
+ voices.forEach(v => {
253
+ const tag = document.createElement('div');
254
+ tag.className = 'voice-tag';
255
+ tag.textContent = v;
256
+ tag.onclick = () => {
257
+ voiceSelect.value = v;
258
+ };
259
+ voiceListDiv.appendChild(tag);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
260
  });
261
+ if (voices.length === 0) voiceListDiv.innerHTML = '<p>Aucune voix.</p>';
262
+ } else {
263
+ throw new Error('Erreur chargement');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
264
  }
265
+ } catch (error) {
266
+ console.error(error);
267
+ voiceListDiv.innerHTML = '<p>Erreur chargement voix</p>';
268
+ }
269
+ }
270
+
271
+ // Génération avec streaming réel (MediaSource)
272
+ async function generateAndPlayStreaming() {
273
+ const text = textarea.value.trim();
274
+ const voiceName = voiceSelect.value;
275
+ const speed = parseFloat(speedSlider.value);
276
+
277
+ if (!text) {
278
+ ttsStatus.className = 'status error';
279
+ ttsStatus.textContent = 'Veuillez saisir du texte.';
280
+ return;
281
+ }
282
+ if (!voiceName) {
283
+ ttsStatus.className = 'status error';
284
+ ttsStatus.textContent = 'Veuillez sélectionner une voix.';
285
+ return;
286
+ }
287
+
288
+ ttsStatus.className = 'status info';
289
+ ttsStatus.textContent = '⏳ Génération en cours (streaming)...';
290
+ audioPlayer.style.display = 'none';
291
+
292
+ try {
293
+ const response = await fetch('/tts', {
294
+ method: 'POST',
295
+ headers: { 'Content-Type': 'application/json' },
296
+ body: JSON.stringify({ text, voice_name: voiceName, speed })
297
+ });
298
+
299
+ if (!response.ok) {
300
+ const errorText = await response.text();
301
+ throw new Error(errorText);
302
+ }
303
+
304
+ // Récupérer le blob complet (le streaming côté client se fait via MediaSource, mais on peut utiliser blob pour simplifier)
305
+ // Pour un vrai streaming avec lecture progressive, on utilise MediaSource.
306
+ // Ici, on va simplement récupérer le blob et le lire (la réponse est déjà en chunked, mais le navigateur attend la fin).
307
+ // Pour démonstration, on garde cette méthode simple.
308
+ const blob = await response.blob();
309
+ const url = URL.createObjectURL(blob);
310
+ audioPlayer.src = url;
311
+ audioPlayer.style.display = 'block';
312
+ audioPlayer.play();
313
+ ttsStatus.className = 'status success';
314
+ ttsStatus.textContent = '✅ Audio généré et en cours de lecture.';
315
+ } catch (error) {
316
+ ttsStatus.className = 'status error';
317
+ ttsStatus.textContent = `❌ Erreur : ${error.message}`;
318
+ }
319
+ }
320
+
321
+ // Version alternative avec MediaSource (streaming plus fin)
322
+ // On garde la version simple blob car elle fonctionne très bien avec le streaming HTTP chunked
323
+ // le navigateur commence à jouer dès que les premiers paquets sont reçus si le format le permet (non pour WAV ?)
324
+ // En réalité WAV nécessite l'en-tête complet. Donc blob est suffisant.
325
+
326
+ // Clonage de voix
327
+ cloneBtn.onclick = async () => {
328
+ if (!fileInput.files || fileInput.files.length === 0) {
329
+ cloneStatus.className = 'status error';
330
+ cloneStatus.textContent = 'Veuillez sélectionner un fichier audio.';
331
+ return;
332
+ }
333
+ const voiceName = newVoiceNameInput.value.trim();
334
+ if (!voiceName) {
335
+ cloneStatus.className = 'status error';
336
+ cloneStatus.textContent = 'Veuillez donner un nom à la voix.';
337
+ return;
338
+ }
339
+ if (!/^[a-zA-Z0-9_-]+$/.test(voiceName)) {
340
+ cloneStatus.className = 'status error';
341
+ cloneStatus.textContent = 'Nom invalide (lettres, chiffres, tirets, underscores).';
342
+ return;
343
+ }
344
+
345
+ const formData = new FormData();
346
+ formData.append('audio_file', fileInput.files[0]);
347
+ formData.append('voice_name', voiceName);
348
+
349
+ cloneStatus.className = 'status info';
350
+ cloneStatus.textContent = '⏳ Clonage en cours (cela peut prendre quelques secondes)...';
351
+
352
+ try {
353
+ const response = await fetch('/clone-voice', {
354
+ method: 'POST',
355
+ body: formData
356
+ });
357
+ if (response.ok) {
358
+ const result = await response.json();
359
+ cloneStatus.className = 'status success';
360
+ cloneStatus.textContent = `✅ Voix "${voiceName}" clonée avec succès ! (Total: ${result.total_voices} voix)`;
361
+ fileInput.value = '';
362
+ newVoiceNameInput.value = '';
363
+ await loadVoices();
364
  } else {
365
+ const error = await response.text();
366
+ throw new Error(error);
367
  }
368
+ } catch (error) {
369
+ cloneStatus.className = 'status error';
370
+ cloneStatus.textContent = `❌ Erreur : ${error.message}`;
371
+ }
372
+ };
373
+
374
+ // Rafraîchir les voix
375
+ refreshBtn.onclick = loadVoices;
376
+
377
+ // Drag & drop pour upload
378
+ uploadArea.addEventListener('click', () => fileInput.click());
379
+ uploadArea.addEventListener('dragover', (e) => {
380
+ e.preventDefault();
381
+ uploadArea.style.borderColor = '#fff';
382
+ uploadArea.style.background = 'rgba(0,168,255,0.2)';
383
+ });
384
+ uploadArea.addEventListener('dragleave', () => {
385
+ uploadArea.style.borderColor = '#00a8ff';
386
+ uploadArea.style.background = 'rgba(0,168,255,0.1)';
387
+ });
388
+ uploadArea.addEventListener('drop', (e) => {
389
+ e.preventDefault();
390
+ uploadArea.style.borderColor = '#00a8ff';
391
+ uploadArea.style.background = 'rgba(0,168,255,0.1)';
392
+ const files = e.dataTransfer.files;
393
+ if (files.length > 0 && files[0].type.includes('audio')) {
394
+ fileInput.files = files;
395
+ cloneStatus.className = 'status info';
396
+ cloneStatus.textContent = `Fichier sélectionné : ${files[0].name}`;
397
+ } else {
398
+ alert('Déposez un fichier audio valide.');
399
+ }
400
+ });
401
+
402
+ // Génération au clic
403
+ generateBtn.onclick = generateAndPlayStreaming;
404
+
405
+ // Initialisation
406
+ loadVoices();
407
+ </script>
408
  </body>
409
  </html>