Shxtou / RVC
NhatMinhhh's picture
Upload RVC
ae2a13a
{"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"private_outputs":true,"provenance":[{"file_id":"1TU-kkQWVf-PLO_hSa2QCMZS1XF5xVHqs","timestamp":1690707922243},{"file_id":"1fc09UzPha3n-q6e5WFwUhr6u5EwOWM9p","timestamp":1684765299701},{"file_id":"1iWOLYE9znqT6XE5Rw2iETE19ZlqpziLx","timestamp":1684167429804},{"file_id":"1BKP-JSMOHm5d4-1TmbgTqIR8TSgXKobk","timestamp":1683349174242},{"file_id":"1mrHh7uqWp43F5jJp6MOXPvumMho3Lj4X","timestamp":1683214917901},{"file_id":"1iHumZNFgvIHqX4VCJh4dcXkdzECPE8fO","timestamp":1682377764710},{"file_id":"1DunK_g2uq8dTA13MtA_RXF4uG4Ph_uqg","timestamp":1682320070478},{"file_id":"1jrsoiIQiJcbpgQPPFAHbbYo8-N88xIME","timestamp":1682284944875},{"file_id":"https://github.com/liujing04/Retrieval-based-Voice-Conversion-WebUI/blob/main/Retrieval_based_Voice_Conversion_WebUI.ipynb","timestamp":1682115412258}],"collapsed_sections":["F6zbsuNs6xZF","p9SHghdUw2O_"],"gpuType":"T4"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"},"accelerator":"GPU"},"cells":[{"cell_type":"markdown","source":["# RVC GENERAL COVER GUIDE:\n","\n","https://docs.google.com/document/d/13_l1bd1Osgz7qlAZn-zhklCbHpVRk6bYOuAuB78qmsE/edit?usp=sharing\n","\n","# RVC VOICE TRAINING GUIDE:\n","\n","https://docs.google.com/document/d/13ebnzmeEBc6uzYCMt-QVFQk-whVrK4zw8k7_Lw3Bv_A/edit?usp=sharing"],"metadata":{"id":"2pShUKPuERDq"}},{"cell_type":"markdown","source":["#Step 1. Install everything and connect your Drive (RUN THIS ONE FIRST)"],"metadata":{"id":"F6zbsuNs6xZF"}},{"cell_type":"code","execution_count":null,"metadata":{"id":"GmFP6bN9dvOq"},"outputs":[],"source":["#@title Initialize External Code\n","import time\n","import os\n","import subprocess\n","import shutil\n","\n","# Store the current working directory\n","current_path = os.getcwd()\n","\n","# Clear the /content/ directory\n","shutil.rmtree('/content/')\n","os.makedirs('/content/', exist_ok=True)\n","\n","# Change the current working directory back to the original path\n","os.chdir(current_path)\n","\n","start_time = time.time()\n","\n","!nvidia-smi\n","!git clone https://github.com/kalomaze/externalcolabcode.git /content/Retrieval-based-Voice-Conversion-WebUI/utils\n","\n","end_time = time.time()\n","elapsed_time = end_time - start_time\n","print(f\"Time taken for utils Download: {elapsed_time} seconds\")"]},{"cell_type":"code","source":["#@title Install Dependencies and Clone Github Repository\n","\n","import threading\n","\n","start_time = time.time()\n","\n","os.chdir(\"/content/Retrieval-based-Voice-Conversion-WebUI/\")\n","from utils.dependency import *\n","from utils.clone_alt import *\n","os.chdir(\"..\")\n","\n","end_time = time.time()\n","elapsed_time = end_time - start_time\n","print(f\"Time taken for imports: {elapsed_time} seconds\")\n","\n","#@markdown This will forcefully update dependencies even after the initial install seemed to have functioned.\n","ForceUpdateDependencies = False #@param{type:\"boolean\"}\n","#@markdown This will force temporary storage to be used, so it will download dependencies every time instead of on Drive. Not needed, unless you really want that 160mb storage. (Turned on by default for non-training colab to boost the initial launch speed)\n","ForceTemporaryStorage = False #@param{type:\"boolean\"}\n","\n","# Setup environment\n","print(\"Attempting to setup environment dependencies...\")\n","print(\"\\n----------------------------------------\")\n","\n","start_time_setup = time.time()\n","setup_environment(ForceUpdateDependencies, ForceTemporaryStorage)\n","end_time_setup = time.time()\n","elapsed_time_setup = end_time_setup - start_time_setup\n","print(f\"Time taken for setup environment: {elapsed_time_setup} seconds\")\n","\n","print(\"----------------------------------------\\n\")\n","print(\"Attempting to clone necessary files...\")\n","print(\"\\n----------------------------------------\")\n","\n","start_time_clone = time.time()\n","clone_repository(True)\n","!wget https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/main/rmvpe.pt -P /content/Retrieval-based-Voice-Conversion-WebUI/\n","\n","end_time_clone = time.time()\n","elapsed_time_clone = end_time_clone - start_time_clone\n","print(f\"Time taken for clone repository: {elapsed_time_clone} seconds\")\n","\n","print(\"----------------------------------------\\n\")\n","print(\"Cell completed.\")\n","\n","total_time = elapsed_time + elapsed_time_setup + elapsed_time_clone\n","print(f\"Total time taken: {total_time} seconds\")\n","\n","!pip install -q stftpitchshift==1.5.1"],"metadata":{"id":"wjddIFr1oS3W"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["#Choose what you want to do.\n","##Do you want to load a MODEL and run it or make a new one with a DATASET?"],"metadata":{"id":"XAuGUlHDB4cx"}},{"cell_type":"code","source":["#@markdown #Step 2. Download The Model\n","#@markdown Link the URL path to the model (Mega, Drive, etc.) and start the code\n","\n","from mega import Mega\n","import os\n","import shutil\n","from urllib.parse import urlparse, parse_qs\n","import urllib.parse\n","from google.oauth2.service_account import Credentials\n","import gspread\n","import pandas as pd\n","from tqdm import tqdm\n","from bs4 import BeautifulSoup\n","import requests\n","import hashlib\n","\n","def calculate_md5(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","# Initialize gspread\n","scope = ['https://www.googleapis.com/auth/spreadsheets',\n"," 'https://www.googleapis.com/auth/drive.file',\n"," 'https://www.googleapis.com/auth/drive']\n","\n","config_path = '/content/Retrieval-based-Voice-Conversion-WebUI/stats/peppy-generator-388800-07722f17a188.json'\n","\n","if os.path.exists(config_path):\n"," # File exists, proceed with creation of creds and client\n"," creds = Credentials.from_service_account_file(config_path, scopes=scope)\n"," client = gspread.authorize(creds)\n","else:\n"," # File does not exist, print message and skip creation of creds and client\n"," print(\"Sheet credential file missing.\")\n","\n","# Open the Google Sheet (this will write any URLs so I can easily track popular models)\n","book = client.open(\"RealtimeRVCStats\")\n","sheet = book.get_worksheet(3) # get the fourth sheet\n","\n","def update_sheet(url, filename, filesize, md5_hash, index_version):\n"," data = sheet.get_all_records()\n"," df = pd.DataFrame(data)\n","\n"," if md5_hash in df['MD5 Hash'].values:\n"," idx = df[df['MD5 Hash'] == md5_hash].index[0]\n","\n"," # Update download count\n"," df.loc[idx, 'Download Counter'] = int(df.loc[idx, 'Download Counter']) + 1\n"," sheet.update_cell(idx+2, df.columns.get_loc('Download Counter') + 1, int(df.loc[idx, 'Download Counter']))\n","\n"," # Find the next available Alt URL field\n"," alt_url_cols = [col for col in df.columns if 'Alt URL' in col]\n"," alt_url_values = [df.loc[idx, col_name] for col_name in alt_url_cols]\n","\n"," # Check if url is the same as the main URL or any of the Alt URLs\n"," if url not in alt_url_values and url != df.loc[idx, 'URL']:\n"," for col_name in alt_url_cols:\n"," if df.loc[idx, col_name] == '':\n"," df.loc[idx, col_name] = url\n"," sheet.update_cell(idx+2, df.columns.get_loc(col_name) + 1, url)\n"," break\n"," else:\n"," # Prepare a new row as a dictionary\n"," new_row_dict = {'URL': url, 'Download Counter': 1, 'Filename': filename,\n"," 'Filesize (.pth)': filesize, 'MD5 Hash': md5_hash, 'RVC Version': index_version}\n","\n"," alt_url_cols = [col for col in df.columns if 'Alt URL' in col]\n"," for col in alt_url_cols:\n"," new_row_dict[col] = '' # Leave the Alt URL fields empty\n","\n"," # Convert fields other than 'Download Counter' and 'Filesize (.pth)' to string\n"," new_row_dict = {key: str(value) if key not in ['Download Counter', 'Filesize (.pth)'] else value for key, value in new_row_dict.items()}\n","\n"," # Append new row to sheet in the same order as existing columns\n"," ordered_row = [new_row_dict.get(col, '') for col in df.columns]\n"," sheet.append_row(ordered_row, value_input_option='RAW')\n","\n","condition1 = False\n","condition2 = False\n","already_downloaded = False\n","\n","# condition1 here is to check if the .index was imported. 2 is for if the .pth was.\n","\n","!rm -rf /content/unzips/\n","!rm -rf /content/zips/\n","!mkdir /content/unzips\n","!mkdir /content/zips\n","\n","def sanitize_directory(directory):\n"," for filename in os.listdir(directory):\n"," file_path = os.path.join(directory, filename)\n"," if os.path.isfile(file_path):\n"," if filename == \".DS_Store\" or filename.startswith(\"._\"):\n"," os.remove(file_path)\n"," elif os.path.isdir(file_path):\n"," sanitize_directory(file_path)\n","\n","url = 'https://huggingface.co/kalomaze/KanyeV2_Redux/resolve/main/KanyeV2_REDUX_40khz.zip' #@param {type:\"string\"}\n","model_zip = urlparse(url).path.split('/')[-2] + '.zip'\n","model_zip_path = '/content/zips/' + model_zip\n","\n","#@markdown This option should only be ticked if you don't want your model listed on the public tracker.\n","private_model = False #@param{type:\"boolean\"}\n","\n","if url != '':\n"," MODEL = \"\" # Initialize MODEL variable\n"," !mkdir -p /content/Retrieval-based-Voice-Conversion-WebUI/logs/$MODEL\n"," !mkdir -p /content/zips/\n"," !mkdir -p /content/Retrieval-based-Voice-Conversion-WebUI/weights/ # Create the 'weights' directory\n","\n"," if \"drive.google.com\" in url:\n"," !gdown $url --fuzzy -O \"$model_zip_path\"\n"," elif \"/blob/\" in url:\n"," url = url.replace(\"blob\", \"resolve\")\n"," print(\"Resolved URL:\", url) # Print the resolved URL\n"," !wget \"$url\" -O \"$model_zip_path\"\n"," elif \"mega.nz\" in url:\n"," m = Mega()\n"," print(\"Starting download from MEGA....\")\n"," m.download_url(url, '/content/zips')\n"," elif \"/tree/main\" in url:\n"," response = requests.get(url)\n"," soup = BeautifulSoup(response.content, 'html.parser')\n"," temp_url = ''\n"," for link in soup.find_all('a', href=True):\n"," if link['href'].endswith('.zip'):\n"," temp_url = link['href']\n"," break\n"," if temp_url:\n"," url = temp_url\n"," print(\"Updated URL:\", url) # Print the updated URL\n"," url = url.replace(\"blob\", \"resolve\")\n"," print(\"Resolved URL:\", url) # Print the resolved URL\n","\n"," if \"huggingface.co\" not in url:\n"," url = \"https://huggingface.co\" + url\n","\n"," !wget \"$url\" -O \"$model_zip_path\"\n"," else:\n"," print(\"No .zip file found on the page.\")\n"," # Handle the case when no .zip file is found\n"," else:\n"," !wget \"$url\" -O \"$model_zip_path\"\n","\n"," for filename in os.listdir(\"/content/zips\"):\n"," if filename.endswith(\".zip\"):\n"," zip_file = os.path.join(\"/content/zips\", filename)\n"," shutil.unpack_archive(zip_file, \"/content/unzips\", 'zip')\n","\n","sanitize_directory(\"/content/unzips\")\n","\n","def find_pth_file(folder):\n"," for root, dirs, files in os.walk(folder):\n"," for file in files:\n"," if file.endswith(\".pth\"):\n"," file_name = os.path.splitext(file)[0]\n"," if file_name.startswith(\"G_\") or file_name.startswith(\"P_\"):\n"," config_file = os.path.join(root, \"config.json\")\n"," if os.path.isfile(config_file):\n"," print(\"Outdated .pth detected! This is not compatible with the RVC method. Find the RVC equivalent model!\")\n"," continue # Continue searching for a valid file\n"," file_path = os.path.join(root, file)\n"," if os.path.getsize(file_path) > 100 * 1024 * 1024: # Check file size in bytes (100MB)\n"," print(\"Skipping unusable training file:\", file)\n"," continue # Continue searching for a valid file\n"," return file_name\n"," return None\n","\n","MODEL = find_pth_file(\"/content/unzips\")\n","if MODEL is not None:\n"," print(\"Found .pth file:\", MODEL + \".pth\")\n","else:\n"," print(\"Error: Could not find a valid .pth file within the extracted zip.\")\n"," print(\"If there's an error above this talking about 'Access denied', try one of the Alt URLs in the Google Sheets for this model.\")\n"," MODEL = \"\"\n"," global condition3\n"," condition3 = True\n","\n","index_path = \"\"\n","\n","def find_version_number(index_path):\n"," if condition2 and not condition1:\n"," if file_size >= 55180000:\n"," return 'RVC v2'\n"," else:\n"," return 'RVC v1'\n","\n"," filename = os.path.basename(index_path)\n","\n"," if filename.endswith(\"_v2.index\"):\n"," return 'RVC v2'\n"," elif filename.endswith(\"_v1.index\"):\n"," return 'RVC v1'\n"," else:\n"," if file_size >= 55180000:\n"," return 'RVC v2'\n"," else:\n"," return 'RVC v1'\n","\n","if MODEL != \"\":\n"," # Move model into logs folder\n"," for root, dirs, files in os.walk('/content/unzips'):\n"," for file in files:\n"," file_path = os.path.join(root, file)\n"," if file.endswith(\".index\"):\n"," print(\"Found index file:\", file)\n"," condition1 = True\n"," logs_folder = os.path.join('/content/Retrieval-based-Voice-Conversion-WebUI/logs', MODEL)\n"," os.makedirs(logs_folder, exist_ok=True) # Create the logs folder if it doesn't exist\n","\n"," # Delete identical .index file if it exists\n"," if file.endswith(\".index\"):\n"," identical_index_path = os.path.join(logs_folder, file)\n"," if os.path.exists(identical_index_path):\n"," os.remove(identical_index_path)\n","\n"," shutil.move(file_path, logs_folder)\n"," index_path = os.path.join(logs_folder, file) # Set index_path variable\n","\n"," elif \"G_\" not in file and \"D_\" not in file and file.endswith(\".pth\"):\n"," destination_path = f'/content/Retrieval-based-Voice-Conversion-WebUI/weights/{MODEL}.pth'\n"," if os.path.exists(destination_path):\n"," print(\"You already downloaded this model. Re-importing anyways..\")\n"," already_downloaded = True\n"," shutil.move(file_path, destination_path)\n"," condition2 = True\n"," if already_downloaded is False and os.path.exists(config_path):\n"," file_size = os.path.getsize(destination_path) # Get file size\n"," md5_hash = calculate_md5(destination_path) # Calculate md5 hash\n"," index_version = find_version_number(index_path) # Get the index version\n","\n","if condition1 is False:\n"," logs_folder = os.path.join('/content/Retrieval-based-Voice-Conversion-WebUI/logs', MODEL)\n"," os.makedirs(logs_folder, exist_ok=True)\n","# this is here so it doesnt crash if the model is missing an index for some reason\n","\n","if condition2 and not condition1:\n"," print(\"Model partially imported! No .index file was found in the model download. The author may have forgotten to add the index file.\")\n"," if already_downloaded is False and os.path.exists(config_path) and not private_model:\n"," update_sheet(url, MODEL, file_size, md5_hash, index_version)\n","\n","elif condition1 and condition2:\n"," print(\"Model successfully imported!\")\n"," if already_downloaded is False and os.path.exists(config_path) and not private_model:\n"," update_sheet(url, MODEL, file_size, md5_hash, index_version)\n","\n","elif condition3:\n"," pass # Do nothing when condition3 is true\n","else:\n"," print(\"URL cannot be left empty. If you don't want to download a model now, just skip this step.\")\n","\n","!rm -r /content/unzips/\n","!rm -r /content/zips/"],"metadata":{"id":"OVQoLQJXS7WX","cellView":"form"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@markdown #Step 3. Upload your files\n","#@markdown Run this cell to upload your vocal files that you want to use, (or zip files containing audio) to your Colab. <br>\n","#@markdown Alternatively, you can upload from the colab files panel as seen in the video, but this should be more convenient. This method may not work on iOS.\n","from google.colab import files\n","from IPython.display import display, Javascript\n","import os\n","import shutil\n","import zipfile\n","import ipywidgets as widgets\n","\n","# Create the target directory if it doesn't exist\n","target_dir = '/content/audio_files/'\n","if not os.path.exists(target_dir):\n"," os.makedirs(target_dir)\n","\n","uploaded = files.upload()\n","\n","for fn in uploaded.keys():\n"," # Check if the uploaded file is a zip file\n"," if fn.endswith('.zip'):\n"," # Write the uploaded zip file to the target directory\n"," zip_path = os.path.join(target_dir, fn)\n"," with open(zip_path, 'wb') as f:\n"," f.write(uploaded[fn])\n","\n"," unzip_dir = os.path.join(target_dir, fn[:-4]) # Remove the .zip extension from the folder name\n","\n"," # Extract the zip file\n"," with zipfile.ZipFile(zip_path, 'r') as zip_ref:\n"," zip_ref.extractall(unzip_dir)\n","\n"," # Delete the zip file\n"," if os.path.exists(zip_path):\n"," os.remove(zip_path)\n","\n"," print('Zip file \"{name}\" extracted and removed. Files are in: {folder}'.format(name=fn, folder=unzip_dir))\n","\n"," # Display copy path buttons for each extracted file\n"," for extracted_file in os.listdir(unzip_dir):\n"," extracted_file_path = os.path.join(unzip_dir, extracted_file)\n"," extracted_file_length = os.path.getsize(extracted_file_path)\n","\n"," extracted_file_label = widgets.HTML(\n"," value='Extracted file \"{name}\" with length {length} bytes'.format(name=extracted_file, length=extracted_file_length)\n"," )\n"," display(extracted_file_label)\n","\n"," extracted_file_path_text = widgets.HTML(\n"," value='File saved to: <a href=\"{}\" target=\"_blank\">{}</a>'.format(extracted_file_path, extracted_file_path)\n"," )\n","\n"," extracted_copy_button = widgets.Button(description='Copy')\n"," extracted_copy_button_file_path = extracted_file_path # Make a local copy of the file path\n","\n"," def copy_to_clipboard(b):\n"," js_code = '''\n"," const el = document.createElement('textarea');\n"," el.value = \"{path}\";\n"," el.setAttribute('readonly', '');\n"," el.style.position = 'absolute';\n"," el.style.left = '-9999px';\n"," document.body.appendChild(el);\n"," el.select();\n"," document.execCommand('copy');\n"," document.body.removeChild(el);\n"," '''\n"," display(Javascript(js_code.format(path=extracted_copy_button_file_path)))\n","\n"," extracted_copy_button.on_click(copy_to_clipboard)\n"," display(widgets.HBox([extracted_file_path_text, extracted_copy_button]))\n","\n"," continue\n","\n"," # For non-zip files\n"," # Save the file to the target directory\n"," file_path = os.path.join(target_dir, fn)\n"," with open(file_path, 'wb') as f:\n"," f.write(uploaded[fn])\n","\n"," file_length = len(uploaded[fn])\n"," file_label = widgets.HTML(\n"," value='User uploaded file \"{name}\" with length {length} bytes'.format(name=fn, length=file_length)\n"," )\n"," display(file_label)\n","\n"," # Check if the uploaded file is a .pth or .index file\n"," if fn.endswith('.pth') or fn.endswith('.index'):\n"," warning_text = widgets.HTML(\n"," value='<b style=\"color: red;\">Warning:</b> You are uploading a model file in the wrong place. Please ensure it is uploaded to the correct location.'\n"," )\n"," display(warning_text)\n","\n"," # Create a clickable path with copy button\n"," file_path_text = widgets.HTML(\n"," value='File saved to: <a href=\"{}\" target=\"_blank\">{}</a>'.format(file_path, file_path)\n"," )\n","\n"," copy_button = widgets.Button(description='Copy')\n"," copy_button_file_path = file_path # Make a local copy of the file path\n","\n"," def copy_to_clipboard(b):\n"," js_code = '''\n"," const el = document.createElement('textarea');\n"," el.value = \"{path}\";\n"," el.setAttribute('readonly', '');\n"," el.style.position = 'absolute';\n"," el.style.left = '-9999px';\n"," document.body.appendChild(el);\n"," el.select();\n"," document.execCommand('copy');\n"," document.body.removeChild(el);\n"," '''\n"," display(Javascript(js_code.format(path=copy_button_file_path)))\n","\n"," copy_button.on_click(copy_to_clipboard)\n"," display(widgets.HBox([file_path_text, copy_button]))\n","\n","# Remove the original uploaded files from /content/\n","for fn in uploaded.keys():\n"," if os.path.exists(os.path.join(\"/content/\", fn)):\n"," os.remove(os.path.join(\"/content/\", fn))"],"metadata":{"cellView":"form","id":"gh-HHZ8jJBVp"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@markdown ##Click this to load a DATASET instead.\n","DATASET = \"PaulTrimmed.zip\" #@param {type:\"string\"}\n","#@markdown This will look for that zip inside your 'dataset' folder in google drive. (Fixed)\n","\n","import os\n","import shutil\n","from glob import glob\n","import concurrent.futures\n","import subprocess\n","\n","def sanitize_directory(directory):\n"," for filename in os.listdir(directory):\n"," file_path = os.path.join(directory, filename)\n"," if os.path.isfile(file_path):\n"," if filename == \".DS_Store\" or filename.startswith(\"._\") or not filename.endswith(('.wav', '.flac', '.mp3', '.ogg', '.m4a')):\n"," os.remove(file_path)\n"," elif os.path.isdir(file_path):\n"," sanitize_directory(file_path)\n","\n","def convert_file(source_file, output_filename_converted):\n"," # Check if the input file is 16-bit\n"," probe_cmd = f'ffprobe -v error -select_streams a:0 -show_entries stream=sample_fmt -of default=noprint_wrappers=1:nokey=1 \"{source_file}\"'\n"," sample_format = subprocess.run(probe_cmd, shell=True, text=True, capture_output=True).stdout.strip()\n","\n"," # Use appropriate ffmpeg command based on sample format\n"," if sample_format == 's16':\n"," # Export as 16-bit WAV\n"," cmd = f'ffmpeg -i \"{source_file}\" -c:a pcm_s16le \"{output_filename_converted}\"'\n"," else:\n"," # Export as 32-bit float WAV (default behavior)\n"," cmd = f'ffmpeg -i \"{source_file}\" -c:a pcm_f32le \"{output_filename_converted}\"'\n","\n"," process = subprocess.run(cmd, shell=True)\n"," if process.returncode != 0:\n"," print(f'Failed to convert {source_file}. The file may be corrupt.')\n"," else:\n"," os.remove(source_file)\n","\n","def convert_audio_files(source_dir, dest_dir):\n"," with concurrent.futures.ProcessPoolExecutor() as executor:\n"," for root, _, files in os.walk(source_dir):\n"," for filename in files:\n"," file_ext = os.path.splitext(filename)[1].lower()\n"," if file_ext in ['.wav', '.flac', '.mp3', '.ogg', '.m4a']:\n"," source_file = os.path.join(root, filename)\n"," output_filename = os.path.join(dest_dir, filename)\n"," output_filename_converted = os.path.splitext(output_filename)[0] + '_converted.wav'\n"," executor.submit(convert_file, source_file, output_filename_converted)\n","\n","dataset_path = '/content/drive/MyDrive/dataset/' + DATASET\n","final_directory = '/content/dataset'\n","temp_directory = '/content/temp_dataset'\n","\n","try:\n"," if os.path.exists(final_directory):\n"," shutil.rmtree(final_directory)\n"," print(\"Dataset folder already found. Wiping clean for import operation...\")\n","except Exception as e:\n"," print(f\"Error in removing the final directory: {e}\")\n","\n","try:\n"," if not os.path.exists(dataset_path):\n"," raise Exception(f'There is no {DATASET} in {os.path.dirname(dataset_path)}')\n","except Exception as e:\n"," print(f\"Error in verifying dataset: {e}\")\n","\n","try:\n"," os.makedirs(final_directory, exist_ok=True)\n"," os.makedirs(temp_directory, exist_ok=True)\n","except Exception as e:\n"," print(f\"Error in creating directories: {e}\")\n","\n","try:\n"," # Unzip data into a temporary directory\n"," !unzip -d {temp_directory} -B {dataset_path}\n","except Exception as e:\n"," print(f\"Error in unzipping data: {e}\")\n","\n","try:\n"," # Sanitize temporary directory\n"," sanitize_directory(temp_directory)\n","except Exception as e:\n"," print(f\"Error in sanitizing directory: {e}\")\n","\n","try:\n"," # Convert audio files and move them to the final directory\n"," convert_audio_files(temp_directory, final_directory)\n","except Exception as e:\n"," print(f\"Error in converting audio files: {e}\")\n","\n","try:\n"," # Clean up temp directory\n"," shutil.rmtree(temp_directory)\n","except Exception as e:\n"," print(f\"Error in removing temp directory: {e}\")\n","\n","try:\n"," # Rename files if needed\n"," !rename 's/(\\w+)\\.(\\w+)~(\\d*)/$1_$3.$2/' {final_directory}/*.*~*\n","except Exception as e:\n"," print(f\"Error in renaming files: {e}\")\n","\n","print('Dataset imported. You can now copy the path of the dataset folder to the training path.')"],"metadata":{"id":"Mwk7Q0Loqzjx","cellView":"form"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["#Step 3. Run the GUI by tapping on the public URL. It's gonna look like this:\n","![alt text](https://drive.google.com/uc?id=1YpraB1Fc8B24TCtdzOo_AmzMMGoZXZ2e)\n"],"metadata":{"id":"dGDewjhS7wXS"}},{"cell_type":"code","source":["import os\n","import threading\n","import time\n","from utils import backups\n","\n","#@markdown #Click here to run the GUI\n","\n","#@markdown Keep this option enabled to use the simplified, easy interface.\n","easy_gui = False #@param{type:\"boolean\"}\n","\n","#@markdown Keep this option enabled to use automatic backups feature.\n","auto_backups = True #@param{type:\"boolean\"}\n","\n","#@markdown On this colab, the TensorBoard is automatically loaded. This lets you track advanced training statistics (not relevant for using existing models).\n","#@markdown <br> The important one being, loss/g/total. To avoid overtraining, watch the value and wait till it starts to rise again. <br>\n","#@markdown Overtraining is much more likely to happen on v2 weights. This is not necessarily a bad thing, as it means models will be finished sooner. <br>\n","#@markdown <div style=\"display:flex; justify-content:center\">\n","#@markdown <div style=\"margin-right:10px\">\n","#@markdown <img src=\"https://media.discordapp.net/attachments/1089076875999072302/1113732090391969792/image.png\" width=\"700\">\n","#@markdown </div>\n","#@markdown </div>\n","\n","#@markdown Follow the whole training guide here: <br> https://docs.google.com/document/d/13ebnzmeEBc6uzYCMt-QVFQk-whVrK4zw8k7_Lw3Bv_A/edit?usp=sharing\n","\n","LOGS_FOLDER = '/content/Retrieval-based-Voice-Conversion-WebUI/logs'\n","if not os.path.exists(LOGS_FOLDER):\n"," os.makedirs(LOGS_FOLDER)\n","\n","WEIGHTS_FOLDER = '/content/Retrieval-based-Voice-Conversion-WebUI/weights'\n","if not os.path.exists(WEIGHTS_FOLDER):\n"," os.makedirs(WEIGHTS_FOLDER)\n","\n","def extract_wav2lip_tar_files():\n"," !wget -P /content/ https://github.com/777gt/EVC/raw/main/wav2lip-HD.tar.gz\n"," !wget -P /content/ https://github.com/777gt/EVC/raw/main/wav2lip-cache.tar.gz\n","\n"," with tarfile.open('/content/wav2lip-cache.tar.gz', 'r:gz') as tar:\n"," for member in tar.getmembers():\n"," target_path = os.path.join('/', member.name)\n"," try:\n"," tar.extract(member, '/')\n"," except:\n"," pass\n"," with tarfile.open('/content/wav2lip-HD.tar.gz') as tar:\n"," tar.extractall('/content')\n","\n","def start_web_server():\n"," %cd /content/Retrieval-based-Voice-Conversion-WebUI\n"," %load_ext tensorboard\n"," %tensorboard --logdir /content/Retrieval-based-Voice-Conversion-WebUI/logs\n"," !mkdir -p /content/Retrieval-based-Voice-Conversion-WebUI/audios\n"," if easy_gui:\n"," !pip install -q gTTS\n"," !pip install -q elevenlabs\n"," !wget https://github.com/777gt/-EVC-/raw/main/audios/someguy.mp3 -P /content/Retrieval-based-Voice-Conversion-WebUI/audios/\n"," !wget https://github.com/777gt/-EVC-/raw/main/audios/somegirl.mp3 -P /content/Retrieval-based-Voice-Conversion-WebUI/audios/\n"," extract_wav2lip_tar_files()\n"," !python3 EasierGUI.py --colab --pycmd python3\n"," else:\n"," !python3 infer-web.py --colab --pycmd python3\n","\n","# Import the Google Drive backup before starting the server only if auto_backups is True\n","if auto_backups:\n"," backups.import_google_drive_backup()\n","\n","\n","# Start the web server in a separate thread\n","web_server_thread = threading.Thread(target=start_web_server)\n","web_server_thread.start()\n","\n","# Run the backup loop in the main thread only if auto_backups is True\n","if auto_backups:\n"," backups.backup_files()\n","else:\n"," while True:\n"," time.sleep(10) # sleep for 10 seconds"],"metadata":{"id":"7vh6vphDwO0b","cellView":"form"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["# Step 4. If you need to save a model to your RVC folder, choose a method."],"metadata":{"id":"TNd_AYmtodr4"}},{"cell_type":"code","source":["#@markdown # Save finished model(s) as zip files (to Drive)\n","#@markdown If you have completed training a model and want to save it\n","#@markdown for future use, without any extra files for training, you can run this cell.\n","#@markdown <br>Alternatively, you can manually create it by getting the added_ .index file (the added one not the 'trained' one) from `/RVC_Backup/` on your Drive and zipping it along with the .pth in `/RVC_Backup/weights/`\n","\n","import os\n","import shutil\n","import zipfile\n","import re # Import the regex module\n","\n","logs_dir = '/content/Retrieval-based-Voice-Conversion-WebUI/logs/'\n","weights_dir = '/content/Retrieval-based-Voice-Conversion-WebUI/weights/'\n","output_dir = '/content/drive/MyDrive/RVC_Backup/Finished/'\n","zip_output_dir = '/content/finalzips_forcopying/'\n","directories = ['/content/finalsavetemp', '/content/finalzips_forcopying']\n","\n","# Delete directories if they exist\n","for directory in directories:\n"," if os.path.exists(directory):\n"," shutil.rmtree(directory)\n","\n","# Create the output directories if they don't exist\n","os.makedirs(output_dir, exist_ok=True)\n","os.makedirs(zip_output_dir, exist_ok=True)\n","\n","# Find .pth files in weights directory\n","pth_files = [file for file in os.listdir(weights_dir) if file.endswith('.pth')]\n","\n","skipped_files = set() # Keep track of base names of skipped files\n","\n","for pth_file in pth_files:\n"," match = re.search(r'(.*)_s\\d+.pth$', pth_file)\n"," if match: # Skip if file ends with _s followed by a number\n"," base_name = match.group(1) # Get the base file name (before the `_s<number>` suffix)\n"," if base_name not in skipped_files:\n"," print(f'Skipping autosave epoch files for {base_name}.')\n"," skipped_files.add(base_name)\n"," continue\n","\n"," print(f'Processing file: {pth_file}')\n"," folder = os.path.splitext(pth_file)[0]\n","\n"," finalsavetemp_dir = '/content/finalsavetemp/'\n"," os.makedirs(finalsavetemp_dir, exist_ok=True)\n"," shutil.copy2(os.path.join(weights_dir, pth_file), finalsavetemp_dir)\n","\n"," if os.path.isdir(os.path.join(logs_dir, folder)):\n"," index_files = [\n"," file for file in os.listdir(os.path.join(logs_dir, folder))\n"," if file.startswith('added') and file.endswith('.index')\n"," ]\n","\n"," if index_files:\n"," latest_index_file = max(\n"," index_files,\n"," key=lambda x: os.path.getmtime(os.path.join(logs_dir, folder, x))\n"," )\n"," shutil.copy2(\n"," os.path.join(logs_dir, folder, latest_index_file),\n"," finalsavetemp_dir\n"," )\n"," print(f'Found matching .index file: {latest_index_file}')\n"," else:\n"," print(\"Model with no .index detected. Please regenerate using 'train feature index' if you are training it yourself\")\n"," else:\n"," print(\"Model with no .index detected. Please regenerate using 'train feature index' if you are training it yourself\")\n","\n"," # Create zip and write files into it\n"," with zipfile.ZipFile(os.path.join(zip_output_dir, f'{folder}.zip'), 'w') as zipf:\n"," for root, dirs, files in os.walk(finalsavetemp_dir):\n"," for file in files:\n"," zipf.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), finalsavetemp_dir))\n","\n"," print(f'Created zip file for {folder}.')\n","\n"," # Remove 'finalsavetemp'\n"," shutil.rmtree(finalsavetemp_dir)\n","\n"," # Copy the finished zip file to the output directory\n"," shutil.copy2(os.path.join(zip_output_dir, f'{folder}.zip'), output_dir)\n"," print(f'Copied {folder}.zip to output directory: {output_dir}')\n","\n","print('Backup process completed.')\n","print('Finished zips copied to /content/drive/MyDrive/RVC_Backup/Finished.')\n","\n","# Delete directories if they exist\n","for directory in directories:\n"," if os.path.exists(directory):\n"," shutil.rmtree(directory)"],"metadata":{"id":"MErtbNbp4wn0","cellView":"form"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@markdown # Backup your model(s) training data from /logs/ as .zip files (to your Drive)\n","#@markdown This colab should already auto backup everything in `/weights/` or `/logs/` to `/RVC_Backup/` on your drive if you have free space; therefore, this isn't necessary.\n","#@markdown <br> If that somehow fails, you can use this cell to make each folder in /logs/ a zip file, one by one.\n","import os\n","import shutil\n","\n","logs_dir = '/content/Retrieval-based-Voice-Conversion-WebUI/logs/'\n","output_dir = '/content/drive/MyDrive/RVC_Backup/ManualTrainingBackup'\n","\n","# Get a list of all folders in the logs directory\n","folders = [folder for folder in os.listdir(logs_dir) if os.path.isdir(os.path.join(logs_dir, folder))]\n","\n","# Create the output directory if it doesn't exist\n","os.makedirs(output_dir, exist_ok=True)\n","\n","# Iterate over each folder and zip it\n","for folder in folders:\n"," folder_path = os.path.join(logs_dir, folder)\n"," zip_file_path = os.path.join(output_dir, f'{folder}_TrainingData.zip') # Change here\n","\n"," # Check if the zip file already exists in the output directory\n"," if os.path.exists(zip_file_path):\n"," existing_size = os.path.getsize(zip_file_path)\n"," shutil.make_archive(folder_path, 'zip', folder_path)\n"," new_size = os.path.getsize(f'{folder_path}.zip')\n"," if existing_size == new_size:\n"," print(f'Skipped {folder} because a zip with the same name and size already exists in {output_dir}')\n"," continue\n","\n"," # Zip the folder\n"," shutil.make_archive(folder_path, 'zip', folder_path)\n","\n"," # Move the zip file to the output directory\n"," shutil.move(f'{folder_path}.zip', zip_file_path)\n","\n"," print(f'Zipped {folder} and saved it as {zip_file_path}')"],"metadata":{"id":"8lvrCh7T3BOV","cellView":"form"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["#Extra Stuff (These are tools to make your job easier)"],"metadata":{"id":"p9SHghdUw2O_"}},{"cell_type":"code","source":["#@markdown #Text To Speech GUI\n","from IPython.display import clear_output\n","if not \"tts_installed\" in locals():\n"," %cd /content/\n"," !pip uninstall -y cmake\n"," !wget https://github.com/Kitware/CMake/releases/download/v3.22.1/cmake-3.22.1-linux-x86_64.tar.gz\n"," !tar xf cmake-3.22.1-linux-x86_64.tar.gz\n"," !rm cmake-3.22.1-linux-x86_64.tar.gz\n"," !PATH=$PATH:/content/cmake-3.22.1-linux-x86_64/bin\n"," import os\n"," os.environ[\"PATH\"] += \":/content/cmake-3.22.1-linux-x86_64/bin\"\n"," !apt-get install espeak\n"," !git clone https://github.com/log1stics/voice-generator-webui\n"," %cd voice-generator-webui\n"," !chmod +x setup.sh\n"," !./setup.sh\n"," clear_output()\n"," tts_installed=True\n","%cd /content/Retrieval-based-Voice-Conversion-WebUI/weights/\n","!for file in *.pth; do folder=\"${file%.pth}\"; mkdir -p \"/content/voice-generator-webui/vc/models/$folder\"; cp \"$file\" \"/content/voice-generator-webui/vc/models/$folder\"; mv \"$folder\" \"/content/voice-generator-webui/vc/models\"; done\n","%cd /content/voice-generator-webui\n","!python3 webui.py --colab"],"metadata":{"id":"Y-6VkSiqXQcH","cellView":"form"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["import os\n","import os.path\n","import shutil\n","#@title Manual Zip loading from Google Drive\n","\n","#@markdown Model Zip Location\n","\n","MODELLOCATION = \"/content/drive/MyDrive/b10.zip\" #@param {type:\"string\"}\n","\n","!mkdir -p /content/Retrieval-based-Voice-Conversion-WebUI/logs/{MODELNAME}\n","!mkdir -p /content/unzips/{MODELNAME}/\n","!unzip -d /content/unzips/{MODELNAME} -B {MODELLOCATION}\n","\n","# Set your source and destination directories\n","source_dir = os.path.join(\"/content/unzips/\", MODELNAME)\n","#@markdown If you use this, you'll have to move the files manually."],"metadata":{"id":"zcojhbN2R355","cellView":"form"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@title Easy Dataset Maker (not necessary to split manually on RVC anymore I believe)\n","#@markdown Just upload the .wav acapellas you want into the **EasyDataset** folder (make sure it is good quality stuff, please)\n","#@markdown Do not use spaces, weird symbols, or anything like that.\n","if not \"pydub_installed\" in locals():\n"," !pip install pydub --quiet\n"," pydub_installed=True\n","\n","from pydub import AudioSegment\n","import os, shutil, wave\n","from google.colab import files\n","auto_delete_original_acapella=True#@param {type:\"boolean\"}\n","\n","save_to_drive=True#@param {type:\"boolean\"}\n","#@markdown Choose a name for your dataset (you will use this later in the GUI)\n","dataset_name='mydataset'#@param {type:\"string\"}\n","if not \"installed_pydub\" in locals():\n"," !pip install pydub --quiet\n","\n","if not os.path.exists('/content/EasyDataset'):\n"," !mkdir -p /content/EasyDataset\n"," os.chdir('/content/EasyDataset')\n"," print(\"Upload some files.\")\n"," uploaded = files.upload()\n","else:\n"," os.chdir('/content/EasyDataset')\n"," if not os.listdir():\n"," print(\"Upload some files.\")\n"," uploaded = files.upload()\n","\n","for filename in os.listdir():\n"," if filename.endswith(\".wav\"):\n"," sound = AudioSegment.from_wav(filename)\n"," sound = sound.set_channels(1)\n"," new_filename = filename\n"," sound.export('mono_'+new_filename, format=\"wav\")\n"," os.remove(filename)\n","\n","# define the length of each clip in seconds\n","clip_length = 10\n","# iterate over all .wav files in the current directory\n","for filename in os.listdir():\n"," if not filename.endswith('.wav'):\n"," continue\n"," # open the WAV file and get the sample rate\n"," wav_file = wave.open(filename, 'rb')\n"," sample_rate = wav_file.getframerate()\n"," # calculate the number of frames in each clip\n"," clip_frames = clip_length * sample_rate\n"," # iterate over each clip and write it to a new file\n"," for i in range(int(wav_file.getnframes() / clip_frames) + 1):\n"," clip_name = f\"{filename.split('.')[0]}_{i+1}.wav\"\n"," clip_path = 'split_'+clip_name\n"," clip_start = i * clip_frames\n"," clip_end = min((i+1) * clip_frames, wav_file.getnframes())\n","\n"," # write the clip to a new file\n"," with wave.open(clip_path, 'wb') as clip_file:\n"," clip_file.setparams(wav_file.getparams())\n"," clip_file.writeframes(wav_file.readframes(clip_end - clip_start))\n"," # close the original file\n"," wav_file.close()\n"," os.remove(filename)\n","!mkdir -p /content/dataset/{dataset_name}\n","for everything in os.listdir('/content/EasyDataset'):\n"," shutil.move(everything, f'/content/dataset/{dataset_name}')\n","!ls -a /content/dataset/\n","!rename 's/(\\w+)\\.(\\w+)~(\\d*)/$1_$3.$2/' /content/dataset/*.*~*\n","os.chdir(f'/content/dataset')\n","print(f\"Your dataset has been saved to: /content/dataset/{dataset_name}\")\n","if auto_delete_original_acapella:\n"," shutil.rmtree('/content/EasyDataset')\n"," !mkdir -p /content/EasyDataset\n","if save_to_drive:\n"," !zip -r {dataset_name}.zip {dataset_name}\n"," shutil.move(f'/content/dataset/{dataset_name}.zip','/content/drive/MyDrive/dataset')\n","os.chdir('/content')"],"metadata":{"cellView":"form","id":"dF8MCnjxldPC"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["#**EDIT 6/15:** Fixed gradio dependency error. Please go to Runtime > 'Disconnect and delete runtime' if it wasn't working; should work again from here on out.\n","\n","## **Also, consider donating!**\n","\n","By the way, my Ko-fi is https://ko-fi.com/kalomaze if you would like to donate to help keep this thing running, and so I can potentially pay for new features:\n","- ElevenLabs to RVC Text-to-speech tool (would allow for free TTS generations with RVC)\n","- Automatic model archiving (backing up models to a huge central repository is the plan - unlimited storage hosting costs a bit). Would be useful when models are deleted or falsely taken down.<br>\n","\n","Your support would be greatly appreciated! On top of maintaining this colab, I also write and maintain the Google Docs guides, and plan to create a video tutorial for training voices in the future."],"metadata":{"id":"uahhqcP_LuZi"}},{"cell_type":"markdown","source":["#UVR Colab Method (MDX-Net)"],"metadata":{"id":"N5hRDyb8D5XU"}},{"cell_type":"code","source":["initialised = True\n","from time import sleep\n","from google.colab import output\n","from google.colab import drive\n","\n","import sys\n","import os\n","import shutil\n","import psutil\n","import glob\n","\n","mount_to_drive = True\n","mount_path = '/content/drive/MyDrive'\n","\n","ai = 'https://github.com/kae0-0/Colab-for-MDX_B'\n","ai_version = 'https://github.com/kae0-0/Colab-for-MDX_B/raw/main/v'\n","onnx_list = 'https://raw.githubusercontent.com/kae0-0/Colab-for-MDX_B/main/onnx_list'\n","#@title Initialize UVR MDX-Net Models\n","#@markdown The 'ForceUpdate' option will update the models by fully reinstalling.\n","ForceUpdate = True #@param {type:\"boolean\"}\n","class h:\n"," def __enter__(self):\n"," self._original_stdout = sys.stdout\n"," sys.stdout = open(os.devnull, 'w')\n"," def __exit__(self, exc_type, exc_val, exc_tb):\n"," sys.stdout.close()\n"," sys.stdout = self._original_stdout\n","def get_size(bytes, suffix='B'): # read ram\n"," global svmem\n"," factor = 1024\n"," for unit in [\"\", \"K\", \"M\", \"G\", \"T\", \"P\"]:\n"," if bytes < factor:\n"," return f'{bytes:.2f}{unit}{suffix}'\n"," bytes /= factor\n"," svmem = psutil.virtual_memory()\n","def console(t):\n"," get_ipython().system(t)\n","def LinUzip(file): # unzip call linux, force replace\n"," console(f'unzip -o {file}')\n","#-------------------------------------------------------\n","def getONNX():\n"," console(f'wget {onnx_list} -O onnx_list')\n"," _onnx = open(\"onnx_list\", \"r\")\n"," _onnx = _onnx.readlines()\n"," os.remove('onnx_list')\n"," for model in _onnx:\n"," _model = sanitize_filename(os.path.basename(model))\n"," console(f'wget {model}')\n"," LinUzip(_model)\n"," os.remove(_model)\n","\n","def getDemucs(_path):\n"," #https://dl.fbaipublicfiles.com/demucs/v3.0/demucs_extra-3646af93.th\n"," root = \"https://dl.fbaipublicfiles.com/demucs/v3.0/\"\n"," model = {\n"," 'demucs_extra': '3646af93'\n"," }\n"," for models in zip(model.keys(),model.values()):\n"," console(f'wget {root+models[0]+\"-\"+models[1]}.th -O {models[0]}.th')\n"," for _ in glob.glob('*.th'):\n"," if os.path.isfile(os.path.join(os.getcwd(),_path,_)):\n"," os.remove(os.path.join(os.getcwd(),_path,_))\n"," shutil.move(_,_path)\n","\n","def mount(gdrive=False):\n"," if gdrive:\n"," if not os.path.exists(\"/content/drive/MyDrive\"):\n"," try:\n"," drive.mount(\"/content/drive\", force_remount=True)\n"," except:\n"," drive._mount(\"/content/drive\", force_remount=True)\n"," else:\n"," pass\n","\n","mount(mount_to_drive)\n","\n","def toPath(path='local'):\n"," if path == 'local':\n"," os.chdir('/content')\n"," elif path == 'gdrive':\n"," os.chdir(mount_path)\n","\n","def update():\n"," with h():\n"," console(f'wget {ai_version} -O nver')\n"," f = open('nver', 'r')\n"," nver = f.read()\n"," f = open('v', 'r')\n"," cver = f.read()\n"," if nver != cver or ForceUpdate:\n"," print('New update found! {}'.format(nver))\n"," os.chdir('../')\n"," print('Updating ai...',end=' ')\n"," with h():\n"," console(f'git clone {ai} temp_MDX_Colab')\n"," console('cp -a temp_MDX_Colab/* MDX_Colab/')\n"," console('rm -rf temp_MDX_Colab')\n"," print('done')\n"," os.chdir('MDX_Colab')\n"," print('Refreshing models...', end=' ')\n"," with h():\n"," getDemucs('model/')\n"," getONNX()\n"," print('done')\n"," output.clear()\n"," os.remove('v')\n"," os.rename(\"nver\",'v')\n"," #os.chdir(f'{os.path.join(mount_path,\"MDX_Colab\")}')\n"," else:\n"," os.remove('nver')\n"," print('Using latest version.')\n","\n","def past_installation():\n"," return os.path.exists('MDX_Colab')\n","\n","def LoadMDX():\n"," console(f'git clone {ai} MDX_Colab')\n","\n","#-------------------------------------------------------\n","# install requirements\n","print('Installing dependencies will take 45 seconds...',end=' ')\n","\n","gpu_info = !nvidia-smi\n","gpu_info = '\\n'.join(gpu_info)\n","if gpu_info.find('failed') >= 0:\n"," svmem = psutil.virtual_memory()\n"," gpu_runtime = False\n"," with h():\n"," console('pip3 install onnxruntime==1.14.1')\n","else:\n"," gpu_runtime = True\n"," with h():\n"," console('pip3 install onnxruntime-gpu==1.14.1')\n","with h():\n"," deps = [\n"," 'pathvalidate',\n"," 'youtube-dl',\n"," 'django'\n"," ]\n"," for dep in deps:\n"," console('pip3 install {}'.format(dep))\n","# import modules\n","#console('pip3 install torch==1.13.1')\n","console('pip3 install soundfile==0.12.1')\n","console('pip3 install librosa==0.9.1')\n","from pathvalidate import sanitize_filename\n","print('done')\n","if not gpu_runtime:\n"," print(f'GPU runtime is disabled. You have {get_size(svmem.total)} RAM.\\nProcessing will be incredibly slow. 😈')\n","elif gpu_info.find('Tesla T4') >= 0:\n"," print('You got a Tesla T4 GPU. (speeds are around 10-25 it/s)')\n","elif gpu_info.find('Tesla P4') >= 0:\n"," print('You got a Tesla P4 GPU. (speeds are around 8-22 it/s)')\n","elif gpu_info.find('Tesla K80') >= 0:\n"," print('You got a Tesla K80 GPU. (This is the common gpu, speeds are around 2-10 it/s)')\n","elif gpu_info.find('Tesla P100') >= 0:\n"," print('You got a Tesla P100 GPU. (This is the Second to the fastest gpu, speeds are around 15-42 it/s)')\n","else:\n"," if gpu_runtime:\n"," print('You got an unknown GPU. Please report the GPU you got!')\n"," !nvidia-smi\n","\n","#console('pip3 install demucs')\n","#-------------------------------------------------------\n","# Scripting\n","mount(mount_to_drive)\n","toPath('gdrive' if mount_to_drive else 'local')\n","#check for MDX existence\n","if not past_installation():\n"," print('First time installation will take around 3-6 minutes.\\nThis requires around 2-3 GB Free Gdrive space.\\nPlease try not to interup installation process!!')\n"," print('Downloading AI...',end=' ')\n"," with h():\n"," LoadMDX()\n"," os.chdir('MDX_Colab')\n"," print('done')\n","\n"," print('Downloading models...',end=' ')\n"," with h():\n"," getDemucs('model/')\n"," getONNX()\n"," if os.path.isfile('onnx_list'):\n"," os.remove('onnx_list')\n"," print('done')\n","\n","else:\n"," os.chdir('MDX_Colab')\n"," update()\n","\n","################\n","#outro\n","print('Success!')"],"metadata":{"cellView":"form","id":"u61Z3hTK5mAE"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["#@markdown ##Click this to import a ZIP of AUDIO FILES (for isolation.)\n","#@markdown *Or*, you can import your audio files into the /tracks/ folder in the MDX_Colab folder stored in your Google Drive, and it will import them automatically when initializing. <br><br>\n","#@markdown Link the URL path to the audio files (Mega, Drive, etc.) and start the code\n","url = 'INSERTURLHERE' #@param {type:\"string\"}\n","\n","import subprocess\n","import os\n","import shutil\n","from urllib.parse import urlparse, parse_qs\n","from google.colab import output\n","from google.colab import drive\n","\n","\n","mount_to_drive = True\n","mount_path = '/content/drive/MyDrive'\n","\n","def mount(gdrive=False):\n"," if gdrive:\n"," if not os.path.exists(\"/content/drive/MyDrive\"):\n"," try:\n"," drive.mount(\"/content/drive\", force_remount=True)\n"," except:\n"," drive._mount(\"/content/drive\", force_remount=True)\n"," else:\n"," pass\n","\n","mount(mount_to_drive)\n","\n","def check_package_installed(package_name):\n"," command = f\"pip show {package_name}\"\n"," result = subprocess.run(command.split(), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n"," return result.returncode == 0\n","\n","def install_package(package_name):\n"," command = f\"pip install {package_name} --quiet\"\n"," subprocess.run(command.split(), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n","\n","if not check_package_installed(\"mega.py\"):\n"," install_package(\"mega.py\")\n","\n","from mega import Mega\n","import os\n","import shutil\n","from urllib.parse import urlparse, parse_qs\n","import urllib.parse\n","\n","!rm -rf /content/unzips/\n","!rm -rf /content/zips/\n","!mkdir /content/unzips\n","!mkdir /content/zips\n","\n","def sanitize_directory(directory):\n"," for filename in os.listdir(directory):\n"," file_path = os.path.join(directory, filename)\n"," if os.path.isfile(file_path):\n"," if filename == \".DS_Store\" or filename.startswith(\"._\"):\n"," os.remove(file_path)\n"," elif os.path.isdir(file_path):\n"," sanitize_directory(file_path)\n","\n","audio_zip = urlparse(url).path.split('/')[-2] + '.zip'\n","audio_zip_path = '/content/zips/' + audio_zip\n","\n","if url != '':\n"," if \"drive.google.com\" in url:\n"," !gdown $url --fuzzy -O \"$audio_zip_path\"\n"," elif \"mega.nz\" in url:\n"," m = Mega()\n"," m.download_url(url, '/content/zips')\n"," else:\n"," !wget \"$url\" -O \"$audio_zip_path\"\n","\n"," for filename in os.listdir(\"/content/zips\"):\n"," if filename.endswith(\".zip\"):\n"," zip_file = os.path.join(\"/content/zips\", filename)\n"," shutil.unpack_archive(zip_file, \"/content/unzips\", 'zip')\n","\n","sanitize_directory(\"/content/unzips\")\n","\n","# Copy the unzipped audio files to the /content/drive/MyDrive/MDX_Colab/tracks folder\n","!mkdir -p /content/drive/MyDrive/MDX_Colab/tracks\n","for filename in os.listdir(\"/content/unzips\"):\n"," if filename.endswith((\".wav\", \".mp3\")):\n"," audio_file = os.path.join(\"/content/unzips\", filename)\n"," destination_file = os.path.join(\"/content/drive/MyDrive/MDX_Colab/tracks\", filename)\n"," shutil.copy2(audio_file, destination_file)\n"," if os.path.exists(destination_file):\n"," print(f\"Copy successful: {destination_file}\")\n"," else:\n"," print(f\"Copy failed: {audio_file}\")\n","\n","!rm -r /content/unzips/\n","!rm -r /content/zips/"],"metadata":{"cellView":"form","id":"PHePMBw3HFYh"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"hakZKxmTtaHn"},"source":["##Audio Isolation"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"NS5gkRxlj-2B","cellView":"form"},"outputs":[],"source":["#@markdown ### Print a list of tracks\n","for i in glob.glob('tracks/*'):\n"," print(os.path.basename(i))"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"UHIQxwkUtSDa","cellView":"form"},"outputs":[],"source":["if not 'initialised' in globals():\n"," raise NameError('Please run the first cell first!! #scrollTo=H_cTbwhVq4K6')\n","\n","#import all models metadata\n","import json\n","with open('model_data.json', 'r') as f:\n"," model_data = json.load(f)\n","\n","# Modifiable variables\n","tracks_path = 'tracks/'\n","separated_path = 'separated/'\n","\n","#@markdown ### Input track\n","#@markdown Enter any link/Filename (Upload your songs in tracks folder)\n","track = \"Butterfly.wav\" #@param {type:\"string\"}\n","\n","#@markdown ---\n","#@markdown ### Models\n","ONNX = \"MDX-UVR Ins Model Full Band 498 (HQ_2)\" #@param [\"off\", \"Karokee\", \"Karokee_AGGR\", \"Karokee 2\", \"baseline\", \"MDX-UVR Ins Model 415\", \"MDX-UVR Ins Model 418\", \"MDX-UVR Ins Model 464\", \"MDX-UVR Ins Model 496 - inst main-MDX 2.1\", \"Kim ft other instrumental model\", \"MDX-UVR Vocal Model 427\", \"MDX-UVR-Kim Vocal Model (old)\", \"MDX-UVR Ins Model Full Band 292\", \"MDX-UVR Ins Model Full Band 403\", \"MDX-UVR Ins Model Full Band 450 (HQ_1)\", \"MDX-UVR Ins Model Full Band 498 (HQ_2)\"]\n","Demucs = 'off'#@param [\"off\",\"demucs_extra\"]\n","\n","#@markdown ---\n","#@markdown ### Parameters\n","denoise = False #@param {type:\"boolean\"}\n","normalise = True #@param {type:\"boolean\"}\n","#getting values from model_data.json related to ONNX var (model folder name)\n","amplitude_compensation = model_data[ONNX][\"compensate\"]\n","dim_f = model_data[ONNX][\"mdx_dim_f_set\"]\n","dim_t = model_data[ONNX][\"mdx_dim_t_set\"]\n","n_fft = model_data[ONNX][\"mdx_n_fft_scale_set\"]\n","\n","mixing_algorithm = 'max_mag' #@param [\"default\",\"min_mag\",\"max_mag\"]\n","chunks = 55 #@param {type:\"slider\", min:1, max:55, step:1}\n","shifts = 10 #@param {type:\"slider\", min:0, max:10, step:0.1}\n","\n","##validate values\n","track = track if 'http' in track else tracks_path+track\n","normalise = '--normalise' if normalise else ''\n","denoise = '--denoise' if denoise else ''\n","\n","if ONNX == 'off':\n"," pass\n","else:\n"," ONNX = 'onnx/'+ONNX\n","if Demucs == 'off':\n"," pass\n","else:\n"," Demucs = 'model/'+Demucs+'.th'\n","#@markdown ---\n","#@markdown ### Stems\n","bass = False #@param {type:\"boolean\"}\n","drums = False #@param {type:\"boolean\"}\n","others = False #@param {type:\"boolean\"}\n","vocals = True #@param {type:\"boolean\"}\n","#@markdown ---\n","#@markdown ### Invert stems to mixture\n","invert_bass = False #@param {type:\"boolean\"}\n","invert_drums = False #@param {type:\"boolean\"}\n","invert_others = False #@param {type:\"boolean\"}\n","invert_vocals = True #@param {type:\"boolean\"}\n","invert_stems = []\n","stems = []\n","if bass:\n"," stems.append('b')\n","if drums:\n"," stems.append('d')\n","if others:\n"," stems.append('o')\n","if vocals:\n"," stems.append('v')\n","\n","invert_stems = []\n","if invert_bass:\n"," invert_stems.append('b')\n","if invert_drums:\n"," invert_stems.append('d')\n","if invert_others:\n"," invert_stems.append('o')\n","if invert_vocals:\n"," invert_stems.append('v')\n","\n","margin = 44100\n","\n","###\n","# incompatibilities\n","###\n","\n","console(f\"python main.py --n_fft {n_fft} --dim_f {dim_f} --dim_t {dim_t} --margin {margin} -i \\\"{track}\\\" --mixing {mixing_algorithm} --onnx \\\"{ONNX}\\\" --model {Demucs} --shifts {round(shifts)} --stems {''.join(stems)} --invert {''.join(invert_stems)} --chunks {chunks} --compensate {amplitude_compensation} {normalise} {denoise}\")"]},{"cell_type":"markdown","source":["<sup>Models provided are from [Kuielab](https://github.com/kuielab/mdx-net-submission/), [UVR](https://github.com/Anjok07/ultimatevocalremovergui/) and [Kim](https://github.com/KimberleyJensen/) <br> (you can support UVR [here](https://www.buymeacoffee.com/uvr5/vip-model-download-instructions) and [here](https://boosty.to/uvr)).</sup></br>\n","<sup>Original UVR notebook by [Audio Hacker](https://www.youtube.com/channel/UC0NiSV1jLMH-9E09wiDVFYw/), modified by Audio Separation community & then kalomaze (for RVC colab).</sup></br>\n","<sup>Big thanks to the [Audio Separation Discord](https://discord.gg/zeYU2Wzbgj) for helping me implement this in the colab.</sup></br>"],"metadata":{"id":"z_DD960nGMdi"}},{"cell_type":"markdown","metadata":{"id":"lOmAsaSTha39"},"source":["##**Settings explanation**<br>\n","\n","The defaults already provided are generally recommended. However, if you would like to try tweaking them, here's an explanation:\n","\n","*Mixing algorithm* - max_mag - is generally for vocals (gives the most residues in instrumentals), min_mag - for instrumentals (the most aggresive) though \"min_mag solve some un-wanted vocal soundings, but instrumental [is] more muffled and less detailed\". Check out also \"default\" as it's in between both - a.k.a. average (it's also required for Demucs enabled which works only for vocal models).<br>\n","\n","*Chunks* - Set it to 55 or 40 (less aggressive) to alleviate some occasional instrument dissapearing.\n","Set 1 for the best clarity. It works for at least instrumental model (4:15 track, at least for Tesla T4 (shown at the top) generally better quality, but some instruments tend to disappear more using 1 than 10. For Demucs enabled and/or vocal model it can be set to 10 if your track is below 5:00 minutes. The more chunks, the faster separation up to ~40. For 4:15 track, 72 is max supported till memory allocation error shows up (disabled chunks returns error too). <br>\n","\n","*Shifts* - can be set max to 10, but it only slightly increases SDR, while processing time is 1.7x longer for each shift and it gives similar result to shifts 5.\n","\n","*Normalization* - \"normalizes all input at first and then changes the wave peak back to original. This makes the separation process better, also less noise\" (e.g. if you have to noisy hihats or big amplitude compensation - disable it).\n","<br>\n","\n","*Demucs* enabled works correctly with mixing algorithm set to default and only with vocal models (Kim and 427). It's also the only option to get rid of noise of MDX models. Normalization enabled is necessary (but that cnfiguration has slightly more vocal residues than instrumental model). Decrease chunks to 40 if you have ONNXRuntimeError with Demucs on (it requires lower chunks).\n","<br>\n","\n","##**Recommended models**<br>\n","\n","For vocals (by raw SDR output, not factoring in manual cleanup):\n","- Kim vocal 2 (less instrumental residues in vocal stem)\n","- Kim vocal 1\n","<br>or alternatively\n","- 427\n","- 406\n","\n","For best lead vocals:\n","- Karaokee 2\n","\n","For best backing vocals:\n","- [HP_KAROKEE-MSB2-3BAND-3090](https://colab.research.google.com/drive/16Q44VBJiIrXOgTINztVDVeb0XKhLKHwl?usp=sharing)\n","\n","(Yeah it's inconvenient that the VR Architecture models aren't here and have to be run through the above colab, but they can't coexist in the same colab as of right now, I will attempting a better solution in the future.)\n","\n","4 Stems:\n","- [Demucs ft](https://colab.research.google.com/drive/117SWWC0k9N2MBj7biagHjkRZpmd_ozu1) (don't use baseline and Anjok Vocal here - they're worse and outdated) / [GSEP](https://studio.gaudiolab.io/) / [MDX23](https://mvsep1.ru) (best SDR)\n"]},{"cell_type":"markdown","source":["#Other"],"metadata":{"id":"Yj6CRqPNEGsi"}},{"cell_type":"markdown","source":["#**Consider subscribing to my Patreon!**\n","\n","Benefits include:\n","- Full on tech support for AI covers in general\n","- This includes audio mixing and how to train your own models, with any tier.\n","- Tech support priority is given to the latter tier.\n","\n","https://patreon.com/kalomaze\n","\n","Your support would be greatly appreciated! On top of maintaining this colab, I also write and maintain the Google Docs guides, and plan to create a video tutorial for training voices in the future.\n"],"metadata":{"id":"IbwNaVJQBkRi"}},{"cell_type":"markdown","source":["##Credits\n","**Rejekts** - Original colab author, and then he probably based it off Snoop's old colab before that? Idk it gets messy with these colabs we all kinda stole from each other xd<br>\n","**RVC-Project dev team** - Original RVC software developers <br>\n","**Mangio621** - Developer of the RVC fork that added crepe support, helped me get it up and running + taught me how to use TensorBoard<br>\n","**Kalomaze** - Creator of this colab, added autobackup + loader feature, fixed downloader to work with zips that had parentheses + streamlined downloader, added TensorBoard picture, made the doc thats linked, general God amongst men (def not biased 100%)"],"metadata":{"id":"Y13Eh9r_g8f-"}},{"cell_type":"markdown","source":["##Inference ONLY colab:\n","\n","https://colab.research.google.com/drive/1Gj6UTf2gicndUW_tVheVhTXIIYpFTYc7?usp=sharing\n","\n","<br>\n","Some random old models list from rejekts, the OG colab author: <br>\n","\n","##Rejekts' Models List:\n","###I will be posting some of my models here for easy access. Copy the link and paste it on step 2 (and type the name of the artist)\n","\n","jungkook: https://drive.google.com/file/d/1i5CMlcnKfVEpzD5wvwjWytrwT2fT74g6/view?usp=share_link\n","\n","BENEE: https://drive.google.com/file/d/1nuUVTqg1_lja7JFctjd18W9hQ7rk7aDZ/view?usp=share_link\n","\n","shiloh: https://drive.google.com/file/d/12nk3OOEVdhWB6eBNYN5Gw0wbifIYx_fF/view?usp=share_link\n","\n","\n"],"metadata":{"id":"xcaqfmiugcWS"}}]}