python Copy code
import os
import sys
import json
import re
import shutil
import threading
import time
import traceback
from multiprocessing import Process, Queue, cpu_count
from queue import Empty
import numpy as np
import pyworld
import librosa
import sounddevice as sd
import torch
import torch.nn.functional as F
import torchaudio.transforms as tat
from dotenv import load_dotenv
from tkinter import (
Tk,
Frame,
Label,
Entry,
Button,
Scale,
Checkbutton,
Radiobutton,
StringVar,
IntVar,
DoubleVar,
BooleanVar,
filedialog,
messagebox,
)
from tkinter import ttk
from infer.lib import rtrvc as rvc_for_realtime
from i18n.i18n import I18nAuto
from configs.config import Config
from tools.torchgate import TorchGate
load_dotenv()
os.environ["OMP_NUM_THREADS"] = "4"
if sys.platform == "darwin":
os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
now_dir = os.getcwd()
sys.path.append(now_dir)
flag_vc = False
def printt(strr, *args):
if len(args) == 0:
print(strr)
else:
print(strr % args)
def phase_vocoder(a, b, fade_out, fade_in):
window = torch.sqrt(fade_out * fade_in)
fa = torch.fft.rfft(a * window)
fb = torch.fft.rfft(b * window)
absab = torch.abs(fa) + torch.abs(fb)
n = a.shape[0]
if n % 2 == 0:
absab[1:-1] *= 2
else:
absab[1:] *= 2
phia = torch.angle(fa)
phib = torch.angle(fb)
deltaphase = phib - phia
deltaphase = deltaphase - 2 * np.pi * torch.floor(deltaphase / 2 / np.pi + 0.5)
w = 2 * np.pi * torch.arange(n // 2 + 1).to(a) + deltaphase
t = torch.arange(n).unsqueeze(-1).to(a) / n
result = (
a * (fade_out**2)
+ b * (fade_in**2)
+ torch.sum(absab * torch.cos(w * t + phia), -1) * window / n
)
return result
class Harvest(Process):
def __init__(self, inp_q, opt_q):
super().__init__()
self.inp_q = inp_q
self.opt_q = opt_q
def run(self):
while True:
try:
idx, x, res_f0, n_cpu, ts = self.inp_q.get()
f0, t = pyworld.harvest(
x.astype(np.double),
fs=16000,
f0_ceil=1100,
f0_floor=50,
frame_period=10,
)
res_f0[idx] = f0
if len(res_f0.keys()) >= n_cpu:
self.opt_q.put(ts)
except Exception as e:
print("Harvest process error:", e)
traceback.print_exc()
class GUIConfig:
def __init__(self) -> None:
self.pth_path: str = ""
self.index_path: str = ""
self.pitch: int = 0
self.formant = 0.0
self.sr_type: str = "sr_model"
self.block_time: float = 0.25 # s
self.threhold: int = -60
self.crossfade_time: float = 0.05
self.extra_time: float = 2.5
self.I_noise_reduce: bool = False
self.O_noise_reduce: bool = False
self.use_pv: bool = False
self.rms_mix_rate: float = 0.0
self.index_rate: float = 0.0
self.n_cpu: int = min(cpu_count(), 4)
self.f0method: str = "fcpe"
self.sg_hostapi: str = ""
self.wasapi_exclusive: bool = False
self.sg_input_device: str = ""
self.sg_output_device: str = ""
class GUI:
def __init__(self, root):
self.root = root
self.root.title("RVC - GUI")
self.gui_config = GUIConfig()
self.config = Config()
self.function = "vc"
self.delay_time = 0
self.hostapis = None
self.input_devices = None
self.output_devices = None
self.input_devices_indices = None
self.output_devices_indices = None
self.stream = None
self.i18n = I18nAuto()
self.inp_q = Queue()
self.opt_q = Queue()
self.n_cpu = min(cpu_count(), 8)
self.processes = []
for _ in range(self.n_cpu):
p = Harvest(self.inp_q, self.opt_q)
p.daemon = True
p.start()
self.processes.append(p)
self.update_devices()
self.create_widgets()
def load(self):
try:
if not os.path.exists("configs/inuse/config.json"):
shutil.copy("configs/config.json", "configs/inuse/config.json")
with open("configs/inuse/config.json", "r") as j:
data = json.load(j)
data["sr_model"] = data["sr_type"] == "sr_model"
data["sr_device"] = data["sr_type"] == "sr_device"
data["pm"] = data["f0method"] == "pm"
data["harvest"] = data["f0method"] == "harvest"
data["crepe"] = data["f0method"] == "crepe"
data["rmvpe"] = data["f0method"] == "rmvpe"
data["fcpe"] = data["f0method"] == "fcpe"
if data["sg_hostapi"] in self.hostapis:
self.update_devices(hostapi_name=data["sg_hostapi"])
if (
data["sg_input_device"] not in self.input_devices
or data["sg_output_device"] not in self.output_devices
):
self.update_devices()
data["sg_hostapi"] = self.hostapis[0]
data["sg_input_device"] = self.input_devices[
self.input_devices_indices.index(sd.default.device[0])
]
data["sg_output_device"] = self.output_devices[
self.output_devices_indices.index(sd.default.device[1])
]
else:
data["sg_hostapi"] = self.hostapis[0]
data["sg_input_device"] = self.input_devices[
self.input_devices_indices.index(sd.default.device[0])
]
data["sg_output_device"] = self.output_devices[
self.output_devices_indices.index(sd.default.device[1])
]
except Exception as e:
print("Load config error:", e)
data = {
"pth_path": "",
"index_path": "",
"sg_hostapi": self.hostapis[0],
"sg_wasapi_exclusive": False,
"sg_input_device": self.input_devices[
self.input_devices_indices.index(sd.default.device[0])
],
"sg_output_device": self.output_devices[
self.output_devices_indices.index(sd.default.device[1])
],
"sr_type": "sr_model",
"threhold": -60,
"pitch": 0,
"formant": 0.0,
"index_rate": 0,
"rms_mix_rate": 0,
"block_time": 0.25,
"crossfade_length": 0.05,
"extra_time": 2.5,
"n_cpu": 4,
"f0method": "rmvpe",
"use_jit": False,
"use_pv": False,
}
data["sr_model"] = data["sr_type"] == "sr_model"
data["sr_device"] = data["sr_type"] == "sr_device"
data["pm"] = data["f0method"] == "pm"
data["harvest"] = data["f0method"] == "harvest"
data["crepe"] = data["f0method"] == "crepe"
data["rmvpe"] = data["f0method"] == "rmvpe"
data["fcpe"] = data["f0method"] == "fcpe"
return data
def save_config(self, settings):
try:
with open("configs/inuse/config.json", "w") as j:
json.dump(settings, j, indent=4)
except Exception as e:
print("Save config error:", e)
def create_widgets(self):
data = self.load()
# Load Model Frame
load_model_frame = Frame(self.root, relief="groove", borderwidth=2, padx=10, pady=10)
load_model_frame.grid(row=0, column=0, padx=10, pady=5, sticky="ew")
Label(load_model_frame, text=self.i18n("加载模型")).grid(row=0, column=0, columnspan=2, sticky="w")
# PTH File
Label(load_model_frame, text=self.i18n("PTH 文件:")).grid(row=1, column=0, sticky="e")
self.pth_path_var = StringVar(value=data.get("pth_path", ""))
self.pth_entry = Entry(load_model_frame, textvariable=self.pth_path_var, width=50)
self.pth_entry.grid(row=1, column=1, padx=5, pady=2)
Button(
load_model_frame,
text=self.i18n("选择.pth 文件"),
command=self.browse_pth_file
).grid(row=1, column=2, padx=5, pady=2)
# Index File
Label(load_model_frame, text=self.i18n("Index 文件:")).grid(row=2, column=0, sticky="e")
self.index_path_var = StringVar(value=data.get("index_path", ""))
self.index_entry = Entry(load_model_frame, textvariable=self.index_path_var, width=50)
self.index_entry.grid(row=2, column=1, padx=5, pady=2)
Button(
load_model_frame,
text=self.i18n("选择.index 文件"),
command=self.browse_index_file
).grid(row=2, column=2, padx=5, pady=2)
# Audio Devices Frame
audio_devices_frame = Frame(self.root, relief="groove", borderwidth=2, padx=10, pady=10)
audio_devices_frame.grid(row=1, column=0, padx=10, pady=5, sticky="ew")
Label(audio_devices_frame, text=self.i18n("音频设备")).grid(row=0, column=0, columnspan=4, sticky="w")
# Host API
Label(audio_devices_frame, text=self.i18n("设备类型:")).grid(row=1, column=0, sticky="e")
self.sg_hostapi_var = StringVar(value=data.get("sg_hostapi", ""))
self.hostapi_combo = ttk.Combobox(
audio_devices_frame,
textvariable=self.sg_hostapi_var,
values=self.hostapis,
state="readonly",
width=20
)
self.hostapi_combo.grid(row=1, column=1, padx=5, pady=2)
self.hostapi_combo.bind("<<ComboboxSelected>>", self.on_hostapi_change)
# WASAPI Exclusive
self.sg_wasapi_exclusive_var = BooleanVar(value=data.get("sg_wasapi_exclusive", False))
self.wasapi_checkbox = Checkbutton(
audio_devices_frame,
text=self.i18n("独占 WASAPI 设备"),
variable=self.sg_wasapi_exclusive_var,
command=self.on_wasapi_change
)
self.wasapi_checkbox.grid(row=1, column=2, padx=5, pady=2, sticky="w")
# Input Device
Label(audio_devices_frame, text=self.i18n("输入设备:")).grid(row=2, column=0, sticky="e")
self.sg_input_device_var = StringVar(value=data.get("sg_input_device", ""))
self.input_device_combo = ttk.Combobox(
audio_devices_frame,
textvariable=self.sg_input_device_var,
values=self.input_devices,
state="readonly",
width=45
)
self.input_device_combo.grid(row=2, column=1, columnspan=2, padx=5, pady=2)
# Output Device
Label(audio_devices_frame, text=self.i18n("输出设备:")).grid(row=3, column=0, sticky="e")
self.sg_output_device_var = StringVar(value=data.get("sg_output_device", ""))
self.output_device_combo = ttk.Combobox(
audio_devices_frame,
textvariable=self.sg_output_device_var,
values=self.output_devices,
state="readonly",
width=45
)
self.output_device_combo.grid(row=3, column=1, columnspan=2, padx=5, pady=2)
# Reload Devices Button
self.reload_devices_button = Button(
audio_devices_frame,
text=self.i18n("重载设备列表"),
command=self.reload_devices
)
self.reload_devices_button.grid(row=4, column=0, padx=5, pady=5)
# Sample Rate Options
self.sr_model_var = BooleanVar(value=data.get("sr_model", True))
self.sr_device_var = BooleanVar(value=data.get("sr_device", False))
self.sr_model_radio = Radiobutton(
audio_devices_frame,
text=self.i18n("使用模型采样率"),
variable=self.sr_type,
value="sr_model",
command=self.on_sr_type_change
)
self.sr_model_radio.grid(row=4, column=1, padx=5, pady=2, sticky="w")
self.sr_device_radio = Radiobutton(
audio_devices_frame,
text=self.i18n("使用设备采样率"),
variable=self.sr_type,
value="sr_device",
command=self.on_sr_type_change
)
self.sr_device_radio.grid(row=4, column=2, padx=5, pady=2, sticky="w")
# Sample Rate Display
Label(audio_devices_frame, text=self.i18n("采样率:")).grid(row=5, column=0, sticky="e")
self.sr_stream_label = Label(audio_devices_frame, text="")
self.sr_stream_label.grid(row=5, column=1, padx=5, pady=2, sticky="w")
# General Settings Frame
general_settings_frame = Frame(self.root, relief="groove", borderwidth=2, padx=10, pady=10)
general_settings_frame.grid(row=2, column=0, padx=10, pady=5, sticky="ew")
Label(general_settings_frame, text=self.i18n("常规设置")).grid(row=0, column=0, columnspan=4, sticky="w")
# Threshold
Label(general_settings_frame, text=self.i18n("响应阈值:")).grid(row=1, column=0, sticky="e")
self.threhold_var = IntVar(value=data.get("threhold", -60))
self.threhold_slider = Scale(
general_settings_frame,
from_=-60,
to=0,
orient="horizontal",
variable=self.threhold_var,
command=self.on_threshold_change
)
self.threhold_slider.grid(row=1, column=1, padx=5, pady=2, sticky="w")
# Pitch
Label(general_settings_frame, text=self.i18n("音调设置:")).grid(row=2, column=0, sticky="e")
self.pitch_var = IntVar(value=data.get("pitch", 0))
self.pitch_slider = Scale(
general_settings_frame,
from_=-16,
to=16,
orient="horizontal",
variable=self.pitch_var,
command=self.on_pitch_change
)
self.pitch_slider.grid(row=2, column=1, padx=5, pady=2, sticky="w")
# Formant
Label(general_settings_frame, text=self.i18n("性别因子/声线粗细:")).grid(row=3, column=0, sticky="e")
self.formant_var = DoubleVar(value=data.get("formant", 0.0))
self.formant_slider = Scale(
general_settings_frame,
from_=-2.0,
to=2.0,
resolution=0.05,
orient="horizontal",
variable=self.formant_var,
command=self.on_formant_change
)
self.formant_slider.grid(row=3, column=1, padx=5, pady=2, sticky="w")
# Index Rate
Label(general_settings_frame, text=self.i18n("Index Rate:")).grid(row=4, column=0, sticky="e")
self.index_rate_var = DoubleVar(value=data.get("index_rate", 0.0))
self.index_rate_slider = Scale(
general_settings_frame,
from_=0.0,
to=1.0,
resolution=0.01,
orient="horizontal",
variable=self.index_rate_var,
command=self.on_index_rate_change
)
self.index_rate_slider.grid(row=4, column=1, padx=5, pady=2, sticky="w")
# RMS Mix Rate
Label(general_settings_frame, text=self.i18n("响度因子:")).grid(row=5, column=0, sticky="e")
self.rms_mix_rate_var = DoubleVar(value=data.get("rms_mix_rate", 0.0))
self.rms_mix_rate_slider = Scale(
general_settings_frame,
from_=0.0,
to=1.0,
resolution=0.01,
orient="horizontal",
variable=self.rms_mix_rate_var,
command=self.on_rms_mix_rate_change
)
self.rms_mix_rate_slider.grid(row=5, column=1, padx=5, pady=2, sticky="w")
# F0 Method
Label(general_settings_frame, text=self.i18n("音高算法:")).grid(row=6, column=0, sticky="e")
self.f0method_var = StringVar(value=data.get("f0method", "fcpe"))
methods = ["pm", "harvest", "crepe", "rmvpe", "fcpe"]
for idx, method in enumerate(methods):
Radiobutton(
general_settings_frame,
text=method,
variable=self.f0method_var,
value=method,
command=self.on_f0method_change
).grid(row=6, column=1+idx, padx=2, pady=2, sticky="w")
# Performance Settings Frame
performance_settings_frame = Frame(self.root, relief="groove", borderwidth=2, padx=10, pady=10)
performance_settings_frame.grid(row=3, column=0, padx=10, pady=5, sticky="ew")
Label(performance_settings_frame, text=self.i18n("性能设置")).grid(row=0, column=0, columnspan=4, sticky="w")
# Block Time
Label(performance_settings_frame, text=self.i18n("采样长度:")).grid(row=1, column=0, sticky="e")
self.block_time_var = DoubleVar(value=data.get("block_time", 0.25))
self.block_time_slider = Scale(
performance_settings_frame,
from_=0.02,
to=1.5,
resolution=0.01,
orient="horizontal",
variable=self.block_time_var,
command=self.on_block_time_change
)
self.block_time_slider.grid(row=1, column=1, padx=5, pady=2, sticky="w")
# Harvest CPU
Label(performance_settings_frame, text=self.i18n("harvest进程数:")).grid(row=2, column=0, sticky="e")
self.n_cpu_var = IntVar(value=data.get("n_cpu", min(self.gui_config.n_cpu, cpu_count())))
self.n_cpu_slider = Scale(
performance_settings_frame,
from_=1,
to=cpu_count(),
resolution=1,
orient="horizontal",
variable=self.n_cpu_var,
command=self.on_n_cpu_change
)
self.n_cpu_slider.grid(row=2, column=1, padx=5, pady=2, sticky="w")
# Crossfade Length
Label(performance_settings_frame, text=self.i18n("淡入淡出长度:")).grid(row=3, column=0, sticky="e")
self.crossfade_length_var = DoubleVar(value=data.get("crossfade_length", 0.05))
self.crossfade_length_slider = Scale(
performance_settings_frame,
from_=0.01,
to=0.15,
resolution=0.01,
orient="horizontal",
variable=self.crossfade_length_var,
command=self.on_crossfade_length_change
)
self.crossfade_length_slider.grid(row=3, column=1, padx=5, pady=2, sticky="w")
# Extra Time
Label(performance_settings_frame, text=self.i18n("额外推理时长:")).grid(row=4, column=0, sticky="e")
self.extra_time_var = DoubleVar(value=data.get("extra_time", 2.5))
self.extra_time_slider = Scale(
performance_settings_frame,
from_=0.05,
to=5.00,
resolution=0.01,
orient="horizontal",
variable=self.extra_time_var,
command=self.on_extra_time_change
)
self.extra_time_slider.grid(row=4, column=1, padx=5, pady=2, sticky="w")
# Noise Reduction and Phase Vocoder
self.I_noise_reduce_var = BooleanVar(value=data.get("I_noise_reduce", False))
self.I_noise_reduce_checkbox = Checkbutton(
performance_settings_frame,
text=self.i18n("输入降噪"),
variable=self.I_noise_reduce_var,
command=self.on_I_noise_reduce_change
)
self.I_noise_reduce_checkbox.grid(row=5, column=0, padx=5, pady=2, sticky="w")
self.O_noise_reduce_var = BooleanVar(value=data.get("O_noise_reduce", False))
self.O_noise_reduce_checkbox = Checkbutton(
performance_settings_frame,
text=self.i18n("输出降噪"),
variable=self.O_noise_reduce_var,
command=self.on_O_noise_reduce_change
)
self.O_noise_reduce_checkbox.grid(row=5, column=1, padx=5, pady=2, sticky="w")
self.use_pv_var = BooleanVar(value=data.get("use_pv", False))
self.use_pv_checkbox = Checkbutton(
performance_settings_frame,
text=self.i18n("启用相位声码器"),
variable=self.use_pv_var,
command=self.on_use_pv_change
)
self.use_pv_checkbox.grid(row=5, column=2, padx=5, pady=2, sticky="w")
# Buttons Frame
buttons_frame = Frame(self.root, padx=10, pady=10)
buttons_frame.grid(row=4, column=0, padx=10, pady=5, sticky="ew")
self.start_vc_button = Button(
buttons_frame,
text=self.i18n("开始音频转换"),
command=self.start_vc
)
self.start_vc_button.grid(row=0, column=0, padx=5, pady=5)
self.stop_vc_button = Button(
buttons_frame,
text=self.i18n("停止音频转换"),
command=self.stop_vc
)
self.stop_vc_button.grid(row=0, column=1, padx=5, pady=5)
self.function_var = StringVar(value="vc")
self.im_radio = Radiobutton(
buttons_frame,
text=self.i18n("输入监听"),
variable=self.function_var,
value="im",
command=self.on_function_change
)
self.im_radio.grid(row=0, column=2, padx=5, pady=5, sticky="w")
self.vc_radio = Radiobutton(
buttons_frame,
text=self.i18n("输出变声"),
variable=self.function_var,
value="vc",
command=self.on_function_change
)
self.vc_radio.grid(row=0, column=3, padx=5, pady=5, sticky="w")
# Status Labels
Label(buttons_frame, text=self.i18n("算法延迟(ms):")).grid(row=1, column=0, sticky="e")
self.delay_time_label = Label(buttons_frame, text="0")
self.delay_time_label.grid(row=1, column=1, sticky="w")
Label(buttons_frame, text=self.i18n("推理时间(ms):")).grid(row=1, column=2, sticky="e")
self.infer_time_label = Label(buttons_frame, text="0")
self.infer_time_label.grid(row=1, column=3, sticky="w")
self.window = None # Placeholder for future use
def browse_pth_file(self):
file_path = filedialog.askopenfilename(
title=self.i18n("选择.pth文件"),
initialdir=os.path.join(os.getcwd(), "assets", "weights"),
filetypes=[("PTH files", "*.pth")]
)
if file_path:
self.pth_path_var.set(file_path)
def browse_index_file(self):
file_path = filedialog.askopenfilename(
title=self.i18n("选择.index文件"),
initialdir=os.path.join(os.getcwd(), "logs"),
filetypes=[("Index files", "*.index")]
)
if file_path:
self.index_path_var.set(file_path)
def update_devices(self, hostapi_name=None):
global flag_vc
flag_vc = False
sd._terminate()
sd._initialize()
devices = sd.query_devices()
hostapis = sd.query_hostapis()
for hostapi in hostapis:
for device_idx in hostapi["devices"]:
devices[device_idx]["hostapi_name"] = hostapi["name"]
self.hostapis = [hostapi["name"] for hostapi in hostapis]
if hostapi_name not in self.hostapis:
hostapi_name = self.hostapis[0]
self.input_devices = [
d["name"]
for d in devices
if d["max_input_channels"] > 0 and d["hostapi_name"] == hostapi_name
]
self.output_devices = [
d["name"]
for d in devices
if d["max_output_channels"] > 0 and d["hostapi_name"] == hostapi_name
]
self.input_devices_indices = [
d["index"] if "index" in d else d["name"]
for d in devices
if d["max_input_channels"] > 0 and d["hostapi_name"] == hostapi_name
]
self.output_devices_indices = [
d["index"] if "index" in d else d["name"]
for d in devices
if d["max_output_channels"] > 0 and d["hostapi_name"] == hostapi_name
]
# Update Comboboxes
self.hostapi_combo['values'] = self.hostapis
self.hostapi_combo.set(hostapi_name)
self.input_device_combo['values'] = self.input_devices
self.output_device_combo['values'] = self.output_devices
if self.gui_config.sg_input_device not in self.input_devices:
self.gui_config.sg_input_device = self.input_devices[0]
self.sg_input_device_var.set(self.gui_config.sg_input_device)
if self.gui_config.sg_output_device not in self.output_devices:
self.gui_config.sg_output_device = self.output_devices[0]
self.sg_output_device_var.set(self.gui_config.sg_output_device)
def reload_devices(self):
self.update_devices()
def on_hostapi_change(self, event=None):
selected_hostapi = self.sg_hostapi_var.get()
self.update_devices(hostapi_name=selected_hostapi)
def on_wasapi_change(self):
# Handle WASAPI exclusive checkbox change if needed
pass
def on_sr_type_change(self):
selected = self.sr_type.get()
self.gui_config.sr_type = selected
# Update sample rate display or other related settings
self.update_sample_rate_display()
def update_sample_rate_display(self):
if self.gui_config.sr_type == "sr_model":
samplerate = self.gui_config.samplerate if hasattr(self, 'samplerate') else "Unknown"
else:
samplerate = self.get_device_samplerate()
self.sr_stream_label.config(text=str(samplerate))
def on_threshold_change(self, event=None):
self.gui_config.threhold = self.threhold_var.get()
def on_pitch_change(self, event=None):
self.gui_config.pitch = self.pitch_var.get()
if hasattr(self, "rvc"):
self.rvc.change_key(self.gui_config.pitch)
def on_formant_change(self, event=None):
self.gui_config.formant = self.formant_var.get()
if hasattr(self, "rvc"):
self.rvc.change_formant(self.gui_config.formant)
def on_index_rate_change(self, event=None):
self.gui_config.index_rate = self.index_rate_var.get()
if hasattr(self, "rvc"):
self.rvc.change_index_rate(self.gui_config.index_rate)
def on_rms_mix_rate_change(self, event=None):
self.gui_config.rms_mix_rate = self.rms_mix_rate_var.get()
def on_f0method_change(self):
self.gui_config.f0method = self.f0method_var.get()
def on_block_time_change(self, event=None):
self.gui_config.block_time = self.block_time_var.get()
def on_n_cpu_change(self, event=None):
self.gui_config.n_cpu = self.n_cpu_var.get()
def on_crossfade_length_change(self, event=None):
self.gui_config.crossfade_time = self.crossfade_length_var.get()
def on_extra_time_change(self, event=None):
self.gui_config.extra_time = self.extra_time_var.get()
def on_I_noise_reduce_change(self):
self.gui_config.I_noise_reduce = self.I_noise_reduce_var.get()
if self.stream is not None:
delta = min(self.crossfade_length_var.get(), 0.04) if self.I_noise_reduce_var.get() else -min(self.crossfade_length_var.get(), 0.04)
self.delay_time += delta
self.delay_time_label.config(text=str(int(np.round(self.delay_time * 1000))))
def on_O_noise_reduce_change(self):
self.gui_config.O_noise_reduce = self.O_noise_reduce_var.get()
def on_use_pv_change(self):
self.gui_config.use_pv = self.use_pv_var.get()
def on_function_change(self):
self.function = self.function_var.get()
def set_devices(self, input_device, output_device):
try:
sd.default.device = (
self.input_devices_indices[self.input_devices.index(input_device)],
self.output_devices_indices[self.output_devices.index(output_device)]
)
printt("Input device: %s:%s", str(sd.default.device[0]), input_device)
printt("Output device: %s:%s", str(sd.default.device[1]), output_device)
except Exception as e:
print("Set devices error:", e)
def get_device_samplerate(self):
return int(
sd.query_devices(device=sd.default.device[0])["default_samplerate"]
)
def get_device_channels(self):
max_input_channels = sd.query_devices(device=sd.default.device[0])["max_input_channels"]
max_output_channels = sd.query_devices(device=sd.default.device[1])["max_output_channels"]
return min(max_input_channels, max_output_channels, 2)
def set_values(self, values):
if len(self.pth_path_var.get().strip()) == 0:
messagebox.showwarning(self.i18n("警告"), self.i18n("请选择pth文件"))
return False
if len(self.index_path_var.get().strip()) == 0:
messagebox.showwarning(self.i18n("警告"), self.i18n("请选择index文件"))
return False
pattern = re.compile("[^\x00-\x7F]+")
if pattern.findall(self.pth_path_var.get()):
messagebox.showwarning(self.i18n("警告"), self.i18n("pth文件路径不可包含中文"))
return False
if pattern.findall(self.index_path_var.get()):
messagebox.showwarning(self.i18n("警告"), self.i18n("index文件路径不可包含中文"))
return False
self.set_devices(self.sg_input_device_var.get(), self.sg_output_device_var.get())
self.config.use_jit = False
self.gui_config.sg_hostapi = self.sg_hostapi_var.get()
self.gui_config.sg_wasapi_exclusive = self.sg_wasapi_exclusive_var.get()
self.gui_config.sg_input_device = self.sg_input_device_var.get()
self.gui_config.sg_output_device = self.sg_output_device_var.get()
self.gui_config.pth_path = self.pth_path_var.get()
self.gui_config.index_path = self.index_path_var.get()
self.gui_config.sr_type = self.sr_type.get()
self.gui_config.threhold = self.threhold_var.get()
self.gui_config.pitch = self.pitch_var.get()
self.gui_config.formant = self.formant_var.get()
self.gui_config.block_time = self.block_time_var.get()
self.gui_config.crossfade_time = self.crossfade_length_var.get()
self.gui_config.extra_time = self.extra_time_var.get()
self.gui_config.I_noise_reduce = self.I_noise_reduce_var.get()
self.gui_config.O_noise_reduce = self.O_noise_reduce_var.get()
self.gui_config.use_pv = self.use_pv_var.get()
self.gui_config.rms_mix_rate = self.rms_mix_rate_var.get()
self.gui_config.index_rate = self.index_rate_var.get()
self.gui_config.n_cpu = self.n_cpu_var.get()
self.gui_config.f0method = self.f0method_var.get()
return True
def start_vc(self):
if not self.set_values(None):
return
printt("cuda_is_available: %s", torch.cuda.is_available())
self.rvc = rvc_for_realtime.RVC(
self.gui_config.pitch,
self.gui_config.formant,
self.gui_config.pth_path,
self.gui_config.index_path,
self.gui_config.index_rate,
self.gui_config.n_cpu,
self.inp_q,
self.opt_q,
self.config,
self.rvc if hasattr(self, "rvc") else None,
)
self.gui_config.samplerate = (
self.rvc.tgt_sr
if self.gui_config.sr_type == "sr_model"
else self.get_device_samplerate()
)
self.gui_config.channels = self.get_device_channels()
self.zc = self.gui_config.samplerate // 100
self.block_frame = (
int(
np.round(
self.gui_config.block_time
* self.gui_config.samplerate
/ self.zc
)
)
* self.zc
)
self.block_frame_16k = 160 * self.block_frame // self.zc
self.crossfade_frame = (
int(
np.round(
self.gui_config.crossfade_time
* self.gui_config.samplerate
/ self.zc
)
)
* self.zc
)
self.sola_buffer_frame = min(self.crossfade_frame, 4 * self.zc)
self.sola_search_frame = self.zc
self.extra_frame = (
int(
np.round(
self.gui_config.extra_time
* self.gui_config.samplerate
/ self.zc
)
)
* self.zc
)
self.input_wav: torch.Tensor = torch.zeros(
self.extra_frame
+ self.crossfade_frame
+ self.sola_search_frame
+ self.block_frame,
device=self.config.device,
dtype=torch.float32,
)
self.input_wav_denoise: torch.Tensor = self.input_wav.clone()
self.input_wav_res: torch.Tensor = torch.zeros(
160 * self.input_wav.shape[0] // self.zc,
device=self.config.device,
dtype=torch.float32,
)
self.rms_buffer: np.ndarray = np.zeros(4 * self.zc, dtype="float32")
self.sola_buffer: torch.Tensor = torch.zeros(
self.sola_buffer_frame, device=self.config.device, dtype=torch.float32
)
self.nr_buffer: torch.Tensor = self.sola_buffer.clone()
self.output_buffer: torch.Tensor = self.input_wav.clone()
self.skip_head = self.extra_frame // self.zc
self.return_length = (
self.block_frame + self.sola_buffer_frame + self.sola_search_frame
) // self.zc
self.fade_in_window: torch.Tensor = (
torch.sin(
0.5
* np.pi
* torch.linspace(
0.0,
1.0,
steps=self.sola_buffer_frame,
device=self.config.device,
dtype=torch.float32,
)
)
** 2
)
self.fade_out_window: torch.Tensor = 1 - self.fade_in_window
self.resampler = tat.Resample(
orig_freq=self.gui_config.samplerate,
new_freq=16000,
dtype=torch.float32,
).to(self.config.device)
if self.rvc.tgt_sr != self.gui_config.samplerate:
self.resampler2 = tat.Resample(
orig_freq=self.rvc.tgt_sr,
new_freq=self.gui_config.samplerate,
dtype=torch.float32,
).to(self.config.device)
else:
self.resampler2 = None
self.tg = TorchGate(
sr=self.gui_config.samplerate, n_fft=4 * self.zc, prop_decrease=0.9
).to(self.config.device)
self.start_stream()
def start_stream(self):
global flag_vc
if not flag_vc:
flag_vc = True
if (
"WASAPI" in self.gui_config.sg_hostapi
and self.gui_config.sg_wasapi_exclusive
):
extra_settings = sd.WasapiSettings(exclusive=True)
else:
extra_settings = None
try:
self.stream = sd.Stream(
callback=self.audio_callback,
blocksize=self.block_frame,
samplerate=self.gui_config.samplerate,
channels=self.gui_config.channels,
dtype="float32",
extra_settings=extra_settings,
)
self.stream.start()
except Exception as e:
print("Error starting stream:", e)
flag_vc = False
def stop_vc(self):
global flag_vc
if flag_vc:
flag_vc = False
if self.stream is not None:
try:
self.stream.abort()
self.stream.close()
except Exception as e:
print("Error stopping stream:", e)
self.stream = None
def audio_callback(
self, indata: np.ndarray, outdata: np.ndarray, frames, times, status
):
global flag_vc
start_time = time.perf_counter()
indata = librosa.to_mono(indata.T)
if self.gui_config.threhold > -60:
indata = np.append(self.rms_buffer, indata)
rms = librosa.feature.rms(
y=indata, frame_length=4 * self.zc, hop_length=self.zc
)[:, 2:]
self.rms_buffer[:] = indata[-4 * self.zc :]
indata = indata[2 * self.zc - self.zc // 2 :]
db_threhold = (
librosa.amplitude_to_db(rms, ref=1.0)[0] < self.gui_config.threhold
)
for i in range(db_threhold.shape[0]):
if db_threhold[i]:
indata[i * self.zc : (i + 1) * self.zc] = 0
indata = indata[self.zc // 2 :]
self.input_wav[: -self.block_frame] = self.input_wav[
self.block_frame :
].clone()
self.input_wav[-indata.shape[0] :] = torch.from_numpy(indata).to(
self.config.device
)
self.input_wav_res[: -self.block_frame_16k] = self.input_wav_res[
self.block_frame_16k :
].clone()
# Input noise reduction and resampling
if self.gui_config.I_noise_reduce:
self.input_wav_denoise[: -self.block_frame] = self.input_wav_denoise[
self.block_frame :
].clone()
input_wav = self.input_wav[-self.sola_buffer_frame - self.block_frame :]
input_wav = self.tg(
input_wav.unsqueeze(0), self.input_wav.unsqueeze(0)
).squeeze(0)
input_wav[: self.sola_buffer_frame] *= self.fade_in_window
input_wav[: self.sola_buffer_frame] += (
self.nr_buffer * self.fade_out_window
)
self.input_wav_denoise[-self.block_frame :] = input_wav[
: self.block_frame
]
self.nr_buffer[:] = input_wav[self.block_frame :]
self.input_wav_res[-self.block_frame_16k - 160 :] = self.resampler(
self.input_wav_denoise[-self.block_frame - 2 * self.zc :]
)[160:]
else:
self.input_wav_res[-160 * (indata.shape[0] // self.zc + 1) :] = (
self.resampler(self.input_wav[-indata.shape[0] - 2 * self.zc :])[160:]
)
# Infer
if self.function == "vc":
infer_wav = self.rvc.infer(
self.input_wav_res,
self.block_frame_16k,
self.skip_head,
self.return_length,
self.gui_config.f0method,
)
if self.resampler2 is not None:
infer_wav = self.resampler2(infer_wav)
elif self.gui_config.I_noise_reduce:
infer_wav = self.input_wav_denoise[self.extra_frame :].clone()
else:
infer_wav = self.input_wav[self.extra_frame :].clone()
# Output noise reduction
if self.gui_config.O_noise_reduce and self.function == "vc":
self.output_buffer[: -self.block_frame] = self.output_buffer[
self.block_frame :
].clone()
self.output_buffer[-self.block_frame :] = infer_wav[-self.block_frame :]
infer_wav = self.tg(
infer_wav.unsqueeze(0), self.output_buffer.unsqueeze(0)
).squeeze(0)
# Volume envelop mixing
if self.gui_config.rms_mix_rate < 1 and self.function == "vc":
if self.gui_config.I_noise_reduce:
input_wav = self.input_wav_denoise[self.extra_frame :]
else:
input_wav = self.input_wav[self.extra_frame :]
rms1 = librosa.feature.rms(
y=input_wav[: infer_wav.shape[0]].cpu().numpy(),
frame_length=4 * self.zc,
hop_length=self.zc,
)
rms1 = torch.from_numpy(rms1).to(self.config.device)
rms1 = F.interpolate(
rms1.unsqueeze(0),
size=infer_wav.shape[0] + 1,
mode="linear",
align_corners=True,
)[0, 0, :-1]
rms2 = librosa.feature.rms(
y=infer_wav[:].cpu().numpy(),
frame_length=4 * self.zc,
hop_length=self.zc,
)
rms2 = torch.from_numpy(rms2).to(self.config.device)
rms2 = F.interpolate(
rms2.unsqueeze(0),
size=infer_wav.shape[0] + 1,
mode="linear",
align_corners=True,
)[0, 0, :-1]
rms2 = torch.max(rms2, torch.zeros_like(rms2) + 1e-3)
infer_wav *= torch.pow(
rms1 / rms2, torch.tensor(1 - self.gui_config.rms_mix_rate)
)
# SOLA algorithm
conv_input = infer_wav[
None, None, : self.sola_buffer_frame + self.sola_search_frame
]
cor_nom = F.conv1d(conv_input, self.sola_buffer[None, None, :])
cor_den = torch.sqrt(
F.conv1d(
conv_input**2,
torch.ones(1, 1, self.sola_buffer_frame, device=self.config.device),
)
+ 1e-8
)
if sys.platform == "darwin":
_, sola_offset = torch.max(cor_nom[0, 0] / cor_den[0, 0])
sola_offset = sola_offset.item()
else:
sola_offset = torch.argmax(cor_nom[0, 0] / cor_den[0, 0])
printt("sola_offset = %d", int(sola_offset))
infer_wav = infer_wav[sola_offset:]
if "privateuseone" in str(self.config.device) or not self.gui_config.use_pv:
infer_wav[: self.sola_buffer_frame] *= self.fade_in_window
infer_wav[: self.sola_buffer_frame] += (
self.sola_buffer * self.fade_out_window
)
else:
infer_wav[: self.sola_buffer_frame] = phase_vocoder(
self.sola_buffer,
infer_wav[: self.sola_buffer_frame],
self.fade_out_window,
self.fade_in_window,
)
self.sola_buffer[:] = infer_wav[
self.block_frame : self.block_frame + self.sola_buffer_frame
]
outdata[:] = (
infer_wav[: self.block_frame]
.repeat(self.gui_config.channels, 1)
.t()
.cpu()
.numpy()
)
total_time = time.perf_counter() - start_time
if flag_vc:
self.infer_time_label.config(text=str(int(total_time * 1000)))
printt("Infer time: %.2f", total_time)
def start_vc_thread(self):
threading.Thread(target=self.start_vc, daemon=True).start()
def stop_vc_thread(self):
threading.Thread(target=self.stop_vc, daemon=True).start()
def event_loop(self):
self.root.protocol("WM_DELETE_WINDOW", self.on_close)
self.root.mainloop()
def on_close(self):
self.stop_vc()
self.root.destroy()
class Application:
def __init__(self):
self.root = Tk()
self.gui = GUI(self.root)
def run(self):
self.gui.event_loop()
if __name__ == "__main__":
app = Application()
app.run()
Ensure that all required libraries are installed. You can install any missing dependencies using pip. For example:
This Tkinter-based GUI provides a more straightforward and native Python interface for your application while maintaining all the functionalities of the original PySimpleGUI version. Feel free to adjust the layout, styles, and functionalities further to better suit your specific needs.