Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,163 +2,158 @@ import gradio as gr
|
|
| 2 |
import torch
|
| 3 |
import numpy as np
|
| 4 |
import librosa
|
| 5 |
-
from transformers import
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
import soundfile as sf
|
| 7 |
import json
|
| 8 |
import time
|
| 9 |
from datetime import datetime
|
| 10 |
import os
|
| 11 |
import warnings
|
|
|
|
| 12 |
|
| 13 |
-
# Suppress warnings for cleaner output
|
| 14 |
warnings.filterwarnings("ignore")
|
| 15 |
|
| 16 |
-
class
|
| 17 |
def __init__(self):
|
| 18 |
-
# Set device
|
| 19 |
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 20 |
-
print(f"
|
| 21 |
|
| 22 |
-
# Load
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
"
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
-
# Load LLM
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
-
# Load
|
| 39 |
-
self.
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
-
# Load
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
)
|
| 52 |
|
| 53 |
-
# Conversation
|
| 54 |
self.conversations = {}
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
|
|
|
| 58 |
try:
|
| 59 |
-
if
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
# Process with Whisper
|
| 66 |
-
inputs = self.asr_processor(
|
| 67 |
-
audio,
|
| 68 |
-
sampling_rate=16000,
|
| 69 |
-
return_tensors="pt",
|
| 70 |
-
language="en"
|
| 71 |
-
).to(self.device)
|
| 72 |
-
|
| 73 |
-
with torch.no_grad():
|
| 74 |
-
predicted_ids = self.asr_model.generate(
|
| 75 |
-
inputs.input_features,
|
| 76 |
-
max_new_tokens=100,
|
| 77 |
-
do_sample=False
|
| 78 |
-
)
|
| 79 |
-
|
| 80 |
-
transcription = self.asr_processor.batch_decode(
|
| 81 |
-
predicted_ids,
|
| 82 |
-
skip_special_tokens=True
|
| 83 |
-
)[0]
|
| 84 |
-
|
| 85 |
-
return transcription.strip()
|
| 86 |
-
|
| 87 |
except Exception as e:
|
| 88 |
return f"Transcription error: {str(e)}"
|
| 89 |
|
| 90 |
-
def
|
| 91 |
-
"""Recognize emotion
|
| 92 |
try:
|
| 93 |
-
if audio_path is None:
|
| 94 |
-
return "neutral"
|
| 95 |
-
|
| 96 |
result = self.emotion_model(audio_path)
|
| 97 |
emotion_label = result[0]["label"].lower()
|
| 98 |
|
| 99 |
-
# Map
|
| 100 |
-
|
| 101 |
-
"ang": "angry",
|
| 102 |
-
"
|
| 103 |
-
"
|
| 104 |
-
"sad": "sad",
|
| 105 |
-
"fru": "frustrated",
|
| 106 |
-
"fea": "fearful",
|
| 107 |
-
"sur": "surprised",
|
| 108 |
-
"neu": "neutral",
|
| 109 |
-
"dis": "disgusted"
|
| 110 |
}
|
| 111 |
|
| 112 |
-
return
|
| 113 |
-
|
| 114 |
-
except Exception as e:
|
| 115 |
-
print(f"Emotion recognition error: {e}")
|
| 116 |
return "neutral"
|
| 117 |
|
| 118 |
-
def
|
| 119 |
-
"""Generate
|
| 120 |
try:
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
"
|
| 127 |
-
"
|
| 128 |
-
"
|
| 129 |
-
"
|
| 130 |
-
"fearful": "I can hear the concern in your voice. Let's work through this together.",
|
| 131 |
-
"surprised": "That sounds quite unexpected! What happened?",
|
| 132 |
-
"frustrated": "I can tell this is bothering you. Let's see how I can help.",
|
| 133 |
-
"neutral": "I'm listening. Please go on."
|
| 134 |
}
|
| 135 |
|
| 136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
return f"{emotion_context} Could you tell me more about that?"
|
| 141 |
|
| 142 |
-
|
| 143 |
|
| 144 |
-
# Tokenize
|
| 145 |
inputs = self.llm_tokenizer(
|
| 146 |
-
prompt,
|
| 147 |
return_tensors="pt",
|
| 148 |
-
padding=True,
|
| 149 |
truncation=True,
|
| 150 |
-
max_length=
|
| 151 |
).to(self.device)
|
| 152 |
|
|
|
|
| 153 |
with torch.no_grad():
|
| 154 |
outputs = self.llm_model.generate(
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
max_new_tokens=60,
|
| 158 |
temperature=0.7,
|
| 159 |
do_sample=True,
|
| 160 |
-
pad_token_id=self.llm_tokenizer.eos_token_id
|
| 161 |
-
eos_token_id=self.llm_tokenizer.eos_token_id
|
| 162 |
)
|
| 163 |
|
| 164 |
# Decode response
|
|
@@ -167,58 +162,109 @@ class ConversationalAI:
|
|
| 167 |
skip_special_tokens=True
|
| 168 |
).strip()
|
| 169 |
|
| 170 |
-
# Clean up
|
| 171 |
if not response or len(response) < 5:
|
| 172 |
return emotion_context
|
| 173 |
|
| 174 |
return response
|
| 175 |
|
| 176 |
except Exception as e:
|
| 177 |
-
return "I
|
| 178 |
|
| 179 |
-
def
|
| 180 |
-
"""Generate speech
|
| 181 |
try:
|
| 182 |
if not text or len(text.strip()) == 0:
|
| 183 |
return None
|
| 184 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
# Clean text for TTS
|
| 186 |
-
clean_text =
|
| 187 |
if len(clean_text) > 200:
|
| 188 |
clean_text = clean_text[:200] + "..."
|
| 189 |
|
| 190 |
-
|
| 191 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
|
| 193 |
except Exception as e:
|
| 194 |
print(f"TTS error: {e}")
|
| 195 |
return None
|
| 196 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
def process_conversation(self, audio_input, user_id="default"):
|
| 198 |
"""Main conversation processing pipeline"""
|
|
|
|
|
|
|
|
|
|
| 199 |
if audio_input is None:
|
| 200 |
-
return "Please record some audio
|
| 201 |
|
| 202 |
start_time = time.time()
|
| 203 |
|
| 204 |
-
# Initialize user conversation if not exists
|
| 205 |
if user_id not in self.conversations:
|
| 206 |
self.conversations[user_id] = []
|
| 207 |
|
| 208 |
try:
|
| 209 |
-
# Step 1:
|
| 210 |
-
transcription = self.
|
| 211 |
|
| 212 |
-
# Step 2:
|
| 213 |
-
emotion = self.
|
| 214 |
|
| 215 |
-
# Step 3:
|
| 216 |
-
response_text = self.
|
| 217 |
transcription, emotion, self.conversations[user_id]
|
| 218 |
)
|
| 219 |
|
| 220 |
-
# Step 4:
|
| 221 |
-
response_audio = self.
|
| 222 |
|
| 223 |
# Step 5: Update conversation history
|
| 224 |
processing_time = time.time() - start_time
|
|
@@ -232,147 +278,139 @@ class ConversationalAI:
|
|
| 232 |
|
| 233 |
self.conversations[user_id].append(conversation_entry)
|
| 234 |
|
| 235 |
-
# Keep
|
| 236 |
-
if len(self.conversations[user_id]) >
|
| 237 |
-
self.conversations[user_id] = self.conversations[user_id][-
|
| 238 |
|
| 239 |
-
# Format conversation history
|
| 240 |
history = self.format_conversation_history(user_id)
|
| 241 |
|
| 242 |
-
return transcription, response_audio, history
|
| 243 |
|
| 244 |
except Exception as e:
|
| 245 |
-
|
| 246 |
-
return error_msg, None, "Error occurred during processing"
|
| 247 |
|
| 248 |
def format_conversation_history(self, user_id):
|
| 249 |
"""Format conversation history for display"""
|
| 250 |
if user_id not in self.conversations or not self.conversations[user_id]:
|
| 251 |
-
return "No conversation history yet.
|
| 252 |
|
| 253 |
history = []
|
| 254 |
-
for i, entry in enumerate(self.conversations[user_id][-
|
| 255 |
history.append(f"**Exchange {i}** ({entry['timestamp']})")
|
| 256 |
history.append(f"π€ **You** ({entry['user_emotion']}): {entry['user_input']}")
|
| 257 |
history.append(f"π€ **Maya**: {entry['ai_response']}")
|
| 258 |
-
history.append(f"β±οΈ *
|
| 259 |
history.append("---")
|
| 260 |
|
| 261 |
return "\n".join(history)
|
| 262 |
-
|
| 263 |
-
def clear_conversation(self, user_id="default"):
|
| 264 |
-
"""Clear conversation history"""
|
| 265 |
-
if user_id in self.conversations:
|
| 266 |
-
self.conversations[user_id] = []
|
| 267 |
-
return "Conversation cleared! Ready for a fresh start."
|
| 268 |
|
| 269 |
-
# Initialize
|
| 270 |
-
print("
|
| 271 |
-
|
| 272 |
-
print("Maya AI ready!")
|
| 273 |
|
| 274 |
-
# Gradio
|
| 275 |
-
def
|
| 276 |
-
|
| 277 |
-
return "Please record some audio first", None, "Click the microphone button above to start recording"
|
| 278 |
-
|
| 279 |
-
return ai_system.process_conversation(audio)
|
| 280 |
|
| 281 |
-
def
|
| 282 |
-
|
| 283 |
-
return "", None, message
|
| 284 |
|
| 285 |
-
def
|
| 286 |
-
return
|
| 287 |
|
| 288 |
-
# Create Gradio
|
| 289 |
with gr.Blocks(
|
| 290 |
-
title="Maya AI -
|
| 291 |
theme=gr.themes.Soft(),
|
| 292 |
css="""
|
| 293 |
-
.
|
| 294 |
-
|
| 295 |
-
}
|
| 296 |
-
.audio-container {
|
| 297 |
-
min-height: 200px;
|
| 298 |
-
}
|
| 299 |
"""
|
| 300 |
) as demo:
|
| 301 |
|
| 302 |
gr.Markdown("""
|
| 303 |
-
# π€ Maya AI -
|
| 304 |
-
*Advanced
|
| 305 |
|
| 306 |
-
**
|
| 307 |
""")
|
| 308 |
|
| 309 |
with gr.Row():
|
| 310 |
with gr.Column(scale=1):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 311 |
gr.Markdown("### ποΈ Voice Input")
|
| 312 |
audio_input = gr.Audio(
|
| 313 |
sources=["microphone"],
|
| 314 |
type="filepath",
|
| 315 |
-
label="Record your message"
|
| 316 |
-
elem_classes=["audio-container"]
|
| 317 |
)
|
| 318 |
|
| 319 |
-
|
| 320 |
-
process_btn = gr.Button("π¬ Process Audio", variant="primary", size="lg")
|
| 321 |
-
clear_btn = gr.Button("ποΈ Clear Chat", variant="secondary")
|
| 322 |
|
| 323 |
with gr.Column(scale=2):
|
| 324 |
-
gr.Markdown("###
|
|
|
|
| 325 |
transcription_output = gr.Textbox(
|
| 326 |
-
label="What you said",
|
| 327 |
lines=2,
|
| 328 |
-
interactive=False
|
| 329 |
-
placeholder="Your speech will appear here..."
|
| 330 |
)
|
| 331 |
|
| 332 |
audio_output = gr.Audio(
|
| 333 |
-
label="π Maya's Response",
|
| 334 |
interactive=False,
|
| 335 |
autoplay=True
|
| 336 |
)
|
| 337 |
|
| 338 |
-
|
| 339 |
-
label="π Conversation
|
| 340 |
-
lines=
|
| 341 |
interactive=False,
|
| 342 |
-
placeholder="Conversation history will appear here...",
|
| 343 |
show_copy_button=True
|
| 344 |
)
|
| 345 |
|
| 346 |
-
# Event
|
| 347 |
-
|
| 348 |
-
fn=
|
| 349 |
-
|
| 350 |
-
outputs=[transcription_output, audio_output, conversation_history]
|
| 351 |
)
|
| 352 |
|
| 353 |
-
|
| 354 |
-
fn=
|
| 355 |
-
outputs=[transcription_output, audio_output,
|
| 356 |
)
|
| 357 |
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
fn=process_audio,
|
| 361 |
inputs=[audio_input],
|
| 362 |
-
outputs=[transcription_output, audio_output,
|
| 363 |
)
|
| 364 |
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
outputs=[transcription_output, audio_output,
|
| 369 |
)
|
| 370 |
|
| 371 |
-
# Launch the app
|
| 372 |
if __name__ == "__main__":
|
| 373 |
demo.launch(
|
| 374 |
server_name="0.0.0.0",
|
| 375 |
server_port=7860,
|
| 376 |
-
show_error=True
|
| 377 |
-
quiet=True
|
| 378 |
)
|
|
|
|
| 2 |
import torch
|
| 3 |
import numpy as np
|
| 4 |
import librosa
|
| 5 |
+
from transformers import (
|
| 6 |
+
pipeline, AutoTokenizer, AutoModelForCausalLM,
|
| 7 |
+
WhisperProcessor, WhisperForConditionalGeneration,
|
| 8 |
+
SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5HifiGan
|
| 9 |
+
)
|
| 10 |
import soundfile as sf
|
| 11 |
import json
|
| 12 |
import time
|
| 13 |
from datetime import datetime
|
| 14 |
import os
|
| 15 |
import warnings
|
| 16 |
+
from datasets import load_dataset
|
| 17 |
|
|
|
|
| 18 |
warnings.filterwarnings("ignore")
|
| 19 |
|
| 20 |
+
class MayaAI:
|
| 21 |
def __init__(self):
|
|
|
|
| 22 |
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 23 |
+
print(f"π Initializing Maya AI on {self.device}")
|
| 24 |
|
| 25 |
+
# Load Parakeet ASR (Best performance)
|
| 26 |
+
try:
|
| 27 |
+
from nemo.collections.asr import ASRModel
|
| 28 |
+
self.asr_model = ASRModel.from_pretrained("nvidia/parakeet-tdt-0.6b-v2")
|
| 29 |
+
print("β
Parakeet ASR loaded")
|
| 30 |
+
except:
|
| 31 |
+
self.asr_model = pipeline("automatic-speech-recognition",
|
| 32 |
+
model="openai/whisper-large-v3",
|
| 33 |
+
torch_dtype=torch.float16,
|
| 34 |
+
device=self.device)
|
| 35 |
+
print("β οΈ Using Whisper fallback")
|
| 36 |
|
| 37 |
+
# Load FREE DeepSeek-V3 LLM (Best free option)[1][5]
|
| 38 |
+
try:
|
| 39 |
+
self.llm_tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/deepseek-llm-67b-chat")
|
| 40 |
+
self.llm_model = AutoModelForCausalLM.from_pretrained(
|
| 41 |
+
"deepseek-ai/deepseek-llm-67b-chat",
|
| 42 |
+
torch_dtype=torch.float16,
|
| 43 |
+
device_map="auto",
|
| 44 |
+
trust_remote_code=True
|
| 45 |
+
)
|
| 46 |
+
print("β
DeepSeek-V3 loaded (FREE)")
|
| 47 |
+
except:
|
| 48 |
+
# Fallback to Llama 3.1 (also free)
|
| 49 |
+
self.llm_tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-70B-Instruct")
|
| 50 |
+
self.llm_model = AutoModelForCausalLM.from_pretrained(
|
| 51 |
+
"meta-llama/Llama-3.1-70B-Instruct",
|
| 52 |
+
torch_dtype=torch.float16,
|
| 53 |
+
device_map="auto"
|
| 54 |
+
)
|
| 55 |
+
print("β
Llama 3.1 loaded (FREE fallback)")
|
| 56 |
|
| 57 |
+
# Load Emotion Recognition
|
| 58 |
+
self.emotion_model = pipeline("audio-classification",
|
| 59 |
+
model="superb/wav2vec2-base-superb-er",
|
| 60 |
+
device=self.device)
|
| 61 |
+
print("β
Emotion recognition loaded")
|
| 62 |
+
|
| 63 |
+
# Load TTS with speaker embeddings (FREE)
|
| 64 |
+
self.tts_processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")
|
| 65 |
+
self.tts_model = SpeechT5ForTextToSpeech.from_pretrained(
|
| 66 |
+
"microsoft/speecht5_tts",
|
| 67 |
+
torch_dtype=torch.float16
|
| 68 |
+
).to(self.device)
|
| 69 |
+
self.vocoder = SpeechT5HifiGan.from_pretrained(
|
| 70 |
+
"microsoft/speecht5_hifigan",
|
| 71 |
+
torch_dtype=torch.float16
|
| 72 |
+
).to(self.device)
|
| 73 |
|
| 74 |
+
# Load speaker embeddings for natural female voice
|
| 75 |
+
embeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")
|
| 76 |
+
# Use female speaker embedding (index 7306 is female)
|
| 77 |
+
self.speaker_embeddings = torch.tensor(embeddings_dataset[7306]["xvector"]).unsqueeze(0).to(self.device)
|
| 78 |
+
print("β
Natural female TTS voice loaded")
|
|
|
|
| 79 |
|
| 80 |
+
# Conversation storage
|
| 81 |
self.conversations = {}
|
| 82 |
+
self.call_active = False
|
| 83 |
+
|
| 84 |
+
def transcribe_with_parakeet(self, audio_path):
|
| 85 |
+
"""Transcribe using Parakeet (6.05% WER)"""
|
| 86 |
try:
|
| 87 |
+
if hasattr(self.asr_model, 'transcribe'):
|
| 88 |
+
transcription = self.asr_model.transcribe([audio_path])
|
| 89 |
+
return transcription[0] if transcription else ""
|
| 90 |
+
else:
|
| 91 |
+
result = self.asr_model(audio_path)
|
| 92 |
+
return result["text"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
except Exception as e:
|
| 94 |
return f"Transcription error: {str(e)}"
|
| 95 |
|
| 96 |
+
def recognize_emotion_from_audio(self, audio_path):
|
| 97 |
+
"""Recognize emotion using superb model"""
|
| 98 |
try:
|
|
|
|
|
|
|
|
|
|
| 99 |
result = self.emotion_model(audio_path)
|
| 100 |
emotion_label = result[0]["label"].lower()
|
| 101 |
|
| 102 |
+
# Map to human emotions
|
| 103 |
+
emotion_map = {
|
| 104 |
+
"ang": "angry", "hap": "happy", "exc": "excited",
|
| 105 |
+
"sad": "sad", "fru": "frustrated", "fea": "fearful",
|
| 106 |
+
"sur": "surprised", "neu": "neutral", "dis": "disgusted"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
}
|
| 108 |
|
| 109 |
+
return emotion_map.get(emotion_label, emotion_label)
|
| 110 |
+
except:
|
|
|
|
|
|
|
| 111 |
return "neutral"
|
| 112 |
|
| 113 |
+
def generate_with_free_llm(self, text, emotion, history):
|
| 114 |
+
"""Generate response using FREE DeepSeek-V3 or Llama"""
|
| 115 |
try:
|
| 116 |
+
# Emotional context prompting
|
| 117 |
+
emotion_prompts = {
|
| 118 |
+
"angry": "I understand you're frustrated. Let me help calm this situation.",
|
| 119 |
+
"sad": "I can hear the sadness in your voice. I'm here to support you.",
|
| 120 |
+
"happy": "Your joy is infectious! I love your positive energy.",
|
| 121 |
+
"excited": "Your enthusiasm is amazing! Tell me more!",
|
| 122 |
+
"fearful": "I sense your concern. Let's work through this together.",
|
| 123 |
+
"surprised": "That sounds unexpected! What happened?",
|
| 124 |
+
"neutral": "I'm listening carefully. Please continue."
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
}
|
| 126 |
|
| 127 |
+
context = f"Previous conversation: {history[-3:] if history else 'None'}"
|
| 128 |
+
emotion_context = emotion_prompts.get(emotion, "I'm here to help.")
|
| 129 |
+
|
| 130 |
+
prompt = f"""You are Maya, an emotionally intelligent AI assistant with natural conversational abilities.
|
| 131 |
+
|
| 132 |
+
{context}
|
| 133 |
+
User emotion detected: {emotion}
|
| 134 |
+
User input: {text}
|
| 135 |
|
| 136 |
+
Respond naturally with emotional intelligence. Keep responses under 100 words and conversational.
|
| 137 |
+
{emotion_context}
|
|
|
|
| 138 |
|
| 139 |
+
Maya:"""
|
| 140 |
|
| 141 |
+
# Tokenize input
|
| 142 |
inputs = self.llm_tokenizer(
|
| 143 |
+
prompt,
|
| 144 |
return_tensors="pt",
|
|
|
|
| 145 |
truncation=True,
|
| 146 |
+
max_length=2048
|
| 147 |
).to(self.device)
|
| 148 |
|
| 149 |
+
# Generate response
|
| 150 |
with torch.no_grad():
|
| 151 |
outputs = self.llm_model.generate(
|
| 152 |
+
**inputs,
|
| 153 |
+
max_new_tokens=100,
|
|
|
|
| 154 |
temperature=0.7,
|
| 155 |
do_sample=True,
|
| 156 |
+
pad_token_id=self.llm_tokenizer.eos_token_id
|
|
|
|
| 157 |
)
|
| 158 |
|
| 159 |
# Decode response
|
|
|
|
| 162 |
skip_special_tokens=True
|
| 163 |
).strip()
|
| 164 |
|
| 165 |
+
# Clean up response
|
| 166 |
if not response or len(response) < 5:
|
| 167 |
return emotion_context
|
| 168 |
|
| 169 |
return response
|
| 170 |
|
| 171 |
except Exception as e:
|
| 172 |
+
return f"{emotion_prompts.get(emotion, 'I understand.')} Could you tell me more about that?"
|
| 173 |
|
| 174 |
+
def synthesize_emotional_speech(self, text, emotion):
|
| 175 |
+
"""Generate emotional speech with natural breathing"""
|
| 176 |
try:
|
| 177 |
if not text or len(text.strip()) == 0:
|
| 178 |
return None
|
| 179 |
+
|
| 180 |
+
# Add emotional markers to text
|
| 181 |
+
emotional_text = text
|
| 182 |
+
if emotion == "happy":
|
| 183 |
+
emotional_text = f"*cheerfully* {text}"
|
| 184 |
+
elif emotion == "sad":
|
| 185 |
+
emotional_text = f"*gently* {text}"
|
| 186 |
+
elif emotion == "excited":
|
| 187 |
+
emotional_text = f"*enthusiastically* {text}"
|
| 188 |
+
elif emotion == "angry":
|
| 189 |
+
emotional_text = f"*calmly* {text}"
|
| 190 |
+
|
| 191 |
# Clean text for TTS
|
| 192 |
+
clean_text = emotional_text.replace("*", "").replace("[", "").replace("]", "").strip()
|
| 193 |
if len(clean_text) > 200:
|
| 194 |
clean_text = clean_text[:200] + "..."
|
| 195 |
|
| 196 |
+
# Add natural breathing pauses for longer text
|
| 197 |
+
if len(clean_text.split()) > 10:
|
| 198 |
+
words = clean_text.split()
|
| 199 |
+
mid_point = len(words) // 2
|
| 200 |
+
clean_text = " ".join(words[:mid_point]) + "... " + " ".join(words[mid_point:])
|
| 201 |
+
|
| 202 |
+
# Process with TTS
|
| 203 |
+
inputs = self.tts_processor(text=clean_text, return_tensors="pt").to(self.device)
|
| 204 |
+
|
| 205 |
+
with torch.no_grad():
|
| 206 |
+
speech = self.tts_model.generate_speech(
|
| 207 |
+
inputs["input_ids"],
|
| 208 |
+
self.speaker_embeddings,
|
| 209 |
+
vocoder=self.vocoder
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
if isinstance(speech, torch.Tensor):
|
| 213 |
+
speech = speech.cpu().numpy()
|
| 214 |
+
|
| 215 |
+
return speech
|
| 216 |
|
| 217 |
except Exception as e:
|
| 218 |
print(f"TTS error: {e}")
|
| 219 |
return None
|
| 220 |
|
| 221 |
+
def start_call(self):
|
| 222 |
+
"""Start a new call session"""
|
| 223 |
+
self.call_active = True
|
| 224 |
+
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?"
|
| 225 |
+
|
| 226 |
+
greeting_audio = self.synthesize_emotional_speech(greeting, "happy")
|
| 227 |
+
|
| 228 |
+
return greeting, (22050, greeting_audio) if greeting_audio is not None else None, "π Call started! Maya is greeting you..."
|
| 229 |
+
|
| 230 |
+
def end_call(self, user_id="default"):
|
| 231 |
+
"""End call and clear conversation"""
|
| 232 |
+
self.call_active = False
|
| 233 |
+
if user_id in self.conversations:
|
| 234 |
+
self.conversations[user_id] = []
|
| 235 |
+
|
| 236 |
+
farewell = "Thank you for chatting with me! It was wonderful talking with you. Have a great day!"
|
| 237 |
+
farewell_audio = self.synthesize_emotional_speech(farewell, "happy")
|
| 238 |
+
|
| 239 |
+
return farewell, (22050, farewell_audio) if farewell_audio is not None else None, "π Call ended. Conversation cleared!"
|
| 240 |
+
|
| 241 |
def process_conversation(self, audio_input, user_id="default"):
|
| 242 |
"""Main conversation processing pipeline"""
|
| 243 |
+
if not self.call_active:
|
| 244 |
+
return "Please start a call first by clicking the 'Start Call' button", None, "No active call"
|
| 245 |
+
|
| 246 |
if audio_input is None:
|
| 247 |
+
return "Please record some audio", None, "No audio input"
|
| 248 |
|
| 249 |
start_time = time.time()
|
| 250 |
|
|
|
|
| 251 |
if user_id not in self.conversations:
|
| 252 |
self.conversations[user_id] = []
|
| 253 |
|
| 254 |
try:
|
| 255 |
+
# Step 1: ASR with Parakeet
|
| 256 |
+
transcription = self.transcribe_with_parakeet(audio_input)
|
| 257 |
|
| 258 |
+
# Step 2: Emotion recognition
|
| 259 |
+
emotion = self.recognize_emotion_from_audio(audio_input)
|
| 260 |
|
| 261 |
+
# Step 3: FREE LLM generation
|
| 262 |
+
response_text = self.generate_with_free_llm(
|
| 263 |
transcription, emotion, self.conversations[user_id]
|
| 264 |
)
|
| 265 |
|
| 266 |
+
# Step 4: Emotional TTS
|
| 267 |
+
response_audio = self.synthesize_emotional_speech(response_text, emotion)
|
| 268 |
|
| 269 |
# Step 5: Update conversation history
|
| 270 |
processing_time = time.time() - start_time
|
|
|
|
| 278 |
|
| 279 |
self.conversations[user_id].append(conversation_entry)
|
| 280 |
|
| 281 |
+
# Keep last 1000 exchanges as specified
|
| 282 |
+
if len(self.conversations[user_id]) > 1000:
|
| 283 |
+
self.conversations[user_id] = self.conversations[user_id][-1000:]
|
| 284 |
|
|
|
|
| 285 |
history = self.format_conversation_history(user_id)
|
| 286 |
|
| 287 |
+
return transcription, (22050, response_audio) if response_audio is not None else None, history
|
| 288 |
|
| 289 |
except Exception as e:
|
| 290 |
+
return f"Processing error: {str(e)}", None, "Error in processing"
|
|
|
|
| 291 |
|
| 292 |
def format_conversation_history(self, user_id):
|
| 293 |
"""Format conversation history for display"""
|
| 294 |
if user_id not in self.conversations or not self.conversations[user_id]:
|
| 295 |
+
return "No conversation history yet."
|
| 296 |
|
| 297 |
history = []
|
| 298 |
+
for i, entry in enumerate(self.conversations[user_id][-10:], 1):
|
| 299 |
history.append(f"**Exchange {i}** ({entry['timestamp']})")
|
| 300 |
history.append(f"π€ **You** ({entry['user_emotion']}): {entry['user_input']}")
|
| 301 |
history.append(f"π€ **Maya**: {entry['ai_response']}")
|
| 302 |
+
history.append(f"β±οΈ *{entry['processing_time']:.2f}s*")
|
| 303 |
history.append("---")
|
| 304 |
|
| 305 |
return "\n".join(history)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 306 |
|
| 307 |
+
# Initialize Maya AI
|
| 308 |
+
print("π Starting Maya AI with FREE models...")
|
| 309 |
+
maya = MayaAI()
|
| 310 |
+
print("β
Maya AI ready with ZERO API costs!")
|
| 311 |
|
| 312 |
+
# Gradio Interface Functions
|
| 313 |
+
def start_call_handler():
|
| 314 |
+
return maya.start_call()
|
|
|
|
|
|
|
|
|
|
| 315 |
|
| 316 |
+
def end_call_handler():
|
| 317 |
+
return maya.end_call()
|
|
|
|
| 318 |
|
| 319 |
+
def process_audio_handler(audio):
|
| 320 |
+
return maya.process_conversation(audio)
|
| 321 |
|
| 322 |
+
# Create Gradio Interface
|
| 323 |
with gr.Blocks(
|
| 324 |
+
title="Maya AI - FREE Sesame AI Killer",
|
| 325 |
theme=gr.themes.Soft(),
|
| 326 |
css="""
|
| 327 |
+
.call-button { background: linear-gradient(45deg, #00d2d3, #01a3a4) !important; }
|
| 328 |
+
.end-button { background: linear-gradient(45deg, #ff3838, #c0392b) !important; }
|
|
|
|
|
|
|
|
|
|
|
|
|
| 329 |
"""
|
| 330 |
) as demo:
|
| 331 |
|
| 332 |
gr.Markdown("""
|
| 333 |
+
# π€ Maya AI - FREE Sesame AI Killer
|
| 334 |
+
*Advanced conversational AI with emotional intelligence - NO API COSTS!*
|
| 335 |
|
| 336 |
+
**FREE Models:** DeepSeek-V3 β’ Parakeet ASR β’ Emotion Recognition β’ Natural Female TTS
|
| 337 |
""")
|
| 338 |
|
| 339 |
with gr.Row():
|
| 340 |
with gr.Column(scale=1):
|
| 341 |
+
gr.Markdown("### π Call Controls")
|
| 342 |
+
|
| 343 |
+
start_call_btn = gr.Button(
|
| 344 |
+
"π Start Call",
|
| 345 |
+
variant="primary",
|
| 346 |
+
size="lg",
|
| 347 |
+
elem_classes=["call-button"]
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
end_call_btn = gr.Button(
|
| 351 |
+
"π End Call",
|
| 352 |
+
variant="stop",
|
| 353 |
+
size="lg",
|
| 354 |
+
elem_classes=["end-button"]
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
gr.Markdown("### ποΈ Voice Input")
|
| 358 |
audio_input = gr.Audio(
|
| 359 |
sources=["microphone"],
|
| 360 |
type="filepath",
|
| 361 |
+
label="Record your message"
|
|
|
|
| 362 |
)
|
| 363 |
|
| 364 |
+
process_btn = gr.Button("π― Process Audio", variant="primary")
|
|
|
|
|
|
|
| 365 |
|
| 366 |
with gr.Column(scale=2):
|
| 367 |
+
gr.Markdown("### π¬ FREE Conversation")
|
| 368 |
+
|
| 369 |
transcription_output = gr.Textbox(
|
| 370 |
+
label="π What you said",
|
| 371 |
lines=2,
|
| 372 |
+
interactive=False
|
|
|
|
| 373 |
)
|
| 374 |
|
| 375 |
audio_output = gr.Audio(
|
| 376 |
+
label="π Maya's Emotional Response",
|
| 377 |
interactive=False,
|
| 378 |
autoplay=True
|
| 379 |
)
|
| 380 |
|
| 381 |
+
conversation_display = gr.Textbox(
|
| 382 |
+
label="π Live Conversation (FREE)",
|
| 383 |
+
lines=15,
|
| 384 |
interactive=False,
|
|
|
|
| 385 |
show_copy_button=True
|
| 386 |
)
|
| 387 |
|
| 388 |
+
# Event Handlers
|
| 389 |
+
start_call_btn.click(
|
| 390 |
+
fn=start_call_handler,
|
| 391 |
+
outputs=[transcription_output, audio_output, conversation_display]
|
|
|
|
| 392 |
)
|
| 393 |
|
| 394 |
+
end_call_btn.click(
|
| 395 |
+
fn=end_call_handler,
|
| 396 |
+
outputs=[transcription_output, audio_output, conversation_display]
|
| 397 |
)
|
| 398 |
|
| 399 |
+
process_btn.click(
|
| 400 |
+
fn=process_audio_handler,
|
|
|
|
| 401 |
inputs=[audio_input],
|
| 402 |
+
outputs=[transcription_output, audio_output, conversation_display]
|
| 403 |
)
|
| 404 |
|
| 405 |
+
audio_input.stop_recording(
|
| 406 |
+
fn=process_audio_handler,
|
| 407 |
+
inputs=[audio_input],
|
| 408 |
+
outputs=[transcription_output, audio_output, conversation_display]
|
| 409 |
)
|
| 410 |
|
|
|
|
| 411 |
if __name__ == "__main__":
|
| 412 |
demo.launch(
|
| 413 |
server_name="0.0.0.0",
|
| 414 |
server_port=7860,
|
| 415 |
+
show_error=True
|
|
|
|
| 416 |
)
|