TTS / app.py
subikshababu's picture
feat: protect voice cloning with password
af6c84e
Raw History Blame Contribute Delete
22.8 kB
import asyncio
import os
import re
import secrets
import tempfile
import time
import uuid
import edge_tts
import gradio as gr
import spaces
from gtts import gTTS
from gtts.lang import tts_langs
from pydub import AudioSegment
from audio_utils import cleanup_temp_audio_files
from voice_engines import (
ENGINE_DISPLAY_NAMES,
DEFAULT_ENGINE,
convert_voice,
VoiceEngineError,
)
LOGGER = __import__("logging").getLogger(__name__)
GTTS_CHUNK_MAX_CHARS = 1200
GTTS_CHUNK_PREFIX = "indic_tts_chunk_"
GTTS_FINAL_PREFIX = "indic_tts_final_"
CLONED_OUTPUT_PREFIX = "voice_conversion_"
MERGE_PAUSE_MS = 300
MAX_CHUNKS = 50
APP_OUTPUT_PREFIXES = (GTTS_CHUNK_PREFIX, GTTS_FINAL_PREFIX, CLONED_OUTPUT_PREFIX)
GTTS_PROVIDER = "Google gTTS"
EDGE_TTS_PROVIDER = "Microsoft Edge TTS"
# UI label -> engine key for the five audio-only converters.
CLONE_METHOD_KEYS = {label: key for key, label in ENGINE_DISPLAY_NAMES.items()}
EDGE_TAMIL_VOICES = {
"Pallavi — Female (India)": "ta-IN-PallaviNeural",
"Valluvar — Male (India)": "ta-IN-ValluvarNeural",
"Saranya — Female (Sri Lanka)": "ta-LK-SaranyaNeural",
"Kumar — Male (Sri Lanka)": "ta-LK-KumarNeural",
"Kani — Female (Malaysia)": "ta-MY-KaniNeural",
"Surya — Male (Malaysia)": "ta-MY-SuryaNeural",
"Venba — Female (Singapore)": "ta-SG-VenbaNeural",
"Anbu — Male (Singapore)": "ta-SG-AnbuNeural",
}
PREFERRED_INDIC_LANGUAGES = {
"Assamese": "as",
"Bengali": "bn",
"Gujarati": "gu",
"Hindi": "hi",
"Kannada": "kn",
"Malayalam": "ml",
"Marathi": "mr",
"Nepali": "ne",
"Odia": "or",
"Punjabi": "pa",
"Sanskrit": "sa",
"Sinhala": "si",
"Tamil": "ta",
"Telugu": "te",
"Urdu": "ur",
}
SAMPLE_TEXTS = {
"ta": "வணக்கம்! இது ஒரு குறுகிய தமிழ் உரை உதாரணம்.",
"hi": "नमस्ते! यह हिंदी का एक छोटा उदाहरण है।",
"te": "నమస్కారం! ఇది తెలుగు లో చిన్న ఉదాహరణ.",
"kn": "ನಮಸ್ಕಾರ! ಇದು ಕನ್ನಡದ ಒಂದು ಚಿಕ್ಕ ಉದಾಹರಣೆ.",
"ml": "നമസ്കാരം! ഇത് മലയാളത്തിലെ ചെറിയ ഉദാഹരണമാണ്.",
"bn": "নমস্কার! এটি বাংলা ভাষার একটি ছোট উদাহরণ।",
"mr": "नमस्कार! हे मराठीतील एक छोटे उदाहरण आहे.",
"gu": "નમસ્તે! આ ગુજરાતીનું એક નાનું ઉદાહરણ છે.",
"ur": "السلام علیکم! یہ اردو کا ایک مختصر نمونہ ہے۔",
"pa": "ਸਤ ਸ੍ਰੀ ਅਕਾਲ! ਇਹ ਪੰਜਾਬੀ ਦਾ ਇੱਕ ਛੋਟਾ ਉਦਾਹਰਨ ਹੈ।",
}
VOICE_VARIANTS = {
"ta": {"Default": None, "India": "co.in"},
"hi": {"Default": None, "India": "co.in"},
"bn": {"Default": None, "India": "co.in"},
"gu": {"Default": None, "India": "co.in"},
"kn": {"Default": None, "India": "co.in"},
"ml": {"Default": None, "India": "co.in"},
"mr": {"Default": None, "India": "co.in"},
"te": {"Default": None, "India": "co.in"},
"ur": {"Default": None, "India": "co.in", "Pakistan-ish/Regional Test": "com.pk"},
"pa": {"Default": None, "India": "co.in"},
"ne": {"Default": None, "India": "co.in"},
"si": {"Default": None},
"or": {"Default": None},
"as": {"Default": None},
"sa": {"Default": None},
}
NEUTRAL_SAMPLE_TEXT = "Hello! This is a short text-to-speech sample."
SUPPORTED_GTTS_LANGS = tts_langs()
INDIC_LANGUAGE_OPTIONS = {
f"{name} ({code})": code
for name, code in PREFERRED_INDIC_LANGUAGES.items()
if code in SUPPORTED_GTTS_LANGS
}
if not INDIC_LANGUAGE_OPTIONS:
raise RuntimeError("No preferred Indic languages are currently supported by gTTS in this environment.")
DEFAULT_LANGUAGE_LABEL = "Tamil (ta)" if "Tamil (ta)" in INDIC_LANGUAGE_OPTIONS else next(iter(INDIC_LANGUAGE_OPTIONS))
DEFAULT_LANGUAGE_CODE = INDIC_LANGUAGE_OPTIONS[DEFAULT_LANGUAGE_LABEL]
DEFAULT_SAMPLE_TEXT = SAMPLE_TEXTS.get(DEFAULT_LANGUAGE_CODE, NEUTRAL_SAMPLE_TEXT)
def cleanup_old_temp_files():
cleanup_temp_audio_files(APP_OUTPUT_PREFIXES, {".mp3", ".wav"})
def get_language_code(language_label):
language_code = INDIC_LANGUAGE_OPTIONS.get(language_label)
if not language_code:
raise gr.Error("Please select a valid supported language.")
return language_code
def get_selected_tts_provider(gtts_enabled, edge_tts_enabled):
if bool(gtts_enabled) == bool(edge_tts_enabled):
raise gr.Error("Select exactly one TTS provider: Google gTTS or Microsoft Edge TTS.")
return GTTS_PROVIDER if gtts_enabled else EDGE_TTS_PROVIDER
def get_voice_variant_options(language_code, provider=GTTS_PROVIDER):
if provider == EDGE_TTS_PROVIDER:
return list(EDGE_TAMIL_VOICES) if language_code == "ta" else []
variants = VOICE_VARIANTS.get(language_code, {"Default": None})
if "Default" not in variants:
variants = {"Default": None, **variants}
return list(variants.keys())
def get_voice_update(language_code, provider):
options = get_voice_variant_options(language_code, provider)
return gr.update(
choices=options,
value=options[0] if options else None,
interactive=bool(options),
)
def get_variant_tld(language_code, voice_variant):
variants = VOICE_VARIANTS.get(language_code, {"Default": None})
return variants.get(voice_variant, variants.get("Default"))
def _hard_split_segment(segment, max_chars):
words = segment.split()
if not words:
return []
chunks = []
current = ""
for word in words:
if len(word) > max_chars:
if current:
chunks.append(current)
current = ""
for start in range(0, len(word), max_chars):
chunks.append(word[start : start + max_chars])
continue
if not current:
current = word
continue
candidate = f"{current} {word}"
if len(candidate) <= max_chars:
current = candidate
else:
chunks.append(current)
current = word
if current:
chunks.append(current)
return chunks
def split_text_into_chunks(text, max_chars=GTTS_CHUNK_MAX_CHARS):
cleaned = re.sub(r"[ \t]+", " ", (text or "").strip())
if not cleaned:
return []
paragraphs = [p.strip() for p in re.split(r"\n\s*\n+", cleaned) if p.strip()]
chunks = []
for paragraph in paragraphs:
sentences = [s.strip() for s in re.split(r"(?<=[.!?।॥])\s+", paragraph) if s.strip()]
if not sentences:
sentences = [paragraph]
current = ""
for sentence in sentences:
if len(sentence) > max_chars:
if current:
chunks.append(current)
current = ""
chunks.extend(_hard_split_segment(sentence, max_chars))
continue
candidate = sentence if not current else f"{current} {sentence}"
if len(candidate) <= max_chars:
current = candidate
else:
chunks.append(current)
current = sentence
if current:
chunks.append(current)
return [chunk.strip() for chunk in chunks if chunk.strip()]
def generate_chunk_audio(chunk_text, language_code, selected_tld):
chunk_file = os.path.join(tempfile.gettempdir(), f"{GTTS_CHUNK_PREFIX}{uuid.uuid4().hex}.mp3")
try:
if selected_tld:
tts = gTTS(text=chunk_text, lang=language_code, tld=selected_tld)
else:
tts = gTTS(text=chunk_text, lang=language_code)
tts.save(chunk_file)
except Exception as exc:
raise gr.Error(f"Chunk generation failed with gTTS: {exc}") from exc
if not os.path.exists(chunk_file):
raise gr.Error("A chunk audio file could not be created.")
return chunk_file
def generate_edge_tts_audio(text, language_code, voice_variant):
if language_code != "ta":
raise gr.Error(
"Microsoft Edge TTS is currently enabled for Tamil. "
"Select Tamil or switch back to Google gTTS."
)
voice_name = EDGE_TAMIL_VOICES.get(voice_variant)
if not voice_name:
raise gr.Error("Please select a valid Microsoft Edge Tamil voice.")
output_file = os.path.join(
tempfile.gettempdir(),
f"{GTTS_FINAL_PREFIX}{uuid.uuid4().hex}.mp3",
)
try:
asyncio.run(edge_tts.Communicate(text, voice_name).save(output_file))
except Exception as exc:
try:
os.remove(output_file)
except OSError:
pass
raise gr.Error(
f"Audio generation failed with Microsoft Edge TTS: {exc}"
) from exc
if not os.path.exists(output_file) or os.path.getsize(output_file) == 0:
try:
os.remove(output_file)
except OSError:
pass
raise gr.Error("Microsoft Edge TTS did not create an audio file. Please try again.")
return output_file
def merge_audio_files(chunk_files):
if not chunk_files:
raise gr.Error("No audio chunks were generated.")
for chunk_file in chunk_files:
if not os.path.exists(chunk_file):
raise gr.Error("One or more chunk audio files are missing. Please try generating again.")
final_file = os.path.join(tempfile.gettempdir(), f"{GTTS_FINAL_PREFIX}{uuid.uuid4().hex}.mp3")
try:
merged = AudioSegment.empty()
for index, chunk_file in enumerate(chunk_files):
if index > 0:
merged += AudioSegment.silent(duration=MERGE_PAUSE_MS)
merged += AudioSegment.from_file(chunk_file, format="mp3")
merged.export(final_file, format="mp3")
except Exception as exc:
raise gr.Error(
"Failed to merge chunk audio into the final MP3 file. "
"Please ensure ffmpeg/libav is available in the runtime. "
f"Details: {exc}"
) from exc
if not os.path.exists(final_file):
raise gr.Error("Final merged audio file could not be created.")
return final_file
def generate_tts(
text,
language_label,
voice_variant,
gtts_enabled=True,
edge_tts_enabled=False,
):
cleanup_old_temp_files()
normalized_text = (text or "").strip()
if not normalized_text:
raise gr.Error("Please enter some text before generating audio.")
language_code = get_language_code(language_label)
provider = get_selected_tts_provider(gtts_enabled, edge_tts_enabled)
if provider == EDGE_TTS_PROVIDER:
return generate_edge_tts_audio(normalized_text, language_code, voice_variant)
chunks = split_text_into_chunks(normalized_text)
if not chunks:
raise gr.Error("Text could not be prepared for generation. Please try again.")
if len(chunks) > MAX_CHUNKS:
raise gr.Error(
f"Input is too large for reliable generation ({len(chunks)} chunks). "
f"Please shorten the text slightly and try again."
)
if language_code not in SUPPORTED_GTTS_LANGS:
raise gr.Error(f"Language '{language_code}' is not supported by gTTS in this environment.")
selected_tld = get_variant_tld(language_code, voice_variant)
chunk_files = []
try:
for chunk in chunks:
chunk_files.append(generate_chunk_audio(chunk, language_code, selected_tld))
return merge_audio_files(chunk_files)
finally:
for chunk_file in chunk_files:
try:
if os.path.exists(chunk_file):
os.remove(chunk_file)
except OSError:
pass
def generate_tts_for_ui(
text,
language_label,
voice_variant,
gtts_enabled,
edge_tts_enabled,
):
generated_audio = generate_tts(
text,
language_label,
voice_variant,
gtts_enabled,
edge_tts_enabled,
)
return generated_audio, generated_audio, generated_audio
def on_language_change(
selected_label,
current_text,
previous_label,
gtts_enabled,
edge_tts_enabled,
):
selected_code = get_language_code(selected_label)
selected_sample = SAMPLE_TEXTS.get(selected_code, NEUTRAL_SAMPLE_TEXT)
previous_sample = ""
if previous_label in INDIC_LANGUAGE_OPTIONS:
previous_code = INDIC_LANGUAGE_OPTIONS[previous_label]
previous_sample = SAMPLE_TEXTS.get(previous_code, NEUTRAL_SAMPLE_TEXT)
normalized_text = (current_text or "").strip()
next_text = selected_sample if not normalized_text or normalized_text == previous_sample else current_text
provider = get_selected_tts_provider(gtts_enabled, edge_tts_enabled)
variant_update = get_voice_update(selected_code, provider)
return next_text, selected_label, variant_update
def _on_provider_checkbox_input(
preferred_provider,
preferred_enabled,
fallback_enabled,
language_label,
):
if preferred_enabled or not fallback_enabled:
provider = preferred_provider
else:
provider = EDGE_TTS_PROVIDER if preferred_provider == GTTS_PROVIDER else GTTS_PROVIDER
language_code = get_language_code(language_label)
return (
provider == GTTS_PROVIDER,
provider == EDGE_TTS_PROVIDER,
get_voice_update(language_code, provider),
)
def on_gtts_checkbox_input(gtts_enabled, edge_tts_enabled, language_label):
return _on_provider_checkbox_input(
GTTS_PROVIDER,
gtts_enabled,
edge_tts_enabled,
language_label,
)
def on_edge_tts_checkbox_input(gtts_enabled, edge_tts_enabled, language_label):
return _on_provider_checkbox_input(
EDGE_TTS_PROVIDER,
edge_tts_enabled,
gtts_enabled,
language_label,
)
TEXT_SOURCE = "Text to Speech"
DIRECT_SOURCE = "Upload / Record Audio"
def on_source_mode_change(mode):
# All source-mutating events share voice_workflow, including generation.
# Clear both visible inputs and the one canonical source on every switch.
return gr.update(visible=mode == TEXT_SOURCE), gr.update(visible=mode == DIRECT_SOURCE), None, None, None, None
def use_direct_source(audio, mode):
return audio if mode == DIRECT_SOURCE else None
CLONING_PASSWORD_ENV_VAR = "CLONING_PASSWORD"
def validate_cloning_password(cloning_password):
"""Authorization gate for voice cloning. Fails closed; never echoes input."""
expected = os.environ.get(CLONING_PASSWORD_ENV_VAR)
if not expected:
# Fail closed: a missing/unset secret disables cloning entirely rather
# than silently bypassing authentication.
raise gr.Error("Voice cloning is currently unavailable.")
supplied = (cloning_password or "").encode("utf-8")
if not secrets.compare_digest(supplied, expected.encode("utf-8")):
raise gr.Error("Invalid cloning password.")
def clone_voice_ui(engine_label, source_audio, reference_audio, permission_confirmed, cloning_password):
validate_cloning_password(cloning_password)
if not permission_confirmed:
raise gr.Error("Permission confirmed is required for voice cloning.")
if not source_audio:
raise gr.Error("Generate, upload or record source speech first.")
if not reference_audio:
raise gr.Error("Upload or record a reference voice first.")
key = CLONE_METHOD_KEYS.get(engine_label)
if key is None:
raise gr.Error("Unknown voice converter.")
start = time.perf_counter()
try:
result = convert_voice(source_audio, reference_audio, key)
except gr.Error:
raise
except VoiceEngineError as exc:
raise gr.Error(str(exc)) from exc
except Exception as exc:
LOGGER.exception("Converter %s failed", key)
raise gr.Error(f"{engine_label} failed ({type(exc).__name__}). Try another converter.") from exc
return result, f"{engine_label} | Conversion time: {time.perf_counter() - start:.2f}s", result
with gr.Blocks(
title="Tamil Speech Research",
delete_cache=(60 * 60, 2 * 60 * 60),
) as demo:
gr.Markdown(
"""
# 🗣️ Indic Text-to-Speech
Generate speech with Google gTTS or a larger Microsoft Edge Tamil
voice catalog, then
optionally clone its tone color from a consented reference recording.
- Select one provider checkbox. Edge TTS offers eight Tamil neural voices.
- Voice / Variant uses named voices or accent/domain variants where available.
- Available languages depend on gTTS support.
- Long text is split internally and merged automatically for reliability.
- Voice cloning accepts generated or uploaded source audio up to 30 seconds long.
- Very large text may take longer to process.
"""
)
gr.Markdown("## Source speech")
source_mode = gr.Radio([TEXT_SOURCE, DIRECT_SOURCE], value=TEXT_SOURCE, label="Source Mode")
source_audio_state = gr.State(value=None, time_to_live=2 * 60 * 60)
with gr.Group() as tts_group:
language_input = gr.Dropdown(
label="Language",
choices=list(INDIC_LANGUAGE_OPTIONS.keys()),
value=DEFAULT_LANGUAGE_LABEL,
)
with gr.Row():
gtts_enabled_input = gr.Checkbox(
label=GTTS_PROVIDER,
value=True,
)
edge_tts_enabled_input = gr.Checkbox(
label=EDGE_TTS_PROVIDER,
value=False,
)
voice_variant_input = gr.Dropdown(
label="Voice / Variant",
choices=get_voice_variant_options(DEFAULT_LANGUAGE_CODE),
value=get_voice_variant_options(DEFAULT_LANGUAGE_CODE)[0],
)
text_input = gr.Textbox(label="Text", value=DEFAULT_SAMPLE_TEXT, lines=4)
previous_language_state = gr.State(DEFAULT_LANGUAGE_LABEL)
generate_btn = gr.Button("Generate Source")
audio_output = gr.Audio(label="Generated Audio", type="filepath", interactive=False)
tts_download = gr.DownloadButton("Download TTS MP3")
language_input.change(
fn=on_language_change,
inputs=[
language_input,
text_input,
previous_language_state,
gtts_enabled_input,
edge_tts_enabled_input,
],
outputs=[text_input, previous_language_state, voice_variant_input],
concurrency_id="voice_workflow",
concurrency_limit=1,
)
gtts_enabled_input.input(
fn=on_gtts_checkbox_input,
inputs=[gtts_enabled_input, edge_tts_enabled_input, language_input],
outputs=[gtts_enabled_input, edge_tts_enabled_input, voice_variant_input],
concurrency_id="voice_workflow",
concurrency_limit=1,
)
edge_tts_enabled_input.input(
fn=on_edge_tts_checkbox_input,
inputs=[gtts_enabled_input, edge_tts_enabled_input, language_input],
outputs=[gtts_enabled_input, edge_tts_enabled_input, voice_variant_input],
concurrency_id="voice_workflow",
concurrency_limit=1,
)
generate_btn.click(
fn=generate_tts_for_ui,
inputs=[
text_input,
language_input,
voice_variant_input,
gtts_enabled_input,
edge_tts_enabled_input,
],
outputs=[audio_output, source_audio_state, tts_download],
api_name=False,
concurrency_id="voice_workflow",
concurrency_limit=1,
show_progress="full",
)
legacy_generate_api = gr.Button(visible=False)
legacy_generate_api.click(
fn=generate_tts,
inputs=[text_input, language_input, voice_variant_input],
outputs=audio_output,
api_name="generate_tts",
)
with gr.Group(visible=False) as direct_group:
direct_source_input = gr.Audio(label="Source audio / preview", sources=["upload", "microphone"], type="filepath")
source_mode.change(
on_source_mode_change, inputs=[source_mode],
outputs=[tts_group, direct_group, source_audio_state, direct_source_input, audio_output, tts_download],
concurrency_id="voice_workflow", concurrency_limit=1,
)
direct_source_input.change(
use_direct_source, inputs=[direct_source_input, source_mode], outputs=[source_audio_state],
concurrency_id="voice_workflow", concurrency_limit=1,
)
gr.Markdown("## Target / reference voice\nOnly use voices you own or have permission to convert. Disclose synthetic output.")
reference_audio_input = gr.Audio(label="Target voice / preview", sources=["upload", "microphone"], type="filepath")
cloning_permission_input = gr.Checkbox(value=False, label="I confirm I have permission to use the source and reference voice for this synthetic conversion.")
gr.Markdown("## Voice converter\nUAT comparison: no quality winner selected. Use 0.5–30 seconds of source and 0.5–20 seconds of reference audio. MeanVC2 uses ZeroGPU; ONNX engines use CPU and download on first use.")
clone_method_labels = list(CLONE_METHOD_KEYS)
engine_select = gr.Dropdown(choices=clone_method_labels, value=ENGINE_DISPLAY_NAMES[DEFAULT_ENGINE], label="Voice Converter")
cloning_password_input = gr.Textbox(
label="Cloning Password",
type="password",
)
clone_voice_btn = gr.Button("Convert Voice", variant="primary")
cloned_audio_output = gr.Audio(label="Converted audio", type="filepath", interactive=False)
generation_time_display = gr.Textbox(label="Conversion info", interactive=False)
converted_download = gr.DownloadButton("Download converted WAV")
clone_voice_btn.click(
fn=clone_voice_ui,
inputs=[engine_select, source_audio_state, reference_audio_input, cloning_permission_input, cloning_password_input],
outputs=[cloned_audio_output, generation_time_display, converted_download],
api_name="convert_voice", concurrency_id="voice_workflow", concurrency_limit=1,
show_progress="full",
)
if __name__ == "__main__":
demo.queue(default_concurrency_limit=1, max_size=5).launch(
server_name="0.0.0.0", server_port=int(os.environ.get("PORT", "7860")), max_file_size="50mb",
)