Update app.py
Browse files
app.py
CHANGED
|
@@ -1,119 +1,209 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import os
|
| 3 |
-
import
|
| 4 |
import torch
|
| 5 |
import gradio as gr
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
#
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
#
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
try:
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
with gr.Row():
|
| 96 |
-
with gr.Column():
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
)
|
| 110 |
-
|
| 111 |
-
gr.Markdown("""
|
| 112 |
-
---
|
| 113 |
-
**Tips:**
|
| 114 |
-
- For best results, use clean reference audio (3-10 seconds of clear speech)
|
| 115 |
-
- Source and reference should ideally be similar in speaking pace
|
| 116 |
-
""")
|
| 117 |
|
| 118 |
if __name__ == "__main__":
|
| 119 |
-
demo.launch()
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Kanade Tokenizer β Text-to-Audio with Voice Cloning
|
| 3 |
+
=====================================================
|
| 4 |
+
Original project: Audio-to-Audio (voice conversion)
|
| 5 |
+
This version: Text + Reference Audio β Cloned Voice Audio
|
| 6 |
+
|
| 7 |
+
Pipeline:
|
| 8 |
+
1. Text β [TTS engine] β intermediate WAV (content only)
|
| 9 |
+
2. Reference Audio β Kanade encode β global_embedding (speaker identity)
|
| 10 |
+
3. intermediate WAV β Kanade encode β content_token_indices
|
| 11 |
+
4. Kanade decode(content_tokens, reference_speaker_embedding) β output mel
|
| 12 |
+
5. Vocoder β final WAV (your text, in the reference speaker's voice)
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
import os
|
| 16 |
+
import tempfile
|
| 17 |
import torch
|
| 18 |
import gradio as gr
|
| 19 |
+
import numpy as np
|
| 20 |
+
import soundfile as sf
|
| 21 |
|
| 22 |
+
# ββ Kanade ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 23 |
+
from kanade_tokenizer import KanadeModel, load_audio, load_vocoder, vocode
|
| 24 |
+
|
| 25 |
+
# ββ TTS back-end (edge-tts is zero-install, async) ββββββββββββββββββββββββββ
|
| 26 |
+
import asyncio
|
| 27 |
+
import edge_tts
|
| 28 |
+
|
| 29 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 30 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 31 |
+
MODEL_ID = "frothywater/kanade-25hz-clean" # change to kanade-12.5hz if preferred
|
| 32 |
+
|
| 33 |
+
print(f"[init] Loading Kanade model: {MODEL_ID} ({DEVICE})")
|
| 34 |
+
kanade = KanadeModel.from_pretrained(MODEL_ID).eval().to(DEVICE)
|
| 35 |
+
vocoder = load_vocoder(kanade.config.vocoder_name).to(DEVICE)
|
| 36 |
+
SR = kanade.config.sample_rate # typically 16000
|
| 37 |
+
print("[init] Models ready.")
|
| 38 |
+
|
| 39 |
+
# ββ TTS voices available via edge-tts βββββββββββββββββββββββββββββββββββββββ
|
| 40 |
+
TTS_VOICES = {
|
| 41 |
+
"English (US) Female β Aria": "en-US-AriaNeural",
|
| 42 |
+
"English (US) Male β Guy": "en-US-GuyNeural",
|
| 43 |
+
"English (UK) Female β Sonia": "en-GB-SoniaNeural",
|
| 44 |
+
"English (UK) Male β Ryan": "en-GB-RyanNeural",
|
| 45 |
+
"English (AU) Female β Natasha": "en-AU-NatashaNeural",
|
| 46 |
+
"English (IN) Female β Neerja": "en-IN-NeerjaNeural",
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
# ββ helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 50 |
+
|
| 51 |
+
def tts_to_wav(text: str, voice: str) -> str:
|
| 52 |
+
"""Run edge-tts and return path to a temp WAV file."""
|
| 53 |
+
tmp = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)
|
| 54 |
+
tmp.close()
|
| 55 |
+
|
| 56 |
+
async def _run():
|
| 57 |
+
communicate = edge_tts.Communicate(text, voice)
|
| 58 |
+
# edge-tts outputs MP3; write to mp3 then convert
|
| 59 |
+
mp3_path = tmp.name.replace(".wav", ".mp3")
|
| 60 |
+
await communicate.save(mp3_path)
|
| 61 |
+
return mp3_path
|
| 62 |
+
|
| 63 |
+
mp3_path = asyncio.run(_run())
|
| 64 |
+
|
| 65 |
+
# Convert MP3 β WAV via soundfile / pydub fallback
|
|
|
|
| 66 |
try:
|
| 67 |
+
import pydub
|
| 68 |
+
audio = pydub.AudioSegment.from_mp3(mp3_path)
|
| 69 |
+
audio = audio.set_frame_rate(SR).set_channels(1)
|
| 70 |
+
audio.export(tmp.name, format="wav")
|
| 71 |
+
except Exception:
|
| 72 |
+
# fallback: scipy / librosa
|
| 73 |
+
import librosa
|
| 74 |
+
y, _ = librosa.load(mp3_path, sr=SR, mono=True)
|
| 75 |
+
sf.write(tmp.name, y, SR)
|
| 76 |
+
|
| 77 |
+
os.unlink(mp3_path)
|
| 78 |
+
return tmp.name
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def load_wav_tensor(path: str) -> torch.Tensor:
|
| 82 |
+
"""Load a WAV file β 1-D float32 tensor at Kanade's sample rate."""
|
| 83 |
+
return load_audio(path, sample_rate=SR).to(DEVICE)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# ββ main inference ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 87 |
+
|
| 88 |
+
def synthesize(
|
| 89 |
+
text: str,
|
| 90 |
+
tts_voice_label: str,
|
| 91 |
+
reference_audio_path: str,
|
| 92 |
+
speed: float,
|
| 93 |
+
) -> tuple[int, np.ndarray]:
|
| 94 |
+
"""
|
| 95 |
+
Returns (sample_rate, waveform_numpy) for Gradio Audio output.
|
| 96 |
+
"""
|
| 97 |
+
if not text.strip():
|
| 98 |
+
raise gr.Error("Please enter some text to synthesize.")
|
| 99 |
+
if reference_audio_path is None:
|
| 100 |
+
raise gr.Error("Please upload a reference audio clip (the voice to clone).")
|
| 101 |
+
|
| 102 |
+
voice_id = TTS_VOICES[tts_voice_label]
|
| 103 |
+
|
| 104 |
+
# ββ Step 1: Text β intermediate speech WAV βββββββββββββββββββββββββββββ
|
| 105 |
+
gr.Info("Step 1/4 β Synthesising text with TTSβ¦")
|
| 106 |
+
tts_wav_path = tts_to_wav(text, voice_id)
|
| 107 |
+
|
| 108 |
+
# ββ Step 2: Encode TTS audio β content tokens ββββββββββββββββββββββββββ
|
| 109 |
+
gr.Info("Step 2/4 β Extracting content tokens from TTS audioβ¦")
|
| 110 |
+
tts_waveform = load_wav_tensor(tts_wav_path)
|
| 111 |
+
os.unlink(tts_wav_path)
|
| 112 |
+
|
| 113 |
+
with torch.inference_mode():
|
| 114 |
+
tts_features = kanade.encode(tts_waveform)
|
| 115 |
+
|
| 116 |
+
# ββ Step 3: Encode reference audio β speaker embedding βββββββββββββββββ
|
| 117 |
+
gr.Info("Step 3/4 β Extracting speaker embedding from reference audioβ¦")
|
| 118 |
+
ref_waveform = load_wav_tensor(reference_audio_path)
|
| 119 |
+
|
| 120 |
+
with torch.inference_mode():
|
| 121 |
+
ref_features = kanade.encode(ref_waveform)
|
| 122 |
+
|
| 123 |
+
# ββ Step 4: Decode with cloned speaker embedding ββββββββββββββββββββββββ
|
| 124 |
+
gr.Info("Step 4/4 β Decoding with cloned voiceβ¦")
|
| 125 |
+
with torch.inference_mode():
|
| 126 |
+
mel = kanade.decode(
|
| 127 |
+
content_token_indices=tts_features.content_token_indices, # WHAT to say
|
| 128 |
+
global_embedding=ref_features.global_embedding, # WHO says it
|
| 129 |
+
)
|
| 130 |
+
waveform = vocode(vocoder, mel.unsqueeze(0)) # (1, samples)
|
| 131 |
+
|
| 132 |
+
audio_np = waveform.squeeze().cpu().float().numpy()
|
| 133 |
+
|
| 134 |
+
# Optional speed adjustment via resampling
|
| 135 |
+
if abs(speed - 1.0) > 0.05:
|
| 136 |
+
import librosa
|
| 137 |
+
audio_np = librosa.effects.time_stretch(audio_np, rate=speed)
|
| 138 |
+
|
| 139 |
+
return int(SR), audio_np
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# ββ Gradio UI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 143 |
+
|
| 144 |
+
CSS = """
|
| 145 |
+
#title { text-align: center; }
|
| 146 |
+
#banner { text-align: center; color: #6366f1; font-size: 0.9em; }
|
| 147 |
+
footer { display: none !important; }
|
| 148 |
+
"""
|
| 149 |
+
|
| 150 |
+
with gr.Blocks(title="Kanade TTS Voice Cloner", css=CSS, theme=gr.themes.Soft()) as demo:
|
| 151 |
+
gr.Markdown("# ποΈ Kanade β Text-to-Audio with Voice Cloning", elem_id="title")
|
| 152 |
+
gr.Markdown(
|
| 153 |
+
"Type any text, upload a **reference audio** (the voice you want to clone), "
|
| 154 |
+
"and Kanade will speak your text **in that person's voice**.",
|
| 155 |
+
elem_id="banner",
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
with gr.Row():
|
| 159 |
+
with gr.Column(scale=3):
|
| 160 |
+
text_input = gr.Textbox(
|
| 161 |
+
label="π Text to synthesise",
|
| 162 |
+
placeholder="Enter any text hereβ¦",
|
| 163 |
+
lines=5,
|
| 164 |
+
)
|
| 165 |
+
tts_voice = gr.Dropdown(
|
| 166 |
+
label="π Base TTS voice (used for content extraction only)",
|
| 167 |
+
choices=list(TTS_VOICES.keys()),
|
| 168 |
+
value=list(TTS_VOICES.keys())[0],
|
| 169 |
+
info="This voice provides pronunciation β the output will sound like the reference speaker.",
|
| 170 |
+
)
|
| 171 |
+
speed_slider = gr.Slider(
|
| 172 |
+
label="β© Speed",
|
| 173 |
+
minimum=0.7, maximum=1.5, value=1.0, step=0.05,
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
with gr.Column(scale=2):
|
| 177 |
+
reference_audio = gr.Audio(
|
| 178 |
+
label="π€ Reference audio (voice to clone)",
|
| 179 |
+
type="filepath",
|
| 180 |
+
sources=["upload", "microphone"],
|
| 181 |
+
)
|
| 182 |
+
gr.Markdown(
|
| 183 |
+
"π‘ **Tips for best results:**\n"
|
| 184 |
+
"- Use 5β30 seconds of clean speech\n"
|
| 185 |
+
"- Single speaker, minimal background noise\n"
|
| 186 |
+
"- WAV or high-quality MP3\n"
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
run_btn = gr.Button("π Generate Cloned Speech", variant="primary", size="lg")
|
| 190 |
+
|
| 191 |
+
output_audio = gr.Audio(label="π Output β Your text in the reference speaker's voice", type="numpy")
|
| 192 |
+
|
| 193 |
+
run_btn.click(
|
| 194 |
+
fn=synthesize,
|
| 195 |
+
inputs=[text_input, tts_voice, reference_audio, speed_slider],
|
| 196 |
+
outputs=output_audio,
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
gr.Markdown("---")
|
| 200 |
+
gr.Markdown(
|
| 201 |
+
"**How it works:** Kanade disentangles speech into *content tokens* (what is said) "
|
| 202 |
+
"and a *global speaker embedding* (who says it). "
|
| 203 |
+
"We extract content from a TTS-generated intermediate and speaker identity from your "
|
| 204 |
+
"reference audio, then recombine them. "
|
| 205 |
+
"Model: [`frothywater/kanade-25hz-clean`](https://huggingface.co/frothywater/kanade-25hz-clean)"
|
| 206 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
|
| 208 |
if __name__ == "__main__":
|
| 209 |
+
demo.launch()
|