forked from devnen/Chatterbox-TTS-Server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
1360 lines (1176 loc) · 50.7 KB
/
server.py
File metadata and controls
1360 lines (1176 loc) · 50.7 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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# File: server.py
# Main FastAPI application for the TTS Server.
# Handles API requests for text-to-speech generation, UI serving,
# configuration management, and file uploads.
import os
import io
import logging
import logging.handlers # For RotatingFileHandler
import shutil
import time
import uuid
import yaml # For loading presets
import numpy as np
import librosa # For potential direct use if needed, though utils.py handles most
from pathlib import Path
from contextlib import asynccontextmanager
from typing import Optional, List, Dict, Any, Literal
import webbrowser # For automatic browser opening
import threading # For automatic browser opening
from fastapi import (
FastAPI,
HTTPException,
Request,
File,
UploadFile,
Form,
BackgroundTasks,
)
from fastapi.responses import (
HTMLResponse,
JSONResponse,
StreamingResponse,
FileResponse,
)
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.middleware.cors import CORSMiddleware
# --- Internal Project Imports ---
from config import (
config_manager,
get_host,
get_port,
get_log_file_path,
get_output_path,
get_reference_audio_path,
get_predefined_voices_path,
get_ui_title,
get_gen_default_temperature,
get_gen_default_exaggeration,
get_gen_default_cfg_weight,
get_gen_default_seed,
get_gen_default_speed_factor,
get_gen_default_language,
get_audio_sample_rate,
get_full_config_for_template,
get_audio_output_format,
)
import engine # TTS Engine interface
from models import ( # Pydantic models
CustomTTSRequest,
ErrorResponse,
UpdateStatusResponse,
)
import utils # Utility functions
from pydantic import BaseModel, Field
class OpenAISpeechRequest(BaseModel):
model: str
input_: str = Field(..., alias="input")
voice: str
response_format: Literal["wav", "opus", "mp3"] = "wav" # Add "mp3"
speed: float = 1.0
seed: Optional[int] = None
# --- Logging Configuration ---
log_file_path_obj = get_log_file_path()
log_file_max_size_mb = config_manager.get_int("server.log_file_max_size_mb", 10)
log_backup_count = config_manager.get_int("server.log_file_backup_count", 5)
log_file_path_obj.parent.mkdir(parents=True, exist_ok=True)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
handlers=[
logging.handlers.RotatingFileHandler(
str(log_file_path_obj),
maxBytes=log_file_max_size_mb * 1024 * 1024,
backupCount=log_backup_count,
encoding="utf-8",
),
logging.StreamHandler(),
],
)
logging.getLogger("uvicorn.access").setLevel(logging.WARNING)
logging.getLogger("watchfiles").setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
# --- Global Variables & Application Setup ---
startup_complete_event = threading.Event() # For coordinating browser opening
def _delayed_browser_open(host: str, port: int):
"""
Waits for the startup_complete_event, then opens the web browser
to the server's main page after a short delay.
"""
try:
startup_complete_event.wait(timeout=30)
if not startup_complete_event.is_set():
logger.warning(
"Server startup did not signal completion within timeout. Browser will not be opened automatically."
)
return
time.sleep(1.5)
display_host = "localhost" if host == "0.0.0.0" else host
browser_url = f"http://{display_host}:{port}/"
logger.info(f"Attempting to open web browser to: {browser_url}")
webbrowser.open(browser_url)
except Exception as e:
logger.error(f"Failed to open browser automatically: {e}", exc_info=True)
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Manages application startup and shutdown events."""
logger.info("TTS Server: Initializing application...")
try:
logger.info(f"Configuration loaded. Log file at: {get_log_file_path()}")
paths_to_ensure = [
get_output_path(),
get_reference_audio_path(),
get_predefined_voices_path(),
Path("ui"),
config_manager.get_path(
"paths.model_cache", "./model_cache", ensure_absolute=True
),
]
for p in paths_to_ensure:
p.mkdir(parents=True, exist_ok=True)
if not engine.load_model():
logger.critical(
"CRITICAL: TTS Model failed to load on startup. Server might not function correctly."
)
else:
logger.info("TTS Model loaded successfully via engine.")
host_address = get_host()
server_port = get_port()
browser_thread = threading.Thread(
target=lambda: _delayed_browser_open(host_address, server_port),
daemon=True,
)
browser_thread.start()
logger.info("Application startup sequence complete.")
startup_complete_event.set()
yield
except Exception as e_startup:
logger.error(
f"FATAL ERROR during application startup: {e_startup}", exc_info=True
)
startup_complete_event.set()
yield
finally:
logger.info("TTS Server: Application shutdown sequence initiated...")
logger.info("TTS Server: Application shutdown complete.")
# --- FastAPI Application Instance ---
app = FastAPI(
title=get_ui_title(),
description="Text-to-Speech server with advanced UI and API capabilities.",
version="2.0.2", # Version Bump
lifespan=lifespan,
)
# --- CORS Middleware ---
app.add_middleware(
CORSMiddleware,
allow_origins=["*", "null"],
allow_credentials=True,
allow_methods=["GET", "POST", "OPTIONS"],
allow_headers=["*"],
)
# --- Static Files and HTML Templates ---
ui_static_path = Path(__file__).parent / "ui"
if ui_static_path.is_dir():
app.mount("/ui", StaticFiles(directory=ui_static_path), name="ui_static_assets")
else:
logger.warning(
f"UI static assets directory not found at '{ui_static_path}'. UI may not load correctly."
)
# This will serve files from 'ui_static_path/vendor' when requests come to '/vendor/*'
if (ui_static_path / "vendor").is_dir():
app.mount(
"/vendor", StaticFiles(directory=ui_static_path / "vendor"), name="vendor_files"
)
else:
logger.warning(
f"Vendor directory not found at '{ui_static_path}' /vendor. Wavesurfer might not load."
)
@app.get("/styles.css", include_in_schema=False)
async def get_main_styles():
styles_file = ui_static_path / "styles.css"
if styles_file.is_file():
return FileResponse(styles_file)
raise HTTPException(status_code=404, detail="styles.css not found")
@app.get("/script.js", include_in_schema=False)
async def get_main_script():
script_file = ui_static_path / "script.js"
if script_file.is_file():
return FileResponse(script_file)
raise HTTPException(status_code=404, detail="script.js not found")
outputs_static_path = get_output_path(ensure_absolute=True)
try:
app.mount(
"/outputs",
StaticFiles(directory=str(outputs_static_path)),
name="generated_outputs",
)
except RuntimeError as e_mount_outputs:
logger.error(
f"Failed to mount /outputs directory '{outputs_static_path}': {e_mount_outputs}. "
"Output files may not be accessible via URL."
)
templates = Jinja2Templates(directory=str(ui_static_path))
# --- API Endpoints ---
# --- Audio Stitching Helper Functions ---
# These functions support smart audio chunk concatenation with crossfading
def _generate_equal_power_curves(n_samples: int):
"""
Generate equal-power crossfade curves using cos²/sin² functions.
These curves maintain perceptually constant loudness during transitions.
Args:
n_samples: Number of samples in the fade region
Returns:
Tuple of (fade_out, fade_in) numpy arrays
"""
t = np.linspace(0, np.pi / 2, n_samples, dtype=np.float32)
fade_out = np.cos(t) ** 2 # 1 → 0
fade_in = np.sin(t) ** 2 # 0 → 1
return fade_out, fade_in
def _crossfade_with_overlap(
chunk_a: np.ndarray, chunk_b: np.ndarray, fade_samples: int
) -> np.ndarray:
"""
Perform true crossfade by overlapping and summing audio regions.
This creates a seamless transition by:
1. Taking the tail of chunk_a and head of chunk_b
2. Applying equal-power fade curves
3. Summing the overlapped regions
Result length = len(chunk_a) + len(chunk_b) - fade_samples
Args:
chunk_a: First audio chunk (numpy float32 array)
chunk_b: Second audio chunk (numpy float32 array)
fade_samples: Number of samples to overlap
Returns:
Crossfaded audio as numpy float32 array
"""
# Handle edge cases
fade_samples = min(fade_samples, len(chunk_a), len(chunk_b))
if fade_samples <= 0:
return np.concatenate([chunk_a, chunk_b])
fade_out, fade_in = _generate_equal_power_curves(fade_samples)
# Extract overlap regions
a_tail = chunk_a[-fade_samples:]
b_head = chunk_b[:fade_samples]
# Crossfade: weighted sum of overlapping regions
crossfaded_region = (a_tail * fade_out) + (b_head * fade_in)
# Assemble: [chunk_a without tail] + [crossfaded region] + [chunk_b without head]
return np.concatenate(
[chunk_a[:-fade_samples], crossfaded_region, chunk_b[fade_samples:]]
)
def _apply_edge_fades(
chunk: np.ndarray, fade_samples: int, fade_in: bool = True, fade_out: bool = True
) -> np.ndarray:
"""
Apply minimal linear edge fades for click protection.
This is used in fallback mode when full crossfading is disabled.
Linear fades are acceptable for ultra-short safety fades (2-3ms).
Args:
chunk: Audio chunk (numpy array)
fade_samples: Number of samples to fade
fade_in: Whether to apply fade-in at start
fade_out: Whether to apply fade-out at end
Returns:
Audio chunk with edge fades applied (numpy float32 array)
"""
# Skip if chunk is too short for fading
if len(chunk) < fade_samples * 2:
return chunk.astype(np.float32, copy=False)
result = chunk.astype(np.float32, copy=True)
if fade_in:
result[:fade_samples] *= np.linspace(0, 1, fade_samples, dtype=np.float32)
if fade_out:
result[-fade_samples:] *= np.linspace(1, 0, fade_samples, dtype=np.float32)
return result
def _remove_dc_offset(
audio: np.ndarray, sample_rate: int, cutoff_hz: float = 15.0
) -> np.ndarray:
"""
Remove DC offset using a high-pass Butterworth filter.
DC offset can cause low-frequency thumps when concatenating audio chunks.
This applies a 2nd-order high-pass filter at the specified cutoff frequency.
Args:
audio: Audio data (numpy array)
sample_rate: Sample rate in Hz
cutoff_hz: High-pass filter cutoff frequency (default 15 Hz)
Returns:
Audio with DC offset removed (numpy float32 array)
Note:
Requires scipy. If scipy is not available, returns audio unchanged
with a warning logged.
"""
try:
from scipy.signal import butter, filtfilt
nyquist = sample_rate / 2
normalized_cutoff = cutoff_hz / nyquist
# 2nd-order Butterworth high-pass filter
b, a = butter(2, normalized_cutoff, btype="high")
# Zero-phase filtering (no phase distortion)
return filtfilt(b, a, audio).astype(np.float32)
except ImportError:
logger.warning(
"scipy not available for DC offset removal. "
"Install scipy to enable this feature: pip install scipy"
)
return audio.astype(np.float32, copy=False)
except Exception as e:
logger.error(f"DC offset removal failed: {e}")
return audio.astype(np.float32, copy=False)
# --- End Audio Stitching Helper Functions ---
# --- Main UI Route ---
@app.get("/", response_class=HTMLResponse, include_in_schema=False)
async def get_web_ui(request: Request):
"""Serves the main web interface (index.html)."""
logger.info("Request received for main UI page ('/').")
try:
return templates.TemplateResponse("index.html", {"request": request})
except Exception as e_render:
logger.error(f"Error rendering main UI page: {e_render}", exc_info=True)
return HTMLResponse(
"<html><body><h1>Internal Server Error</h1><p>Could not load the TTS interface. "
"Please check server logs for more details.</p></body></html>",
status_code=500,
)
# --- API Endpoint for Model Information ---
@app.get("/api/model-info", tags=["Model Information"])
async def get_model_info_endpoint():
"""
Returns detailed information about the currently loaded TTS model.
This endpoint is used by the UI to display model status and
conditionally show features like paralinguistic tags.
"""
logger.debug("Request received for /api/model-info")
try:
model_info = engine.get_model_info()
return model_info
except Exception as e:
logger.error(f"Error getting model info: {e}", exc_info=True)
raise HTTPException(
status_code=500, detail="Failed to retrieve model information"
)
# --- API Endpoint for Initial UI Data ---
@app.get("/api/ui/initial-data", tags=["UI Helpers"])
async def get_ui_initial_data():
"""
Provides all necessary initial data for the UI to render,
including configuration, file lists, presets, and model information.
"""
logger.info("Request received for /api/ui/initial-data.")
try:
full_config = get_full_config_for_template()
reference_files = utils.get_valid_reference_files()
predefined_voices = utils.get_predefined_voices()
# Get model information for UI
model_info = engine.get_model_info()
loaded_presets = []
presets_file = ui_static_path / "presets.yaml"
if presets_file.exists():
with open(presets_file, "r", encoding="utf-8") as f:
yaml_content = yaml.safe_load(f)
if isinstance(yaml_content, list):
loaded_presets = yaml_content
else:
logger.warning(
f"Invalid format in {presets_file}. Expected a list, got {type(yaml_content)}."
)
else:
logger.info(
f"Presets file not found: {presets_file}. No presets will be loaded for initial data."
)
initial_gen_result_placeholder = {
"outputUrl": None,
"filename": None,
"genTime": None,
"submittedVoiceMode": None,
"submittedPredefinedVoice": None,
"submittedCloneFile": None,
}
return {
"config": full_config,
"reference_files": reference_files,
"predefined_voices": predefined_voices,
"presets": loaded_presets,
"initial_gen_result": initial_gen_result_placeholder,
"model_info": model_info, # NEW: Include model information
}
except Exception as e:
logger.error(f"Error preparing initial UI data for API: {e}", exc_info=True)
raise HTTPException(
status_code=500, detail="Failed to load initial data for UI."
)
# --- Configuration Management API Endpoints ---
@app.post("/save_settings", response_model=UpdateStatusResponse, tags=["Configuration"])
async def save_settings_endpoint(request: Request):
"""
Saves partial configuration updates to the config.yaml file.
Merges the update with the current configuration.
"""
logger.info("Request received for /save_settings.")
try:
partial_update = await request.json()
if not isinstance(partial_update, dict):
raise ValueError("Request body must be a JSON object for /save_settings.")
logger.debug(f"Received partial config data to save: {partial_update}")
if config_manager.update_and_save(partial_update):
restart_needed = any(
key in partial_update
for key in ["server", "tts_engine", "paths", "model"]
)
message = "Settings saved successfully."
if restart_needed:
message += " A server restart may be required for some changes to take full effect."
return UpdateStatusResponse(message=message, restart_needed=restart_needed)
else:
logger.error(
"Failed to save configuration via config_manager.update_and_save."
)
raise HTTPException(
status_code=500,
detail="Failed to save configuration file due to an internal error.",
)
except ValueError as ve:
logger.error(f"Invalid data format for /save_settings: {ve}")
raise HTTPException(status_code=400, detail=f"Invalid request data: {str(ve)}")
except Exception as e:
logger.error(f"Error processing /save_settings request: {e}", exc_info=True)
raise HTTPException(
status_code=500,
detail=f"Internal server error during settings save: {str(e)}",
)
@app.post(
"/reset_settings", response_model=UpdateStatusResponse, tags=["Configuration"]
)
async def reset_settings_endpoint():
"""Resets the configuration in config.yaml back to hardcoded defaults."""
logger.warning("Request received to reset all configurations to default values.")
try:
if config_manager.reset_and_save():
logger.info("Configuration successfully reset to defaults and saved.")
return UpdateStatusResponse(
message="Configuration reset to defaults. Please reload the page. A server restart may be beneficial.",
restart_needed=True,
)
else:
logger.error("Failed to reset and save configuration via config_manager.")
raise HTTPException(
status_code=500, detail="Failed to reset and save configuration file."
)
except Exception as e:
logger.error(f"Error processing /reset_settings request: {e}", exc_info=True)
raise HTTPException(
status_code=500,
detail=f"Internal server error during settings reset: {str(e)}",
)
@app.post(
"/restart_server", response_model=UpdateStatusResponse, tags=["Configuration"]
)
async def restart_server_endpoint():
"""
Triggers a hot-swap of the TTS model engine.
Unloads the current model, clears VRAM, and loads the model defined in config.
"""
logger.info("Request received for /restart_server (Model Hot-Swap).")
try:
# Attempt to reload the engine with the new configuration
success = engine.reload_model()
if success:
model_info = engine.get_model_info()
new_model_name = model_info.get("class_name", "Unknown Model")
new_model_type = model_info.get("type", "unknown")
message = f"Model hot-swap successful. Now running: {new_model_name} ({new_model_type})"
logger.info(message)
# restart_needed=False because we just performed the hot-swap successfully
return UpdateStatusResponse(message=message, restart_needed=False)
else:
error_msg = "Model reload failed. The server may be in an inconsistent state. Check logs for details."
logger.error(error_msg)
raise HTTPException(status_code=500, detail=error_msg)
except HTTPException:
raise
except Exception as e:
logger.error(f"Critical error during model hot-swap: {e}", exc_info=True)
raise HTTPException(
status_code=500,
detail=f"Internal server error during model reload: {str(e)}",
)
# --- UI Helper API Endpoints ---
@app.get("/get_reference_files", response_model=List[str], tags=["UI Helpers"])
async def get_reference_files_api():
"""Returns a list of valid reference audio filenames (.wav, .mp3)."""
logger.debug("Request for /get_reference_files.")
try:
return utils.get_valid_reference_files()
except Exception as e:
logger.error(f"Error getting reference files for API: {e}", exc_info=True)
raise HTTPException(
status_code=500, detail="Failed to retrieve reference audio files."
)
@app.get(
"/get_predefined_voices", response_model=List[Dict[str, str]], tags=["UI Helpers"]
)
async def get_predefined_voices_api():
"""Returns a list of predefined voices with display names and filenames."""
logger.debug("Request for /get_predefined_voices.")
try:
return utils.get_predefined_voices()
except Exception as e:
logger.error(f"Error getting predefined voices for API: {e}", exc_info=True)
raise HTTPException(
status_code=500, detail="Failed to retrieve predefined voices list."
)
# --- File Upload Endpoints ---
@app.post("/upload_reference", tags=["File Management"])
async def upload_reference_audio_endpoint(files: List[UploadFile] = File(...)):
"""
Handles uploading of reference audio files (.wav, .mp3) for voice cloning.
Validates files and saves them to the configured reference audio path.
"""
logger.info(f"Request to /upload_reference with {len(files)} file(s).")
ref_path = get_reference_audio_path(ensure_absolute=True)
uploaded_filenames_successfully: List[str] = []
upload_errors: List[Dict[str, str]] = []
for file in files:
if not file.filename:
upload_errors.append(
{"filename": "Unknown", "error": "File received with no filename."}
)
logger.warning("Upload attempt with no filename.")
continue
safe_filename = utils.sanitize_filename(file.filename)
destination_path = ref_path / safe_filename
try:
if not (
safe_filename.lower().endswith(".wav")
or safe_filename.lower().endswith(".mp3")
):
raise ValueError("Invalid file type. Only .wav and .mp3 are allowed.")
if destination_path.exists():
logger.info(
f"Reference file '{safe_filename}' already exists. Skipping duplicate upload."
)
if safe_filename not in uploaded_filenames_successfully:
uploaded_filenames_successfully.append(safe_filename)
continue
with open(destination_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
logger.info(
f"Successfully saved uploaded reference file to: {destination_path}"
)
max_duration = config_manager.get_int(
"audio_output.max_reference_duration_sec", 30
)
is_valid, validation_msg = utils.validate_reference_audio(
destination_path, max_duration
)
if not is_valid:
logger.warning(
f"Uploaded file '{safe_filename}' failed validation: {validation_msg}. Deleting."
)
destination_path.unlink(missing_ok=True)
upload_errors.append(
{"filename": safe_filename, "error": validation_msg}
)
else:
uploaded_filenames_successfully.append(safe_filename)
except Exception as e_upload:
error_msg = f"Error processing file '{file.filename}': {str(e_upload)}"
logger.error(error_msg, exc_info=True)
upload_errors.append({"filename": file.filename, "error": str(e_upload)})
finally:
await file.close()
all_current_reference_files = utils.get_valid_reference_files()
response_data = {
"message": f"Processed {len(files)} file(s).",
"uploaded_files": uploaded_filenames_successfully,
"all_reference_files": all_current_reference_files,
"errors": upload_errors,
}
status_code = (
200 if not upload_errors or len(uploaded_filenames_successfully) > 0 else 400
)
if upload_errors:
logger.warning(
f"Upload to /upload_reference completed with {len(upload_errors)} error(s)."
)
return JSONResponse(content=response_data, status_code=status_code)
@app.post("/upload_predefined_voice", tags=["File Management"])
async def upload_predefined_voice_endpoint(files: List[UploadFile] = File(...)):
"""
Handles uploading of predefined voice files (.wav, .mp3).
Validates files and saves them to the configured predefined voices path.
"""
logger.info(f"Request to /upload_predefined_voice with {len(files)} file(s).")
predefined_voices_path = get_predefined_voices_path(ensure_absolute=True)
uploaded_filenames_successfully: List[str] = []
upload_errors: List[Dict[str, str]] = []
for file in files:
if not file.filename:
upload_errors.append(
{"filename": "Unknown", "error": "File received with no filename."}
)
logger.warning("Upload attempt for predefined voice with no filename.")
continue
safe_filename = utils.sanitize_filename(file.filename)
destination_path = predefined_voices_path / safe_filename
try:
if not (
safe_filename.lower().endswith(".wav")
or safe_filename.lower().endswith(".mp3")
):
raise ValueError(
"Invalid file type. Only .wav and .mp3 are allowed for predefined voices."
)
if destination_path.exists():
logger.info(
f"Predefined voice file '{safe_filename}' already exists. Skipping duplicate upload."
)
if safe_filename not in uploaded_filenames_successfully:
uploaded_filenames_successfully.append(safe_filename)
continue
with open(destination_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
logger.info(
f"Successfully saved uploaded predefined voice file to: {destination_path}"
)
# Basic validation (can be extended if predefined voices have specific requirements)
is_valid, validation_msg = utils.validate_reference_audio(
destination_path, max_duration_sec=None
) # No duration limit for predefined
if not is_valid:
logger.warning(
f"Uploaded predefined voice '{safe_filename}' failed basic validation: {validation_msg}. Deleting."
)
destination_path.unlink(missing_ok=True)
upload_errors.append(
{"filename": safe_filename, "error": validation_msg}
)
else:
uploaded_filenames_successfully.append(safe_filename)
except Exception as e_upload:
error_msg = f"Error processing predefined voice file '{file.filename}': {str(e_upload)}"
logger.error(error_msg, exc_info=True)
upload_errors.append({"filename": file.filename, "error": str(e_upload)})
finally:
await file.close()
all_current_predefined_voices = (
utils.get_predefined_voices()
) # Fetches formatted list
response_data = {
"message": f"Processed {len(files)} predefined voice file(s).",
"uploaded_files": uploaded_filenames_successfully, # List of raw filenames uploaded
"all_predefined_voices": all_current_predefined_voices, # Formatted list for UI
"errors": upload_errors,
}
status_code = (
200 if not upload_errors or len(uploaded_filenames_successfully) > 0 else 400
)
if upload_errors:
logger.warning(
f"Upload to /upload_predefined_voice completed with {len(upload_errors)} error(s)."
)
return JSONResponse(content=response_data, status_code=status_code)
# --- TTS Generation Endpoint ---
@app.post(
"/tts",
tags=["TTS Generation"],
summary="Generate speech with custom parameters",
responses={
200: {
"content": {"audio/wav": {}, "audio/opus": {}},
"description": "Successful audio generation.",
},
400: {
"model": ErrorResponse,
"description": "Invalid request parameters or input.",
},
404: {
"model": ErrorResponse,
"description": "Required resource not found (e.g., voice file).",
},
500: {
"model": ErrorResponse,
"description": "Internal server error during generation.",
},
503: {
"model": ErrorResponse,
"description": "TTS engine not available or model not loaded.",
},
},
)
async def custom_tts_endpoint(
request: CustomTTSRequest, background_tasks: BackgroundTasks
):
"""
Generates speech audio from text using specified parameters.
Handles various voice modes (predefined, clone) and audio processing options.
Returns audio as a stream (WAV or Opus).
"""
perf_monitor = utils.PerformanceMonitor(
enabled=config_manager.get_bool("server.enable_performance_monitor", False)
)
perf_monitor.record("TTS request received")
if not engine.MODEL_LOADED:
logger.error("TTS request failed: Model not loaded.")
raise HTTPException(
status_code=503,
detail="TTS engine model is not currently loaded or available.",
)
logger.info(
f"Received /tts request: mode='{request.voice_mode}', format='{request.output_format}'"
)
logger.debug(
f"TTS params: seed={request.seed}, split={request.split_text}, chunk_size={request.chunk_size}"
)
logger.debug(f"Input text (first 100 chars): '{request.text[:100]}...'")
audio_prompt_path_for_engine: Optional[Path] = None
if request.voice_mode == "predefined":
if not request.predefined_voice_id:
raise HTTPException(
status_code=400,
detail="Missing 'predefined_voice_id' for 'predefined' voice mode.",
)
voices_dir = get_predefined_voices_path(ensure_absolute=True)
potential_path = voices_dir / request.predefined_voice_id
if not potential_path.is_file():
logger.error(f"Predefined voice file not found: {potential_path}")
raise HTTPException(
status_code=404,
detail=f"Predefined voice file '{request.predefined_voice_id}' not found.",
)
audio_prompt_path_for_engine = potential_path
logger.info(f"Using predefined voice: {request.predefined_voice_id}")
elif request.voice_mode == "clone":
if not request.reference_audio_filename:
raise HTTPException(
status_code=400,
detail="Missing 'reference_audio_filename' for 'clone' voice mode.",
)
ref_dir = get_reference_audio_path(ensure_absolute=True)
potential_path = ref_dir / request.reference_audio_filename
if not potential_path.is_file():
logger.error(
f"Reference audio file for cloning not found: {potential_path}"
)
raise HTTPException(
status_code=404,
detail=f"Reference audio file '{request.reference_audio_filename}' not found.",
)
max_dur = config_manager.get_int("audio_output.max_reference_duration_sec", 30)
is_valid, msg = utils.validate_reference_audio(potential_path, max_dur)
if not is_valid:
raise HTTPException(
status_code=400, detail=f"Invalid reference audio: {msg}"
)
audio_prompt_path_for_engine = potential_path
logger.info(
f"Using reference audio for cloning: {request.reference_audio_filename}"
)
perf_monitor.record("Parameters and voice path resolved")
all_audio_segments_np: List[np.ndarray] = []
final_output_sample_rate = (
get_audio_sample_rate()
) # Target SR for the final output file
engine_output_sample_rate: Optional[int] = (
None # SR from the TTS engine (e.g., 24000 Hz)
)
if request.split_text and len(request.text) > (
request.chunk_size * 1.5 if request.chunk_size else 120 * 1.5
):
chunk_size_to_use = (
request.chunk_size if request.chunk_size is not None else 120
)
logger.info(f"Splitting text into chunks of size ~{chunk_size_to_use}.")
text_chunks = utils.chunk_text_by_sentences(request.text, chunk_size_to_use)
perf_monitor.record(f"Text split into {len(text_chunks)} chunks")
else:
text_chunks = [request.text]
logger.info(
"Processing text as a single chunk (splitting not enabled or text too short)."
)
if not text_chunks:
raise HTTPException(
status_code=400, detail="Text processing resulted in no usable chunks."
)
for i, chunk in enumerate(text_chunks):
logger.info(f"Synthesizing chunk {i+1}/{len(text_chunks)}...")
try:
chunk_audio_tensor, chunk_sr_from_engine = engine.synthesize(
text=chunk,
audio_prompt_path=(
str(audio_prompt_path_for_engine)
if audio_prompt_path_for_engine
else None
),
temperature=(
request.temperature
if request.temperature is not None
else get_gen_default_temperature()
),
exaggeration=(
request.exaggeration
if request.exaggeration is not None
else get_gen_default_exaggeration()
),
cfg_weight=(
request.cfg_weight
if request.cfg_weight is not None
else get_gen_default_cfg_weight()
),
seed=(
request.seed if request.seed is not None else get_gen_default_seed()
),
language=(
request.language
if request.language is not None
else get_gen_default_language()
),
)
perf_monitor.record(f"Engine synthesized chunk {i+1}")
if chunk_audio_tensor is None or chunk_sr_from_engine is None:
error_detail = f"TTS engine failed to synthesize audio for chunk {i+1}."
logger.error(error_detail)
raise HTTPException(status_code=500, detail=error_detail)
if engine_output_sample_rate is None:
engine_output_sample_rate = chunk_sr_from_engine
elif engine_output_sample_rate != chunk_sr_from_engine:
logger.warning(
f"Inconsistent sample rate from engine: chunk {i+1} ({chunk_sr_from_engine}Hz) "
f"differs from previous ({engine_output_sample_rate}Hz). Using first chunk's SR."
)
current_processed_audio_tensor = chunk_audio_tensor
speed_factor_to_use = (
request.speed_factor
if request.speed_factor is not None
else get_gen_default_speed_factor()
)
if speed_factor_to_use != 1.0:
current_processed_audio_tensor, _ = utils.apply_speed_factor(
current_processed_audio_tensor,
chunk_sr_from_engine,
speed_factor_to_use,
)
perf_monitor.record(f"Speed factor applied to chunk {i+1}")
# ### MODIFICATION ###
# All other processing is REMOVED from the loop.
# We will process the final concatenated audio clip.
processed_audio_np = current_processed_audio_tensor.cpu().numpy().squeeze()
all_audio_segments_np.append(processed_audio_np)
except HTTPException as http_exc:
raise http_exc
except Exception as e_chunk:
error_detail = f"Error processing audio chunk {i+1}: {str(e_chunk)}"
logger.error(error_detail, exc_info=True)
raise HTTPException(status_code=500, detail=error_detail)
if not all_audio_segments_np:
logger.error("No audio segments were successfully generated.")
raise HTTPException(
status_code=500, detail="Audio generation resulted in no output."