MyTTSAPI / core /cloner.py
AthanasiusRG's picture
Update core/cloner.py
29795a4 verified
Raw
History Blame Contribute Delete
10.5 kB
import importlib.resources
import json
import os
import sys
import tempfile
import time
import types
import numpy as np
import torch
import soundfile as sf
from huggingface_hub import hf_hub_download
from kanade_tokenizer import KanadeModel, load_audio, load_vocoder, vocode
from kokoro_onnx import Kokoro
from kokoro_onnx.config import MAX_PHONEME_LENGTH, SAMPLE_RATE
from misaki import espeak
from misaki.espeak import EspeakG2P
from core.chunked_convert import chunked_voice_conversion
class KokoClone:
def __init__(self, kanade_model="frothywater/kanade-12.5hz", hf_repo="PatnaikAshish/kokoclone"):
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Initializing KokoClone on: {self.device.type.upper()}")
self.hf_repo = hf_repo
print("Loading Kanade model...")
self.kanade = KanadeModel.from_pretrained(kanade_model).to(self.device).eval()
self.vocoder = load_vocoder(self.kanade.config.vocoder_name).to(self.device)
self.sample_rate = self.kanade.config.sample_rate
self.kokoro_cache = {}
def _get_vocab_config(self, lang):
if lang in {"zh", "ja"}:
zh_vocab = os.path.join("model", "config-v1.1-zh.json")
if not os.path.exists(zh_vocab):
print("Downloading missing file 'config-v1.1-zh.json' from hexgrad/Kokoro-82M-v1.1-zh...")
hf_hub_download(
repo_id="hexgrad/Kokoro-82M-v1.1-zh",
filename="config.json",
local_dir=".",
)
downloaded = os.path.join("config.json")
if os.path.exists(downloaded):
os.replace(downloaded, zh_vocab)
if os.path.exists(zh_vocab):
return zh_vocab
local_config = os.path.join("model", "config.json")
if os.path.exists(local_config):
try:
with open(local_config, encoding="utf-8") as fp:
config = json.load(fp)
if isinstance(config, dict) and "vocab" in config:
return local_config
print("Warning: model/config.json is missing 'vocab'; using packaged kokoro_onnx config instead")
except (OSError, json.JSONDecodeError) as exc:
print(f"Warning: could not read model/config.json ({exc}); using packaged kokoro_onnx config instead")
return str(importlib.resources.files("kokoro_onnx").joinpath("config.json"))
def _patch_kokoro_compat(self, kokoro):
input_types = {input_meta.name: input_meta.type for input_meta in kokoro.sess.get_inputs()}
if input_types.get("speed") != "tensor(float)" or "input_ids" not in input_types:
return kokoro
def _create_audio_compat(instance, phonemes, voice, speed):
if len(phonemes) > MAX_PHONEME_LENGTH:
phonemes = phonemes[:MAX_PHONEME_LENGTH]
start_t = time.time()
tokens = np.array(instance.tokenizer.tokenize(phonemes), dtype=np.int64)
assert len(tokens) <= MAX_PHONEME_LENGTH, (
f"Context length is {MAX_PHONEME_LENGTH}, but leave room for the pad token 0 at start & end"
)
voice_style = voice[len(tokens)]
inputs = {
"input_ids": [[0, *tokens, 0]],
"style": np.array(voice_style, dtype=np.float32),
"speed": np.array([speed], dtype=np.float32),
}
audio = instance.sess.run(None, inputs)[0]
audio_duration = len(audio) / SAMPLE_RATE
create_duration = time.time() - start_t
if audio_duration > 0:
_ = create_duration / audio_duration
return audio, SAMPLE_RATE
kokoro._create_audio = types.MethodType(_create_audio_compat, kokoro)
return kokoro
def _ensure_file(self, folder, filename):
filepath = os.path.join(folder, filename)
if not os.path.exists(filepath):
print(f"Downloading missing file '{filename}' from {self.hf_repo}...")
hf_hub_download(
repo_id=self.hf_repo,
filename=f"{folder}/{filename}",
local_dir="."
)
return filepath
def _create_en_callable(self):
en_g2p = EspeakG2P(language="en-us")
def en_callable(text):
try:
phonemes, _ = en_g2p(text)
return phonemes
except Exception:
return text
return en_callable
def _get_config(self, lang):
model_file = self._ensure_file("model", "kokoro.onnx")
voices_file = self._ensure_file("voice", "voices-v1.0.bin")
vocab = None
g2p = None
en_callable = None
if lang == "en":
voice = "af_bella"
elif lang == "hi":
g2p = EspeakG2P(language="hi")
voice = "hf_alpha"
elif lang == "fr":
g2p = EspeakG2P(language="fr-fr")
voice = "ff_siwis"
elif lang == "it":
g2p = EspeakG2P(language="it")
voice = "im_nicola"
elif lang == "es":
g2p = EspeakG2P(language="es")
voice = "im_nicola"
elif lang == "pt":
g2p = EspeakG2P(language="pt-br")
voice = "pf_dora"
elif lang == "ja":
from misaki import ja
import unidic
import subprocess
if not os.path.exists(unidic.DICDIR):
print("Downloading Japanese dictionary...")
subprocess.run([sys.executable, "-m", "unidic", "download"], check=True)
g2p = ja.JAG2P()
voice = "jf_alpha"
vocab = self._get_vocab_config(lang)
en_callable = self._create_en_callable()
elif lang == "zh":
from misaki import zh
import re
base_g2p = zh.ZHG2P(version="1.1")
en_callable = self._create_en_callable()
def mixed_g2p(text):
parts = re.split(r'([a-zA-Z]+)', text)
phonemes_list = []
for part in parts:
if part and part[0].isalpha() and part[0].isascii():
phonemes_list.append(en_callable(part))
else:
if part:
ph, _ = base_g2p(part)
phonemes_list.append(ph)
return "".join(phonemes_list), text
g2p = mixed_g2p
voice = "zf_001"
model_file = self._ensure_file("model", "kokoro-v1.1-zh.onnx")
voices_file = self._ensure_file("voice", "voices-v1.1-zh.bin")
vocab = self._get_vocab_config(lang)
else:
raise ValueError(f"Language '{lang}' not supported.")
return model_file, voices_file, vocab, g2p, voice, en_callable
def _load_kokoro(self, model_file, voices_file, vocab):
"""Charge Kokoro avec cache."""
if model_file not in self.kokoro_cache:
kokoro = Kokoro(model_file, voices_file, vocab_config=vocab) if vocab else Kokoro(model_file, voices_file)
self.kokoro_cache[model_file] = self._patch_kokoro_compat(kokoro)
return self.kokoro_cache[model_file]
def speak(self, text, lang, output_path="output.wav", speed=1.0):
"""
TTS simple avec la voix Kokoro par défaut — sans clonage.
Supporte toutes les langues disponibles.
"""
model_file, voices_file, vocab, g2p, voice, en_callable = self._get_config(lang)
kokoro = self._load_kokoro(model_file, voices_file, vocab)
print(f"Synthesizing text ({lang.upper()}) with voice '{voice}'...")
if g2p:
phonemes, _ = g2p(text)
samples, sr = kokoro.create(phonemes, voice=voice, speed=speed, is_phonemes=True)
else:
samples, sr = kokoro.create(text, voice=voice, speed=speed, lang="en-us")
sf.write(output_path, samples, sr)
print(f"Success! Saved: {output_path}")
def generate(self, text, lang, reference_audio, output_path="output.wav"):
"""TTS + voice cloning via Kanade."""
model_file, voices_file, vocab, g2p, voice, en_callable = self._get_config(lang)
kokoro = self._load_kokoro(model_file, voices_file, vocab)
print(f"Synthesizing text ({lang.upper()})...")
if g2p:
phonemes, _ = g2p(text)
samples, sr = kokoro.create(phonemes, voice=voice, speed=1.0, is_phonemes=True)
else:
samples, sr = kokoro.create(text, voice=voice, speed=0.9, lang="en-us")
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_audio:
temp_path = temp_audio.name
sf.write(temp_path, samples, sr)
try:
print("Applying Voice Clone...")
source_wav = load_audio(temp_path, sample_rate=self.sample_rate).to(self.device)
ref_wav = load_audio(reference_audio, sample_rate=self.sample_rate).to(self.device)
with torch.inference_mode():
converted_wav = chunked_voice_conversion(
kanade=self.kanade,
vocoder_model=self.vocoder,
source_wav=source_wav,
ref_wav=ref_wav,
sample_rate=self.sample_rate
)
sf.write(output_path, converted_wav.numpy(), self.sample_rate)
print(f"Success! Saved: {output_path}")
finally:
if os.path.exists(temp_path):
os.remove(temp_path)
def convert(self, source_audio, reference_audio, output_path="output.wav"):
"""Re-voicing : source audio → voix de référence."""
print("Applying Voice Conversion...")
source_wav = load_audio(source_audio, sample_rate=self.sample_rate).to(self.device)
ref_wav = load_audio(reference_audio, sample_rate=self.sample_rate).to(self.device)
with torch.inference_mode():
converted_wav = chunked_voice_conversion(
kanade=self.kanade,
vocoder_model=self.vocoder,
source_wav=source_wav,
ref_wav=ref_wav,
sample_rate=self.sample_rate
)
sf.write(output_path, converted_wav.numpy(), self.sample_rate)
print(f"Success! Saved: {output_path}")