| """ |
| Script ini dibuat oleh __drat |
| Petunjuk: |
| 1. Script ini digunakan untuk mengkonversi teks menjadi suara menggunakan teknologi Edge TTS dan Retrieval-based Voice Conversion (RVC). |
| 2. Teknologi yang digunakan meliputi model text-to-speech (TTS) yang canggih dengan konversi teks ke fonem (G2P). |
| 3. Model yang dipakai dilatih khusus untuk bahasa Indonesia, Jawa, dan Sunda. |
| 4. Antarmuka dibuat dengan menggunakan Gradio dengan tema kustom bernama IndonesiaTheme. |
| |
| Cara Menggunakan: |
| 1. Pilih model suara dari dropdown yang tersedia. |
| 2. Atur parameter seperti kecepatan bicara, metode ekstraksi pitch, dan tingkat perlindungan. |
| 3. Masukkan teks yang ingin dikonversi menjadi suara. |
| 4. Klik tombol "Convert" untuk memulai proses konversi. |
| 5. Dengarkan hasil konversi melalui komponen audio yang tersedia. |
| """ |
|
|
| import asyncio |
| import datetime |
| import logging |
| import os |
| import time |
| import traceback |
| import warnings |
|
|
| import edge_tts |
| import gradio as gr |
| import librosa |
| import torch |
| from fairseq import checkpoint_utils |
|
|
| from config import Config |
| from lib.infer_pack.models import ( |
| SynthesizerTrnMs256NSFsid, |
| SynthesizerTrnMs256NSFsid_nono, |
| SynthesizerTrnMs768NSFsid, |
| SynthesizerTrnMs768NSFsid_nono, |
| ) |
| from rmvpe import RMVPE |
| from vc_infer_pipeline import VC |
| from themes import IndonesiaTheme |
|
|
| |
| warnings.filterwarnings("ignore") |
|
|
| |
| logging.getLogger("fairseq").setLevel(logging.ERROR) |
| logging.getLogger("numba").setLevel(logging.ERROR) |
| logging.getLogger("markdown_it").setLevel(logging.ERROR) |
| logging.getLogger("urllib3").setLevel(logging.ERROR) |
| logging.getLogger("matplotlib").setLevel(logging.ERROR) |
|
|
| |
| limitation = os.getenv("SYSTEM") == "spaces" |
|
|
| |
| config = Config() |
|
|
| |
| edge_output_filename = "edge_output.mp3" |
| tts_voice_list = asyncio.get_event_loop().run_until_complete(edge_tts.list_voices()) |
| tts_voices = [f"{v['ShortName']}-{v['Gender']}" for v in tts_voice_list] |
|
|
| |
| model_root = "weights" |
| models = [d for d in os.listdir(model_root) if os.path.isdir(f"{model_root}/{d}")] |
| models.sort() |
|
|
| |
| def model_data(model_name): |
| |
| pth_path = [ |
| f"{model_root}/{model_name}/{f}" |
| for f in os.listdir(f"{model_root}/{model_name}") |
| if f.endswith(".pth") |
| ][0] |
| print(f"Memuat {pth_path}") |
| cpt = torch.load(pth_path, map_location="cpu") |
| tgt_sr = cpt["config"][-1] |
| cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] |
| if_f0 = cpt.get("f0", 1) |
| version = cpt.get("version", "v1") |
|
|
| |
| if version == "v1": |
| if if_f0 == 1: |
| net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=config.is_half) |
| else: |
| net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"]) |
| elif version == "v2": |
| if if_f0 == 1: |
| net_g = SynthesizerTrnMs768NSFsid(*cpt["config"], is_half=config.is_half) |
| else: |
| net_g = SynthesizerTrnMs768NSFsid_nono(*cpt["config"]) |
| else: |
| raise ValueError("Versi tidak diketahui") |
| |
| |
| del net_g.enc_q |
| net_g.load_state_dict(cpt["weight"], strict=False) |
| print("Model dimuat") |
| net_g.eval().to(config.device) |
| |
| |
| if config.is_half: |
| net_g = net_g.half() |
| else: |
| net_g = net_g.float() |
| |
| vc = VC(tgt_sr, config) |
|
|
| |
| index_files = [ |
| f"{model_root}/{model_name}/{f}" |
| for f in os.listdir(f"{model_root}/{model_name}") |
| if f.endswith(".index") |
| ] |
| if len(index_files) == 0: |
| print("Tidak ada file indeks ditemukan") |
| index_file = "" |
| else: |
| index_file = index_files[0] |
| print(f"File indeks ditemukan: {index_file}") |
|
|
| return tgt_sr, net_g, vc, version, index_file, if_f0 |
|
|
| |
| def load_hubert(): |
| models, _, _ = checkpoint_utils.load_model_ensemble_and_task( |
| ["hubert_base.pt"], |
| suffix="", |
| ) |
| hubert_model = models[0] |
| hubert_model = hubert_model.to(config.device) |
| if config.is_half: |
| hubert_model = hubert_model.half() |
| else: |
| hubert_model = hubert_model.float() |
| return hubert_model.eval() |
|
|
| |
| def tts( |
| model_name, |
| speed, |
| tts_text, |
| tts_voice, |
| f0_up_key, |
| f0_method, |
| index_rate, |
| protect, |
| filter_radius=3, |
| resample_sr=0, |
| rms_mix_rate=0.25, |
| ): |
| print("------------------") |
| print(datetime.datetime.now()) |
| print("Teks TTS:") |
| print(tts_text) |
| print(f"Suara TTS: {tts_voice}, kecepatan: {speed}") |
| print(f"Nama model: {model_name}") |
| print(f"F0: {f0_method}, Key: {f0_up_key}, Index: {index_rate}, Protect: {protect}") |
| try: |
| |
| if limitation and len(tts_text) > 280: |
| print("Error: Teks terlalu panjang") |
| return ( |
| f"Teks harus kurang dari 280 karakter di space ini, tetapi didapatkan {len(tts_text)} karakter.", |
| None, |
| None, |
| ) |
| |
| t0 = time.time() |
| |
| if speed >= 0: |
| speed_str = f"+{speed}%" |
| else: |
| speed_str = f"{speed}%" |
| |
| |
| asyncio.run( |
| edge_tts.Communicate( |
| tts_text, "-".join(tts_voice.split("-")[:-1]), rate=speed_str |
| ).save(edge_output_filename) |
| ) |
| t1 = time.time() |
| edge_time = t1 - t0 |
| |
| |
| audio, sr = librosa.load(edge_output_filename, sr=16000, mono=True) |
| duration = len(audio) / sr |
| print(f"Durasi audio: {duration}s") |
| |
| |
| if limitation and duration >= 20: |
| print("Error: Audio terlalu panjang") |
| return ( |
| f"Audio harus kurang dari 20 detik di space ini, tetapi didapatkan {duration}s.", |
| edge_output_filename, |
| None, |
| ) |
| |
| f0_up_key = int(f0_up_key) |
|
|
| |
| tgt_sr, net_g, vc, version, index_file, if_f0 = model_data(model_name) |
| if f0_method == "rmvpe": |
| vc.model_rmvpe = rmvpe_model |
| times = [0, 0, 0] |
| |
| |
| audio_opt = vc.pipeline( |
| hubert_model, |
| net_g, |
| 0, |
| audio, |
| edge_output_filename, |
| times, |
| f0_up_key, |
| f0_method, |
| index_file, |
| index_rate, |
| if_f0, |
| filter_radius, |
| tgt_sr, |
| resample_sr, |
| rms_mix_rate, |
| version, |
| protect, |
| None, |
| ) |
| |
| |
| if tgt_sr != resample_sr >= 16000: |
| tgt_sr = resample_sr |
| |
| info = f"Berhasil. Waktu: edge-tts: {edge_time}s, npy: {times[0]}s, f0: {times[1]}s, infer: {times[2]}s" |
| print(info) |
| return ( |
| info, |
| edge_output_filename, |
| (tgt_sr, audio_opt), |
| ) |
| except EOFError: |
| info = ( |
| "Sepertinya output edge-tts tidak valid. " |
| "Ini bisa terjadi jika teks input dan pembicara tidak cocok. " |
| "Misalnya, mungkin Anda memasukkan teks dalam bahasa Jepang (tanpa huruf alfabet) tetapi memilih pembicara non-Jepang?" |
| ) |
| print(info) |
| return info, None, None |
| except: |
| info = traceback.format_exc() |
| print(info) |
| return info, None, None |
|
|
| |
| print("Memuat model hubert...") |
| hubert_model = load_hubert() |
| print("Model hubert dimuat.") |
|
|
| |
| print("Memuat model rmvpe...") |
| rmvpe_model = RMVPE("rmvpe.pt", config.is_half, config.device) |
| print("Model rmvpe dimuat.") |
|
|
| |
| initial_md = """ |
| # TTS-RVC-Tokoh Indonesia |
| |
| Pembuktian algoritma **Retrieval-based Voice Conversion (RVC)** dan teknologi **Edge TTS** yang dapat membuat clone dari suara tokoh-tokoh penting di Indonesia. |
| |
| **Perhatian:** Harap tidak menyalahgunakan teknologi ini. |
| """ |
|
|
| |
| app = gr.Blocks(theme=IndonesiaTheme(), title="TTS-RVC-Tokoh Indonesia") |
| with app: |
| |
| gr.HTML(""" |
| <div style="text-align: center; margin-top: 20px;"> |
| <img src="https://i.ibb.co.com/dm13YjJ/banner1.jpg" alt="Banner" style="width: 100%; max-width: 1200px; border-radius: 10px;"> |
| </div> |
| """) |
| gr.Markdown(initial_md) |
| with gr.Row(): |
| with gr.Column(): |
| model_name = gr.Dropdown( |
| label="Model", |
| choices=models, |
| value=models[0], |
| ) |
| f0_key_up = gr.Number( |
| label="Tune (+12 = 1 oktaf dari edge-tts, nilai terbaik tergantung pada model dan pembicara)", |
| value=2, |
| ) |
| with gr.Column(): |
| f0_method = gr.Radio( |
| label="Metode ekstraksi pitch (pm: sangat cepat, kualitas rendah, rmvpe: sedikit lambat, kualitas tinggi)", |
| choices=["pm", "rmvpe"], |
| value="rmvpe", |
| interactive=True, |
| ) |
| index_rate = gr.Slider( |
| minimum=0, |
| maximum=1, |
| label="Tingkat indeks", |
| value=0.5, |
| interactive=True, |
| ) |
| protect0 = gr.Slider( |
| minimum=0, |
| maximum=0.5, |
| label="Perlindungan", |
| value=0.33, |
| step=0.01, |
| interactive=True, |
| ) |
| with gr.Row(): |
| with gr.Column(): |
| tts_voice = gr.Dropdown( |
| label="Pembicara Edge-tts (format: bahasa-Negara-Nama-Jenis Kelamin), pastikan jenis kelamin cocok dengan model", |
| choices=tts_voices, |
| allow_custom_value=False, |
| value="id-ID-ArdiNeural-Male", |
| ) |
| speed = gr.Slider( |
| minimum=-100, |
| maximum=100, |
| label="Kecepatan bicara (%)", |
| value=0, |
| step=10, |
| interactive=True, |
| ) |
| tts_text = gr.Textbox(label="Teks Input", value="Konversi dari teks ke suara dalam bahasa Indonesia.") |
| with gr.Column(): |
| but0 = gr.Button("Konversi", variant="primary") |
| info_text = gr.Textbox(label="Informasi Output") |
| with gr.Column(): |
| edge_tts_output = gr.Audio(label="Suara Edge", type="filepath") |
| tts_output = gr.Audio(label="Hasil") |
| but0.click( |
| tts, |
| [ |
| model_name, |
| speed, |
| tts_text, |
| tts_voice, |
| f0_key_up, |
| f0_method, |
| index_rate, |
| protect0, |
| ], |
| [info_text, edge_tts_output, tts_output], |
| ) |
| with gr.Row(): |
| examples = gr.Examples( |
| examples_per_page=100, |
| examples=[ |
| ["Ini adalah demo percobaan menggunakan Bahasa Indonesia untuk pria.", "id-ID-ArdiNeural-Male"], |
| ["Ini adalah teks percobaan menggunakan Bahasa Indonesia pada wanita.", "id-ID-GadisNeural-Female"], |
| ], |
| inputs=[tts_text, tts_voice], |
| ) |
| |
| |
| gr.HTML(""" |
| <footer style="text-align: center; margin-top: 20px; color:silver;"> |
| Transfer Energi Semesta Digital © 2024 __drat. | 🇮🇩 Untuk Indonesia Jaya! |
| </footer> |
| """) |
|
|
| |
| app.launch() |
|
|