forked from maum-ai/assem-vc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
inference-colab.py
196 lines (143 loc) · 6.3 KB
/
inference-colab.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# -*- coding: utf-8 -*-
"""Assem_VC_Inference_Example.ipynb のコピー
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1ouxKWGGuBp77GVQj0a9lEI-kh-iHqJYo
# Inference Example for Assem-VC
This script shows the example usage of pre-trained Assem-VC and HiFi-GAN.
---
"Assem-VC: Realistic Voice Conversion by Assembling Modern Speech Synthesis Techniques"
Author: Kang-wook Kim, Seung-won Park, Myun-chul Joe @ MINDsLab Inc., SNU
Paper: https://arxiv.org/abs/2104.00931
Audio Samples: https://mindslab-ai.github.io/assem-vc
GitHub: https://github.com/mindslab-ai/assem-vc
"""
# Check GPU being used.
"""## Import requirements"""
# Commented out IPython magic to ensure Python compatibility.
import matplotlib
import matplotlib.pyplot as plt
#import IPython.display as ipd
import gdown
import sys
sys.path.append('hifi-gan/')
import os
import numpy as np
import json
import librosa
import torch
import random
from omegaconf import OmegaConf
from attrdict import AttrDict
import soundfile as sf
from synthesizer import Synthesizer
from datasets import TextMelDataset, text_mel_collate
from models import Generator
from meldataset import MAX_WAV_VALUE
# %matplotlib inline
def plot_mel_f0_alignment(mel_source, mel_outputs_postnet, f0s, alignments, figsize=(16, 16)):
fig, axes = plt.subplots(4, 1, figsize=figsize)
axes = axes.flatten()
axes[0].imshow(mel_source, aspect='auto', origin='lower', interpolation='none')
axes[1].imshow(mel_outputs_postnet, aspect='auto', origin='lower', interpolation='none')
axes[2].scatter(range(len(f0s)), f0s, alpha=0.5, color='red', marker='.', s=100)
axes[2].set_xlim(0, len(f0s))
axes[3].imshow(alignments, aspect='auto', origin='lower', interpolation='none')
axes[0].set_title("Source Mel")
axes[1].set_title("Predicted Mel")
axes[2].set_title("Source pitch contour")
axes[3].set_title("Source rhythm")
plt.tight_layout()
"""## Download pre-trained weights and config files
The pre-trained decoder file also contains the cotatron by itself.
"""
#gdown.download('https://drive.google.com/uc?id=1gt_rLVw83-FMtvTv6PJ5hdqZQRiyaQnh', 'config/global/config.yaml', quiet=False)
#gdown.download('https://drive.google.com/uc?id=1kKwchYCAB1A67ELI1LQcpjrYFnSmiPYS', 'config/vc/config.yaml', quiet=False)
#gdown.download('https://drive.google.com/uc?id=1ZadibQMbbnYmsB5rG68de2fKgVM0mtG6', 'config/cota/config.yaml', quiet=False)
#gdown.download('https://drive.google.com/uc?id=1dKN4knY0mSBKWZqjP_sX8W_EJSV-7bNP', 'f0s.txt', quiet=False)
#gdown.download('https://drive.google.com/uc?id=1k2uJBh3FEK38pCdH38-MaXpgJFb5sEk6', 'pretrained_decoder.ckpt', quiet=False)
#gdown.download('https://drive.google.com/uc?id=1Q1XCoY_SKno34dLLm1zNu6PtKuqumXYi', 'hifigan_vctk_g_2600000.ckpt', quiet=False)
"""## Load models from checkpoint
write down your paths below.
"""
vc_decoder_path = 'pretrained_decoder.ckpt' # path of vc decoder checkpoint
generator_path = 'hifigan_vctk_g_2600000.ckpt' # path of hifi-gan checkpoint
config_path = 'hifi-gan/config_v1.json' # path of hifi-gan's configuration
print("Loading Synthesizer's checkpoint...")
net=Synthesizer.load_from_checkpoint(vc_decoder_path).cuda().eval()
net.freeze()
hp =net.hp
print("Complete.")
with open(config_path) as f:
data = f.read()
json_config = json.loads(data)
h = AttrDict(json_config)
torch.manual_seed(h.seed)
generator = Generator(h).cuda().eval()
print("Loading Generator's checkpoint...")
state_dict_g = torch.load(generator_path, map_location='cpu')
generator.load_state_dict(state_dict_g['generator'])
generator.remove_weight_norm()
print("Complete.")
"""## Load source data
1. Add your custom source audios at datasets/inference_source
2. Add your audio's name and transcript at datasets/inference_source/metadata.txt
3. Change file_idx below and inference with that source audio
"""
target_root = 'datasets/inference_target'
target_dir = 'metadata_g2p.txt'
targetloader = TextMelDataset(hp, 'datasets/inference_source','metadata_g2p.txt',train=False, use_f0s = True)
dataloader = TextMelDataset(hp, target_root, target_dir, train=False, use_f0s = True)
print("length of the source metadata is : ",len(targetloader))
file_idx = 3 # 0 ~ len(source_metadata) - 1
audio_path, text,_ = targetloader.meta[file_idx]
x = targetloader.__getitem__(file_idx)
batch = text_mel_collate([x])
print(text)
x, sr = librosa.load(os.path.join('datasets/inference_source',audio_path))
#ipd.Audio(x, rate=hp.audio.sampling_rate)
"""## Define Speakers Set"""
speaker_list = list(hp.data.speakers)
print(speaker_list)
with open('f0s.txt', 'r', encoding='utf-8') as g:
pitches = g.readlines()
speaker_list_2 = [x.split('|')[0].strip() for x in pitches]
means = [float(x.split('|')[1].strip()) for x in pitches]
variences = [float(x.split('|')[2].strip()) for x in pitches]
if(speaker_list == speaker_list_2):
print('ok')
else:
print('error')
"""## Style Transfer (Rhythm and Pitch Contour)"""
file_idx = random.randrange(len(dataloader))
audio_path, _,_ = dataloader.meta[file_idx]
x = dataloader.__getitem__(file_idx)
target_batch = text_mel_collate([x])
x, sr = librosa.load(os.path.join(target_root,audio_path))
#ipd.Audio(x, rate=hp.audio.sampling_rate)
text, mel_source, speakers, f0_padded, input_lengths, output_lengths, max_input_len, _ = batch
_, mel_reference, _,_,_,_,_, _ = target_batch # get mel spectrogram of target
with torch.no_grad():
text=text.cuda()
mel_source = mel_source.cuda()
mel_reference = mel_reference.cuda()
f0_padded = f0_padded.cuda()
mel_predicted, alignment, residual = net.inference(text, mel_source, mel_reference, f0_padded)
print(text)
with torch.no_grad():
plot_mel_f0_alignment(mel_source.data.cpu().numpy()[0],
mel_predicted.data.cpu().numpy()[0],
f0_padded.cpu().numpy()[0, 0],
alignment.data.cpu().numpy()[0].T)
"""## Convert spectrogram to audio using vocoder"""
with torch.no_grad():
y_g_hat = generator(mel_predicted)
audio = y_g_hat.squeeze()
audio = audio * MAX_WAV_VALUE
audio = audio.detach().cpu().numpy().astype('int16')
#ipd.Audio(audio, rate=hp.audio.sampling_rate)
sf.write('converted.wav', audio, hp.audio.sampling_rate)
plt.figure(figsize=(16,4))
plt.title("Output waveform")
plt.plot(audio / MAX_WAV_VALUE)
plt.show()