forked from erew123/alltalk_tts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.py
4962 lines (4485 loc) · 212 KB
/
script.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 V2: A Comprehensive TTS and ASR Framework with WebUI Integration
Github: https://github.com/erew123/
This script serves as the core for the Alltalk V2 system, a robust framework combining
Text-to-Speech (TTS) and Automatic Speech Recognition (ASR) capabilities. It is highly
configurable and integrates with Text-Generation-WebUI (TGWUI) while also supporting
standalone deployments. The script initializes configurations, handles subprocess
management, enables API interactions, and provides transcription utilities.
Key Features:
-------------
1. **TTS Engine Management**:
- Dynamically load and swap between TTS engines and models.
- Manage engine-specific configurations and optimize for GPU or CPU usage.
2. **ASR/Transcription Utilities**:
- Integrates Whisper for audio-to-text transcription.
- Supports batch processing, live dictation, and various output formats (JSON, TXT, SRT).
3. **WebUI and API Integration**:
- Extends Text-Generation-WebUI for seamless integration with conversational AI.
- Provides a Gradio-based interface for managing settings and TTS generation.
4. **Enhanced User Configurations**:
- Centralized configuration loader for system-wide consistency.
- Handles first-time setups and runtime environment detection (Docker, Google Colab, etc.).
5. **Audio File Processing**:
- Supports multiple audio formats with validation, pre-processing (noise reduction, bandpass filtering),
and file output management.
- Automatically organizes transcription files and generates metadata summaries.
6. **Real-Time Feedback and Debugging**:
- Extensive debug logging for monitoring function entries, file operations, and network requests.
- Progress tracking for long-running tasks like model loading and transcription.
7. **Command-Line Arguments**:
- Accepts a `--tts_model` argument to bypass the interactive menu and directly set up a specific TTS engine
on the first time start-up:
- `piper`: Sets up the Piper TTS engine.
- `vits`: Sets up the VITS TTS engine.
- `xtts`: Sets up the XTTS TTS engine.
- `none`: Skips model setup entirely.
Requirements:
-------------
- Python 3.8 or later.
- Dependencies listed in the repository's requirements.txt.
- Whisper ASR, PyTorch, Gradio, and other specified modules.
Supported Environments:
-----------------------
- Google Colab
- Docker
- Text-Generation-WebUI (TGWUI)
- Standalone mode
"""
import atexit
import argparse
import gc
import inspect
import importlib
import json
import mimetypes
import os
import platform
import shutil
import signal as system_signal
import subprocess
import sys
import threading
import time
import warnings
import zipfile
from datetime import datetime, timedelta
from pathlib import Path
import gradio as gr
import numpy as np
import requests
from requests.exceptions import ConnectionError as RequestsConnectionError
from requests.exceptions import RequestException
from tqdm import tqdm
import torch
try:
import whisper
import soundfile as sf
import plotly.graph_objects as go
from scipy import signal as scipy_signal
except ImportError as e:
print(f"Error: {e}")
print("=" * 50)
print("🚨 Missing Dependencies Detected 🚨\n")
print(
"It seems you are missing some required packages.\n"
"To resolve this, please install the dependencies by running:\n"
)
print(" 🔹 pip install -r system/requirements/requirements_standalone.txt")
print(" 🔹 or use the 'atsetup' command\n")
print("Once the installation is complete, try running the script again.")
print("=" * 50)
sys.exit(1) # Exit the script to avoid further errors
this_dir = Path(__file__).parent.resolve()
# Note: The following function names are reserved for TGWUI integration.
# When running under text-generation-webui, these functions will be imported from
# system/TGWUI Extension/script.py when in TGWUI's Python environment/extensions dir.
#
# Reserved names:
# - output_modifier
# - input_modifier
# - state_modifier
# - ui
# - history_modifier
# - remove_tts_from_history
# - toggle_text_in_history
TGWUI_AVAILABLE = False
# pylint: disable=import-outside-toplevel
def output_modifier(string, state):
"""Modify chat output (required for TGWUI)"""
try:
from .system.TGWUI_Extension.script import (
output_modifier as tgwui_output_modifier,
)
except ImportError:
from system.TGWUI_Extension.script import (
output_modifier as tgwui_output_modifier,
)
return tgwui_output_modifier(string, state)
def input_modifier(string, state):
"""Modify chat input (required for TGWUI)"""
try:
from .system.TGWUI_Extension.script import (
input_modifier as tgwui_input_modifier,
)
except ImportError:
from system.TGWUI_Extension.script import input_modifier as tgwui_input_modifier
return tgwui_input_modifier(string, state)
def state_modifier(state):
"""Modify chat state (required for TGWUI)"""
try:
from .system.TGWUI_Extension.script import (
state_modifier as tgwui_state_modifier,
)
except ImportError:
from system.TGWUI_Extension.script import state_modifier as tgwui_state_modifier
return tgwui_state_modifier(state)
def ui():
"""Create extension UI (required for TGWUI)"""
try:
from system.TGWUI_Extension.script import ui as tgwui_ui
return tgwui_ui()
except ImportError:
# Return empty interface if not in TGWUI
return gr.Blocks()
def history_modifier(history):
"""Modify chat history (required for TGWUI)"""
try:
from .system.TGWUI_Extension.script import (
history_modifier as tgwui_history_modifier,
)
except ImportError:
from system.TGWUI_Extension.script import (
history_modifier as tgwui_history_modifier,
)
return tgwui_history_modifier(history)
def remove_tts_from_history(history):
"""Remove TTS from history (required for TGWUI)"""
try:
from .system.TGWUI_Extension.script import (
remove_tts_from_history as tgwui_remove_tts,
)
except ImportError:
from system.TGWUI_Extension.script import (
remove_tts_from_history as tgwui_remove_tts,
)
return tgwui_remove_tts(history)
def toggle_text_in_history(history):
"""Toggle text in history (required for TGWUI)"""
try:
from .system.TGWUI_Extension.script import (
toggle_text_in_history as tgwui_toggle_text,
)
except ImportError:
from system.TGWUI_Extension.script import (
toggle_text_in_history as tgwui_toggle_text,
)
return tgwui_toggle_text(history)
# pylint: disable=ungrouped-imports,unused-import,import-outside-toplevel
try:
from modules import chat, shared, ui_chat
TGWUI_AVAILABLE = True
except ImportError:
class DummyShared: # pylint: disable=too-few-public-methods
"fake class relating to how we import or dont import TGWUI's remote extension"
processing_message = ""
class DummyState: # pylint: disable=too-few-public-methods
"fake class relating to how we import or dont import TGWUI's remote extension"
def __init__(self):
self.mode = "chat" # Add default mode
shared = DummyShared()
# pylint: enable=ungrouped-imports,unused-import,import-outside-toplevel
#########################
# Central config loader #
#########################
# Confguration file management for confignew.json
try:
from .config import (
AlltalkConfig,
AlltalkTTSEnginesConfig,
AlltalkNewEnginesConfig,
) # TGWUI import
from .system.gradio_pages.help_content import AllTalkHelpContent
from .system.gradio_pages.alltalk_diskspace import get_disk_interface
from .system.proxy_module.proxy_manager import ProxyManager
from .system.proxy_module.interface import create_proxy_interface
except ImportError:
from config import (
AlltalkConfig,
AlltalkTTSEnginesConfig,
AlltalkNewEnginesConfig,
) # Standalone import
from system.gradio_pages.help_content import AllTalkHelpContent
from system.gradio_pages.alltalk_diskspace import get_disk_interface
from system.proxy_module.proxy_manager import ProxyManager
from system.proxy_module.interface import create_proxy_interface
def initialize_configs():
"""Initialize all configuration instances"""
config_initalize = AlltalkConfig.get_instance()
tts_engines_config_initalize = AlltalkTTSEnginesConfig.get_instance()
new_engines_config_initalize = AlltalkNewEnginesConfig.get_instance()
return config_initalize, tts_engines_config_initalize, new_engines_config_initalize
# pylint: enable=import-outside-toplevel
# Load in configs
config, tts_engines_config, new_engines_config = initialize_configs()
config.save() # Force the config file to save in case it was missing new any settings
#########################################
# START-UP # State Dictionary (GLOABLS) #
#########################################
_state = {
'process': None,
'running_on_google_colab': False, # Are we running on a Google Colab Server?
'tunnel_url_1': None, # Used for Google Colab and finding the tunnel URL for API address
'tunnel_url_2': None, # Used for Google Colab and finding the tunnel URL for Gradio address
'running_in_docker': False, # Are we running on a Docker Server?
'docker_url': f"http://localhost:{config.api_def.api_port_number}", # The inital URL used by docker for API communication in gradio
'alltalk_protocol': "http://", # HTTP is always used, bar Docker or Google Colab. Can be configured here though
'alltalk_ip_port': f"127.0.0.1:{config.api_def.api_port_number}", # IP/Port used for Docker, Google Colab or default
'my_current_url': "null",
'srv_models_available': None, # The current models available for the current TTS engine, pulled from the tts_server's API
'srv_current_model_loaded': None, # The current model loaded, Initally loaded from central config and later pulled from the tts_server's API
'srv_engines_available': None, # The current TTS engines available, Initally loaded from central config and later pulled from the tts_server's API
'srv_current_engine_loaded': None, # The current TTS engines loaded in, Initally loaded from central config and later pulled from the tts_server's API
'gradio_languages_list': None, # The list of languauges disaplyed in the Gradio interface.
'whisper_model': None, # Used to track the whisper model used for dictation etc
'proxy_manager': None # Used for the Proxy manager
}
############################################################
# START-UP # Populate _state Engine info - Gradio Needs it #
############################################################
def initialize_engine_state(_state):
"""Initialize engine state from central config"""
_state['srv_current_engine_loaded'] = tts_engines_config.engine_loaded
_state['srv_engines_available'] = tts_engines_config.get_engine_names_available()
_state['srv_current_model_loaded'] = tts_engines_config.selected_model
return _state
# Call this after creating _state
_state = initialize_engine_state(_state)
##################################################################
# START-UP # Populate Language Options Choices - Gradio Needs it #
##################################################################
with open(os.path.join(this_dir, "system", "config", "languages.json"), "r", encoding="utf-8") as f:
_state['gradio_languages_list'] = json.load(f)
##########################
# 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} script.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")
###########################
# Central config updaters #
###########################
def update_settings_at(
delete_output_wavs,
gradio_interface,
gradio_port_number,
upd_output_folder,
api_port_number,
gr_debug_tts,
transcode_audio_format,
generate_help_page,
voice2rvc_page,
tts_generator_page,
tts_engines_settings_page,
alltalk_documentation_page,
api_documentation_page,
):
"""Update AllTalk main settings using the centralized config system"""
debug_func_entry()
try:
# Get the current config instance
upd_set_config = AlltalkConfig.get_instance()
# Update main settings
upd_set_config.delete_output_wavs = delete_output_wavs
upd_set_config.gradio_interface = gradio_interface == "Enabled"
upd_set_config.output_folder = upd_output_folder
upd_set_config.api_def.api_port_number = api_port_number
upd_set_config.gradio_port_number = gradio_port_number
upd_set_config.transcode_audio_format = transcode_audio_format
# Update debugging options
for key in vars(upd_set_config.debugging):
if not key.startswith("_"): # Skip private attributes
setattr(upd_set_config.debugging, key, key in gr_debug_tts)
# Update gradio pages settings
upd_set_config.gradio_pages.Generate_Help_page = generate_help_page
upd_set_config.gradio_pages.Voice2RVC_page = voice2rvc_page
upd_set_config.gradio_pages.TTS_Generator_page = tts_generator_page
upd_set_config.gradio_pages.TTS_Engines_Settings_page = tts_engines_settings_page
upd_set_config.gradio_pages.alltalk_documentation_page = alltalk_documentation_page
upd_set_config.gradio_pages.api_documentation_page = api_documentation_page
# Save the updated configuration
upd_set_config.save()
# Tell tts_server.py to update
get_alltalk_settings()
print_message("Default Settings Saved")
return "Settings updated successfully!"
except (AttributeError, TypeError) as e:
print_message(
f"Configuration structure error: {str(e)}",
message_type="error"
)
return "Error updating settings: Invalid configuration structure"
except (OSError, IOError) as e:
print_message(
f"File system error while saving configuration: {str(e)}",
message_type="error"
)
return "Error saving settings: File system error"
except ValueError as e:
print_message(
f"Invalid value provided for configuration: {str(e)}",
message_type="error"
)
return "Error updating settings: Invalid value provided"
def update_settings_api(
api_length_stripping,
api_legacy_ip_address,
api_allowed_filter,
api_max_characters,
api_use_legacy_api,
api_text_filtering,
api_narrator_enabled,
api_text_not_inside,
api_language,
api_output_file_name,
api_output_file_timestamp,
api_autoplay,
api_autoplay_volume,
):
"""Update API settings using the centralized config system"""
debug_func_entry()
try:
# Get the current config instance
upd_config = AlltalkConfig.get_instance()
# Update API settings
upd_config.api_def.api_length_stripping = api_length_stripping
upd_config.api_def.api_legacy_ip_address = api_legacy_ip_address
upd_config.api_def.api_allowed_filter = api_allowed_filter
upd_config.api_def.api_max_characters = api_max_characters
upd_config.api_def.api_use_legacy_api = (
api_use_legacy_api == "AllTalk v1 API (Legacy)"
)
upd_config.api_def.api_text_filtering = api_text_filtering
upd_config.api_def.api_narrator_enabled = api_narrator_enabled
upd_config.api_def.api_text_not_inside = api_text_not_inside
upd_config.api_def.api_language = api_language
upd_config.api_def.api_output_file_name = api_output_file_name
upd_config.api_def.api_output_file_timestamp = (
api_output_file_timestamp == "Timestamp files"
)
upd_config.api_def.api_autoplay = api_autoplay == "Play remotely"
upd_config.api_def.api_autoplay_volume = api_autoplay_volume
# Save the updated configuration
upd_config.save()
# Tell tts_server.py to update
get_alltalk_settings()
print_message("API Settings Saved")
return "Default API settings updated successfully!"
except (AttributeError, TypeError) as e:
print_message(
f"Configuration structure error: {str(e)}",
message_type="error"
)
return "Error updating settings: Invalid configuration structure"
except (OSError, IOError) as e:
print_message(
f"File system error while saving configuration: {str(e)}",
message_type="error"
)
return "Error saving settings: File system error"
except ValueError as e:
print_message(
f"Invalid value provided for configuration: {str(e)}",
message_type="error"
)
return "Error updating settings: Invalid value provided"
def update_settings_tgwui(activate, autoplay, show_text, language, narrator_enabled):
"""Update Text-gen-webui settings using the centralized config system"""
debug_func_entry()
try:
# Get the current config instance
tgwui_config = AlltalkConfig.get_instance()
# Update TGWUI settings
tgwui_config.tgwui.tgwui_activate_tts = activate == "Enabled"
tgwui_config.tgwui.tgwui_autoplay_tts = autoplay == "Enabled"
tgwui_config.tgwui.tgwui_show_text = show_text == "Enabled"
tgwui_config.tgwui.tgwui_language = language
tgwui_config.tgwui.tgwui_narrator_enabled = narrator_enabled
# Save the updated configuration
tgwui_config.save()
print_message("Default Text-gen-webui Settings Saved")
return "Settings updated successfully!"
except (AttributeError, TypeError) as e:
error_msg = f"Configuration structure error: {str(e)}"
return_message = "Error updating settings: Invalid configuration structure"
except (OSError, IOError) as e:
error_msg = f"File system error while saving configuration: {str(e)}"
return_message = "Error saving settings: File system error"
except ValueError as e:
error_msg = f"Invalid value provided for configuration: {str(e)}"
return_message = "Error updating settings: Invalid value provided"
print_message(error_msg, message_type="error")
return return_message
def update_rvc_settings(
rvc_enabled,
rvc_char_model_file,
rvc_narr_model_file,
split_audio,
autotune,
pitch,
filter_radius,
index_rate,
rms_mix_rate,
protect,
hop_length,
f0method,
embedder_model,
training_data_size,
progress=None,
):
"""Update RVC settings using the centralized config system"""
debug_func_entry()
try:
# Get the current config instance
rvc_set_config = AlltalkConfig.get_instance()
# Update RVC settings
rvc_set_config.rvc_settings.rvc_enabled = rvc_enabled
rvc_set_config.rvc_settings.rvc_char_model_file = rvc_char_model_file
rvc_set_config.rvc_settings.rvc_narr_model_file = rvc_narr_model_file
rvc_set_config.rvc_settings.split_audio = split_audio
rvc_set_config.rvc_settings.autotune = autotune
rvc_set_config.rvc_settings.pitch = pitch
rvc_set_config.rvc_settings.filter_radius = filter_radius
rvc_set_config.rvc_settings.index_rate = index_rate
rvc_set_config.rvc_settings.rms_mix_rate = rms_mix_rate
rvc_set_config.rvc_settings.protect = protect
rvc_set_config.rvc_settings.hop_length = hop_length
rvc_set_config.rvc_settings.f0method = f0method
rvc_set_config.rvc_settings.embedder_model = embedder_model
rvc_set_config.rvc_settings.training_data_size = training_data_size
def ensure_directory_exists(directory):
"""Confirm a directory exists"""
if not os.path.exists(directory):
os.makedirs(directory)
def load_file_urls(json_path):
"""Load and return JSON data from specified file path."""
with open(json_path, "r", encoding="utf-8") as json_file:
return json.load(json_file)
def download_file(useurl, dest_path):
"""
Download file from URL and save to specified path.
Args:
url (str): URL to download from
dest_path (str): Path where file will be saved
"""
# First number (5) = connection timeout (time to establish connection)
# Second number (30) = read timeout (time between bytes received)
file_response = requests.get(useurl, stream=True, timeout=(5, 30))
file_response.raise_for_status()
with open(dest_path, "wb") as downloaded_file:
for chunk in file_response.iter_content(chunk_size=8192):
downloaded_file.write(chunk)
if rvc_enabled:
base_dir = os.path.join(this_dir, "models", "rvc_base")
rvc_voices_dir = os.path.join(this_dir, "models", "rvc_voices")
ensure_directory_exists(base_dir)
ensure_directory_exists(rvc_voices_dir)
json_path = os.path.join(
this_dir, "system", "tts_engines", "rvc_files.json"
)
file_urls = load_file_urls(json_path)
for idx, file in enumerate(file_urls):
if not os.path.exists(os.path.join(base_dir, file)):
progress(
idx / len(file_urls),
desc=f"Downloading Required RVC Files: {file}...",
)
print(
f"[{config.branding}TTS] Downloading {file}..."
) # Print statement for terminal
download_file(file_urls[file], os.path.join(base_dir, file))
download_result = (
"All RVC Base Files are present."
if len(file_urls) > 0
else "All files are present."
)
print_message(download_result)
# Save the updated configuration
rvc_set_config.save()
# Tell tts_server.py to update
get_alltalk_settings()
return "RVC settings updated successfully!"
except RequestException as e:
error_msg = f"Error downloading RVC files: {str(e)}"
return_message = "Error downloading RVC files: Network or server error"
except json.JSONDecodeError as e:
error_msg = f"Error reading RVC configuration file: {str(e)}"
return_message = "Error with RVC configuration: Invalid JSON format"
except (AttributeError, TypeError) as e:
error_msg = f"Configuration structure error: {str(e)}"
return_message = "Error updating RVC settings: Invalid configuration structure"
except (OSError, IOError) as e:
error_msg = f"File system error while saving/creating directories: {str(e)}"
return_message = "Error with RVC files: File system error"
print_message(error_msg, message_type="error")
return return_message
def update_proxy_settings(
proxy_enabled,
start_on_startup,
gradio_proxy_enabled,
api_proxy_enabled,
external_ip,
gradio_cert_name,
api_cert_name,
cert_validation,
logging_enabled,
log_level
):
"""Update proxy settings using the centralized config system"""
debug_func_entry()
try:
# Get the current config instance
config = AlltalkConfig.get_instance()
# Update proxy settings
config.proxy_settings.proxy_enabled = proxy_enabled
config.proxy_settings.start_on_startup = start_on_startup
config.proxy_settings.gradio_proxy_enabled = gradio_proxy_enabled
config.proxy_settings.api_proxy_enabled = api_proxy_enabled
config.proxy_settings.external_ip = external_ip
config.proxy_settings.gradio_cert_name = gradio_cert_name
config.proxy_settings.api_cert_name = api_cert_name
config.proxy_settings.cert_validation = cert_validation
config.proxy_settings.logging_enabled = logging_enabled
config.proxy_settings.log_level = log_level
# Save the updated configuration
config.save()
print_message("Proxy Settings Saved")
return "Proxy settings updated successfully!"
except Exception as e:
print_message(f"Error updating proxy settings: {str(e)}", message_type="error")
return f"Error updating proxy settings: {str(e)}"
# Add to your state dictionary initialization
def initialize_proxy_state(_state):
"""Initialize proxy state"""
config = AlltalkConfig.get_instance()
_state['proxy_process'] = None
_state['proxy_status'] = 'stopped'
_state['proxy_enabled'] = config.proxy_settings.proxy_enabled
_state['proxy_gradio_enabled'] = config.proxy_settings.gradio_proxy_enabled
_state['proxy_api_enabled'] = config.proxy_settings.api_proxy_enabled
return _state
# Modify your existing initialize_engine_state function:
def initialize_engine_state(_state):
"""Initialize engine state from central config"""
_state = initialize_proxy_state(_state) # Add proxy initialization
_state['srv_current_engine_loaded'] = tts_engines_config.engine_loaded
_state['srv_engines_available'] = tts_engines_config.get_engine_names_available()
_state['srv_current_model_loaded'] = tts_engines_config.selected_model
return _state
###########################################################################
# START-UP # Silence Character Normaliser when it checks the Ready Status #
###########################################################################
warnings.filterwarnings(
"ignore", message="Trying to detect encoding from a tiny portion"
)
###########################################
# START-UP # AllTalk allowed startup time #
###########################################
startup_wait_time = 240
# You can change the above setting to a larger number to allow AllTAlk more time to start up.
# The default setting is 240 seconds (4 minutes). If its taking longer though, you may have a
# Very old system or system issue.
##############################################
# START-UP # Load confignew.json into params #
##############################################
config = AlltalkConfig.get_instance()
github_site = "erew123"
github_repository = "alltalk_tts"
github_branch = "alltalkbeta"
current_folder = os.path.basename(os.getcwd())
output_folder = config.get_output_directory()
delete_output_wavs_setting = config.delete_output_wavs
gradio_enabled = config.gradio_interface
script_path = this_dir / "tts_server.py"
############################################
# START-UP # Display initial splash screen #
############################################
# pylint: disable=line-too-long,anomalous-backslash-in-string
print_message(
"\033[94m _ _ _ \033[1;35m_____ _ _ \033[0m _____ _____ ____ "
)
print_message(
"\033[94m / \ | | |\033[1;35m_ _|_ _| | | __ \033[0m |_ _|_ _/ ___| "
)
print_message(
"\033[94m / _ \ | | |\033[1;35m | |/ _` | | |/ / \033[0m | | | | \___ \ "
)
print_message(
"\033[94m / ___ \| | |\033[1;35m | | (_| | | < \033[0m | | | | ___) |"
)
print_message(
"\033[94m/_/ \_\_|_|\033[1;35m |_|\__,_|_|_|\_\ \033[0m |_| |_| |____/ "
)
print_message("")
# pylint: enable=line-too-long,anomalous-backslash-in-string
#############################################################################
# START-UP # Check current folder name has dashes '-' in it and error if so #
#############################################################################
# Get the directory of the current script
this_script_path = Path(__file__).resolve()
this_script_dir = this_script_path.parent
# Get the current folder name
this_current_folder = this_script_dir.name
if "-" in this_current_folder:
print_message("")
print_message( # pylint: disable=line-too-long
"The current folder name contains a dash ('\033[93m-\033[0m') and this causes errors/issues. Please ensure",
message_type="warning",
)
# pylint: disable=line-too-long
print_message(
"the folder name does not have a dash e.g. rename ('\033[93malltalk_tts-main\033[0m') to ('\033[93malltalk_tts\033[0m').",
message_type="warning",
)
print_message("")
print_message(
"\033[92mCurrent folder:\033[0m {this_current_folder}", message_type="warning"
)
sys.exit(1)
# pylint: disable=ungrouped-imports,unused-import,import-outside-toplevel,import-error
##############################################
# START-UP # Check if we are on Google Colab #
##############################################
def check_google_colab():
"""
Test if we are running on a google colab server
"""
debug_func_entry()
try:
import google.colab
return True
except ImportError:
return False
_state['running_on_google_colab'] = check_google_colab()
###############################################################################
# START-UP # Test if we are running within Text-gen-webui or as a Standalone #
###############################################################################
try:
from modules import chat, shared, ui_chat
from modules.logging_colors import logger
from modules.ui import create_refresh_button
from modules.utils import gradio
print_message("\033[92mStart-up Mode : \033[93mText-gen-webui mode\033[0m")
running_in_standalone = False
running_in_tgwui = True
except ModuleNotFoundError:
running_in_standalone = True
running_in_tgwui = False
print_message("\033[92mStart-up Mode : \033[93mStandalone mode\033[0m")
# pylint: enable=ungrouped-imports,unused-import,import-outside-toplevel,import-error
######################################################
# START-UP # Check if this is a first time start-up #
######################################################
def run_firsttime_script(tts_model=None):
"""
Run the first time startup script based on the current environment
(Google Colab, standalone, or TGWUI). Optionally, pass a TTS model
argument to the script for direct configuration.
Args:
tts_model (str): Optional. TTS model to set up ('piper', 'vits', 'xtts', or 'none').
"""
debug_func_entry()
try:
# Get the current config instance
firstrun_config = AlltalkConfig.get_instance()
# Determine the script path based on environment
if _state['running_on_google_colab']:
firstrun_script_path = "/content/alltalk_tts/system/config/firstrun.py"
elif running_in_standalone:
firstrun_script_path = os.path.join(this_dir, "system", "config", "firstrun.py")
elif running_in_tgwui:
firstrun_script_path = os.path.join(
this_dir, "system", "config", "firstrun_tgwui.py"
)
else:
firstrun_script_path = os.path.join(this_dir, "system", "config", "firstrun.py")
# Prepare the subprocess command
command = [sys.executable, firstrun_script_path]
# Append the --tts_model argument if provided
if tts_model:
if tts_model not in ['piper', 'vits', 'xtts', 'none']:
raise ValueError(f"Invalid tts_model value: {tts_model}")
command.extend(['--tts_model', tts_model])
# Run the script
subprocess.run(command, check=True)
# Reload the configuration after script execution
firstrun_config.reload()
except subprocess.CalledProcessError as e:
error_msg = f"Error running first-time setup script: {str(e)}"
print_message(error_msg, message_type="error")
except (FileNotFoundError, PermissionError) as e:
error_msg = f"File system error during first-time setup: {str(e)}"
print_message(error_msg, message_type="error")
except ValueError as e:
error_msg = f"Invalid argument passed to first-time setup script: {str(e)}"
print_message(error_msg, message_type="error")
# Add argparse for command-line arguments
parser = argparse.ArgumentParser(description="Run the first-time setup script.")
parser.add_argument(
"--tts_model",
type=str,
choices=["piper", "vits", "xtts", "none"],
help="Specify the TTS model to set up (piper, vits, xtts, or none).",
)
# Parse the arguments
args = parser.parse_args()
# Call the function to run the startup script
run_firsttime_script(tts_model=args.tts_model)
###########################################################
# START-UP # Delete files in outputs folder if configured #
###########################################################
def delete_old_files(folder_path, amt_days_to_keep):
"""
Delete files in the output folder that are X days old
"""
debug_func_entry()
current_time = datetime.now()
print_message(
"\033[92mWAV file deletion :\033[93m", delete_output_wavs_setting, "\033[0m"
)
for file_name in os.listdir(folder_path):
file_path = os.path.join(folder_path, file_name)
if os.path.isfile(file_path):
file_creation_time = datetime.fromtimestamp(os.path.getctime(file_path))
age = current_time - file_creation_time
if age > timedelta(days=amt_days_to_keep):
os.remove(file_path)
# Check and perform file deletion
if delete_output_wavs_setting.strip().lower() == "disabled":
print_message("\033[92mWAV file deletion :\033[93m Disabled\033[0m")
else:
try:
days_to_keep = int(delete_output_wavs_setting.split()[0])
delete_old_files(output_folder, days_to_keep)
except ValueError:
# pylint: disable=line-too-long
print_message(
"\033[92mWAV file deletion :\033[93m Invalid setting for deleting old wav files. Please use 'Disabled' or 'X Days' format\033[0m"
)
#####################################################################
# START-UP # Check Githubs last update and output into splashscreen #
#####################################################################
def format_datetime(iso_str):
"""
Formats an ISO datetime string into a human-readable format with ordinal day numbers.
Example: Converts "2024-03-19T10:30:00Z" to "19th March 2024 at 10:30"
"""
debug_func_entry()
def _ordinal(n):
"""Helper function to convert numbers to ordinal form (1st, 2nd, 3rd, etc)"""
debug_func_entry()
suffix = "th" if 4 <= n % 100 <= 20 else {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th")
return f"{n}{suffix}"
dt = datetime.strptime(iso_str, "%Y-%m-%dT%H:%M:%SZ")
return dt.strftime(f"{_ordinal(dt.day)} %B %Y at %H:%M")
def fetch_latest_commit_sha_and_date(owner, repo, branch):
"""
Fetch the latest commit SHA and date from a GitHub repository branch.
Args:
owner (str): GitHub repository owner
repo (str): Repository name
branch (str): Branch name to check
Returns:
tuple: (commit_sha, commit_date) or (None, None) if fetch fails
"""
debug_func_entry()
# Modified URL to include the branch
github_url = f"https://api.github.com/repos/{owner}/{repo}/commits/{branch}"
try:
# Add timeout for both connect and read operations
github_response = requests.get(github_url, timeout=(5, 30))
if github_response.status_code == 200:
commit_data = github_response.json()
github_latest_commit_sha = commit_data["sha"]
github_latest_commit_date = commit_data["commit"]["committer"]["date"]
return github_latest_commit_sha, github_latest_commit_date
# pylint: disable=line-too-long
print_message(
f"\033[92mGithub updated :\033[91m Failed to fetch the latest commit from branch {branch} due to an unexpected response from GitHub"
)
return None, None
except (RequestsConnectionError, requests.Timeout): # Added Timeout to caught exceptions
print_message(
"\033[92mGithub updated :\033[91m Could not reach GitHub to check for updates\033[0m"
)
return None, None
def read_or_initialize_sha(file_path, owner, repo, branch):
"""
Read SHA from existing file or initialize with latest commit SHA if file doesn't exist.
"""
debug_func_entry()
if os.path.exists(file_path):
with open(file_path, "r", encoding="utf-8") as file:
current_data = json.load(file)
return current_data.get("last_known_commit_sha")
else:
# File doesn't exist, fetch the latest SHA and create the file
current_commit_sha, _ = fetch_latest_commit_sha_and_date(owner, repo, branch)
if current_commit_sha:
with open(file_path, "w", encoding="utf-8") as file:
json.dump({"last_known_commit_sha": current_commit_sha}, file)
return current_commit_sha
return None
def update_sha_file(file_path, new_sha):
"""
Update the stored commit SHA in the specified file.
"""
debug_func_entry()
with open(file_path, "w", encoding="utf-8") as file:
json.dump({"last_known_commit_sha": new_sha}, file)
# Define the file path based on your directory structure