archivartaunik commited on
Commit
c6fbbbc
·
verified ·
1 Parent(s): ea2768e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -79
app.py CHANGED
@@ -1,69 +1,57 @@
1
- # Імпартуем патрэбныя модулі
2
- import gradio as gr
3
- import torch
4
- from huggingface_hub import hf_hub_download
5
  import os
6
- import sys
7
- import tempfile
8
- from scipy.io.wavfile import write
 
9
  from tqdm import tqdm
10
- import nltk
11
- from nltk.tokenize import sent_tokenize
12
- import warnings
13
- import logging
14
 
15
- # Наладжваем лагаванне
16
- logging.basicConfig(level=logging.INFO)
17
- logger = logging.getLogger(__name__)
18
 
19
- # Ігнаруем папярэджанні NVML
20
- warnings.filterwarnings("ignore", category=UserWarning, message="Can't initialize NVML")
 
21
 
22
- # Загружаем NLTK даныя
23
- nltk.download('punkt')
24
 
25
- # Клонуем рэпазіторый, калі ён яшчэ не загружаны
26
- if not os.path.exists("XTTSv2-Finetuning-for-New-Languages"):
27
- logger.info("Кланаванне рэпазіторыя...")
28
- os.system("git clone https://github.com/hellcatmon/XTTSv2-Finetuning-for-New-Languages.git")
 
 
29
 
30
- # Перамяшчаем тэчку TTS у асноўную дырэкторыю
31
- if os.path.exists("XTTSv2-Finetuning-for-New-Languages/TTS"):
32
- logger.info("Перамяшчэнне тэчкі TTS...")
33
- os.system("mv XTTSv2-Finetuning-for-New-Languages/TTS ./")
34
 
35
- # Дадаем тэчку TTS у PYTHONPATH
36
- sys.path.append("./TTS")
37
- from TTS.tts.configs.xtts_config import XttsConfig
38
- from TTS.tts.models.xtts import Xtts
39
 
40
- # Вызначэнне прылады (наўпрост CPU)
41
- device = "cpu"
42
- logger.info(f"Выбраная прылада: {device}")
43
 
44
- # Шлях да мадэлі ў Hugging Face
45
- repo_id = "archivartaunik/BE_XTTS_V2_60epoch3Dataset"
46
- checkpoint_file = hf_hub_download(repo_id, filename="model.pth")
47
- config_file = hf_hub_download(repo_id, filename="config.json")
48
- vocab_file = hf_hub_download(repo_id, filename="vocab.json")
49
- default_voice_file = hf_hub_download(repo_id, filename="voice.wav")
50
 
51
- # Загрузка канфігурацыі мадэлі
52
  config = XttsConfig()
53
- config.load_json(config_file)
54
-
55
- # Ініцыялізацыя і загрузка мадэлі без weights_only
56
  XTTS_MODEL = Xtts.init_from_config(config)
57
- XTTS_MODEL.load_checkpoint(config, checkpoint_path=checkpoint_file, vocab_path=vocab_file, use_deepspeed=False)
58
  XTTS_MODEL.to(device)
 
59
 
60
- def text_to_speech(belarusian_story, lang="be", speaker_audio_file=None):
61
- # Калі файл не пададзены, выкарыстоўваем голас па змаўчанні
62
- if not speaker_audio_file or (not isinstance(speaker_audio_file, str) and speaker_audio_file.name == ""):
63
- speaker_audio_file = default_voice_file
64
 
65
- logger.info("Атрыманне латэнтных умоў і эмацый...")
66
- # Атрыманне латэнтных умоў і эмацый
67
  gpt_cond_latent, speaker_embedding = XTTS_MODEL.get_conditioning_latents(
68
  audio_path=speaker_audio_file,
69
  gpt_cond_len=XTTS_MODEL.config.gpt_cond_len,
@@ -71,12 +59,8 @@ def text_to_speech(belarusian_story, lang="be", speaker_audio_file=None):
71
  sound_norm_refs=XTTS_MODEL.config.sound_norm_refs,
72
  )
73
 
74
- logger.info("Токенізацыя тэксту на асобныя сказы...")
75
- # Токенізацыя тэксту на асобныя сказы
76
- tts_texts = sent_tokenize(belarusian_story)
77
 
78
- logger.info("Генерацыя аўдыё для кожнага сказы...")
79
- # Генерацыя аўдыё для кожнага сказы
80
  wav_chunks = []
81
  for text in tqdm(tts_texts):
82
  wav_chunk = XTTS_MODEL.inference(
@@ -92,30 +76,30 @@ def text_to_speech(belarusian_story, lang="be", speaker_audio_file=None):
92
  )
93
  wav_chunks.append(torch.tensor(wav_chunk["wav"]))
94
 
