-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathpandrator_installer_launcher.py
More file actions
1786 lines (1514 loc) · 85.4 KB
/
pandrator_installer_launcher.py
File metadata and controls
1786 lines (1514 loc) · 85.4 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
import os
import subprocess
import logging
import time
import shutil
import requests
import threading
import customtkinter as ctk
from datetime import datetime
import atexit
import psutil
import json
import tkinter.messagebox as messagebox
import traceback
import tempfile
import sys
import ctypes
import winreg
from dulwich import porcelain
import packaging.version
from CTkMessagebox import CTkMessagebox
class ScrollableFrame(ctk.CTkScrollableFrame):
def __init__(self, container, *args, **kwargs):
super().__init__(container, *args, **kwargs)
self.inner_frame = ctk.CTkFrame(self, fg_color="transparent")
self.inner_frame.pack(fill="both", expand=True)
def get_inner_frame(self):
return self.inner_frame
class PandratorInstaller(ctk.CTk):
def __init__(self):
super().__init__()
self.initial_working_dir = os.getcwd()
# Check for spaces in the working directory
if ' ' in self.initial_working_dir:
self.title("Warning: Path Contains Spaces")
warning_message = (
f"⚠️ WARNING: Your installation path contains spaces:\n\n"
f"{self.initial_working_dir}\n\n"
f"This will likely cause problems with Conda and may prevent Pandrator from installing correctly.\n\n"
f"It's strongly recommended to move this installer to a path without spaces, such as:\n"
f"C:\\Pandrator\n\n"
f"Would you like to exit the installer so you can move it to a better location?"
)
result = messagebox.askyesno("Path Contains Spaces", warning_message, icon="warning")
if result:
sys.exit(0)
else:
messagebox.showinfo(
"Continuing With Risk",
"Installation will continue, but you may encounter errors.\n"
"If installation fails, please restart the installer from a path without spaces."
)
# Define instance variables for checkboxes
self.pandrator_var = ctk.BooleanVar(value=True)
self.xtts_var = ctk.BooleanVar(value=False)
self.xtts_cpu_var = ctk.BooleanVar(value=False)
self.silero_var = ctk.BooleanVar(value=False)
self.rvc_var = ctk.BooleanVar(value=False)
# Define instance variables for launch options
self.launch_pandrator_var = ctk.BooleanVar(value=True)
self.launch_xtts_var = ctk.BooleanVar(value=False)
self.lowvram_var = ctk.BooleanVar(value=False)
self.deepspeed_var = ctk.BooleanVar(value=False)
self.xtts_cpu_launch_var = ctk.BooleanVar(value=False)
self.launch_silero_var = ctk.BooleanVar(value=False)
# Initialize process attributes
self.xtts_process = None
self.pandrator_process = None
self.silero_process = None
self.title("Pandrator Installer & Launcher")
# Calculate 92% of screen height and get full screen width
screen_width = self.winfo_screenwidth()
screen_height = self.winfo_screenheight()
window_height = int(screen_height * 0.92)
# Set the window geometry to full width and 92% height, positioned at the top
self.geometry(f"{screen_width}x{window_height}+0+0")
ctk.set_appearance_mode("dark")
ctk.set_default_color_theme("blue")
# Create main scrollable frame
self.main_frame = ScrollableFrame(self)
self.main_frame.pack(fill="both", expand=True, padx=10, pady=10)
# Content Frame (to align content to the top)
self.content_frame = ctk.CTkFrame(self.main_frame.get_inner_frame(), fg_color="transparent")
self.content_frame.pack(fill="both", expand=True)
# Title
self.title_label = ctk.CTkLabel(self.content_frame, text="Pandrator Installer & Launcher", font=("Arial", 32, "bold"))
self.title_label.pack(pady=(20, 10))
# Information Text Area
self.info_text = ctk.CTkTextbox(self.content_frame, height=100, wrap="word", font=("Arial", 12))
self.info_text.pack(fill="x", padx=20, pady=10)
self.info_text.insert("1.0", "This tool will help you set up and run Pandrator as well as TTS engines and tools. "
"It will install Pandrator, Miniconda, required Python packages, "
"and dependencies (Calibre, Visual Studio C++ Build Tools)."
"To uninstall Pandrator, simply delete the Pandrator folder.\n\n"
"The installation will take between 3 and 30GB of disk space depending on the number of selected options.")
self.info_text.configure(state="disabled")
# New frame to contain installation and launch frames
self.main_options_frame = ctk.CTkFrame(self.content_frame)
self.main_options_frame.pack(fill="both", expand=True, padx=20, pady=10)
self.main_options_frame.grid_columnconfigure(0, weight=1)
self.main_options_frame.grid_columnconfigure(1, weight=1)
# Installation Frame
self.installation_frame = ctk.CTkFrame(self.main_options_frame)
self.installation_frame.grid(row=0, column=0, padx=(0, 10), pady=10, sticky="nsew")
ctk.CTkLabel(self.installation_frame, text="Install", font=("Arial", 20, "bold")).pack(anchor="w", padx=10, pady=(10, 5))
# Build Tools notice and button section
build_tools_frame = ctk.CTkFrame(self.installation_frame, fg_color="#2C2C2C")
build_tools_frame.pack(fill="x", padx=10, pady=(5, 15))
admin_warning = ctk.CTkLabel(
build_tools_frame,
text="⚠️ IMPORTANT: Pandrator Installer must be run as administrator to install Build Tools!",
font=("Arial", 11, "bold"),
text_color="#FF9900",
justify="left"
)
admin_warning.pack(anchor="w", padx=10, pady=(10, 5))
build_tools_label = ctk.CTkLabel(
build_tools_frame,
text="Visual C++ Build Tools are required for installation.\nIf not already installed:",
font=("Arial", 11),
justify="left"
)
build_tools_label.pack(anchor="w", padx=10, pady=(0, 5))
build_tools_steps = ctk.CTkLabel(
build_tools_frame,
text="1. Click the button below to install them\n2. After installation, close all command prompt/PowerShell windows\n3. Restart this installer",
font=("Arial", 10),
justify="left"
)
build_tools_steps.pack(anchor="w", padx=20, pady=(0, 5))
self.build_tools_button = ctk.CTkButton(
build_tools_frame,
text="Install Visual C++ Build Tools",
command=self.open_build_tools_installer,
width=200
)
self.build_tools_button.pack(anchor="w", padx=10, pady=(0, 10))
self.pandrator_checkbox = ctk.CTkCheckBox(self.installation_frame, text="Pandrator", variable=self.pandrator_var)
self.pandrator_checkbox.pack(anchor="w", padx=10, pady=(5, 0))
ctk.CTkLabel(self.installation_frame, text="TTS Engines", font=("Arial", 14, "bold")).pack(anchor="w", padx=10, pady=(20, 0))
ctk.CTkLabel(self.installation_frame, text="You can select and install new engines and tools after the initial installation.", font=("Arial", 10, "bold")).pack(anchor="w", padx=10, pady=(0, 10))
engine_frame = ctk.CTkFrame(self.installation_frame, fg_color="transparent")
engine_frame.pack(fill="x", padx=10, pady=(0, 10))
self.xtts_checkbox = ctk.CTkCheckBox(engine_frame, text="XTTS", variable=self.xtts_var)
self.xtts_checkbox.pack(side="left", padx=(0, 20), pady=5)
self.xtts_cpu_checkbox = ctk.CTkCheckBox(engine_frame, text="XTTS CPU only", variable=self.xtts_cpu_var)
self.xtts_cpu_checkbox.pack(side="left", padx=(0, 20), pady=5)
self.silero_checkbox = ctk.CTkCheckBox(engine_frame, text="Silero", variable=self.silero_var)
self.silero_checkbox.pack(side="left", padx=(0, 20), pady=5)
ctk.CTkLabel(self.installation_frame, text="Other tools", font=("Arial", 14, "bold")).pack(anchor="w", padx=10, pady=(20, 5))
self.rvc_checkbox = ctk.CTkCheckBox(self.installation_frame, text="RVC (rvc-python)", variable=self.rvc_var)
self.rvc_checkbox.pack(anchor="w", padx=10, pady=5)
self.whisperx_var = ctk.BooleanVar(value=False)
self.whisperx_checkbox = ctk.CTkCheckBox(self.installation_frame, text="WhisperX (needed for dubbing and XTTS training)", variable=self.whisperx_var)
self.whisperx_checkbox.pack(anchor="w", padx=10, pady=5)
self.xtts_finetuning_var = ctk.BooleanVar(value=False)
self.xtts_finetuning_checkbox = ctk.CTkCheckBox(self.installation_frame, text="XTTS Fine-tuning", variable=self.xtts_finetuning_var, command=self.update_whisperx_checkbox)
self.xtts_finetuning_checkbox.pack(anchor="w", padx=10, pady=5)
button_frame = ctk.CTkFrame(self.installation_frame, fg_color="transparent")
button_frame.pack(anchor="w", padx=10, pady=(20, 10))
self.install_button = ctk.CTkButton(button_frame, text="Install", command=self.install_pandrator, width=200, height=40)
self.install_button.pack(side="left", padx=(0, 10))
self.update_button = ctk.CTkButton(button_frame, text="Update Pandrator", command=self.update_pandrator, width=200, height=40)
self.update_button.pack(side="left", padx=10)
self.open_log_button = ctk.CTkButton(button_frame, text="View Installation Log", command=self.open_log_file, width=200, height=40)
self.open_log_button.pack(side="left", padx=10)
self.open_log_button.configure(state="disabled")
# Progress Bar and Status Label (now inside installation frame)
self.progress_bar = ctk.CTkProgressBar(self.installation_frame)
self.progress_bar.pack(fill="x", padx=20, pady=(20, 10))
self.progress_bar.set(0)
self.status_label = ctk.CTkLabel(self.installation_frame, text="", font=("Arial", 14))
self.status_label.pack(pady=(0, 10))
# Launch Frame
self.launch_frame = ctk.CTkFrame(self.main_options_frame)
self.launch_frame.grid(row=0, column=1, padx=(10, 0), pady=10, sticky="nsew")
ctk.CTkLabel(self.launch_frame, text="Launch", font=("Arial", 20, "bold")).grid(row=0, column=0, columnspan=4, sticky="w", padx=10, pady=(10, 5))
ctk.CTkCheckBox(self.launch_frame, text="Pandrator", variable=self.launch_pandrator_var).grid(row=1, column=0, columnspan=4, sticky="w", padx=10, pady=5)
# XTTS options in one row
ctk.CTkCheckBox(self.launch_frame, text="XTTS", variable=self.launch_xtts_var).grid(row=2, column=0, sticky="w", padx=10, pady=5)
self.xtts_cpu_checkbox = ctk.CTkCheckBox(self.launch_frame, text="Use CPU", variable=self.xtts_cpu_launch_var)
self.xtts_cpu_checkbox.grid(row=2, column=1, sticky="w", padx=10, pady=5)
self.lowvram_checkbox = ctk.CTkCheckBox(self.launch_frame, text="Low VRAM", variable=self.lowvram_var)
self.lowvram_checkbox.grid(row=2, column=2, sticky="w", padx=10, pady=5)
self.deepspeed_checkbox = ctk.CTkCheckBox(self.launch_frame, text="DeepSpeed", variable=self.deepspeed_var)
self.deepspeed_checkbox.grid(row=2, column=3, sticky="w", padx=10, pady=5)
ctk.CTkCheckBox(self.launch_frame, text="Silero", variable=self.launch_silero_var).grid(row=3, column=0, columnspan=4, sticky="w", padx=10, pady=5)
self.launch_button = ctk.CTkButton(self.launch_frame, text="Launch", command=self.launch_apps, width=200, height=40)
self.launch_button.grid(row=5, column=0, columnspan=4, sticky="w", padx=10, pady=(20, 10))
self.refresh_ui_state()
atexit.register(self.shutdown_apps)
def initialize_logging(self):
pandrator_path = os.path.join(self.initial_working_dir, 'Pandrator')
os.makedirs(pandrator_path, exist_ok=True)
logs_path = os.path.join(pandrator_path, 'Logs')
os.makedirs(logs_path, exist_ok=True)
current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
self.log_filename = os.path.join(logs_path, f'pandrator_installation_log_{current_time}.log')
# Configure logging with explicit encoding handling
handler = logging.FileHandler(self.log_filename, encoding='utf-8')
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger = logging.getLogger()
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
self.open_log_button.configure(state="normal")
def is_admin(self):
"""Check if the current process has admin privileges."""
try:
return ctypes.windll.shell32.IsUserAnAdmin() != 0
except:
return False
def is_build_tools_installed(self):
"""Check if Visual Studio Build Tools are installed."""
try:
# Method 1: Check common installation paths
vs_paths = [
r"C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools",
r"C:\Program Files\Microsoft Visual Studio\2022\BuildTools"
]
for path in vs_paths:
vc_tools_path = os.path.join(path, "VC", "Tools", "MSVC")
if os.path.exists(vc_tools_path) and os.listdir(vc_tools_path):
logging.info(f"Found Build Tools at {vc_tools_path}")
return True
# Method 2: Check registry
try:
# Check if Visual C++ Build Tools registry key exists
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
r"SOFTWARE\Microsoft\VisualStudio\SxS\VS7",
0, winreg.KEY_READ) as key:
# Just checking if the key exists and has values
if winreg.QueryValueEx(key, "17.0")[0]:
logging.info("Found Build Tools in registry")
return True
except FileNotFoundError:
# Registry key not found
pass
except Exception as reg_error:
logging.warning(f"Error checking registry for Build Tools: {str(reg_error)}")
# Method 3: Try to use cl.exe (MSVC compiler)
try:
subprocess.run(["cl"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
logging.info("Found cl.exe in PATH, Build Tools appear to be installed")
return True
except:
# cl.exe not found in PATH
pass
return False
except Exception as e:
logging.error(f"Error checking Build Tools installation: {str(e)}")
return False
def open_build_tools_installer(self):
"""Check for and install Visual Studio Build Tools."""
# Check for admin privileges
if not self.is_admin():
message = ("Administrator privileges required!\n\n"
"The Pandrator Installer must be run as administrator to install Visual C++ Build Tools.\n\n"
"Please right-click on the Pandrator Installer and select 'Run as administrator'.")
messagebox.showerror("Admin Rights Required", message)
return
# First check if Build Tools are already installed
if self.is_build_tools_installed():
# Build Tools are already installed, ask if user wants to force reinstall
result = messagebox.askyesno(
"Build Tools Already Installed",
"Visual C++ Build Tools appear to be already installed on your system.\n\n"
"Do you want to force a reinstallation anyway?\n\n"
"• Select 'Yes' to reinstall\n"
"• Select 'No' to continue with Pandrator installation",
icon="info"
)
if not result:
# User chose not to reinstall, update status and return
self.update_status("Using existing Visual C++ Build Tools installation.")
return
# User chose to reinstall, continue with installation
logging.info("User chose to reinstall Build Tools despite existing installation")
self.update_status("Preparing Visual C++ Build Tools installation...")
logging.info("Starting Visual C++ Build Tools installation process...")
try:
# URL for VS Build Tools 2022
url = "https://aka.ms/vs/17/release/vs_buildtools.exe"
# Download the installer
self.update_status("Downloading VS Build Tools installer...")
response = requests.get(url, stream=True)
if response.status_code != 200:
raise Exception(f"Failed to download installer, status code: {response.status_code}")
# Save the installer to a temporary file
installer_path = os.path.join(tempfile.gettempdir(), "vs_buildtools.exe")
with open(installer_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
# Run the installer silently with required components
self.update_status("Installing VS Build Tools (running silently)...")
# Command arguments with quiet mode
install_cmd = [
installer_path,
"--quiet", "--norestart",
"--add", "Microsoft.VisualStudio.Workload.VCTools",
"--includeRecommended"
]
# Launch the installer
process = subprocess.Popen(install_cmd)
# Start a background thread to monitor installation
threading.Thread(target=self.monitor_build_tools_installation,
args=(process,), daemon=True).start()
message = ("Visual Studio Build Tools installation has started and is running silently in the background.\n\n"
"⏱️ This may take 5-15 minutes to complete.\n\n"
"The Pandrator Installer will notify you when the installation is complete or if it fails.\n\n"
"AFTER INSTALLATION:\n"
"1. Close all command prompt/PowerShell windows\n"
"2. Restart the Pandrator Installer")
messagebox.showinfo("Build Tools Installation", message)
except Exception as e:
logging.error(f"Failed to run VS Build Tools installer: {str(e)}")
logging.error(traceback.format_exc())
message = ("Failed to download or start the Visual Studio Build Tools installer.\n\n"
"Please install it manually:\n"
"1. Download from: https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2022\n"
"2. Run the installer and select 'Desktop development with C++'\n"
"3. Complete the installation\n"
"4. Close all terminal windows and restart Pandrator Installer")
messagebox.showerror("Build Tools Installation Error", message)
def monitor_build_tools_installation(self, process):
"""Monitor the Build Tools installation process in a background thread."""
try:
# Wait for the initial process to complete
return_code = process.wait()
if return_code == 0:
# Initial process succeeded, now check for actual installation
# Wait for installation to complete (can take several minutes)
for attempt in range(30): # Check for 5 minutes (30 x 10 seconds)
if self.is_build_tools_installed():
# Schedule UI updates on the main thread
self.after(0, lambda: self.update_status("VS Build Tools installation completed successfully!"))
self.after(0, lambda: messagebox.showinfo("Installation Complete",
"Visual Studio Build Tools installation completed successfully!\n\n"
"Please:\n"
"1. Close all command prompt/PowerShell windows\n"
"2. Restart the Pandrator Installer"))
return
time.sleep(10) # Wait 10 seconds between checks
# If we get here, we couldn't confirm the installation
self.after(0, lambda: self.update_status("Could not confirm VS Build Tools installation"))
self.after(0, lambda: messagebox.showwarning("Installation Status Unknown",
"The Visual Studio Build Tools installer completed, but we couldn't confirm if all components were installed correctly.\n\n"
"Please restart your computer and then run the Pandrator Installer again."))
else:
# Initial process failed
self.after(0, lambda: self.update_status(f"VS Build Tools installation failed with code {return_code}"))
self.after(0, lambda: messagebox.showerror("Installation Failed",
f"Visual Studio Build Tools installation failed with code {return_code}.\n\n"
"Please try installing manually:\n"
"1. Download from: https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2022\n"
"2. Run the installer and select 'Desktop development with C++'\n"
"3. Complete the installation\n"
"4. Close all terminal windows and restart Pandrator Installer"))
except Exception as e:
logging.error(f"Error monitoring Build Tools installation: {str(e)}")
self.after(0, lambda: self.update_status("Error monitoring VS Build Tools installation"))
def install_pytorch_for_xtts_finetuning(self, conda_path, env_name):
logging.info(f"Installing PyTorch for XTTS Fine-tuning in {env_name}...")
env_path = os.path.join(conda_path, 'envs', env_name)
try:
self.run_command([
os.path.join(conda_path, 'Scripts', 'conda.exe'),
'run', '-p', env_path, 'python', '-m',
'pip', 'install', 'torch==2.2.0+cu118', 'torchaudio==2.2.0+cu118',
'--index-url', 'https://download.pytorch.org/whl/cu118'
])
logging.info("PyTorch for XTTS Fine-tuning installed successfully.")
except subprocess.CalledProcessError as e:
logging.error(f"Failed to install PyTorch for XTTS Fine-tuning in {env_name}")
logging.error(f"Error message: {str(e)}")
raise
def disable_buttons(self):
for widget in self.installation_frame.winfo_children():
if isinstance(widget, (ctk.CTkCheckBox, ctk.CTkButton)):
widget.configure(state="disabled")
self.launch_button.configure(state="disabled")
def enable_buttons(self):
self.refresh_ui_state()
def refresh_ui_state(self):
pandrator_path = os.path.join(self.initial_working_dir, 'Pandrator')
config_path = os.path.join(pandrator_path, 'config.json')
if os.path.exists(config_path):
with open(config_path, 'r') as f:
config = json.load(f)
else:
config = {}
# Helper function
def set_widget_state(widget, state, value=None):
widget.configure(state=state)
if isinstance(widget, ctk.CTkCheckBox) and value is not None:
if value:
widget.select()
else:
widget.deselect()
# Pandrator
pandrator_installed = os.path.exists(pandrator_path)
set_widget_state(self.pandrator_checkbox, "disabled" if pandrator_installed else "normal", False)
set_widget_state(self.launch_frame.winfo_children()[1], "normal" if pandrator_installed else "disabled", pandrator_installed)
# XTTS
xtts_support = config.get('xtts_support', False)
xtts_cuda_support = config.get('cuda_support', False)
# RVC
rvc_support = config.get('rvc_support', False)
set_widget_state(self.rvc_checkbox, "disabled" if rvc_support else "normal", False)
# Disable both XTTS and XTTS CPU checkboxes if XTTS is installed in any form
set_widget_state(self.xtts_checkbox, "disabled" if xtts_support else "normal", False)
set_widget_state(self.xtts_cpu_checkbox, "disabled" if xtts_support else "normal", False)
xtts_launch_checkbox = next(widget for widget in self.launch_frame.winfo_children() if isinstance(widget, ctk.CTkCheckBox) and widget.cget("text") == "XTTS")
set_widget_state(xtts_launch_checkbox, "normal" if xtts_support else "disabled", False)
cpu_checkbox = next(widget for widget in self.launch_frame.winfo_children() if isinstance(widget, ctk.CTkCheckBox) and widget.cget("text") == "Use CPU")
lowvram_checkbox = next(widget for widget in self.launch_frame.winfo_children() if isinstance(widget, ctk.CTkCheckBox) and widget.cget("text") == "Low VRAM")
deepspeed_checkbox = next(widget for widget in self.launch_frame.winfo_children() if isinstance(widget, ctk.CTkCheckBox) and widget.cget("text") == "DeepSpeed")
if xtts_support:
if xtts_cuda_support:
set_widget_state(cpu_checkbox, "normal", False)
set_widget_state(lowvram_checkbox, "normal", False)
set_widget_state(deepspeed_checkbox, "normal", True)
else:
set_widget_state(cpu_checkbox, "normal", True)
set_widget_state(lowvram_checkbox, "disabled", False)
set_widget_state(deepspeed_checkbox, "disabled", False)
else:
set_widget_state(cpu_checkbox, "disabled", False)
set_widget_state(lowvram_checkbox, "disabled", False)
set_widget_state(deepspeed_checkbox, "disabled", False)
# Silero
silero_support = config.get('silero_support', False)
set_widget_state(self.silero_checkbox, "disabled" if silero_support else "normal", False)
silero_launch_checkbox = next(widget for widget in self.launch_frame.winfo_children() if isinstance(widget, ctk.CTkCheckBox) and widget.cget("text") == "Silero")
set_widget_state(silero_launch_checkbox, "normal" if silero_support else "disabled", False)
# RVC
rvc_support = config.get('rvc_support', False)
set_widget_state(self.rvc_checkbox, "disabled" if rvc_support else "normal", False)
# XTTS Fine-tuning
xtts_finetuning_support = config.get('xtts_finetuning_support', False)
set_widget_state(self.xtts_finetuning_checkbox, "disabled" if xtts_finetuning_support else "normal", False)
# WhisperX
whisperx_support = config.get('whisperx_support', False)
if whisperx_support:
set_widget_state(self.whisperx_checkbox, "disabled", False)
elif xtts_finetuning_support:
# XTTS Fine-tuning is installed
set_widget_state(self.whisperx_checkbox, "disabled", False)
elif self.xtts_finetuning_var.get():
# XTTS Fine-tuning is not installed but selected
set_widget_state(self.whisperx_checkbox, "disabled", True)
else:
set_widget_state(self.whisperx_checkbox, "normal", False)
# Update launch and install buttons state
self.launch_button.configure(state="normal" if pandrator_installed else "disabled")
self.install_button.configure(state="normal")
self.update_button.configure(state="normal" if pandrator_installed else "disabled")
def get_installed_components(self):
pandrator_path = os.path.join(self.initial_working_dir, 'Pandrator')
config_path = os.path.join(pandrator_path, 'config.json')
if os.path.exists(config_path):
with open(config_path, 'r') as f:
config = json.load(f)
else:
config = {}
return {
'xtts': config.get('xtts_support', False),
'silero': config.get('silero_support', False),
'rvc': config.get('rvc_support', False),
'whisperx': config.get('whisperx_support', False),
'xtts_finetuning': config.get('xtts_finetuning_support', False)
}
def install_whisperx(self, conda_path, env_name):
logging.info(f"Installing WhisperX in {env_name}...")
env_path = os.path.join(conda_path, 'envs', env_name)
try:
## Install Git through Conda
#self.run_command([
# os.path.join(conda_path, 'Scripts', 'conda.exe'),
# 'install', '-p', env_path,
# 'git', '-c', 'conda-forge', '-y'
#])
# Install PyTorch
self.run_command([
os.path.join(conda_path, 'Scripts', 'conda.exe'),
'run', '-p', env_path,
'python', '-m', 'pip', 'install',
'torch==2.5.1', 'torchvision==0.20.1', 'torchaudio==2.5.1',
'--index-url', 'https://download.pytorch.org/whl/cu118'
])
# Install cuDNN
self.run_command([
os.path.join(conda_path, 'Scripts', 'conda.exe'),
'install', '-p', env_path,
'cudnn=8.9.7.29', '-c', 'conda-forge', '-y'
])
# Install ffmpeg
self.run_command([
os.path.join(conda_path, 'Scripts', 'conda.exe'),
'install', '-p', env_path,
'ffmpeg', '-c', 'conda-forge', '-y'
])
# Install CTranslate2
self.run_command([
os.path.join(conda_path, 'Scripts', 'conda.exe'),
'run', '-p', env_path, 'python', '-m',
'pip', 'install',
'pip<24'
])
# Install WhisperX
self.run_command([
os.path.join(conda_path, 'Scripts', 'conda.exe'),
'run', '-p', env_path, 'python', '-m',
'pip', 'install', 'whisperx'
])
# Install CTranslate2
self.run_command([
os.path.join(conda_path, 'Scripts', 'conda.exe'),
'run', '-p', env_path, 'python', '-m',
'pip', 'install',
'ctranslate2==4.4.0'
])
logging.info("WhisperX installation completed successfully.")
except subprocess.CalledProcessError as e:
logging.error(f"Failed to install WhisperX in {env_name}")
logging.error(f"Error message: {str(e)}")
raise
def remove_directory(self, path):
max_attempts = 5
for attempt in range(max_attempts):
try:
shutil.rmtree(path)
return True
except PermissionError:
time.sleep(1) # Wait for a second before retrying
return False
def install_pandrator(self):
pandrator_path = os.path.join(self.initial_working_dir, 'Pandrator')
pandrator_already_installed = os.path.exists(pandrator_path)
installed_components = self.get_installed_components()
new_components_selected = (
(self.xtts_var.get() or self.xtts_cpu_var.get()) and not installed_components['xtts'] or
self.silero_var.get() and not installed_components['silero'] or
self.rvc_var.get() and not installed_components['rvc'] or
self.whisperx_var.get() and not installed_components['whisperx']
)
if pandrator_already_installed and not self.pandrator_var.get():
if not new_components_selected:
messagebox.showinfo("Info", "No new components selected for installation.")
return
elif not pandrator_already_installed and not self.pandrator_var.get():
messagebox.showerror("Error", "Pandrator must be installed first before adding new components.")
return
self.disable_buttons()
self.progress_bar.set(0)
self.status_label.configure(text="Installing...")
self.initialize_logging()
logging.info("Installation process started.")
threading.Thread(target=self.install_process, daemon=True).start()
def open_log_file(self):
if hasattr(self, 'log_filename') and os.path.exists(self.log_filename):
os.startfile(self.log_filename)
else:
self.status_label.configure(text="No log file available.")
def update_progress(self, value):
self.progress_bar.set(value)
def update_status(self, text):
self.status_label.configure(text=text)
logging.info(text)
def run_command(self, command, use_shell=False, cwd=None):
try:
if use_shell:
process = subprocess.Popen(
command if isinstance(command, str) else " ".join(command),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
cwd=cwd,
encoding='utf-8', # Add explicit encoding
errors='replace' # Replace invalid characters instead of failing
)
else:
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=cwd,
encoding='utf-8', # Add explicit encoding
errors='replace' # Replace invalid characters instead of failing
)
stdout, stderr = process.communicate()
if process.returncode != 0:
raise subprocess.CalledProcessError(process.returncode, command, stdout, stderr)
logging.info(f"Command executed: {command if isinstance(command, str) else ' '.join(command)}")
logging.debug(f"STDOUT: {stdout}")
logging.debug(f"STDERR: {stderr}")
return stdout, stderr
except subprocess.CalledProcessError as e:
logging.error(f"Error executing command: {command if isinstance(command, str) else ' '.join(command)}")
logging.error(f"Error message: {str(e)}")
logging.error(f"STDOUT: {e.stdout}")
logging.error(f"STDERR: {e.stderr}")
raise
def check_program_installed(self, program):
try:
self.run_command(['where', program])
return True
except subprocess.CalledProcessError:
return False
def install_chocolatey(self):
logging.info("Installing Chocolatey...")
try:
powershell_command = """
Set-ExecutionPolicy Bypass -Scope Process -Force;
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072;
iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
"""
# Run the installation command
process = subprocess.Popen(
["powershell", "-Command", powershell_command],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
creationflags=subprocess.CREATE_NO_WINDOW
)
# Capture and log the output
for line in process.stdout:
logging.info(line.strip())
process.wait()
if process.returncode == 0:
logging.info("Chocolatey installed successfully.")
# Enable global confirmation
subprocess.run(["powershell", "-Command", "choco feature enable -n=allowGlobalConfirmation"],
check=True, capture_output=True, text=True)
logging.info("Global confirmation enabled for Chocolatey.")
# Refresh environment variables
self.refresh_environment_variables()
return True
else:
error_output = process.stderr.read()
logging.error(f"Failed to install Chocolatey: {error_output}")
return False
except Exception as e:
logging.error(f"An error occurred during Chocolatey installation: {str(e)}")
logging.error(traceback.format_exc())
return False
def refresh_environment_variables(self):
"""Refresh the environment variables for the current session."""
try:
# Refresh environment variables for the current session
logging.info("Refreshing environment variables...")
HWND_BROADCAST = 0xFFFF
WM_SETTINGCHANGE = 0x001A
SMTO_ABORTIFHUNG = 0x0002
result = ctypes.windll.user32.SendMessageTimeoutW(
HWND_BROADCAST, WM_SETTINGCHANGE, 0, "Environment",
SMTO_ABORTIFHUNG, 5000, ctypes.byref(ctypes.c_long())
)
if result == 0:
logging.warning("Environment variables refresh timed out.")
else:
logging.info("Environment variables refreshed successfully.")
except Exception as e:
logging.error(f"Failed to refresh environment variables: {str(e)}")
logging.error(traceback.format_exc())
raise
def install_dependencies(self):
return self.install_calibre()
def show_calibre_installation_message(self):
message = ("Calibre installation failed. Please install Calibre manually.\n"
"You can download it from: https://calibre-ebook.com/download_windows")
messagebox.showwarning("Calibre Installation Required", message)
def refresh_env_in_new_session(self):
refresh_cmd = 'powershell -Command "[System.Environment]::GetEnvironmentVariables([System.EnvironmentVariableTarget]::Machine)"'
output, _ = self.run_command(refresh_cmd, use_shell=True)
new_env = dict(line.split('=', 1) for line in output.strip().split('\n') if '=' in line)
os.environ.update(new_env)
logging.info("Refreshed environment variables in a new session")
def install_with_chocolatey(self, package_name, args=""):
logging.info(f"Attempting to install {package_name} with Chocolatey...")
# First, try using 'choco' command
try:
process = subprocess.Popen(
f"choco install {package_name} -y {args}",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
text=True
)
stdout, stderr = process.communicate()
logging.info(stdout)
if process.returncode == 0:
logging.info(f"{package_name} installed successfully using 'choco' command.")
return True
except Exception as e:
logging.error(f"Error using 'choco' command: {str(e)}")
# If 'choco' command fails, try using the Chocolatey executable directly
try:
choco_exe = os.path.join(os.environ.get('ProgramData', ''), 'chocolatey', 'bin', 'choco.exe')
if os.path.exists(choco_exe):
process = subprocess.Popen(
f'"{choco_exe}" install {package_name} -y {args}',
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
text=True
)
stdout, stderr = process.communicate()
logging.info(stdout)
if process.returncode == 0:
logging.info(f"{package_name} installed successfully using Chocolatey executable.")
return True
else:
logging.error("Chocolatey executable not found.")
except Exception as e:
logging.error(f"Error using Chocolatey executable: {str(e)}")
logging.error(f"Failed to install {package_name} using Chocolatey.")
return False
def install_calibre(self):
logging.info("Checking installation for Calibre")
if not self.check_program_installed('calibre'):
logging.info("Installing Calibre...")
if self.install_with_chocolatey('calibre'):
self.refresh_env_in_new_session()
if self.check_program_installed('calibre'):
logging.info("Calibre installed successfully.")
return True
else:
logging.warning("Calibre installation not detected after installation attempt.")
return False
else:
return False
else:
logging.info("Calibre is already installed.")
return True
def install_conda(self, install_path):
logging.info("Installing Miniconda...")
conda_installer = 'Miniconda3-latest-Windows-x86_64.exe'
url = f'https://repo.anaconda.com/miniconda/{conda_installer}'
# Download the file
response = requests.get(url)
with open(conda_installer, 'wb') as f:
f.write(response.content)
self.run_command([
conda_installer,
'/InstallationType=JustMe',
'/AddToPath=0',
'/RegisterPython=0',
'/NoRegistry=1',
'/S',
f'/D={install_path}'
])
os.remove(conda_installer)
def check_conda(self, conda_path):
return os.path.exists(os.path.join(conda_path, 'Scripts', 'conda.exe'))
def create_conda_env(self, conda_path, env_name, python_version, additional_packages=None):
logging.info(f"Creating conda environment {env_name}...")
env_path = os.path.join(conda_path, 'envs', env_name)
try:
# Create the environment with Python
create_command = [
os.path.join(conda_path, 'Scripts', 'conda.exe'),
'create',
'-p', env_path,
f'python={python_version}',
'-y'
]
self.run_command(create_command)
# If it's the pandrator_installer environment, install ffmpeg from conda-forge
if env_name == 'pandrator_installer':
logging.info("Installing ffmpeg from conda-forge for pandrator_installer...")
ffmpeg_command = [
os.path.join(conda_path, 'Scripts', 'conda.exe'),
'install',
'-p', env_path,
'ffmpeg',
'-c',
'conda-forge',
'-y'
]
self.run_command(ffmpeg_command)
# Install additional packages if specified
if additional_packages:
logging.info(f"Installing additional packages: {', '.join(additional_packages)}")
install_command = [
os.path.join(conda_path, 'Scripts', 'conda.exe'),
'install',
'-p', env_path,
'-y'
] + additional_packages
self.run_command(install_command)
except subprocess.CalledProcessError as e:
logging.error(f"Failed to create or setup conda environment {env_name}")
logging.error(f"Error output: {e.stderr.decode('utf-8')}")
raise
def install_requirements(self, conda_path, env_name, requirements_file):
logging.info(f"Installing requirements for {env_name}...")
env_path = os.path.join(conda_path, 'envs', env_name)
# Log requirements file contents
with open(requirements_file, 'r') as f:
reqs = f.read()
logging.info(f"Requirements file contents:\n{reqs}")
self.run_command([os.path.join(conda_path, 'Scripts', 'conda.exe'), 'run', '-p', env_path, 'python', '-m', 'pip', 'install', '-r', requirements_file])
# Only check for dulwich in pandrator_installer environment
if env_name == 'pandrator_installer':
logging.info("Checking if dulwich is installed in pandrator_installer environment...")
try:
self.run_command([
os.path.join(conda_path, 'Scripts', 'conda.exe'),
'run', '-p', env_path,
'python', '-c', 'import dulwich; print(f"Dulwich version {dulwich.__version__} is installed")'
])
logging.info("Dulwich check completed successfully")
except subprocess.CalledProcessError:
logging.warning("Dulwich not found in pandrator_installer environment, installing separately...")
try:
self.run_command([
os.path.join(conda_path, 'Scripts', 'conda.exe'),
'run', '-p', env_path, 'python', '-m',
'pip', 'install', 'dulwich'
])
logging.info("Dulwich installed successfully in pandrator_installer environment")
except subprocess.CalledProcessError as e:
logging.error(f"Failed to install dulwich in pandrator_installer environment: {str(e)}")
raise
def install_package(self, conda_path, env_name, package):
logging.info(f"Installing {package} in {env_name}...")
env_path = os.path.join(conda_path, 'envs', env_name)
self.run_command([os.path.join(conda_path, 'Scripts', 'conda.exe'), 'run', '-p', env_path, 'pip', 'install', package])
def install_pytorch_and_xtts_api_server(self, conda_path, env_name):
logging.info(f"Installing xtts-api-server, PyTorch, and FFmpeg in {env_name}...")
env_path = os.path.join(conda_path, 'envs', env_name)
try:
# Install xtts-api-server package
xtts_cmd = [os.path.join(conda_path, 'Scripts', 'conda.exe'), 'run', '-p', env_path, 'python', '-m', 'pip', 'install', 'xtts-api-server']
self.run_command(xtts_cmd)
# Install PyTorch
if self.xtts_cpu_var.get():
pytorch_cmd = [os.path.join(conda_path, 'Scripts', 'conda.exe'), 'run', '-p', env_path, 'python', '-m', 'pip', 'install', 'torch==2.1.1', 'torchaudio==2.1.1']
else:
pytorch_cmd = [os.path.join(conda_path, 'Scripts', 'conda.exe'), 'run', '-p', env_path, 'python', '-m', 'pip', 'install', 'torch==2.1.1+cu118', 'torchaudio==2.1.1+cu118', '--extra-index-url', 'https://download.pytorch.org/whl/cu118']
self.run_command(pytorch_cmd)
# Install FFmpeg