File size: 8,009 Bytes
f3b4964
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c56240
555e118
f3b4964
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219

import os
from glob import glob
from loguru import logger
import soundfile as sf
import librosa
import gradio as gr

from huggingface_hub import hf_hub_download
import time
import torch
import yaml

from s3prl_vc.upstream.interface import get_upstream
from s3prl.nn import Featurizer
import s3prl_vc.models
from s3prl_vc.utils import read_hdf5
from s3prl_vc.vocoder import Vocoder


# ---------- Settings ----------
GPU_ID = '-1'
os.environ['CUDA_VISIBLE_DEVICES'] = GPU_ID
DEVICE = 'cuda' if GPU_ID != '-1' else 'cpu'

SERVER_PORT = 42208
SERVER_NAME = "0.0.0.0"
SSL_DIR = './keyble_ssl'

EXAMPLE_DIR = './examples'
en_examples = sorted(glob(os.path.join(EXAMPLE_DIR, "en", '*.wav')))
jp_examples = sorted(glob(os.path.join(EXAMPLE_DIR, "jp", '*.wav')))
zh_examples = sorted(glob(os.path.join(EXAMPLE_DIR, "zh", '*.wav')))

TRGSPKS = ["TEF1", "TEF2", "TEM1", "TEM2"]

ref_samples = {
    trgspk: sorted(glob(os.path.join("./ref_samples", trgspk, '*.wav')))
    for trgspk in TRGSPKS
}

# ---------- Logging ----------
logger.add('app.log', mode='a')
logger.info('============================= App restarted =============================')

# ---------- Download models ----------
logger.info('============================= Download models ===========================')

vocoder_paths = {
    "ckpt": hf_hub_download(repo_id="unilight/hifigan_vctk_plus_vcc2020", filename="checkpoint-2500000steps.pkl"),
    "config": hf_hub_download(repo_id="unilight/hifigan_vctk_plus_vcc2020", filename="config.yml"),
    "stats": hf_hub_download(repo_id="unilight/hifigan_vctk_plus_vcc2020", filename="stats.h5")
}

vc_model_paths = {
    trgspk: {
        "ckpt": hf_hub_download(repo_id="unilight/s3prl-vc-vcc2020", filename=f"{trgspk}/checkpoint-10000steps.pkl"), 
        "config": hf_hub_download(repo_id="unilight/s3prl-vc-vcc2020", filename=f"{trgspk}/config.yml"),
        "stats": hf_hub_download(repo_id="unilight/s3prl-vc-vcc2020", filename=f"{trgspk}/stats.h5"),
    } for trgspk in TRGSPKS
}

# ---------- Model ----------
vc_models = {}
for trgspk in TRGSPKS:
    logger.info(f'============================= Setting up model for {trgspk} =============')
    checkpoint_path = vc_model_paths[trgspk]["ckpt"]
    config_path = vc_model_paths[trgspk]["config"]
    stats_path = vc_model_paths[trgspk]["stats"]
    with open(config_path) as f:
        config = yaml.load(f, Loader=yaml.Loader)

    config["trg_stats"] = {
        "mean": torch.from_numpy(read_hdf5(stats_path, "mean")).float().to(DEVICE),
        "scale": torch.from_numpy(read_hdf5(stats_path, "scale"))
        .float()
        .to(DEVICE),
    }
    
    # define upstream model
    upstream_model = get_upstream(config["upstream"]).to(DEVICE)
    upstream_model.eval()
    upstream_featurizer = Featurizer(upstream_model).to(DEVICE)
    upstream_featurizer.load_state_dict(
        torch.load(checkpoint_path, map_location="cpu")["featurizer"]
    )
    upstream_featurizer.eval()

    # get model and load parameters
    model_class = getattr(s3prl_vc.models, config["model_type"])
    model = model_class(
        upstream_featurizer.output_size,
        config["num_mels"],
        config["sampling_rate"]
        / config["hop_size"]
        * upstream_featurizer.downsample_rate
        / 16000,
        config["trg_stats"],
        use_spemb=config.get("use_spk_emb", False),
        **config["model_params"],
    ).to(DEVICE)
    model.load_state_dict(torch.load(checkpoint_path, map_location="cpu")["model"])
    model = model.eval().to(DEVICE)
    logger.info(f"Loaded model parameters from {checkpoint_path}.")

    # load vocoder
    vocoder = Vocoder(
        vocoder_paths["ckpt"],
        vocoder_paths["config"],
        vocoder_paths["stats"],
        config["trg_stats"],
        DEVICE,
    )

    vc_models[trgspk] = {
        "upstream": upstream_model,
        "featurizer": upstream_featurizer,
        "decoder": model,
        "vocoder": vocoder
    }