95
- logger.info("Аб'яднанне аўдыё частак у адзін масіў...")
96
- # Аб'ядноўваем усе часткі аўдыё ў адзін масіў
97
- out_wav = torch.cat(wav_chunks, dim=0).squeeze().cpu().numpy()
98
-
99
- logger.info("Захаванне аўдыё ў часовы файл...")
100
- # Захоўваем аўдыё ў часовы файл з памяншанай частатой
101
- temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
102
- write(temp_file.name, 16000, out_wav) # Выкарыстоўвайце 16000 Гц
103
-
104
- logger.info("Вяртанне шляху да аўдыё файла.")
105
- return temp_file.name
106
-
107
- # Стварэнне Gradio Інтэрфейсу
108
- demo = gr.Interface(
109
- fn=text_to_speech,
110
- inputs=[
111
- gr.Textbox(lines=5, label="Тэкст на беларускай мове"),
112
- gr.Textbox(value="be", label="Мова (па змаўчанні BE)", visible=False),
113
- gr.Audio(type="filepath", label="Запішыце або загрузіце файл голасу (без іншых гукаў) не карацей 7 секунд", interactive=True),
114
- ],
115
- outputs="audio",
116
- title="XTTS Belarusian TTS Demo",
117
- description="Увядзіце тэкст, і мадэль пераўтворыць яго ў аўдыя. Вы можаце выкарыстоўваць голас па змаўчанні, загрузіць уласны файл або запісаць аўдыё.",
118
- )
119
 
120
  # Launch the app
121
  if __name__ == "__main__":
 
 
 
 
 
1
  import os
2
+ import shutil
3
+ import torch
4
+ import torchaudio
5
+ import gradio as gr
6
  from tqdm import tqdm
7
+ from huggingface_hub import snapshot_download
8
+ from underthesea import sent_tokenize
9
+ from TTS.tts.configs.xtts_config import XttsConfig
10
+ from TTS.tts.models.xtts import Xtts
11
 
12
+ # Define repo and model paths
13
+ repo_id = "archivartaunik/BE_XTTS_V2_60epoch3Dataset"
14
+ destination_dir = "checkpoints/XTTS_v2.0_original_model_files/"
15
 
16
+ # Download model files
17
+ print("Downloading model files from Hugging Face...")
18
+ local_repo_path = snapshot_download(repo_id)
19
 
20
+ os.makedirs(destination_dir, exist_ok=True)
 
21
 
22
+ print("Copying model files...")
23
+ for root, _, files in os.walk(local_repo_path):
24
+ for file in files:
25
+ source_file = os.path.join(root, file)
26
+ relative_path = os.path.relpath(source_file, local_repo_path)
27
+ destination_file = os.path.join(destination_dir, relative_path)
28
 
29
+ os.makedirs(os.path.dirname(destination_file), exist_ok=True)
30
+ shutil.copy2(source_file, destination_file)
 
 
31
 
32
+ print(f"Model files are saved in {destination_dir}.")
 
 
 
33
 
34
+ # Initialize device
35
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
 
36
 
37
+ # Load model
38
+ print("Loading the model...")
39
+ xtts_checkpoint = os.path.join(destination_dir, "model.pth")
40
+ xtts_config = os.path.join(destination_dir, "config.json")
41
+ xtts_vocab = os.path.join(destination_dir, "vocab.json")
 
42
 
 
43
  config = XttsConfig()
44
+ config.load_json(xtts_config)
 
 
45
  XTTS_MODEL = Xtts.init_from_config(config)
46
+ XTTS_MODEL.load_checkpoint(config, checkpoint_path=xtts_checkpoint, vocab_path=xtts_vocab, use_deepspeed=False)
47
  XTTS_MODEL.to(device)
48
+ print("Model loaded successfully!")
49
 
50
+ # Function for inference
51
+ def tts_inference(belarusian_text):
52
+ lang = "be"
53
+ speaker_audio_file = os.path.join(destination_dir, "voice.wav")
54
 
 
 
55
  gpt_cond_latent, speaker_embedding = XTTS_MODEL.get_conditioning_latents(
56
  audio_path=speaker_audio_file,
57
  gpt_cond_len=XTTS_MODEL.config.gpt_cond_len,
 
59
  sound_norm_refs=XTTS_MODEL.config.sound_norm_refs,
60
  )
61
 
62
+ tts_texts = sent_tokenize(belarusian_text)
 
 
63
 
 
 
64
  wav_chunks = []
65
  for text in tqdm(tts_texts):
66
  wav_chunk = XTTS_MODEL.inference(
 
76
  )
77
  wav_chunks.append(torch.tensor(wav_chunk["wav"]))
78
 
79
+ out_wav = torch.cat(wav_chunks, dim=0).unsqueeze(0).cpu()
80
+
81
+ # Save the generated audio
82
+ output_path = "output.wav"
83
+ torchaudio.save(output_path, out_wav, sample_rate=24000)
84
+
85
+ return output_path
86
+
87
+ # Create Gradio app
88
+ def gradio_app():
89
+ with gr.Blocks() as app:
90
+ gr.Markdown("# Belarusian TTS Inference App")
91
+ text_input = gr.Textbox(label="Enter Belarusian Text", placeholder="Быў раз...")
92
+ audio_output = gr.Audio(label="Generated Speech")
93
+
94
+ generate_button = gr.Button("Generate Speech")
95
+
96
+ generate_button.click(
97
+ fn=tts_inference,
98
+ inputs=text_input,
99
+ outputs=audio_output,
100
+ )
101
+
102
+ return app
103
 
104
  # Launch the app
105
  if __name__ == "__main__":