-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi_example.html
More file actions
513 lines (458 loc) · 18.2 KB
/
Copy pathapi_example.html
File metadata and controls
513 lines (458 loc) · 18.2 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
<!-- MIT License
Copyright (c) 2024-2026 Mateusz Dera
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WhisperSpeech web UI API Client</title>
<style>
body {
max-width: 800px;
margin: 0 auto;
padding: 20px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}
form {
display: flex;
flex-direction: column;
gap: 15px;
}
label {
font-weight: bold;
margin-bottom: 5px;
}
input, select, button, textarea {
padding: 8px;
font-size: 16px;
border: 1px solid #ddd;
border-radius: 4px;
}
button {
cursor: pointer;
background-color: #007bff;
color: white;
border: none;
padding: 12px;
font-weight: bold;
}
button:hover {
background-color: #0056b3;
}
button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
.row {
display: flex;
gap: 10px;
}
.row > div {
flex: 1;
}
.row input {
width: 100%;
box-sizing: border-box;
}
.button-row {
display: flex;
gap: 10px;
}
.button-row button {
flex: 1;
}
#cancelBtn {
background-color: #dc3545;
display: none;
}
#cancelBtn:hover {
background-color: #c82333;
}
#audioControls {
display: none;
margin-top: 20px;
border: 1px solid #ddd;
padding: 15px;
border-radius: 5px;
background-color: #f9f9f9;
}
#downloadBtn {
background-color: #28a745;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
margin-top: 10px;
}
#downloadBtn:hover {
background-color: #218838;
}
#downloadBtn:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
.audio-info {
margin-top: 10px;
font-size: 14px;
color: #666;
}
.voice-section {
border: 1px solid #e0e0e0;
padding: 15px;
border-radius: 5px;
background-color: #fafafa;
}
.voice-section h3 {
margin-top: 0;
margin-bottom: 10px;
color: #333;
}
.file-input-wrapper {
position: relative;
display: inline-block;
cursor: pointer;
width: 100%;
}
.file-input-wrapper input[type=file] {
position: absolute;
left: -9999px;
}
.file-input-display {
display: block;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
background-color: white;
cursor: pointer;
min-height: 20px;
}
.file-input-display:hover {
background-color: #f8f9fa;
}
.file-selected {
color: #28a745;
}
.file-placeholder {
color: #6c757d;
}
.clear-file-btn {
background-color: #dc3545;
color: white;
border: none;
padding: 5px 10px;
border-radius: 3px;
cursor: pointer;
font-size: 12px;
margin-top: 5px;
}
.clear-file-btn:hover {
background-color: #c82333;
}
.note {
font-size: 12px;
color: #666;
margin-top: 5px;
font-style: italic;
}
.status-message {
padding: 10px;
border-radius: 4px;
margin-top: 10px;
display: none;
}
.status-message.info {
background-color: #d1ecf1;
border: 1px solid #bee5eb;
color: #0c5460;
}
.status-message.success {
background-color: #d4edda;
border: 1px solid #c3e6cb;
color: #155724;
}
.status-message.error {
background-color: #f8d7da;
border: 1px solid #f5c6cb;
color: #721c24;
}
.status-message.warning {
background-color: #fff3cd;
border: 1px solid #ffeaa7;
color: #856404;
}
</style>
</head>
<body>
<h1>WhisperSpeech API Client</h1>
<form id="ttsForm">
<div class="row">
<div>
<label for="ip">IP Address:</label>
<input type="text" id="ip" value="localhost" required>
</div>
<div>
<label for="port">Port:</label>
<input type="number" id="port" value="5050" required>
</div>
</div>
<label for="text">Text:</label>
<textarea id="text" rows="4" placeholder="English is the default language and does not require a tag if used standalone.
Multiple languages:
<pl>To jest tekst w języku polskim.<en> And this is text in English" required></textarea>
<label for="speed">Speed (characters per second):</label>
<input type="number" id="speed" min="10" max="15" step="0.25" value="13.5" required>
<label for="format">Audio Format:</label>
<select id="format" required>
<option value="wav">WAV</option>
<option value="mp3">MP3</option>
<option value="ogg">OGG</option>
</select>
<label for="model">Model:</label>
<select id="model" required>
<option value="tiny" selected>Tiny</option>
<option value="small">Small</option>
<option value="base">Base</option>
</select>
<div class="voice-section">
<h3>Voice Cloning (Optional)</h3>
<label for="voiceFile">Upload Voice Sample:</label>
<div class="file-input-wrapper">
<input type="file" id="voiceFile" accept=".mp3,.wav,.ogg,audio/*">
<div class="file-input-display" id="fileDisplay">
<span class="file-placeholder">Click to select an audio file (MP3, WAV, OGG)</span>
</div>
</div>
<button type="button" class="clear-file-btn" id="clearFileBtn" style="display: none;">Remove File</button>
<div class="note">Upload a short audio sample (3-10 seconds) of the voice you want to clone. The quality and clarity of the sample will affect the cloning results.</div>
</div>
<div class="button-row">
<button type="submit" id="generateBtn">Generate Audio</button>
<button type="button" id="cancelBtn">Cancel</button>
</div>
</form>
<div class="status-message" id="statusMessage"></div>
<div id="audioControls">
<audio id="audioPlayer" controls style="width: 100%;"></audio>
<button id="downloadBtn" disabled>Download Audio</button>
<div class="audio-info" id="audioInfo"></div>
</div>
<script>
const form = document.getElementById('ttsForm');
const audioPlayer = document.getElementById('audioPlayer');
const audioControls = document.getElementById('audioControls');
const downloadBtn = document.getElementById('downloadBtn');
const audioInfo = document.getElementById('audioInfo');
const voiceFileInput = document.getElementById('voiceFile');
const fileDisplay = document.getElementById('fileDisplay');
const clearFileBtn = document.getElementById('clearFileBtn');
const generateBtn = document.getElementById('generateBtn');
const cancelBtn = document.getElementById('cancelBtn');
const statusMessage = document.getElementById('statusMessage');
let currentBlob = null;
let currentFormat = null;
let currentTaskId = null;
let abortController = null;
function showStatus(message, type = 'info') {
statusMessage.textContent = message;
statusMessage.className = `status-message ${type}`;
statusMessage.style.display = 'block';
}
function hideStatus() {
statusMessage.style.display = 'none';
}
// Handle file input display
voiceFileInput.addEventListener('change', function(e) {
const file = e.target.files[0];
if (file) {
fileDisplay.innerHTML = `<span class="file-selected">📁 ${file.name} (${(file.size / 1024 / 1024).toFixed(2)} MB)</span>`;
clearFileBtn.style.display = 'inline-block';
} else {
resetFileDisplay();
}
});
// Handle file display click
fileDisplay.addEventListener('click', function() {
voiceFileInput.click();
});
// Handle clear file button
clearFileBtn.addEventListener('click', function() {
voiceFileInput.value = '';
resetFileDisplay();
});
function resetFileDisplay() {
fileDisplay.innerHTML = '<span class="file-placeholder">Click to select an audio file (MP3, WAV, OGG)</span>';
clearFileBtn.style.display = 'none';
}
// Validate file type
function isValidAudioFile(file) {
const validTypes = ['audio/mpeg', 'audio/wav', 'audio/ogg', 'audio/mp3'];
const validExtensions = ['.mp3', '.wav', '.ogg'];
return validTypes.includes(file.type) ||
validExtensions.some(ext => file.name.toLowerCase().endsWith(ext));
}
// Handle cancel button
cancelBtn.addEventListener('click', async function() {
if (abortController) {
abortController.abort();
showStatus('Generation cancelled by user', 'warning');
}
if (currentTaskId) {
try {
const ip = document.getElementById('ip').value;
const port = document.getElementById('port').value;
const cancelUrl = `http://${ip}:${port}/cancel/${currentTaskId}`;
await fetch(cancelUrl, { method: 'POST' });
showStatus('Cancellation request sent to server', 'warning');
} catch (error) {
console.error('Error sending cancel request:', error);
}
}
// Reset UI state
generateBtn.disabled = false;
generateBtn.textContent = 'Generate Audio';
cancelBtn.style.display = 'none';
downloadBtn.disabled = true;
downloadBtn.textContent = 'Download Audio';
currentTaskId = null;
abortController = null;
});
form.addEventListener('submit', async (e) => {
e.preventDefault();
const ip = document.getElementById('ip').value;
const port = document.getElementById('port').value;
const text = document.getElementById('text').value;
const speed = document.getElementById('speed').value;
const format = document.getElementById('format').value;
const model = document.getElementById('model').value;
const voiceFile = voiceFileInput.files[0];
// Validate voice file if provided
if (voiceFile && !isValidAudioFile(voiceFile)) {
showStatus('Please select a valid audio file (MP3, WAV, or OGG).', 'error');
return;
}
const apiUrl = `http://${ip}:${port}/generate`;
// Create abort controller for cancellation
abortController = new AbortController();
// Update UI for generation state
generateBtn.disabled = true;
generateBtn.textContent = 'Generating...';
cancelBtn.style.display = 'block';
downloadBtn.disabled = true;
downloadBtn.textContent = 'Generating...';
hideStatus();
showStatus('Starting audio generation...', 'info');
try {
let requestBody;
let requestHeaders = {};
if (voiceFile) {
// Use FormData for file upload
requestBody = new FormData();
requestBody.append('text', text);
requestBody.append('speed', speed);
requestBody.append('format', format);
requestBody.append('model', model);
requestBody.append('voice', voiceFile);
// Don't set Content-Type header for FormData - let browser set it with boundary
} else {
// Use JSON for text-only request
requestHeaders['Content-Type'] = 'application/json';
requestBody = JSON.stringify({
text,
speed: parseFloat(speed),
format,
model
});
}
const response = await fetch(apiUrl, {
method: 'POST',
headers: requestHeaders,
body: requestBody,
signal: abortController.signal
});
// Extract task ID from response headers
currentTaskId = response.headers.get('X-Task-ID');
if (response.ok) {
currentBlob = await response.blob();
currentFormat = format;
const url = URL.createObjectURL(currentBlob);
audioPlayer.src = url;
audioControls.style.display = 'block';
audioPlayer.play();
// Enable download button
downloadBtn.disabled = false;
downloadBtn.textContent = `Download ${format.toUpperCase()}`;
// Show file info
const fileSizeKB = (currentBlob.size / 1024).toFixed(2);
const voiceInfo = voiceFile ? ` | Voice: ${voiceFile.name}` : ' | Voice: Default';
audioInfo.innerHTML = `Size: ${fileSizeKB} KB | Format: ${format.toUpperCase()}${voiceInfo}`;
showStatus('Audio generated successfully!', 'success');
// Auto-hide success message after 3 seconds
setTimeout(() => {
hideStatus();
}, 3000);
} else if (response.status === 499) {
// Task was cancelled
const errorData = await response.json();
showStatus(`Generation cancelled: ${errorData.error || 'Unknown error'}`, 'warning');
} else {
const errorText = await response.text();
throw new Error(`Server error: ${response.status} - ${errorText}`);
}
} catch (error) {
console.error('Error:', error);
if (error.name === 'AbortError') {
showStatus('Generation cancelled by user', 'warning');
} else {
showStatus(`Error generating audio: ${error.message}\n\nPlease check the API address and try again.`, 'error');
}
audioInfo.innerHTML = '';
} finally {
// Reset UI state
generateBtn.disabled = false;
generateBtn.textContent = 'Generate Audio';
cancelBtn.style.display = 'none';
if (downloadBtn.textContent === 'Generating...') {
downloadBtn.textContent = 'Download Audio';
}
currentTaskId = null;
abortController = null;
}
});
downloadBtn.addEventListener('click', () => {
if (currentBlob && currentFormat) {
// Create download link
const url = URL.createObjectURL(currentBlob);
const a = document.createElement('a');
a.href = url;
// Generate filename with timestamp
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').split('T')[0] + '_' +
new Date().toTimeString().split(' ')[0].replace(/:/g, '-');
a.download = `whisperspeech_${timestamp}.${currentFormat}`;
// Trigger download
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
// Clean up
setTimeout(() => URL.revokeObjectURL(url), 100);
}
});
</script>
</body>
</html>