-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathexample_pandrator.txt
1800 lines (1495 loc) · 93.2 KB
/
example_pandrator.txt
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
Folder structure:
├── tmpqu97eipl/
├── pandrator.ico
├── pandrator.png
├── pandrator.py
├── pandrator_demonstration.gif
├── pandrator_installer_launcher.py
├── README.md
├── requirements.txt
├── tts_voices/
│ ├── sample_male_new.wav
│ ├── VoiceCraft/
│ │ ├── sample_male_16k.txt
│ │ ├── sample_male_16k.wav
│ │ ├── tmp.txt
Concatenated content:
---/---
--README.md--
<p align="left">
<img src="pandrator.png" alt="Icon" width="200" height="200"/>
</p>
# Pandrator, a GUI audiobook and dubbing generator with voice cloning and AI text optimisation
>[!NOTE]
> Please note that Pandrator is still in an alpha stage and I'm not an experienced developer (I'm a noob, in fact), so the code is far from perfect in terms of optimisation, features and reliability. Please keep this in mind and contribute, if you want to help me make it better.
Pandrator aspires to be easy to use and install - it has a one-click installer and a graphical user interface. It is a tool designed to perform two tasks:
- transform text, PDF, EPUB and SRT files into spoken audio in multiple languages based on open source software, including preprocessing to make the generated speech sound as natural as possible by, among other things, splitting the text into paragraphs, sentences and smaller logical text blocks (clauses), which the TTS models can process with minimal artifacts. Each sentence can be regenerated if the first attempt is not satisfacory. Voice cloning is possible for models that support it, and text can be additionally preprocessed using LLMs (to remove OCR artifacts or spell out things that the TTS models struggle with, like Roman numerals and abbreviations, for example),
- generate dubbing either directly from a video file, including transcription (using [WhisperX](https://github.com/m-bain/whisperX)), or from an .srt file. It includes a complete workflow from a video file to a dubbed video file with subtitles - including translation using a variety of APIs and techniques to improve the quality of translation. [Subdud](https://github.com/lukaszliniewicz/Subdub), a companion app developed for this purpose, can also be used on its own.
It leverages the [XTTS](https://huggingface.co/coqui/XTTS-v2), [Silero](https://github.com/snakers4/silero-models) and [VoiceCraft](https://github.com/jasonppy/VoiceCraft) model(s) for text-to-speech conversion and voice cloning, enhanced by [RVC_CLI](https://github.com/blaisewf/rvc-cli) for quality improvement and better voice cloning results, and NISQA for audio quality evaluation. Additionally, it incorporates [Text Generation Webui's](https://github.com/oobabooga/text-generation-webui) API for local LLM-based text pre-processing, enabling a wide range of text manipulations before audio generation.
- [Pandrator, an audiobook generator](#pandrator-an-audiobook-generator)
- [Samples](#samples)
- [Requirements](#requirements)
- [Hardware](#hardware)
- [Dependencies](#dependencies)
- [Required](#required)
- [Optional](#optional)
- [Installation](#installation)
- [Minimal One-Click Installation Executable (Windows with an Nvidia GPU only)](#installer-and-launcher)
- [Manual Installation](#manual-installation)
- [Features](#features)
- [Quick Start Guide](#quick-start-guide)
- [Basic Usage](#basic-usage)
- [General Audio Settings](#general-audio-settings)
- [General Text Pre-Processing Settings](#general-text-pre-processing-settings)
- [LLM Pre-processing](#llm-preprocessing)
- [RVC Quality Enhancement and Voice Cloning](#rvc-quality-enhancement-and-voice-cloning)
- [NISQA TTS Evaluation](#nisqa-tts-evaluation)
- [Contributing](#contributing)
- [Tips](#tips)
- [To-do](#to-do)

## Samples
The samples were generated using the minimal settings - no LLM text processing, RVC or TTS evaluation, and no sentences were regenerated. Both XTTS and Silero generations were faster than playback speed.
https://github.com/user-attachments/assets/1c763c94-c66b-4c22-a698-6c4bcf3e875d
https://github.com/lukaszliniewicz/Pandrator/assets/75737665/bbb10512-79ed-43ea-bee3-e271b605580e
https://github.com/lukaszliniewicz/Pandrator/assets/75737665/118f5b9c-641b-4edd-8ef6-178dd924a883
Dubbing sample, including translation ([video source](https://www.youtube.com/watch?v=_SwUpU0E2Eg&t=61s&pp=ygUn0LLRi9GB0YLRg9C_0LvQtdC90LjQtSDQu9C10LPQsNGB0L7QstCw)):
https://github.com/user-attachments/assets/1ba8068d-986e-4dec-a162-3b7cc49052f4
## Requirements
### Hardware
#### XTTS
It's likely that you will need at least 16GB of RAM, a reasonably modern CPU for CPU-only generation (which you can choose in the launcher), and ideally an NVIDIA GPU with 4 GB+ of VRAM for really good performance.
#### Silero
Silero runs on the CPU. It should perform well on almost all reasonably modern systems.
#### VoiceCraft
You can run VoiceCraft on a cpu, but generation will be very slow. To achieve meaningful acceleration with a GPU (Nvidia), you need one with at least 8GB of VRAM. If you have only 4GB, disable kv cache in advanced settings.
### Dependencies
This project relies on several APIs and services (running locally) and libraries, notably:
#### Required
- [XTTS API Server by daswer123](https://github.com/daswer123/xtts-api-server.git) for Text-to-Speech (TTS) generation using Coqui [XTTSv2](https://huggingface.co/coqui/XTTS-v2) OR [Silero API Server by ouoertheo](https://github.com/ouoertheo/silero-api-server) for TTS generaton using the [Silero models](https://github.com/snakers4/silero-models) OR [VoiceCraft by jasonppy](https://github.com/jasonppy/VoiceCraft). XTTS and VoiceCraft perform best on a GPU (Nvidia), though can work on a CPU (especially XTTS), and Silero uses only the CPU. Silero can be run on low-end systems.
- [FFmpeg](https://github.com/FFmpeg/FFmpeg) for audio encoding.
- [Sentence Splitter by mediacloud](https://github.com/mediacloud/sentence-splitter) for splitting `.txt ` files into sentences, [customtkinter by TomSchimansky](https://github.com/TomSchimansky/CustomTkinter), [num2words by savoirfairelinux](https://github.com/savoirfairelinux/num2words) for converting numbers to words (Silero requirs this), `pysrt`, `pydub` and others (see `requirements.txt`).
#### Optional
- [Text Generation Webui API by oobabooga](https://github.com/oobabooga/text-generation-webui.git) for LLM-based text pre-processing.
- [RVC_CLI by blaise-tk](https://github.com/blaise-tk/RVC_CLI.git) for enhancing voice quality and cloning results with [Retrieval Based Voice Conversion](https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI).
- [NISQA by gabrielmittag](https://github.com/gabrielmittag/NISQA.git) for evaluating TTS generations (using the [FastAPI implementation](https://github.com/lukaszliniewicz/NISQA-API)).
## Installation
### GUI Installer and Launcher (Windows)
Run `pandrator_installer_launcher.exe` with administrator priviliges. You will find it under [Releases](https://github.com/lukaszliniewicz/Pandrator/releases). The executable was created using [pyinstaller](https://github.com/pyinstaller/pyinstaller) from `pandrator_installer_launcher.py` in the repository.
**The file may be flagged as a threat by antivirus software, so you may have to add it as an exception.**
You can choose which TTS engines to install and whether to install the software that enabled RVC voice cloning (RVC_CLI). You may install new components later. The installer creates the Pandrator folder, installs `winget`, `git`, `ffmpeg`, `C++ Build Tools` and/or `Calibre` if not installed already and `Miniconda`, clones the XTTS Api Server respository, the Silero Api Server repository or the VoiceCraft API repository and the Pandrator repository, creates conda environments, installs dependencies and launches Pandrator and the server you chose. **You may use the the Installer/Launcher to launch Pandrator and all the tools later**.
If you want to perform the setup again, remove the Pandrator folder it created. Please allow at least a couple of minutes for the initial setup process to download models and install dependencies. Depending on the options you've chosen, it may take up to 25 minutes.
For additional functionality not yet included in the installer:
- Install Text Generation Webui and remember to enable the API (add `--api` to `CMD_FLAGS.txt` in the main directory of the Webui before starting it).
- Set up NISQA API for automatic evaluation of generations.
Please refer to the repositories linked under [Dependencies](#Dependencies) for detailed installation instructions. Remember that the APIs must be running to make use of the functionalities they offer.
### Manual Installation:
1. Make sure that Python 3, git, calibre and ffmpeg are installed and in PATH.
2. Install and run at least XTTS API Server, Silero API Server or VoiceCraft API Server.
3. Clone this repository (`git clone https://github.com/lukaszliniewicz/Pandrator.git`).
4. `cd` to the repository directory.
5. Install requirements using `pip install -r requirements.txt`.
6. Run `python pandrator.py`.
## Features
- **Text Pre-processing:** Splits text into sentences and (attempts to) preserve paragraphs. Profiles for multiple languages are available.
- **LLM Text Pre-processing:** Utilizes a local LLM for text corrections and enhancements with up to three different prompts run sequentially, and an evaluation mechanism that asks the model to perform a task twice and then choose the better response. I've been using `openchat-3.5-0106.Q5_K_M.gguf` with good results, as well as for example `Mistral 7B Instruct 0.2`. Different models may perform different tasks well, so it's possible to choose a specific model for a specific prompt.
- **Audio Generation:** Converts processed text into speech, with options for voice cloning and quality enhancement. It currently supports `.txt`, `.srt` and `.pdf` files.
- **Audio Evaluation:** An experimental feature that predicts Mean Opinion Score (MOS) for generated sentences and sets a score threshold or chooses the best score from a set number of generations.
- **Generating and adding dubbing to video files:** Speech generated from subtitle files is synchronized with the SRT timestamps and can be saved as a file or mixed with an audio track of a video file, effectively producing dubbing. It handles cases where generated speech exceeds the time alloted for a subtitle and self-corrects synchronisation. It's possible to speed up or slow down generated audio.
- **Session Management:** Supports creating, deleting, and loading sessions for organized workflow.
- **GUI:** Built with customtkinker for a user-friendly experience.
## Quick Start Guide
### Basic Usage
If you don't want to use the additional functionalities, you have everything you need in the **Session tab**.
1. Either create a new session or load an existing one (select a folder in `Outputs` to do that).
2. Choose your `.txt`, `.srt`, `.pdf` or `epub` file. If you choose a PDF or EPUB file, a preview window will open with the extracted text. You may edit it (OCRed books often have poorly recognized text from the title page, for example). Files that contain a lot of text, regardless of format, can take a long time to finish preprocessing before generation begins. The GUI will freeze, but as long as there is processor activity, it's simply working. For whole books, expect 10m+ for preprocessing.
3. Select the TTS server you want to use - XTTS, Silero or VoiceCraft - and the language from the dropdown (VoiceCraft currently supports only English).
4. Choose the voice you want to use.
1. **XTTS**, voices are short, 6-12s `.wav` files (22050hz sample rate, mono) stored in the `tts_voices` directory. The XTTS model uses the audio to clone the voice. It doesn't matter what language the sample is in, you will be able to generate speech in all supported languages, but the quality will be best if you provide a sample in your target language. You may use the sample one in the repository or upload your own. Please make sure that the audio is between 6 and 12s, mono, and the sample rate is 22050hz. You may use a tool like Audacity to prepare the files. The less noise, the better. You may use a tool like [Resemble AI](https://github.com/resemble-ai/resemble-enhance) for denoising and/or enhancement of your samples on [Hugging Face](https://huggingface.co/spaces/ResembleAI/resemble-enhance).
2. **Silero** offers a number of voices for each language it supports. It doesn't support voice cloning. Simply select a voice from the dropdown after choosing the language.
3. **VoiceCraft** works similarly to XTTS in that it clones the voice from a `.wav ` sample. However, it needs both a properly formatted `.wav` file (mono, 16000hz) and a `.txt` file with the transcription of what is said in the sample. The files must have the same name (apart from the extension, of course). You need to upload them to `tts_voices/VoiceCraft` and you will be able to select them in the GUI. Currently only English is supported. If you generate with a new voice for the first time, the server will perform the alignment procedure, so the first sentence will be generated with a delay. This won't happen when you use that voice again.
6. If you want, you can either slow down or speed up the generated audio (type in or choose a ratio, e.g. 1.1, which is 10% faster than generated; it may be especially useful for dubbing).
7. If you chose an `.srt` file, you will be given the option to select a video file and one of its audio tracks to mix with the synchronized output, as well as weather you want to lower the volume of the original audio when subtitle audio is playing.
8. Start the generation. You may stop and resume it later, or close the programme and load the session later.
9. You can play back the generated sentences, also as a playlist, edit them (the text for regeneration), regenerate or remove individual ones.
10. "Save Output" concatenates the sentences generated so far an encodes them as one file (default is `.opus` at 64k bitrate; you may change it in the Audio tab to `.wav` or `.mp3`).
### General Audio Settings
1. You can change the lenght of silence appended to the end of sentences and paragraphs.
2. You can enable a fade-in and -out effect and set the duration.
3. You can choose the output format and bitrate.
### General Text Pre-Processing Settings
1. You can disable/enable splitting long sentences and set the max lenght a text fragment sent for TTS generation may have (enabled by default; it tries to split sentences whose lenght exceeds the max lenght value; it looks for punctuation marks (, ; : -) and chooses the one closest to the midpoint of the sentence; if there are no punctuation marks, it looks for conjunctions like "and"); it performs this operation twice as some sentence fragments may still be too long after just one split.
2. You can disable/enable appending short sentences (to preceding or following sentences; disabled by default, may perhaps improve the flow as the lenght of text fragments sent to the model is more uniform).
3. Remove diacritics (useful when generating a text that contains many foreign words or transliterations from foreign alphabets, e.g. Japanese). Do not enable this if you generate in a language that needs diacritics, like German or Polish! The pronounciation will be wrong then.
### LLM Pre-processing
- Enable LLM processing to use language models for preprocessing the text before sending it to the TTS API. For example, you may ask the LLM to remove OCR artifacts, spell out abbreviations, correct punctuation etc.
- You can define up to three prompts for text optimization. Each prompt is sent to the LLM API separately, and the output of the last prompt is used for TTS generation.
- For each prompt, you can enable/disable it, set the prompt text, choose the LLM model to use, and enable/disable evaluation (if enabled, the LLM API will be called twice for each prompt, and then again for the model to choose the better result).
- Load the available LLM models using the "Load LLM Models" button in the Session tab.
### RVC Quality Enhancement and Voice Cloning
- Enable RVC to enhance the generated audio quality and apply voice cloning.
- Select the RVC model file (.pth) and the corresponding index file using the "Select RVC Model" and "Select RVC Index" buttons in the Audio Processing tab.
- When RVC is enabled, the generated audio will be processed using the selected RVC model and index before being saved.
### NISQA TTS Evaluation
- Enable TTS evaluation to assess the quality of the generated audio using the NISQA (Non-Intrusive Speech Quality Assessment) model.
- Set the target MOS (Mean Opinion Score) value and the maximum number of attempts for each sentence.
- When TTS evaluation is enabled, the generated audio will be evaluated using the NISQA model, and the best audio (based on the MOS score) will be chosen for each sentence.
- If the target MOS value is not reached within the maximum number of attempts, the best audio generated so far will be used.
## Contributing
Contributions, suggestions for improvements, and bug reports are most welcome!
## Tips
- You can find a collection of voice sample for example [here](https://aiartes.com/voiceai). They are intended for use with ElevenLabs, so you will need to pick an 8-12s fragment and save it as 22050khz mono `.wav` usuing Audacity, for instance.
- You can find a collection of RVC models for example [here](https://voice-models.com/).
## To-do
- [ ] Add support for chapter segmentation
- [ ] Add support for Surya for PDF OCR, layout and redeaing order detection, plus preprocessing of chapters, headers, footers, footnotes and tables.
- [ ] Add support for StyleTTS2
- [ ] Add importing/exporting settings.
- [ ] Add support for proprietary APIs for text pre-processing and TTS generation.
- [ ] Include OCR for PDFs.
- [ ] Add support for a higher quality local TTS model, Tortoise.
- [ ] Add option to record a voice sample and use it for TTS to the GUI.
- [x] Add all API servers to the setup script.
- [x] Add support for custom XTTS models
- [x] Add workflow to create dubbing from `.srt` subtitle files.
- [x] Include support for PDF files.
- [x] Integrate editing capabilities for processed sentences within the UI.
- [x] Add support for a lower quality but faster local TTS model that can easily run on CPU, e.g. Silero or Piper.
- [x] Add support for EPUB.
--pandrator_installer_launcher.py--
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
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()
# 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.voicecraft_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)
self.launch_voicecraft_var = ctk.BooleanVar(value=False)
# Initialize process attributes
self.xtts_process = None
self.pandrator_process = None
self.silero_process = None
self.voicecraft_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) using winget if not installed already.\n\n"
"To uninstall Pandrator, simply delete the Pandrator folder.\n\n"
"The installation will take about 6-20GB of disk space depending on the number of selected options.")
self.info_text.configure(state="disabled")
# Installation Frame
self.installation_frame = ctk.CTkFrame(self.content_frame)
self.installation_frame.pack(fill="x", padx=20, pady=10)
ctk.CTkLabel(self.installation_frame, text="Installation", font=("Arial", 18, "bold")).pack(anchor="w", padx=10, pady=(10, 5))
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)
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)
self.voicecraft_checkbox = ctk.CTkCheckBox(engine_frame, text="Voicecraft", variable=self.voicecraft_var)
self.voicecraft_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", variable=self.whisperx_var)
self.whisperx_checkbox.pack(anchor="w", padx=10, pady=5)
button_frame = ctk.CTkFrame(self.installation_frame)
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")
# Launch Frame
self.launch_frame = ctk.CTkFrame(self.content_frame)
self.launch_frame.pack(fill="x", padx=20, pady=10)
ctk.CTkLabel(self.launch_frame, text="Launch", font=("Arial", 18, "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)
ctk.CTkCheckBox(self.launch_frame, text="Voicecraft", variable=self.launch_voicecraft_var).grid(row=4, 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))
# Progress Bar and Status Label
self.progress_bar = ctk.CTkProgressBar(self.content_frame)
self.progress_bar.pack(fill="x", padx=20, pady=(20, 10))
self.progress_bar.set(0)
self.status_label = ctk.CTkLabel(self.content_frame, text="", font=("Arial", 14))
self.status_label.pack(pady=(0, 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')
logging.basicConfig(filename=self.log_filename, level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s')
self.open_log_button.configure(state="normal")
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)
# 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)
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)
# VoiceCraft
voicecraft_support = config.get('voicecraft_support', False)
set_widget_state(self.voicecraft_checkbox, "disabled" if voicecraft_support else "normal", False)
voicecraft_launch_checkbox = next(widget for widget in self.launch_frame.winfo_children() if isinstance(widget, ctk.CTkCheckBox) and widget.cget("text") == "Voicecraft")
set_widget_state(voicecraft_launch_checkbox, "normal" if voicecraft_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)
# WhisperX
whisperx_support = config.get('whisperx_support', False)
set_widget_state(self.whisperx_checkbox, "disabled" if whisperx_support else "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),
'voicecraft': config.get('voicecraft_support', False),
'rvc': config.get('rvc_support', False),
'whisperx': config.get('whisperx_support', False)
}
def install_whisperx(self, conda_path, env_name):
logging.info(f"Installing WhisperX in {env_name}...")
try:
# Install Git through Conda
self.run_command([
os.path.join(conda_path, 'Scripts', 'conda.exe'),
'install', '-n', env_name,
'git', '-c', 'conda-forge', '-y'
])
# Install PyTorch
self.run_command([
os.path.join(conda_path, 'Scripts', 'conda.exe'),
'run', '-n', env_name,
'pip', 'install',
'torch==2.0.1', 'torchvision==0.15.2', 'torchaudio==2.0.2',
'--index-url', 'https://download.pytorch.org/whl/cu118'
])
# Install cuDNN
self.run_command([
os.path.join(conda_path, 'Scripts', 'conda.exe'),
'install', '-n', env_name,
'cudnn=8.9.7.29', '-c', 'conda-forge', '-y'
])
# Install ffmpeg
self.run_command([
os.path.join(conda_path, 'Scripts', 'conda.exe'),
'install', '-n', env_name,
'ffmpeg', '-c', 'conda-forge', '-y'
])
# Install WhisperX
self.run_command([
os.path.join(conda_path, 'Scripts', 'conda.exe'),
'run', '-n', env_name,
'pip', 'install', 'git+https://github.com/m-bain/whisperx.git'
])
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.voicecraft_var.get() and not installed_components['voicecraft'] 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
)
else:
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=cwd
)
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.decode('utf-8')}")
logging.debug(f"STDERR: {stderr.decode('utf-8')}")
return stdout.decode('utf-8'), stderr.decode('utf-8')
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.decode('utf-8')}")
logging.error(f"STDERR: {e.stderr.decode('utf-8')}")
raise
def check_program_installed(self, program):
try:
self.run_command(['where', program])
return True
except subprocess.CalledProcessError:
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_winget(self):
try:
logging.info("Checking if winget is installed...")
try:
version_output, _ = self.run_command(['winget', '--version'])
current_version = version_output.strip()
if current_version.startswith("v"):
current_version = current_version[1:]
logging.info(f"Current winget version: {current_version}")
needs_update = packaging.version.parse(current_version) < packaging.version.parse("1.7")
except FileNotFoundError:
logging.info("winget is not installed.")
needs_update = True
if needs_update:
logging.info("Installing/Updating winget...")
with tempfile.TemporaryDirectory() as temp_dir:
script_path = os.path.join(temp_dir, "winget-install.ps1")
# Download the PowerShell script
self.run_command([
'powershell',
'-Command',
f'Invoke-WebRequest -Uri "https://github.com/asheroto/winget-install/releases/latest/download/winget-install.ps1" -OutFile "{script_path}"'
], use_shell=True)
# Execute the PowerShell script with -Force parameter and wait for it to finish
try:
process = subprocess.Popen([
'powershell',
'-ExecutionPolicy', 'Bypass',
'-File', script_path,
'-Force' # Add this to force the update
], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, creationflags=subprocess.CREATE_NO_WINDOW)
# Real-time output processing
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
logging.info(output.strip())
# Get the return code
return_code = process.poll()
# Check for any errors
errors = process.stderr.read()
if errors:
logging.error(f"Errors during winget installation: {errors}")
if return_code != 0:
raise subprocess.CalledProcessError(return_code, 'PowerShell script')
logging.info("Winget installation/update script completed.")
except subprocess.CalledProcessError as e:
logging.error(f"Failed to execute PowerShell script: {str(e)}")
raise
# Refresh environment variables
self.refresh_environment_variables()
# Verify installation/update
try:
new_version_output, _ = self.run_command(['winget', '--version'])
new_version = new_version_output.strip()
if new_version.startswith("v"):
new_version = new_version[1:]
logging.info(f"Installed/Updated winget version: {new_version}")
if packaging.version.parse(new_version) >= packaging.version.parse("1.7"):
logging.info("winget has been successfully installed/updated.")
else:
logging.warning(f"winget version is still below 1.7 after installation/update attempt.")
messagebox.showwarning("Update Warning", "winget installation/update may not have succeeded. Please check and update manually if needed.")
except FileNotFoundError:
logging.error("winget still not found after installation attempt.")
messagebox.showerror("Error", "Failed to install winget. Please install it manually.")
else:
logging.info(f"Existing winget version {current_version} is adequate. No update needed.")
except Exception as e:
logging.error(f"An error occurred during winget installation/update: {str(e)}")
logging.error(traceback.format_exc())
messagebox.showerror("Error", f"Failed to install/update winget: {str(e)}")
def get_system_architecture(self):
return 'x64' if sys.maxsize > 2**32 else 'x86'
def get_program_path_from_registry(self, program_name):
try:
if program_name == 'git':
key_path = r"SOFTWARE\GitForWindows"
value_name = "InstallPath"
else:
return None
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_path) as key:
if value_name:
return winreg.QueryValueEx(key, value_name)[0]
else:
return winreg.QueryValueEx(key, "")[0] # Default value
except WindowsError:
return None
def install_dependencies(self):
return self.install_calibre()
def install_calibre(self):
logging.info("Checking installation for Calibre")
if not self.check_program_installed('calibre'):
logging.info("Installing Calibre...")
try:
self.run_command(['winget', 'install', '--id', 'calibre.calibre', '-e', '--accept-source-agreements', '--accept-package-agreements'])
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
except subprocess.CalledProcessError as e:
logging.error("Failed to install Calibre.")
logging.error(f"Error output: {e.stderr.decode('utf-8')}")
return False
else:
logging.info("Calibre is already installed.")
return True
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_visual_cpp_build_tools(self):
logging.info("Installing/Updating Microsoft Visual C++ Build Tools...")
self.update_status("Installing/Updating Microsoft Visual C++ Build Tools...")
# First, accept source agreements
accept_agreements_command = [
"winget", "source", "update",
"--accept-source-agreements"
]
try:
self.run_command(accept_agreements_command)
logging.info("Source agreements accepted.")
except subprocess.CalledProcessError as e:
logging.error(f"Failed to accept source agreements: {e}")
# Continue with the installation attempt even if this fails
winget_command = [
"winget", "install",
"--id", "Microsoft.VisualStudio.2022.BuildTools",
"--override", "--quiet --wait --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended",
"--accept-package-agreements",
"--accept-source-agreements"
]
try:
process = subprocess.Popen(winget_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, errors='replace')
output = []
while True:
try:
line = process.stdout.readline()
if not line and process.poll() is not None:
break
if line:
output.append(line.strip())
logging.info(line.strip())
except UnicodeDecodeError as ude:
logging.warning(f"UnicodeDecodeError encountered: {ude}")
continue
error_output = process.stderr.read().strip()
if error_output:
logging.debug(f"STDERR: {error_output}")
returncode = process.poll()
if returncode == 0 or any("No available upgrade found" in line for line in output):
logging.info("Microsoft Visual C++ Build Tools are up to date or successfully installed.")
self.update_status("Build Tools are ready.")
return True
else:
logging.error(f"Failed to install/update Microsoft Visual C++ Build Tools. Return code: {returncode}")
if error_output:
logging.error(f"Error output: {error_output}")
self.update_status("Error during Build Tools installation/update. Check the log for details.")
return False
except Exception as e:
logging.error(f"An error occurred during Visual C++ Build Tools installation: {str(e)}")
logging.error(traceback.format_exc())
self.update_status("Error during Build Tools installation/update. Check the log for details.")
return False
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', '/RegisterPython=0', '/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}...")
try:
# Create the environment with Python
create_command = [
os.path.join(conda_path, 'Scripts', 'conda.exe'),
'create',
'-n', env_name,
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',
'-n', env_name,
'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',
'-n', env_name,
'-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}...")
self.run_command([os.path.join(conda_path, 'Scripts', 'conda.exe'), 'run', '-n', env_name, 'pip', 'install', '-r', requirements_file])
def install_package(self, conda_path, env_name, package):
logging.info(f"Installing {package} in {env_name}...")
self.run_command([os.path.join(conda_path, 'Scripts', 'conda.exe'), 'run', '-n', env_name, 'pip', 'install', package])
def download_pretrained_models(self, repo_path):
pretrained_models_dir = os.path.join(repo_path, 'pretrained_models')
os.makedirs(pretrained_models_dir, exist_ok=True)
encodec_url = 'https://huggingface.co/pyp1/VoiceCraft/resolve/main/encodec_4cb2048_giga.th'
voicecraft_model_dir = os.path.join(pretrained_models_dir, 'VoiceCraft_gigaHalfLibri330M_TTSEnhanced_max16s')
os.makedirs(voicecraft_model_dir, exist_ok=True)
config_url = 'https://huggingface.co/pyp1/VoiceCraft_gigaHalfLibri330M_TTSEnhanced_max16s/resolve/main/config.json'
model_url = 'https://huggingface.co/pyp1/VoiceCraft_gigaHalfLibri330M_TTSEnhanced_max16s/resolve/main/model.safetensors'
encodec_path = os.path.join(pretrained_models_dir, 'encodec_4cb2048_giga.th')
config_path = os.path.join(voicecraft_model_dir, 'config.json')
model_path = os.path.join(voicecraft_model_dir, 'model.safetensors')
def download_file(url, path):
if not os.path.exists(path):
logging.info(f"Downloading {os.path.basename(path)}...")
try:
response = requests.get(url, stream=True)
response.raise_for_status()
with open(path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
logging.info(f"Successfully downloaded {os.path.basename(path)}")
except requests.RequestException as e:
logging.error(f"Failed to download {os.path.basename(path)}")
logging.error(f"Error message: {str(e)}")
raise
else:
logging.info(f"{os.path.basename(path)} already exists. Skipping download.")
download_file(encodec_url, encodec_path)
download_file(config_url, config_path)
download_file(model_url, model_path)
def install_pytorch_and_xtts_api_server(self, conda_path, env_name):
logging.info(f"Installing PyTorch and xtts-api-server package in {env_name}...")
try:
# Install PyTorch
if self.xtts_cpu_var.get():
pytorch_cmd = [os.path.join(conda_path, 'Scripts', 'conda.exe'), 'run', '-n', env_name, 'pip', 'install', 'torch==2.1.1', 'torchaudio==2.1.1']
else:
pytorch_cmd = [os.path.join(conda_path, 'Scripts', 'conda.exe'), 'run', '-n', env_name, '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 xtts-api-server package
xtts_cmd = [os.path.join(conda_path, 'Scripts', 'conda.exe'), 'run', '-n', env_name, 'pip', 'install', 'xtts-api-server']
self.run_command(xtts_cmd)
logging.info("PyTorch and xtts-api-server package installed successfully.")
except subprocess.CalledProcessError as e:
logging.error("Error installing PyTorch and xtts-api-server package.")
logging.error(f"Error output: {e.stderr.decode('utf-8')}")
raise
def install_audiocraft(self, conda_path, env_name, voicecraft_repo_path):
logging.info(f"Installing audiocraft package in {env_name}...")
try:
audiocraft_repo = 'https://github.com/facebookresearch/audiocraft.git'
audiocraft_commit = 'c5157b5bf14bf83449c17ea1eeb66c19fb4bc7f0'