Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,64 +1,161 @@
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
import gradio as gr
|
| 3 |
+
import requests
|
| 4 |
+
import json
|
| 5 |
+
import speech_recognition as sr
|
| 6 |
+
from tempfile import NamedTemporaryFile
|
| 7 |
+
import pyttsx3
|
| 8 |
+
import logging
|
| 9 |
+
import time
|
| 10 |
+
|
| 11 |
+
# Set up logging
|
| 12 |
+
logging.basicConfig(level=logging.INFO)
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
# Groq API setup
|
| 16 |
+
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "your_key_here")
|
| 17 |
+
GROQ_MODEL = os.getenv("GROQ_MODEL", "mixtral-8x7b-32768")
|
| 18 |
+
GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
|
| 19 |
+
|
| 20 |
+
headers = {
|
| 21 |
+
"Authorization": f"Bearer {GROQ_API_KEY}",
|
| 22 |
+
"Content-Type": "application/json"
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
# Emotion options
|
| 26 |
+
emotion_options = {
|
| 27 |
+
"neutral": "Neutral or balanced mood",
|
| 28 |
+
"positive": "Generally positive or optimistic",
|
| 29 |
+
"happy": "Feeling joy or happiness",
|
| 30 |
+
"excited": "Feeling enthusiastic or energetic",
|
| 31 |
+
"sad": "Feeling down or unhappy",
|
| 32 |
+
"angry": "Feeling frustrated or irritated",
|
| 33 |
+
"negative": "Generally negative or pessimistic",
|
| 34 |
+
"anxious": "Feeling worried or nervous"
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
# Initialize conversation history
|
| 38 |
+
conversation_history = []
|
| 39 |
+
|
| 40 |
+
# Transcribe audio to text
|
| 41 |
+
def transcribe_audio(audio_path):
|
| 42 |
+
recognizer = sr.Recognizer()
|
| 43 |
+
try:
|
| 44 |
+
with sr.AudioFile(audio_path) as source:
|
| 45 |
+
audio_data = recognizer.record(source)
|
| 46 |
+
transcription = recognizer.recognize_google(audio_data)
|
| 47 |
+
return transcription
|
| 48 |
+
except Exception as e:
|
| 49 |
+
logger.error(f"Audio transcription failed: {e}")
|
| 50 |
+
return ""
|
| 51 |
+
|
| 52 |
+
# Get Groq response
|
| 53 |
+
def get_groq_response(prompt, history):
|
| 54 |
+
messages = [{"role": "system", "content": prompt}]
|
| 55 |
+
for message in history:
|
| 56 |
+
if message.startswith("User: "):
|
| 57 |
+
messages.append({"role": "user", "content": message[6:]})
|
| 58 |
+
elif message.startswith("AI: "):
|
| 59 |
+
messages.append({"role": "assistant", "content": message[4:]})
|
| 60 |
+
data = {
|
| 61 |
+
"model": GROQ_MODEL,
|
| 62 |
+
"messages": messages,
|
| 63 |
+
"temperature": 0.7,
|
| 64 |
+
"max_tokens": 1024
|
| 65 |
+
}
|
| 66 |
+
try:
|
| 67 |
+
response = requests.post(GROQ_API_URL, headers=headers, json=data)
|
| 68 |
+
return response.json()["choices"][0]["message"]["content"]
|
| 69 |
+
except Exception as e:
|
| 70 |
+
logger.error(f"Groq API error: {e}")
|
| 71 |
+
return "Error contacting AI."
|
| 72 |
+
|
| 73 |
+
# Generate speech using pyttsx3 and save to WAV
|
| 74 |
+
def generate_speech(text):
|
| 75 |
+
try:
|
| 76 |
+
tts = pyttsx3.init()
|
| 77 |
+
temp_file = NamedTemporaryFile(delete=False, suffix=".wav")
|
| 78 |
+
temp_path = temp_file.name
|
| 79 |
+
tts.save_to_file(text, temp_path)
|
| 80 |
+
tts.runAndWait()
|
| 81 |
+
time.sleep(1) # Ensure file is saved
|
| 82 |
+
return temp_path
|
| 83 |
+
except Exception as e:
|
| 84 |
+
logger.error(f"TTS error: {e}")
|
| 85 |
+
return None
|
| 86 |
+
|
| 87 |
+
# Main interaction
|
| 88 |
+
def chat_with_ai(audio, text_input, emotion, history):
|
| 89 |
+
global conversation_history
|
| 90 |
+
user_text = text_input or ""
|
| 91 |
+
if audio:
|
| 92 |
+
transcription = transcribe_audio(audio)
|
| 93 |
+
if transcription:
|
| 94 |
+
user_text = transcription
|
| 95 |
+
else:
|
| 96 |
+
return "Couldn't understand the audio.", None, history
|
| 97 |
+
if not user_text.strip():
|
| 98 |
+
return "No input provided.", None, history
|
| 99 |
+
|
| 100 |
+
conversation_history.append(f"User: {user_text}")
|
| 101 |
+
recent_messages = conversation_history[-20:]
|
| 102 |
+
|
| 103 |
+
prompt = f"""You are an empathetic AI assistant. The user is feeling {emotion} ({emotion_options[emotion]}). Respond supportively."""
|
| 104 |
+
ai_response = get_groq_response(prompt, recent_messages)
|
| 105 |
+
conversation_history.append(f"AI: {ai_response}")
|
| 106 |
+
|
| 107 |
+
audio_path = generate_speech(ai_response)
|
| 108 |
+
return ai_response, audio_path, history + [[user_text, ai_response]]
|
| 109 |
+
|
| 110 |
+
def clear_conversation():
|
| 111 |
+
global conversation_history
|
| 112 |
+
conversation_history = []
|
| 113 |
+
return [], None, None, "Conversation cleared."
|
| 114 |
+
|
| 115 |
+
# Gradio Interface
|
| 116 |
+
iface = gr.Blocks()
|
| 117 |
+
|
| 118 |
+
with iface:
|
| 119 |
+
gr.Markdown("# Mind AID AI Assistant")
|
| 120 |
+
gr.Markdown("Talk or type to the AI assistant. Your emotional state helps tailor the response.")
|
| 121 |
+
|
| 122 |
+
with gr.Row():
|
| 123 |
+
with gr.Column(scale=3):
|
| 124 |
+
emotion = gr.Dropdown(label="Your emotion?", choices=list(emotion_options.keys()), value="neutral")
|
| 125 |
+
emotion_description = gr.Markdown("**Current mood:** Neutral")
|
| 126 |
+
def update_emotion_desc(em):
|
| 127 |
+
return f"**Current mood:** {emotion_options.get(em, 'Unknown')}"
|
| 128 |
+
emotion.change(fn=update_emotion_desc, inputs=[emotion], outputs=[emotion_description])
|
| 129 |
+
with gr.Column(scale=1):
|
| 130 |
+
clear_btn = gr.Button("Clear Conversation")
|
| 131 |
+
status = gr.Textbox(label="Status")
|
| 132 |
+
|
| 133 |
+
chat_history = gr.Chatbot(label="Chat History", height=300)
|
| 134 |
+
|
| 135 |
+
with gr.Row():
|
| 136 |
+
text_input = gr.Textbox(label="Type your message", lines=2)
|
| 137 |
+
audio_input = gr.Audio(label="Or speak", type="filepath", sources=["microphone"])
|
| 138 |
+
|
| 139 |
+
output_audio = gr.Audio(label="AI Voice Response")
|
| 140 |
+
submit_btn = gr.Button("Send", variant="primary")
|
| 141 |
+
|
| 142 |
+
submit_btn.click(
|
| 143 |
+
fn=chat_with_ai,
|
| 144 |
+
inputs=[audio_input, text_input, emotion, chat_history],
|
| 145 |
+
outputs=[status, output_audio, chat_history]
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
text_input.submit(
|
| 149 |
+
fn=chat_with_ai,
|
| 150 |
+
inputs=[audio_input, text_input, emotion, chat_history],
|
| 151 |
+
outputs=[status, output_audio, chat_history]
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
clear_btn.click(
|
| 155 |
+
fn=clear_conversation,
|
| 156 |
+
inputs=[],
|
| 157 |
+
outputs=[chat_history, audio_input, text_input, status]
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
# Launch (MUST be outside if __name__ == "__main__")
|
| 161 |
+
iface.launch()
|