Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,53 +1,50 @@
|
|
| 1 |
-
|
| 2 |
-
# app.py
|
| 3 |
import gradio as gr
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
from
|
| 7 |
-
|
| 8 |
-
from
|
| 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 |
-
demo.launch()
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import google.generativeai as genai
|
| 3 |
+
import os
|
| 4 |
+
from gtts import gTTS
|
| 5 |
+
import random
|
| 6 |
+
from tempfile import NamedTemporaryFile
|
| 7 |
+
from dotenv import load_dotenv
|
| 8 |
+
|
| 9 |
+
load_dotenv()
|
| 10 |
+
API_KEY = os.getenv("GEMINI_API_KEY") or "YOUR_GEMINI_API_KEY"
|
| 11 |
+
|
| 12 |
+
genai.configure(api_key=API_KEY)
|
| 13 |
+
model = genai.GenerativeModel("gemini-1.5-pro")
|
| 14 |
+
|
| 15 |
+
def predict_emotion():
|
| 16 |
+
return random.choice(["positive", "neutral", "negative"])
|
| 17 |
+
|
| 18 |
+
def chat_with_ai(audio):
|
| 19 |
+
if audio is None:
|
| 20 |
+
return "No audio provided", None
|
| 21 |
+
|
| 22 |
+
import speech_recognition as sr
|
| 23 |
+
recognizer = sr.Recognizer()
|
| 24 |
+
with sr.AudioFile(audio) as source:
|
| 25 |
+
audio_data = recognizer.record(source)
|
| 26 |
+
try:
|
| 27 |
+
text = recognizer.recognize_google(audio_data)
|
| 28 |
+
except sr.UnknownValueError:
|
| 29 |
+
return "Sorry, I couldn't understand the audio.", None
|
| 30 |
+
|
| 31 |
+
emotion = predict_emotion()
|
| 32 |
+
prompt = f"The user is feeling {emotion}. Respond appropriately.\nUser said: {text}"
|
| 33 |
+
response = model.generate_content(prompt).text
|
| 34 |
+
|
| 35 |
+
# Convert response to audio
|
| 36 |
+
tts = gTTS(text=response, lang='en', tld='com.ng')
|
| 37 |
+
temp_audio = NamedTemporaryFile(delete=False, suffix=".mp3")
|
| 38 |
+
tts.save(temp_audio.name)
|
| 39 |
+
|
| 40 |
+
return response, temp_audio.name
|
| 41 |
+
|
| 42 |
+
iface = gr.Interface(
|
| 43 |
+
fn=chat_with_ai,
|
| 44 |
+
inputs=gr.Audio(source="microphone", type="filepath", label="Speak"),
|
| 45 |
+
outputs=[gr.Textbox(label="AI Response"), gr.Audio(label="AI Voice")],
|
| 46 |
+
title="Voice-Based AI Assistant",
|
| 47 |
+
description="Speak to the AI and get an emotional, spoken response."
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
iface.launch()
|
|
|