{
  "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\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",
        "f0method = \"rmvpe\"  # @param [\"pm\", \"dio\", \"crepe\", \"crepe-tiny\", \"harvest\", \"rmvpe\", \"fcpe\", \"hybrid[rmvpe+fcpe]\"] {allow-input: false}\n",
        "f0up_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",
        "autotune = False  # @param{type:\"boolean\"}\n",
        "\n",
        "!python core.py infer --f0up_key \"{f0up_key}\" --filter_radius \"{filter_radius}\" --index_rate \"{index_rate}\" --hop_length \"{hop_length}\" --rms_mix_rate \"{rms_mix_rate}\" --protect \"{protect}\" --f0autotune \"{autotune}\" --f0method \"{f0method}\" --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",
        "\n",
        "!python core.py preprocess --model_name \"{model_name}\" --dataset_path \"{dataset_path}\" --sampling_rate \"{sr}\""
      ]
    },
    {
      "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",
        "f0method = \"rmvpe\"  # @param [\"pm\", \"dio\", \"crepe\", \"crepe-tiny\", \"harvest\", \"rmvpe\"] {allow-input: false}\n",
        "hop_length = 128  # @param {type:\"slider\", min:1, max:512, step:0}\n",
        "\n",
        "sr = int(sample_rate.rstrip(\"k\")) * 1000\n",
        "\n",
        "!python core.py extract --model_name \"{model_name}\" --rvc_version \"{rvc_version}\" --f0method \"{f0method}\" --hop_length \"{hop_length}\" --sampling_rate \"{sr}\""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "TI6LLdIzKAIa"
      },
      "outputs": [],
      "source": [
        "# @title Train\n",
        "# @markdown ### ➡️ Model Information\n",
        "import requests\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 e:\n",
        "        print(f\"An error occurred while copying weights: {str(e)}\")\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 e:\n",
        "            print(f\"An error occurred: {str(e)}\")\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",
        "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/pretraineds/pretraineds_custom/G48k.pth\"  # @param {type:\"string\"}\n",
        "d_pretrained_path = \"/content/Applio/rvc/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}\" --sampling_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}\"\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 MODELNAME 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",
        "f0method = \"rmvpe\"  # @param [\"pm\", \"dio\", \"crepe\", \"crepe-tiny\", \"harvest\", \"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
}