Skip to content

Commit fe79f13

Browse files
committed
Заменен метод для сохранения результат в файл
В связи с тем, что функция scipy.io.wavfile.write поддерживает сохранение итогового файла исключительно в формате WAV, что требовало разработки отдельных функций для преобразования выходного файла в другие форматы, было принято решение о замене данной функции на pydub.AudioSegment.
1 parent b77745c commit fe79f13

1 file changed

Lines changed: 31 additions & 34 deletions

File tree

rvc/infer/infer.py

Lines changed: 31 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import edge_tts
66
import gradio as gr
7+
import numpy as np
78
import torch
89
from fairseq.checkpoint_utils import load_model_ensemble_and_task
910
from fairseq.data.dictionary import Dictionary
@@ -29,12 +30,9 @@
2930

3031

3132
# Отображает прогресс выполнения задачи.
32-
def display_progress(percent, message, progress=gr.Progress()):
33-
progress(percent, desc=message)
34-
35-
36-
def print_display_progress(percent, message, progress=gr.Progress()):
37-
print(message)
33+
def display_progress(percent, message, is_print, progress=gr.Progress()):
34+
if is_print:
35+
print(message)
3836
progress(percent, desc=message)
3937

4038

@@ -99,19 +97,6 @@ def get_vc(model_path):
9997
return cpt, version, net_g, tgt_sr, vc
10098

10199

102-
# Конвертируем файл в стерео и выбранный пользователем формат
103-
def convert_audio(input_audio, output_audio, output_format):
104-
# Загружаем аудиофайл
105-
audio = AudioSegment.from_file(input_audio)
106-
107-
# Если аудио моно, конвертируем его в стерео
108-
if audio.channels == 1:
109-
audio = audio.set_channels(2)
110-
111-
# Сохраняем аудиофайл в выбранном формате
112-
audio.export(output_audio, format=output_format)
113-
114-
115100
# Синтезирует текст в речь с использованием edge_tts.
116101
async def text_to_speech(voice, text, rate, volume, pitch, output_path):
117102
if not -100 <= rate <= 100:
@@ -148,16 +133,16 @@ def rvc_infer(
148133
if not os.path.exists(input_path):
149134
raise ValueError(f"Не удалось найти файл '{input_path}'. Убедитесь, что он загрузился или проверьте правильность пути к нему.")
150135

151-
print_display_progress(0, "\n[⚙️] Запуск конвейера генерации...")
136+
display_progress(0, "\n[⚙️] Запуск конвейера генерации...", True)
152137

153138
# Загружаем модель Hubert
154-
display_progress(0.1, "Загружаем модель Hubert...")
139+
display_progress(0.1, "Загружаем модель Hubert...", False)
155140
hubert_model = load_hubert(HUBERT_BASE_PATH)
156141
# Загружаем модель RVC и индекс
157-
display_progress(0.2, "Загружаем модель RVC и индекс...")
142+
display_progress(0.2, "Загружаем модель RVC и индекс...", False)
158143
model_path, index_path = load_rvc_model(rvc_model)
159144
# Получаем конвертер голоса
160-
display_progress(0.3, "Получаем конвертер голоса...")
145+
display_progress(0.3, "Получаем конвертер голоса...", False)
161146
cpt, version, net_g, tgt_sr, vc = get_vc(model_path)
162147
pitch_guidance = cpt.get("f0", 1)
163148

@@ -169,10 +154,10 @@ def rvc_infer(
169154
output_path = os.path.join(OUTPUT_DIR, f"{base_name}_({rvc_model}).{output_format}")
170155

171156
# Загружаем аудиофайл
172-
display_progress(0.4, "Загружаем аудиофайл...")
157+
display_progress(0.4, "Загружаем аудиофайл...", False)
173158
audio = load_audio(input_path, 16000)
174159

175-
print_display_progress(0.5, f"[🌌] Преобразование аудио — {base_name}...")
160+
display_progress(0.5, f"[🌌] Преобразование аудио — {base_name}...", True)
176161
audio_opt = vc.pipeline(
177162
hubert_model,
178163
net_g,
@@ -190,21 +175,33 @@ def rvc_infer(
190175
f0_min=f0_min,
191176
f0_max=f0_max,
192177
)
193-
# Сохраняем результат в wav файл
194-
display_progress(0.6, "Сохраняем результат...")
195-
wavfile.write(output_path, tgt_sr, audio_opt)
196178

197-
# Конвертируем файл в стерео и выбранный пользователем формат
198-
print_display_progress(0.8, "[💫] Конвертация аудио в стерео...")
199-
convert_audio(output_path, output_path, output_format)
179+
# Определяем тип данных и нормализуем
180+
if audio_opt.dtype == np.float32:
181+
# Масштабируем float32 [-1, 1] в int16
182+
audio_opt = (audio_opt * 32767).astype(np.int16)
183+
elif audio_opt.dtype == np.int16:
184+
pass
185+
else:
186+
raise ValueError(f"Неподдерживаемый формат аудио: {audio_opt.dtype}")
187+
188+
# Сохраняем результат в файл
189+
display_progress(0.8, "Сохраняем результат...", False)
190+
audio_segment = AudioSegment(
191+
audio_opt.tobytes(),
192+
frame_rate=tgt_sr,
193+
sample_width=audio_opt.dtype.itemsize,
194+
channels=1
195+
)
196+
audio_segment.export(output_path, format=output_format)
200197

201198
# Освобождаем память
202-
display_progress(0.9, "Освобождаем память...")
199+
display_progress(0.9, "Освобождаем память...", False)
203200
del hubert_model, cpt, net_g, vc
204201
gc.collect()
205202
torch.cuda.empty_cache()
206203

207-
print_display_progress(1.0, f"[✅] Преобразование завершено — {output_path}")
204+
display_progress(1.0, f"[✅] Преобразование завершено — {output_path}", True)
208205
return gr.Audio(output_path, label=os.path.basename(output_path))
209206

210207

@@ -232,7 +229,7 @@ def rvc_edgetts_infer(
232229
if not tts_voice:
233230
raise ValueError("Выберите язык и голос для синтеза речи.")
234231

235-
display_progress(1.0, "[🎙️] Синтезируем речь...")
232+
display_progress(1.0, "[🎙️] Синтезируем речь...", False)
236233
input_path = os.path.join(OUTPUT_DIR, "TTS_Voice.wav")
237234
asyncio.run(text_to_speech(tts_voice, tts_text, tts_rate, tts_volume, tts_pitch, input_path))
238235

0 commit comments

Comments
 (0)