Spaces:
Running
Running
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411"""Vaakya-Open TTS DemoText-to-Speech for Hindi & English by Voxaura Labs"""
import gradio as grimport torchimport numpy as npfrom transformers import AutoModelForCausalLM, AutoTokenizerfrom snac import SNAC
# ============================================================================# Model Configuration# ============================================================================
MODEL_ID = "voxaura-labs/vaakya-open"SAMPLE_RATE = 24000
# Token IDsSTART_OF_SPEECH_TOKEN = 128257END_OF_SPEECH_TOKEN = 128258START_OF_HUMAN_TOKEN = 128259END_OF_HUMAN_TOKEN = 128260AUDIO_CODE_BASE_OFFSET = 128266
# ============================================================================# Model Loading# ============================================================================
def load_models(): """Load the TTS model and SNAC decoder."""
print("Loading Vaakya-Open model...")
# Load main model in FP16 for faster inference model = AutoModelForCausalLM.from_pretrained( MODEL_ID, torch_dtype=torch.float16, device_map="auto", trust_remote_code=True, )
# Load tokenizer tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
# Load SNAC decoder print("Loading SNAC decoder...") snac_model = SNAC.from_pretrained("hubertsiuzdak/snac_24khz")
if torch.cuda.is_available(): snac_model = snac_model.cuda()
snac_model.eval()
print("Models loaded successfully!")
return model, tokenizer, snac_model
# Global model instancesprint("Initializing models...")model, tokenizer, snac_model = load_models()
# ============================================================================# Audio Generation Functions# ============================================================================
def decode_snac_tokens(code_list: list) -> np.ndarray: """Decode SNAC tokens to audio waveform. This model uses a 7-token interleaved encoding per audio frame with offsets: Token 1: offset +0 (level 0, coarse) Token 2: offset +4096 (level 1, medium) Token 3: offset +8192 (level 2, fine) Token 4: offset +12288 (level 2, fine) Token 5: offset +16384 (level 1, medium) Token 6: offset +20480 (level 2, fine) Token 7: offset +24576 (level 2, fine) Args: code_list: List of audio codes (already offset-adjusted) Returns: numpy array: Decoded audio waveform """ if not code_list or len(code_list) % 7 != 0: raise ValueError("Code list must be non-empty and divisible by 7")
# Move SNAC to CPU for decoding (important for stability) snac_model.to("cpu")
# Redistribute codes into SNAC's 3-level hierarchy layer_1 = [] # Coarse: 1 token per frame layer_2 = [] # Medium: 2 tokens per frame layer_3 = [] # Fine: 4 tokens per frame
for i in range(len(code_list) // 7): # Extract and adjust each token based on its offset layer_1.append(code_list[7*i]) layer_2.append(code_list[7*i + 1] - 4096) layer_3.append(code_list[7*i + 2] - (2*4096)) layer_3.append(code_list[7*i + 3] - (3*4096)) layer_2.append(code_list[7*i + 4] - (4*4096)) layer_3.append(code_list[7*i + 5] - (5*4096)) layer_3.append(code_list[7*i + 6] - (6*4096))
# Create hierarchical code tensors for SNAC (on same device as SNAC model) snac_device = next(snac_model.parameters()).device codes = [ torch.tensor(layer_1, device=snac_device).unsqueeze(0), torch.tensor(layer_2, device=snac_device).unsqueeze(0), torch.tensor(layer_3, device=snac_device).unsqueeze(0) ]
# Decode to audio waveform with torch.no_grad(): audio_hat = snac_model.decode(codes)
# Convert to 16-bit PCM format for Gradio (prevents conversion warning) audio_float = audio_hat.squeeze().clamp(-1, 1).cpu().numpy() audio_int16 = (audio_float * 32767).astype(np.int16)
return audio_int16
def generate_speech( text: str, max_length: int = 768, temperature: float = 0.4, top_p: float = 0.95, repetition_penalty: float = 1.2,) -> tuple: """Generate speech from text with performance metrics.""" import time
if not text or not text.strip(): raise gr.Error("Please enter some text to synthesize.")
text = text.strip()
# Start timing start_time = time.time()
# Move SNAC to CPU for decoding (important for stability) snac_model.to("cpu")
# Tokenize text (automatically adds BOS token) input_ids = tokenizer(text, return_tensors="pt").input_ids
start_token = torch.tensor([[START_OF_HUMAN_TOKEN]], dtype=torch.int64) end_tokens = torch.tensor([[128009, END_OF_HUMAN_TOKEN]], dtype=torch.int64)
input_sequence = torch.cat([start_token, input_ids, end_tokens], dim=1) input_sequence = input_sequence.to(model.device)
# Generate audio tokens with torch.no_grad(): generated_ids = model.generate( input_ids=input_sequence, max_new_tokens=max_length, do_sample=True, temperature=temperature, top_p=top_p, repetition_penalty=repetition_penalty, num_return_sequences=1, eos_token_id=END_OF_SPEECH_TOKEN, use_cache=True, pad_token_id=tokenizer.pad_token_id, )
# Extract generated tokens gen_tokens = generated_ids[0]
# Find the last occurrence of START_OF_SPEECH token sos_indices = (gen_tokens == START_OF_SPEECH_TOKEN).nonzero(as_tuple=True)[0]
if len(sos_indices) > 0: # Start from after the last START_OF_SPEECH token start_idx = sos_indices[-1].item() + 1 cropped_tokens = gen_tokens[start_idx:] else: cropped_tokens = gen_tokens
# Remove END_OF_SPEECH tokens audio_tokens = cropped_tokens[cropped_tokens != END_OF_SPEECH_TOKEN]
# Truncate to make divisible by 7 num_tokens = len(audio_tokens) num_frames = num_tokens // 7 audio_tokens = audio_tokens[:num_frames * 7]
if len(audio_tokens) == 0: raise gr.Error("No audio tokens generated. Please try again with different text.")
# Convert to list and subtract offset code_list = [t.item() - AUDIO_CODE_BASE_OFFSET for t in audio_tokens]
# Decode to audio try: audio = decode_snac_tokens(code_list) except Exception as e: raise gr.Error(f"Failed to decode audio: {str(e)}")
if audio is None or len(audio) == 0: raise gr.Error("Failed to generate audio. Please try again.")
# Calculate RTF (Real-Time Factor) generation_time = time.time() - start_time audio_duration = len(audio) / SAMPLE_RATE rtf = generation_time / audio_duration if audio_duration > 0 else 0 speed_text = f"{1/rtf:.1f}x faster" if rtf < 1 else f"{rtf:.1f}x slower"
# Format RTF info as 2x2 table rtf_info = f"""| **Generation Time** | {generation_time:.2f}s | **Audio Duration** | {audio_duration:.2f}s ||---------------------|------------------------|--------------------|-----------------------|| **Real-Time Factor** | {rtf:.3f}x | **Speed** | {speed_text} than real-time |"""
return (SAMPLE_RATE, audio), rtf_info
# ============================================================================# Gradio Interface# ============================================================================
EXAMPLES = [ ["Hello, I am your shopping assistant. How can I help you today"], ["आज का मौसम बहुत अच्छा है। Let's go for a walk !"], ["Welcome to Voxygen AI"], ["मुझे आपकी मदद करने में खुशी होगी"], ["The weather is beautiful today. चलो बाहर चलते हैं !"], ["Thank you for using our service. हम आपकी सेवा में हमेशा तत्पर हैं"], ["यह एक बहुत ही रोचक परियोजना है"], ["Hello ! This is a test of the text-to-speech system with mixed languages. आप कैसे हैं ?"], ["भारत एक विविधताओं से भरा देश है जहाँ अनेक भाषाएँ बोली जाती हैं। India is a land of diversity where many languages are spoken."],]
# CSS for stylingCSS = """.gradio-container { max-width: 1100px !important; margin: auto !important; font-size: 16px !important;}.title-text { text-align: center; margin-bottom: 0.5em; font-size: 2.5em;}.title-text::first-letter { font-size: 1.2em !important;}.subtitle-text { text-align: center; color: #666; margin-bottom: 1.5em; font-size: 1.15em;}/* Text input styling */.gr-textbox textarea { font-size: 15px !important; line-height: 1.6 !important;}/* Button styling */.gr-button { font-size: 16px !important; padding: 12px 24px !important; font-weight: 500 !important;}/* Make emoji in buttons bigger */.gr-button::first-letter { font-size: 1.3em !important;}/* Labels */label { font-size: 15px !important; font-weight: 500 !important; margin-bottom: 8px !important;}/* Make emoji in labels bigger */label::first-letter { font-size: 1.3em !important;}/* Audio player */.gr-audio { margin-top: 8px !important;}/* Accordion */.gr-accordion { margin-top: 20px !important;}/* Markdown performance display */.gr-markdown { font-size: 14px !important; line-height: 1.8 !important;}/* Examples section */.gr-examples { margin-top: 20px !important;}footer { text-align: center; margin-top: 2em; color: #888; font-size: 14px;}"""
with gr.Blocks(css=CSS, title="Vaakya-Open TTS") as demo: gr.HTML(""" <div style="text-align: center; padding: 20px 0;"> <h1 class="title-text" style="margin-bottom: 10px;">🎙️ Vaakya-Open</h1> <p class="subtitle-text" style="margin-bottom: 0;"> High-quality Text-to-Speech for Hindi & English<br> by <a href="https://www.voxygen.ai" target="_blank" style="color: #4A90E2; text-decoration: none; font-weight: 600;">Voxygen AI</a> </p> </div> """)
with gr.Row(): with gr.Column(scale=1): text_input = gr.Textbox( label="📝 Enter Text", value="The weather is beautiful today. चलो बाहर चलते हैं !", placeholder="Type your text here in English, Hindi, or mix both...", lines=5, max_lines=12, ) generate_btn = gr.Button("🔊 Generate Speech", variant="primary", size="lg")
with gr.Column(scale=1): audio_output = gr.Audio( label="🎧 Generated Speech", type="numpy", interactive=False, autoplay=True, ) rtf_display = gr.Markdown( value="*Performance metrics will appear here after generation*", label="⚡ Performance" )
with gr.Accordion("⚙️ Advanced Settings", open=False): gr.Markdown("*Fine-tune generation parameters for optimal results*") with gr.Row(): max_length = gr.Dropdown( choices=[256, 384, 512, 768, 1024, 1280, 1536, 1792, 2048], value=768, label="🎯 Max Length", info="Maximum number of tokens to generate (higher = longer audio)" ) temperature = gr.Slider( minimum=0.1, maximum=1.0, value=0.4, step=0.05, label="🌡️ Temperature", info="Higher = more expressive, Lower = more consistent" ) with gr.Row(): top_p = gr.Slider( minimum=0.5, maximum=1.0, value=0.95, step=0.05, label="🎲 Top-P", info="Nucleus sampling parameter" ) repetition_penalty = gr.Slider( minimum=1.0, maximum=1.8, value=1.4, step=0.05, label="🔁 Repetition Penalty", info="Penalize repeated tokens" )
gr.Examples( examples=EXAMPLES, inputs=[text_input], label="📝 Example Texts (click to try)", )
generate_btn.click( fn=generate_speech, inputs=[text_input, max_length, temperature, top_p, repetition_penalty], outputs=[audio_output, rtf_display], )
text_input.submit( fn=generate_speech, inputs=[text_input, max_length, temperature, top_p, repetition_penalty], outputs=[audio_output, rtf_display], )
gr.HTML(""" <footer> <p> Model: <a href="https://huggingface.co/voxaura-labs/vaakya-open" target="_blank">voxaura-labs/vaakya-open</a> · Built on <a href="https://github.com/canopyai/Orpheus-TTS" target="_blank">Orpheus TTS</a> architecture · Made in India 🇮🇳 </p> </footer> """)
# ============================================================================# Launch# ============================================================================
if __name__ == "__main__": demo.launch()app.pyAdded+411