File size: 30,677 Bytes
4efe6b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0pKllbPyK_BC"
      },
      "source": [
        "# Applio NoUI\n",
        "Created by [Blaise](https://github.com/blaise-tk) with [Vidal](https://github.com/Vidalnt) and [Poopmaster](https://github.com/poiqazwsx). Based on [RVC_CLI](https://github.com/blaise-tk/RVC_CLI).\n",
        "\n",
        "- Colab inspired on [RVC v2 Disconnected](https://colab.research.google.com/drive/1XIPCP9ken63S7M6b5ui1b36Cs17sP-NS).\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Y-iR3WeLMlac"
      },
      "source": [
        "### If you restart the runtime, run it again."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "xwZkZGd-H0zT"
      },
      "outputs": [],
      "source": [
        "%cd /content/Applio"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ymMCTSD6m8qV"
      },
      "source": [
        "# Installation\n",
        "## If the runtime restarts, run the cell above and re-run the installation steps."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "yFhAeKGOp9aa"
      },
      "outputs": [],
      "source": [
        "# @title Mount Google Drive\n",
        "from google.colab import drive\n",
        "\n",
        "drive.mount(\"/content/drive\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "7GysECSxBya4"
      },
      "outputs": [],
      "source": [
        "# @title Clone\n",
        "!git clone https://github.com/IAHispano/Applio --branch 3.2.2 --single-branch\n",
        "%cd /content/Applio"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "CAXW55BQm0PP"
      },
      "outputs": [],
      "source": [
        "# @title Install\n",
        "rot_47 = lambda encoded_text: \"\".join(\n",
        "    [\n",
        "        (\n",
        "            chr(\n",
        "                (ord(c) - (ord(\"a\") if c.islower() else ord(\"A\")) - 47) % 26\n",
        "                + (ord(\"a\") if c.islower() else ord(\"A\"))\n",
        "            )\n",
        "            if c.isalpha()\n",
        "            else c\n",
        "        )\n",
        "        for c in encoded_text\n",
        "    ]\n",
        ")\n",
        "import codecs\n",
        "import os\n",
        "import shutil\n",
        "import tarfile\n",
        "import subprocess\n",
        "from pathlib import Path\n",
        "from datetime import datetime\n",
        "E = Exception\n",
        "B = print\n",
        "\n",
        "\n",
        "def vidal_setup(ForceIn):\n",
        "    L = \"Kikpm.ovm.bu\"\n",
        "    K = \"/content/\"\n",
        "    C = ForceIn\n",
        "\n",
        "    def F():\n",
        "        print(\"Installing pip packages...\")\n",
        "        subprocess.check_call([\"pip\", \"install\", \"-r\", \"requirements.txt\", \"--quiet\"])\n",
        "\n",
        "    A = K + rot_47(L)\n",
        "    G = K + rot_47(L)\n",
        "    D = \"/\"\n",
        "    if not os.path.exists(A):\n",
        "        M = os.path.dirname(A)\n",
        "        os.makedirs(M, exist_ok=True)\n",
        "        print(\"No cached install found..\")\n",
        "        try:\n",
        "            N = rot_47(\n",
        "                codecs.decode(\n",
        "                    \"pbbxa://pcooqvonikm.kw/QIPqaxivw/Ixxtqw/zmawtdm/uiqv/Kwtij/Xvxcz.biz.oh\",\n",
        "                    \"rot_13\",\n",
        "                )\n",
        "            )\n",
        "            subprocess.run([\"wget\", \"-O\", A, N])\n",
        "            print(\"Download completed successfully!\")\n",
        "        except E as H:\n",
        "            print(str(H))\n",
        "            if os.path.exists(A):\n",
        "                os.remove(A)\n",
        "    if Path(A).exists():\n",
        "        with tarfile.open(G, \"r:gz\") as I:\n",
        "            for J in I.getmembers():\n",
        "                O = os.path.join(D, J.name)\n",
        "                try:\n",
        "                    I.extract(J, D)\n",
        "                except E as H:\n",
        "                    print(\"Failed to extract a file\")\n",
        "                    C = True\n",
        "            print(f\"Extraction of {G} to {D} completed.\")\n",
        "        if os.path.exists(A):\n",
        "            os.remove(A)\n",
        "        if C:\n",
        "            F()\n",
        "            C = False\n",
        "    else:\n",
        "        F()\n",
        "\n",
        "\n",
        "vidal_setup(False)\n",
        "print(\"Finished installing requirements!\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "QlTibPnjmj6-"
      },
      "outputs": [],
      "source": [
        "# @title Download models\n",
        "!python core.py prerequisites"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "YzaeMYsUE97Y"
      },
      "source": [
        "# Infer\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "v0EgikgjFCjE"
      },
      "outputs": [],
      "source": [
        "# @title Download model\n",
        "# @markdown Hugging Face or Google Drive\n",
        "model_link = \"https://huggingface.co./Darwin/Darwin/resolve/main/Darwin.zip\"  # @param {type:\"string\"}\n",
        "\n",
        "!python core.py download --model_link \"{model_link}\""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "lrCKEOzvDPRu"
      },
      "outputs": [],
      "source": [
        "# @title Run Inference\n",
        "# @markdown Please upload the audio file to your Google Drive path `/content/drive/MyDrive` and specify its name here. For the model name, use the zip file name without the extension. Alternatively, you can check the path `/content/Applio/logs` for the model name (name of the folder).\n",
        "\n",
        "import os\n",
        "\n",
        "current_dir = os.getcwd()\n",
        "\n",
        "model_name = \"Darwin\"  # @param {type:\"string\"}\n",
        "model_folder = os.path.join(current_dir, f\"logs/{model_name}\")\n",
        "\n",
        "if not os.path.exists(model_folder):\n",
        "    raise FileNotFoundError(f\"Model directory not found: {model_folder}\")\n",
        "\n",
        "files_in_folder = os.listdir(model_folder)\n",
        "pth_path = next((f for f in files_in_folder if f.endswith(\".pth\")), None)\n",
        "index_file = next((f for f in files_in_folder if f.endswith(\".index\")), None)\n",
        "\n",
        "if pth_path is None or index_file is None:\n",
        "    raise FileNotFoundError(\"No model found.\")\n",
        "\n",
        "pth_file = os.path.join(model_folder, pth_path)\n",
        "index_file = os.path.join(model_folder, index_file)\n",
        "\n",
        "input_path = \"/content/example.wav\"  # @param {type:\"string\"}\n",
        "output_path = \"/content/output.wav\"\n",
        "export_format = \"WAV\"  # @param ['WAV', 'MP3', 'FLAC', 'OGG', 'M4A'] {allow-input: false}\n",
        "f0_method = \"rmvpe\"  # @param [\"crepe\", \"crepe-tiny\", \"rmvpe\", \"fcpe\", \"hybrid[rmvpe+fcpe]\"] {allow-input: false}\n",
        "f0_up_key = 0  # @param {type:\"slider\", min:-24, max:24, step:0}\n",
        "filter_radius = 3  # @param {type:\"slider\", min:0, max:10, step:0}\n",
        "rms_mix_rate = 0.8  # @param {type:\"slider\", min:0.0, max:1.0, step:0.1}\n",
        "protect = 0.5  # @param {type:\"slider\", min:0.0, max:0.5, step:0.1}\n",
        "index_rate = 0.7  # @param {type:\"slider\", min:0.0, max:1.0, step:0.1}\n",
        "hop_length = 128  # @param {type:\"slider\", min:1, max:512, step:0}\n",
        "clean_strength = 0.7  # @param {type:\"slider\", min:0.0, max:1.0, step:0.1}\n",
        "split_audio = False  # @param{type:\"boolean\"}\n",
        "clean_audio = False  # @param{type:\"boolean\"}\n",
        "f0_autotune = False  # @param{type:\"boolean\"}\n",
        "\n",
        "!python core.py infer --pitch \"{f0_up_key}\" --filter_radius \"{filter_radius}\" --volume_envelope \"{rms_mix_rate}\" --index_rate \"{index_rate}\" --hop_length \"{hop_length}\" --protect \"{protect}\" --f0_autotune \"{f0_autotune}\" --f0_method \"{f0_method}\" --input_path \"{input_path}\" --output_path \"{output_path}\" --pth_path \"{pth_file}\" --index_path \"{index_file}\" --split_audio \"{split_audio}\" --clean_audio \"{clean_audio}\" --clean_strength \"{clean_strength}\" --export_format \"{export_format}\"\n",
        "\n",
        "from IPython.display import Audio, display, clear_output\n",
        "\n",
        "output_path = output_path.replace(\".wav\", f\".{export_format.lower()}\")\n",
        "# clear_output()\n",
        "display(Audio(output_path, autoplay=True))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1QkabnLlF2KB"
      },
      "source": [
        "# Train"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "oBzqm4JkGGa0"
      },
      "outputs": [],
      "source": [
        "# @title Preprocess Dataset\n",
        "model_name = \"Darwin\"  # @param {type:\"string\"}\n",
        "dataset_path = \"/content/drive/MyDrive/Darwin_Dataset\"  # @param {type:\"string\"}\n",
        "\n",
        "sample_rate = \"40k\"  # @param [\"32k\", \"40k\", \"48k\"] {allow-input: false}\n",
        "sr = int(sample_rate.rstrip(\"k\")) * 1000\n",
        "cpu_cores = 2 # @param {type:\"slider\", min:1, max:2, step:1}\n",
        "\n",
        "!python core.py preprocess --model_name \"{model_name}\" --dataset_path \"{dataset_path}\" --sample_rate \"{sr}\" --cpu_cores \"{cpu_cores}\""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "zWMiMYfRJTJv"
      },
      "outputs": [],
      "source": [
        "# @title Extract Features\n",
        "rvc_version = \"v2\"  # @param [\"v2\", \"v1\"] {allow-input: false}\n",
        "f0_method = \"rmvpe\"  # @param [\"crepe\", \"crepe-tiny\", \"rmvpe\"] {allow-input: false}\n",
        "pitch_guidance = True  # @param{type:\"boolean\"}\n",
        "hop_length = 128  # @param {type:\"slider\", min:1, max:512, step:0}\n",
        "\n",
        "sr = int(sample_rate.rstrip(\"k\")) * 1000\n",
        "cpu_cores = 2 # @param {type:\"slider\", min:1, max:2, step:1}\n",
        "\n",
        "!python core.py extract --model_name \"{model_name}\" --rvc_version \"{rvc_version}\" --f0_method \"{f0_method}\" --pitch_guidance \"{pitch_guidance}\" --hop_length \"{hop_length}\" --sample_rate \"{sr}\" --cpu_cores \"{cpu_cores}\" --gpu \"0\""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "TI6LLdIzKAIa"
      },
      "outputs": [],
      "source": [
        "# @title Train\n",
        "# @markdown ### ➡️ Model Information\n",
        "import threading\n",
        "import time\n",
        "import os\n",
        "import shutil\n",
        "import hashlib\n",
        "import time\n",
        "\n",
        "LOGS_FOLDER = \"/content/Applio/logs/\"\n",
        "WEIGHTS_FOLDER = LOGS_FOLDER + model_name\n",
        "GOOGLE_DRIVE_PATH = \"/content/drive/MyDrive/RVC_Backup\"\n",
        "\n",
        "\n",
        "def import_google_drive_backup():\n",
        "    print(\"Importing Google Drive backup...\")\n",
        "    weights_exist = False\n",
        "    for root, dirs, files in os.walk(GOOGLE_DRIVE_PATH):\n",
        "        for filename in files:\n",
        "            filepath = os.path.join(root, filename)\n",
        "            if os.path.isfile(filepath) and not filepath.startswith(\n",
        "                os.path.join(GOOGLE_DRIVE_PATH, \"weights\")\n",
        "            ):\n",
        "                backup_filepath = os.path.join(\n",
        "                    LOGS_FOLDER, os.path.relpath(filepath, GOOGLE_DRIVE_PATH)\n",
        "                )\n",
        "                backup_folderpath = os.path.dirname(backup_filepath)\n",
        "                if not os.path.exists(backup_folderpath):\n",
        "                    os.makedirs(backup_folderpath)\n",
        "                    print(f\"Created backup folder: {backup_folderpath}\", flush=True)\n",
        "                shutil.copy2(filepath, backup_filepath)  # copy file with metadata\n",
        "                print(f\"Imported file from Google Drive backup: {filename}\")\n",
        "            elif filepath.startswith(\n",
        "                os.path.join(GOOGLE_DRIVE_PATH, \"weights\")\n",
        "            ) and filename.endswith(\".pth\"):\n",
        "                weights_exist = True\n",
        "                weights_filepath = os.path.join(\n",
        "                    WEIGHTS_FOLDER,\n",
        "                    os.path.relpath(\n",
        "                        filepath, os.path.join(GOOGLE_DRIVE_PATH, \"weights\")\n",
        "                    ),\n",
        "                )\n",
        "                weights_folderpath = os.path.dirname(weights_filepath)\n",
        "                if not os.path.exists(weights_folderpath):\n",
        "                    os.makedirs(weights_folderpath)\n",
        "                    print(f\"Created weights folder: {weights_folderpath}\", flush=True)\n",
        "                shutil.copy2(filepath, weights_filepath)  # copy file with metadata\n",
        "                print(f\"Imported file from weights: {filename}\")\n",
        "    if weights_exist:\n",
        "        print(\"Copied weights from Google Drive backup to local weights folder.\")\n",
        "    else:\n",
        "        print(\"No weights found in Google Drive backup.\")\n",
        "    print(\"Google Drive backup import completed.\")\n",
        "\n",
        "\n",
        "def get_md5_hash(file_path):\n",
        "    hash_md5 = hashlib.md5()\n",
        "    with open(file_path, \"rb\") as f:\n",
        "        for chunk in iter(lambda: f.read(4096), b\"\"):\n",
        "            hash_md5.update(chunk)\n",
        "    return hash_md5.hexdigest()\n",
        "\n",
        "\n",
        "def copy_weights_folder_to_drive():\n",
        "    destination_folder = os.path.join(GOOGLE_DRIVE_PATH, \"weights\")\n",
        "    try:\n",
        "        if not os.path.exists(destination_folder):\n",
        "            os.makedirs(destination_folder)\n",
        "\n",
        "        num_copied = 0\n",
        "        for filename in os.listdir(WEIGHTS_FOLDER):\n",
        "            if filename.endswith(\".pth\"):\n",
        "                source_file = os.path.join(WEIGHTS_FOLDER, filename)\n",
        "                destination_file = os.path.join(destination_folder, filename)\n",
        "                if not os.path.exists(destination_file):\n",
        "                    shutil.copy2(source_file, destination_file)\n",
        "                    num_copied += 1\n",
        "                    print(f\"Copied {filename} to Google Drive!\")\n",
        "\n",
        "        if num_copied == 0:\n",
        "            print(\"No new finished models found for copying.\")\n",
        "        else:\n",
        "            print(f\"Finished copying {num_copied} files to Google Drive!\")\n",
        "\n",
        "    except Exception as error:\n",
        "        print(f\"An error occurred during copying weights to Google Drive: {str(error)}\")\n",
        "\n",
        "\n",
        "if \"autobackups\" not in globals():\n",
        "    autobackups = False\n",
        "\n",
        "\n",
        "def backup_files():\n",
        "    print(\"\\nStarting backup loop...\")\n",
        "    last_backup_timestamps_path = os.path.join(\n",
        "        LOGS_FOLDER, \"last_backup_timestamps.txt\"\n",
        "    )\n",
        "    fully_updated = False\n",
        "\n",
        "    while True:\n",
        "        try:\n",
        "            updated = False\n",
        "            last_backup_timestamps = {}\n",
        "\n",
        "            try:\n",
        "                with open(last_backup_timestamps_path, \"r\") as f:\n",
        "                    last_backup_timestamps = dict(line.strip().split(\":\") for line in f)\n",
        "            except FileNotFoundError:\n",
        "                pass\n",
        "\n",
        "            for root, dirs, files in os.walk(LOGS_FOLDER):\n",
        "                # Excluding \"zips\" directory\n",
        "                if \"zips\" in dirs:\n",
        "                    dirs.remove(\"zips\")\n",
        "                if \"mute\" in dirs:\n",
        "                    dirs.remove(\"mute\")\n",
        "                for filename in files:\n",
        "                    if filename != \"last_backup_timestamps.txt\":\n",
        "                        filepath = os.path.join(root, filename)\n",
        "                        if os.path.isfile(filepath):\n",
        "                            backup_filepath = os.path.join(\n",
        "                                GOOGLE_DRIVE_PATH,\n",
        "                                os.path.relpath(filepath, LOGS_FOLDER),\n",
        "                            )\n",
        "                            backup_folderpath = os.path.dirname(backup_filepath)\n",
        "                            if not os.path.exists(backup_folderpath):\n",
        "                                os.makedirs(backup_folderpath)\n",
        "                                print(\n",
        "                                    f\"Created backup folder: {backup_folderpath}\",\n",
        "                                    flush=True,\n",
        "                                )\n",
        "                            last_backup_timestamp = last_backup_timestamps.get(filepath)\n",
        "                            current_timestamp = os.path.getmtime(filepath)\n",
        "                            if (\n",
        "                                last_backup_timestamp is None\n",
        "                                or float(last_backup_timestamp) < current_timestamp\n",
        "                            ):\n",
        "                                shutil.copy2(filepath, backup_filepath)\n",
        "                                last_backup_timestamps[filepath] = str(\n",
        "                                    current_timestamp\n",
        "                                )\n",
        "                                if last_backup_timestamp is None:\n",
        "                                    print(f\"Backed up file: {filename}\")\n",
        "                                else:\n",
        "                                    print(f\"Updating backed up file: {filename}\")\n",
        "                                updated = True\n",
        "                                fully_updated = False\n",
        "\n",
        "            for filepath in list(last_backup_timestamps.keys()):\n",
        "                if not os.path.exists(filepath):\n",
        "                    backup_filepath = os.path.join(\n",
        "                        GOOGLE_DRIVE_PATH, os.path.relpath(filepath, LOGS_FOLDER)\n",
        "                    )\n",
        "                    if os.path.exists(backup_filepath):\n",
        "                        os.remove(backup_filepath)\n",
        "                        print(f\"Deleted file: {filepath}\")\n",
        "                    del last_backup_timestamps[filepath]\n",
        "                    updated = True\n",
        "                    fully_updated = False\n",
        "\n",
        "            if not updated and not fully_updated:\n",
        "                print(\"Files are up to date.\")\n",
        "                fully_updated = True\n",
        "                sleep_time = 15\n",
        "            else:\n",
        "                sleep_time = 0.1\n",
        "\n",
        "            with open(last_backup_timestamps_path, \"w\") as f:\n",
        "                for filepath, timestamp in last_backup_timestamps.items():\n",
        "                    f.write(f\"{filepath}:{timestamp}\\n\")\n",
        "\n",
        "            time.sleep(sleep_time)\n",
        "\n",
        "        except Exception as error:\n",
        "            print(f\"An error occurred during backup: {str(error)}\")\n",
        "\n",
        "\n",
        "if autobackups:\n",
        "    autobackups = False\n",
        "    print(\"Autobackup Disabled\")\n",
        "else:\n",
        "    autobackups = True\n",
        "    print(\"Autobackup Enabled\")\n",
        "\n",
        "total_epoch = 800  # @param {type:\"integer\"}\n",
        "batch_size = 15  # @param {type:\"slider\", min:1, max:25, step:0}\n",
        "gpu = 0\n",
        "sr = int(sample_rate.rstrip(\"k\")) * 1000\n",
        "pitch_guidance = True  # @param{type:\"boolean\"}\n",
        "auto_backups = True  # @param{type:\"boolean\"}\n",
        "pretrained = True  # @param{type:\"boolean\"}\n",
        "sync_graph = False  # @param{type:\"boolean\"}\n",
        "cache_data_in_gpu = False  # @param{type:\"boolean\"}\n",
        "tensorboard = True  # @param{type:\"boolean\"}\n",
        "# @markdown ### ➡️ Choose how many epochs your model will be stored\n",
        "save_every_epoch = 10  # @param {type:\"slider\", min:1, max:100, step:0}\n",
        "save_only_latest = False  # @param{type:\"boolean\"}\n",
        "save_every_weights = False  # @param{type:\"boolean\"}\n",
        "overtraining_detector = False  # @param{type:\"boolean\"}\n",
        "overtraining_threshold = 50  # @param {type:\"slider\", min:1, max:100, step:0}\n",
        "# @markdown ### ❓ Optional\n",
        "# @markdown In case you select custom pretrained, you will have to download the pretraineds and enter the path of the pretraineds.\n",
        "custom_pretrained = False  # @param{type:\"boolean\"}\n",
        "g_pretrained_path = \"/content/Applio/rvc/models/pretraineds/pretraineds_custom/G48k.pth\"  # @param {type:\"string\"}\n",
        "d_pretrained_path = \"/content/Applio/rvc/models/pretraineds/pretraineds_custom/D48k.pth\"  # @param {type:\"string\"}\n",
        "\n",
        "if \"pretrained\" not in globals():\n",
        "    pretrained = True\n",
        "\n",
        "if \"custom_pretrained\" not in globals():\n",
        "    custom_pretrained = False\n",
        "\n",
        "if \"g_pretrained_path\" not in globals():\n",
        "    g_pretrained_path = \"Custom Path\"\n",
        "\n",
        "if \"d_pretrained_path\" not in globals():\n",
        "    d_pretrained_path = \"Custom Path\"\n",
        "\n",
        "\n",
        "def start_train():\n",
        "    if tensorboard == True:\n",
        "        %load_ext tensorboard\n",
        "        %tensorboard --logdir /content/Applio/logs/\n",
        "    !python core.py train --model_name \"{model_name}\" --rvc_version \"{rvc_version}\" --save_every_epoch \"{save_every_epoch}\" --save_only_latest \"{save_only_latest}\" --save_every_weights \"{save_every_weights}\" --total_epoch \"{total_epoch}\" --sample_rate \"{sr}\" --batch_size \"{batch_size}\" --gpu \"{gpu}\" --pitch_guidance \"{pitch_guidance}\" --pretrained \"{pretrained}\" --custom_pretrained \"{custom_pretrained}\" --g_pretrained_path \"{g_pretrained_path}\" --d_pretrained_path \"{d_pretrained_path}\" --overtraining_detector \"{overtraining_detector}\" --overtraining_threshold \"{overtraining_threshold}\" --sync_graph \"{sync_graph}\" --cache_data_in_gpu \"{cache_data_in_gpu}\"\n",
        "\n",
        "\n",
        "server_thread = threading.Thread(target=start_train)\n",
        "server_thread.start()\n",
        "\n",
        "if auto_backups:\n",
        "    backup_files()\n",
        "else:\n",
        "    while True:\n",
        "        time.sleep(10)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "bHLs5AT4Q1ck"
      },
      "outputs": [],
      "source": [
        "# @title Generate index file\n",
        "!python core.py index --model_name \"{model_name}\" --rvc_version \"{rvc_version}\""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "X_eU_SoiHIQg"
      },
      "outputs": [],
      "source": [
        "# @title Save model\n",
        "# @markdown Enter the name of the model and the steps. You can find it in your `/content/Applio/logs` folder.\n",
        "%cd /content\n",
        "import shutil, os\n",
        "\n",
        "model_name = \"Darwin\"  # @param {type:\"string\"}\n",
        "model_epoch = 800  # @param {type:\"integer\"}\n",
        "save_big_file = False  # @param {type:\"boolean\"}\n",
        "\n",
        "if os.path.exists(\"/content/zips\"):\n",
        "    shutil.rmtree(\"/content/zips\")\n",
        "print(\"Removed zips.\")\n",
        "!mkdir -p /content/zips/{model_name}/\n",
        "print(\"Created zips.\")\n",
        "if f\"{model_name}.pth\" not in os.listdir(f\"/content/Applio/weights\"):\n",
        "    print(\"There is no weight file with that name\")\n",
        "if not save_big_file:\n",
        "    !cp /content/Applio/logs/{model_name}/added_*.index /content/zips/{model_name}/\n",
        "    !cp /content/Applio/logs/{model_name}/total_*.npy /content/zips/{model_name}/\n",
        "    !cp /content/Applio/weights/{model_name}.pth /content/zips/{model_name}/{model_name}{model_epoch}.pth\n",
        "    %cd /content/zips\n",
        "    !zip -r {model_name}.zip {model_name}\n",
        "if save_big_file:\n",
        "    %cd /content/Applio\n",
        "    latest_steps = -1\n",
        "    logs_folder = \"./logs/\" + model_name\n",
        "    for filename in os.listdir(logs_folder):\n",
        "        if filename.startswith(\"G_\") and filename.endswith(\".pth\"):\n",
        "            steps = int(filename.split(\"_\")[1].split(\".\")[0])\n",
        "            if steps > latest_steps:\n",
        "                latest_steps = steps\n",
        "    MODELZIP = model_name + \".zip\"\n",
        "    !mkdir -p /content/zips\n",
        "    ZIPFILEPATH = os.path.join(\"/content/zips\", MODELZIP)\n",
        "    for filename in os.listdir(logs_folder):\n",
        "        if \"G_\" in filename or \"D_\" in filename:\n",
        "            if str(latest_steps) in filename:\n",
        "                !zip -r {ZIPFILEPATH} {os.path.join(logs_folder, filename)}\n",
        "        else:\n",
        "            !zip -r {ZIPFILEPATH} {os.path.join(logs_folder, filename)}\n",
        "    for filename in os.listdir(\"./weights\"):\n",
        "        if model_name in filename:\n",
        "            !zip -r {ZIPFILEPATH} {os.path.join('./weights/', filename)}\n",
        "\n",
        "!mkdir -p /content/drive/MyDrive/RVC_Backup/\n",
        "shutil.move(\n",
        "    f\"/content/zips/{model_name}.zip\",\n",
        "    f\"/content/drive/MyDrive/RVC_Backup/{model_name}.zip\",\n",
        ")\n",
        "%cd /content\n",
        "shutil.rmtree(\"/content/zips\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OaKoymXsyEYN"
      },
      "source": [
        "# Resume-training"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "d3KgLAYnyHkP"
      },
      "outputs": [],
      "source": [
        "# @title Load a Backup\n",
        "from google.colab import drive\n",
        "import os\n",
        "import shutil\n",
        "\n",
        "# @markdown Put the exact name you put as your Model Name in Applio.\n",
        "modelname = \"My-Project\"  # @param {type:\"string\"}\n",
        "source_path = \"/content/drive/MyDrive/RVC_Backup/\" + modelname\n",
        "destination_path = \"/content/Applio/logs/\" + modelname\n",
        "backup_timestamps_file = \"last_backup_timestamps.txt\"\n",
        "if not os.path.exists(source_path):\n",
        "    print(\n",
        "        \"The model folder does not exist. Please verify the name is correct or check your Google Drive.\"\n",
        "    )\n",
        "else:\n",
        "    time_ = os.path.join(\"/content/drive/MyDrive/RVC_Backup/\", backup_timestamps_file)\n",
        "    time__ = os.path.join(\"/content/Applio/logs/\", backup_timestamps_file)\n",
        "    if os.path.exists(time_):\n",
        "        shutil.copy(time_, time__)\n",
        "    shutil.copytree(source_path, destination_path)\n",
        "    print(\"Model backup loaded successfully.\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "sc9DzvRCyJ2d"
      },
      "outputs": [],
      "source": [
        "# @title Set training variables\n",
        "# @markdown ### ➡️ Use the same as you did previously\n",
        "model_name = \"Darwin\"  # @param {type:\"string\"}\n",
        "sample_rate = \"40k\"  # @param [\"32k\", \"40k\", \"48k\"] {allow-input: false}\n",
        "rvc_version = \"v2\"  # @param [\"v2\", \"v1\"] {allow-input: false}\n",
        "f0_method = \"rmvpe\"  # @param [\"crepe\", \"crepe-tiny\", \"rmvpe\"] {allow-input: false}\n",
        "hop_length = 128  # @param {type:\"slider\", min:1, max:512, step:0}\n",
        "sr = int(sample_rate.rstrip(\"k\")) * 1000"
      ]
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "collapsed_sections": [
        "ymMCTSD6m8qV"
      ],
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}