Spaces:
Runtime error
Runtime error
Update app.py
Browse files12 unmodified lines13141516171819201617181920212223242225262728292728303132333435303136373839404142353637383940414243444546474849505152535455565758596061626364656667686970434473454675767778798081824748495051525354555688899057585960616263646566989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812967681311326970717273747576134135136137138139140777879808182838485868788899091929394959697981429910010110220 unmodified lines1231241251691261271281296 unmodified lines1361371381821831841391401411421431446 unmodified lines1511521531971541551561579 unmodified lines1671681692131701711721731741751761771781792201801811822232242251831841851861871881891901912322331921931942362371951961971981992002422432012022032042053 unmodified lines2092102112532542552122132142152168 unmodified lines2252262272702282292302312 unmodified lines23423523627928028128228328423712 unmodified lines# Initialize modelsclass ConversationalAI: def __init__(self): # Load Parakeet ASR self.asr_model = self.load_parakeet_asr() # Load Gemini (using local alternative due to API constraints) self.llm_tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-9b-it") # Load ASR model (using Whisper as fallback since Parakeet may not be available) self.asr_model = pipeline("automatic-speech-recognition", model="openai/whisper-large-v3", torch_dtype=torch.float16, device="cuda" if torch.cuda.is_available() else "cpu") # Load LLM (using smaller model for HF Spaces) self.llm_tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium") self.llm_model = AutoModelForCausalLM.from_pretrained( "google/gemma-2-9b-it", "microsoft/DialoGPT-medium", torch_dtype=torch.float16, device_map="auto" ) # Load Dia TTS self.tts_model = self.load_dia_tts() # Load TTS model self.tts_model = pipeline("text-to-speech", model="microsoft/speecht5_tts", torch_dtype=torch.float16, device="cuda" if torch.cuda.is_available() else "cpu") # Load ERVQ for emotion recognition self.emotion_model = self.load_ervq_emotion() # Load emotion recognition self.emotion_model = pipeline("audio-classification", model="ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition", device="cuda" if torch.cuda.is_available() else "cpu") # Conversation history self.conversations = {} def load_parakeet_asr(self): try: from nemo.collections.asr import ASRModel model = ASRModel.from_pretrained("nvidia/parakeet-tdt-0.6b-v2") return model except: # Fallback to Whisper if Parakeet unavailable return pipeline("automatic-speech-recognition", model="openai/whisper-large-v3", torch_dtype=torch.float16, device="cuda") def load_dia_tts(self): try: # Load Dia model from Nari Labs from transformers import AutoModel model = AutoModel.from_pretrained("narilabs/dia-1.6b", torch_dtype=torch.float16, device_map="auto") return model except: # Fallback to high-quality alternative return pipeline("text-to-speech", model="microsoft/speecht5_tts", torch_dtype=torch.float16, device="cuda") def load_ervq_emotion(self): # ERVQ emotion recognition model try: return pipeline("audio-classification", model="speechbrain/emotion-recognition-wav2vec2-IEMOCAP", device="cuda") except: return None def transcribe_audio(self, audio_path): """Transcribe audio using Parakeet ASR""" """Transcribe audio using Whisper""" try: if hasattr(self.asr_model, 'transcribe'): # Parakeet method transcription = self.asr_model.transcribe([audio_path]) return transcription[0] if transcription else "" else: # Whisper fallback result = self.asr_model(audio_path) return result["text"] if audio_path is None: return "No audio provided" result = self.asr_model(audio_path) return result["text"] except Exception as e: return f"Transcription error: {str(e)}" def recognize_emotion(self, audio_path): """Recognize emotion from audio""" if self.emotion_model is None: return "neutral" try: if audio_path is None: return "neutral" result = self.emotion_model(audio_path) return result[0]["label"].lower() except: return "neutral" def generate_response(self, text, emotion, conversation_history): """Generate contextual response using Gemini""" # Build context-aware prompt context = f"Previous conversation: {conversation_history[-3:] if conversation_history else 'None'}" emotion_context = f"User emotion detected: {emotion}" prompt = f"""You are Maya, a naturally conversational AI assistant with emotional intelligence. {context} {emotion_context} Respond naturally and emotionally appropriate to: {text} Keep responses conversational, empathetic, and under 100 words.""" inputs = self.llm_tokenizer(prompt, return_tensors="pt").to("cuda") with torch.no_grad(): outputs = self.llm_model.generate( **inputs, max_new_tokens=150, temperature=0.7, do_sample=True, pad_token_id=self.llm_tokenizer.eos_token_id ) response = self.llm_tokenizer.decode(outputs[0], skip_special_tokens=True) # Extract only the new response response = response.split("Respond naturally")[-1].strip() return response def synthesize_speech(self, text, emotion): """Generate emotional speech using Dia TTS""" """Generate contextual response""" try: # Emotional context for TTS emotional_prompt = f"[{emotion}] {text}" # Build context-aware prompt context = f"Previous conversation: {conversation_history[-2:] if conversation_history else 'None'}" emotion_context = f"User emotion: {emotion}" prompt = f"You are Maya, a friendly AI assistant. {context} {emotion_context} User: {text} Maya:" inputs = self.llm_tokenizer.encode(prompt, return_tensors="pt") if hasattr(self.tts_model, 'generate_speech'): # Dia method audio = self.tts_model.generate_speech(emotional_prompt) else: # Fallback method audio = self.tts_model(text) audio = audio["audio"] with torch.no_grad(): outputs = self.llm_model.generate( inputs, max_new_tokens=100, temperature=0.7, do_sample=True, pad_token_id=self.llm_tokenizer.eos_token_id ) response = self.llm_tokenizer.decode(outputs[0], skip_special_tokens=True) # Extract only the new response response = response.split("Maya:")[-1].strip() return response except Exception as e: return f"I'm sorry, I encountered an error: {str(e)}" def synthesize_speech(self, text): """Generate speech using TTS""" try: # Use a simple TTS approach for HF Spaces audio = self.tts_model(text) return audio return audio["audio"] except Exception as e: return None 20 unmodified lines ) # Step 4: Synthesize speech response_audio = self.synthesize_speech(response_text, emotion) response_audio = self.synthesize_speech(response_text) # Step 5: Update conversation history conversation_entry = {6 unmodified lines self.conversations[user_id].append(conversation_entry) # Keep only last 50 exchanges per user if len(self.conversations[user_id]) > 50: self.conversations[user_id] = self.conversations[user_id][-50:] # Keep only last 20 exchanges per user if len(self.conversations[user_id]) > 20: self.conversations[user_id] = self.conversations[user_id][-20:] # Format conversation history history = self.format_conversation_history(user_id)6 unmodified lines return "No conversation history" history = [] for entry in self.conversations[user_id][-10:]: # Show last 10 exchanges for entry in self.conversations[user_id][-5:]: # Show last 5 exchanges history.append(f"π€ You ({entry['user_emotion']}): {entry['user_input']}") history.append(f"π€ Maya: {entry['ai_response']}") history.append(f"β±οΈ Response time: {entry['processing_time']:.2f}s\n")9 unmodified lines# Initialize the AI systemai_system = ConversationalAI()
# Gradio interface# Gradio interface functionsdef process_audio(audio): if audio is None: return "No audio provided", None, "No conversation yet" transcription, response_audio, history = ai_system.process_conversation(audio) return transcription, response_audio, history
def clear_chat(): message = ai_system.clear_conversation() return message, "Conversation cleared!" return "", "Conversation cleared!"
# Create Gradio interfacewith gr.Blocks(title="Maya AI - Advanced Conversational AI", theme=gr.themes.Soft()) as demo: gr.Markdown("# π€ Maya AI - Your Emotional Conversational Partner") gr.Markdown("*Powered by Parakeet ASR, Gemini LLM, and Dia TTS with emotional intelligence*")with gr.Blocks(title="Maya AI - Conversational Assistant", theme=gr.themes.Soft()) as demo: gr.Markdown("# π€ Maya AI - Your Conversational Partner") gr.Markdown("*Speak naturally and Maya will respond with voice and emotion recognition*") with gr.Row(): with gr.Column(scale=1): audio_input = gr.Audio( sources=["microphone"], type="filepath", label="ποΈ Speak to Maya", interactive=True label="ποΈ Speak to Maya" ) process_btn = gr.Button("π¬ Process Conversation", variant="primary") clear_btn = gr.Button("ποΈ Clear Conversation", variant="secondary") process_btn = gr.Button("π¬ Process", variant="primary") clear_btn = gr.Button("ποΈ Clear Chat", variant="secondary") with gr.Column(scale=2): transcription_output = gr.Textbox( label="π What you said", interactive=False, lines=3 lines=2, interactive=False ) audio_output = gr.Audio(3 unmodified lines conversation_history = gr.Textbox( label="π Conversation History", interactive=False, lines=15, max_lines=20 lines=10, interactive=False ) # Event handlers8 unmodified lines outputs=[transcription_output, conversation_history] ) # Auto-process when audio is recorded # Auto-process when audio is uploaded audio_input.change( fn=process_audio, inputs=[audio_input],2 unmodified lines
# Launch the appif __name__ == "__main__": demo.launch( server_name="0.0.0.0", server_port=7860, share=True, show_error=True ) demo.launch()app.py+79-126