File size: 8,636 Bytes
e6d6bb1
 
0ae5ec9
e6d6bb1
d07b6f4
645c216
 
 
 
d07b6f4
 
645c216
a0ad823
d07b6f4
 
645c216
 
0ae5ec9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
645c216
 
 
 
 
015a5f1
 
 
 
 
645c216
015a5f1
645c216
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fe2bf8
 
645c216
 
 
 
28cee66
645c216
 
8fe2bf8
645c216
 
 
 
 
8fe2bf8
 
645c216
a0ad823
 
 
 
 
 
 
 
 
 
 
 
 
645c216
 
 
 
 
 
d07b6f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28cee66
d07b6f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0f46ba
 
0ae5ec9
 
 
 
645c216
 
 
 
 
 
 
 
5459d70
645c216
 
 
0ae5ec9
 
 
 
 
 
 
645c216
 
 
5459d70
645c216
 
 
 
 
 
d07b6f4
 
 
 
a0ad823
d07b6f4
 
 
 
 
 
 
 
 
645c216
 
 
5459d70
645c216
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d07b6f4
 
 
 
 
 
 
 
 
 
 
 
645c216
 
 
 
 
 
0ae5ec9
 
b0f46ba
0ae5ec9
 
 
645c216
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import os

os.environ["PYTORCH_JIT"] = "0v"

from random import shuffle
import gradio as gr
import zipfile
import tempfile
import shutil
from glob import glob
from infer.modules.train.preprocess import PreProcess
from infer.modules.train.extract.extract_f0_rmvpe import FeatureInput
from infer.modules.train.extract_feature_print import HubertFeatureExtractor
from infer.modules.train.train import train
from infer.lib.train.process_ckpt import extract_small_model
from zero import zero

# patch for jit script
# if we find `def expand_2d_or_3d_tensor(x,` in /usr/local/lib/python3.10/site-packages/fairseq/models/model_utils.py
# patch it with `def expand_2d_or_3d_tensor(x: Tensor,`
FAIRSEQ_CODE = "/usr/local/lib/python3.10/site-packages/fairseq/models/model_utils.py"
if os.path.exists(FAIRSEQ_CODE):
    with open(FAIRSEQ_CODE, "r") as f:
        lines = f.readlines()
    with open(FAIRSEQ_CODE, "w") as f:
        for line in lines:
            if "def expand_2d_or_3d_tensor(x, trg_dim: int, padding_idx: int):" in line:
                f.write(
                    "def expand_2d_or_3d_tensor(x: Tensor, trg_dim: int, padding_idx: int) -> Tensor:\n"
                )
            else:
                f.write(line)


def extract_audio_files(zip_file: str, target_dir: str) -> list[str]:
    with zipfile.ZipFile(zip_file, "r") as zip_ref:
        zip_ref.extractall(target_dir)

    audio_files = [
        os.path.join(target_dir, f)
        for f in os.listdir(target_dir)
        if f.endswith((".wav", ".mp3", ".ogg"))
    ]
    if not audio_files:
        raise gr.Error("No audio files found at the top level of the zip file")

    return audio_files


def train_rvc_model(audio_files: list[str]) -> str:
    return "model_path"


def preprocess(zip_file: str) -> str:
    temp_dir = tempfile.mkdtemp()
    print(f"Using exp dir: {temp_dir}")

    data_dir = os.path.join(temp_dir, "_data")
    os.makedirs(data_dir)
    audio_files = extract_audio_files(zip_file, data_dir)

    pp = PreProcess(48000, temp_dir, 3.0, False)
    pp.pipeline_mp_inp_dir(data_dir, 4)

    pp.logfile.seek(0)
    log = pp.logfile.read()

    return temp_dir, f"Preprocessed {len(audio_files)} audio files.\n{log}"


@zero(duration=300)
def extract_features(exp_dir: str) -> str:
    err = None
    fi = FeatureInput(exp_dir)
    try:
        fi.run()
    except Exception as e:
        err = e

    fi.logfile.seek(0)
    log = fi.logfile.read()

    if err:
        log = f"Error: {err}\n{log}"
        return log

    hfe = HubertFeatureExtractor(exp_dir)
    try:
        hfe.run()
    except Exception as e:
        err = e

    hfe.logfile.seek(0)
    log += hfe.logfile.read()

    if err:
        log = f"Error: {err}\n{log}"

    return log


