Skip to content

Commit

Permalink
sync with applio
Browse files Browse the repository at this point in the history
  • Loading branch information
blaisewf committed Jul 30, 2024
1 parent ea0015b commit b567ee7
Show file tree
Hide file tree
Showing 25 changed files with 108 additions and 87 deletions.
13 changes: 7 additions & 6 deletions rvc/infer/infer.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING)
logging.getLogger("faiss").setLevel(logging.WARNING)


class VoiceConverter:
Expand Down Expand Up @@ -79,7 +80,7 @@ def remove_audio_noise(input_audio_path, reduction_strength=0.7):
)
return reduced_noise
except Exception as error:
print(f"Error cleaning audio: {error}")
print(f"An error occurred removing audio noise: {error}")
return None

@staticmethod
Expand Down Expand Up @@ -114,7 +115,7 @@ def convert_audio_format(input_path, output_path, output_format):
sf.write(output_path, audio, target_sr, format=output_format.lower())
return output_path
except Exception as error:
print(f"Failed to convert audio to {output_format} format: {error}")
print(f"An error occurred converting the audio format: {error}")

def convert_audio(
self,
Expand Down Expand Up @@ -233,15 +234,15 @@ def convert_audio(
split_audio=False,
f0_autotune=f0_autotune,
filter_radius=filter_radius,
export_format=export_format,
upscale_audio=upscale_audio,
embedder_model=embedder_model,
embedder_model_custom=embedder_model_custom,
clean_audio=clean_audio,
clean_strength=clean_strength,
export_format=export_format,
upscale_audio=upscale_audio,
)
except Exception as error:
print(f"Error in processing split audio segment: {error}")
print(f"An error occurred processing the segmented audio: {error}")
print(traceback.format_exc())
return f"Error {error}"
print("Finished processing segmented audio, now merging audio...")
Expand Down Expand Up @@ -299,7 +300,7 @@ def convert_audio(
)

except Exception as error:
print(f"Voice conversion failed: {error}")
print(f"An error occurred during audio conversion: {error}")
print(traceback.format_exc())

def get_vc(self, weight_root, sid):
Expand Down
9 changes: 6 additions & 3 deletions rvc/infer/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,17 @@
import librosa
import numpy as np
from scipy import signal
from functools import lru_cache
from torch import Tensor

now_dir = os.getcwd()
sys.path.append(now_dir)

from rvc.lib.predictors.RMVPE import RMVPE0Predictor
from rvc.lib.predictors.FCPE import FCPEF0Predictor

import logging

logging.getLogger("faiss").setLevel(logging.WARNING)

# Constants for high-pass filter
FILTER_ORDER = 5
Expand Down Expand Up @@ -541,7 +544,7 @@ def pipeline(
index = faiss.read_index(file_index)
big_npy = index.reconstruct_n(0, index.ntotal)
except Exception as error:
print(error)
print(f"An error occurred reading the FAISS index: {error}")
index = big_npy = None
else:
index = big_npy = None
Expand Down Expand Up @@ -576,7 +579,7 @@ def pipeline(
inp_f0.append([float(i) for i in line.split(",")])
inp_f0 = np.array(inp_f0, dtype="float32")
except Exception as error:
print(error)
print(f"An error occurred reading the F0 file: {error}")
sid = torch.tensor(sid, device=self.device).unsqueeze(0).long()
if pitch_guidance == True:
pitch, pitchf = self.get_f0(
Expand Down
2 changes: 1 addition & 1 deletion rvc/lib/predictors/FCPE.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def load_wav_to_torch(full_path, target_sr=None, return_empty_on_exception=False
try:
data, sampling_rate = sf.read(full_path, always_2d=True) # than soundfile.
except Exception as error:
print(f"'{full_path}' failed to load with {error}")
print(f"An error occurred loading {full_path}: {error}")
if return_empty_on_exception:
return [], sampling_rate or target_sr or 48000
else:
Expand Down
12 changes: 7 additions & 5 deletions rvc/lib/tools/model_download.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,9 @@ def download_from_url(url):
fuzzy=True,
)
except Exception as error:
error_message = str(error)
error_message = str(
f"An error occurred downloading the file: {error}"
)
if (
"Too many users have viewed or downloaded this file recently"
in error_message
Expand Down Expand Up @@ -132,8 +134,8 @@ def download_from_url(url):
else:
os.chdir(file_path)
return None
except Exception as e:
print(e)
except Exception as error:
print(f"An error occurred downloading the file: {error}")
os.chdir(file_path)
return None

Expand Down Expand Up @@ -238,7 +240,7 @@ def download_from_url(url):
wget.download(url)
except Exception as error:
os.chdir(now_dir)
print(error)
print(f"An error occurred downloading the file: {error}")
return None

for currentPath, _, zipFiles in os.walk(zips_path):
Expand All @@ -265,7 +267,7 @@ def extract_and_show_progress(zipfile_path, unzips_path):
os.remove(zipfile_path)
return True
except Exception as error:
print(error)
print(f"An error occurred extracting the zip file: {error}")
return False


Expand Down
2 changes: 1 addition & 1 deletion rvc/lib/tools/prerequisites_download.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def prequisites_download_pipeline(pretraineds_v1, pretraineds_v2, models, exe):
download_mapping_files(pretraineds_v2_list)

# Clear the console after all downloads are completed
clear_console()
clear_console()


def clear_console():
Expand Down
8 changes: 4 additions & 4 deletions rvc/lib/tools/split_audio.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ def process_audio(file_path):

return "Finish", new_dir_path

except Exception as e:
print(f"An error occurred: {e}")
except Exception as error:
print(f"An error occurred splitting the audio: {error}")
return "Error", None


Expand Down Expand Up @@ -103,5 +103,5 @@ def merge_audio(timestamps_file):
# print(f"Exported merged file: {merged_filename}\n")
return merged_audio.frame_rate, merged_audio_np

except Exception as e:
print(f"An error occurred: {e}")
except Exception as error:
print(f"An error occurred splitting the audio: {error}")
2 changes: 1 addition & 1 deletion rvc/lib/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def load_audio(file, sample_rate):
if sr != sample_rate:
audio = librosa.resample(audio, orig_sr=sr, target_sr=sample_rate)
except Exception as error:
raise RuntimeError(f"Failed to load audio: {error}")
raise RuntimeError(f"An error occurred loading the audio: {error}")

return audio.flatten()

Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
12 changes: 4 additions & 8 deletions rvc/train/data_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,7 @@ def get_audio(self, filename):
audio, sample_rate = load_wav_to_torch(filename)
if sample_rate != self.sample_rate:
raise ValueError(
"{} SR doesn't match target {} SR".format(
sample_rate, self.sample_rate
)
"{} SR doesn't match target {} SR".format(sample_rate, self.sample_rate)
)
audio_norm = audio
audio_norm = audio_norm.unsqueeze(0)
Expand All @@ -129,7 +127,7 @@ def get_audio(self, filename):
try:
spec = torch.load(spec_filename)
except Exception as error:
print(f"{spec_filename}: {error}")
print(f"An error occurred getting spec from {spec_filename}: {error}")
spec = spectrogram_torch(
audio_norm,
self.filter_length,
Expand Down Expand Up @@ -344,9 +342,7 @@ def get_audio(self, filename):
audio, sample_rate = load_wav_to_torch(filename)
if sample_rate != self.sample_rate:
raise ValueError(
"{} SR doesn't match target {} SR".format(
sample_rate, self.sample_rate
)
"{} SR doesn't match target {} SR".format(sample_rate, self.sample_rate)
)
audio_norm = audio
audio_norm = audio_norm.unsqueeze(0)
Expand All @@ -355,7 +351,7 @@ def get_audio(self, filename):
try:
spec = torch.load(spec_filename)
except Exception as error:
print(f"{spec_filename}: {error}")
print(f"An error occurred getting spec from {spec_filename}: {error}")
spec = spectrogram_torch(
audio_norm,
self.filter_length,
Expand Down
4 changes: 2 additions & 2 deletions rvc/train/extract/extract_f0_print.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def process_file(self, file_info):
coarse_pit = self.coarse_f0(feature_pit)
np.save(opt_path1, coarse_pit, allow_pickle=False)
except Exception as error:
print(f"F0 extraction failed for {inp_path}: {error}")
print(f"An error occurred extracting file {inp_path}: {error}")


if __name__ == "__main__":
Expand All @@ -124,7 +124,7 @@ def process_file(self, file_info):
input_path = os.path.join(input_root, name)
output_path1 = os.path.join(output_root1, name)
output_path2 = os.path.join(output_root2, name)
np_arr = load_audio(input_path, 16000) #self.fs?
np_arr = load_audio(input_path, 16000) # self.fs?
paths.append([input_path, output_path1, output_path2, np_arr])

print(f"Starting extraction with {num_processes} cores and {f0_method}...")
Expand Down
2 changes: 1 addition & 1 deletion rvc/train/extract/extract_feature_print.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def read_wave(wav_path, normalize=False):
print(f"{file} is invalid")
pbar.set_description(f"Processing {file} {feats.shape}")
except Exception as error:
print(error)
print(f"An error occurred processing {file}: {error}")
pbar.update(1)

elapsed_time = time.time() - start_time
Expand Down
4 changes: 3 additions & 1 deletion rvc/train/extract/preparing_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ def generate_config(rvc_version: str, sample_rate: int, model_path: str):
shutil.copyfile(config_path, config_save_path)


def generate_filelist(pitch_guidance: bool, model_path: str, rvc_version: str, sample_rate: int):
def generate_filelist(
pitch_guidance: bool, model_path: str, rvc_version: str, sample_rate: int
):
gt_wavs_dir = f"{model_path}/sliced_audios"
feature_dir = (
f"{model_path}/v1_extracted"
Expand Down
4 changes: 2 additions & 2 deletions rvc/train/preprocess/preprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def process_audio(self, path: str, idx0: int):
break
self.normalize_and_write(tmp_audio, idx0, idx1)
except Exception as error:
print(f"{path}: {error}")
print(f"An error occurred on {path} path: {error}")

def process_audio_multiprocessing(self, infos: List[Tuple[str, int]]):
for path, idx0 in infos:
Expand All @@ -119,7 +119,7 @@ def process_audio_multiprocessing_input_directory(
[infos[i::num_processes] for i in range(num_processes)],
)
except Exception as error:
print(error)
print(f"An error occurred on {input_root} path: {error}")


def preprocess_training_set(
Expand Down
2 changes: 1 addition & 1 deletion rvc/train/process/change_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ def change_info(path, info, name):
torch.save(ckpt, f"logs/{name}/{name}")
return "Success."
except Exception as error:
print(error)
print(f"An error occurred changing the info: {error}")
9 changes: 4 additions & 5 deletions rvc/train/process/extract_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,7 @@
print(f"Saved index file '{index_filepath_added}'")

except Exception as error:
print(f"Failed to train index: {error}")
if "one array to concatenate" in str(error):
print(
"If you are running this code in a virtual environment, make sure you have enough GPU available to generate the Index file."
)
print(f"An error occurred extracting the index: {error}")
print(
"If you are running this code in a virtual environment, make sure you have enough GPU available to generate the Index file."
)
11 changes: 8 additions & 3 deletions rvc/train/process/extract_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,15 @@ def replace_keys_in_dict(d, old_key_part, new_key_part):
def extract_model(ckpt, sr, pitch_guidance, name, model_dir, epoch, step, version, hps):
try:
print(f"Saved model '{model_dir}' (epoch {epoch} and step {step})")

model_dir_path = os.path.dirname(model_dir)
os.makedirs(model_dir_path, exist_ok=True)

pth_file = f"{name}_{epoch}e_{step}s.pth"
pth_file_old_version_path = os.path.join(
model_dir, f"{pth_file}_old_version.pth"
model_dir_path, f"{pth_file}_old_version.pth"
)

opt = OrderedDict(
weight={
key: value.half() for key, value in ckpt.items() if "enc_q" not in key
Expand Down Expand Up @@ -62,7 +67,7 @@ def extract_model(ckpt, sr, pitch_guidance, name, model_dir, epoch, step, versio
model_hash = hashlib.sha256(hash_input.encode()).hexdigest()
opt["model_hash"] = model_hash

torch.save(opt, model_dir)
torch.save(opt, os.path.join(model_dir_path, pth_file))

model = torch.load(model_dir, map_location=torch.device("cpu"))
torch.save(
Expand All @@ -79,4 +84,4 @@ def extract_model(ckpt, sr, pitch_guidance, name, model_dir, epoch, step, versio
os.rename(pth_file_old_version_path, model_dir)

except Exception as error:
print(error)
print(f"An error occurred extracting the model: {error}")
12 changes: 10 additions & 2 deletions rvc/train/process/extract_small_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,15 @@ def replace_keys_in_dict(d, old_key_part, new_key_part):
return updated_dict


def extract_small_model(path: str, name: str, sr: int, pitch_guidance: bool, version: str, epoch: int, step: int):
def extract_small_model(
path: str,
name: str,
sr: int,
pitch_guidance: bool,
version: str,
epoch: int,
step: int,
):
try:
ckpt = torch.load(path, map_location="cpu")
pth_file = f"{name}.pth"
Expand Down Expand Up @@ -172,4 +180,4 @@ def extract_small_model(path: str, name: str, sr: int, pitch_guidance: bool, ver
os.remove(pth_file_old_version_path)
os.rename(pth_file_old_version_path, pth_file)
except Exception as error:
print(error)
print(f"An error occurred extracting the model: {error}")
8 changes: 5 additions & 3 deletions rvc/train/process/model_blender.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import torch
from collections import OrderedDict


def extract(ckpt):
a = ckpt["model"]
opt = OrderedDict()
Expand All @@ -12,15 +13,16 @@ def extract(ckpt):
opt["weight"][key] = a[key]
return opt


def model_blender(name, path1, path2, ratio):
try:
message = f"Model {path1} and {path2} are merged with alpha {ratio}."
ckpt1 = torch.load(path1, map_location="cpu")
ckpt2 = torch.load(path2, map_location="cpu")

if ckpt1["sr"] != ckpt2["sr"]:
return "The sample rates of the two models are not the same."

cfg = ckpt1["config"]
cfg_f0 = ckpt1["f0"]
cfg_version = ckpt1["version"]
Expand Down Expand Up @@ -61,5 +63,5 @@ def model_blender(name, path1, path2, ratio):
print(message)
return message, os.path.join("logs", "%s.pth" % name)
except Exception as error:
print(error)
print(f"An error occurred blending the models: {error}")
return error
Loading

0 comments on commit b567ee7

Please sign in to comment.