Spaces:
Runtime error
Runtime error
Update app.py
Browse files3 unmodified lines45678910113 unmodified lines15161718192037 unmodified lines585960616263646566676869707172737475767710 unmodified lines8889909192939495115 unmodified lines21121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825930 unmodified lines2902912922932942952962972983 unmodified lines30230330430530630730830931021 unmodified lines3323333343353363373383397 unmodified lines34734834935035135235335435535635735835915 unmodified lines3753763773783793803819 unmodified lines39139239339439539639739839940040140240340440513 unmodified lines4194204214224234244252 unmodified lines4284294304314324334344354364374384394403 unmodified linesimport librosafrom transformers import (pipeline, AutoTokenizer, AutoModelForCausalLM,WhisperProcessor, WhisperForConditionalGeneration,SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5HifiGan)import soundfile as sfimport json3 unmodified linesimport warningsfrom datasets import load_datasetwarnings.filterwarnings("ignore")class MayaAI:37 unmodified lines)print("β Emotion recognition loaded")# Load REAL Natural TTS (Better than Dia)try:# Use Bark for natural, emotional speechfrom transformers import BarkModel, BarkProcessorself.bark_processor = BarkProcessor.from_pretrained("suno/bark")self.bark_model = BarkModel.from_pretrained("suno/bark",torch_dtype=torch.float16 if self.device == "cuda" else torch.float32).to(self.device)print("β Bark TTS loaded (Natural emotional speech)")self.use_bark = Trueexcept Exception as e:print(f"β οΈ Bark loading failed: {e}")# Fallback to SpeechT5 with FIXED dtypesself.tts_processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")self.tts_model = SpeechT5ForTextToSpeech.from_pretrained("microsoft/speecht5_tts",10 unmodified linesembeddings_dataset[7306]["xvector"],dtype=torch.float32).unsqueeze(0).to(self.device)print("β SpeechT5 TTS loaded with natural female voice")self.use_bark = False# Conversation storageself.conversations = {}115 unmodified linesexcept Exception as e:return f"{emotion_prompts.get(emotion, 'I understand.')} Could you tell me more about that?"def synthesize_natural_speech(self, text, emotion):"""Generate natural emotional speech (Better than Dia)"""try:if not text or len(text.strip()) == 0:return Noneif self.use_bark:# Use Bark for natural emotional speech with breathingvoice_preset = "v2/en_speaker_6" # Female voice# Add emotional context to textif emotion == "happy":emotional_text = f"βͺ {text} βͺ" # Musical notes for happinesselif emotion == "sad":emotional_text = f"[sighs] {text}"elif emotion == "excited":emotional_text = f"{text}!"elif emotion == "angry":emotional_text = f"[frustrated] {text}"else:emotional_text = text# Add natural breathing for longer textif len(emotional_text.split()) > 15:words = emotional_text.split()mid_point = len(words) // 2emotional_text = " ".join(words[:mid_point]) + " [pause] " + " ".join(words[mid_point:])inputs = self.bark_processor(emotional_text,voice_preset=voice_preset,return_tensors="pt").to(self.device)with torch.no_grad():audio_array = self.bark_model.generate(**inputs)if isinstance(audio_array, torch.Tensor):audio_array = audio_array.cpu().numpy().squeeze()return audio_arrayelse:# Use SpeechT5 with emotional contextclean_text = text.replace("[", "").replace("]", "").strip()if len(clean_text) > 200:clean_text = clean_text[:200] + "..."30 unmodified linesself.call_active = Truegreeting = "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_natural_speech(greeting, "happy")sample_rate = 24000 if self.use_bark else 22050return greeting, (sample_rate, greeting_audio) if greeting_audio is not None else None, "π Call started! Maya is greeting you..."def end_call(self, user_id="default"):3 unmodified linesself.conversations[user_id] = []farewell = "Thank you for chatting with me! It was wonderful talking with you. Have a great day!"farewell_audio = self.synthesize_natural_speech(farewell, "happy")sample_rate = 24000 if self.use_bark else 22050return 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 linestranscription, emotion, self.conversations[user_id])# Step 4: Natural TTS (Better than Dia)response_audio = self.synthesize_natural_speech(response_text, emotion)# Step 5: Update conversation historyprocessing_time = time.time() - start_time7 unmodified linesself.conversations[user_id].append(conversation_entry)# Keep last 1000 exchangesif len(self.conversations[user_id]) > 1000:self.conversations[user_id] = self.conversations[user_id][-1000:]history = self.format_conversation_history(user_id)sample_rate = 24000 if self.use_bark else 22050return transcription, (sample_rate, response_audio) if response_audio is not None else None, historyexcept Exception as e:15 unmodified linesreturn "\n".join(history)# Initialize Maya AIprint("π Starting Maya AI with REAL natural speech...")maya = MayaAI()print("β Maya AI ready with natural emotional speech!")9 unmodified lines# Create Gradio Interfacewith gr.Blocks(title="Maya AI - Natural Speech Sesame Killer",theme=gr.themes.Soft()) as demo:gr.Markdown("""# π€ Maya AI - Natural Speech Sesame Killer*Better than Dia: Natural emotional speech with breathing, laughter, and human-like responses***Features:** β Bark Natural TTS β English-only ASR β Emotion Recognition β FREE Models β Human-like Speech""")with gr.Row():13 unmodified linesprocess_btn = gr.Button("π― Process Audio", variant="primary")with gr.Column(scale=2):gr.Markdown("### π¬ Natural Conversation")transcription_output = gr.Textbox(label="π What you said (English)",2 unmodified lines)audio_output = gr.Audio(label="π Maya's Natural Response (Better than Dia)",interactive=False,autoplay=True)conversation_display = gr.Textbox(label="π Live Conversation (FREE & Natural)",lines=15,interactive=False,show_copy_button=True3 unmodified lines456789103 unmodified lines14151617181920212237 unmodified lines6061626364656667686970717273747576777810 unmodified lines8990919293949596115 unmodified lines21221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425530 unmodified lines2862872882892902912922932942953 unmodified lines29930030130230330430530630721 unmodified lines3293303313323333343353367 unmodified lines34434534634734834935035135235335435535615 unmodified lines3723733743753763773789 unmodified lines38838939039139239339439539639739839940040140213 unmodified lines4164174184194204214222 unmodified lines4254264274284294304314324334344354364373 unmodified linesimport librosafrom transformers import (pipeline, AutoTokenizer, AutoModelForCausalLM,WhisperProcessor, WhisperForConditionalGeneration)import soundfile as sfimport json3 unmodified linesimport warningsfrom datasets import load_dataset# Import Dia TTS modelfrom dia.model import Diawarnings.filterwarnings("ignore")class MayaAI:37 unmodified lines)print("β Emotion recognition loaded")# Load Dia TTS Model (The REAL Dia from Nari Labs)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 = Trueexcept Exception as e:print(f"β οΈ Dia loading failed: {e}")# Fallback to SpeechT5 with FIXED dtypesfrom transformers import SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5HifiGanself.tts_processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")self.tts_model = SpeechT5ForTextToSpeech.from_pretrained("microsoft/speecht5_tts",10 unmodified linesembeddings_dataset[7306]["xvector"],dtype=torch.float32).unsqueeze(0).to(self.device)print("β SpeechT5 TTS loaded as fallback")self.use_dia = False# Conversation storageself.conversations = {}115 unmodified linesexcept Exception as e: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]try:if not text or len(text.strip()) == 0:return Noneif self.use_dia:# Use Dia TTS with proper speaker tags and emotional context# Add emotional markers based on Dia's supported non-verbal tagsif emotion == "happy":emotional_text = f"[S1] {text} (laughs)"[11][15]elif emotion == "sad":emotional_text = f"[S1] {text} (sighs)"[11][15]elif emotion == "excited":emotional_text = f"[S1] {text}!"elif emotion == "angry":emotional_text = f"[S1] {text} (clears throat)"[11][15]elif emotion == "surprised":emotional_text = f"[S1] {text} (gasps)"[11][15]else:emotional_text = f"[S1] {text}"[11][15]# Add natural breathing for longer text (Dia feature)if len(emotional_text.split()) > 15:words = emotional_text.split()mid_point = len(words) // 2emotional_text = " ".join(words[:mid_point]) + " (inhales) " + " ".join(words[mid_point:])# Generate using Dia modeloutput = self.dia_model.generate(emotional_text,use_torch_compile=True if self.device == "cuda" else False,verbose=False)[11][18]return outputelse:# Use SpeechT5 fallback with emotional contextclean_text = text.replace("[", "").replace("]", "").strip()if len(clean_text) > 200:clean_text = clean_text[:200] + "..."30 unmodified linesself.call_active = Truegreeting = "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 ratesample_rate = 44100 if self.use_dia else 22050return greeting, (sample_rate, greeting_audio) if greeting_audio is not None else None, "π Call started! Maya is greeting you..."def end_call(self, user_id="default"):3 unmodified linesself.conversations[user_id] = []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 22050return 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 linestranscription, emotion, self.conversations[user_id])# Step 4: Dia TTS with natural emotional speechresponse_audio = self.synthesize_with_dia(response_text, emotion)# Step 5: Update conversation historyprocessing_time = time.time() - start_time7 unmodified linesself.conversations[user_id].append(conversation_entry)# Keep last 1000 exchanges as specifiedif 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 22050return transcription, (sample_rate, response_audio) if response_audio is not None else None, historyexcept Exception as e:15 unmodified linesreturn "\n".join(history)# Initialize Maya AIprint("π Starting Maya AI with Dia TTS...")maya = MayaAI()print("β Maya AI ready with natural emotional speech!")9 unmodified lines# Create Gradio Interfacewith gr.Blocks(title="Maya AI - Dia TTS 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***Features:** β Dia Natural TTS β English-only ASR β Emotion Recognition β FREE Models β Human-like Speech with Non-verbals""")with gr.Row():13 unmodified linesprocess_btn = gr.Button("π― Process Audio", variant="primary")with gr.Column(scale=2):gr.Markdown("### π¬ Natural Dia 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)",interactive=False,autoplay=True)conversation_display = gr.Textbox(label="π Live Conversation (FREE & Natural Dia TTS)",lines=15,interactive=False,show_copy_button=True
app.py+55-58