adjust this code


import os
import shutil
import subprocess
import glob
from datetime import datetime
from tools.useftools import *
import gradio as gr
import torch
from infer.modules.vc.modules import VC
from infer.modules.vc import show_info, hash_similarity # some shit
from configs.config import Config
from web import *
# Setting up environment variables
os.environ["rmvpe_root"] = "assets/rmvpe"
os.environ['index_root'] = "logs"
os.environ['weight_root'] = "assets/weights"

# Ensure the audios directory exists
os.makedirs(os.path.join(".", "audios"), exist_ok=True)

# Initialize configuration and voice conversion module
config = Config()
vc = VC(config)

# Function to display warnings
def warn(text):
    try:
        gr.Warning(text)
    except:
        pass

# Function to show available files in a directory with optional format filtering
def show_available(filepath, format=None):
    if format:
        files = [file for file in os.listdir(filepath) if file.endswith(format)]
        return files if files else ['']
    return os.listdir(filepath) if os.listdir(filepath) else ['']

# Function to load model and update the index picker
def load_model(model_picker, index_picker):
    logs = show_available("logs")
    log = model_picker.replace(".pth", "") if model_picker.replace(".pth", "") in logs else index_picker
    vc.get_vc(model_picker, 0, 0)
    if log != model_picker.replace(".pth", ""):
        warn("Could not find a matching index file.")
    return {"choices": logs, "value": log, "__type__": "update"}

# Function to convert audio using specified parameters
def convert(audio_picker, model_picker, index_picker, index_rate, pitch, method):
    warn("Your audio is being converted. Please wait.")
    now = datetime.now().strftime("%d%m%Y%H%M%S")
    index_files = glob.glob(f"logs/{index_picker}/*.index") or [f'logs/{model_picker}/fake_index.index']
    if not index_files:
        warn("Sorry, I couldn't find your .index file.")
    device = "cuda" if torch.cuda.is_available() else "cpu"
    command = [
        "python", "tools/cmd/infer_cli.py",
        "--f0up_key", str(pitch), "--input_path", f"audios/{audio_picker}",
        "--index_path", index_files[0], "--f0method", method,
        "--opt_path", f"audios/cli_output_{now}.wav", "--model_name", model_picker,
        "--index_rate", str(float(index_rate)), "--device", device,
        "--filter_radius", "3", "--resample_sr", "0", "--rms_mix_rate", "0.0", "--protect", "0"
    ]
    try:
        subprocess.run(command, check=True)
        return {"choices": show_available("audios"), "__type__": "update", "value": f"cli_output_{now}.wav"}, f"audios/cli_output_{now}.wav"
    except subprocess.CalledProcessError as e:
        print(f"Error: {e}")
        return {"choices": show_available("audios"), "__type__": "update"}, None

# Function to download files from URLs
def download_from_url(url, model):
    model = model or url.split('/')[-1].split('?')[0]
    if not model:
        return "You need to name your model. For example: My-Model", {"choices": show_available("assets/weights"), "__type__": "update"}
    url = url.replace('/blob/main/', '/resolve/main/').strip()
    zip_dirs = ["zips", "unzips"]
    for directory in zip_dirs:
        if os.path.exists(directory):
            shutil.rmtree(directory)
    os.makedirs("zips", exist_ok=True)
    os.makedirs("unzips", exist_ok=True)
    zipfile_path = f'./zips/{model}.zip'
    try:
        if url.endswith('.pth'):
            subprocess.run(["wget", url, "-O", f'./assets/weights/{model}.pth'])
        elif url.endswith('.index'):
            os.makedirs(f'./logs/{model}', exist_ok=True)
            subprocess.run(["wget", url, "-O", f'./logs/{model}/added_{model}.index'])
        else:
            subprocess.run(["wget", url, "-O", zipfile_path])
            shutil.unpack_archive(zipfile_path, "./unzips", 'zip')
            for root, _, files in os.walk('./unzips'):
                for file in files:
                    file_path = os.path.join(root, file)
                    if file.endswith(".index"):
                        os.makedirs(f'./logs/{model}', exist_ok=True)
                        shutil.copy2(file_path, f'./logs/{model}')
                    elif "G_" not in file and "D_" not in file and file.endswith(".pth"):
                        shutil.copy(file_path, f'./assets/weights/{model}.pth')
        shutil.rmtree("zips")
        shutil.rmtree("unzips")
        return "Success.", {"choices": show_available("assets/weights"), "__type__": "update"}
    except:
        return "There's been an error.", {"choices": show_available("assets/weights"), "__type__": "update"}

# Function to import a model from a predefined list
def import_from_name(model):
    try:
        url = models[f'{model}']
    except KeyError:
        return "", {"__type__": "update"}
    return download_from_url(url, model)

