poushali369's picture
Update app.py
04fda8a verified
import gradio as gr
import os
from huggingface_hub import InferenceClient
# ---------------- CONFIG ----------------
HF_TOKEN = os.environ.get("HF_TOKEN")
client = InferenceClient(
provider="hf-inference",
api_key=HF_TOKEN,
)
print("HF TOKEN:", HF_TOKEN)
# ---------------- MOOD DETECTION ----------------
def detect_mood(text):
text = text.lower()
if any(w in text for w in ["sad", "down", "upset"]):
return "sad"
elif any(w in text for w in ["bored", "nothing to do"]):
return "bored"
elif any(w in text for w in ["stress", "tired", "overwhelmed"]):
return "stressed"
elif any(w in text for w in ["happy", "excited", "great"]):
return "happy"
else:
return "neutral"
# ---------------- SUGGESTION ----------------
def suggest_activity(mood):
suggestions = {
"bored": "Try a quick 5-minute coding challenge.",
"sad": "Go for a short walk or listen to music.",
"stressed": "Take 5 deep breaths and focus on one small task.",
"happy": "Channel this energy into something exciting!",
"neutral": "Try organizing a small task or learning something new."
}
return suggestions.get(mood, suggestions["neutral"])
# ---------------- PERSONALITY ----------------
def apply_personality(text, personality):
if personality == "Motivational Coach":
return f"💪 You got this! {text}"
elif personality == "Sarcastic Friend":
return f"😏 Oh wow, emotions again. Anyway—{text}"
elif personality == "Zen Monk":
return f"🧘 Peace comes from within. {text}"
return text
# ---------------- MODEL CALL ----------------
def query_model(prompt):
try:
response = client.chat.completions.create(
model="bartowski/Qwen2.5-7B-Instruct-GGUF",
messages=[
{"role": "user", "content": prompt}
],
max_tokens=60,
temperature=0.7,
)
return response.choices[0].message["content"]
except Exception as e:
print("MODEL ERROR:", str(e))
return "⚠️ Model is temporarily unavailable. Please try again."
# ---------------- CHAT FUNCTION ----------------
def respond(message, history, personality):
mood = detect_mood(message)
activity = suggest_activity(mood)
prompt = f"""
You are a friendly and helpful assistant.
User mood: {mood}
User message: {message}
Respond naturally like a human in 1-2 sentences.
"""
model_reply = query_model(prompt)
model_reply = apply_personality(model_reply, personality)
final_reply = f"{model_reply}\n\n👉 Suggestion: {activity}"
history = history or []
history.append({"role": "user", "content": message})
history.append({"role": "assistant", "content": final_reply})
return history
# ---------------- UI ----------------
with gr.Blocks() as demo:
gr.Markdown("# 🧠 Mood-Based Life Assistant")
personality = gr.Dropdown(
["Motivational Coach", "Sarcastic Friend", "Zen Monk"],
value="Motivational Coach",
label="Choose Personality"
)
chatbot = gr.Chatbot(type="messages")
msg = gr.Textbox(placeholder="How are you feeling?")
msg.submit(respond, [msg, chatbot, personality], [chatbot])
demo.launch()