2024-06-27 19:32:34 +08:00
|
|
|
#api for 240604 release version by Xiaokai
|
2024-06-24 22:19:42 +08:00
|
|
|
import os
|
|
|
|
import sys
|
|
|
|
import json
|
|
|
|
import re
|
|
|
|
import time
|
|
|
|
import librosa
|
|
|
|
import torch
|
|
|
|
import numpy as np
|
|
|
|
import torch.nn.functional as F
|
|
|
|
import torchaudio.transforms as tat
|
|
|
|
import sounddevice as sd
|
|
|
|
from dotenv import load_dotenv
|
|
|
|
from fastapi import FastAPI, HTTPException
|
|
|
|
from pydantic import BaseModel
|
|
|
|
import threading
|
|
|
|
import uvicorn
|
2024-06-25 19:05:05 +08:00
|
|
|
import logging
|
2024-06-27 19:32:34 +08:00
|
|
|
from multiprocessing import Queue, Process, cpu_count, freeze_support
|
2024-06-24 22:19:42 +08:00
|
|
|
|
2024-06-25 19:05:05 +08:00
|
|
|
# Initialize the logger
|
|
|
|
logging.basicConfig(level=logging.INFO)
|
|
|
|
logger = logging.getLogger(__name__)
|
2024-06-24 22:19:42 +08:00
|
|
|
|
2024-06-25 19:05:05 +08:00
|
|
|
# Define FastAPI app
|
2024-06-24 22:19:42 +08:00
|
|
|
app = FastAPI()
|
|
|
|
|
|
|
|
class GUIConfig:
|
|
|
|
def __init__(self) -> None:
|
|
|
|
self.pth_path: str = ""
|
|
|
|
self.index_path: str = ""
|
|
|
|
self.pitch: int = 0
|
2024-06-27 19:32:34 +08:00
|
|
|
self.formant: float = 0.0
|
|
|
|
self.sr_type: str = "sr_model"
|
|
|
|
self.block_time: float = 0.25 # s
|
2024-06-24 22:19:42 +08:00
|
|
|
self.threhold: int = -60
|
|
|
|
self.crossfade_time: float = 0.05
|
|
|
|
self.extra_time: float = 2.5
|
2024-06-27 19:32:34 +08:00
|
|
|
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 = 4
|
|
|
|
self.f0method: str = "fcpe"
|
|
|
|
self.sg_input_device: str = ""
|
|
|
|
self.sg_output_device: str = ""
|
2024-06-24 22:19:42 +08:00
|
|
|
|
|
|
|
class ConfigData(BaseModel):
|
|
|
|
pth_path: str
|
|
|
|
index_path: str
|
|
|
|
sg_input_device: str
|
|
|
|
sg_output_device: str
|
|
|
|
threhold: int = -60
|
|
|
|
pitch: int = 0
|
2024-06-27 19:32:34 +08:00
|
|
|
formant: float = 0.0
|
2024-06-24 22:19:42 +08:00
|
|
|
index_rate: float = 0.3
|
|
|
|
rms_mix_rate: float = 0.0
|
|
|
|
block_time: float = 0.25
|
|
|
|
crossfade_length: float = 0.05
|
|
|
|
extra_time: float = 2.5
|
|
|
|
n_cpu: int = 4
|
|
|
|
I_noise_reduce: bool = False
|
|
|
|
O_noise_reduce: bool = False
|
2024-06-27 19:32:34 +08:00
|
|
|
use_pv: bool = False
|
|
|
|
f0method: str = "fcpe"
|
|
|
|
|
|
|
|
class Harvest(Process):
|
|
|
|
def __init__(self, inp_q, opt_q):
|
|
|
|
super(Harvest, self).__init__()
|
|
|
|
self.inp_q = inp_q
|
|
|
|
self.opt_q = opt_q
|
|
|
|
|
|
|
|
def run(self):
|
|
|
|
import numpy as np
|
|
|
|
import pyworld
|
|
|
|
while True:
|
|
|
|
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)
|
2024-06-24 22:19:42 +08:00
|
|
|
|
|
|
|
class AudioAPI:
|
|
|
|
def __init__(self) -> None:
|
|
|
|
self.gui_config = GUIConfig()
|
2024-06-25 19:05:05 +08:00
|
|
|
self.config = None # Initialize Config object as None
|
2024-06-24 22:19:42 +08:00
|
|
|
self.flag_vc = False
|
|
|
|
self.function = "vc"
|
|
|
|
self.delay_time = 0
|
2024-06-25 19:05:05 +08:00
|
|
|
self.rvc = None # Initialize RVC object as None
|
2024-06-27 19:32:34 +08:00
|
|
|
self.inp_q = None
|
|
|
|
self.opt_q = None
|
|
|
|
self.n_cpu = min(cpu_count(), 8)
|
|
|
|
|
|
|
|
def initialize_queues(self):
|
|
|
|
self.inp_q = Queue()
|
|
|
|
self.opt_q = Queue()
|
|
|
|
for _ in range(self.n_cpu):
|
|
|
|
p = Harvest(self.inp_q, self.opt_q)
|
|
|
|
p.daemon = True
|
|
|
|
p.start()
|
2024-06-24 22:19:42 +08:00
|
|
|
|
|
|
|
def load(self):
|
|
|
|
input_devices, output_devices, _, _ = self.get_devices()
|
|
|
|
try:
|
2024-06-25 19:05:05 +08:00
|
|
|
with open("configs/config.json", "r", encoding='utf-8') as j:
|
2024-06-24 22:19:42 +08:00
|
|
|
data = json.load(j)
|
|
|
|
if data["sg_input_device"] not in input_devices:
|
|
|
|
data["sg_input_device"] = input_devices[sd.default.device[0]]
|
|
|
|
if data["sg_output_device"] not in output_devices:
|
|
|
|
data["sg_output_device"] = output_devices[sd.default.device[1]]
|
2024-06-25 19:05:05 +08:00
|
|
|
except Exception as e:
|
|
|
|
logger.error(f"Failed to load configuration: {e}")
|
|
|
|
with open("configs/config.json", "w", encoding='utf-8') as j:
|
2024-06-24 22:19:42 +08:00
|
|
|
data = {
|
2024-06-27 19:32:34 +08:00
|
|
|
"pth_path": "",
|
|
|
|
"index_path": "",
|
2024-06-24 22:19:42 +08:00
|
|
|
"sg_input_device": input_devices[sd.default.device[0]],
|
|
|
|
"sg_output_device": output_devices[sd.default.device[1]],
|
2024-06-27 19:32:34 +08:00
|
|
|
"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": "fcpe",
|
2024-06-24 22:19:42 +08:00
|
|
|
"use_jit": False,
|
2024-06-27 19:32:34 +08:00
|
|
|
"use_pv": False,
|
2024-06-24 22:19:42 +08:00
|
|
|
}
|
2024-06-25 19:05:05 +08:00
|
|
|
json.dump(data, j, ensure_ascii=False)
|
2024-06-24 22:19:42 +08:00
|
|
|
return data
|
|
|
|
|
|
|
|
def set_values(self, values):
|
2024-06-25 19:05:05 +08:00
|
|
|
logger.info(f"Setting values: {values}")
|
|
|
|
if not values.pth_path.strip():
|
2024-06-24 22:19:42 +08:00
|
|
|
raise HTTPException(status_code=400, detail="Please select a .pth file")
|
2024-06-25 19:05:05 +08:00
|
|
|
if not values.index_path.strip():
|
2024-06-24 22:19:42 +08:00
|
|
|
raise HTTPException(status_code=400, detail="Please select an index file")
|
|
|
|
self.set_devices(values.sg_input_device, values.sg_output_device)
|
|
|
|
self.config.use_jit = False
|
|
|
|
self.gui_config.pth_path = values.pth_path
|
|
|
|
self.gui_config.index_path = values.index_path
|
|
|
|
self.gui_config.threhold = values.threhold
|
|
|
|
self.gui_config.pitch = values.pitch
|
2024-06-27 19:32:34 +08:00
|
|
|
self.gui_config.formant = values.formant
|
2024-06-24 22:19:42 +08:00
|
|
|
self.gui_config.block_time = values.block_time
|
|
|
|
self.gui_config.crossfade_time = values.crossfade_length
|
|
|
|
self.gui_config.extra_time = values.extra_time
|
|
|
|
self.gui_config.I_noise_reduce = values.I_noise_reduce
|
|
|
|
self.gui_config.O_noise_reduce = values.O_noise_reduce
|
|
|
|
self.gui_config.rms_mix_rate = values.rms_mix_rate
|
|
|
|
self.gui_config.index_rate = values.index_rate
|
|
|
|
self.gui_config.n_cpu = values.n_cpu
|
2024-06-27 19:32:34 +08:00
|
|
|
self.gui_config.use_pv = values.use_pv
|
|
|
|
self.gui_config.f0method = values.f0method
|
2024-06-24 22:19:42 +08:00
|
|
|
return True
|
|
|
|
|
|
|
|
def start_vc(self):
|
|
|
|
torch.cuda.empty_cache()
|
|
|
|
self.flag_vc = True
|
|
|
|
self.rvc = rvc_for_realtime.RVC(
|
|
|
|
self.gui_config.pitch,
|
|
|
|
self.gui_config.pth_path,
|
|
|
|
self.gui_config.index_path,
|
|
|
|
self.gui_config.index_rate,
|
2024-06-27 19:32:34 +08:00
|
|
|
self.gui_config.n_cpu,
|
|
|
|
self.inp_q,
|
|
|
|
self.opt_q,
|
2024-06-24 22:19:42 +08:00
|
|
|
self.config,
|
2024-06-25 19:05:05 +08:00
|
|
|
self.rvc if self.rvc else None,
|
2024-06-24 22:19:42 +08:00
|
|
|
)
|
2024-06-27 19:32:34 +08:00
|
|
|
self.gui_config.samplerate = (
|
|
|
|
self.rvc.tgt_sr
|
|
|
|
if self.gui_config.sr_type == "sr_model"
|
|
|
|
else self.get_device_samplerate()
|
|
|
|
)
|
|
|
|
self.zc = self.gui_config.samplerate // 100
|
2024-06-24 22:19:42 +08:00
|
|
|
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
|
|
|
|
)
|
2024-06-27 19:32:34 +08:00
|
|
|
self.sola_buffer_frame = min(self.crossfade_frame, 4 * self.zc)
|
2024-06-24 22:19:42 +08:00
|
|
|
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.zeros(
|
2024-06-27 19:32:34 +08:00
|
|
|
self.extra_frame
|
|
|
|
+ self.crossfade_frame
|
|
|
|
+ self.sola_search_frame
|
|
|
|
+ self.block_frame,
|
2024-06-24 22:19:42 +08:00
|
|
|
device=self.config.device,
|
|
|
|
dtype=torch.float32,
|
|
|
|
)
|
2024-06-27 19:32:34 +08:00
|
|
|
self.input_wav_denoise = self.input_wav.clone()
|
2024-06-24 22:19:42 +08:00
|
|
|
self.input_wav_res = torch.zeros(
|
|
|
|
160 * self.input_wav.shape[0] // self.zc,
|
|
|
|
device=self.config.device,
|
|
|
|
dtype=torch.float32,
|
|
|
|
)
|
2024-06-27 19:32:34 +08:00
|
|
|
self.rms_buffer = np.zeros(4 * self.zc, dtype="float32")
|
|
|
|
self.sola_buffer = torch.zeros(
|
|
|
|
self.sola_buffer_frame, device=self.config.device, dtype=torch.float32
|
|
|
|
)
|
2024-06-24 22:19:42 +08:00
|
|
|
self.nr_buffer = self.sola_buffer.clone()
|
|
|
|
self.output_buffer = self.input_wav.clone()
|
2024-06-27 19:32:34 +08:00
|
|
|
self.skip_head = self.extra_frame // self.zc
|
|
|
|
self.return_length = (
|
|
|
|
self.block_frame + self.sola_buffer_frame + self.sola_search_frame
|
|
|
|
) // self.zc
|
2024-06-24 22:19:42 +08:00
|
|
|
self.fade_in_window = (
|
2024-06-27 19:32:34 +08:00
|
|
|
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
|
2024-06-24 22:19:42 +08:00
|
|
|
)
|
|
|
|
self.fade_out_window = 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)
|
2024-06-27 19:32:34 +08:00
|
|
|
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
|
2024-06-24 22:19:42 +08:00
|
|
|
self.tg = TorchGate(
|
|
|
|
sr=self.gui_config.samplerate, n_fft=4 * self.zc, prop_decrease=0.9
|
|
|
|
).to(self.config.device)
|
|
|
|
thread_vc = threading.Thread(target=self.soundinput)
|
|
|
|
thread_vc.start()
|
|
|
|
|
|
|
|
def soundinput(self):
|
|
|
|
channels = 1 if sys.platform == "darwin" else 2
|
|
|
|
with sd.Stream(
|
|
|
|
channels=channels,
|
|
|
|
callback=self.audio_callback,
|
|
|
|
blocksize=self.block_frame,
|
|
|
|
samplerate=self.gui_config.samplerate,
|
|
|
|
dtype="float32",
|
|
|
|
) as stream:
|
|
|
|
global stream_latency
|
|
|
|
stream_latency = stream.latency[-1]
|
|
|
|
while self.flag_vc:
|
|
|
|
time.sleep(self.gui_config.block_time)
|
2024-06-25 19:05:05 +08:00
|
|
|
logger.info("Audio block passed.")
|
|
|
|
logger.info("Ending VC")
|
2024-06-24 22:19:42 +08:00
|
|
|
|
|
|
|
def audio_callback(self, indata: np.ndarray, outdata: np.ndarray, frames, times, status):
|
|
|
|
start_time = time.perf_counter()
|
|
|
|
indata = librosa.to_mono(indata.T)
|
|
|
|
if self.gui_config.threhold > -60:
|
2024-06-27 19:32:34 +08:00
|
|
|
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
|
|
|
|
)
|
2024-06-24 22:19:42 +08:00
|
|
|
for i in range(db_threhold.shape[0]):
|
|
|
|
if db_threhold[i]:
|
|
|
|
indata[i * self.zc : (i + 1) * self.zc] = 0
|
2024-06-27 19:32:34 +08:00
|
|
|
indata = indata[self.zc // 2 :]
|
2024-06-24 22:19:42 +08:00
|
|
|
self.input_wav[: -self.block_frame] = self.input_wav[self.block_frame :].clone()
|
2024-06-27 19:32:34 +08:00
|
|
|
self.input_wav[-indata.shape[0] :] = torch.from_numpy(indata).to(self.config.device)
|
2024-06-24 22:19:42 +08:00
|
|
|
self.input_wav_res[: -self.block_frame_16k] = self.input_wav_res[self.block_frame_16k :].clone()
|
2024-06-27 19:32:34 +08:00
|
|
|
# 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:]
|
2024-06-24 22:19:42 +08:00
|
|
|
else:
|
2024-06-27 19:32:34 +08:00
|
|
|
self.input_wav_res[-160 * (indata.shape[0] // self.zc + 1) :] = (
|
|
|
|
self.resampler(self.input_wav[-indata.shape[0] - 2 * self.zc :])[160:]
|
|
|
|
)
|
|
|
|
# infer
|
2024-06-24 22:19:42 +08:00
|
|
|
if self.function == "vc":
|
|
|
|
infer_wav = self.rvc.infer(
|
|
|
|
self.input_wav_res,
|
|
|
|
self.block_frame_16k,
|
2024-06-27 19:32:34 +08:00
|
|
|
self.skip_head,
|
|
|
|
self.return_length,
|
2024-06-24 22:19:42 +08:00
|
|
|
self.gui_config.f0method,
|
|
|
|
)
|
2024-06-27 19:32:34 +08:00
|
|
|
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()
|
2024-06-24 22:19:42 +08:00
|
|
|
else:
|
2024-06-27 19:32:34 +08:00
|
|
|
infer_wav = self.input_wav[self.extra_frame :].clone()
|
|
|
|
# output noise reduction
|
|
|
|
if self.gui_config.O_noise_reduce and self.function == "vc":
|
2024-06-24 22:19:42 +08:00
|
|
|
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)
|
2024-06-27 19:32:34 +08:00
|
|
|
# volume envelop mixing
|
2024-06-24 22:19:42 +08:00
|
|
|
if self.gui_config.rms_mix_rate < 1 and self.function == "vc":
|
2024-06-27 19:32:34 +08:00
|
|
|
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,
|
|
|
|
)
|
2024-06-24 22:19:42 +08:00
|
|
|
rms1 = torch.from_numpy(rms1).to(self.config.device)
|
2024-06-27 19:32:34 +08:00
|
|
|
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,
|
|
|
|
)
|
2024-06-24 22:19:42 +08:00
|
|
|
rms2 = torch.from_numpy(rms2).to(self.config.device)
|
2024-06-27 19:32:34 +08:00
|
|
|
rms2 = F.interpolate(
|
|
|
|
rms2.unsqueeze(0),
|
|
|
|
size=infer_wav.shape[0] + 1,
|
|
|
|
mode="linear",
|
|
|
|
align_corners=True,
|
|
|
|
)[0, 0, :-1]
|
2024-06-24 22:19:42 +08:00
|
|
|
rms2 = torch.max(rms2, torch.zeros_like(rms2) + 1e-3)
|
2024-06-27 19:32:34 +08:00
|
|
|
infer_wav *= torch.pow(
|
|
|
|
rms1 / rms2, torch.tensor(1 - self.gui_config.rms_mix_rate)
|
|
|
|
)
|
|
|
|
# SOLA algorithm from https://github.com/yxlllc/DDSP-SVC
|
|
|
|
conv_input = infer_wav[None, None, : self.sola_buffer_frame + self.sola_search_frame]
|
2024-06-24 22:19:42 +08:00
|
|
|
cor_nom = F.conv1d(conv_input, self.sola_buffer[None, None, :])
|
2024-06-27 19:32:34 +08:00
|
|
|
cor_den = torch.sqrt(
|
|
|
|
F.conv1d(
|
|
|
|
conv_input**2,
|
|
|
|
torch.ones(1, 1, self.sola_buffer_frame, device=self.config.device),
|
|
|
|
)
|
|
|
|
+ 1e-8
|
|
|
|
)
|
2024-06-24 22:19:42 +08:00
|
|
|
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])
|
2024-06-25 19:05:05 +08:00
|
|
|
logger.info(f"sola_offset = {sola_offset}")
|
2024-06-27 19:32:34 +08:00
|
|
|
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
|
|
|
|
]
|
2024-06-24 22:19:42 +08:00
|
|
|
if sys.platform == "darwin":
|
2024-06-27 19:32:34 +08:00
|
|
|
outdata[:] = infer_wav[: self.block_frame].cpu().numpy()[:, np.newaxis]
|
2024-06-24 22:19:42 +08:00
|
|
|
else:
|
2024-06-27 19:32:34 +08:00
|
|
|
outdata[:] = infer_wav[: self.block_frame].repeat(2, 1).t().cpu().numpy()
|
2024-06-24 22:19:42 +08:00
|
|
|
total_time = time.perf_counter() - start_time
|
2024-06-25 19:05:05 +08:00
|
|
|
logger.info(f"Infer time: {total_time:.2f}")
|
2024-06-24 22:19:42 +08:00
|
|
|
|
|
|
|
def get_devices(self, update: bool = True):
|
|
|
|
if update:
|
|
|
|
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"]
|
|
|
|
input_devices = [
|
|
|
|
f"{d['name']} ({d['hostapi_name']})"
|
|
|
|
for d in devices
|
|
|
|
if d["max_input_channels"] > 0
|
|
|
|
]
|
|
|
|
output_devices = [
|
|
|
|
f"{d['name']} ({d['hostapi_name']})"
|
|
|
|
for d in devices
|
|
|
|
if d["max_output_channels"] > 0
|
|
|
|
]
|
|
|
|
input_devices_indices = [
|
|
|
|
d["index"] if "index" in d else d["name"]
|
|
|
|
for d in devices
|
|
|
|
if d["max_input_channels"] > 0
|
|
|
|
]
|
|
|
|
output_devices_indices = [
|
|
|
|
d["index"] if "index" in d else d["name"]
|
|
|
|
for d in devices
|
|
|
|
if d["max_output_channels"] > 0
|
|
|
|
]
|
|
|
|
return (
|
|
|
|
input_devices,
|
|
|
|
output_devices,
|
|
|
|
input_devices_indices,
|
|
|
|
output_devices_indices,
|
|
|
|
)
|
|
|
|
|
|
|
|
def set_devices(self, input_device, output_device):
|
|
|
|
(
|
|
|
|
input_devices,
|
|
|
|
output_devices,
|
|
|
|
input_device_indices,
|
|
|
|
output_device_indices,
|
|
|
|
) = self.get_devices()
|
2024-06-25 19:05:05 +08:00
|
|
|
logger.debug(f"Available input devices: {input_devices}")
|
|
|
|
logger.debug(f"Available output devices: {output_devices}")
|
|
|
|
logger.debug(f"Selected input device: {input_device}")
|
|
|
|
logger.debug(f"Selected output device: {output_device}")
|
|
|
|
|
|
|
|
if input_device not in input_devices:
|
|
|
|
logger.error(f"Input device '{input_device}' is not in the list of available devices")
|
|
|
|
raise HTTPException(status_code=400, detail=f"Input device '{input_device}' is not available")
|
|
|
|
|
|
|
|
if output_device not in output_devices:
|
|
|
|
logger.error(f"Output device '{output_device}' is not in the list of available devices")
|
|
|
|
raise HTTPException(status_code=400, detail=f"Output device '{output_device}' is not available")
|
|
|
|
|
2024-06-24 22:19:42 +08:00
|
|
|
sd.default.device[0] = input_device_indices[input_devices.index(input_device)]
|
|
|
|
sd.default.device[1] = output_device_indices[output_devices.index(output_device)]
|
2024-06-25 19:05:05 +08:00
|
|
|
logger.info(f"Input device set to {sd.default.device[0]}: {input_device}")
|
|
|
|
logger.info(f"Output device set to {sd.default.device[1]}: {output_device}")
|
2024-06-24 22:19:42 +08:00
|
|
|
|
|
|
|
audio_api = AudioAPI()
|
|
|
|
|
2024-06-25 19:05:05 +08:00
|
|
|
@app.get("/inputDevices", response_model=list)
|
2024-06-24 22:19:42 +08:00
|
|
|
def get_input_devices():
|
2024-06-25 19:05:05 +08:00
|
|
|
try:
|
|
|
|
input_devices, _, _, _ = audio_api.get_devices()
|
|
|
|
return input_devices
|
|
|
|
except Exception as e:
|
|
|
|
logger.error(f"Failed to get input devices: {e}")
|
|
|
|
raise HTTPException(status_code=500, detail="Failed to get input devices")
|
2024-06-24 22:19:42 +08:00
|
|
|
|
2024-06-25 19:05:05 +08:00
|
|
|
@app.get("/outputDevices", response_model=list)
|
2024-06-24 22:19:42 +08:00
|
|
|
def get_output_devices():
|
2024-06-25 19:05:05 +08:00
|
|
|
try:
|
|
|
|
_, output_devices, _, _ = audio_api.get_devices()
|
|
|
|
return output_devices
|
|
|
|
except Exception as e:
|
|
|
|
logger.error(f"Failed to get output devices: {e}")
|
|
|
|
raise HTTPException(status_code=500, detail="Failed to get output devices")
|
2024-06-24 22:19:42 +08:00
|
|
|
|
|
|
|
@app.post("/config")
|
|
|
|
def configure_audio(config_data: ConfigData):
|
|
|
|
try:
|
2024-06-25 19:05:05 +08:00
|
|
|
logger.info(f"Configuring audio with data: {config_data}")
|
2024-06-24 22:19:42 +08:00
|
|
|
if audio_api.set_values(config_data):
|
|
|
|
settings = config_data.dict()
|
|
|
|
settings["use_jit"] = False
|
2024-06-25 19:05:05 +08:00
|
|
|
with open("configs/config.json", "w", encoding='utf-8') as j:
|
|
|
|
json.dump(settings, j, ensure_ascii=False)
|
|
|
|
logger.info("Configuration set successfully")
|
2024-06-24 22:19:42 +08:00
|
|
|
return {"message": "Configuration set successfully"}
|
2024-06-25 19:05:05 +08:00
|
|
|
except HTTPException as e:
|
|
|
|
logger.error(f"Configuration error: {e.detail}")
|
|
|
|
raise
|
2024-06-24 22:19:42 +08:00
|
|
|
except Exception as e:
|
2024-06-25 19:05:05 +08:00
|
|
|
logger.error(f"Configuration failed: {e}")
|
2024-06-24 22:19:42 +08:00
|
|
|
raise HTTPException(status_code=400, detail=f"Configuration failed: {e}")
|
|
|
|
|
|
|
|
@app.post("/start")
|
|
|
|
def start_conversion():
|
|
|
|
try:
|
|
|
|
if not audio_api.flag_vc:
|
|
|
|
audio_api.start_vc()
|
|
|
|
return {"message": "Audio conversion started"}
|
|
|
|
else:
|
2024-06-25 19:05:05 +08:00
|
|
|
logger.warning("Audio conversion already running")
|
2024-06-24 22:19:42 +08:00
|
|
|
raise HTTPException(status_code=400, detail="Audio conversion already running")
|
2024-06-25 19:05:05 +08:00
|
|
|
except HTTPException as e:
|
|
|
|
logger.error(f"Start conversion error: {e.detail}")
|
|
|
|
raise
|
2024-06-24 22:19:42 +08:00
|
|
|
except Exception as e:
|
2024-06-25 19:05:05 +08:00
|
|
|
logger.error(f"Failed to start conversion: {e}")
|
2024-06-27 19:32:34 +08:00
|
|
|
raise HTTPException(status_code=500, detail="Failed to start conversion: {e}")
|
2024-06-24 22:19:42 +08:00
|
|
|
|
|
|
|
@app.post("/stop")
|
|
|
|
def stop_conversion():
|
|
|
|
try:
|
|
|
|
if audio_api.flag_vc:
|
|
|
|
audio_api.flag_vc = False
|
|
|
|
global stream_latency
|
|
|
|
stream_latency = -1
|
|
|
|
return {"message": "Audio conversion stopped"}
|
|
|
|
else:
|
2024-06-25 19:05:05 +08:00
|
|
|
logger.warning("Audio conversion not running")
|
2024-06-24 22:19:42 +08:00
|
|
|
raise HTTPException(status_code=400, detail="Audio conversion not running")
|
2024-06-25 19:05:05 +08:00
|
|
|
except HTTPException as e:
|
|
|
|
logger.error(f"Stop conversion error: {e.detail}")
|
|
|
|
raise
|
2024-06-24 22:19:42 +08:00
|
|
|
except Exception as e:
|
2024-06-25 19:05:05 +08:00
|
|
|
logger.error(f"Failed to stop conversion: {e}")
|
2024-06-27 19:32:34 +08:00
|
|
|
raise HTTPException(status_code=500, detail="Failed to stop conversion: {e}")
|
2024-06-24 22:19:42 +08:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2024-06-25 19:05:05 +08:00
|
|
|
if sys.platform == "win32":
|
|
|
|
freeze_support()
|
|
|
|
load_dotenv()
|
|
|
|
os.environ["OMP_NUM_THREADS"] = "4"
|
|
|
|
if sys.platform == "darwin":
|
|
|
|
os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
|
|
|
|
from tools.torchgate import TorchGate
|
|
|
|
import tools.rvc_for_realtime as rvc_for_realtime
|
|
|
|
from configs.config import Config
|
|
|
|
audio_api.config = Config()
|
2024-06-27 19:32:34 +08:00
|
|
|
audio_api.initialize_queues()
|
2024-06-25 19:05:05 +08:00
|
|
|
uvicorn.run(app, host="0.0.0.0", port=6242)
|