EncourageAI / app.py
SatyamSinghal's picture
Update app.py
5431955 verified
import gradio as gr
import openai
import os
# Set OpenAI API Key
openai.api_key = os.getenv("GROQ_API_KEY")
openai.api_base = "https://api.groq.com/openai/v1"
# Dictionary to store categorized chats
saved_chats = {
"Stress Management": [],
"Career Advice": [],
"General": [],
"Suggestions": []
}
# Function to get response from GROQ API
def get_groq_response(message):
try:
response = openai.ChatCompletion.create(
model="llama-3.1-70b-versatile",
messages=[
{"role": "user", "content": message},
{"role": "system", "content": "You will talk like a Motivational Speaker to help people come out of stress."}
]
)
return response.choices[0].message["content"]
except Exception as e:
return f"Error: {str(e)}"
# Function to classify messages based on the topic
def classify_message(user_message, bot_response):
if "stress" in user_message.lower():
saved_chats["Stress Management"].append((user_message, bot_response))
return "Stress Management"
elif "career" in user_message.lower():
saved_chats["Career Advice"].append((user_message, bot_response))
return "Career Advice"
elif "suggestions" in user_message.lower():
saved_chats["Suggestions"].append((user_message, bot_response))
return "Suggestions"
else:
saved_chats["General"].append((user_message, bot_response))
return "General"
# Chatbot function
def chatbot(user_input, history=[]):
bot_response = get_groq_response(user_input)
topic = classify_message(user_input, bot_response)
history.append((f"({topic}) You: {user_input}", f"Motivator Bot: {bot_response}"))
return history, saved_chats
# Custom HTML, CSS, and JavaScript
custom_html = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Motivational Chatbot</title>
<style>
body {
font-family: 'Poppins', sans-serif;
background: #121212;
color: #f3f3f3;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
width: 90%;
max-width: 800px;
background: #1e1e1e;
border-radius: 15px;
box-shadow: 0px 10px 30px rgba(0, 0, 0, 0.5);
overflow: hidden;
display: flex;
flex-direction: column;
}
header {
background: #282828;
padding: 20px;
text-align: center;
color: #ffffff;
border-bottom: 2px solid #ff6a95;
}
header h1 {
margin: 0;
font-size: 1.8rem;
}
header p {
margin: 5px 0 0;
font-size: 1rem;
color: #cccccc;
}
main {
flex: 1;
padding: 20px;
display: flex;
flex-direction: column;
}
.chat-container {
display: flex;
flex-direction: column;
height: 100%;
}
#chat-output {
flex: 1;
overflow-y: auto;
background: #212121;
border-radius: 10px;
padding: 10px;
margin-bottom: 10px;
box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.5);
}
.chat-input {
display: flex;
gap: 10px;
}
textarea {
flex: 1;
padding: 10px;
border-radius: 5px;
border: none;
background: #333;
color: #fff;
resize: none;
font-size: 1rem;
}
textarea:focus {
outline: none;
box -shadow: 0 0 5px #ff6a95;
}
button {
padding: 10px 20px;
background: linear-gradient(45deg, #ff6a95, #ff4b81);
border: none;
border-radius: 5px;
color: #fff;
font-weight: bold;
cursor: pointer;
transition: background 0.3s, transform 0.3s;
}
button:hover {
background: linear-gradient(45deg, #ff4b81, #ff6a95);
transform: scale(1.05);
}
footer {
background: #282828;
text-align: center;
padding: 10px;
color: #999;
font-size: 0.9rem;
border-top: 2px solid #ff6a95;
}
</style>
</head>
<body>
<div class="container">
<header>
<h1>✨ Motivational Chatbot ✨</h1>
<p>Your personal motivational speaker!</p>
</header>
<main>
<div class="chat-container">
<div id="chat-output"></div>
<div class="chat-input">
<textarea id="user-input" placeholder="Type your message here..."></textarea>
<button id="send-btn">Send</button>
</div>
</div>
</main>
<footer>
<p>Developed with ❤️ using OpenAI APIs</p>
</footer>
</div>
<script>
document.getElementById("send-btn").addEventListener("click", async () => {
const userInput = document.getElementById("user-input").value.trim();
if (!userInput) return;
// Display user input
const chatOutput = document.getElementById("chat-output");
const userMessage = `<div class="user-message"><strong>You:</strong> ${userInput}</div>`;
chatOutput.innerHTML += userMessage;
// Call backend
const response = await fetch("/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ user_input: userInput })
});
const botResponse = await response.json();
// Display bot response
const botMessage = `<div class="bot-message"><strong>Bot:</strong> ${botResponse}</div>`;
chatOutput.innerHTML += botMessage;
// Clear input
document.getElementById("user-input").value = "";
chatOutput.scrollTop = chatOutput.scrollHeight;
});
</script>
</body>
</html>
"""
# Launch Gradio interface with custom frontend
interface = gr.Interface(
fn=chatbot,
inputs=[gr.Textbox(lines=2, label="Your Message"), gr.State()],
outputs=[gr.JSON(), gr.State()],
live=True
)
app = gr.HTML(custom_html)
interface.launch(share=True)