| import gradio as gr
|
| import numpy as np
|
| import openai
|
| import os
|
| import zipfile
|
| from stable_baselines3 import PPO
|
| import matplotlib.pyplot as plt
|
| import io
|
| import base64
|
|
|
|
|
| openai.api_key = os.getenv("OPENAI_API_KEY")
|
|
|
|
|
| if not os.path.exists("ppo_mental_health_model_expanded"):
|
| with zipfile.ZipFile("ppo_mental_health_model_expanded.zip", "r") as zip_ref:
|
| zip_ref.extractall(".")
|
|
|
|
|
| ppo_model = PPO.load("ppo_mental_health_model_expanded")
|
|
|
|
|
| ACTIONS = ['meditation', 'talk_therapy', 'journal_prompt', 'breathing_ex', 'video', 'nature_walk', 'soothing_music', 'gratitude_exercise']
|
| INDEX_TO_ACTION = {i: a for i, a in enumerate(ACTIONS)}
|
| suggestion_map = {
|
| 'meditation': "Would you like to try a short meditation exercise? π§",
|
| 'talk_therapy': "Talking to someone might help. Want to explore talk therapy?",
|
| 'journal_prompt': "Journaling might help you express your thoughts. π",
|
| 'breathing_ex': "Try a calming breathing exercise. Inhale deeply... π¨",
|
| 'video': "Hereβs a calming video that might lift your mood. π₯",
|
| 'nature_walk': "How about a short walk in nature? A little fresh air might help. πΏ",
|
| 'soothing_music': "Listening to soothing music might help you relax. πΆ",
|
| 'gratitude_exercise': "Let's try a quick gratitude exercise. Name one thing you're thankful for. π"
|
| }
|
|
|
|
|
| mood_score_map = {
|
| 'positive': 0.8, 'negative': 0.3,
|
| 'joy': 0.9, 'love': 0.8, 'surprise': 0.6, 'neutral': 0.5,
|
| 'sadness': 0.3, 'fear': 0.2, 'anger': 0.2, 'anxiety': 0.3,
|
| 'disgust': 0.2, 'guilt': 0.2, 'hope': 0.7, 'calm': 0.75
|
| }
|
|
|
|
|
| chat_history = []
|
| mood_scores = []
|
| suggestion_memory = {action: 0 for action in ACTIONS}
|
|
|
|
|
| def get_mood_from_openai(user_input, history):
|
| chat_context = "\n".join([f"User: {msg}" for msg in history[-3:]])
|
| prompt = f"""You are a mental health assistant. Analyze the user's emotional state from their recent conversation and return one mood word from:
|
| ["joy", "sadness", "anger", "fear", "anxiety", "guilt", "neutral", "love", "surprise", "disgust", "hope", "calm", "positive", "negative"].
|
| Conversation:
|
| {chat_context}
|
| User: {user_input}
|
| Mood:"""
|
| response = openai.chat.completions.create(
|
| model="gpt-3.5-turbo",
|
| messages=[{"role": "user", "content": prompt}],
|
| temperature=0.2,
|
| max_tokens=5,
|
| timeout=20
|
| )
|
| return response.choices[0].message.content.strip().lower()
|
|
|
|
|
| def plot_mood_trend():
|
| fig, ax = plt.subplots()
|
| ax.plot(range(1, len(mood_scores)+1), mood_scores, marker='o')
|
| ax.set_title("Mood Score Over Time")
|
| ax.set_xlabel("Turn")
|
| ax.set_ylabel("Mood Score")
|
| ax.set_ylim(0, 1)
|
| filepath = "mood_trend.png"
|
| plt.savefig(filepath)
|
| plt.close(fig)
|
| return filepath
|
|
|
|
|
| def chatbot_response(user_input, history=None):
|
| try:
|
| chat_history.append(user_input)
|
| mood_label = get_mood_from_openai(user_input, chat_history)
|
| mood_score = mood_score_map.get(mood_label, 0.4)
|
| mood_scores.append(mood_score)
|
|
|
| obs = np.array([mood_score], dtype=np.float32).reshape(1, -1)
|
| action, _ = ppo_model.predict(obs)
|
| suggestion = INDEX_TO_ACTION[int(action)]
|
| suggestion_memory[suggestion] += 1
|
| response = suggestion_map[suggestion]
|
|
|
| chat_output = f"π€ I sense you might be feeling *{mood_label}*. {response}"
|
| return chat_output, plot_mood_trend()
|
|
|
| except Exception as e:
|
| import traceback
|
| traceback.print_exc()
|
| return f"β Error: {str(e)}", None
|
|
|
|
|
| gr.Interface(
|
| fn=chatbot_response,
|
| inputs=gr.Textbox(lines=2, placeholder="How are you feeling today?"),
|
| outputs=[gr.Textbox(label="Chatbot Response"), gr.Image(label="Mood Trend")],
|
| title="Mental Health Support Bot",
|
| description="This chatbot tracks mood over time, remembers your context, and suggests helpful wellness strategies."
|
| ).launch()
|
|
|