From ce020f3a41748bc80a09a276d227494389205084 Mon Sep 17 00:00:00 2001 From: Politrees <143968312+Bebra777228@users.noreply.github.com> Date: Thu, 14 Mar 2024 15:38:56 +0500 Subject: [PATCH] Update demo.py --- demo.py | 190 ++++++++++++++++++++++++++++---------------------------- 1 file changed, 94 insertions(+), 96 deletions(-) diff --git a/demo.py b/demo.py index 94f80ff..7dde6d9 100644 --- a/demo.py +++ b/demo.py @@ -5,41 +5,39 @@ model_library = CachedModels() with gr.Blocks(title="🔊",theme=gr.themes.Base(primary_hue="rose",neutral_hue="zinc")) as app: + with gr.Row(): + gr.HTML("image") with gr.Tabs(): - with gr.TabItem("Интерфейс"): + with gr.TabItem("Inference"): with gr.Row(): - voice_model = gr.Dropdown(label="Модель голоса:", choices=sorted(names), value=lambda:sorted(names)[0] if len(sorted(names)) > 0 else '', interactive=True) - refresh_button = gr.Button("Обновить", variant="primary") + voice_model = gr.Dropdown(label="Model Voice", choices=sorted(names), value=lambda:sorted(names)[0] if len(sorted(names)) > 0 else '', interactive=True) + refresh_button = gr.Button("Refresh", variant="primary") spk_item = gr.Slider( minimum=0, maximum=2333, step=1, - label="Идентификатор спикера", + label="Speaker ID", value=0, visible=False, interactive=True, ) - vc_transform0 = gr.Slider( - minimum=-20, - maximum=20, - step=1, - label="Тон", - value=0, - interactive=True, + vc_transform0 = gr.Number( + label="Pitch", + value=0 ) - but0 = gr.Button(value="🔊Преобразовать🔊", variant="primary") + but0 = gr.Button(value="Convert", variant="primary") with gr.Row(): with gr.Column(): with gr.Row(): - dropbox = gr.File(label="Перетащите сюда аудиофайл и нажмите кнопку 'Обновить'") + dropbox = gr.File(label="Drop your audio here & hit the Reload button.") with gr.Row(): - record_button=gr.Audio(source="microphone", label="Записать звук с микрофона", type="filepath") + record_button=gr.Audio(source="microphone", label="OR Record audio.", type="filepath") with gr.Row(): paths_for_files = lambda path:[os.path.abspath(os.path.join(path, f)) for f in os.listdir(path) if os.path.splitext(f)[1].lower() in ('.mp3', '.wav', '.flac', '.ogg')] input_audio0 = gr.Dropdown( - label="Путь к входному файлу:", + label="Input Path", value=paths_for_files('audios')[0] if len(paths_for_files('audios')) > 0 else '', - choices=paths_for_files('audios'), # Показывать только абсолютные пути к аудиофайлам с расширениями .mp3, .wav, .flac или .ogg + choices=paths_for_files('audios'), # Only show absolute paths for audio files ending in .mp3, .wav, .flac or .ogg allow_custom_value=True ) with gr.Row(): @@ -50,17 +48,17 @@ fn=lambda path: {"value":path,"__type__":"update"} if os.path.exists(path) else None ) record_button.stop_recording( - fn=lambda audio:audio, #TODO сохранить wav lambda - inputs=[record_button], + fn=lambda audio:audio, #TODO save wav lambda + inputs=[record_button], outputs=[input_audio0]) dropbox.upload( fn=lambda audio:audio.name, - inputs=[dropbox], + inputs=[dropbox], outputs=[input_audio0]) with gr.Column(): - with gr.Accordion("Настройка index файла", open=False): + with gr.Accordion("Change Index", open=False): file_index2 = gr.Dropdown( - label="Index модели:", + label="Change Index", choices=sorted(index_paths), interactive=True, value=sorted(index_paths)[0] if len(sorted(index_paths)) > 0 else '' @@ -68,14 +66,14 @@ index_rate1 = gr.Slider( minimum=0, maximum=1, - label="Сила индекса", - value=0.66, + label="Index Strength", + value=0.5, interactive=True, ) - vc_output2 = gr.Audio(label="Выход") - with gr.Accordion("Дополнительные настройки", open=False): + vc_output2 = gr.Audio(label="Output") + with gr.Accordion("General Settings", open=False): f0method0 = gr.Radio( - label="Метод", + label="Method", choices=["pm", "harvest", "crepe", "rmvpe"] if config.dml == False else ["pm", "harvest", "rmvpe"], @@ -85,7 +83,7 @@ filter_radius0 = gr.Slider( minimum=0, maximum=7, - label="Снижение шума дыхания (только для Harvest)", + label="Breathiness Reduction (Harvest only)", value=3, step=1, interactive=True, @@ -93,7 +91,7 @@ resample_sr0 = gr.Slider( minimum=0, maximum=48000, - label="Перевыборка", + label="Resample", value=0, step=1, interactive=True, @@ -102,23 +100,23 @@ rms_mix_rate0 = gr.Slider( minimum=0, maximum=1, - label="Нормализация громкости", + label="Volume Normalization", value=0, interactive=True, ) protect0 = gr.Slider( minimum=0, maximum=0.5, - label="Защита от шума дыхания (0 - включено, 0.5 - выключено)", + label="Breathiness Protection (0 is enabled, 0.5 is disabled)", value=0.33, step=0.01, interactive=True, ) if voice_model != None: vc.get_vc(voice_model.value,protect0,protect0) file_index1 = gr.Textbox( - label="Путь к индексному файлу", + label="Index Path", interactive=True, - visible=False#Здесь не используется + visible=False#Not used here ) refresh_button.click( fn=change_choices, @@ -127,21 +125,21 @@ api_name="infer_refresh", ) refresh_button.click( - fn=lambda:{"choices":paths_for_files('audios'),"__type__":"update"}, #TODO проверить, правильно ли возвращается отсортированный список аудиофайлов в папке 'audios' с расширениями '.wav', '.mp3', '.ogg' или '.flac' + fn=lambda:{"choices":paths_for_files('audios'),"__type__":"update"}, #TODO check if properly returns a sorted list of audio files in the 'audios' folder that have the extensions '.wav', '.mp3', '.ogg', or '.flac' inputs=[], - outputs = [input_audio0], + outputs = [input_audio0], ) refresh_button.click( - fn=lambda:{"value":paths_for_files('audios')[0],"__type__":"update"} if len(paths_for_files('audios')) > 0 else {"value":"","__type__":"update"}, #TODO проверить, правильно ли возвращается отсортированный список аудиофайлов в папке 'audios' с расширениями '.wav', '.mp3', '.ogg' или '.flac' + fn=lambda:{"value":paths_for_files('audios')[0],"__type__":"update"} if len(paths_for_files('audios')) > 0 else {"value":"","__type__":"update"}, #TODO check if properly returns a sorted list of audio files in the 'audios' folder that have the extensions '.wav', '.mp3', '.ogg', or '.flac' inputs=[], - outputs = [input_audio0], + outputs = [input_audio0], ) with gr.Row(): - f0_file = gr.File(label="Путь к файлу F0", visible=False) + f0_file = gr.File(label="F0 Path", visible=False) with gr.Row(): - vc_output1 = gr.Textbox(label="Информация", placeholder="Добро пожаловать!",visible=False) + vc_output1 = gr.Textbox(label="Information", placeholder="Welcome!",visible=False) but0.click( - vc.vc_single, + vc.vc_single, [ spk_item, input_audio0, @@ -158,89 +156,89 @@ ], [vc_output1, vc_output2], api_name="infer_convert", - ) + ) voice_model.change( fn=vc.get_vc, inputs=[voice_model, protect0, protect0], outputs=[spk_item, protect0, protect0, file_index2, file_index2], api_name="infer_change_voice", ) - with gr.TabItem("Загрузка модели"): + with gr.TabItem("Download Models"): with gr.Row(): - url_input = gr.Textbox(label="URL модели:", value="",placeholder="https://...", scale=6) - name_output = gr.Textbox(label="Сохранить как", value="",placeholder="MyModel",scale=2) - url_download = gr.Button(value="Загрузить модель",scale=2) + url_input = gr.Textbox(label="URL to model", value="",placeholder="https://...", scale=6) + name_output = gr.Textbox(label="Save as", value="",placeholder="MyModel",scale=2) + url_download = gr.Button(value="Download Model",scale=2) url_download.click( inputs=[url_input,name_output], outputs=[url_input], fn=download_from_url, ) with gr.Row(): - model_browser = gr.Dropdown(choices=list(model_library.models.keys()),label="Пользовательские модели",scale=5) - download_from_browser = gr.Button(value="Получить",scale=2) + model_browser = gr.Dropdown(choices=list(model_library.models.keys()),label="OR Search Models (Quality UNKNOWN)",scale=5) + download_from_browser = gr.Button(value="Get",scale=2) download_from_browser.click( inputs=[model_browser], outputs=[model_browser], fn=lambda model: download_from_url(model_library.models[model],model), ) - with gr.TabItem("Тренировка"): + with gr.TabItem("Train"): with gr.Row(): with gr.Column(): - training_name = gr.Textbox(label="Дайте имя своей модели:", value="Model_Name",placeholder="Shanin") + training_name = gr.Textbox(label="Name your model", value="My-Voice",placeholder="My-Voice") np7 = gr.Slider( minimum=0, maximum=config.n_cpu, step=1, - label="Количество процессов CPU, используемых для выделения характеристик тона", + label="Number of CPU processes used to extract pitch features", value=int(np.ceil(config.n_cpu / 1.5)), interactive=True, ) sr2 = gr.Radio( - label="Частота дискретизации", + label="Sampling Rate", choices=["40k", "32k"], - value="40k", + value="32k", interactive=True, visible=False ) if_f0_3 = gr.Radio( - label="Будет ли ваша модель использоваться для пения? Если нет, вы можете проигнорировать это", + label="Will your model be used for singing? If not, you can ignore this.", choices=[True, False], value=True, interactive=True, visible=False ) version19 = gr.Radio( - label="Версия", + label="Version", choices=["v1", "v2"], value="v2", interactive=True, visible=False, ) dataset_folder = gr.Textbox( - label="Папка с набором данных:", value='dataset' + label="dataset folder", value='dataset' ) - easy_uploader = gr.Files(label="Перетащите сюда ваши аудиофайлы",file_types=['audio']) - but1 = gr.Button("1. Обработать", variant="primary") - info1 = gr.Textbox(label="Информация:", value="",visible=True) + easy_uploader = gr.Files(label="Drop your audio files here",file_types=['audio']) + but1 = gr.Button("1. Process", variant="primary") + info1 = gr.Textbox(label="Information", value="",visible=True) easy_uploader.upload(inputs=[dataset_folder],outputs=[],fn=lambda folder:os.makedirs(folder,exist_ok=True)) easy_uploader.upload( - fn=lambda files,folder: [shutil.copy2(f.name,os.path.join(folder,os.path.split(f.name)[1])) for f in files] if folder != "" else gr.Warning('Пожалуйста, укажите имя папки для вашего набора данных'), - inputs=[easy_uploader, dataset_folder], + fn=lambda files,folder: [shutil.copy2(f.name,os.path.join(folder,os.path.split(f.name)[1])) for f in files] if folder != "" else gr.Warning('Please enter a folder name for your dataset'), + inputs=[easy_uploader, dataset_folder], outputs=[]) gpus6 = gr.Textbox( - label="Введите номера GPU через дефис, (например, 0-1-2)", + label="Enter the GPU numbers to use separated by -, (e.g. 0-1-2)", value=gpus, interactive=True, visible=F0GPUVisible, ) gpu_info9 = gr.Textbox( - label="Информация о GPU:", value=gpu_info, visible=F0GPUVisible + label="GPU Info", value=gpu_info, visible=F0GPUVisible ) spk_id5 = gr.Slider( minimum=0, maximum=4, step=1, - label="Идентификатор спикера", + label="Speaker ID", value=0, interactive=True, visible=False @@ -250,22 +248,22 @@ [dataset_folder, training_name, sr2, np7], [info1], api_name="train_preprocess", - ) + ) with gr.Column(): f0method8 = gr.Radio( - label="Метод выделения характеристик F0", + label="F0 extraction method", choices=["pm", "harvest", "dio", "rmvpe", "rmvpe_gpu"], value="rmvpe_gpu", interactive=True, ) gpus_rmvpe = gr.Textbox( - label="Номера GPU для использования через дефис (например 0-1-2)", + label="GPU numbers to use separated by -, (e.g. 0-1-2)", value="%s-%s" % (gpus, gpus), interactive=True, visible=F0GPUVisible, ) - but2 = gr.Button("2. Выделить характеристики", variant="primary") - info2 = gr.Textbox(label="Информация:", value="", max_lines=8) + but2 = gr.Button("2. Extract Features", variant="primary") + info2 = gr.Textbox(label="Information", value="", max_lines=8) f0method8.change( fn=change_f0_method, inputs=[f0method8], @@ -288,18 +286,18 @@ with gr.Column(): total_epoch11 = gr.Slider( minimum=2, - maximum=2000, + maximum=1000, step=1, - label="Эпохи (больше эпох может улучшить качество, но занимает больше времени)", - value=300, + label="Epochs (more epochs may improve quality but takes longer)", + value=150, interactive=True, ) - but4 = gr.Button("3. Тренировать индекс", variant="primary") - but3 = gr.Button("4. Тренировать модель", variant="primary") - info3 = gr.Textbox(label="Информация:", value="", max_lines=10) - with gr.Accordion(label="Общие настройки", open=False): + but4 = gr.Button("3. Train Index", variant="primary") + but3 = gr.Button("4. Train Model", variant="primary") + info3 = gr.Textbox(label="Information", value="", max_lines=10) + with gr.Accordion(label="General Settings", open=False): gpus16 = gr.Textbox( - label="GPU через дефис (например 0-1-2)", + label="GPUs separated by -, (e.g. 0-1-2)", value="0", interactive=True, visible=True @@ -308,61 +306,61 @@ minimum=1, maximum=50, step=1, - label="Частота сохранения модели", - value=20, + label="Weight Saving Frequency", + value=25, interactive=True, ) batch_size12 = gr.Slider( minimum=1, - maximum=20, + maximum=40, step=1, - label="Размер пакета", + label="Batch Size", value=default_batch_size, interactive=True, ) if_save_latest13 = gr.Radio( - label="Сохранять только последнюю модель", - choices=["Да", "Нет"], - value="Да", + label="Only save the latest model", + choices=["yes", "no"], + value="yes", interactive=True, visible=False ) if_cache_gpu17 = gr.Radio( - label="Если ваш набор данных МЕНЬШЕ 10 минут, кэшируйте его для более быстрой тренировки", - choices=["Да", "Нет"], - value="Да", + label="If your dataset is UNDER 10 minutes, cache it to train faster", + choices=["yes", "no"], + value="no", interactive=True, ) if_save_every_weights18 = gr.Radio( - label="Сохранять маленькую модель после каждого сохранения", - choices=["Да", "Нет"], - value="Да", + label="Save small model at every save point", + choices=["yes", "no"], + value="yes", interactive=True, ) - with gr.Accordion(label="Список предварительно обученных моделей", open=False): + with gr.Accordion(label="Change pretrains", open=False): pretrained = lambda sr, letter: [os.path.abspath(os.path.join('assets/pretrained_v2', file)) for file in os.listdir('assets/pretrained_v2') if file.endswith('.pth') and sr in file and letter in file] pretrained_G14 = gr.Dropdown( - label="pretrain G:", - # Получить список всех предобученных моделей G в assets/pretrained_v2, заканчивающихся на .pth + label="pretrained G", + # Get a list of all pretrained G model files in assets/pretrained_v2 that end with .pth choices = pretrained(sr2.value, 'G'), value=pretrained(sr2.value, 'G')[0] if len(pretrained(sr2.value, 'G')) > 0 else '', interactive=True, visible=True ) pretrained_D15 = gr.Dropdown( - label="pretrain D:", + label="pretrained D", choices = pretrained(sr2.value, 'D'), value= pretrained(sr2.value, 'D')[0] if len(pretrained(sr2.value, 'G')) > 0 else '', visible=True, interactive=True ) with gr.Row(): - download_model = gr.Button('5. Скачать файлы модели') + download_model = gr.Button('5.Download Model') with gr.Row(): - model_files = gr.Files(label='Ваша модель и индексный файл могут быть загружены здесь:') + model_files = gr.Files(label='Your Model and Index file can be downloaded here:') download_model.click( fn=lambda name: os.listdir(f'assets/weights/{name}') + glob.glob(f'logs/{name.split(".")[0]}/added_*.index'), - inputs=[training_name], + inputs=[training_name], outputs=[model_files, info3]) with gr.Row(): sr2.change( @@ -381,7 +379,7 @@ [f0method8, pretrained_G14, pretrained_D15], ) with gr.Row(): - but5 = gr.Button("⚠️Тренировка в один клик⚠️", variant="primary", visible=True) + but5 = gr.Button("1 Click Training", variant="primary", visible=False) but3.click( click_train, [