-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
207 lines (179 loc) · 8.23 KB
/
Copy pathapp.py
File metadata and controls
207 lines (179 loc) · 8.23 KB
1
2
3
4
5
6
7
8
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import streamlit as st
import cohere
import random
from datetime import datetime
import pandas as pd
import os
from collections import Counter
# --- Config ---
st.set_page_config(page_title="CalmMind AI", page_icon="🧘", layout="wide")
# --- Theme Colors ---
PRIMARY = "#00d0b3"
BG = "#1e1e2f"
TEXT = "#ffffff"
CONTAINER_BG = "#2c2c3c"
# --- Custom CSS ---
st.markdown(f"""
<style>
html, body, .main {{
background-color: {BG};
color: {TEXT};
font-family: 'Segoe UI', sans-serif;
}}
h1, h2, h3 {{
color: {PRIMARY};
}}
.quote-box, .activity-box, .story-box, .highlight-box {{
background-color: {CONTAINER_BG};
padding: 20px;
border-radius: 12px;
margin-bottom: 20px;
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
}}
.big-text {{
font-size: 28px;
font-weight: bold;
color: {PRIMARY};
text-align: center;
margin-top: 10px;
}}
</style>
""", unsafe_allow_html=True)
# --- App Title ---
st.markdown("<h1 style='text-align:center;'>🧘 CalmMind AI – Your Personal Emotional Wellness Guide</h1>", unsafe_allow_html=True)
st.markdown("### Track your mood, receive support, and discover peace.")
# --- Load API Key ---
co = cohere.Client(st.secrets["api_keys"]["cohere"])
# --- Constants ---
MOODS = ["😌 Calm", "😐 Meh", "😫 Stressed", "😭 Overwhelmed"]
SPIRITUAL_BOOKS = ["None", "Bhagavad Gita", "Bible", "Quran", "Buddhist Texts"]
DATA_FILE = "stress_logs.csv"
# --- Daily Affirmation ---
affirmations = [
"You are doing the best you can. And that’s enough.",
"Every breath you take is a step toward peace.",
"You are stronger than you think.",
"Progress, not perfection.",
"You are loved, even when it feels quiet.",
"There’s peace waiting on the other side of this moment.",
"It’s okay to rest. That’s where healing happens.",
"Storms pass. You will find the sun again.",
]
random.seed(datetime.now().day)
today_affirmation = random.choice(affirmations)
st.info(f"🌞 *Affirmation of the Day:* **{today_affirmation}**")
# --- Input Fields ---
col1, col2 = st.columns(2)
with col1:
mood = st.radio("🧠 How are you feeling today?", MOODS, horizontal=True)
with col2:
spiritual_choice = st.selectbox("📖 Want support from spiritual books?", SPIRITUAL_BOOKS)
user_input = st.text_area("📝 Describe your current thoughts or stress:", height=150)
journal = st.text_area("📓 Optional journal space:", height=100)
# --- Stress Classifier ---
def classify_stress(text):
prompt = f"""Classify this into low, medium, or high stress.
"I'm a little anxious but mostly okay" → low
"Deadlines are crushing me" → medium
"I feel mentally drained and hopeless" → high
"{text}" →"""
res = co.generate(model="command-r-plus", prompt=prompt, max_tokens=1, temperature=0)
level = res.generations[0].text.strip().lower()
return level if level in ["low", "medium", "high"] else "medium"
# --- Quote Generator ---
def generate_quotes(level):
prompts = {
"low": "Give 2 calming quotes for someone mildly stressed.",
"medium": "Give 2 strong motivational quotes for someone overwhelmed.",
"high": "Give 2 powerful quotes for emotional burnout and sadness."
}
res = co.generate(model="command-r-plus", prompt=prompts[level], max_tokens=100, temperature=0.9)
return [q.strip("- ") for q in res.generations[0].text.strip().split("\n") if q.strip()]
# --- Activities ---
def suggest_activities(level):
if level == "low":
return [("🌳 Go outside", "Fresh air and movement help clear your mind."),
("🎧 Calm music", "Gentle rhythms reduce cortisol levels.")]
elif level == "medium":
return [("🧘 5-min meditation", "Brings awareness back to the present."),
("🗂️ Break your tasks", "Reduces overwhelm by managing focus.")]
else:
return [("📞 Talk to someone", "Support systems are vital for mental health."),
("✍️ Write your emotions", "Journaling provides safe expression.")]
# --- Success Story ---
def generate_story(user_input, book):
prompt = f"""The user said: "{user_input}".
Write a success story showing emotional healing. Use hope and emotional strength. Include a relevant message or reference from {book if book != 'None' else 'a wise person'} if appropriate."""
res = co.generate(model="command-r-plus", prompt=prompt, max_tokens=300, temperature=0.8)
return res.generations[0].text.strip()
# --- Trigger Word Analysis ---
def get_emotional_triggers():
if not os.path.exists(DATA_FILE):
return []
df = pd.read_csv(DATA_FILE)
words = []
for t in df["text"].dropna():
words.extend([w.lower() for w in t.split() if len(w) > 3])
common = Counter(words).most_common(5)
return common
# --- YouTube Search ---
def youtube_search_link(query):
return f"https://www.youtube.com/results?search_query={query.replace(' ', '+')}"
# --- Log Entry ---
def log_entry(date, mood, level, text, journal):
row = {"date": date, "mood": mood, "stress_level": level, "text": text, "journal": journal}
df = pd.DataFrame([row])
if os.path.exists(DATA_FILE):
df.to_csv(DATA_FILE, mode="a", header=False, index=False)
else:
df.to_csv(DATA_FILE, index=False)
# --- Support Engine ---
if st.button("💡 Get Support"):
if not user_input.strip():
st.warning("Please describe your thoughts to begin.")
else:
with st.spinner("Analyzing... please wait."):
level = classify_stress(user_input)
st.success(f"🎯 Detected Stress Level: **{level.upper()}**")
log_entry(datetime.now().strftime("%Y-%m-%d"), mood, level, user_input, journal)
# --- Quotes ---
st.markdown("### 💬 Motivational Quotes")
for quote in generate_quotes(level):
st.markdown(f"<div class='quote-box'>💬 {quote}</div>", unsafe_allow_html=True)
# --- New: YOU & GOD section for high stress only ---
if level == "high":
st.markdown("<div class='highlight-box'><div class='big-text'>🤝 You & God – The Perfect Solution</div><p style='text-align:center;'>No matter how heavy the burden feels, remember: You are never alone. With your own courage and faith in God, you can rise above any challenge.</p></div>", unsafe_allow_html=True)
# --- Activities ---
st.markdown("### 💡 Suggested Activities & Why")
for act, reason in suggest_activities(level):
st.markdown(f"<div class='activity-box'><b>{act}</b><br><span style='font-size:13px'>{reason}</span></div>", unsafe_allow_html=True)
# --- Story ---
st.markdown("### 🌟 An Inspired Story for You")
st.markdown(f"<div class='story-box'>{generate_story(user_input, spiritual_choice)}</div>", unsafe_allow_html=True)
# --- YouTube Video Links ---
st.markdown("### 🎥 Helpful Videos")
query_map = {
"low": "relaxing music stress relief",
"medium": "guided meditation for work stress",
"high": "recovery motivation depression"
}
st.markdown(f"🔗 [🎧 Meditation/Music Video]({youtube_search_link(query_map[level])})")
st.markdown(f"🔗 [🌟 Uplifting Stories]({youtube_search_link('success stories about ' + level + ' stress')})")
if spiritual_choice != "None":
st.markdown(f"🔗 [📖 {spiritual_choice} Guidance Videos]({youtube_search_link(spiritual_choice + ' stress wisdom')})")
# --- History Chart & Emotional Triggers ---
if os.path.exists(DATA_FILE):
st.markdown("---")
st.markdown("### 📈 Mood and Stress Trends")
df = pd.read_csv(DATA_FILE)
df["date"] = pd.to_datetime(df["date"])
df["score"] = df["stress_level"].map({"low": 1, "medium": 2, "high": 3})
st.line_chart(df.groupby("date")["score"].mean())
# Emotional Triggers Section
triggers = get_emotional_triggers()
if triggers:
st.markdown("### 🔍 Common Emotional Triggers in Your Logs")
for word, freq in triggers:
st.markdown(f"- **{word}** ({freq} times)")
with st.expander("📔 View Full Journal Log"):
st.dataframe(df[::-1])