|
import json |
|
import os |
|
import shutil |
|
import urllib.request |
|
import zipfile |
|
from argparse import ArgumentParser |
|
|
|
import gradio as gr |
|
|
|
from main import song_cover_pipeline |
|
|
|
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
|
|
|
mdxnet_models_dir = os.path.join(BASE_DIR, 'mdxnet_models') |
|
rvc_models_dir = os.path.join(BASE_DIR, 'rvc_models') |
|
output_dir = os.path.join(BASE_DIR, 'song_output') |
|
|
|
|
|
def get_current_models(models_dir): |
|
models_list = os.listdir(models_dir) |
|
items_to_remove = ['hubert_base.pt', 'MODELS.txt', 'public_models.json', 'rmvpe.pt'] |
|
return [item for item in models_list if item not in items_to_remove] |
|
|
|
|
|
def update_models_list(): |
|
models_l = get_current_models(rvc_models_dir) |
|
return gr.Dropdown.update(choices=models_l) |
|
|
|
|
|
def load_public_models(): |
|
models_table = [] |
|
for model in public_models['voice_models']: |
|
if not model['name'] in voice_models: |
|
model = [model['name'], model['description'], model['credit'], model['url'], ', '.join(model['tags'])] |
|
models_table.append(model) |
|
|
|
tags = list(public_models['tags'].keys()) |
|
return gr.DataFrame.update(value=models_table), gr.CheckboxGroup.update(choices=tags) |
|
|
|
|
|
def extract_zip(extraction_folder, zip_name): |
|
os.makedirs(extraction_folder) |
|
with zipfile.ZipFile(zip_name, 'r') as zip_ref: |
|
zip_ref.extractall(extraction_folder) |
|
os.remove(zip_name) |
|
|
|
index_filepath, model_filepath = None, None |
|
for root, dirs, files in os.walk(extraction_folder): |
|
for name in files: |
|
if name.endswith('.index') and os.stat(os.path.join(root, name)).st_size > 1024 * 100: |
|
index_filepath = os.path.join(root, name) |
|
|
|
if name.endswith('.pth') and os.stat(os.path.join(root, name)).st_size > 1024 * 1024 * 40: |
|
model_filepath = os.path.join(root, name) |
|
|
|
if not model_filepath: |
|
raise gr.Error(f'No .pth model file was found in the extracted zip. Please check {extraction_folder}.') |
|
|
|
|
|
os.rename(model_filepath, os.path.join(extraction_folder, os.path.basename(model_filepath))) |
|
if index_filepath: |
|
os.rename(index_filepath, os.path.join(extraction_folder, os.path.basename(index_filepath))) |
|
|
|
|
|
for filepath in os.listdir(extraction_folder): |
|
if os.path.isdir(os.path.join(extraction_folder, filepath)): |
|
shutil.rmtree(os.path.join(extraction_folder, filepath)) |
|
|
|
|
|
def download_online_model(url, dir_name, progress=gr.Progress()): |
|
try: |
|
progress(0, desc=f'[~] Downloading voice model with name {dir_name}...') |
|
zip_name = url.split('/')[-1] |
|
extraction_folder = os.path.join(rvc_models_dir, dir_name) |
|
if os.path.exists(extraction_folder): |
|
raise gr.Error(f'Voice model directory {dir_name} already exists! Choose a different name for your voice model.') |
|
|
|
if 'pixeldrain.com' in url: |
|
url = f'https://pixeldrain.com/api/file/{zip_name}' |
|
|
|
urllib.request.urlretrieve(url, zip_name) |
|
|
|
progress(0.5, desc='[~] Extracting zip...') |
|
extract_zip(extraction_folder, zip_name) |
|
return f'[+] {dir_name} Model successfully downloaded!' |
|
|
|
except Exception as e: |
|
raise gr.Error(str(e)) |
|
|
|
|
|
def upload_local_model(zip_path, dir_name, progress=gr.Progress()): |
|
try: |
|
extraction_folder = os.path.join(rvc_models_dir, dir_name) |
|
if os.path.exists(extraction_folder): |
|
raise gr.Error(f'Voice model directory {dir_name} already exists! Choose a different name for your voice model.') |
|
|
|
zip_name = zip_path.name |
|
progress(0.5, desc='[~] Extracting zip...') |
|
extract_zip(extraction_folder, zip_name) |
|
return f'[+] {dir_name} Model successfully uploaded!' |
|
|
|
except Exception as e: |
|
raise gr.Error(str(e)) |
|
|
|
|
|
def filter_models(tags, query): |
|
models_table = [] |
|
|
|
|
|
if len(tags) == 0 and len(query) == 0: |
|
for model in public_models['voice_models']: |
|
models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']]) |
|
|
|
|
|
elif len(tags) > 0 and len(query) > 0: |
|
for model in public_models['voice_models']: |
|
if all(tag in model['tags'] for tag in tags): |
|
model_attributes = f"{model['name']} {model['description']} {model['credit']} {' '.join(model['tags'])}".lower() |
|
if query.lower() in model_attributes: |
|
models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']]) |
|
|
|
|
|
elif len(tags) > 0: |
|
for model in public_models['voice_models']: |
|
if all(tag in model['tags'] for tag in tags): |
|
models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']]) |
|
|
|
|
|
else: |
|
for model in public_models['voice_models']: |
|
model_attributes = f"{model['name']} {model['description']} {model['credit']} {' '.join(model['tags'])}".lower() |
|
if query.lower() in model_attributes: |
|
models_table.append([model['name'], model['description'], model['credit'], model['url'], model['tags']]) |
|
|
|
return gr.DataFrame.update(value=models_table) |
|
|
|
|
|
def pub_dl_autofill(pub_models, event: gr.SelectData): |
|
return gr.Text.update(value=pub_models.loc[event.index[0], 'URL']), gr.Text.update(value=pub_models.loc[event.index[0], 'Model Name']) |
|
|
|
|
|
def swap_visibility(): |
|
return gr.update(visible=True), gr.update(visible=False), gr.update(value=''), gr.update(value=None) |
|
|
|
|
|
def process_file_upload(file): |
|
return file.name, gr.update(value=file.name) |
|
|
|
|
|
def show_hop_slider(pitch_detection_algo): |
|
if pitch_detection_algo == 'mangio-crepe': |
|
return gr.update(visible=True) |
|
else: |
|
return gr.update(visible=False) |
|
|
|
css = """ |
|
footer {visibility: hidden !important;} |
|
""" |
|
|
|
if __name__ == '__main__': |
|
parser = ArgumentParser(description='Создайте AI кавер-версию в каталоге song_output/id.', add_help=True) |
|
parser.add_argument("--share", action="store_true", dest="share_enabled", default=False, help="Включить общий доступ") |
|
parser.add_argument("--listen", action="store_true", default=False, help="Сделайте WebUI доступным из вашей локальной сети.") |
|
parser.add_argument('--listen-host', type=str, help='Имя хоста, которое будет использовать сервер.') |
|
parser.add_argument('--listen-port', type=int, help='Порт прослушивания, который будет использовать сервер.') |
|
args = parser.parse_args() |
|
|
|
voice_models = get_current_models(rvc_models_dir) |
|
with open(os.path.join(rvc_models_dir, 'public_models.json'), encoding='utf8') as infile: |
|
public_models = json.load(infile) |
|
|
|
with gr.Blocks(title='AICoverGenWebUI', css=css) as app: |
|
|
|
with gr.Tab("Генерация"): |
|
|
|
with gr.Accordion('Основные настройки'): |
|
with gr.Row(): |
|
with gr.Column(): |
|
rvc_model = gr.Dropdown(voice_models, label='Voice Models', info='Папка моделей «AICoverGen --> rvc_models». После добавления новых моделей в эту папку нажмите кнопку «Обновить».') |
|
ref_btn = gr.Button('Обновить 🔁', variant='primary') |
|
|
|
with gr.Column() as yt_link_col: |
|
song_input = gr.Text(label='Песня', info='Ссылка на песню на YouTube или полный путь к локальному файлу. Для загрузки файла нажмите кнопку ниже. Пример: https://www.youtube.com/watch?v=M-mtdN6R3bQ') |
|
show_file_upload_button = gr.Button('Загрузить файл') |
|
|
|
with gr.Column(visible=False) as file_upload_col: |
|
local_file = gr.File(label='Аудио файл') |
|
song_input_file = gr.UploadButton('Загрузить 📂', file_types=['audio'], variant='primary') |
|
show_yt_link_button = gr.Button('По ссылке') |
|
song_input_file.upload(process_file_upload, inputs=[song_input_file], outputs=[local_file, song_input]) |
|
|
|
with gr.Column(): |
|
pitch = gr.Slider(-3, 3, value=0, step=1, label='Pitch Change (Vocals ONLY)', info='Обычно 1 используется для преобразования мужского голоса в женский, а -1 наоборот. (Октавы)') |
|
pitch_all = gr.Slider(-12, 12, value=0, step=1, label='Overall Pitch Change', info='Изменяет высоту/тональность вокала и инструментальной партии одновременно. Изменение этого параметра немного снижает качество звука. (Полутона)') |
|
show_file_upload_button.click(swap_visibility, outputs=[file_upload_col, yt_link_col, song_input, local_file]) |
|
show_yt_link_button.click(swap_visibility, outputs=[yt_link_col, file_upload_col, song_input, local_file]) |
|
|
|
with gr.Accordion('Параметры образования голоса', open=False): |
|
with gr.Row(): |
|
index_rate = gr.Slider(0, 1, value=0.5, label='Index Rate', info="Управляет тем, какую часть акцента голоса AI следует сохранить в вокале.") |
|
filter_radius = gr.Slider(0, 7, value=3, step=1, label='Filter radius', info='Если >=3: применить медианную фильтрацию к собранным результатам основного тона. Может уменьшить одышку') |
|
rms_mix_rate = gr.Slider(0, 1, value=0.25, label='RMS mix rate', info="Управляйте тем, насколько имитировать громкость исходного вокала (0) или фиксированную громкость (1).") |
|
protect = gr.Slider(0, 0.5, value=0.33, label='Protect rate', info='Защищайте глухие согласные и звуки дыхания. Установите значение 0,5, чтобы отключить.') |
|
with gr.Column(): |
|
f0_method = gr.Dropdown(['rmvpe', 'mangio-crepe'], value='rmvpe', label='Pitch detection algorithm', info='Лучший вариант — rmvpe (четкость вокала), затем mangio-crepe (более плавный вокал).') |
|
crepe_hop_length = gr.Slider(32, 320, value=128, step=1, visible=False, label='Crepe hop length', info='Более низкие значения приводят к более длительному преобразованию и более высокому риску прерывания голоса, но к большей точности высоты тона.') |
|
f0_method.change(show_hop_slider, inputs=f0_method, outputs=crepe_hop_length) |
|
keep_files = gr.Checkbox(label='Keep intermediate files', info='Сохраняйте все сгенерированные аудиофайлы в каталоге song_output/id, например. Изолированный вокал/инструментал. Оставьте флажок снятым, чтобы сэкономить место') |
|
|
|
with gr.Accordion('Параметры микширования звука', open=False): |
|
gr.Markdown('### Изменение громкости (децибелы)') |
|
with gr.Row(): |
|
main_gain = gr.Slider(-20, 20, value=0, step=1, label='Основной вокал') |
|
backup_gain = gr.Slider(-20, 20, value=0, step=1, label='Бэк-вокал') |
|
inst_gain = gr.Slider(-20, 20, value=0, step=1, label='Музыка') |
|
|
|
gr.Markdown('### Reverb Control on AI Vocals') |
|
with gr.Row(): |
|
reverb_rm_size = gr.Slider(0, 1, value=0.15, label='Room size', info='Чем больше комната, тем дольше время реверберации.') |
|
reverb_wet = gr.Slider(0, 1, value=0.2, label='Wetness level', info='Уровень AI-вокала с реверберацией') |
|
reverb_dry = gr.Slider(0, 1, value=0.8, label='Dryness level', info='Уровень AI-вокала без реверберации') |
|
reverb_damping = gr.Slider(0, 1, value=0.7, label='Damping level', info='Поглощение высоких частот в реверберации') |
|
|
|
gr.Markdown('### Аудио') |
|
output_format = gr.Dropdown(['mp3', 'wav'], value='mp3', label='Выходной формат аудио', info='mp3: небольшой размер файла, достойное качество. wav: большой размер файла, лучшее качество.') |
|
|
|
with gr.Row(): |
|
clear_btn = gr.ClearButton(value='Очистить', components=[song_input, rvc_model, keep_files, local_file]) |
|
generate_btn = gr.Button("Сгенерировать", variant='primary') |
|
ai_cover = gr.Audio(label='AI Cover', show_share_button=False) |
|
|
|
ref_btn.click(update_models_list, None, outputs=rvc_model) |
|
is_webui = gr.Number(value=1, visible=False) |
|
generate_btn.click(song_cover_pipeline, |
|
inputs=[song_input, rvc_model, pitch, keep_files, is_webui, main_gain, backup_gain, |
|
inst_gain, index_rate, filter_radius, rms_mix_rate, f0_method, crepe_hop_length, |
|
protect, pitch_all, reverb_rm_size, reverb_wet, reverb_dry, reverb_damping, |
|
output_format], |
|
outputs=[ai_cover]) |
|
clear_btn.click(lambda: [0, 0, 0, 0, 0.5, 3, 0.25, 0.33, 'rmvpe', 128, 0, 0.15, 0.2, 0.8, 0.7, 'mp3', None], |
|
outputs=[pitch, main_gain, backup_gain, inst_gain, index_rate, filter_radius, rms_mix_rate, |
|
protect, f0_method, crepe_hop_length, pitch_all, reverb_rm_size, reverb_wet, |
|
reverb_dry, reverb_damping, output_format, ai_cover]) |
|
|
|
|
|
with gr.Tab('Загрузка моделей'): |
|
|
|
with gr.Tab('С HuggingFace/Pixeldrain URL'): |
|
with gr.Row(): |
|
model_zip_link = gr.Text(label='Ссылка на скачивание модели', info='Это должен быть ZIP-файл, содержащий файл модели .pth и необязательный файл .index.') |
|
model_name = gr.Text(label='Название', info='Дайте вашей новой модели уникальное имя среди других моделей голоса.') |
|
|
|
with gr.Row(): |
|
download_btn = gr.Button('Скачать 🌐', variant='primary', scale=19) |
|
dl_output_message = gr.Text(label='Output Message', interactive=False, scale=20) |
|
|
|
download_btn.click(download_online_model, inputs=[model_zip_link, model_name], outputs=dl_output_message) |
|
|
|
gr.Markdown('## Input Voces') |
|
gr.Examples( |
|
[ |
|
['https://huggingface.co/phant0m4r/LiSA/resolve/main/LiSA.zip', 'Lisa'], |
|
['https://pixeldrain.com/u/3tJmABXA', '- Gura'], |
|
['https://pixeldrain.com/u/3Uf84csp', '- Yandex Alisa'], |
|
['https://huggingface.co/Kit-Lemonfoot/kitlemonfoot_rvc_models/resolve/main/AZKi%20(Hybrid).zip', 'Azki'] |
|
], |
|
[model_zip_link, model_name], |
|
[], |
|
download_online_model, |
|
) |
|
|
|
with gr.Tab('Из общедоступного индекса'): |
|
|
|
gr.Markdown('## Как использовать') |
|
gr.Markdown('- Нажмите «Инициализировать таблицу общедоступных моделей»') |
|
gr.Markdown('- Фильтрация моделей по тегам или строке поиска') |
|
gr.Markdown('- Выберите строку для автозаполнения ссылки для скачивания и названия модели') |
|
gr.Markdown('- Нажмите Загрузить') |
|
|
|
with gr.Row(): |
|
pub_zip_link = gr.Text(label='Ссылка на скачивание модели') |
|
pub_model_name = gr.Text(label='Название') |
|
|
|
with gr.Row(): |
|
download_pub_btn = gr.Button('Скачать 🌐', variant='primary', scale=19) |
|
pub_dl_output_message = gr.Text(label='Output Message', interactive=False, scale=20) |
|
|
|
filter_tags = gr.CheckboxGroup(value=[], label='Показать модели голоса с тегами', choices=[]) |
|
search_query = gr.Text(label='Search') |
|
load_public_models_button = gr.Button(value='Обновить таблицу общедоступных моделей', variant='primary') |
|
|
|
public_models_table = gr.DataFrame(value=[], headers=['Model Name', 'Description', 'Credit', 'URL', 'Tags'], label='Available Public Models', interactive=False) |
|
public_models_table.select(pub_dl_autofill, inputs=[public_models_table], outputs=[pub_zip_link, pub_model_name]) |
|
load_public_models_button.click(load_public_models, outputs=[public_models_table, filter_tags]) |
|
search_query.change(filter_models, inputs=[filter_tags, search_query], outputs=public_models_table) |
|
filter_tags.change(filter_models, inputs=[filter_tags, search_query], outputs=public_models_table) |
|
download_pub_btn.click(download_online_model, inputs=[pub_zip_link, pub_model_name], outputs=pub_dl_output_message) |
|
|
|
|
|
with gr.Tab('Загрузить свою модель'): |
|
gr.Markdown('## Загрузить локально обученную модель RVC v2 и индексный файл') |
|
gr.Markdown('- Найти файл модели (папка весов) и дополнительный индексный файл (папка журналов/[имя])') |
|
gr.Markdown('- Сжать файлы в zip-файл') |
|
gr.Markdown('- Загрузите zip-файл и укажите уникальное имя для голоса') |
|
gr.Markdown('- Нажмите Загрузить модель') |
|
|
|
with gr.Row(): |
|
with gr.Column(): |
|
zip_file = gr.File(label='Zip файл') |
|
|
|
local_model_name = gr.Text(label='Название') |
|
|
|
with gr.Row(): |
|
model_upload_button = gr.Button('Загрузить модель', variant='primary', scale=19) |
|
local_upload_output_message = gr.Text(label='Output Message', interactive=False, scale=20) |
|
model_upload_button.click(upload_local_model, inputs=[zip_file, local_model_name], outputs=local_upload_output_message) |
|
|
|
app.launch( |
|
share=args.share_enabled, |
|
enable_queue=True, |
|
server_name=None if not args.listen else (args.listen_host or '0.0.0.0'), |
|
server_port=args.listen_port, |
|
) |
|
|