228 lines
8.9 KiB
Python
228 lines
8.9 KiB
Python
import os
|
|
import sys
|
|
import re
|
|
import io
|
|
import torch
|
|
import numpy as np
|
|
import soundfile as sf
|
|
from typing import Dict, List, Optional, Tuple, Any
|
|
|
|
from vocoloom.voice import Voice
|
|
|
|
class VoiceManager:
|
|
"""
|
|
Central manager for VocoLoom multi-voice platform.
|
|
Discovers voices, manages VRAM caching, and executes speech synthesis.
|
|
"""
|
|
def __init__(self, root_dir: Optional[str] = None, device: Optional[str] = None):
|
|
if root_dir is None:
|
|
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
|
self.root_dir = root_dir
|
|
self.voices_dir = os.path.join(self.root_dir, "voices")
|
|
self.vocab_path = os.path.join(self.root_dir, "models", "F5-TTS-German", "vocab.txt")
|
|
|
|
self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
|
self.voices: Dict[str, Voice] = {}
|
|
|
|
# Shared base components
|
|
self.vocoder = None
|
|
self.vocab_char_map = None
|
|
self.vocab_size = None
|
|
self.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)
|
|
self.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")
|
|
|
|
# Active voice cache in VRAM
|
|
self.active_voice_id: Optional[str] = None
|
|
self.active_model = None
|
|
self.active_ref_audio = None
|
|
self.active_ref_text = None
|
|
|
|
self.refresh_voices()
|
|
|
|
def refresh_voices(self) -> List[Voice]:
|
|
"""Scans the voices/ directory and loads all voice definitions."""
|
|
self.voices.clear()
|
|
if not os.path.exists(self.voices_dir):
|
|
os.makedirs(self.voices_dir, exist_ok=True)
|
|
|
|
for entry in os.scandir(self.voices_dir):
|
|
if entry.is_dir():
|
|
json_path = os.path.join(entry.path, "voice.json")
|
|
if os.path.exists(json_path):
|
|
try:
|
|
voice = Voice.from_directory(entry.path)
|
|
self.voices[voice.id] = voice
|
|
print(f"[VoiceManager] Stimme geladen: {voice.name} (id='{voice.id}')")
|
|
except Exception as e:
|
|
print(f"[VoiceManager] Fehler beim Laden von '{entry.name}': {e}")
|
|
return list(self.voices.values())
|
|
|
|
def list_voices(self) -> List[Voice]:
|
|
return list(self.voices.values())
|
|
|
|
def get_voice(self, voice_id: str) -> Optional[Voice]:
|
|
return self.voices.get(voice_id)
|
|
|
|
def _ensure_shared_engine(self):
|
|
"""Initializes the shared tokenizer and vocoder once."""
|
|
if self.vocoder is None:
|
|
print(f"[VoiceManager] Initialisiere Vocoder und Tokenizer auf {self.device}...")
|
|
from f5_tts.infer.utils_infer import load_vocoder
|
|
from f5_tts.model.utils import get_tokenizer
|
|
|
|
self.vocab_char_map, self.vocab_size = get_tokenizer(self.vocab_path, "custom")
|
|
self.vocoder = load_vocoder(vocoder_name="vocos", is_local=False, device=self.device)
|
|
|
|
def load_voice(self, voice_id: str):
|
|
"""Loads a voice's model and prompt into VRAM if not already active."""
|
|
if self.active_voice_id == voice_id and self.active_model is not None:
|
|
return
|
|
|
|
voice = self.get_voice(voice_id)
|
|
if not voice:
|
|
raise ValueError(f"Stimme '{voice_id}' nicht gefunden. Verfügbar: {list(self.voices.keys())}")
|
|
|
|
self._ensure_shared_engine()
|
|
|
|
print(f"[VoiceManager] Lade Modell für '{voice.name}' in GPU-VRAM...")
|
|
from f5_tts.infer.utils_infer import preprocess_ref_audio_text
|
|
from f5_tts.model import CFM, DiT
|
|
|
|
# Clean previous model from VRAM
|
|
if self.active_model is not None:
|
|
del self.active_model
|
|
self.active_model = None
|
|
if torch.cuda.is_available():
|
|
torch.cuda.empty_cache()
|
|
|
|
ref_audio_path = voice.get_reference_audio_path()
|
|
ref_text = voice.reference_text
|
|
self.active_ref_audio, self.active_ref_text = preprocess_ref_audio_text(ref_audio_path, ref_text)
|
|
|
|
model = CFM(
|
|
transformer=DiT(**self.model_cfg, text_num_embeds=self.vocab_size, mel_dim=100),
|
|
mel_spec_kwargs=self.mel_spec_kwargs,
|
|
vocab_char_map=self.vocab_char_map,
|
|
)
|
|
|
|
model_path = voice.get_model_path()
|
|
checkpoint = torch.load(model_path, map_location=self.device, weights_only=True)
|
|
|
|
if "ema_model_state_dict" in checkpoint:
|
|
state = checkpoint["ema_model_state_dict"]
|
|
else:
|
|
state = checkpoint
|
|
|
|
state = {k.replace("ema_model.", ""): v for k, v in state.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 state:
|
|
del state[key]
|
|
|
|
model.load_state_dict(state)
|
|
self.active_model = model.to(self.device).eval()
|
|
self.active_voice_id = voice_id
|
|
print(f"[VoiceManager] '{voice.name}' ist jetzt aktiv und bereit.")
|
|
|
|
@staticmethod
|
|
def split_into_phrases(text: str, max_chars: int = 80) -> List[str]:
|
|
"""Splits text into natural breath phrases to avoid flow trajectory drift."""
|
|
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 synthesize(
|
|
self,
|
|
voice_id: str,
|
|
text: str,
|
|
speed: Optional[float] = None,
|
|
use_rvc: bool = False,
|
|
rvc_index: float = 0.70,
|
|
output_path: Optional[str] = None
|
|
) -> Tuple[np.ndarray, int, str]:
|
|
"""
|
|
Synthesizes speech with the given voice.
|
|
Returns: (audio_numpy_array, sample_rate, status_message)
|
|
"""
|
|
voice = self.get_voice(voice_id)
|
|
if not voice:
|
|
raise ValueError(f"Stimme '{voice_id}' nicht gefunden.")
|
|
|
|
self.load_voice(voice_id)
|
|
|
|
target_speed = speed if speed is not None else voice.default_speed
|
|
phrases = self.split_into_phrases(text)
|
|
if not phrases:
|
|
raise ValueError("Kein gültiger Text zum Synthetisieren vorhanden.")
|
|
|
|
from f5_tts.infer.utils_infer import infer_process
|
|
|
|
audio_segments = []
|
|
silence_250ms = np.zeros(int(24000 * 0.25), dtype=np.float32)
|
|
|
|
for i, phrase in enumerate(phrases):
|
|
audio, sr, _ = infer_process(
|
|
self.active_ref_audio,
|
|
self.active_ref_text,
|
|
phrase,
|
|
self.active_model,
|
|
self.vocoder,
|
|
mel_spec_type="vocos",
|
|
nfe_step=voice.nfe_step,
|
|
cfg_strength=voice.cfg_strength,
|
|
target_rms=0.1,
|
|
speed=target_speed,
|
|
device=self.device,
|
|
)
|
|
audio_segments.append(audio)
|
|
if i < len(phrases) - 1:
|
|
audio_segments.append(silence_250ms)
|
|
|
|
final_audio = np.concatenate(audio_segments)
|
|
|
|
# Optional RVC
|
|
if use_rvc and voice.rvc_support.get("supported"):
|
|
rvc_model = os.path.join(self.root_dir, voice.rvc_support.get("model_path", ""))
|
|
rvc_idx = os.path.join(self.root_dir, voice.rvc_support.get("index_path", ""))
|
|
if os.path.exists(rvc_model):
|
|
temp_in = os.path.join(self.root_dir, "temp_rvc_in.wav")
|
|
temp_out = os.path.join(self.root_dir, "temp_rvc_out.wav")
|
|
sf.write(temp_in, final_audio, sr)
|
|
|
|
applio_dir = os.path.join(self.root_dir, "Applio")
|
|
if applio_dir not in sys.path:
|
|
sys.path.insert(0, applio_dir)
|
|
cwd = os.getcwd()
|
|
try:
|
|
os.chdir(applio_dir)
|
|
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_in,
|
|
output_path=temp_out,
|
|
pth_path=rvc_model,
|
|
index_path=rvc_idx if os.path.exists(rvc_idx) else None,
|
|
export_format="WAV"
|
|
)
|
|
final_audio, sr = sf.read(temp_out)
|
|
finally:
|
|
os.chdir(cwd)
|
|
|
|
if output_path:
|
|
sf.write(output_path, final_audio, sr)
|
|
|
|
status_msg = f"Erfolgreich generiert ({len(phrases)} Phrasen, {voice.name})"
|
|
return final_audio, sr, status_msg
|