pbichpur commited on
Commit
5b99e1d
·
verified ·
1 Parent(s): bac72fa

Upload 4 files

Browse files
Files changed (4) hide show
  1. README.md +95 -0
  2. app.py +109 -0
  3. ppo_mental_health_model_expanded.zip +3 -0
  4. requirements.txt +5 -0
README.md ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: PPO Mood Chatbot
3
+ emoji: 🧠
4
+ colorFrom: blue
5
+ colorTo: green
6
+ sdk: gradio
7
+ sdk_version: 5.25.2
8
+ app_file: app.py
9
+ pinned: true
10
+ ---
11
+
12
+ # 🧠 Mood Support Chatbot with PPO & GPT-3.5
13
+
14
+ This project is an AI-powered mental health support chatbot that infers a user's emotional state from natural language input and provides personalized wellness suggestions. It combines:
15
+
16
+ - **GPT-3.5** for mood detection from conversation
17
+ - **PPO (Proximal Policy Optimization)** for reinforcement-learned action selection
18
+ - **Gradio** for an interactive web interface
19
+ - **Hugging Face Spaces** for free public hosting
20
+
21
+ ---
22
+
23
+ ## 🌟 Features
24
+ - **Multi-turn Conversation Context**: Mood detection takes the recent chat history into account
25
+ - **Visual Mood Tracking**: A mood trend chart tracks how the user's state evolves
26
+ - **Personalized Suggestion Memory**: Keeps count of which strategies are offered per session
27
+ - **Custom PPO Policy**: Trained in a simulated environment with an expanded action space of 8 wellness suggestions
28
+ - **Deployment Ready**: Packaged and hosted on Hugging Face Spaces with OpenAI key stored securely
29
+
30
+ ---
31
+
32
+ ## 🧩 Action Space
33
+ The agent selects from the following actions:
34
+
35
+ - meditation 🧘
36
+ - talk_therapy 💬
37
+ - journal_prompt 📝
38
+ - breathing_ex 💨
39
+ - video 🎥
40
+ - nature_walk 🌿
41
+ - soothing_music 🎶
42
+ - gratitude_exercise 🙏
43
+
44
+ ---
45
+
46
+ ## 🛠 Training
47
+ The PPO agent was trained using `stable-baselines3` in a custom Gymnasium environment. The reward is based on simulated mood improvements, and training ends when the mood exceeds a threshold (e.g., 0.95).
48
+
49
+ **Training script includes:**
50
+ - SimulatedUser with mood boost logic
51
+ - MoodSupportEnv with gym-style `reset()` and `step()`
52
+ - PPO training loop with model save + zip
53
+
54
+ ---
55
+
56
+ ## 🧪 How to Test
57
+ Use emotional prompts like:
58
+
59
+ - "I'm so tired and I can't stop overthinking."
60
+ - "I'm feeling hopeful but a bit nervous."
61
+ - "I don't feel like doing anything."
62
+
63
+ Or test edge cases like:
64
+
65
+ - Extremely long emotional rants
66
+ - Repeated vague responses ("I don't know")
67
+ - Rapid mood swings over turns
68
+
69
+ ---
70
+
71
+ ## 🚀 Deployment on Hugging Face Spaces
72
+ This project runs on Hugging Face using:
73
+ - `app.py`: Main chatbot logic and UI
74
+ - `ppo_mental_health_model_expanded.zip`: Trained PPO model
75
+ - `requirements.txt`: Dependency list
76
+ - `OPENAI_API_KEY`: Set as a Hugging Face Secret
77
+
78
+ ---
79
+
80
+ ## 🧠 Future Enhancements
81
+ - Mood-aware GPT text responses
82
+ - Feedback buttons (👍/👎) to improve the agent
83
+ - Session export or user login
84
+ - Local transformer fallback (offline mode)
85
+ - Mood milestone alerts ("You've improved by 40%!")
86
+
87
+ ---
88
+
89
+ ## 👤 Author
90
+ Built and maintained by Chirasmayee B and Pallavi Bichupriya.
91
+
92
+ ---
93
+
94
+ ## 📄 License
95
+ MIT License
app.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import openai
4
+ import os
5
+ import zipfile
6
+ from stable_baselines3 import PPO
7
+ import matplotlib.pyplot as plt
8
+ import io
9
+ import base64
10
+
11
+ # Load OpenAI API key from environment
12
+ openai.api_key = os.getenv("OPENAI_API_KEY")
13
+
14
+ # Unzip PPO model only if not already extracted
15
+ if not os.path.exists("ppo_mental_health_model_expanded"):
16
+ with zipfile.ZipFile("ppo_mental_health_model_expanded.zip", "r") as zip_ref:
17
+ zip_ref.extractall(".")
18
+
19
+ # Load PPO model
20
+ ppo_model = PPO.load("ppo_mental_health_model_expanded")
21
+
22
+ # PPO environment-related mappings
23
+ ACTIONS = ['meditation', 'talk_therapy', 'journal_prompt', 'breathing_ex', 'video', 'nature_walk', 'soothing_music', 'gratitude_exercise']
24
+ INDEX_TO_ACTION = {i: a for i, a in enumerate(ACTIONS)}
25
+ suggestion_map = {
26
+ 'meditation': "Would you like to try a short meditation exercise? 🧘",
27
+ 'talk_therapy': "Talking to someone might help. Want to explore talk therapy?",
28
+ 'journal_prompt': "Journaling might help you express your thoughts. 📝",
29
+ 'breathing_ex': "Try a calming breathing exercise. Inhale deeply... 💨",
30
+ 'video': "Here’s a calming video that might lift your mood. 🎥",
31
+ 'nature_walk': "How about a short walk in nature? A little fresh air might help. 🌿",
32
+ 'soothing_music': "Listening to soothing music might help you relax. 🎶",
33
+ 'gratitude_exercise': "Let's try a quick gratitude exercise. Name one thing you're thankful for. 🙏"
34
+ }
35
+
36
+ # Mood scoring
37
+ mood_score_map = {
38
+ 'positive': 0.8, 'negative': 0.3,
39
+ 'joy': 0.9, 'love': 0.8, 'surprise': 0.6, 'neutral': 0.5,
40
+ 'sadness': 0.3, 'fear': 0.2, 'anger': 0.2, 'anxiety': 0.3,
41
+ 'disgust': 0.2, 'guilt': 0.2, 'hope': 0.7, 'calm': 0.75
42
+ }
43
+
44
+ # Session state
45
+ chat_history = []
46
+ mood_scores = []
47
+ suggestion_memory = {action: 0 for action in ACTIONS}
48
+
49
+ # Mood inference using OpenAI (with context)
50
+ def get_mood_from_openai(user_input, history):
51
+ chat_context = "\n".join([f"User: {msg}" for msg in history[-3:]])
52
+ prompt = f"""You are a mental health assistant. Analyze the user's emotional state from their recent conversation and return one mood word from:
53
+ ["joy", "sadness", "anger", "fear", "anxiety", "guilt", "neutral", "love", "surprise", "disgust", "hope", "calm", "positive", "negative"].
54
+ Conversation:
55
+ {chat_context}
56
+ User: {user_input}
57
+ Mood:"""
58
+ response = openai.chat.completions.create(
59
+ model="gpt-3.5-turbo",
60
+ messages=[{"role": "user", "content": prompt}],
61
+ temperature=0.2,
62
+ max_tokens=5,
63
+ timeout=20
64
+ )
65
+ return response.choices[0].message.content.strip().lower()
66
+
67
+ # Mood trend plot
68
+ def plot_mood_trend():
69
+ fig, ax = plt.subplots()
70
+ ax.plot(range(1, len(mood_scores)+1), mood_scores, marker='o')
71
+ ax.set_title("Mood Score Over Time")
72
+ ax.set_xlabel("Turn")
73
+ ax.set_ylabel("Mood Score")
74
+ ax.set_ylim(0, 1)
75
+ filepath = "mood_trend.png"
76
+ plt.savefig(filepath)
77
+ plt.close(fig)
78
+ return filepath
79
+
80
+ # Chatbot response with tracking
81
+ def chatbot_response(user_input, history=None):
82
+ try:
83
+ chat_history.append(user_input)
84
+ mood_label = get_mood_from_openai(user_input, chat_history)
85
+ mood_score = mood_score_map.get(mood_label, 0.4)
86
+ mood_scores.append(mood_score)
87
+
88
+ obs = np.array([mood_score], dtype=np.float32).reshape(1, -1)
89
+ action, _ = ppo_model.predict(obs)
90
+ suggestion = INDEX_TO_ACTION[int(action)]
91
+ suggestion_memory[suggestion] += 1
92
+ response = suggestion_map[suggestion]
93
+
94
+ chat_output = f"🤖 I sense you might be feeling *{mood_label}*. {response}"
95
+ return chat_output, plot_mood_trend()
96
+
97
+ except Exception as e:
98
+ import traceback
99
+ traceback.print_exc()
100
+ return f"❌ Error: {str(e)}", None
101
+
102
+ # Launch Gradio interface
103
+ gr.Interface(
104
+ fn=chatbot_response,
105
+ inputs=gr.Textbox(lines=2, placeholder="How are you feeling today?"),
106
+ outputs=[gr.Textbox(label="Chatbot Response"), gr.Image(label="Mood Trend")],
107
+ title="Mental Health Support Bot",
108
+ description="This chatbot tracks mood over time, remembers your context, and suggests helpful wellness strategies."
109
+ ).launch()
ppo_mental_health_model_expanded.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:01c3ca64a9811778df1754325b4fde3b9b43588faf676ec366ff7e05d88627bd
3
+ size 142140
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ openai
2
+ gradio
3
+ stable-baselines3
4
+ numpy
5
+ gymnasium