Spaces:
Runtime error
Runtime error
Update app.py
Browse files11 unmodified lines12131415151718161718192021222324252638 unmodified lines65666763686970717273747576777879808182838485868788899091929394956566676869707172739697989910012 unmodified lines11311411593949596979811611711811912012187 unmodified lines20921021119221221321421517 unmodified lines2332342352162362372382392402412222232422432442452462252472482272492502292512522312532542332552562352572582372382392402412422432592602612622632482642652662672682692702522532542552562572582592602612622632642652662672682692702712722732742752762772782712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063072813083093103113123133143153163173182912922933193203213223233244 unmodified lines32933033130433233333433521 unmodified lines3573583593323603613623638 unmodified lines37237337434737537637737837938035338138238338415 unmodified lines4004014023754034043774054064074085 unmodified lines41441541638941741839141942042142242339639742442542639942742842943013 unmodified lines4444454464194474484494502 unmodified lines45345445542845645745845946046143446246346446511 unmodified linesfrom datetime import datetimeimport osimport warningsfrom datasets import load_dataset
# Import Dia TTS modelfrom dia.model import Dia# Import Dia model correctly[2]try: from dia.model import Dia DIA_AVAILABLE = True print("β
Dia model imported successfully")except ImportError as e: print(f"β οΈ Dia import failed: {e}") DIA_AVAILABLE = False
warnings.filterwarnings("ignore")
38 unmodified lines ) print("β
Emotion recognition loaded") # Load Dia TTS Model (The REAL Dia from Nari Labs) # Load REAL Dia TTS Model[2] if DIA_AVAILABLE: try: # Load Dia model with correct parameters[2] self.dia_model = Dia.from_pretrained( "nari-labs/Dia-1.6B", compute_dtype="float16" if self.device == "cuda" else "float32", device=self.device ) print("β
Dia TTS loaded (Ultra-realistic dialogue generation)") self.use_dia = True except Exception as e: print(f"β οΈ Dia loading failed: {e}") self.use_dia = False self._load_fallback_tts() else: print("β οΈ Dia not available, using fallback TTS") self.use_dia = False self._load_fallback_tts() # Conversation storage self.conversations = {} self.call_active = False self.speaker_turn = 1 # Track speaker turns for Dia[2] def _load_fallback_tts(self): """Load fallback TTS if Dia is not available""" try: self.dia_model = Dia.from_pretrained( "nari-labs/Dia-1.6B", compute_dtype="float16" if self.device == "cuda" else "float32" )[11][13][15] print("β
Dia TTS loaded successfully from Nari Labs") self.use_dia = True except Exception as e: print(f"β οΈ Dia loading failed: {e}") # Fallback to SpeechT5 with FIXED dtypes from transformers import SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5HifiGan from datasets import load_dataset self.tts_processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts") self.tts_model = SpeechT5ForTextToSpeech.from_pretrained(12 unmodified lines dtype=torch.float32 ).unsqueeze(0).to(self.device) print("β
SpeechT5 TTS loaded as fallback") self.use_dia = False # Conversation storage self.conversations = {} self.call_active = False except Exception as e: print(f"β Fallback TTS loading failed: {e}") def transcribe_with_whisper(self, audio_path): """Transcribe using Whisper with FORCED English""" try:87 unmodified lines with torch.no_grad(): outputs = self.llm_model.generate( input_ids=inputs.input_ids, attention_mask=inputs.attention_mask, # FIX: Explicit attention mask attention_mask=inputs.attention_mask, max_new_tokens=80, temperature=0.7, do_sample=True,17 unmodified lines return f"{emotion_prompts.get(emotion, 'I understand.')} Could you tell me more about that?" def synthesize_with_dia(self, text, emotion): """Generate natural emotional speech using Dia TTS"""[11][13][15] """Generate ultra-realistic dialogue using Dia[2]""" try: if not text or len(text.strip()) == 0: return None if self.use_dia: # Use Dia TTS with proper speaker tags and emotional context # Add emotional markers based on Dia's supported non-verbal tags # Format text for Dia with proper speaker tags[2] speaker_tag = f"[S{self.speaker_turn}]" # Add emotional non-verbals based on emotion[2] if emotion == "happy": emotional_text = f"[S1] {text} (laughs)"[11][15] emotional_text = f"{speaker_tag} {text} (laughs)" elif emotion == "sad": emotional_text = f"[S1] {text} (sighs)"[11][15] emotional_text = f"{speaker_tag} {text} (sighs)" elif emotion == "excited": emotional_text = f"[S1] {text}!" emotional_text = f"{speaker_tag} {text}!" elif emotion == "angry": emotional_text = f"[S1] {text} (clears throat)"[11][15] emotional_text = f"{speaker_tag} {text} (frustrated tone)" elif emotion == "surprised": emotional_text = f"[S1] {text} (gasps)"[11][15] emotional_text = f"{speaker_tag} {text} (gasps)" else: emotional_text = f"[S1] {text}"[11][15] emotional_text = f"{speaker_tag} {text}" # Add natural breathing for longer text (Dia feature) if len(emotional_text.split()) > 15: words = emotional_text.split() mid_point = len(words) // 2 emotional_text = " ".join(words[:mid_point]) + " (inhales) " + " ".join(words[mid_point:]) # Generate using Dia model # Generate with Dia[2] output = self.dia_model.generate( emotional_text, use_torch_compile=True if self.device == "cuda" else False, verbose=False )[11][18] ) # Toggle speaker for next turn[2] self.speaker_turn = 2 if self.speaker_turn == 1 else 1 return output else: # Use SpeechT5 fallback with emotional context clean_text = text.replace("[", "").replace("]", "").strip() if len(clean_text) > 200: clean_text = clean_text[:200] + "..." # Add emotional inflection through punctuation if emotion == "happy": clean_text = clean_text.replace(".", "!") elif emotion == "excited": clean_text = clean_text + "!" elif emotion == "sad": clean_text = clean_text.replace("!", ".") inputs = self.tts_processor(text=clean_text, return_tensors="pt") inputs = {k: v.to(self.device) for k, v in inputs.items()} with torch.no_grad(): speech = self.tts_model.generate_speech( inputs["input_ids"], self.speaker_embeddings, vocoder=self.vocoder ) if isinstance(speech, torch.Tensor): speech = speech.cpu().numpy().astype(np.float32) return speech # Fallback to SpeechT5 return self._synthesize_with_fallback(text, emotion) except Exception as e: print(f"Dia TTS error: {e}") return self._synthesize_with_fallback(text, emotion) def _synthesize_with_fallback(self, text, emotion): """Fallback TTS synthesis""" try: clean_text = text.replace("[", "").replace("]", "").strip() if len(clean_text) > 200: clean_text = clean_text[:200] + "..." # Add emotional inflection through punctuation if emotion == "happy": clean_text = clean_text.replace(".", "!") elif emotion == "excited": clean_text = clean_text + "!" elif emotion == "sad": clean_text = clean_text.replace("!", ".") inputs = self.tts_processor(text=clean_text, return_tensors="pt") inputs = {k: v.to(self.device) for k, v in inputs.items()} with torch.no_grad(): speech = self.tts_model.generate_speech( inputs["input_ids"], self.speaker_embeddings, vocoder=self.vocoder ) if isinstance(speech, torch.Tensor): speech = speech.cpu().numpy().astype(np.float32) return speech except Exception as e: print(f"TTS error: {e}") print(f"Fallback TTS error: {e}") return None def start_call(self): """Start a new call session""" self.call_active = True self.speaker_turn = 1 # Reset speaker turn[2] greeting = "Hello! I'm Maya, your AI conversation partner. I'm here to chat with you naturally and understand your emotions. How are you feeling today?" greeting_audio = self.synthesize_with_dia(greeting, "happy") # Dia outputs at 44100 Hz sample rate sample_rate = 44100 if self.use_dia else 22050 return greeting, (sample_rate, greeting_audio) if greeting_audio is not None else None, "π Call started! Maya is greeting you..." # Dia outputs at 24kHz, fallback at 22050Hz[2] sample_rate = 24000 if self.use_dia else 22050 return greeting, (sample_rate, greeting_audio) if greeting_audio is not None else None, "π Call started! Maya is greeting you with ultra-realistic speech..." def end_call(self, user_id="default"): """End call and clear conversation"""4 unmodified lines farewell = "Thank you for chatting with me! It was wonderful talking with you. Have a great day!" farewell_audio = self.synthesize_with_dia(farewell, "happy") sample_rate = 44100 if self.use_dia else 22050 sample_rate = 24000 if self.use_dia else 22050 return farewell, (sample_rate, farewell_audio) if farewell_audio is not None else None, "π Call ended. Conversation cleared!" def process_conversation(self, audio_input, user_id="default"):21 unmodified lines transcription, emotion, self.conversations[user_id] ) # Step 4: Dia TTS with natural emotional speech # Step 4: Ultra-realistic TTS with Dia[2] response_audio = self.synthesize_with_dia(response_text, emotion) # Step 5: Update conversation history8 unmodified lines self.conversations[user_id].append(conversation_entry) # Keep last 1000 exchanges as specified # Keep last 1000 exchanges as requested[5] if len(self.conversations[user_id]) > 1000: self.conversations[user_id] = self.conversations[user_id][-1000:] history = self.format_conversation_history(user_id) sample_rate = 44100 if self.use_dia else 22050 sample_rate = 24000 if self.use_dia else 22050 return transcription, (sample_rate, response_audio) if response_audio is not None else None, history except Exception as e:15 unmodified lines return "\n".join(history)
# Initialize Maya AIprint("π Starting Maya AI with Dia TTS...")print("π Starting Maya AI with REAL Dia TTS...")maya = MayaAI()print("β
Maya AI ready with natural emotional speech!")print("β
Maya AI ready with ultra-realistic dialogue generation!")
# Gradio Interface Functionsdef start_call_handler():5 unmodified linesdef process_audio_handler(audio): return maya.process_conversation(audio)
# Create Gradio Interface# Create Gradio Interface[7]with gr.Blocks( title="Maya AI - Dia TTS Sesame Killer", title="Maya AI - Dia-Powered Sesame Killer", theme=gr.themes.Soft()) as demo: gr.Markdown(""" # π€ Maya AI - Dia TTS Sesame Killer *Powered by Nari Labs Dia TTS: Ultra-realistic dialogue with natural breathing, laughter, and emotional speech* # π€ Maya AI - Dia-Powered Sesame Killer *Ultra-realistic dialogue generation with Dia TTS - Natural breathing, laughter, and human-like responses* **Features:** β
Dia Natural TTS β
English-only ASR β
Emotion Recognition β
FREE Models β
Human-like Speech with Non-verbals **Features:** β
Real Dia TTS β
English-only ASR β
Emotion Recognition β
FREE LLM β
Ultra-realistic Speech """) with gr.Row():13 unmodified lines process_btn = gr.Button("π― Process Audio", variant="primary") with gr.Column(scale=2): gr.Markdown("### π¬ Natural Dia Conversation") gr.Markdown("### π¬ Ultra-Realistic Conversation") transcription_output = gr.Textbox( label="π What you said (English)",2 unmodified lines ) audio_output = gr.Audio( label="π Maya's Dia Response (Natural with Breathing & Emotions)", label="π Maya's Ultra-Realistic Response (Dia TTS)", interactive=False, autoplay=True ) conversation_display = gr.Textbox( label="π Live Conversation (FREE & Natural Dia TTS)", label="π Live Conversation (FREE & Ultra-Realistic)", lines=15, interactive=False, show_copy_button=Trueapp.py+110-82