Spaces:
Runtime error
Runtime error
Update app.py
Browse files11 unmodified lines1213141516171819202138 unmodified lines60616263646566676869707172737475767712 unmodified lines9091929394959697989910010187 unmodified lines18919019119219319419517 unmodified lines2132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952964 unmodified lines30130230330430530630721 unmodified lines3293303313323333343358 unmodified lines34434534634734834935035135235335435535615 unmodified lines3723733743753763773783793805 unmodified lines38638738838939039139239339439539639739839940040140213 unmodified lines4164174184194204214222 unmodified lines42542642742842943043143243343443543643711 unmodified linesfrom datetime import datetimeimport osimport warningsfrom datasets import load_dataset# Import Dia TTS modelfrom dia.model import Diawarnings.filterwarnings("ignore")38 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(12 unmodified linesdtype=torch.float32).unsqueeze(0).to(self.device)print("β SpeechT5 TTS loaded as fallback")self.use_dia = False# Conversation storageself.conversations = {}self.call_active = Falsedef transcribe_with_whisper(self, audio_path):"""Transcribe using Whisper with FORCED English"""try:87 unmodified lineswith torch.no_grad():outputs = self.llm_model.generate(input_ids=inputs.input_ids,attention_mask=inputs.attention_mask, # FIX: Explicit attention maskmax_new_tokens=80,temperature=0.7,do_sample=True,17 unmodified linesreturn 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] + "..."# Add emotional inflection through punctuationif 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 speechexcept Exception as e:print(f"TTS error: {e}")return Nonedef start_call(self):"""Start a new call session"""self.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"):"""End call and clear conversation"""4 unmodified linesfarewell = "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 history8 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!")# Gradio Interface Functionsdef start_call_handler():5 unmodified linesdef process_audio_handler(audio):return maya.process_conversation(audio)# 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=True11 unmodified lines12131415161718192021222324252638 unmodified lines656667686970717273747576777879808182838485868788899091929394959697989910012 unmodified lines11311411511611711811912012187 unmodified lines20921021121221321421517 unmodified lines2332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233244 unmodified lines32933033133233333433521 unmodified lines3573583593603613623638 unmodified lines37237337437537637737837938038138238338415 unmodified lines4004014024034044054064074085 unmodified lines41441541641741841942042142242342442542642742842943013 unmodified lines4444454464474484494502 unmodified lines45345445545645745845946046146246346446511 unmodified linesfrom datetime import datetimeimport osimport warnings# Import Dia model correctly[2]try:from dia.model import DiaDIA_AVAILABLE = Trueprint("β Dia model imported successfully")except ImportError as e:print(f"β οΈ Dia import failed: {e}")DIA_AVAILABLE = Falsewarnings.filterwarnings("ignore")38 unmodified lines)print("β Emotion recognition loaded")# 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 = Trueexcept Exception as e:print(f"β οΈ Dia loading failed: {e}")self.use_dia = Falseself._load_fallback_tts()else:print("β οΈ Dia not available, using fallback TTS")self.use_dia = Falseself._load_fallback_tts()# Conversation storageself.conversations = {}self.call_active = Falseself.speaker_turn = 1 # Track speaker turns for Dia[2]def _load_fallback_tts(self):"""Load fallback TTS if Dia is not available"""try:from transformers import SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5HifiGanfrom datasets import load_datasetself.tts_processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")self.tts_model = SpeechT5ForTextToSpeech.from_pretrained(12 unmodified linesdtype=torch.float32).unsqueeze(0).to(self.device)print("β SpeechT5 TTS loaded as fallback")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 lineswith torch.no_grad():outputs = self.llm_model.generate(input_ids=inputs.input_ids,attention_mask=inputs.attention_mask,max_new_tokens=80,temperature=0.7,do_sample=True,17 unmodified linesreturn f"{emotion_prompts.get(emotion, 'I understand.')} Could you tell me more about that?"def synthesize_with_dia(self, text, emotion):"""Generate ultra-realistic dialogue using Dia[2]"""try:if not text or len(text.strip()) == 0:return Noneif self.use_dia:# 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"{speaker_tag} {text} (laughs)"elif emotion == "sad":emotional_text = f"{speaker_tag} {text} (sighs)"elif emotion == "excited":emotional_text = f"{speaker_tag} {text}!"elif emotion == "angry":emotional_text = f"{speaker_tag} {text} (frustrated tone)"elif emotion == "surprised":emotional_text = f"{speaker_tag} {text} (gasps)"else:emotional_text = f"{speaker_tag} {text}"# Generate with Dia[2]output = self.dia_model.generate(emotional_text,use_torch_compile=True if self.device == "cuda" else False,verbose=False)# Toggle speaker for next turn[2]self.speaker_turn = 2 if self.speaker_turn == 1 else 1return outputelse:# Fallback to SpeechT5return 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 punctuationif 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 speechexcept Exception as e:print(f"Fallback TTS error: {e}")return Nonedef start_call(self):"""Start a new call session"""self.call_active = Trueself.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 24kHz, fallback at 22050Hz[2]sample_rate = 24000 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 with ultra-realistic speech..."def end_call(self, user_id="default"):"""End call and clear conversation"""4 unmodified linesfarewell = "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 = 24000 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: Ultra-realistic TTS with Dia[2]response_audio = self.synthesize_with_dia(response_text, emotion)# Step 5: Update conversation history8 unmodified linesself.conversations[user_id].append(conversation_entry)# 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 = 24000 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 REAL Dia TTS...")maya = MayaAI()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[7]with gr.Blocks(title="Maya AI - Dia-Powered Sesame Killer",theme=gr.themes.Soft()) as demo:gr.Markdown("""# π€ Maya AI - Dia-Powered Sesame Killer*Ultra-realistic dialogue generation with Dia TTS - Natural breathing, laughter, and human-like responses***Features:** β Real Dia TTS β English-only ASR β Emotion Recognition β FREE LLM β Ultra-realistic Speech""")with gr.Row():13 unmodified linesprocess_btn = gr.Button("π― Process Audio", variant="primary")with gr.Column(scale=2):gr.Markdown("### π¬ Ultra-Realistic Conversation")transcription_output = gr.Textbox(label="π What you said (English)",2 unmodified lines)audio_output = gr.Audio(label="π Maya's Ultra-Realistic Response (Dia TTS)",interactive=False,autoplay=True)conversation_display = gr.Textbox(label="π Live Conversation (FREE & Ultra-Realistic)",lines=15,interactive=False,show_copy_button=True
app.py+110-82