# Function to upload a file and move it to the audios directory if it's a valid format
def upload_file(file):
    audio_formats = ['.wav', '.mp3', '.ogg', '.flac', '.aac']
    try:
        filename = os.path.basename(file.name)
        file_path = file.name
    except AttributeError:
        filename = os.path.basename(file)
        file_path = file
    _, ext = os.path.splitext(filename)
    if ext.lower() in audio_formats:
        shutil.move(file_path, 'audios')
    else:
        warn('File incompatible')
    return {"choices": show_available('audios'), "__type__": "update", "value": filename}

# Function to refresh available options
def refresh():
    return {
        "choices": show_available("audios"), "__type__": "update"
    }, {
        "choices": show_available("assets/weights", ".pth"), "__type__": "update"
    }, {
        "choices": show_available("logs"), "__type__": "update"
    }

# Function to update the audio player with a selected file
def update_audio_player(choice):
    return os.path.join("audios", choice)

# Building the Gradio interface
with gr.Blocks() as app:
    with gr.Row():
        with gr.Column():
            gr.Markdown("# RVC PlayGround 🎮")
        with gr.Column():
            gr.HTML("<a href='https://ko-fi.com/rejekts' target='_blank'><img src='file/kofi_button.png' alt='🤝 Support Me'></a>")
    
    with gr.Row():
        with gr.Column():
            with gr.Tabs():
                with gr.TabItem(i18n("Model Inference")):
                with gr.Row():
                    sid0 = gr.Dropdown(
                        label=i18n("Inferencing voice"), choices=sorted(names)
                    )
                    with gr.Column():
                        refresh_button = gr.Button(
                            i18n("Refresh voice list and index path"), variant="primary"
                        )
                    clean_button = gr.Button(
                        i18n("Unload model to save GPU memory"), variant="primary"
                    )
                spk_item = gr.Slider(
                    minimum=0,
                    maximum=2333,
                    step=1,
                    label=i18n("Select Speaker/Singer ID"),
                    value=0,
                    visible=False,
                    interactive=True,
                )
                clean_button.click(
                    fn=clean, inputs=[], outputs=[sid0], api_name="infer_clean"
                )
            modelinfo = gr.Textbox(label=i18n("Model info"), max_lines=8)
            with gr.TabItem(i18n("Single inference")):
                with gr.Row():
                    with gr.Column():
                        vc_transform0 = gr.Number(
                            label=i18n(
                                "Transpose (integer, number of semitones, raise by an octave: 12, lower by an octave: -12)"
                            ),
                            value=0,
                        )
                        input_audio0 = gr.Audio(
                            label=i18n("The audio file to be processed"),
                            type="filepath",
                        )
                        file_index2 = gr.Dropdown(
                            label=i18n(
                                "Auto-detect index path and select from the dropdown"
                            ),
                            choices=sorted(index_paths),
                            interactive=True,
                        )
                        file_index1 = gr.File(
                            label=i18n(
                                "Path to the feature index file. Leave blank to use the selected result from the dropdown"
                            ),
                        )
                    with gr.Column():
                        f0method0 = gr.Radio(
                            label=i18n(
                                "Select the pitch extraction algorithm ('pm': faster extraction but lower-quality speech; 'harvest': better bass but extremely slow; 'crepe': better quality but GPU intensive), 'rmvpe': best quality, and little GPU requirement"
                            ),
                            choices=(
                                ["pm", "dio", "harvest", "crepe", "rmvpe", "fcpe"]
                            ),
                            value="rmvpe",
                            interactive=True,
                        )
                        resample_sr0 = gr.Slider(
                            minimum=0,
                            maximum=48000,
                            label=i18n(
                                "Resample the output audio in post-processing to the final sample rate. Set to 0 for no resampling"
                            ),
                            value=0,
                            step=1,
                            interactive=True,
                        )
                        rms_mix_rate0 = gr.Slider(
                            minimum=0,
                            maximum=1,
                            label=i18n(
                                "Adjust the volume envelope scaling. Closer to 0, the more it mimicks the volume of the original vocals. Can help mask noise and make volume sound more natural when set relatively low. Closer to 1 will be more of a consistently loud volume"
                            ),
                            value=0.25,
                            interactive=True,
                        )
                        protect0 = gr.Slider(
                            minimum=0,
                            maximum=0.5,
                            label=i18n(
                                "Protect voiceless consonants and breath sounds to prevent artifacts such as tearing in electronic music. Set to 0.5 to disable. Decrease the value to increase protection, but it may reduce indexing accuracy"
                            ),
                            value=0.33,
                            step=0.01,
                            interactive=True,
                        )
                        filter_radius0 = gr.Slider(
                            minimum=0,
                            maximum=7,
                            label=i18n(
                                "If >=3: apply median filtering to the harvested pitch results. The value represents the filter radius and can reduce breathiness."
                            ),
                            value=3,
                            step=1,
                            interactive=True,
                        )
                        index_rate1 = gr.Slider(
                            minimum=0,
                            maximum=1,
                            label=i18n("Feature searching ratio"),
                            value=0.75,
                            interactive=True,
                        )
                        f0_file = gr.File(
                            label=i18n(
                                "F0 curve file (optional). One pitch per line. Replaces the default F0 and pitch modulation"
                            ),
                            visible=False,
                        )
                        but0 = gr.Button(i18n("Convert"), variant="primary")
                        vc_output2 = gr.Audio(
                            label=i18n(
                                "Export audio (click on the three dots in the lower right corner to download)"
                            )
                        )

                        refresh_button.click(
                            fn=change_choices,
                            inputs=[],
                            outputs=[sid0, file_index2],
                            api_name="infer_refresh",
                        )

                vc_output1 = gr.Textbox(label=i18n("Output information"))

                but0.click(
                    vc.vc_single,
                    [
                        spk_item,
                        input_audio0,
                        vc_transform0,
                        f0_file,
                        f0method0,
                        file_index1,
                        file_index2,
                        # file_big_npy1,
                        index_rate1,
                        filter_radius0,
                        resample_sr0,
                        rms_mix_rate0,
                        protect0,
                    ],
                    [vc_output1, vc_output2],
                    api_name="infer_convert",
                )
                with gr.TabItem("1.Choose a voice model:"):
                    model_picker = gr.Dropdown(label="Model:", choices=show_available('assets/weights', '.pth'), value=show_available('assets/weights', '.pth')[0], interactive=True, allow_custom_value=True)
                    index_picker = gr.Dropdown(label="Index:", interactive=True, choices=show_available('logs'), value=show_available('logs')[0], allow_custom_value=True)
                    model_picker.change(fn=load_model, inputs=[model_picker, index_picker], outputs=[index_picker])
    
                with gr.TabItem("2.Choose an audio file:"):
                    recorder = gr.Microphone(label="Record audio here...", type='filepath')
                    audio_picker = gr.Dropdown(label="", choices=show_available('audios'), value='', interactive=True)
                    try:
                        recorder.stop_recording(upload_file, inputs=[recorder], outputs=[audio_picker])
                    except:
                        recorder.upload(upload_file, inputs=[recorder], outputs=[audio_picker])
                    dropbox = gr.File(label="Drop an audio here.", file_types=['.wav', '.mp3', '.ogg', '.flac', '.aac'], type="filepath")
                    dropbox.upload(fn=upload_file, inputs=[dropbox], outputs=[audio_picker])
                    with gr.Row():
                        audio_refresher = gr.Button("Refresh")
                        audio_refresher.click(fn=refresh, inputs=[], outputs=[audio_picker, model_picker, index_picker])
                        convert_button = gr.Button("Convert")
                    with gr.Row():
                        audio_player = gr.Audio()
                        inputs = [audio_picker, model_picker, index_picker, index_rate, pitch, method]
                        audio_picker.change(fn=update_audio_player, inputs=[audio_picker], outputs=[audio_player])
                        convert_button.click(convert, inputs=inputs, outputs=[audio_picker, audio_player])
                with gr.TabItem("(Or download a model here)"):
                    with gr.Row():
                        url = gr.Textbox(label="Paste the URL here:", value="", placeholder="(i.e. https://huggingface.co/repo/model/resolve/main/model.zip)")
                    with gr.Row():
                        with gr.Column():
                            model_rename = gr.Textbox(placeholder="My-Model", label="Name your model:", value="")
                        with gr.Column():
                            download_button = gr.Button("Download")
                            download_button.click(fn=download_from_url, inputs=[url, model_rename], outputs=[url, model_picker])
                            with gr.Row():
                                selected_import = gr.Dropdown(choices=list(models.keys()), label="OR Search Models (Quality UNKNOWN)", scale=5)
                                import_model = gr.Button("Download")
                                import_model.click(fn=import_from_name, inputs=[selected_import], outputs=[selected_import, model_picker])
            
            with gr.TabItem("Advanced"):
                index_rate = gr.Slider(label='Index Rate:', minimum=0, maximum=1, value=0.66, step=0.01)
                pitch = gr.Slider(label='Pitch (-12 lowers it an octave, 0 keeps the original pitch, 12 lifts it an octave):', minimum=-12, maximum=12, step=1, value=0, interactive=True)
                method = gr.Dropdown(label="Method:", choices=["pm", "crepe", "harvest", "dio", "rmvpe", "fcpe"], value="rmvpe")

app.queue(max_size=20).launch(debug=True, share=True)