def write_filelist(exp_dir: str) -> None:
    if_f0_3 = True
    spk_id5 = 0
    gt_wavs_dir = "%s/0_gt_wavs" % (exp_dir)
    feature_dir = "%s/3_feature768" % (exp_dir)

    if if_f0_3:
        f0_dir = "%s/2a_f0" % (exp_dir)
        f0nsf_dir = "%s/2b-f0nsf" % (exp_dir)
        names = (
            set([name.split(".")[0] for name in os.listdir(gt_wavs_dir)])
            & set([name.split(".")[0] for name in os.listdir(feature_dir)])
            & set([name.split(".")[0] for name in os.listdir(f0_dir)])
            & set([name.split(".")[0] for name in os.listdir(f0nsf_dir)])
        )
    else:
        names = set([name.split(".")[0] for name in os.listdir(gt_wavs_dir)]) & set(
            [name.split(".")[0] for name in os.listdir(feature_dir)]
        )
    opt = []
    for name in names:
        if if_f0_3:
            opt.append(
                "%s/%s.wav|%s/%s.npy|%s/%s.wav.npy|%s/%s.wav.npy|%s"
                % (
                    gt_wavs_dir.replace("\\", "\\\\"),
                    name,
                    feature_dir.replace("\\", "\\\\"),
                    name,
                    f0_dir.replace("\\", "\\\\"),
                    name,
                    f0nsf_dir.replace("\\", "\\\\"),
                    name,
                    spk_id5,
                )
            )
        else:
            opt.append(
                "%s/%s.wav|%s/%s.npy|%s"
                % (
                    gt_wavs_dir.replace("\\", "\\\\"),
                    name,
                    feature_dir.replace("\\", "\\\\"),
                    name,
                    spk_id5,
                )
            )
    fea_dim = 768

    now_dir = os.getcwd()
    sr2 = "40k"
    if if_f0_3:
        for _ in range(2):
            opt.append(
                "%s/logs/mute/0_gt_wavs/mute%s.wav|%s/logs/mute/3_feature%s/mute.npy|%s/logs/mute/2a_f0/mute.wav.npy|%s/logs/mute/2b-f0nsf/mute.wav.npy|%s"
                % (now_dir, sr2, now_dir, fea_dim, now_dir, now_dir, spk_id5)
            )
    else:
        for _ in range(2):
            opt.append(
                "%s/logs/mute/0_gt_wavs/mute%s.wav|%s/logs/mute/3_feature%s/mute.npy|%s"
                % (now_dir, sr2, now_dir, fea_dim, spk_id5)
            )
    shuffle(opt)
    with open("%s/filelist.txt" % exp_dir, "w") as f:
        f.write("\n".join(opt))


@zero(duration=300)
def train_model(exp_dir: str) -> str:
    shutil.copy("config.json", exp_dir)
    write_filelist(exp_dir)
    train(exp_dir)

    models = glob(f"{exp_dir}/G_*.pth")
    print(models)
    if not models:
        raise gr.Error("No model found")

    latest_model = max(models, key=os.path.getctime)
    return latest_model


def download_weight(exp_dir: str) -> str:
    models = glob(f"{exp_dir}/G_*.pth")
    if not models:
        raise gr.Error("No model found")

    latest_model = max(models, key=os.path.getctime)

    name = os.path.basename(exp_dir)
    extract_small_model(
        latest_model, name, "40k", True, "Model trained by ZeroGPU.", "v2"
    )

    return "assets/weights/%s.pth" % name


def download_expdir(exp_dir: str) -> str:
    shutil.make_archive(exp_dir, "zip", exp_dir)
    return f"{exp_dir}.zip"


def restore_expdir(zip: str) -> str:
    exp_dir = tempfile.mkdtemp()
    shutil.unpack_archive(zip, exp_dir)
    return exp_dir


with gr.Blocks() as app:
    with gr.Row():
        with gr.Column():
            zip_file = gr.File(
                label="Upload a zip file containing audio files for training",
                file_types=["zip"],
            )
            exp_dir = gr.Textbox(label="Experiment directory", visible=True)
            preprocess_btn = gr.Button(value="Preprocess", variant="primary")
        with gr.Column():
            preprocess_output = gr.Textbox(label="Preprocessing output", lines=5)

    with gr.Row():
        restore_zip_file = gr.File(
            label="Upload the experiment directory zip file",
            file_types=["zip"],
        )
        restore_btn = gr.Button(value="Preprocess")

    with gr.Row():
        with gr.Column():
            extract_features_btn = gr.Button(
                value="Extract features", variant="primary"
            )
        with gr.Column():
            extract_features_output = gr.Textbox(
                label="Feature extraction output", lines=5
            )

    with gr.Row():
        with gr.Column():
            train_btn = gr.Button(value="Train", variant="primary")
        with gr.Column():
            latest_model = gr.File(label="Latest checkpoint")

    with gr.Row():
        with gr.Column():
            download_weight_btn = gr.Button(
                value="Download latest model", variant="primary"
            )
        with gr.Column():
            download_weight_output = gr.File(label="Download latest model")

    with gr.Row():
        with gr.Column():
            download_expdir_btn = gr.Button(
                value="Download experiment directory", variant="primary"
            )
        with gr.Column():
            download_expdir_output = gr.File(label="Download experiment directory")

    preprocess_btn.click(
        fn=preprocess,
        inputs=[zip_file],
        outputs=[exp_dir, preprocess_output],
    )

    extract_features_btn.click(
        fn=extract_features,
        inputs=[exp_dir],
        outputs=[extract_features_output],
    )

    train_btn.click(
        fn=train_model,
        inputs=[exp_dir],
        outputs=[latest_model],
    )

    download_weight_btn.click(
        fn=download_weight,
        inputs=[exp_dir],
        outputs=[download_weight_output],
    )

    download_expdir_btn.click(
        fn=download_expdir,
        inputs=[exp_dir],
        outputs=[download_expdir_output],
    )

    restore_btn.click(
        fn=restore_expdir,
        inputs=[restore_zip_file],
        outputs=[exp_dir],
    )

    app.launch()