def predict(trgspk, wav_file):
    x, fs = librosa.load(wav_file, sr=16000)
    logger.info('wav file loaded')

    with torch.no_grad():
        start_time = time.time()
        xs = torch.from_numpy(x).unsqueeze(0).float().to(DEVICE)
        ilens = torch.LongTensor([x.shape[0]]).to(DEVICE)

        all_hs, all_hlens = vc_models[trgspk]["upstream"](xs, ilens)
        logger.info('upstream done')
        
        hs, hlens = vc_models[trgspk]["featurizer"](all_hs, all_hlens)
        logger.info('featurizer done')
        
        outs, _ = vc_models[trgspk]["decoder"](hs, hlens, spk_embs=None)
        logger.info('downstream done')
        
        out = outs[0]
        y, sr = vc_models[trgspk]["vocoder"].decode(out)
        logger.info('vocoder done')
        sf.write(
            "out.wav",
            y.cpu().numpy(),
            24000,
            "PCM_16",
        )
        logger.info('write done')
        logger.info('RTF={}'.format(
            (time.time() - start_time) / (len(x) / 16000)
        ))

    return "out.wav"

with gr.Blocks(title="S3PRL-VC: Any-to-one voice conversion demo on VCC2020") as demo:
    gr.Markdown(
        """
        # S3PRL-VC: Any-to-one voice conversion demo on VCC2020

        ### [[Paper (ICASSP2023)]](https://arxiv.org/abs/2110.06280) [[Paper(JSTSP)]](https://arxiv.org/abs/2207.04356) [[Code]](https://github.com/unilight/s3prl-vc)

        **S3PRL-VC** is a voice conversion (VC) toolkit for benchmarking self-supervised speech representations (S3Rs). The term **any-to-one** means that the system can convert from any unseen speaker to a pre-defined speaker given in training.

        In this demo, you can record your voice, and the model will convert your voice to one of the four pre-defined speakers. These four speakers come from the **voice conversion challenge (VCC) 2020**. You can listen to the samples to get a sense of what these speakers sound like.

        The **RTF** of the system is around **1.5~2.5**, i.e. if you recorded a 5 second long audio, it will take 5 * (1.5~2.5) = 7.5~12.5 seconds to generate the output.
        """
    )

    with gr.Row():
        with gr.Column():
            gr.Markdown("## Upload a .wav file here!")
            input_wav = gr.Audio(label="Source speech", source='upload', type='filepath')

            gr.Markdown("## Select a target speaker!")
            trgspk = gr.Radio(label="Target speaker", choices=["TEF1", "TEF2", "TEM1", "TEM2"])
            gr.Markdown("### Here is what the target speaker sounds like!")
            ref_sample_wav1 = gr.Audio(label="Sample 1", type="filepath")
            ref_sample_wav2 = gr.Audio(label="Sample 2", type="filepath")
            trgspk.change(lambda trgspk: ref_samples[trgspk],
                          inputs = trgspk,
                          outputs = [ref_sample_wav1, ref_sample_wav2]
            )

            convert_btn = gr.Button(value="Convert!")
            gr.Markdown("### You can use these examples if using a microphone is too troublesome!")
            gr.Markdown("I recorded the samples using my Macbook Pro, so there might be some noises.")
            gr.Examples(
                examples=en_examples,
                inputs=input_wav,
                label="English examples"
            )
            gr.Examples(
                examples=jp_examples,
                inputs=input_wav,
                label="Japanese examples"
            )
            gr.Examples(
                examples=zh_examples,
                inputs=input_wav,
                label="Mandarin examples"
            )
        
        with gr.Column():
            gr.Markdown("## Listen to the converted speech here!")
            output_wav = gr.Audio(type="filepath", label="Converted speech")
        convert_btn.click(predict, [trgspk, input_wav], output_wav)

if __name__ == '__main__':
    try:
        demo.launch(debug=True,
                     enable_queue=True,
                     )    
    except KeyboardInterrupt as e:
        print(e)

    finally:
        demo.close()