mfahadkhan commited on
Commit
1223a44
1 Parent(s): fd29e94

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +214 -0
app.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
+ import random
4
+ import requests
5
+ from groq import Groq
6
+ from datetime import datetime
7
+
8
+ # Initialize the sentiment analysis pipeline
9
+ pipe = pipeline("text-classification", model="bhadresh-savani/bert-base-uncased-emotion")
10
+
11
+ # Initialize Groq client
12
+ client = Groq(api_key="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")
13
+
14
+ # Relaxing music files
15
+ relaxing_music = {
16
+ "Surah Ad-duha": "https://server11.mp3quran.net/yasser/093.mp3",
17
+ "Surah Rehman": "https://server7.mp3quran.net/basit/Almusshaf-Al-Mojawwad/055.mp3",
18
+ "Surah Insan": "https://server6.mp3quran.net/qtm/076.mp3",
19
+ "Surah Takweer": "https://server10.mp3quran.net/jleel/081.mp3",
20
+ "Surah Qasas": "https://server10.mp3quran.net/jleel/028.mp3"
21
+ }
22
+
23
+ # Static list of coping strategies
24
+ coping_strategies = [
25
+ "Practice deep breathing exercises for 5 minutes.",
26
+ "Take a short walk and focus on your surroundings.",
27
+ "Write down three things you're grateful for today.",
28
+ "Try a mindfulness meditation session for 10 minutes.",
29
+ "Listen to calming music or nature sounds.",
30
+ "Take a moment to celebrate! Reflect on what made you happy. ",
31
+ "Trust in Allah’s plan: 'And whoever puts their trust in Allah, He will be enough for them",
32
+ "Face your fears with courage. Remember: 'Fear not, for indeed, I am with you both; I hear and I see.",
33
+
34
+ ]
35
+
36
+ # Function to return a random coping strategy
37
+ def coping_strategy():
38
+ return random.choice(coping_strategies)
39
+
40
+ # Function to fetch motivational quotes from ZenQuotes API
41
+ def daily_motivation():
42
+ url = "https://zenquotes.io/api/random"
43
+ response = requests.get(url)
44
+ if response.status_code == 200:
45
+ data = response.json()
46
+ quote = data[0]['q']
47
+ author = data[0]['a']
48
+ return f"{quote} - {author}"
49
+ else:
50
+ return "Could not fetch a motivational quote at the moment."
51
+
52
+ # Track if a chat has started and detected mood
53
+ chat_started = False
54
+ detected_mood = None
55
+
56
+ # Function to analyze mood using sentiment analysis
57
+ def analyze_mood(text):
58
+ global chat_started, detected_mood
59
+ chat_started = True
60
+ result = pipe(text)[0]
61
+ detected_mood = result['label'].capitalize()
62
+ return f"I sense you're feeling {detected_mood.lower()}."
63
+
64
+ # Function to generate a response using Groq's LLaMA model
65
+ def groq_chat(text):
66
+ try:
67
+ chat_completion = client.chat.completions.create(
68
+ messages=[
69
+ {
70
+ "role": "system",
71
+ "content": "You’re a compassionate and knowledgeable medical health advisor..."
72
+ },
73
+ {"role": "user", "content": text}
74
+ ],
75
+ model="llama3-8b-8192",
76
+ )
77
+ return chat_completion.choices[0].message.content
78
+ except Exception as e:
79
+ return f"Error: {str(e)}"
80
+
81
+ # Function to play relaxing music
82
+ def play_music(music_choice):
83
+ music_url = relaxing_music[music_choice]
84
+ return music_url
85
+
86
+ # Function to handle chat responses
87
+ def handle_chat(text):
88
+ bot_response = groq_chat(text)
89
+ return [(text, bot_response)]
90
+
91
+ # Function to interpret quiz results
92
+ def interpret_results(answers):
93
+ # Answer index:
94
+ # 0-3: Non-distress related (0 points each)
95
+ # 4-7: Distress related (points based on severity)
96
+
97
+ # Distress question answers
98
+ distress_answers = answers[4:8]
99
+
100
+ # Calculate distress score
101
+ distress_score = 0
102
+ for answer in distress_answers:
103
+ if answer == "More than two weeks":
104
+ distress_score += 3
105
+ elif answer == "More than a week":
106
+ distress_score += 2
107
+ elif answer == "A few days but less than a week":
108
+ distress_score += 1
109
+
110
+ # Percentage calculation
111
+ percentage = min(distress_score / 12 * 100, 100) # Assuming max score is 12
112
+
113
+ # Interpret current situation
114
+ if percentage > 70:
115
+ situation = "High distress level. Symptoms are significantly impacting your daily life."
116
+ elif percentage > 40:
117
+ situation = "Moderate distress level. Some symptoms are affecting your daily activities."
118
+ else:
119
+ situation = "Low distress level. You seem to be managing well, but stay mindful."
120
+
121
+ # Suggestions
122
+ if percentage > 70:
123
+ suggestions = "It may be beneficial to seek professional help. Consider talking to a mental health counselor or therapist."
124
+ elif percentage > 40:
125
+ suggestions = "Try incorporating stress management techniques into your routine. Reach out to support networks or consider self-help resources."
126
+ else:
127
+ suggestions = "Continue with your current coping strategies and maintain a healthy routine. Keep track of any changes in your mental state."
128
+
129
+ return f"**Percentage Level:** {percentage:.2f}%\n\n**Current Situation:** {situation}\n\n**Suggestions:** {suggestions}"
130
+
131
+ # Initialize a list to store journal entries
132
+ journal_entries = []
133
+
134
+ # Function to save the journal entry with a timestamp
135
+ def save_journal(entry):
136
+ if entry.strip():
137
+ # Get the current date and time
138
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
139
+
140
+ # Append the entry to the list with the timestamp
141
+ journal_entries.append(f"{timestamp} - {entry}")
142
+
143
+ # Return all entries as a single string, each entry on a new line
144
+ return "\n\n".join(journal_entries)
145
+ else:
146
+ return "Please write something to save."
147
+
148
+ # Gradio UI components
149
+ with gr.Blocks() as demo:
150
+ gr.Markdown("# <div style='text-align:center;'>🧘MindfulMate</div>\n\n**<div style='text-align:center;'>Be present, be peaceful</div>**", elem_id="header")
151
+
152
+
153
+ with gr.Tabs():
154
+ # Tab 1: Chat with MindfulMate
155
+ with gr.Tab("Chat"):
156
+ with gr.Row():
157
+ # Sidebar for music, coping strategies, and motivation
158
+ with gr.Column(scale=1):
159
+ music_choice = gr.Dropdown(choices=list(relaxing_music.keys()), label="Choose the Peace")
160
+ play_music_btn = gr.Button("Play")
161
+ audio_output = gr.Audio(label="Now Playing", autoplay=True, interactive=False)
162
+
163
+ options = gr.Dropdown(["Get Coping Strategy", "Daily Motivation"], label="Choose an option")
164
+ mood_output = gr.Textbox(label="Result", interactive=False)
165
+
166
+ # Handle coping strategy and daily motivation
167
+ options.change(fn=lambda opt: coping_strategy() if opt == "Get Coping Strategy" else daily_motivation(),
168
+ inputs=options, outputs=mood_output)
169
+ play_music_btn.click(fn=play_music, inputs=music_choice, outputs=audio_output)
170
+
171
+ # Main Chat Area
172
+ with gr.Column(scale=4):
173
+ chatbot = gr.Chatbot(label="Chat with MindfulMate")
174
+ with gr.Row():
175
+ text_input = gr.Textbox(label="Feel free to share what's in your mind...", scale=3)
176
+ voice_input = gr.Audio(type="filepath", label="Speak", scale=1)
177
+ submit_btn = gr.Button("Submit")
178
+
179
+ # Corrected click function to return the correct format
180
+ submit_btn.click(fn=lambda text: (handle_chat(text), analyze_mood(text)),
181
+ inputs=text_input, outputs=[chatbot, mood_output])
182
+
183
+ # Tab 2: Journal
184
+ with gr.Tab("Journal"):
185
+ gr.Markdown("### Journaling Section")
186
+ journal_input = gr.Textbox(label="Write about your day", placeholder="How was your day?", lines=6)
187
+ save_journal_btn = gr.Button("Save Entry")
188
+ journal_output = gr.Textbox(label="Your Journal Entries", interactive=False)
189
+
190
+ # Connect the save button to the save_journal function
191
+ save_journal_btn.click(fn=save_journal, inputs=journal_input, outputs=journal_output)
192
+
193
+ # Tab 3: Take the Quiz
194
+ with gr.Tab("Take the Quiz"):
195
+ gr.Markdown("### Mental Health Quiz")
196
+
197
+ question_1 = gr.Dropdown(["Sadness", "Anger", "Fear", "Guilt"], label="Which difficult emotion do you struggle with the most?")
198
+ question_2 = gr.Dropdown(["0-1 hours", "2-3 hours", "4-5 hours", "More than 5 hours"], label="On an average weekday, how many hours do you spend alone?")
199
+ question_3 = gr.Dropdown(["Very well", "Somewhat well", "Not very well", "Not at all"], label="How well do you feel you manage your stress?")
200
+ question_4 = gr.Dropdown(["Introvert", "Extrovert"], label="Would you consider yourself an introvert or an extrovert?")
201
+ question_5 = gr.Dropdown(["Not at all", "A few days but less than a week", "More than a week", "More than two weeks"], label="Over the last 2 weeks, how often have you been feeling nervous or anxious?")
202
+ question_6 = gr.Dropdown(["Not at all", "A few days but less than a week", "More than a week", "More than two weeks"], label="Over the last 2 weeks, how often have you been bothered by not being able to control your thoughts or worries?")
203
+ question_7 = gr.Dropdown(["Not at all", "A few days but less than a week", "More than a week", "More than two weeks"], label="Over the last 2 weeks, how often have you felt little interest or pleasure in doing things that you normally enjoyed doing?")
204
+ question_8 = gr.Dropdown(["Not at all", "A few days but less than a week", "More than a week", "More than two weeks"], label="Over the last 2 weeks, how often have you felt down, depressed, or hopeless?")
205
+
206
+ quiz_submit = gr.Button("Submit Quiz")
207
+ quiz_results = gr.Textbox(label="Quiz Results", interactive=False)
208
+
209
+ # Handle quiz results
210
+ quiz_submit.click(fn=lambda *answers: interpret_results(list(answers)),
211
+ inputs=[question_1, question_2, question_3, question_4, question_5, question_6, question_7, question_8],
212
+ outputs=quiz_results)
213
+
214
+ demo.launch()