forked from erew123/alltalk_tts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tts_server.py
2576 lines (2220 loc) · 119 KB
/
tts_server.py
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
"""
AllTalk TTS server implementation for managing and serving text-to-speech generation.
This script provides endpoints for generating TTS, handling voice configurations,
and managing audio processing, including RVC-based voice conversion and OpenAI-compatible APIs.
It supports features like streaming, file format transcoding, and real-time configuration updates.
Github: https://github.com/erew123/
"""
import warnings
from contextlib import asynccontextmanager
import argparse
import asyncio
from asyncio import Lock
import importlib
import inspect
import json
import logging
import os
import re
import html
import uuid
import hashlib
import sys
import time
import shutil
import subprocess
from pathlib import Path
from typing import Union, List, Optional, Tuple
import aiofiles
import uvicorn
from pydantic import BaseModel, ValidationError, Field, field_validator
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.middleware.cors import CORSMiddleware
from fastapi import FastAPI, Form, Request, Response, Depends, HTTPException, Query
from fastapi.responses import JSONResponse, HTMLResponse, FileResponse, StreamingResponse
import ffmpeg
import numpy as np
import soundfile as sf
import librosa
from config import AlltalkConfig, AlltalkTTSEnginesConfig
logging.disable(logging.WARNING)
########################################################################################
# START-UP # Silence RVC warning about torch.nn.utils.weight_norm even though not used #
########################################################################################
warnings.filterwarnings("ignore", category=UserWarning, module="torch.nn.utils.weight_norm")
warnings.filterwarnings("ignore", category=UserWarning, module="torch.nn.functional", lineno=5476)
# Filter ComplexHalf support warning
warnings.filterwarnings("ignore", message="ComplexHalf support is experimental")
# Filter Flash Attention warning
warnings.filterwarnings("ignore", message="1Torch was not compiled with flash attention")
####################
# Setup local path #
####################
this_dir = Path(__file__).parent.resolve() # Set this_dir as the current alltalk_tts folder
infer_pipeline = None
config: AlltalkConfig | None = None
tts_engines_config: AlltalkTTSEnginesConfig | None = None
def load_config(force_reload = False):
"""Initialize all configuration instances"""
global config, tts_engines_config # pylint: disable=global-statement
config = AlltalkConfig.get_instance(force_reload)
tts_engines_config = AlltalkTTSEnginesConfig.get_instance(force_reload)
after_config_load()
def after_config_load():
"""Initialize the infer_pipeline based on RVC settings."""
global infer_pipeline # pylint: disable=global-statement
if config.rvc_settings.rvc_enabled:
from system.tts_engines.rvc.infer.infer import infer_pipeline as rvc_pipeline # pylint: disable=import-outside-toplevel
infer_pipeline = rvc_pipeline
else:
infer_pipeline = None
load_config()
##########################
# Central print function #
##########################
# ANSI color codes
BLUE = "\033[94m"
# MAGENTA = "\033[95m"
YELLOW = "\033[93m"
RED = "\033[91m"
GREEN = "\033[92m"
RESET = "\033[0m"
def print_message(message, message_type="standard", component="TTS"):
"""Centralized print function for AllTalk messages
Args:
message (str): The message to print
message_type (str): Type of message (standard/warning/error/debug_*/debug)
component (str): Component identifier (TTS/ENG/GEN/API/etc.)
"""
prefix = f"[{config.branding}{component}] "
if message_type.startswith("debug_"):
debug_flag = getattr(config.debugging, message_type, False)
if not debug_flag:
return
if message_type == "debug_func" and "Function entry:" in message:
message_parts = message.split("Function entry:", 1)
print(f"{prefix}{BLUE}Debug{RESET} {YELLOW}{message_type}{RESET} Function entry:{GREEN}{message_parts[1]}{RESET} tts_server.py")
else:
print(f"{prefix}{BLUE}Debug{RESET} {YELLOW}{message_type}{RESET} {message}")
elif message_type == "debug":
print(f"{prefix}{BLUE}Debug{RESET} {message}")
elif message_type == "warning":
print(f"{prefix}{YELLOW}Warning{RESET} {message}")
elif message_type == "error":
print(f"{prefix}{RED}Error{RESET} {message}")
else:
print(f"{prefix}{message}")
def debug_func_entry():
"""Print debug message for function entry if debug_func is enabled"""
if config.debugging.debug_func:
current_func = inspect.currentframe().f_back.f_code.co_name
print_message(f"Function entry: {current_func}", "debug_func")
####################
# Check for FFMPEG #
####################
def check_ffmpeg():
"""Verify FFmpeg availability in the conda environment."""
debug_func_entry()
try:
# Check if ffmpeg is in PATH
ffmpeg_path = shutil.which('ffmpeg')
ffprobe_path = shutil.which('ffprobe')
if not ffmpeg_path or not ffprobe_path:
return False, "FFmpeg not found in conda environment"
# Verify FFmpeg works
subprocess.run(['ffmpeg', '-version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
return True, "FFmpeg found in conda environment"
except (subprocess.CalledProcessError, FileNotFoundError):
return False, "FFmpeg not functioning correctly"
def print_ffmpeg_status(is_ffmpeg_installed, _message):
"""Print FFmpeg installation status and instructions."""
if not is_ffmpeg_installed:
print_message("\033[92mTranscoding :\033[91m ffmpeg not found\033[0m", component="ENG")
print_message("FFmpeg is not installed. Transcoding will be disabled.", "warning", "ENG")
print_message("Please install FFmpeg using:", component="ENG")
print_message("conda install -c conda-forge ffmpeg", component="ENG")
else:
print_message("\033[92mTranscoding :\033[93m ffmpeg found\033[0m", component="ENG")
# Implementation
ffmpeg_installed, ffmpeg_message = check_ffmpeg()
print_ffmpeg_status(ffmpeg_installed, ffmpeg_message)
################################
# Check for portaudio on Linux #
################################
try:
import sounddevice as sd
sounddevice_installed=True
except OSError:
print_message("The PortAudio library is not installed. To enable audio playback for TTS in the terminal or console,", "warning")
print_message("please install PortAudio. This will not impact other features of Alltalk.", "warning")
print_message("You can still play audio through web browsers without PortAudio.", "warning")
print_message("Installing PortAudio is optional and not strictly required.")
sounddevice_installed=False
if sys.platform.startswith('linux'):
print_message("On Linux, you can use the following command to install PortAudio:", "warning")
print_message("sudo apt-get install portaudio19-dev", "warning")
#######################################################################
# Attempt to import the ModelLoader class for the selected TTS engine #
#######################################################################
if tts_engines_config.is_valid_engine(tts_engines_config.engine_loaded):
loader_module = importlib.import_module(f"system.tts_engines.{tts_engines_config.engine_loaded}.model_engine")
tts_class = getattr(loader_module, "tts_class")
# Setup model_engine as the way to call the functions within the Class.
model_engine = tts_class()
else:
raise ValueError(f"Invalid TTS engine: {tts_engines_config.engine_loaded}")
##########################################
# Run setup function in the model_engine #
##########################################
@asynccontextmanager
async def startup_shutdown(no_actual_value_it_demanded_something_be_here): # pylint: disable=unused-argument
"""Initialize model engine and handle graceful shutdown. This is a context manager."""
debug_func_entry()
try:
await model_engine.setup()
except FileNotFoundError as e:
print_message(f"Error during setup: {e}. Continuing without the TTS model.", "error")
yield
###############################
# Setup FastAPI with Lifespan #
###############################
app = FastAPI(lifespan=startup_shutdown)
# Allow all origins, and set other CORS options
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Set this to the specific origins you want to allow
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Global lock
model_change_lock = Lock()
##############################
# API Endpoint - /api/reload #
##############################
@app.route("/api/reload", methods=["POST"])
async def apifunction_reload(request: Request):
"""Handle API request to change TTS model."""
debug_func_entry()
if model_change_lock.locked(): # Check if the lock is already held
print_message("Model change already in progress", "debug_api", "API")
return Response(content=json.dumps({"status": "model-is currently changing"}), media_type="application/json")
async with model_change_lock: # Acquire the lock for this operation
requested_model = request.query_params.get("tts_method")
if requested_model not in model_engine.available_models:
print_message(f"Invalid TTS method requested: {requested_model}", "error", "API")
return {"status": "error", "message": "Invalid TTS method specified"}
print_message(f"Attempting to change model to: {requested_model}", "debug_api", "API")
success = await model_engine.handle_tts_method_change(requested_model)
if success:
model_engine.current_model_loaded = requested_model
print_message(f"Model successfully changed to: {requested_model}", "debug_api", "API")
return Response(content=json.dumps({"status": "model-success"}), media_type="application/json")
print_message(f"Failed to change model to: {requested_model}", "error", "API")
return Response(content=json.dumps({"status": "model-failure"}), media_type="application/json")
####################################
# API Endpoint - /api/enginereload #
####################################
uvicorn_server = None # Global variable to track the server
def restart_self():
"""Restart the current Python process."""
debug_func_entry()
print_message("Restarting subprocess...", component="ENG")
os.execv(sys.executable, ['python'] + sys.argv)
async def handle_restart():
"""Handle graceful shutdown of uvicorn server before restart."""
debug_func_entry()
global uvicorn_server # pylint: disable=global-statement,disable=global-variable-not-assigned
if uvicorn_server:
print_message("Stopping uvicorn server...", component="ENG")
uvicorn_server.should_exit = True
uvicorn_server.force_exit = True
while not uvicorn_server.is_stopped:
await asyncio.sleep(0.1)
restart_self()
@app.post("/api/enginereload")
async def apifunction_enginereload(request: Request):
"""Handle API request to change TTS engine. Validates engine, updates config, and triggers restart."""
debug_func_entry()
requested_engine = request.query_params.get("engine")
if not tts_engines_config.is_valid_engine(requested_engine):
print_message(f"Invalid engine requested: {requested_engine}", "error", "API")
return {"status": "error", "message": "Invalid TTS engine specified"}
print_message("", component="ENG")
print_message("\033[94mChanging model loaded. Please wait.\033[00m", component="ENG")
print_message("", component="ENG")
try:
tts_engines_config.change_engine(requested_engine).save()
print_message(f"Engine configuration updated to: {requested_engine}", "debug_api", "API")
finally:
tts_engines_config.reload()
print_message("Configuration reloaded", "debug_api", "API")
asyncio.create_task(handle_restart())
return Response(content=json.dumps({"status": "engine-success"}), media_type="application/json")
#######################################
# API Endpoint - /api/stop-generation #
#######################################
# When this endpoint it called it will set tts_stop_generation in the model_engine to True, which can be used to interrupt the current TTS generation.
@app.put("/api/stop-generation")
async def apifunction_stop_generation():
"""Handle request to stop ongoing TTS generation."""
debug_func_entry()
if model_engine.tts_generating_lock and not model_engine.tts_stop_generation:
model_engine.tts_stop_generation = True
print_message("Stopping TTS generation", "debug_api", "API")
return {"message": "Cancelling current TTS generation"}
#############################
# API Endpoint - /api/audio #
#############################
@app.get("/audio/{filename}")
async def apifunction_get_audio(filename: str):
"""Serve audio file from output directory."""
debug_func_entry()
audio_path = this_dir / config.get_output_directory() / filename
if not audio_path.is_file():
print_message(f"Audio file not found: {filename}", "error", "API")
raise HTTPException(status_code=404, detail="File not found")
return FileResponse(audio_path)
##################################
# API Endpoint - /api/audiocache #
##################################
@app.get("/audiocache/{filename}")
async def apifunction_get_audiocache(filename: str):
"""Serve cached audio file with caching headers."""
debug_func_entry()
audio_path = Path(config.get_output_directory()) / filename
if not audio_path.is_file():
print_message(f"Cached audio file not found: {filename}", "error", "API")
raise HTTPException(status_code=404, detail="File not found")
response = FileResponse(path=audio_path, media_type='audio/wav', filename=filename)
response.headers["Cache-Control"] = "public, max-age=604800"
response.headers["ETag"] = str(audio_path.stat().st_mtime)
return response
##############################
# API Endpoint - /api/voices #
##############################
@app.get("/api/voices")
async def apifunction_get_voices():
"""Get available voices for current TTS engine."""
debug_func_entry()
try:
if not model_engine.multivoice_capable:
print_message(f"Engine '{model_engine.engine_loaded}' does not support multiple voices", "warning", "API")
return {"status": "error", "message": f"The currently loaded TTS engine '{model_engine.engine_loaded}' does not support multiple voices."}
available_voices = model_engine.voices_file_list()
print_message(f"Successfully retrieved {len(available_voices)} available voices", "debug_api", "API")
return {"status": "success", "voices": available_voices}
except AttributeError as e:
print_message(f"Attribute error in model engine: {str(e)}", "error", "API")
return JSONResponse(
content={"status": "error", "message": "Model engine configuration is invalid. Please check your setup."},
status_code=500
)
except FileNotFoundError as e:
print_message(f"Voices file not found: {str(e)}", "error", "API")
return JSONResponse(
content={"status": "error", "message": "The voices file could not be located. Please ensure the file exists."},
status_code=404
)
#################################
# API Endpoint - /api/rvcvoices #
#################################
@app.get("/api/rvcvoices")
async def apifunction_get_rvcvoices():
"""Get available RVC voice models."""
debug_func_entry()
response_data = {"status": "success", "rvcvoices": ["Disabled"]}
try:
load_config()
if not config.rvc_settings.rvc_enabled:
return response_data
directory = os.path.join(this_dir, "models", "rvc_voices")
if not os.path.exists(directory):
print_message("RVC voices directory not found", "warning", "API")
return response_data
if not os.access(directory, os.R_OK):
print_message("No read permission for RVC voices directory", "error", "API")
raise PermissionError("Cannot access RVC voices directory")
pth_files = []
for root, _dirs, files in os.walk(directory):
for file in files:
if file.endswith(".pth"):
pth_files.append(os.path.relpath(os.path.join(root, file), start=directory))
if pth_files:
response_data["rvcvoices"] = ["Disabled"] + sorted(pth_files)
return response_data
except FileNotFoundError:
print_message("RVC voices directory not found", "error", "API")
return JSONResponse(
content={"status": "error", "message": "RVC voices directory not found"},
status_code=404
)
except PermissionError as e:
print_message(f"Permission denied accessing RVC directory: {str(e)}", "error", "API")
return JSONResponse(
content={"status": "error", "message": "Permission denied accessing RVC directory"},
status_code=403
)
except OSError as e:
print_message(f"OS error processing RVC voices: {str(e)}", "error", "API")
return JSONResponse(
content={"status": "error", "message": "System error accessing RVC voices"},
status_code=500
)
#####################################
# API Endpoint - /api/reload_config #
#####################################
@app.get("/api/reload_config")
async def apifunction_reload_config():
"""Reload configuration settings."""
debug_func_entry()
try:
load_config(True)
print_message("Configuration reloaded successfully", "debug_api", "API")
return Response("Config file reloaded successfully")
except json.JSONDecodeError as e:
print_message(f"Invalid JSON in configuration: {str(e)}", "error", "API")
return JSONResponse(content={"status": "error", "message": "Invalid configuration format"}, status_code=400)
except (ValueError, TypeError) as e:
print_message(f"Invalid configuration value: {str(e)}", "error", "API")
return JSONResponse(content={"status": "error", "message": "Invalid configuration"}, status_code=400)
except OSError as e:
print_message(f"Error accessing configuration file: {str(e)}", "error", "API")
return JSONResponse(content={"status": "error", "message": "Could not access configuration"}, status_code=500)
#############################
# API Endpoint - /api/ready #
#############################
@app.get("/api/ready")
async def apifunction_ready():
"""Check if model engine setup has completed."""
debug_func_entry()
status = "Ready" if model_engine.setup_has_run else "Unloaded"
print_message(f"Engine status: {status}", "debug_api", "API")
return Response(status)
#######################################
# API Endpoint - /api/currentsettings #
#######################################
@app.get('/api/currentsettings')
def apifunction_get_current_settings():
"""Get comprehensive dictionary of current engine settings and capabilities."""
debug_func_entry()
try:
load_config()
settings = {
"engines_available": tts_engines_config.get_engine_names_available(),
"current_engine_loaded": model_engine.engine_loaded,
"models_available": [{"name": name} for name in model_engine.available_models.keys()],
"current_model_loaded": model_engine.current_model_loaded,
"manufacturer_name": model_engine.manufacturer_name,
"audio_format": model_engine.audio_format,
"deepspeed_capable": model_engine.deepspeed_capable,
"deepspeed_available": model_engine.deepspeed_available,
"deepspeed_enabled": model_engine.deepspeed_enabled,
"generationspeed_capable": model_engine.generationspeed_capable,
"generationspeed_set": model_engine.generationspeed_set,
"lowvram_capable": model_engine.lowvram_capable,
"lowvram_enabled": model_engine.lowvram_enabled,
"pitch_capable": model_engine.pitch_capable,
"pitch_set": model_engine.pitch_set,
"repetitionpenalty_capable": model_engine.repetitionpenalty_capable,
"repetitionpenalty_set": model_engine.repetitionpenalty_set,
"streaming_capable": model_engine.streaming_capable,
"temperature_capable": model_engine.temperature_capable,
"temperature_set": model_engine.temperature_set,
"ttsengines_installed": model_engine.engine_installed,
"languages_capable": model_engine.languages_capable,
"multivoice_capable": model_engine.multivoice_capable,
"multimodel_capable": model_engine.multimodel_capable,
}
print_message("Current settings retrieved successfully", "debug_api", "API")
return settings
except AttributeError as e:
print_message(f"Missing required engine attribute: {str(e)}", "error", "API")
return JSONResponse(
content={"status": "error", "message": "Invalid engine configuration"},
status_code=500
)
except KeyError as e:
print_message(f"Missing required configuration key: {str(e)}", "error", "API")
return JSONResponse(
content={"status": "error", "message": "Invalid engine configuration"},
status_code=500
)
except (ValueError, TypeError) as e:
print_message(f"Invalid configuration value: {str(e)}", "error", "API")
return JSONResponse(
content={"status": "error", "message": "Invalid configuration value"},
status_code=500
)
######################################
# API Endpoint - /api/lowvramsetting #
######################################
@app.post("/api/lowvramsetting")
async def apifunction_low_vram(_request: Request, new_low_vram_value: bool):
"""Handle LowVRAM mode toggle. Updates model device allocation between VRAM and system RAM."""
debug_func_entry()
response_content = {"status": "error", "message": ""}
# Early return for unsupported engine
if not model_engine.lowvram_capable:
msg = f"The currently loaded TTS engine '{model_engine.engine_loaded}' does not support lowvram."
print_message(f"Engine '{model_engine.engine_loaded}' does not support lowvram", "error", "API")
response_content["message"] = msg
return Response(content=json.dumps(response_content))
try:
if new_low_vram_value is None:
raise ValueError("Missing 'low_vram' parameter")
# Handle no-change case
if model_engine.lowvram_enabled == new_low_vram_value:
msg = f"LowVRAM is already {'enabled' if new_low_vram_value else 'disabled'}"
print_message(msg, "debug_api", "API")
response_content.update({"status": "success", "message": msg})
else:
# Process LowVRAM change
model_engine.lowvram_enabled = new_low_vram_value
await model_engine.unload_model()
if model_engine.cuda_is_available:
if model_engine.lowvram_enabled:
model_engine.device = "cpu"
print_message("\033[94mLowVRAM Enabled.\033[0m Model will move between \033[93mVRAM(cuda) <> System RAM(cpu)\033[0m", component="ENG")
else:
model_engine.device = "cuda"
print_message("\033[94mLowVRAM Disabled.\033[0m Model will stay in \033[93mVRAM(cuda)\033[0m", component="ENG")
await model_engine.setup()
else:
print_message("Nvidia CUDA is not available on this system. Unable to use LowVRAM mode.", "error", "ENG")
model_engine.lowvram_enabled = False
response_content.update({"status": "lowvram-success", "message": ""})
except ValueError as e:
print_message(f"Invalid parameter value: {str(e)}", "error", "API")
response_content["message"] = str(e)
except AttributeError as e:
print_message(f"Model engine configuration error: {str(e)}", "error", "API")
response_content["message"] = "Invalid model engine configuration"
except RuntimeError as e:
print_message(f"CUDA/Device error: {str(e)}", "error", "API")
response_content["message"] = "Device allocation error"
except json.JSONEncodeError as e:
print_message(f"JSON encoding error: {str(e)}", "error", "API")
response_content["message"] = "Response encoding error"
except OSError as e:
print_message(f"System resource error: {str(e)}", "error", "API")
response_content["message"] = "System resource error"
return Response(content=json.dumps(response_content))
#################################
# API Endpoint - /api/deepspeed #
#################################
@app.post("/api/deepspeed")
async def deepspeed(_request: Request, new_deepspeed_value: bool):
"""Handle DeepSpeed mode toggle. Verifies capability and handles model changes."""
debug_func_entry()
response_content = {"status": "error", "message": ""}
# Early check for DeepSpeed capability
if not model_engine.deepspeed_capable or not model_engine.deepspeed_available:
msg = f"The currently loaded TTS engine '{model_engine.engine_loaded}' does not support DeepSpeed or DeepSpeed is not available on this system."
print_message("DeepSpeed not supported or available", "error", "API")
response_content["message"] = msg
return Response(content=json.dumps(response_content))
try:
if new_deepspeed_value is None:
raise ValueError("Missing 'deepspeed' parameter")
# Handle no-change case
if model_engine.deepspeed_enabled == new_deepspeed_value:
msg = f"DeepSpeed is already {'enabled' if new_deepspeed_value else 'disabled'}"
print_message(msg, "debug_api", "API")
response_content = {"status": "success", "message": msg}
else:
# Process DeepSpeed change
model_engine.deepspeed_enabled = new_deepspeed_value
await model_engine.handle_deepspeed_change(new_deepspeed_value)
print_message(f"DeepSpeed {'enabled' if new_deepspeed_value else 'disabled'}", "debug_api", "API")
response_content = {"status": "deepspeed-success"}
except ValueError as e:
print_message(f"Value error: {str(e)}", "error", "API")
response_content["message"] = f"Invalid input: {str(e)}"
except AttributeError as e:
print_message(f"Attribute error: {str(e)}", "error", "API")
response_content["message"] = "Unexpected attribute error. Check model engine configuration."
except RuntimeError as e:
print_message(f"Runtime error: {str(e)}", "error", "API")
response_content["message"] = f"Runtime error: {str(e)}"
except TypeError as e:
print_message(f"Type error: {str(e)}", "error", "API")
response_content["message"] = f"Type error: {str(e)}"
except OSError as e:
print_message(f"System error: {str(e)}", "error", "API")
response_content["message"] = "System resource or file error"
except json.JSONEncodeError as e:
print_message(f"JSON encoding error: {str(e)}", "error", "API")
response_content["message"] = "Error encoding response"
except ImportError as e:
print_message(f"DeepSpeed import error: {str(e)}", "error", "API")
response_content["message"] = "DeepSpeed module not properly installed"
except MemoryError as e:
print_message(f"Memory allocation error: {str(e)}", "error", "API")
response_content["message"] = "Insufficient memory for DeepSpeed operation"
return Response(content=json.dumps(response_content))
#################################
# API Endpoint - /api/voice2rvc #
#################################
@app.post("/api/voice2rvc")
async def voice2rvc(input_tts_path: str = Form(...), output_rvc_path: str = Form(...),
pth_name: str = Form(...), pitch: str = Form(...), method: str = Form(...)):
"""Handle voice conversion using RVC. Processes input audio through specified RVC model."""
debug_func_entry()
try:
if pth_name.lower() in ["disabled", "disable"]:
print_message("\033[94mVoice2RVC Convert: No voice was specified or the name was Disabled\033[0m")
return {"status": "error", "message": "No voice was specified or the name was Disabled"}
input_tts_path = Path(input_tts_path)
output_rvc_path = Path(output_rvc_path)
if not input_tts_path.is_file():
print_message(f"Input file not found: {input_tts_path}", "error")
raise HTTPException(status_code=400, detail=f"Input file {input_tts_path} does not exist.")
pth_path = this_dir / "models" / "rvc_voices" / pth_name
if not pth_path.is_file():
print_message(f"RVC model file not found: {pth_path}", "error")
raise HTTPException(status_code=400, detail=f"Model file {pth_path} does not exist.")
print_message(f"Starting RVC conversion with model: {pth_name}", "debug_rvc")
result_path = run_voice2rvc(input_tts_path, output_rvc_path, pth_path, pitch, method)
if result_path:
print_message("RVC conversion completed successfully", "debug_rvc")
return {"status": "success", "output_path": str(result_path)}
print_message("RVC conversion failed", "error")
raise HTTPException(status_code=500, detail="RVC conversion failed.")
except Exception as e:
print_message(f"Error during Voice2RVC conversion: {e}", "error")
raise HTTPException(status_code=500, detail=str(e)) from e
def run_voice2rvc(input_tts_path, output_rvc_path, pth_path, pitch, method) -> Optional[str]:
"""Run RVC conversion on input audio using specified model and parameters."""
debug_func_entry()
print_message("\033[94mVoice2RVC Convert: Started\033[0m", component="GEN")
generate_start_time = time.time()
# Get settings from config
settings = {
"f0up_key": pitch,
"filter_radius": config.rvc_settings.filter_radius,
"index_rate": config.rvc_settings.index_rate,
"rms_mix_rate": config.rvc_settings.rms_mix_rate,
"protect": config.rvc_settings.protect,
"hop_length": config.rvc_settings.hop_length,
"f0method": method, # This might need to be converted or mapped
"split_audio": config.rvc_settings.split_audio,
"f0autotune": config.rvc_settings.autotune,
"embedder_model": config.rvc_settings.embedder_model,
"training_data_size": config.rvc_settings.training_data_size,
}
input_tts_path = str(input_tts_path)
pth_path = str(pth_path)
if not os.path.isfile(pth_path):
print_message(f"Model file {pth_path} does not exist. Exiting.", "error", "GEN")
return None
model_dir = os.path.dirname(pth_path)
index_files = [file for file in os.listdir(model_dir) if file.endswith(".index")]
index_path = str(os.path.join(model_dir, index_files[0])) if len(index_files) == 1 else ""
print_message(f"Using RVC model: {os.path.basename(pth_path)}", "debug_rvc", "GEN")
print_message(f"Using index file: {os.path.basename(index_path) if index_path else 'None'}", "debug_rvc", "GEN")
infer_pipeline(settings["f0up_key"], settings["filter_radius"], settings["index_rate"],
settings["rms_mix_rate"], settings["protect"], settings["hop_length"],
settings["f0method"], input_tts_path, output_rvc_path, pth_path, index_path,
settings["split_audio"], settings["f0autotune"], settings["embedder_model"],
settings["training_data_size"], config.debugging.debug_rvc)
generate_elapsed_time = time.time() - generate_start_time
print_message(f"\033[94mVoice2RVC Convert: \033[91m{generate_elapsed_time:.2f} seconds.\033[0m", component="GEN")
return output_rvc_path
##################################
# Transcode between file formats #
##################################
async def get_audio_duration(file_path):
"""Get duration of audio file using FFprobe."""
debug_func_entry()
file_path_str = str(file_path)
print_message("\033[94mGet Audio Duration > get_audio_duration > tts_server.py\033[0m", "debug_transcode" or "debug_openai")
print_message(f"├─ Input file: {file_path_str}", "debug_transcode")
try:
probe = ffmpeg.probe(file_path_str)
duration = float(probe['format']['duration'])
print_message(f"└─ Duration: {duration} seconds", "debug_transcode")
return duration
except Exception as e:
print_message(f"Error getting audio duration: {str(e)}", "error")
raise
async def transcode_audio(input_file, output_format, output_file=None):
"""Transcode audio files between different formats using FFmpeg."""
debug_func_entry()
input_file_str = str(input_file)
print_message("\033[94mTranscode Function Entry > transcode_audio > tts_server.py\033[0m", "debug_transcode")
print_message(f"├─ Input file : {input_file_str}", "debug_transcode")
print_message(f"└─ Output format : {output_format}", "debug_transcode")
if output_file is None:
output_file = os.path.splitext(input_file_str)[0] + f".{output_format}"
print_message(f"└─ Output file : {output_file}", "debug_transcode")
if not ffmpeg_installed:
print_message("FFmpeg is not installed. Format conversion is not possible.", "error")
raise RuntimeError("FFmpeg is not installed. Format conversion is not possible.")
input_extension = os.path.splitext(input_file_str)[1][1:].lower()
if input_extension == output_format.lower():
print_message(f"Input file is already in the requested format: {output_format}", "debug_transcode")
return input_file
output_file = os.path.splitext(input_file_str)[0] + f".{output_format}"
print_message(f"└─ Output file : {output_file}", "debug_transcode")
try:
print_message("\033[94mStarting Transcode Process\033[0m", "debug_transcode")
stream = ffmpeg.input(input_file_str)
# Configure format-specific options
format_options = {
'mp3': {
'acodec': 'libmp3lame',
**{'b:a': '192k'},
'ar': 44100,
'ac': 2
},
'opus': {
'acodec': 'libopus',
**{'b:a': '128k'},
'vbr': 'on',
'compression_level': '10',
'frame_duration': '60',
'application': 'voip',
'ar': 48000,
'ac': 2
},
'aac': {
'acodec': 'aac',
**{'b:a': '192k'},
'ar': 44100,
'ac': 2
},
'vorbis': { # for ogg
'acodec': 'libvorbis',
**{'b:a': '192k'},
'ar': 44100,
'ac': 2,
'f': 'ogg' # Force OGG container format
},
'flac': {
'acodec': 'flac',
'compression_level': '8',
'ar': 44100,
'ac': 2
},
'wav': {
'acodec': 'pcm_s16le',
'ar': 44100,
'ac': 2
}
}
if output_format not in format_options:
raise ValueError(f"Unsupported output format: {output_format}")
# Add options and force overwrite
stream = ffmpeg.output(stream, output_file, **format_options[output_format], y=None)
print_message(f"FFmpeg command: {' '.join(ffmpeg.compile(stream))}", "debug_transcode")
_out, _err = ffmpeg.run(stream, capture_stdout=True, capture_stderr=True)
print_message("Transcoding completed successfully", "debug_transcode")
os.remove(input_file_str)
print_message("\033[94mTranscode Complete\033[0m", "debug_transcode")
print_message(f"└─ Output file: {output_file}", "debug_transcode")
return output_file
except ffmpeg.Error as e:
print_message("FFmpeg error:", "error")
print_message(f"stdout: {e.stdout.decode('utf8')}", "error")
print_message(f"stderr: {e.stderr.decode('utf8')}", "error")
raise
except Exception as e:
print_message(f"Error during transcoding: {str(e)}", "error")
raise
##############################
# Central Transcode function #
##############################
async def transcode_audio_if_necessary(output_file, model_audio_format, output_audio_format):
"""Transcode audio to requested format if needed and generate appropriate URLs."""
debug_func_entry()
print_message(f"model_engine.audio_format is: {model_audio_format}", "debug_transcode")
print_message(f"audio format is: {output_audio_format}", "debug_transcode")
print_message("Entering the transcode condition", "debug_transcode")
try:
print_message("Calling transcode_audio function", "debug_transcode")
output_file = await transcode_audio(output_file, output_audio_format)
print_message("Transcode completed successfully", "debug_transcode")
except Exception as e:
print_message(f"Error occurred during transcoding: {str(e)}", "error")
raise
print_message("Transcode condition completed", "debug_transcode")
print_message("Updating output file paths and URLs", "debug_transcode")
# Generate appropriate URLs based on API configuration
if config.api_def.api_use_legacy_api:
output_file_url = f'http://{config.api_def.api_legacy_ip_address}:{config.api_def.api_port_number}/audio/{os.path.basename(output_file)}'
output_cache_url = f'http://{config.api_def.api_legacy_ip_address}:{config.api_def.api_port_number}/audiocache/{os.path.basename(output_file)}'
else:
output_file_url = f'/audio/{os.path.basename(output_file)}'
output_cache_url = f'/audiocache/{os.path.basename(output_file)}'
print_message("Output file paths and URLs updated", "debug_transcode")
print_message(f"Transcode output_file is now : {output_file}", "debug_transcode")
print_message(f"Transcode output_file_url is now : {output_file_url}", "debug_transcode")
print_message(f"Transcode output_cache_url is now: {output_cache_url}", "debug_transcode")
return output_file, output_file_url, output_cache_url
##############################
#### Streaming Generation ####
##############################
@app.get("/api/tts-generate-streaming", response_class=StreamingResponse)
async def apifunction_generate_streaming(text: str, voice: str, language: str, output_file: str):
"""Handle streaming TTS generation via GET request."""
debug_func_entry()
if not model_engine.streaming_capable:
print_message("The selected TTS Engine does not support streaming. To use streaming, please select a TTS", "warning", "GEN")
print_message("Engine that has streaming capability. You can find the streaming support information for", "warning", "GEN")
print_message("each TTS Engine in its 'Engine Information' section of the Gradio interface.", "warning", "GEN")
try:
output_file_path = f'{this_dir / config.get_output_directory() / output_file}.{model_engine.audio_format}'
print_message(f"Starting streaming TTS generation for: {text[:50]}{'...' if len(text) > 50 else ''}")
stream = await generate_audio(text, voice, language, model_engine.temperature_set,
model_engine.repetitionpenalty_set, 1.0, 1.0,
output_file_path, streaming=True)
return StreamingResponse(stream, media_type="audio/wav")
except ValueError as e:
print_message(f"Value error occurred: {str(e)}", "error", "GEN")
return JSONResponse(content={"error": f"Invalid value: {str(e)}"}, status_code=400)
except KeyError as e:
print_message(f"Key error occurred: Missing key {str(e)}", "error", "GEN")
return JSONResponse(content={"error": f"Missing required field: {str(e)}"}, status_code=400)
except FileNotFoundError as e:
print_message(f"File not found: {str(e)}", "error", "GEN")
return JSONResponse(content={"error": f"File not found: {str(e)}"}, status_code=404)
except TypeError as e:
print_message(f"Type error occurred: {str(e)}", "error", "GEN")
return JSONResponse(content={"error": f"Type error: {str(e)}"}, status_code=400)
except RuntimeError as e:
print_message(f"Runtime error occurred: {str(e)}", "error", "GEN")
return JSONResponse(content={"error": "An internal runtime error occurred"}, status_code=500)
@app.post("/api/tts-generate-streaming", response_class=JSONResponse)
async def tts_generate_streaming(_request: Request, text: str = Form(...), voice: str = Form(...),
language: str = Form(...), output_file: str = Form(...)):
"""Handle streaming TTS generation via POST request."""
debug_func_entry()
if not model_engine.streaming_capable:
print_message("The selected TTS Engine does not support streaming. To use streaming, please select a TTS", "warning", "GEN")
print_message("Engine that has streaming capability. You can find the streaming support information for", "warning", "GEN")
print_message("each TTS Engine in its 'Engine Information' section of the Gradio interface.", "warning", "GEN")
try:
output_file_path = f'{this_dir / config.get_output_directory() / output_file}.{model_engine.audio_format}'
print_message(f"Starting TTS generation for file: {os.path.basename(output_file)}")
await generate_audio(text, voice, language, model_engine.temperature_set,
model_engine.repetitionpenalty_set, "1.0", "1.0",
output_file_path, streaming=False)
return JSONResponse(content={"output_file_path": str(output_file)}, status_code=200)
except ValueError as e:
print_message(f"Invalid streaming parameters: {str(e)}", "error", "GEN")
raise HTTPException(status_code=400, detail=str(e)) from e
except IOError as e:
print_message(f"IO error during streaming: {str(e)}", "error", "GEN")
raise HTTPException(status_code=500, detail="Audio streaming failed") from e
except RuntimeError as e:
print_message(f"Runtime error during streaming: {str(e)}", "error", "GEN")
raise HTTPException(status_code=500, detail="Audio generation failed") from e
###################################
# Central generate_audio function #
###################################
async def generate_audio(text, voice, language, temperature, repetition_penalty, speed, pitch, output_file, streaming=False):
"""Generate TTS audio with specified parameters. Supports streaming and non-streaming modes."""
debug_func_entry()
if not model_engine.streaming_capable and streaming:
print_message("The selected TTS Engine does not support streaming. To use streaming, please select a TTS", "warning", "GEN")
print_message("Engine that has streaming capability. You can find the streaming support information for", "warning", "GEN")
print_message("each TTS Engine in the 'Engine Information' section of the Gradio interface.", "warning", "GEN")
raise ValueError("Streaming not supported by current TTS engine")
response = model_engine.generate_tts(text, voice, language, temperature, repetition_penalty, speed, pitch, output_file, streaming)
if streaming:
async def stream_response():
try:
async for chunk in response:
yield chunk
except Exception as e:
print_message(f"Error during streaming audio generation: {str(e)}", "error", "GEN")
raise
return stream_response()
try:
async for _ in response:
pass
except Exception as e:
print_message(f"Error during audio generation: {str(e)}", "error", "GEN")
raise
###########################
#### PREVIEW VOICE API ####
###########################
@app.post("/api/previewvoice/", response_class=JSONResponse)
async def apifunction_preview_voice(
_request: Request,
voice: str = Form(...),
rvccharacter_voice_gen: Optional[str] = Form(None),
rvccharacter_pitch: Optional[float] = Form(None)
):
"""Generate preview audio for selected voice with optional RVC processing."""
debug_func_entry()
try:
language = "en"
output_file_name = "api_preview_voice"
clean_voice_filename = re.sub(r'\.wav$', '', voice.replace(' ', '_'))
clean_voice_filename = re.sub(r'[^a-zA-Z0-9]', ' ', clean_voice_filename)
text = f"Hello, this is a preview of voice {clean_voice_filename}."
rvccharacter_voice_gen = rvccharacter_voice_gen or "Disabled"
rvccharacter_pitch = rvccharacter_pitch if rvccharacter_pitch is not None else 0
print_message(f"Generating preview for voice: {clean_voice_filename}", "debug_tts", "GEN")
output_file_path = this_dir / config.get_output_directory() / f'{output_file_name}.{model_engine.audio_format}'
await generate_audio(
text, voice, language,
model_engine.temperature_set,
model_engine.repetitionpenalty_set,
1.0, 0, output_file_path,
streaming=False
)
if config.rvc_settings.rvc_enabled:
if rvccharacter_voice_gen.lower() in ["disabled", "disable"]:
print_message("def apifunction_preview_voice RVC processing skipped", "debug_tts")
else:
print_message(f"def apifunction_preview_voice processing with RVC: {rvccharacter_voice_gen}", "debug_tts")
rvccharacter_voice_gen = this_dir / "models" / "rvc_voices" / rvccharacter_voice_gen
pth_path = rvccharacter_voice_gen if rvccharacter_voice_gen else config.rvc_settings.rvc_char_model_file