voice-changer/server/voice_changer/MMVCv13/MMVCv13.py

302 lines
10 KiB
Python
Raw Normal View History

import sys
import os
2023-06-20 00:39:39 +03:00
from data.ModelSlot import MMVCv13ModelSlot
2023-08-05 06:33:31 +03:00
from voice_changer.VoiceChangerParamsManager import VoiceChangerParamsManager
2023-04-28 07:49:40 +03:00
2023-11-08 13:54:13 +03:00
from voice_changer.utils.VoiceChangerModel import AudioInOut, VoiceChangerModel
2023-04-28 07:49:40 +03:00
if sys.platform.startswith("darwin"):
baseDir = [x for x in sys.path if x.endswith("Contents/MacOS")]
if len(baseDir) != 1:
print("baseDir should be only one ", baseDir)
sys.exit()
modulePath = os.path.join(baseDir[0], "MMVC_Client_v13", "python")
sys.path.append(modulePath)
else:
2023-04-11 01:37:39 +03:00
modulePath = os.path.join("MMVC_Client_v13", "python")
sys.path.append(modulePath)
2023-04-10 18:21:17 +03:00
2023-04-28 07:49:40 +03:00
from dataclasses import dataclass, asdict, field
import numpy as np
import torch
import onnxruntime
2023-06-21 10:00:03 +03:00
# from symbols import symbols # type:ignore
# from models import SynthesizerTrn # type:ignore
from voice_changer.MMVCv13.models.models import SynthesizerTrn
from voice_changer.MMVCv13.models.symbols import symbols
2023-04-28 07:49:40 +03:00
from voice_changer.MMVCv13.TrainerFunctions import (
TextAudioSpeakerCollate,
spectrogram_torch,
load_checkpoint,
get_hparams_from_file,
)
2023-04-17 03:45:12 +03:00
from Exceptions import NoModeLoadedException
@dataclass
2023-04-28 07:49:40 +03:00
class MMVCv13Settings:
2023-07-23 13:39:52 +03:00
gpu: int = -9999
srcId: int = 0
dstId: int = 101
# ↓mutableな物だけ列挙
intData = ["gpu", "srcId", "dstId"]
2023-04-28 07:49:40 +03:00
floatData: list[str] = field(default_factory=lambda: [])
2023-06-21 10:00:03 +03:00
strData: list[str] = field(default_factory=lambda: [])
2023-11-08 13:54:13 +03:00
class MMVCv13(VoiceChangerModel):
2023-06-21 10:00:03 +03:00
def __init__(self, slotInfo: MMVCv13ModelSlot):
print("[Voice Changer] [MMVCv13] Creating instance ")
2023-11-08 13:54:13 +03:00
self.voiceChangerType = "MMVCv13"
2023-03-07 19:40:03 +03:00
self.settings = MMVCv13Settings()
self.net_g = None
self.onnx_session = None
self.gpu_num = torch.cuda.device_count()
2023-03-07 19:40:03 +03:00
self.text_norm = torch.LongTensor([0, 6, 0])
2023-06-21 10:00:03 +03:00
self.audio_buffer: AudioInOut | None = None
self.slotInfo = slotInfo
self.initialize()
2023-05-08 12:02:15 +03:00
2023-06-21 10:00:03 +03:00
def initialize(self):
print("[Voice Changer] [MMVCv13] Initializing... ")
2023-08-05 06:33:31 +03:00
vcparams = VoiceChangerParamsManager.get_instance().params
2023-11-08 13:54:13 +03:00
configPath = os.path.join(
vcparams.model_dir, str(self.slotInfo.slotIndex), self.slotInfo.configFile
)
modelPath = os.path.join(
vcparams.model_dir, str(self.slotInfo.slotIndex), self.slotInfo.modelFile
)
2023-08-05 06:33:31 +03:00
self.hps = get_hparams_from_file(configPath)
2023-06-21 10:00:03 +03:00
if self.slotInfo.isONNX:
2023-05-08 12:02:15 +03:00
providers, options = self.getOnnxExecutionProvider()
self.onnx_session = onnxruntime.InferenceSession(
2023-08-05 06:33:31 +03:00
modelPath,
2023-05-08 12:02:15 +03:00
providers=providers,
provider_options=options,
)
2023-06-21 10:00:03 +03:00
else:
2023-11-08 13:54:13 +03:00
self.net_g = SynthesizerTrn(
len(symbols),
self.hps.data.filter_length // 2 + 1,
self.hps.train.segment_size // self.hps.data.hop_length,
n_speakers=self.hps.data.n_speakers,
**self.hps.model
)
2023-06-21 10:00:03 +03:00
self.net_g.eval()
2023-08-05 06:33:31 +03:00
load_checkpoint(modelPath, self.net_g, None)
2023-06-21 10:00:03 +03:00
# その他の設定
self.settings.srcId = self.slotInfo.srcId
self.settings.dstId = self.slotInfo.dstId
print("[Voice Changer] [MMVCv13] Initializing... done")
2023-05-08 12:02:15 +03:00
def getOnnxExecutionProvider(self):
2023-05-29 11:34:35 +03:00
availableProviders = onnxruntime.get_available_providers()
2023-06-21 10:00:03 +03:00
devNum = torch.cuda.device_count()
2023-11-08 13:54:13 +03:00
if (
self.settings.gpu >= 0
and "CUDAExecutionProvider" in availableProviders
and devNum > 0
):
2023-05-08 12:02:15 +03:00
return ["CUDAExecutionProvider"], [{"device_id": self.settings.gpu}]
2023-05-29 11:34:35 +03:00
elif self.settings.gpu >= 0 and "DmlExecutionProvider" in availableProviders:
return ["DmlExecutionProvider"], [{}]
2023-05-08 12:02:15 +03:00
else:
return ["CPUExecutionProvider"], [
{
"intra_op_num_threads": 8,
"execution_mode": onnxruntime.ExecutionMode.ORT_PARALLEL,
"inter_op_num_threads": 8,
}
]
2023-04-28 07:49:40 +03:00
def update_settings(self, key: str, val: int | float | str):
2023-05-08 12:02:15 +03:00
if key in self.settings.intData:
2023-04-28 07:49:40 +03:00
val = int(val)
setattr(self.settings, key, val)
2023-05-08 12:02:15 +03:00
2023-06-21 10:00:03 +03:00
if key == "gpu" and self.slotInfo.isONNX:
2023-05-08 12:02:15 +03:00
providers, options = self.getOnnxExecutionProvider()
2023-08-05 06:33:31 +03:00
vcparams = VoiceChangerParamsManager.get_instance().params
2023-11-08 13:54:13 +03:00
modelPath = os.path.join(
vcparams.model_dir,
str(self.slotInfo.slotIndex),
self.slotInfo.modelFile,
)
2023-05-08 12:02:15 +03:00
self.onnx_session = onnxruntime.InferenceSession(
2023-08-05 06:33:31 +03:00
modelPath,
2023-05-08 12:02:15 +03:00
providers=providers,
provider_options=options,
)
# providers = self.onnx_session.get_providers()
# print("Providers:", providers)
# if "CUDAExecutionProvider" in providers:
# provider_options = [{"device_id": self.settings.gpu}]
# self.onnx_session.set_providers(
# providers=["CUDAExecutionProvider"],
# provider_options=provider_options,
# )
elif key in self.settings.floatData:
setattr(self.settings, key, float(val))
elif key in self.settings.strData:
setattr(self.settings, key, str(val))
else:
return False
return True
def get_info(self):
data = asdict(self.settings)
2023-11-08 13:54:13 +03:00
data["onnxExecutionProviders"] = (
self.onnx_session.get_providers() if self.onnx_session is not None else []
)
return data
def get_processing_sampling_rate(self):
2023-04-28 07:49:40 +03:00
if hasattr(self, "hps") is False:
2023-04-17 03:45:12 +03:00
raise NoModeLoadedException("config")
return self.hps.data.sampling_rate
2023-04-28 07:49:40 +03:00
def _get_spec(self, audio: AudioInOut):
spec = spectrogram_torch(
audio,
self.hps.data.filter_length,
self.hps.data.sampling_rate,
self.hps.data.hop_length,
self.hps.data.win_length,
center=False,
)
spec = torch.squeeze(spec, 0)
return spec
2023-04-28 07:49:40 +03:00
def generate_input(
self,
newData: AudioInOut,
inputSize: int,
crossfadeSize: int,
solaSearchFrame: int = 0,
):
2023-04-14 22:25:30 +03:00
newData = newData.astype(np.float32) / self.hps.data.max_wav_value
2023-04-28 07:49:40 +03:00
if self.audio_buffer is not None:
2023-11-08 13:54:13 +03:00
self.audio_buffer = np.concatenate(
[self.audio_buffer, newData], 0
) # 過去のデータに連結
2023-04-14 22:25:30 +03:00
else:
self.audio_buffer = newData
2023-04-14 22:58:56 +03:00
convertSize = inputSize + crossfadeSize + solaSearchFrame
2023-05-26 17:04:56 +03:00
# if convertSize < 8192:
# convertSize = 8192
if convertSize % self.hps.data.hop_length != 0: # モデルの出力のホップサイズで切り捨てが発生するので補う。
2023-11-08 13:54:13 +03:00
convertSize = convertSize + (
self.hps.data.hop_length - (convertSize % self.hps.data.hop_length)
)
2023-04-28 07:49:40 +03:00
convertOffset = -1 * convertSize
self.audio_buffer = self.audio_buffer[convertOffset:] # 変換対象の部分だけ抽出
2023-03-07 19:40:03 +03:00
audio = torch.FloatTensor(self.audio_buffer)
audio_norm = audio.unsqueeze(0) # unsqueeze
2023-03-07 19:40:03 +03:00
spec = self._get_spec(audio_norm)
sid = torch.LongTensor([int(self.settings.srcId)])
2023-03-07 19:40:03 +03:00
data = (self.text_norm, spec, audio_norm, sid)
data = TextAudioSpeakerCollate()([data])
return data
def _onnx_inference(self, data):
2023-06-21 10:00:03 +03:00
if self.onnx_session is None:
print("[Voice Changer] No ONNX session.")
2023-04-17 03:45:12 +03:00
raise NoModeLoadedException("ONNX")
2023-03-07 19:40:03 +03:00
x, x_lengths, spec, spec_lengths, y, y_lengths, sid_src = [x for x in data]
sid_tgt1 = torch.LongTensor([self.settings.dstId])
2023-03-07 19:40:03 +03:00
# if spec.size()[2] >= 8:
2023-04-28 07:49:40 +03:00
audio1 = (
self.onnx_session.run(
["audio"],
{
"specs": spec.numpy(),
"lengths": spec_lengths.numpy(),
"sid_src": sid_src.numpy(),
"sid_tgt": sid_tgt1.numpy(),
},
2023-11-08 13:54:13 +03:00
)[0][0, 0]
2023-04-28 07:49:40 +03:00
* self.hps.data.max_wav_value
)
return audio1
def _pyTorch_inference(self, data):
2023-04-28 07:49:40 +03:00
if hasattr(self, "net_g") is False or self.net_g is None:
print("[Voice Changer] No pyTorch session.")
2023-04-17 03:45:12 +03:00
raise NoModeLoadedException("pytorch")
if self.settings.gpu < 0 or self.gpu_num == 0:
dev = torch.device("cpu")
else:
dev = torch.device("cuda", index=self.settings.gpu)
with torch.no_grad():
2023-11-08 13:54:13 +03:00
x, x_lengths, spec, spec_lengths, y, y_lengths, sid_src = [
x.to(dev) for x in data
]
sid_target = torch.LongTensor([self.settings.dstId]).to(dev)
2023-11-08 13:54:13 +03:00
audio1 = (
self.net_g.to(dev)
.voice_conversion(
spec, spec_lengths, sid_src=sid_src, sid_tgt=sid_target
)[0, 0]
.data
* self.hps.data.max_wav_value
)
result = audio1.float().cpu().numpy()
2023-03-07 19:40:03 +03:00
return result
def inference(self, data):
2023-06-21 10:00:03 +03:00
if self.slotInfo.isONNX:
audio = self._onnx_inference(data)
else:
audio = self._pyTorch_inference(data)
return audio
2023-04-10 18:21:17 +03:00
def __del__(self):
del self.net_g
del self.onnx_session
2023-04-10 18:21:17 +03:00
remove_path = os.path.join("MMVC_Client_v13", "python")
2023-04-28 07:49:40 +03:00
sys.path = [x for x in sys.path if x.endswith(remove_path) is False]
2023-04-10 18:21:17 +03:00
for key in list(sys.modules):
val = sys.modules.get(key)
try:
file_path = val.__file__
2023-04-11 01:37:39 +03:00
if file_path.find(remove_path + os.path.sep) >= 0:
2023-05-30 20:26:16 +03:00
# print("remove", key, file_path)
2023-04-10 18:21:17 +03:00
sys.modules.pop(key)
2023-07-23 13:39:52 +03:00
except: # NOQA
2023-04-10 18:21:17 +03:00
pass
2023-08-05 06:33:31 +03:00
def get_model_current(self):
return [
{
"key": "srcId",
"val": self.settings.srcId,
},
{
"key": "dstId",
"val": self.settings.dstId,
2023-11-08 13:54:13 +03:00
},
2023-08-05 06:33:31 +03:00
]