233 lines
9.6 KiB
Python
233 lines
9.6 KiB
Python
import os
|
||
import sys
|
||
import re
|
||
import torch
|
||
import numpy as np
|
||
import soundfile as sf
|
||
import gradio as gr
|
||
|
||
BASE_DIR = r"C:\GitHub\VocoLoom"
|
||
VOCAB_PATH = os.path.join(BASE_DIR, "models", "F5-TTS-German", "vocab.txt")
|
||
CKPT_PATH = os.path.join(BASE_DIR, "ckpts", "Juergen_Seiferth", "model_200.pt")
|
||
|
||
REF_AUDIO = os.path.join(BASE_DIR, "cleaned_dataset", "snippet_10_00-06-13-10_to_00-06-23-10_clean.wav")
|
||
REF_TEXT = "Ich bin immer zufrieden. Ich muss das mal so sagen. Was nicht ganz läuft so wie ich das will, das wird so gemacht, damit das läuft. Zum Endeffekt ist passend."
|
||
|
||
MODEL_PATH = os.path.join(BASE_DIR, "Applio", "logs", "Juergen_Seiferth", "Juergen_Seiferth_300e_7800s.pth")
|
||
INDEX_PATH = os.path.join(BASE_DIR, "Applio", "logs", "Juergen_Seiferth", "Juergen_Seiferth.index")
|
||
|
||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||
|
||
print("[WebUI] Initialisiere F5-TTS Jürgen Seiferth Engine auf CUDA...")
|
||
from f5_tts.infer.utils_infer import load_vocoder, infer_process, preprocess_ref_audio_text
|
||
from f5_tts.model import CFM, DiT
|
||
from f5_tts.model.utils import get_tokenizer
|
||
|
||
vocab_char_map, vocab_size = get_tokenizer(VOCAB_PATH, "custom")
|
||
mel_spec_kwargs = dict(n_fft=1024, hop_length=256, win_length=1024, n_mel_channels=100, target_sample_rate=24000, mel_spec_type="vocos")
|
||
model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, text_mask_padding=False, conv_layers=4, pe_attn_head=1)
|
||
|
||
vocoder = load_vocoder(vocoder_name="vocos", is_local=False, device=device)
|
||
ref_audio_proc, ref_text_proc = preprocess_ref_audio_text(REF_AUDIO, REF_TEXT)
|
||
|
||
model = CFM(
|
||
transformer=DiT(**model_cfg, text_num_embeds=vocab_size, mel_dim=100),
|
||
mel_spec_kwargs=mel_spec_kwargs,
|
||
vocab_char_map=vocab_char_map,
|
||
)
|
||
checkpoint = torch.load(CKPT_PATH, map_location=device, weights_only=True)
|
||
ema_state = {k.replace("ema_model.", ""): v for k, v in checkpoint["ema_model_state_dict"].items() if k not in ["initted", "step"]}
|
||
for key in ["mel_spec.mel_stft.mel_scale.fb", "mel_spec.mel_stft.spectrogram.window"]:
|
||
if key in ema_state:
|
||
del ema_state[key]
|
||
model.load_state_dict(ema_state)
|
||
model = model.to(device).eval()
|
||
print("[WebUI] Modell erfolgreich in GPU-VRAM geladen! Bereit für Blitz-Synthese.")
|
||
|
||
def split_into_phrases(text, max_chars=80):
|
||
sentences = re.split(r'(?<=[.!?])\s+', text.strip())
|
||
chunks = []
|
||
for s in sentences:
|
||
s = s.strip()
|
||
if not s:
|
||
continue
|
||
if len(s) > max_chars and ',' in s:
|
||
sub = re.split(r'(?<=,)\s+', s)
|
||
chunks.extend([sub_s.strip() for sub_s in sub if sub_s.strip()])
|
||
else:
|
||
chunks.append(s)
|
||
return chunks
|
||
|
||
def tts_generate(text, speed, use_rvc, rvc_index):
|
||
if not text.strip():
|
||
return None, "Bitte gib einen Text ein."
|
||
|
||
phrases = split_into_phrases(text)
|
||
audio_segments = []
|
||
silence_250ms = np.zeros(int(24000 * 0.25), dtype=np.float32)
|
||
|
||
for i, phrase in enumerate(phrases):
|
||
audio, sr, _ = infer_process(
|
||
ref_audio_proc,
|
||
ref_text_proc,
|
||
phrase,
|
||
model,
|
||
vocoder,
|
||
mel_spec_type="vocos",
|
||
nfe_step=64,
|
||
cfg_strength=1.8,
|
||
target_rms=0.1,
|
||
speed=speed,
|
||
device=device,
|
||
)
|
||
audio_segments.append(audio)
|
||
if i < len(phrases) - 1:
|
||
audio_segments.append(silence_250ms)
|
||
|
||
final_audio = np.concatenate(audio_segments)
|
||
final_out = os.path.join(BASE_DIR, "web_output_juergen.wav")
|
||
|
||
if use_rvc and rvc_index > 0:
|
||
temp_f5 = os.path.join(BASE_DIR, "temp_web_f5.wav")
|
||
sf.write(temp_f5, final_audio, sr)
|
||
os.chdir(r"C:\GitHub\VocoLoom\Applio")
|
||
sys.path.insert(0, r"C:\GitHub\VocoLoom\Applio")
|
||
from core import run_infer_script
|
||
run_infer_script(
|
||
pitch=0,
|
||
index_rate=rvc_index,
|
||
volume_envelope=1.0,
|
||
protect=0.33,
|
||
f0_method="rmvpe",
|
||
input_path=temp_f5,
|
||
output_path=final_out,
|
||
pth_path=MODEL_PATH,
|
||
index_path=INDEX_PATH,
|
||
f0_autotune=False,
|
||
f0_autotune_strength=1.0,
|
||
proposed_pitch=False,
|
||
proposed_pitch_threshold=155.0,
|
||
export_format="WAV",
|
||
embedder_model="contentvec",
|
||
embedder_model_custom=None,
|
||
formant_shifting=False,
|
||
formant_qfrency=1.0,
|
||
formant_timbre=1.0,
|
||
sid=0,
|
||
inference_engine=None,
|
||
onnx_precision="auto",
|
||
cleanup_mode="off",
|
||
cleanup_strength=12
|
||
)
|
||
mode_str = f"F5-TTS Step 200 + {int(rvc_index*100)}% RVC Veredelung"
|
||
else:
|
||
sf.write(final_out, final_audio, sr)
|
||
mode_str = "Pure F5-TTS Step 200 (100% Original-Sprachfluss)"
|
||
|
||
return final_out, f"Erfolgreich generiert ({len(phrases)} Phrasen, {mode_str})!"
|
||
|
||
def vc_convert(audio_path, rvc_index):
|
||
if not audio_path:
|
||
return None, "Bitte nimm Audio auf oder lade eine Datei hoch."
|
||
|
||
os.chdir(r"C:\GitHub\VocoLoom\Applio")
|
||
sys.path.insert(0, r"C:\GitHub\VocoLoom\Applio")
|
||
from core import run_infer_script
|
||
|
||
out_rvc = os.path.join(BASE_DIR, "web_vc_juergen.wav")
|
||
run_infer_script(
|
||
pitch=0,
|
||
index_rate=rvc_index,
|
||
volume_envelope=1.0,
|
||
protect=0.33,
|
||
f0_method="rmvpe",
|
||
input_path=audio_path,
|
||
output_path=out_rvc,
|
||
pth_path=MODEL_PATH,
|
||
index_path=INDEX_PATH,
|
||
f0_autotune=False,
|
||
f0_autotune_strength=1.0,
|
||
proposed_pitch=False,
|
||
proposed_pitch_threshold=155.0,
|
||
export_format="WAV",
|
||
embedder_model="contentvec",
|
||
embedder_model_custom=None,
|
||
formant_shifting=False,
|
||
formant_qfrency=1.0,
|
||
formant_timbre=1.0,
|
||
sid=0,
|
||
inference_engine=None,
|
||
onnx_precision="auto",
|
||
cleanup_mode="off",
|
||
cleanup_strength=12
|
||
)
|
||
return out_rvc, "Stimme erfolgreich zu Jürgen konvertiert!"
|
||
|
||
custom_css = """
|
||
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
|
||
.gradio-container { max-width: 950px !important; margin: auto; }
|
||
.main-title { text-align: center; margin-bottom: 20px; }
|
||
"""
|
||
|
||
with gr.Blocks(title="VocoLoom - Jürgen Seiferth Voice Studio") as demo:
|
||
gr.Markdown("# 🎡 VocoLoom — Jürgen Seiferth Voice Studio", elem_classes=["main-title"])
|
||
gr.Markdown(
|
||
"Gib einen beliebigen Satz ein und lass ihn von **Jürgen Seiferth** (Schausteller-Legende aus *„Die Welt ist unser Feld“*, 1995) mit seiner echten Stimme und Ruhrpott-Kadenz sprechen."
|
||
)
|
||
|
||
with gr.Tab("🗣️ Text-to-Speech (Jürgen spricht)"):
|
||
with gr.Row():
|
||
with gr.Column(scale=3):
|
||
text_input = gr.Textbox(
|
||
label="Text eingeben",
|
||
placeholder="Frag mal, ob du die Fotos vom Tobias krichst. Wir haben keine gemacht. Aber nicht in die Gruppen rein senden! Der Kenny stellt's bloß wieder online.",
|
||
lines=4,
|
||
value="Frag mal, ob du die Fotos vom Tobias krichst. Wir haben keine gemacht. Aber nicht in die Gruppen rein senden! Der Kenny stellt's bloß wieder online."
|
||
)
|
||
with gr.Row():
|
||
speed_slider = gr.Slider(minimum=0.7, maximum=1.3, value=1.0, step=0.05, label="Sprechgeschwindigkeit")
|
||
use_rvc_check = gr.Checkbox(label="Zusätzliche RVC-Veredelung", value=False)
|
||
rvc_slider = gr.Slider(minimum=0.1, maximum=1.0, value=0.70, step=0.05, label="RVC Stärke (Index)")
|
||
|
||
tts_btn = gr.Button("🎤 Jürgen sprechen lassen", variant="primary", size="lg")
|
||
|
||
with gr.Column(scale=2):
|
||
tts_output_audio = gr.Audio(label="Jürgens Sprachausgabe", type="filepath")
|
||
tts_status = gr.Textbox(label="Status", interactive=False)
|
||
|
||
gr.Examples(
|
||
examples=[
|
||
["Frag mal, ob du die Fotos vom Tobias krichst. Wir haben keine gemacht. Aber nicht in die Gruppen rein senden! Der Kenny stellt's bloß wieder online."],
|
||
["Mahlzeit! Ich bin immer zufrieden. Was nicht ganz läuft so wie ich das will, das wird so gemacht, dass es passt."],
|
||
["Fertig Ballett oder was? Jetzt packen wir hier an, sonst wird das heute Abend wieder nix!"],
|
||
["Soll mich aufregen? Eigentlich gar nicht. Lässt mich von der Sache her ein bisschen alles kalt."]
|
||
],
|
||
inputs=[text_input]
|
||
)
|
||
|
||
tts_btn.click(
|
||
fn=tts_generate,
|
||
inputs=[text_input, speed_slider, use_rvc_check, rvc_slider],
|
||
outputs=[tts_output_audio, tts_status]
|
||
)
|
||
|
||
with gr.Tab("🎙️ Voice Conversion (Deine Stimme -> Jürgen)"):
|
||
gr.Markdown("Sprich etwas ins Mikrofon oder lade eine Aufnahme hoch – deine Stimme wird in Jürgens Stimme umgewandelt.")
|
||
with gr.Row():
|
||
with gr.Column():
|
||
vc_input_audio = gr.Audio(label="Deine Spracheingabe", type="filepath")
|
||
vc_rvc_slider = gr.Slider(minimum=0.1, maximum=1.0, value=0.70, step=0.05, label="RVC Stärke (Index)")
|
||
vc_btn = gr.Button("🔄 In Jürgen umwandeln", variant="primary")
|
||
with gr.Column():
|
||
vc_output_audio = gr.Audio(label="Jürgen Sprachausgabe", type="filepath")
|
||
vc_status = gr.Textbox(label="Status", interactive=False)
|
||
|
||
vc_btn.click(
|
||
fn=vc_convert,
|
||
inputs=[vc_input_audio, vc_rvc_slider],
|
||
outputs=[vc_output_audio, vc_status]
|
||
)
|
||
|
||
if __name__ == "__main__":
|
||
demo.launch(server_name="127.0.0.1", server_port=7860, allowed_paths=[BASE_DIR], theme=gr.themes.Soft(), css=custom_css)
|