-
Notifications
You must be signed in to change notification settings - Fork 88
/
app.py
1431 lines (1185 loc) · 58.6 KB
/
app.py
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import base64
import datetime
import time
from pymongo import MongoClient
import streamlit as st
import plotly.express as px
import pandas as pd
import requests, random
from streamlit_lottie import st_lottie
from streamlit_option_menu import option_menu
import streamlit.components.v1 as components
import os
from dotenv import load_dotenv
import logging
import sys
from affirmation_widget import display_affirmation_widget
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s'
)
logging.info("Application started.")
def global_error_handler(exc_type, exc_value, exc_traceback):
if issubclass(exc_type, KeyboardInterrupt):
# Call the default handler for KeyboardInterrupt
sys.__excepthook__(exc_type, exc_value, exc_traceback)
return
logging.critical("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
# Set the global error handler
sys.excepthook = global_error_handler
#AI Integration
import anthropic
import datetime
# CSS for Scroll to Top Button
scroll_to_top = """
<style>
#scrollButton {
position: fixed;
bottom: 20px;
right: 20px;
z-index: 99;
font-size: 18px;
border: none;
outline: none;
background-color: rgb(4, 170, );
color: white;
cursor: pointer;
padding: 10px;
border-radius: 10px;
opacity: 0.7;
}
#scrollButton:hover {
background-color: rgb(4, 170, 109);
opacity: 1;
}
</style>
"""
import streamlit as st
import random
import time
# Adding tabs for different sections of the app
tabs = st.tabs(["Home", "Guided Meditation", "Breathing Exercises", "Monitoring (Beta)"])
# Code for the Monitoring (Beta) tab
import streamlit as st
import random
import time
# Add navigation options in sidebar
selected_tab = st.sidebar.selectbox("Choose a tab", ["Home", "Monitoring (Beta)", "Other Tabs"])
if selected_tab == "Monitoring (Beta)":
st.title("Monitoring (Beta)")
st.subheader("Connect Your Heart Rate and Stress Monitoring Device")
# Connection instructions
st.markdown("""
To connect your device, please follow these steps:
1. **Enable Bluetooth** on your heart rate monitoring device and the device running this app.
2. **Select Your Device** from the dropdown below and click **Connect**.
3. Once connected, your heart rate and stress levels will appear in real-time.
""")
# Simulated dropdown to select a device (for demonstration purposes)
device_name = st.selectbox("Select Monitoring Device", ["Device 1", "Device 2", "Device 3"])
# Simulate a connect button
if st.button("Connect"):
st.success(f"Connected to {device_name}!")
# Display placeholders for real-time data
heart_rate_display = st.empty()
stress_level_display = st.empty()
status_display = st.empty()
def simulate_data():
"""Simulate heart rate and stress level data"""
heart_rate = random.randint(60, 100)
stress_level = random.randint(1, 10)
return heart_rate, stress_level
# Real-time update loop
status_display.write("Monitoring real-time data...")
for _ in range(100): # Use a finite range instead of while True for demonstration
# Simulate or fetch data
heart_rate, stress_level = simulate_data()
# Display the data in real-time
heart_rate_display.metric("Heart Rate", f"{heart_rate} BPM")
stress_level_display.metric("Stress Level", f"{stress_level}/10")
# Refresh data every second
time.sleep(1)
#Changes made by --Charvi Arora
#Added security
# Load environment variables from .env file
load_dotenv()
# Retrieve the API key
claude_api_key = os.getenv("CLAUDE_API_KEY")
client = anthropic.Client(api_key=claude_api_key)
def anxiety_management_guide(mood, feeling_description, current_stress_level, recent_events):
# Construct the message for ClaudeAI
message = client.messages.create(
model="claude-3-opus-20240229",
max_tokens=250,
temperature=0.2,
system=f"You are a helpful mental health assistant that helps users manage their anxiety based on their mood, feelings, stress level, and recent events. Provide recommendations for exercises and techniques to reduce anxiety based on the user's mood, {mood}, their feelings described as: {feeling_description}, their current stress level of {current_stress_level}, and recent events: {recent_events}.",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": f"Task: Help me manage my anxiety. I'm feeling {mood}. Here's what I'm experiencing: {feeling_description}. My current stress level is {current_stress_level}, and these are some recent events that might have contributed: {recent_events}\n\nConsiderations:\nProvide tailored anxiety-reduction exercises.\nConsider the user's mood, stress level, feelings, and recent events.\nOffer practical and effective techniques.\nEnsure the suggestions are easy to follow."
}
]
}
]
)
# Set page config (must be the first Streamlit command)
st.set_page_config(page_title="SereniFi", page_icon=":relieved:", layout="centered")
st.markdown(scroll_to_top, unsafe_allow_html=True)
def scroll_to_top_button():
st.markdown('<a id="scrollButton" title="Go to top" href="#top">↑ Top</a>', unsafe_allow_html=True)
st.markdown('<div id="top"></div>', unsafe_allow_html=True)
scroll_to_top_button()
# Data for mental health (sampled)
data = {
'Activity': ['Meditation', 'Yoga', 'Breathing', 'Journaling', 'Music'],
'Calmness_Level': [85, 78, 90, 75, 88]
}
df = px.data.tips() # Use your actual anxiety relief data
@st.cache_data
def get_img_as_base64(file):
logging.info(f"Entering get_img_as_base64 with file: {file}")
try:
with open(file, "rb") as f:
data = f.read()
encoded_data = base64.b64encode(data).decode()
logging.info(f"Successfully encoded file: {file}")
return encoded_data
except Exception as e:
logging.error(f"Error in get_img_as_base64 with file {file}: {e}")
raise
finally:
logging.info(f"Exiting get_img_as_base64 with file: {file}")
# Animated background
page_bg_img = f"""
<style>
/* Animated background gradient */
[data-testid="stAppViewContainer"] > .main {{
background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
background-size: 400% 400%;
animation: gradientBG 15s ease infinite;
}}
[data-testid="stSidebar"] > div:first-child {{
background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
background-size: 400% 400%;
animation: gradientBG 15s ease infinite;
}}
[data-testid="stHeader"] {{
background: rgba(0,0,0,0);
}}
[data-testid="stToolbar"] {{
right: 2rem;
}}
.main .block-container {{
max-width: 900px; /* Increase the width of the centered section */
padding: 2rem 1rem; /* Adjust padding for a more spacious look */
}}
@keyframes gradientBG {{
0% {{
background-position: 0% 50%;
}}
50% {{
background-position: 100% 50%;
}}
100% {{
background-position: 0% 50%;
}}
}}
</style>
"""
st.markdown(page_bg_img, unsafe_allow_html=True)
def load_lottie_url(url: str):
logging.info(f"Fetching Lottie animation from URL: {url}")
try:
response = requests.get(url)
response.raise_for_status() # Raise an HTTPError for bad responses
logging.info(f"Successfully fetched Lottie animation from URL: {url}")
return response.json()
return None
#Footer Function to show footer and bottom nav
def show_footer():
st.write("---")
# Define the HTML for the footer
footer_html = """
<style>
.footer {
text-align: center;
padding: 10px 0;
font-size: 14px;
color: #333;
}
.social-icons {
margin-top: 5px; /* Space above icons */
}
.social-icons a {
margin: 0 10px; /* Spacing between icons */
color: #333; /* Icon color */
text-decoration: none; /* Remove underline from links */
font-size: 20px; /* Icon size */
}
.social-icons a:hover {
color: #007bff; /* Change color on hover */
}
.footer-links {
margin-top: 10px;
font-size: 14px; /* Link font size */
}
.footer-links a {
margin: 0 15px; /* Space between links */
color: #333;
text-decoration: none;
}
.footer-links a:hover {
text-decoration: underline; /* Underline on hover */
}
.newsletter {
margin-top: 10px;
}
.newsletter input {
padding: 5px;
font-size: 14px;
border-radius: 4px;
background-color: rgba(255, 255, 255, 0.5);
border: 1px solid #000;
}
.newsletter button {
padding: 5px 10px;
font-size: 14px;
margin-left: 5px;
cursor: pointer;
border-radius: 4px;
background-color: rgba(255, 255, 255, 0.5);
border: 1px solid #000;
}
.newsletter button:hover {
background-color: rgba(0, 123, 255, 0.3);
}
</style>
<!-- Load Font Awesome from CDN -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<div class="footer">
<p>© 2024 SereniFi. All rights reserved.</p>
<div class="social-icons">
<a href="https://www.linkedin.com/in/amna-hassan-143b76202/" target="_blank">
<i class="fab fa-linkedin" title="LinkedIn"></i>
</a>
<a href="https://github.com/Amna-Hassan04/Serenity-Guide" target="_blank">
<i class="fab fa-github" title="GitHub"></i>
</a>
<a href="https://www.facebook.com" target="_blank">
<i class="fab fa-facebook" title="Facebook"></i>
</a>
<a href="https://www.twitter.com" target="_blank">
<i class="fab fa-twitter" title="Twitter"></i>
</a>
<a href="https://www.instagram.com" target="_blank">
<i class="fab fa-instagram" title="Instagram"></i>
</a>
</div>
<div class="footer-links">
<a class = "foot-links" href="#" target="_blank">Terms and Conditions</a>
<a class = "foot-links" href="#" target="_blank">Privacy Policy</a>
<a class = "foot-links" href="#" target="_blank">About Us</a>
<a class = "foot-links" href="#" target="_blank">Contact Us</a>
</div>
<div class = "Acknowledgements">
<p>Hackathon Project created by Amna Hassan, Anushka Pote, Madhuri K, Pearl Vashistha. <br>
Maintained and Features added by Contributors.
</p>
</div>
</div>
"""
# Render the HTML in the footer
st.markdown(footer_html, unsafe_allow_html=True)
except requests.RequestException as e:
logging.error(f"Error fetching Lottie animation from URL {url}: {e}")
st.error("Failed to fetch Lottie animation. Please try again later.")
return None
# Main function to control page navigation
def main():
selected = option_menu(
menu_title=None,
options=["Home", "Calm Space", "About & Feedback","FAQs"],
icons=["house-door-fill", "cloud-sun-fill", "chat-dots-fill","question-circle-fill"],
menu_icon="sun",
default_index=0,
orientation="horizontal",
styles={
"container": {
"padding": "0!important",
"background-color": "#333",
"border-radius": "10px",
"box-shadow": "0 4px 6px rgba(0, 0, 0, 0.1)",
"width": "100%", # Increase the width of the menu bar
"max-width": "100%", # Prevent overflow
},
"nav-link": {
"font-size": "18px",
"text-align": "center",
"margin": "0 20px", # Increase left and right margin to expand space between items
"--hover-color": "#ddd",
"border-radius": "10px",
"color": "#fff",
"background-color": "rgba(0, 0, 0, 0.8)", # More opaque background
"transition": "background-color 0.3s ease, transform 0.2s"
},
"nav-link-selected": {
"background-color": "#04AA6D",
"color": "#fff",
"font-size": "14px",
}
}
)
if selected == "Home":
show_main_page()
elif selected == "Calm Space":
show_calm_space()
elif selected == "Resources": # Added condition for "Resources"
show_resources() # Call the new function
elif selected == "About & Feedback":
show_about_and_feedback()
elif selected == "FAQs":
show_FAQs_page()
def show_main_page():
st.markdown(
"""
<style>
.centered-title {
text-align: center;
font-size: 2.5rem;
font-weight: bold;
}
</style>
<h1 class="centered-title">Welcome to SereniFi</h1>
""", unsafe_allow_html=True
)
st.markdown('<h3 class="pulse" style="text-align: center;">Feel Calm, Centered, and Peaceful</h3>', unsafe_allow_html=True)
st.image("https://images.pexels.com/photos/185801/pexels-photo-185801.jpeg?auto=compress&cs=tinysrgb&w=600", caption="Breathe and Relax", use_column_width=True)
st.write("---")
# Interactive content
st.markdown("""
### Welcome to Your Oasis of Calm
Imagine a sanctuary where you can escape the hustle and bustle of everyday life—this is your space to recharge and rejuvenate. Embracing mental health is not just about addressing issues; it's about nurturing your inner self and fostering a sense of tranquility.
**Discover Your Path to Peace:**
- **Mindful Breathing:** Click below to start a guided breathing exercise that helps calm your mind instantly.
- **Relaxation Techniques:** Explore various methods to integrate relaxation into your daily routine.
- **Personalized Tips:** Answer a quick survey to receive tailored advice for enhancing your well-being.
**Engage with Us:**
- Share your favorite relaxation techniques or feedback on how our platform helps you.
Your path to a serene and fulfilling life starts here. Let’s embark on this journey together—take the first step today!
""")
# Interactive Widgets
if st.button('Start Guided Breathing'):
st.balloons()
st.write("**Guided Breathing Exercise:** Inhale deeply through your nose for 4 seconds, hold for 4 seconds, and exhale slowly through your mouth. Repeat this process a few times to feel the calming effect.")
st.write("---")
# Survey for Personalized Tips
st.subheader("Personalized Tips for You")
with st.form(key='personalized_tips_form'):
mood = st.radio("What's your current anxiety level?", ["Low", "Moderate", "High", "Overwhelmed"])
submit_button = st.form_submit_button("Get Tips")
if submit_button:
tips = {
"Low": "Keep up the great work! Stay consistent with mindfulness techniques.",
"Moderate": "Take a moment to practice deep breathing.",
"High": "Pause and try a guided meditation.",
"Overwhelmed": "It's important to step away and take a break."
}
st.write(f"**Tip:** {tips[mood]}")
st.write("---")
st.markdown("""
### Embrace Your Journey to Wellness
Taking care of your mental health is an ongoing journey that requires attention and effort. It's essential to recognize the value of setting aside time for yourself amidst your busy schedule. Activities such as mindfulness, relaxation exercises, and engaging in hobbies can significantly improve your overall well-being.
Remember, mental health is not just the absence of mental illness but a state of complete emotional, psychological, and social well-being. Incorporating small, positive changes into your daily routine can lead to a more balanced and fulfilling life. Embrace these practices with an open heart and notice the positive impact they have on your day-to-day life.
""")
st.video("https://www.youtube.com/watch?v=inpok4MKVLM", start_time=10)
st.write("---")
st.markdown('<h4 style="text-align: center;">The Importance of Mental Health</h4>', unsafe_allow_html=True)
st.write("Mental health is just as important as physical health, but often overlooked. It affects how we think, feel, and act in our daily lives. Prioritizing mental well-being can help us manage stress, connect with others, and make healthier choices.")
# Interactive section for viewers
st.subheader("Let's Explore How Mental Health Affects You")
# User input on mental health habits
daily_mindfulness = st.radio("How often do you practice mindfulness or self-care?", ["Daily", "Weekly", "Occasionally", "Rarely"])
if daily_mindfulness == "Daily":
st.success("Amazing! Regular self-care routines greatly enhance mental wellness.")
elif daily_mindfulness == "Weekly":
st.info("Great start! Try increasing your self-care sessions to enhance its benefits.")
elif daily_mindfulness == "Occasionally":
st.warning("It's good you're trying! Consistency can help you feel more balanced.")
else:
st.error("Mental health is crucial! Start small by incorporating simple self-care practices.")
st.write("---")
# Tip for improving mental health
#|------MongoDb for Quick Tips For Mental Health Section for inserting and retreiving the tips------|
#Setting MongoDb connection
mongodb_uri = os.getenv("MONGODB_URI")
logging.info("Attempting to connect to MongoDB")
try:
client = MongoClient(mongodb_uri)
db = client['serenity_guide_db']
tips_collection = db['mental_health_tips']
logging.info("Successfully connected to MongoDB and accessed the 'serenity_guide_db' database and 'mental_health_tips' collection")
except Exception as e:
logging.error(f"Error connecting to MongoDB: {e}")
raise
# Uncomment the following line to populate the database with tips in the format below:
# tips = []
# tips_collection.insert_one({"tip": "Take deep breaths to relax."})
st.subheader("Quick Tip for Mental Health")
logging.info("Rendering 'Quick Tip for Mental Health' subheader")
all_tips = []
if st.button("Get a Tip"):
logging.info("'Get a Tip' button clicked")
try:
all_tips = list(tips_collection.find({}, {"_id": 0, "tip": 1}))
logging.info(f"Retrieved {len(all_tips)} tips from the database")
except Exception as e:
logging.error(f"Error retrieving tips from the database: {e}")
st.error("Failed to retrieve tips. Please try again later.")
if all_tips:
random_tip = random.choice(all_tips)
logging.info(f"Displaying random tip: {random_tip['tip']}")
st.write(f"Tip: {random_tip['tip']}")
else:
logging.info("No tips available in the database")
st.write("No tips available.")
st.write(f"Tip: {random.choice(tips)}")
#!--------------------------------------------------------------------------------------------------|
lottie_url_breathing = "https://lottie.host/89b3ab99-b7ee-4764-ac3a-5fe1ef057bde/WaOPmT23PU.json"
lottie_json_breathing = load_lottie_url(lottie_url_breathing)
if lottie_json_breathing:
st.markdown(
"""
<style>
.lottie-container {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
background: none;
}
.lottie-item {
margin: 0 10px; /* Add space between animations */
}
.lottie-animation {
background: transparent; /* Make the background of the animation transparent */
}
</style>
<div class="lottie-container">
""", unsafe_allow_html=True)
st.markdown('<div class="lottie-item lottie-animation">', unsafe_allow_html=True)
st_lottie(lottie_json_breathing, speed=1, width=300, height=300, key="breathing-animation")
st.markdown('</div>', unsafe_allow_html=True)
st.markdown('</div>', unsafe_allow_html=True)
st.write("---")
# Convert data to a DataFrame
df = pd.DataFrame(data)
# Introduction to the Data Visualization
st.markdown("""
### Explore the Impact of Different Activities
Understanding which activities can best help in reducing anxiety is essential for making informed decisions about your mental wellness.
Use this visualization to see which activities might work best for you and consider incorporating them into your daily routine. Remember, what works for one person may differ for another, so it's important to explore and find what resonates with you.
""")
# Interactive Section: Activity Preferences
st.subheader("Which Activities Do You Prefer?")
activities = st.multiselect(
"Select the activities you enjoy or want to try:",
options=df['Activity'],
default=df['Activity']
)
if activities:
st.write("You selected:", ", ".join(activities))
selected_data = df[df['Activity'].isin(activities)]
fig_selected = px.bar(selected_data, x='Activity', y='Calmness_Level', title="Selected Activities Effectiveness")
st.plotly_chart(fig_selected)
show_footer()
#adding spotify playlist feature
def spotifyPlaylist():
# Embed Spotify API with JavaScript
spotify_html_podcasts = """
<style>
/* Styling for the buttons */
.podcast-button {
background-color: #1db954; /* Spotify green */
color: white;
border: none;
border-radius: 30px;
padding: 10px 20px;
margin: 10px;
font-size: 14px;
cursor: pointer;
transition: background-color 0.3s ease, transform 0.2s ease;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
/* Hover effect for buttons */
.podcast-button:hover {
background-color: #1aa34a; /* Slightly darker green */
transform: scale(1.05); /* Small zoom effect */
}
/* Active state styling (when clicking the button) */
.podcast-button:active {
background-color: #148b3a;
transform: scale(1);
}
/* Fix the container to center align the buttons */
.button-container {
display: flex;
justify-content: center;
gap: 10px; /* Space between buttons */
}
</style>
<script src="https://open.spotify.com/embed/iframe-api/v1" async></script>
<div id="embed-iframe"></div>
<div class="button-container">
<!-- Buttons to switch between podcasts -->
<button class="podcast-button" onclick="loadPodcast('https://open.spotify.com/playlist/77AOjGgwOTmcDiH15lARCh?si=7c76c455e4e74479')">Podcast 1 </button>
<button class="podcast-button" onclick="loadPodcast('https://open.spotify.com/show/4298EkFJWEK6VAxKARB7bS?si=52e58231da08404a')">Podcast 2</button>
<button class="podcast-button" onclick="loadPodcast('https://open.spotify.com/show/1QBP6aNv7BsdQWwhqxLcIC?si=d7145f9457ee42b3')">Podcast 3</button>
<button class="podcast-button" onclick="loadPodcast('https://open.spotify.com/show/69ZUhdV0q2JtibNU2yLTpQ?si=5f6143e2f1744f71')">Podcast 4 </button>
</div>
<script type="text/javascript">
window.onSpotifyIframeApiReady = (IFrameAPI) => {
let currentController = null;
const element = document.getElementById('embed-iframe');
window.loadPodcast = (uri) => {
const options = { uri: uri };
if (currentController) {
currentController.loadUri(uri); // Update the playlist in the existing controller
} else {
IFrameAPI.createController(element, options, (EmbedController) => {
currentController = EmbedController;
});
}
};
// Load the first playlist by default
loadPodcast('https://open.spotify.com/playlist/77AOjGgwOTmcDiH15lARCh?si=7c76c455e4e74479');
};
</script>
"""
# Embed Spotify API with JavaScript
spotify_html_songs = """
<style>
/* Styling for the buttons */
.playlist-button {
background-color: #1db954; /* Spotify green */
color: white;
border: none;
border-radius: 30px;
padding: 10px 20px;
margin: 10px;
font-size: 14px;
cursor: pointer;
transition: background-color 0.3s ease, transform 0.2s ease;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
/* Hover effect for buttons */
.playlist-button:hover {
background-color: #1aa34a; /* Slightly darker green */
transform: scale(1.05); /* Small zoom effect */
}
/* Active state styling (when clicking the button) */
.playlist-button:active {
background-color: #148b3a;
transform: scale(1);
}
/* Fix the container to center align the buttons */
.button-container {
display: flex;
justify-content: center;
gap: 10px; /* Space between buttons */
}
</style>
<script src="https://open.spotify.com/embed/iframe-api/v1" async></script>
<div id="embed-iframe"></div>
<div class="button-container">
<!-- Buttons to switch between playlists -->
<button class="playlist-button" onclick="loadPlaylist('https://open.spotify.com/playlist/37i9dQZF1DWXe9gFZP0gtP?si=32e4c036692f4da4')">Stress Relief </button>
<button class="playlist-button" onclick="loadPlaylist('https://open.spotify.com/playlist/37i9dQZF1DWTC99MCpbjP8?si=1ee785b4c5064848')">Calm</button>
<button class="playlist-button" onclick="loadPlaylist('https://open.spotify.com/playlist/37i9dQZF1DXaImRpG7HXqp?si=f4dbafdfb4c94563')">Calming Acoustic</button>
<button class="playlist-button" onclick="loadPlaylist('https://open.spotify.com/playlist/37i9dQZF1DXcCnTAt8CfNe?si=43381859af3d4869')">Musical Therapy</button>
</div>
<script type="text/javascript">
window.onSpotifyIframeApiReady = (IFrameAPI) => {
let currentController = null;
const element = document.getElementById('embed-iframe');
window.loadPlaylist = (uri) => {
const options = { uri: uri };
if (currentController) {
currentController.loadUri(uri); // Update the playlist in the existing controller
} else {
IFrameAPI.createController(element, options, (EmbedController) => {
currentController = EmbedController;
});
}
};
// Load the first playlist by default
loadPlaylist('https://open.spotify.com/playlist/37i9dQZF1DWXe9gFZP0gtP?si=32e4c036692f4da4');
};
</script>
"""
logging.info("Displaying podcast collection description")
st.write("Explore our collection of insightful podcasts that empower you with expert advice, inspiring stories, and practical tools to enhance your mental well-being.")
try:
logging.info("Displaying Spotify podcasts HTML component")
components.html(spotify_html_podcasts, height=415)
except Exception as e:
logging.error(f"Error displaying Spotify podcasts HTML component: {e}")
st.error("Failed to load podcasts. Please try again later.")
logging.info("Displaying music playlist description")
st.write("Dive into our curated playlists featuring calming and therapeutic music designed to soothe your mind and uplift your spirit, creating a harmonious backdrop for your mental health journey.")
try:
logging.info("Displaying Spotify songs HTML component")
components.html(spotify_html_songs, height=415)
except Exception as e:
logging.error(f"Error displaying Spotify songs HTML component: {e}")
st.error("Failed to load music playlists. Please try again later.")
def soothing_sounds():
st.subheader("🎵 Calm Down with Soothing Sounds")
#Contributions made by Himanshi-M
sound_options = {
"Rain": "https://cdn.pixabay.com/audio/2022/05/13/audio_257112ce99.mp3",
"Ocean Waves": "https://cdn.pixabay.com/audio/2022/06/07/audio_b9bd4170e4.mp3",
"Forest": "https://cdn.pixabay.com/audio/2022/03/10/audio_4dedf5bf94.mp3",
"Birds Chirping":"https://cdn.pixabay.com/audio/2022/03/09/audio_c610232c26.mp3",
"River Flowing":"https://cdn.pixabay.com/audio/2024/07/30/audio_319893354c.mp3",
"White Noise":"https://cdn.pixabay.com/audio/2022/03/12/audio_b4f7e5a4ff.mp3",
"Pink Noise": "https://cdn.pixabay.com/audio/2023/10/07/audio_df9c190caf.mp3"
}
selected_sound = st.selectbox("Choose a sound to relax:", list(sound_options.keys()))
# Organizing the button, checkbox and volume slider on the same row
col1, col2, col3 = st.columns([1,1,2])
with col1:
playbutton=st.button("Play Sound")
with col2:
# Looping Checkbox
loopcheckbox = st.checkbox("Loop Sound")
if playbutton:
logging.info("Play button clicked")
try:
# Rendering the audio player and JS in the app
with col3:
logging.info(f"Playing sound: {selected_sound}")
st.audio(sound_options[selected_sound], format="audio/mp3", loop=loopcheckbox)
except Exception as e:
logging.error(f"Error playing sound: {selected_sound}, Error: {e}")
st.error("Failed to play the selected sound. Please try again later.")
try:
logging.info("Displaying Spotify playlist")
spotifyPlaylist()
except Exception as e:
logging.error(f"Error displaying Spotify playlist: {e}")
st.error("Failed to load Spotify playlist. Please try again later.")
def interactive_journal():
logging.info("Rendering interactive journal")
if 'journal_entries' not in st.session_state:
logging.info("Initializing journal_entries in session state")
st.session_state.journal_entries = []
journal_input = st.text_area("📝 Daily Journal", placeholder="Write down your thoughts...")
if st.button("Save Entry"):
logging.info("Save Entry button clicked")
try:
st.session_state.journal_entries.append({
"date": datetime.datetime.now(),
"entry": journal_input
})
logging.info("Journal entry saved")
st.success("Journal entry saved!")
except Exception as e:
logging.error(f"Error saving journal entry: {e}")
st.error("Failed to save journal entry. Please try again later.")
# Display past journal entries
if st.checkbox("Show Past Entries"):
logging.info("Show Past Entries checkbox selected")
st.write("### Past Journal Entries:")
for entry in st.session_state.journal_entries:
logging.info(f"Displaying journal entry from {entry['date'].strftime('%Y-%m-%d %H:%M:%S')}")
st.write(f"**{entry['date'].strftime('%Y-%m-%d %H:%M:%S')}**: {entry['entry']}")
def mood_boosting_mini_games():
st.markdown("Relax with a fun mini-game to distract your mind. Choose the game you want:")
# Define button style with off-black background and off-white text color
button_style = """
<style>
.button {
background-color: #1a1a1a; /* off-black */
color: #f5f5f5; /* off-white */
padding: 10px 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 10px 2px;
border-radius: 5px;
border: none;
cursor: pointer;
}
.button a {
color: #f5f5f5; /* off-white text */
text-decoration: none; /* remove underline */
}
.button a:hover {
color: #f5f5f5; /* off-white text on hover */
}
.button:hover {
background-color: #333; /* slightly lighter on hover */
}
</style>
"""
# Apply the button style to the Streamlit app
st.markdown(button_style, unsafe_allow_html=True)
# Create a table with multiple game buttons
st.markdown('''
<table>
<tr>
<td><a href="https://g.co/kgs/o4uSVto" target="_blank"><div class="button">Play Pacman</div></a></td>
<td><a href="https://kidshelpline.com.au/games/thinking-brain" target="_blank"><div class="button">Play Thinking Brain</div></a></td>
<td><a href="https://www.google.com/search?q=snake+game" target="_blank"><div class="button">Play Snake Game</div></a></td>
<td><a href="https://agar.io/" target="_blank"><div class="button">Play Agar.io</div></a></td>
</tr>
<tr>
<td><a href="https://trex-runner.com/" target="_blank"><div class="button">Play T-Rex Game</div></a></td>
<td><a href="https://slither.io/" target="_blank"><div class="button">Play Slither.io</div></a></td>
<td><a href="https://www.google.com/search?q=solitaire" target="_blank"><div class="button">Play Solitaire</div></a></td>
<td><a href="https://mahjon.gg/" target="_blank"><div class="button">Play Mahjong</div></a></td>
</tr>
<tr>
<td><a href="https://sudoku.com/" target="_blank"><div class="button">Play Sudoku</div></a></td>
<td><a href="https://www.crazygames.com/game/fireboy-and-watergirl-the-forest-temple" target="_blank"><div class="button">Play Fireboy & Watergirl</div></a></td>
<td><a href="https://checkers.online/" target="_blank"><div class="button">Play Checkers</div></a></td>
<td><a href="https://krunker.io/" target="_blank"><div class="button">Play Krunker.io</div></a></td>
</tr>
</table>
<br>
''', unsafe_allow_html=True)
#Simon Game Challenge
def simon_game_challenge():
st.markdown("## Simon Game Challenge")
# Description, Instructions, and Play Game button in a table format
st.markdown("""
<style>
.game-table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
.game-table th, .game-table td {
border: 1px solid #ddd;
padding: 10px;
text-align: left;
vertical-align: top;
}
.game-table th {
font-weight: bold;
}
.button {
display: inline-block;
padding: 10px 20px;
color: white;
background-color: white;
border-radius: 5px;
text-decoration: none;
text-align: center;
}
.button:hover {
background-color: black ;
font-color: red;
}
</style>
<table class="game-table">
<tr>
<th>Description</th>
<th>Instructions</th>
<th>Play Game</th>
</tr>
<tr>
<td>
The Simon Game Challenge tests your memory and focus as you follow an
increasingly complex sequence of flashing colors and sounds.
Each level adds a new step to the pattern, which you must repeat perfectly to advance.
One mistake ends the game.
</td>
<td>
<ul>
<li><b>Press any key</b> on your keyboard to start the game.</li>
<li>Watch as <b>one block will light up</b> or make a sound. Click that block to match the sequence.</li>
<li>The sequence will get longer with each level. Follow it correctly to advance.</li>
<li>If you make a mistake, the game will end, and your <b>final score</b> will display.</li>
</ul>
</td>
<td style="text-align: center;">
<a href="https://sanyadureja.github.io/Simon-Game-JavaScript-jQuery/" target="_blank" class="button">
Simon Game Challenge
</a>
</td>
</tr>
</table>
""", unsafe_allow_html=True)
def show_calm_space():
st.title("Calm Space")
st.write("Engage in a breathing exercise to calm your mind.")
st.subheader("Daily Affirmations")
display_affirmation_widget()
st.subheader("Quick Tips for Positivity")
quick_tips = [
"Take a deep breath and count to 5.",
"Focus on what you can control, not on what you can't.",
"Take a moment to reflect on something you're grateful for.",
"Smile at yourself in the mirror."
]
st.write("\n".join(f"- {tip}" for tip in quick_tips))
st.write("---")
# Interactive Section: Daily Challenge Suggestions
st.subheader("Daily Challenge Suggestions")
challenges = {
"Meditation": "Try a 10-minute guided meditation session today. Find a quiet space and focus on your breath.",
"Yoga": "Follow a 15-minute yoga routine to stretch and relax your body. Check out a video for guidance.",
"Breathing": "Engage in deep breathing exercises for 5 minutes. Inhale deeply for 4 seconds, hold for 4 seconds, and exhale slowly.",
"Journaling": "Spend 10 minutes writing down your thoughts and feelings. Reflect on your day and your emotions.",
"Music": "Listen to calming music or nature sounds for 20 minutes. Allow the sounds to help you relax and unwind."
}
selected_challenge = st.selectbox("Choose an activity for your daily challenge:", options=list(challenges.keys()))