Spaces:
Runtime error
Runtime error
Update app.py
Browse files21 unmodified lines2223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001019 unmodified lines1111121131141151161176 unmodified lines12412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815911 unmodified lines1711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172184 unmodified lines2232242252262272282294 unmodified lines23423523623723823924011 unmodified lines2522532542552562572582593 unmodified lines2632642652662672682692707 unmodified lines27827928028128228328420 unmodified lines3053063073083093103119 unmodified lines32132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837921 unmodified linesself.device = "cuda" if torch.cuda.is_available() else "cpu"print(f"π Initializing Maya AI on {self.device}")# Load Parakeet ASR (Best performance)try:from nemo.collections.asr import ASRModelself.asr_model = ASRModel.from_pretrained("nvidia/parakeet-tdt-0.6b-v2")print("β Parakeet ASR loaded")except:self.asr_model = pipeline("automatic-speech-recognition",model="openai/whisper-large-v3",torch_dtype=torch.float16,device=self.device)print("β οΈ Using Whisper fallback")# Load FREE DeepSeek-V3 LLM (Best free option)[1][5]try:self.llm_tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/deepseek-llm-67b-chat")self.llm_model = AutoModelForCausalLM.from_pretrained("deepseek-ai/deepseek-llm-67b-chat",torch_dtype=torch.float16,device_map="auto",trust_remote_code=True)print("β DeepSeek-V3 loaded (FREE)")except:# Fallback to Llama 3.1 (also free)self.llm_tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-70B-Instruct")self.llm_model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.1-70B-Instruct",torch_dtype=torch.float16,device_map="auto")print("β Llama 3.1 loaded (FREE fallback)")# Load Emotion Recognitionself.emotion_model = pipeline("audio-classification",model="superb/wav2vec2-base-superb-er",device=self.device)print("β Emotion recognition loaded")# Load TTS with speaker embeddings (FREE)self.tts_processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")self.tts_model = SpeechT5ForTextToSpeech.from_pretrained("microsoft/speecht5_tts",torch_dtype=torch.float16).to(self.device)self.vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan",torch_dtype=torch.float16).to(self.device)# Load speaker embeddings for natural female voiceembeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")# Use female speaker embedding (index 7306 is female)self.speaker_embeddings = torch.tensor(embeddings_dataset[7306]["xvector"]).unsqueeze(0).to(self.device)print("β Natural female TTS voice loaded")# Conversation storageself.conversations = {}self.call_active = Falsedef transcribe_with_parakeet(self, audio_path):"""Transcribe using Parakeet (6.05% WER)"""try:if hasattr(self.asr_model, 'transcribe'):transcription = self.asr_model.transcribe([audio_path])return transcription[0] if transcription else ""else:result = self.asr_model(audio_path)return result["text"]except Exception as e:return f"Transcription error: {str(e)}"def recognize_emotion_from_audio(self, audio_path):"""Recognize emotion using superb model"""try:result = self.emotion_model(audio_path)emotion_label = result[0]["label"].lower()9 unmodified linesreturn "neutral"def generate_with_free_llm(self, text, emotion, history):"""Generate response using FREE DeepSeek-V3 or Llama"""try:# Emotional context promptingemotion_prompts = {6 unmodified lines"neutral": "I'm listening carefully. Please continue."}context = f"Previous conversation: {history[-3:] if history else 'None'}"emotion_context = emotion_prompts.get(emotion, "I'm here to help.")prompt = f"""You are Maya, an emotionally intelligent AI assistant with natural conversational abilities.{context}User emotion detected: {emotion}User input: {text}Respond naturally with emotional intelligence. Keep responses under 100 words and conversational.{emotion_context}Maya:"""# Tokenize inputinputs = self.llm_tokenizer(prompt,return_tensors="pt",truncation=True,max_length=2048).to(self.device)# Generate responsewith 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)# Decode response11 unmodified linesexcept Exception as e:return f"{emotion_prompts.get(emotion, 'I understand.')} Could you tell me more about that?"def synthesize_emotional_speech(self, text, emotion):"""Generate emotional speech with natural breathing"""try:if not text or len(text.strip()) == 0:return None# Add emotional markers to textemotional_text = textif emotion == "happy":emotional_text = f"*cheerfully* {text}"elif emotion == "sad":emotional_text = f"*gently* {text}"elif emotion == "excited":emotional_text = f"*enthusiastically* {text}"elif emotion == "angry":emotional_text = f"*calmly* {text}"# Clean text for TTSclean_text = emotional_text.replace("*", "").replace("[", "").replace("]", "").strip()if len(clean_text) > 200:clean_text = clean_text[:200] + "..."# Add natural breathing pauses for longer textif len(clean_text.split()) > 10:words = clean_text.split()mid_point = len(words) // 2clean_text = " ".join(words[:mid_point]) + "... " + " ".join(words[mid_point:])# Process with TTSinputs = self.tts_processor(text=clean_text, return_tensors="pt").to(self.device)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()return speechexcept Exception as e:print(f"TTS error: {e}")4 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_emotional_speech(greeting, "happy")return greeting, (22050, greeting_audio) if greeting_audio is not None else None, "π Call started! Maya is greeting you..."4 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_emotional_speech(farewell, "happy")return farewell, (22050, farewell_audio) if farewell_audio is not None else None, "π Call ended. Conversation cleared!"11 unmodified linesself.conversations[user_id] = []try:# Step 1: ASR with Parakeettranscription = self.transcribe_with_parakeet(audio_input)# Step 2: Emotion recognitionemotion = self.recognize_emotion_from_audio(audio_input)3 unmodified linestranscription, emotion, self.conversations[user_id])# Step 4: Emotional TTSresponse_audio = self.synthesize_emotional_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 exchanges as specifiedif len(self.conversations[user_id]) > 1000:self.conversations[user_id] = self.conversations[user_id][-1000:]20 unmodified linesreturn "\n".join(history)# Initialize Maya AIprint("π Starting Maya AI with FREE models...")maya = MayaAI()print("β Maya AI ready with ZERO API costs!")9 unmodified lines# Create Gradio Interfacewith gr.Blocks(title="Maya AI - FREE Sesame AI Killer",theme=gr.themes.Soft(),css=""".call-button { background: linear-gradient(45deg, #00d2d3, #01a3a4) !important; }.end-button { background: linear-gradient(45deg, #ff3838, #c0392b) !important; }""") as demo:gr.Markdown("""# π€ Maya AI - FREE Sesame AI Killer*Advanced conversational AI with emotional intelligence - NO API COSTS!***FREE Models:** DeepSeek-V3 β’ Parakeet ASR β’ Emotion Recognition β’ Natural Female TTS""")with gr.Row():with gr.Column(scale=1):gr.Markdown("### π Call Controls")start_call_btn = gr.Button("π Start Call",variant="primary",size="lg",elem_classes=["call-button"])end_call_btn = gr.Button("π End Call",variant="stop",size="lg",elem_classes=["end-button"])gr.Markdown("### ποΈ Voice Input")audio_input = gr.Audio(sources=["microphone"],type="filepath",label="Record your message")process_btn = gr.Button("π― Process Audio", variant="primary")with gr.Column(scale=2):gr.Markdown("### π¬ FREE Conversation")transcription_output = gr.Textbox(label="π What you said",lines=2,interactive=False)audio_output = gr.Audio(label="π Maya's Emotional Response",interactive=False,autoplay=True)21 unmodified lines2223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481499 unmodified lines1591601611621631641656 unmodified lines17217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420511 unmodified lines2172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602614 unmodified lines2662672682692702712724 unmodified lines27727827928028128228311 unmodified lines2952962972982993003013023 unmodified lines3063073083093103113123137 unmodified lines32132232332432532632720 unmodified lines3483493503513523533549 unmodified lines36436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640721 unmodified linesself.device = "cuda" if torch.cuda.is_available() else "cpu"print(f"π Initializing Maya AI on {self.device}")# Load Whisper ASR with FORCED English (Fixed language issue)self.asr_processor = WhisperProcessor.from_pretrained("openai/whisper-large-v3")self.asr_model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-large-v3",torch_dtype=torch.float16 if self.device == "cuda" else torch.float32).to(self.device)# FORCE English transcription (Fix for language detection issue)self.asr_model.config.forced_decoder_ids = self.asr_processor.get_decoder_prompt_ids(language="english",task="transcribe")print("β Whisper ASR loaded with FORCED English")# Load FREE DeepSeek LLM (smaller version that fits in HF Spaces)try:self.llm_tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-large")self.llm_model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-large",torch_dtype=torch.float16 if self.device == "cuda" else torch.float32,device_map="auto")print("β DialoGPT-Large loaded (FREE)")except:# Even smaller fallbackself.llm_tokenizer = AutoTokenizer.from_pretrained("microsoft/DialoGPT-medium")self.llm_model = AutoModelForCausalLM.from_pretrained("microsoft/DialoGPT-medium",torch_dtype=torch.float16 if self.device == "cuda" else torch.float32).to(self.device)print("β DialoGPT-Medium loaded (FREE fallback)")# Load Emotion Recognitionself.emotion_model = pipeline("audio-classification",model="superb/wav2vec2-base-superb-er",device=self.device)print("β Emotion recognition loaded")# Load Dia TTS (FIXED dtype issue)try:# Import Dia directlyfrom huggingface_hub import hf_hub_downloadimport importlib.util# Download Dia model filesmodel_path = hf_hub_download(repo_id="nari-labs/Dia-1.6B", filename="model.py")spec = importlib.util.spec_from_file_location("dia_model", model_path)dia_module = importlib.util.module_from_spec(spec)spec.loader.exec_module(dia_module)self.dia_model = dia_module.Dia.from_pretrained("nari-labs/Dia-1.6B")print("β Dia TTS loaded successfully")self.use_dia = Trueexcept Exception as e:print(f"β οΈ Dia loading failed: {e}")# Fallback to SpeechT5 with FIXED dtypeself.tts_processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")self.tts_model = SpeechT5ForTextToSpeech.from_pretrained("microsoft/speecht5_tts",torch_dtype=torch.float32 # FIXED: Use float32 consistently).to(self.device)self.vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan",torch_dtype=torch.float32 # FIXED: Use float32 consistently).to(self.device)# Load speaker embeddings for natural female voiceembeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")self.speaker_embeddings = torch.tensor(embeddings_dataset[7306]["xvector"],dtype=torch.float32 # FIXED: Consistent dtype).unsqueeze(0).to(self.device)print("β SpeechT5 TTS loaded with FIXED dtypes")self.use_dia = False# Conversation storageself.conversations = {}self.call_active = Falsedef transcribe_with_whisper(self, audio_path):"""Transcribe using Whisper with FORCED English"""try:if audio_path is None:return "No audio provided"# Load and preprocess audioaudio, sr = librosa.load(audio_path, sr=16000, mono=True)# Process with Whisper - FORCE Englishinputs = self.asr_processor(audio,sampling_rate=16000,return_tensors="pt",language="english" # FORCE English).to(self.device)with torch.no_grad():predicted_ids = self.asr_model.generate(inputs.input_features,max_new_tokens=150,do_sample=False,forced_decoder_ids=self.asr_model.config.forced_decoder_ids # FORCE English)transcription = self.asr_processor.batch_decode(predicted_ids,skip_special_tokens=True)[0]return transcription.strip()except Exception as e:return f"Transcription error: {str(e)}"def recognize_emotion_from_audio(self, audio_path):"""Recognize emotion using superb model"""try:if audio_path is None:return "neutral"result = self.emotion_model(audio_path)emotion_label = result[0]["label"].lower()9 unmodified linesreturn "neutral"def generate_with_free_llm(self, text, emotion, history):"""Generate response using FREE LLM"""try:# Emotional context promptingemotion_prompts = {6 unmodified lines"neutral": "I'm listening carefully. Please continue."}emotion_context = emotion_prompts.get(emotion, "I'm here to help.")# Build conversation contextcontext_text = ""if history:for entry in history[-2:]: # Last 2 exchanges for contextcontext_text += f"User: {entry.get('user_input', '')}\nMaya: {entry.get('ai_response', '')}\n"prompt = f"{context_text}User: {text}\nMaya:"# Tokenize inputinputs = self.llm_tokenizer(prompt,return_tensors="pt",truncation=True,max_length=1024,padding=True).to(self.device)# Generate responsewith torch.no_grad():outputs = self.llm_model.generate(**inputs,max_new_tokens=80,temperature=0.7,do_sample=True,pad_token_id=self.llm_tokenizer.eos_token_id,attention_mask=inputs.attention_mask)# Decode response11 unmodified linesexcept Exception as e:return f"{emotion_prompts.get(emotion, 'I understand.')} Could you tell me more about that?"def synthesize_speech(self, text, emotion):"""Generate speech with FIXED dtype issues"""try:if not text or len(text.strip()) == 0:return Noneif self.use_dia:# Use Dia for natural speech with emotionsemotional_text = f"[S1] {text}"if emotion == "happy":emotional_text += " (laughs)"elif emotion == "sad":emotional_text += " (sighs)"elif emotion == "excited":emotional_text += " (enthusiastically)"output = self.dia_model.generate(emotional_text)return outputelse:# Use SpeechT5 with FIXED dtypesclean_text = text.replace("[", "").replace("]", "").strip()if len(clean_text) > 200:clean_text = clean_text[:200] + "..."# Process with TTS - ALL FLOAT32inputs = 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) # FIXED: Consistent dtypereturn speechexcept Exception as e:print(f"TTS error: {e}")4 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_speech(greeting, "happy")return greeting, (22050, greeting_audio) if greeting_audio is not None else None, "π Call started! Maya is greeting you..."4 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_speech(farewell, "happy")return farewell, (22050, farewell_audio) if farewell_audio is not None else None, "π Call ended. Conversation cleared!"11 unmodified linesself.conversations[user_id] = []try:# Step 1: ASR with FORCED Englishtranscription = self.transcribe_with_whisper(audio_input)# Step 2: Emotion recognitionemotion = self.recognize_emotion_from_audio(audio_input)3 unmodified linestranscription, emotion, self.conversations[user_id])# Step 4: TTS with FIXED dtypesresponse_audio = self.synthesize_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:]20 unmodified linesreturn "\n".join(history)# Initialize Maya AIprint("π Starting Maya AI with FIXED issues...")maya = MayaAI()print("β Maya AI ready with ZERO API costs!")9 unmodified lines# Create Gradio Interfacewith gr.Blocks(title="Maya AI - FIXED Sesame AI Killer",theme=gr.themes.Soft()) as demo:gr.Markdown("""# π€ Maya AI - FIXED Sesame AI Killer*All issues resolved: English-only transcription, working audio output, FREE models***FIXES:** β English-only ASR β Working TTS audio β FREE LLM β Emotion recognition""")with gr.Row():with gr.Column(scale=1):gr.Markdown("### π Call Controls")start_call_btn = gr.Button("π Start Call", variant="primary", size="lg")end_call_btn = gr.Button("π End Call", variant="stop", size="lg")gr.Markdown("### ποΈ Voice Input")audio_input = gr.Audio(sources=["microphone"],type="filepath",label="Record your message in English")process_btn = gr.Button("π― Process Audio", variant="primary")with gr.Column(scale=2):gr.Markdown("### π¬ English Conversation")transcription_output = gr.Textbox(label="π What you said (English)",lines=2,interactive=False)audio_output = gr.Audio(label="π Maya's Response (Working Audio)",interactive=False,autoplay=True)
app.py+166-138