samiee2213 commited on
Commit
8d4b88f
β€’
1 Parent(s): 3f84800

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +1242 -0
app.py ADDED
@@ -0,0 +1,1242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ from dotenv import load_dotenv
4
+ from langchain.schema import HumanMessage, SystemMessage, AIMessage
5
+ from langchain.chat_models import AzureChatOpenAI,ChatOpenAI
6
+ from langchain.memory import ConversationBufferWindowMemory
7
+ from langchain.prompts import PromptTemplate
8
+ import warnings
9
+ import time
10
+ from sqlalchemy import create_engine, Column, Integer, String, Text, Table, MetaData
11
+ from sqlalchemy.orm import sessionmaker
12
+ import matplotlib.pyplot as plt
13
+ import pandas as pd
14
+ import numpy as np
15
+ from dotenv import load_dotenv
16
+
17
+ warnings.filterwarnings("ignore", category=DeprecationWarning)
18
+
19
+ # Load environment variables
20
+ load_dotenv()
21
+ st.set_page_config(page_title="MindMate", layout="wide", initial_sidebar_state="expanded")
22
+
23
+ # CSS styles
24
+ css = '''
25
+ <style>
26
+ /* General styles */
27
+ body {
28
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
29
+ }
30
+
31
+ /* Sidebar styles */
32
+ .sidebar-content {
33
+ display: flex;
34
+ flex-direction: column;
35
+ height: 100%;
36
+ padding: 1rem;
37
+ background-color: #f0f2f6;
38
+ border-radius: 10px;
39
+ box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
40
+ }
41
+ .sidebar-item {
42
+ padding: 1rem;
43
+ margin: 0.5rem 0;
44
+ cursor: pointer;
45
+ transition: background-color 0.3s, transform 0.3s;
46
+ display: flex;
47
+ align-items: center;
48
+ border-radius: 10px;
49
+ }
50
+ .sidebar-item:hover {
51
+ background-color: #e0e0e0;
52
+ transform: scale(1.05);
53
+ }
54
+ .sidebar-item.active {
55
+ background-color: #d0d0d0;
56
+ }
57
+ .sidebar-item .icon {
58
+ margin-right: 10px;
59
+ font-size: 1.5rem;
60
+ }
61
+ .sidebar-item .label {
62
+ font-size: 1.2rem;
63
+ font-weight: bold;
64
+ }
65
+
66
+ /* Chat styles */
67
+ .chat-message {
68
+ padding: 1.5rem;
69
+ border-radius: 0.5rem;
70
+ margin-bottom: 1rem;
71
+ display: flex;
72
+ }
73
+ .chat-message.user {
74
+ align-self: flex-end;
75
+ background-color: #2b313e;
76
+ }
77
+ .chat-message.bot {
78
+ background-color: #475063;
79
+ }
80
+ .chat-message .avatar {
81
+ width: 20%;
82
+ }
83
+ .chat-message .avatar img {
84
+ max-width: 78px;
85
+ max-height: 78px;
86
+ border-radius: 50%;
87
+ object-fit: cover;
88
+ }
89
+ .chat-message .message {
90
+ width: 80%;
91
+ padding: 0 1.5rem;
92
+ color: #fff;
93
+ }
94
+
95
+ /* Session card styles */
96
+ .session-card {
97
+ display: flex;
98
+ flex-direction: column;
99
+ justify-content: space-between;
100
+ align-items: center;
101
+ padding: 1.5rem;
102
+ margin: 1rem;
103
+ background-color: #ffffff;
104
+ border-radius: 15px;
105
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
106
+ transition: transform 0.3s, box-shadow 0.3s;
107
+ text-align: center;
108
+ }
109
+ .session-card:hover {
110
+ transform: translateY(-5px);
111
+ box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
112
+ }
113
+ .session-card .session-info {
114
+ display: flex;
115
+ flex-direction: column;
116
+ align-items: center;
117
+ text-align: center;
118
+ }
119
+ .session-card .session-info .session-title {
120
+ font-weight: bold;
121
+ margin-bottom: 0.5rem;
122
+ color: #333;
123
+ font-size: 1.2rem;
124
+ }
125
+ .session-card .session-info .session-subtitle {
126
+ color: #666;
127
+ margin-bottom: 0.5rem;
128
+ font-size: 1rem;
129
+ }
130
+ .session-card .session-info .session-time {
131
+ color: #aaa;
132
+ margin-bottom: 1rem;
133
+ font-size: 0.9rem;
134
+ }
135
+ .session-card .buttons {
136
+ display: flex;
137
+ justify-content: space-between;
138
+ width: 100%;
139
+ }
140
+ .session-card .buttons button {
141
+ background-color: #007BFF;
142
+ color: white;
143
+ border: none;
144
+ padding: 0.5rem 1rem;
145
+ border-radius: 5px;
146
+ cursor: pointer;
147
+ transition: background-color 0.3s;
148
+ width: 45%;
149
+ font-size: 0.9rem;
150
+ }
151
+ .session-card .buttons button:hover {
152
+ background-color: #0056b3;
153
+ }
154
+ .delete-button {
155
+ background-color: #dc3545;
156
+ }
157
+ .delete-button:hover {
158
+ background-color: #c82333;
159
+ }
160
+ .new-session-card {
161
+ display: flex;
162
+ flex-direction: column;
163
+ justify-content: center;
164
+ align-items: center;
165
+ padding: 1rem;
166
+ margin: 1rem;
167
+ background-color: #e0e0e0;
168
+ border-radius: 15px;
169
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
170
+ cursor: pointer;
171
+ transition: transform 0.3s, box-shadow 0.3s;
172
+ width: 220px;
173
+ height: 150px;
174
+ }
175
+ .new-session-card:hover {
176
+ transform: translateY(-5px);
177
+ box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
178
+ }
179
+ .new-session-card .new-session-icon {
180
+ font-size: 2rem;
181
+ color: #666;
182
+ margin-bottom: 0.5rem;
183
+ }
184
+ .new-session-card .new-session-text {
185
+ color: #666;
186
+ font-weight: bold;
187
+ text-align: center;
188
+ }
189
+
190
+ /* Tool card styles */
191
+ .tool-card {
192
+ background-color: #ffffff;
193
+ border-radius: 15px;
194
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
195
+ padding: 1.5rem;
196
+ margin: 1rem;
197
+ transition: transform 0.3s, box-shadow 0.3s;
198
+ text-align: center;
199
+ }
200
+ .tool-card:hover {
201
+ transform: translateY(-5px);
202
+ box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
203
+ }
204
+ .tool-card .tool-title {
205
+ font-weight: bold;
206
+ margin-bottom: 0.5rem;
207
+ color: #333;
208
+ font-size: 1.2rem;
209
+ }
210
+ .tool-card .tool-description {
211
+ color: #666;
212
+ margin-bottom: 0.5rem;
213
+ font-size: 1rem;
214
+ }
215
+ .tool-card .tool-time {
216
+ color: #aaa;
217
+ margin-bottom: 1rem;
218
+ font-size: 0.9rem;
219
+ }
220
+ .tool-card .start-button {
221
+ background-color: #007BFF;
222
+ color: white;
223
+ border: none;
224
+ padding: 0.5rem 1rem;
225
+ border-radius: 5px;
226
+ cursor: pointer;
227
+ transition: background-color 0.3s;
228
+ }
229
+ .tool-card .start-button:hover {
230
+ background-color: #0056b3;
231
+ }
232
+
233
+ /* Therapist card styles */
234
+ .therapist-card {
235
+ background-color: #ffffff;
236
+ border-radius: 15px;
237
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
238
+ padding: 1.5rem;
239
+ margin: 1rem;
240
+ transition: transform 0.3s, box-shadow 0.3s;
241
+ text-align: center;
242
+ }
243
+ .therapist-card:hover {
244
+ transform: translateY(-5px);
245
+ box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
246
+ }
247
+ .therapist-card img {
248
+ max-width: 100%;
249
+ border-radius: 50%;
250
+ margin-bottom: 1rem;
251
+ }
252
+ .therapist-card .therapist-name {
253
+ font-weight: bold;
254
+ margin-bottom: 0.5rem;
255
+ color: #333;
256
+ font-size: 1.2rem;
257
+ }
258
+ .therapist-card .therapist-description {
259
+ color: #666;
260
+ margin-bottom: 0.5rem;
261
+ font-size: 1rem;
262
+ }
263
+ .therapist-card .select-button {
264
+ background-color: #007BFF;
265
+ color: white;
266
+ border: none;
267
+ padding: 0.5rem 1rem;
268
+ border-radius: 5px;
269
+ cursor: pointer;
270
+ transition: background-color 0.3s;
271
+ }
272
+ .therapist-card .select-button:hover {
273
+ background-color: #0056b3;
274
+ }
275
+
276
+ /* Today page styles */
277
+ .today-page {
278
+ display: flex;
279
+ flex-direction: column;
280
+ align-items: center;
281
+ padding: 2rem;
282
+ }
283
+ .today-page .header {
284
+ text-align: center;
285
+ margin-bottom: 2rem;
286
+ }
287
+ .today-page .header h1 {
288
+ font-size: 2.5rem;
289
+ color: #333;
290
+ margin-bottom: 0.5rem;
291
+ }
292
+ .today-page .header p {
293
+ font-size: 1.2rem;
294
+ color: #666;
295
+ }
296
+ .today-page .content {
297
+ display: flex;
298
+ justify-content: space-around;
299
+ flex-wrap: wrap;
300
+ }
301
+ .today-page .card {
302
+ background-color: #ffffff;
303
+ border-radius: 15px;
304
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
305
+ padding: 1rem;
306
+ margin: 1rem;
307
+ text-align: center;
308
+ transition: transform 0.3s, box-shadow 0.3s;
309
+ width: 300px;
310
+ }
311
+ .today-page .card:hover {
312
+ transform: translateY(-5px);
313
+ box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
314
+ }
315
+ .today-page .card img {
316
+ max-width: 100%;
317
+ border-radius: 15px;
318
+ margin-bottom: 1rem;
319
+ }
320
+ .today-page .card h3 {
321
+ font-size: 1.5rem;
322
+ color: #333;
323
+ margin-bottom: 0.5rem;
324
+ }
325
+ .today-page .card p {
326
+ font-size: 1rem;
327
+ color: #666;
328
+ }/* How to use page styles */
329
+ .how-to-use-page {
330
+ font-family: 'Poppins', sans-serif;
331
+ color: #FAFAFA;
332
+ background-color: #0E1117;
333
+ padding: 2rem;
334
+ border-radius: 15px;
335
+ }
336
+
337
+ .how-to-use-page h2 {
338
+ font-size: 2.5rem;
339
+ color: #FF4B4B;
340
+ text-align: center;
341
+ margin-bottom: 1rem;
342
+ text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
343
+ }
344
+
345
+ .how-to-use-page p {
346
+ font-size: 1.2rem;
347
+ margin-bottom: 1.5rem;
348
+ line-height: 1.6;
349
+ }
350
+
351
+ .how-to-use-page .section {
352
+ margin-bottom: 2rem;
353
+ }
354
+
355
+ .how-to-use-page .section h3 {
356
+ font-size: 1.8rem;
357
+ color: #FF6F61;
358
+ margin-bottom: 0.5rem;
359
+ }
360
+
361
+ .how-to-use-page .section ul {
362
+ list-style-type: none;
363
+ padding-left: 0;
364
+ }
365
+
366
+ .how-to-use-page .section ul li {
367
+ margin-bottom: 0.75rem;
368
+ }
369
+
370
+ .how-to-use-page .section ul li:before {
371
+ content: "βœ”οΈ";
372
+ margin-right: 0.5rem;
373
+ color: #FF4B4B;
374
+ }
375
+
376
+ .how-to-use-page img {
377
+ max-width: 100%;
378
+ border-radius: 10px;
379
+ margin-top: 1rem;
380
+ margin-bottom: 1rem;
381
+ }
382
+ </style>
383
+ '''
384
+
385
+ bot_template = '''
386
+ <div class="chat-message bot">
387
+ <div class="avatar">
388
+ <img src="https://cdn-icons-png.flaticon.com/512/6134/6134346.png" style="max-height: 78px; max-width: 78px; border-radius: 50%; object-fit: cover;">
389
+ </div>
390
+ <div class="message">{{MSG}}</div>
391
+ </div>
392
+ '''
393
+
394
+ user_template = '''
395
+ <div class="chat-message user">
396
+ <div class="message" style="text-align:right">{{MSG}}</div>
397
+ <div class="avatar">
398
+ <img src="https://png.pngtree.com/png-vector/20190321/ourmid/pngtree-vector-users-icon-png-image_856952.jpg">
399
+ </div>
400
+ </div>
401
+ '''
402
+
403
+ # CSS
404
+ st.write(css, unsafe_allow_html=True)
405
+ # Initialize the database
406
+ engine = create_engine('sqlite:///sessions.db')
407
+ metadata = MetaData()
408
+
409
+ sessions_table = Table(
410
+ 'sessions', metadata,
411
+ Column('id', Integer, primary_key=True),
412
+ Column('title', String),
413
+ Column('subtitle', String),
414
+ Column('time', String),
415
+ Column('messages', Text)
416
+ )
417
+
418
+ metadata.create_all(engine)
419
+ DBSession = sessionmaker(bind=engine)
420
+ db_session = DBSession()
421
+
422
+ # Sidebar navigation with model selection
423
+ def sidebar():
424
+ st.sidebar.header("Navigation")
425
+ pages = ["Today", "Sessions", "Tools", "Therapists", "Insights", "Settings", "How to use?"]
426
+ icons = ["πŸ“…", "πŸ’¬", "πŸ› οΈ", "πŸ‘₯", "πŸ“Š", "βš™οΈ", "❓"]
427
+ selected_page = st.sidebar.selectbox(
428
+ "",
429
+ [f"{icons[i]} {pages[i]}" for i in range(len(pages))],
430
+ format_func=lambda x: x.split(" ", 1)[1]
431
+ )
432
+
433
+ # API Key and Model Selection
434
+ st.sidebar.subheader('Select Model')
435
+ models = ['3.5 Turbo', '4.0', 'Azure', 'Gemini', 'Ollama', 'Mistral'] # Example list of models
436
+ selected_model = st.sidebar.selectbox('Select Model', models)
437
+
438
+ api_key = st.sidebar.text_input('Enter API Key', type='password')
439
+
440
+ if selected_model == 'Azure':
441
+ endpoint = st.sidebar.text_input("Enter endpoint", type="url")
442
+ deployment_name = st.sidebar.text_input("Enter deployment name")
443
+
444
+ if st.sidebar.button('Run Model'):
445
+ st.session_state['api_key'] = api_key
446
+
447
+ if selected_model == '3.5 Turbo':
448
+ st.session_state['chat'] = ChatOpenAI(temperature=0, model="gpt-3.5-turbo", api_key=api_key)
449
+ elif selected_model == 'Azure':
450
+ st.session_state['chat'] = AzureChatOpenAI(
451
+ azure_endpoint=endpoint,
452
+ deployment_name=deployment_name,
453
+ openai_api_version="2023-03-15-preview",
454
+ api_key=api_key,
455
+ openai_api_type="Azure"
456
+ )
457
+ elif selected_model == '4.0':
458
+ st.session_state['chat'] = ChatOpenAI(temperature=0, model="gpt-4.0", api_key=api_key)
459
+ elif selected_model == 'Gemini':
460
+ st.session_state['chat'] = ChatOpenAI(temperature=0, model="gemini-1", api_key=api_key)
461
+ elif selected_model == 'Ollama':
462
+ st.session_state['chat'] = ChatOpenAI(temperature=0, model="ollama-1", api_key=api_key)
463
+ elif selected_model == 'Mistral':
464
+ st.session_state['chat'] = ChatOpenAI(temperature=0, model="mistral-1", api_key=api_key)
465
+ else:
466
+ st.error('Invalid model selection')
467
+ return
468
+
469
+ st.success(f'Model {selected_model} is running...')
470
+
471
+ return selected_page.split(" ", 1)[1]
472
+
473
+ page = sidebar()
474
+
475
+ # Initialize the selected model and API key
476
+ if 'api_key' not in st.session_state:
477
+ st.session_state['api_key'] = None
478
+ if 'chat' not in st.session_state:
479
+ st.session_state['chat'] = None
480
+
481
+ # Function to load sessions from the database
482
+ def load_sessions():
483
+ sessions = []
484
+ for s in db_session.query(sessions_table).all():
485
+ session = {
486
+ "id": s.id,
487
+ "title": s.title,
488
+ "subtitle": s.subtitle,
489
+ "time": s.time,
490
+ "messages": eval(s.messages) if s.messages else []
491
+ }
492
+ print(f"Loaded session: {session}") # Debug statement
493
+ sessions.append(session)
494
+ return sessions
495
+
496
+
497
+ # Function to save session to the database
498
+ def save_session(session):
499
+ print(f"Saving session: {session}") # Debug statement
500
+ db_session.query(sessions_table).filter_by(id=session['id']).update({
501
+ 'title': session['title'],
502
+ 'subtitle': session['subtitle'],
503
+ 'time': session['time'],
504
+ 'messages': str(session['messages'])
505
+ })
506
+ db_session.commit()
507
+
508
+
509
+ # Function to add new session to the database
510
+ def add_session(session):
511
+ new_session = sessions_table.insert().values(
512
+ title=session['title'],
513
+ subtitle=session['subtitle'],
514
+ time=session['time'],
515
+ messages=str(session['messages'])
516
+ )
517
+ result = db_session.execute(new_session)
518
+ db_session.commit()
519
+ return result.inserted_primary_key[0]
520
+
521
+ # Function to delete session from the database
522
+ def delete_session(session_id):
523
+ db_session.query(sessions_table).filter_by(id=session_id).delete()
524
+ db_session.commit()
525
+
526
+ # Load existing sessions from the database
527
+ if 'sessions' not in st.session_state:
528
+ st.session_state['sessions'] = load_sessions()
529
+ if 'current_session' not in st.session_state:
530
+ st.session_state['current_session'] = None
531
+ if 'selected_therapist' not in st.session_state:
532
+ st.session_state['selected_therapist'] = None
533
+
534
+ # Therapist prompt templates
535
+ therapist_templates = {
536
+ "Counsellor": """
537
+ You are a compassionate and empathetic counsellor specialized in mental health support.
538
+ Your primary goal is to provide emotional support, offer practical advice, and guide users to helpful resources.
539
+ You are non-judgmental, understanding, and always prioritize the user's well-being.
540
+ Respond in a calm and reassuring manner, ensuring that users feel heard and supported.
541
+
542
+ Guidelines:
543
+ 1. Always be empathetic, supportive, and non-judgmental.
544
+ 2. Provide practical advice and suggest resources where appropriate.
545
+ 3. Use simple and clear language to ensure understanding.
546
+ 4. Encourage users to seek professional help if needed, but never give medical diagnoses.
547
+ 5. Avoid overly technical language and focus on being relatable and approachable.
548
+ 6. Be friendly, remember context and conversation between the user and yourself and become more engaging.
549
+ 7. Use open-ended questions to encourage users to express themselves.
550
+ 8. Validate the user's feelings and experiences.
551
+ 9. Offer coping strategies and self-care tips.
552
+ 10. Maintain confidentiality and respect the user's privacy.
553
+ Translate and respond in {language}.
554
+ Current conversation:
555
+ {chat_history}
556
+
557
+ User: {user_message}
558
+ Counsellor:
559
+ """,
560
+ "Cognitive Behavioral Therapist": """
561
+ You are a cognitive-behavioral therapist specialized in helping individuals challenge and change unhelpful cognitive distortions and behaviors.
562
+ Your role is to guide users through structured exercises and provide evidence-based techniques to improve their mental health.
563
+
564
+ Guidelines:
565
+ 1. Always be empathetic, supportive, and non-judgmental.
566
+ 2. Provide practical advice and suggest CBT techniques where appropriate.
567
+ 3. Use simple and clear language to ensure understanding.
568
+ 4. Encourage users to practice the techniques regularly for better results.
569
+ 5. Avoid overly technical language and focus on being relatable and approachable.
570
+ 6. Provide clear explanations of cognitive-behavioral concepts.
571
+ 7. Use examples and analogies to help users understand complex ideas.
572
+ 8. Offer step-by-step guidance for CBT exercises.
573
+ 9. Encourage users to set and work towards achievable goals.
574
+ 10. Provide positive reinforcement and celebrate progress.
575
+ Translate and Respond in {language}.
576
+ Current conversation:
577
+ {chat_history}
578
+
579
+ User: {user_message}
580
+ Cognitive Behavioral Therapist:
581
+ """,
582
+ "Student Counsellor": """
583
+ You are a student counsellor specialized in helping students with academic, social, and emotional challenges.
584
+ Your role is to provide support, guidance, and practical advice to help students navigate their school or college life effectively.
585
+
586
+ Guidelines:
587
+ 1. Always be empathetic, supportive, and non-judgmental.
588
+ 2. Provide practical advice and suggest resources where appropriate.
589
+ 3. Use simple and clear language to ensure understanding.
590
+ 4. Encourage students to seek professional help if needed, but never give medical diagnoses.
591
+ 5. Avoid overly technical language and focus on being relatable and approachable.
592
+ 6. Help students develop time management and study skills.
593
+ 7. Offer guidance on dealing with peer pressure and social issues.
594
+ 8. Provide tips for managing stress and anxiety.
595
+ 9. Encourage students to set academic and personal goals.
596
+ 10. Validate students' feelings and experiences.
597
+ Translate and Respond in {language}.
598
+ Current conversation:
599
+ {chat_history}
600
+
601
+ User: {user_message}
602
+ Student Counsellor: Respond in {language}.
603
+ """,
604
+ "Psychologist": """
605
+ You are a clinical psychologist specialized in psychological assessment and therapy.
606
+ Your role is to provide evidence-based psychological support and guide users towards better mental health.
607
+
608
+ Guidelines:
609
+ 1. Always be empathetic, supportive, and non-judgmental.
610
+ 2. Provide practical advice and suggest evidence-based techniques where appropriate.
611
+ 3. Use simple and clear language to ensure understanding.
612
+ 4. Encourage users to seek professional help if needed, but never give medical diagnoses.
613
+ 5. Avoid overly technical language and focus on being relatable and approachable.
614
+ 6. Provide clear explanations of psychological concepts.
615
+ 7. Use examples and analogies to help users understand complex ideas.
616
+ 8. Offer step-by-step guidance for therapeutic exercises.
617
+ 9. Encourage users to set and work towards achievable goals.
618
+ 10. Provide positive reinforcement and celebrate progress.
619
+ Translate and Respond in {language}.
620
+ Current conversation:
621
+ {chat_history}
622
+
623
+ User: {user_message}
624
+ Psychologist: Respond in {language}.
625
+ """,
626
+ "Best Friend": """
627
+ You are a supportive and understanding friend who is always here to listen and chat about anything.
628
+ Your role is to provide a non-judgmental, friendly, and comforting presence.
629
+ You respond with warmth, understanding, and encouragement, just like a best friend would.
630
+
631
+ Guidelines:
632
+ 1. Always be empathetic, supportive, and non-judgmental.
633
+ 2. Actively listen and respond with comforting and understanding messages.
634
+ 3. Encourage the user to express themselves and validate their feelings.
635
+ 4. Use simple, friendly, and relatable language.
636
+ 5. Maintain confidentiality and respect the user's privacy.
637
+ 6. Offer encouragement and positive reinforcement.
638
+ 7. Follow up on previously discussed topics.
639
+ 8. Provide meaningful and contextually appropriate support.
640
+ 9. Maintain a casual and approachable tone.
641
+ 10. Share personal anecdotes and experiences to build rapport.
642
+ Translate and respond in {language}
643
+ Current conversation:
644
+ {chat_history}
645
+
646
+ User: {user_message}
647
+ Best Friend: Respond in {language}.
648
+ """
649
+ }
650
+
651
+ therapists = [
652
+ {
653
+ "name": "Counsellor",
654
+ "description": "Compassionate and empathetic, specialized in emotional support.",
655
+ "image": "https://cdn-icons-png.flaticon.com/512/1154/1154448.png" # Female counsellor
656
+ },
657
+ {
658
+ "name": "Cognitive Behavioral Therapist",
659
+ "description": "Specializes in cognitive-behavioral techniques for mental health improvement.",
660
+ "image": "https://cdn-icons-png.flaticon.com/512/1154/1154476.png" # Male therapist
661
+ },
662
+ {
663
+ "name": "Student Counsellor",
664
+ "description": "Helps students with academic, social, and emotional challenges.",
665
+ "image": "https://cdn-icons-png.flaticon.com/512/1154/1154494.png" # New female student counsellor
666
+ },
667
+ {
668
+ "name": "Psychologist",
669
+ "description": "Specializes in psychological assessment and evidence-based therapy.",
670
+ "image": "https://cdn-icons-png.flaticon.com/512/1154/1154480.png" # Male psychologist
671
+ },
672
+ {
673
+ "name": "Best Friend",
674
+ "description": "Supportive and understanding friend for general concerns and casual conversations.",
675
+ "image": "https://cdn-icons-png.flaticon.com/512/1154/1154462.png" # New female best friend
676
+ }
677
+ ]
678
+
679
+
680
+
681
+ # Callback functions
682
+ def open_session(session_id):
683
+ st.session_state['current_session'] = session_id
684
+
685
+ def remove_session(session_id):
686
+ delete_session(session_id)
687
+ st.session_state['sessions'] = load_sessions()
688
+ if st.session_state['current_session'] == session_id:
689
+ st.session_state['current_session'] = None
690
+
691
+ def select_therapist(therapist_name):
692
+ st.session_state['selected_therapist'] = therapist_name
693
+
694
+ # Save conversation to a downloadable format
695
+ def save_conversation_to_file(conversation, filename):
696
+ with open(filename, 'w') as f:
697
+ for message in conversation:
698
+ if isinstance(message, HumanMessage):
699
+ f.write(f"User: {message.content}\n")#save message.content to file
700
+ elif isinstance(message, AIMessage):
701
+ f.write(f"Bot: {message.content}\n")
702
+
703
+ # Function to summarize the conversation using the chat model
704
+ def summarize_conversation(messages):
705
+ conversation_text = "\n".join([f"User: {msg.content}" if isinstance(msg, HumanMessage) else f"Bot: {msg.content}" for msg in messages])
706
+ summary_prompt = f"Summarize the following conversation:\n\n{conversation_text}"
707
+ summary_response = chat([SystemMessage(content=summary_prompt)])
708
+ return summary_response.content.strip()
709
+
710
+ # Generate insights for the selected session
711
+ def generate_insights(session):
712
+ messages = session['messages']
713
+ if not messages:
714
+ return "No messages to summarize.", pd.DataFrame()
715
+
716
+ conversation_summary = summarize_conversation(messages)
717
+
718
+ mood_labels = ['Positive', 'Neutral', 'Negative']
719
+ mood_counts = [0, 0, 0]
720
+ for message in messages:
721
+ if isinstance(message, HumanMessage):
722
+ content = message.content.lower()
723
+ if any(word in content for word in ['happy', 'good', 'great', 'awesome']):
724
+ mood_counts[0] += 1
725
+ elif any(word in content for word in ['okay', 'fine', 'alright', 'normal']):
726
+ mood_counts[1] += 1
727
+ elif any(word in content for word in ['sad', 'bad', 'terrible', 'awful']):
728
+ mood_counts[2] += 1
729
+
730
+ mood_data = [count if count != 0 else 0.1 for count in mood_counts] # Ensure no NaNs
731
+ mood_df = pd.DataFrame({
732
+ 'Mood': mood_labels,
733
+ 'Count': mood_data
734
+ })
735
+
736
+ return conversation_summary, mood_df
737
+
738
+ if page == "Today":
739
+ # CSS Injection
740
+ st.markdown('''
741
+ <style>
742
+ @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap');
743
+
744
+ body {
745
+ font-family: 'Poppins', sans-serif;
746
+ color: #333;
747
+ }
748
+
749
+ .stApp {
750
+ background: linear-gradient(135deg, #f6d365 0%, #fda085 100%);
751
+ }
752
+
753
+ .today-page {
754
+ max-width: 1200px;
755
+ margin: 0 auto;
756
+ padding: 2rem;
757
+ }
758
+
759
+ .today-page .header {
760
+ text-align: center;
761
+ margin-bottom: 3rem;
762
+ animation: fadeInDown 1s ease-out;
763
+ }
764
+
765
+ @keyframes fadeInDown {
766
+ from { opacity: 0; transform: translateY(-30px); }
767
+ to { opacity: 1; transform: translateY(0); }
768
+ }
769
+
770
+ .today-page .header h1 {
771
+ font-size: 3.5rem;
772
+ color: #ff6b6b;
773
+ margin-bottom: 1rem;
774
+ text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
775
+ }
776
+
777
+ .today-page .header p {
778
+ font-size: 1.3rem;
779
+ color: #4a4a4a;
780
+ max-width: 800px;
781
+ margin: 0 auto;
782
+ line-height: 1.6;
783
+ }
784
+
785
+ .today-page .content {
786
+ display: flex;
787
+ justify-content: space-around;
788
+ flex-wrap: wrap;
789
+ }
790
+
791
+ .today-page .card {
792
+ background-color: #ffffff;
793
+ border-radius: 20px;
794
+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
795
+ padding: 2rem;
796
+ margin: 1rem;
797
+ text-align: center;
798
+ transition: all 0.3s ease;
799
+ width: 300px;
800
+ overflow: hidden;
801
+ position: relative;
802
+ }
803
+
804
+ .today-page .card::before {
805
+ content: '';
806
+ position: absolute;
807
+ top: -50%;
808
+ left: -50%;
809
+ width: 200%;
810
+ height: 200%;
811
+ background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.3), transparent);
812
+ transform: rotate(45deg);
813
+ transition: all 0.5s ease;
814
+ }
815
+
816
+ .today-page .card:hover::before {
817
+ left: 100%;
818
+ top: 100%;
819
+ }
820
+
821
+ .today-page .card:hover {
822
+ transform: translateY(-10px) scale(1.02);
823
+ box-shadow: 0 15px 40px rgba(0, 0, 0, 0.2);
824
+ }
825
+
826
+ .today-page .card img {
827
+ max-width: 100%;
828
+ border-radius: 15px;
829
+ margin-bottom: 1.5rem;
830
+ transition: all 0.3s ease;
831
+ }
832
+
833
+ .today-page .card:hover img {
834
+ transform: scale(1.1);
835
+ }
836
+
837
+ .today-page .card h3 {
838
+ font-size: 1.8rem;
839
+ color: #2c3e50;
840
+ margin-bottom: 1rem;
841
+ }
842
+
843
+ .today-page .card p {
844
+ font-size: 1.1rem;
845
+ color: #7f8c8d;
846
+ margin-bottom: 1.5rem;
847
+ }
848
+
849
+ .today-page .card-button {
850
+ background-color: #4facfe;
851
+ color: #ffffff;
852
+ border: none;
853
+ border-radius: 25px;
854
+ padding: 0.75rem 1.5rem;
855
+ font-size: 1rem;
856
+ font-weight: 600;
857
+ transition: all 0.3s ease;
858
+ text-decoration: none;
859
+ display: inline-block;
860
+ }
861
+
862
+ .today-page .card-button:hover {
863
+ background-color: #00f2fe;
864
+ transform: translateY(-2px);
865
+ box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
866
+ }
867
+
868
+ .emoji {
869
+ font-size: 2.5rem;
870
+ margin-bottom: 1rem;
871
+ }
872
+
873
+ /* Custom card colors */
874
+ .card-wellness { background: linear-gradient(135deg, #c3ec52 0%, #0ba29d 100%); }
875
+ .card-support { background: linear-gradient(135deg, #13f1fc 0%, #0470dc 100%); }
876
+ .card-selfcare { background: linear-gradient(135deg, #f6d365 0%, #fda085 100%); }
877
+
878
+ .card-wellness .card-button { background-color: #0ba29d; }
879
+ .card-wellness .card-button:hover { background-color: #c3ec52; color: #333; }
880
+
881
+ .card-support .card-button { background-color: #0470dc; }
882
+ .card-support .card-button:hover { background-color: #13f1fc; color: #333; }
883
+
884
+ .card-selfcare .card-button { background-color: #fda085; }
885
+ .card-selfcare .card-button:hover { background-color: #f6d365; color: #333; }
886
+ </style>
887
+ ''', unsafe_allow_html=True)
888
+
889
+ # HTML Content
890
+ st.markdown('''
891
+ <div class="today-page">
892
+ <div class="header">
893
+ <h1>Welcome to MindMate πŸ§ πŸ’–</h1>
894
+ <p>Your digital wellness companion. Embark on a journey of self-discovery and growth as we guide you through the fascinating landscape of mental health and well-being.</p>
895
+ </div>
896
+ <div class="content">
897
+ <div class="card card-wellness">
898
+ <div class="emoji">🌟</div>
899
+ <img src="https://images.unsplash.com/photo-1544367567-0f2fcb009e0b?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80" alt="Wellness">
900
+ <h3>Understanding Mental Health</h3>
901
+ <p>Unlock the secrets of your mind and learn how mental health shapes your daily life.</p>
902
+ <a href="#" class="card-button">Explore Wellness</a>
903
+ </div>
904
+ <div class="card card-support">
905
+ <div class="emoji">🀝</div>
906
+ <img src="https://images.unsplash.com/photo-1573497019940-1c28c88b4f3e?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80" alt="Support">
907
+ <h3>Finding Support</h3>
908
+ <p>Discover a network of care, from professional guidance to heartwarming personal connections.</p>
909
+ <a href="#" class="card-button">Get Support</a>
910
+ </div>
911
+ <div class="card card-selfcare">
912
+ <div class="emoji">🌼</div>
913
+ <img src="https://images.unsplash.com/photo-1487528278747-ba99ed528ebc?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80" alt="Self-care">
914
+ <h3>Self-Care Tips</h3>
915
+ <p>Nurture your mind and soul with practical strategies for everyday mental wellness.</p>
916
+ <a href="#" class="card-button">Practice Self-Care</a>
917
+ </div>
918
+ </div>
919
+ </div>
920
+ ''', unsafe_allow_html=True)
921
+
922
+ elif page == "Sessions":
923
+ st.subheader("Sessions")
924
+
925
+ new_session_card = '''
926
+ <div class="new-session-card" onclick="document.querySelector('button#start_new_session').click()">
927
+ <div class="new-session-icon">βž•</div>
928
+ <div class="new-session-text">Start a new session</div>
929
+ </div>
930
+ '''
931
+ st.markdown(new_session_card, unsafe_allow_html=True)
932
+ if st.button("Start a new session", key="start_new_session"):
933
+ new_session = {
934
+ "title": "Untitled Session",
935
+ "subtitle": "New session",
936
+ "time": time.strftime("%H:%M %p"),
937
+ "messages": []
938
+ }
939
+ new_session_id = add_session(new_session)
940
+ new_session['id'] = new_session_id
941
+ st.session_state['sessions'].append(new_session)
942
+ st.session_state['current_session'] = new_session_id
943
+ st.experimental_rerun()
944
+
945
+ session_columns = st.columns(3)
946
+ for index, session in enumerate(st.session_state['sessions']):
947
+ col = session_columns[index % 3]
948
+ with col:
949
+ st.markdown(f'''
950
+ <div class="session-card">
951
+ <div class="session-info">
952
+ <div class="session-title">{session["title"]}</div>
953
+ <div class="session-subtitle">{session["subtitle"]}</div>
954
+ <div class="session-time">πŸ•’ {session["time"]}</div>
955
+ </div>
956
+ <div class="buttons">
957
+ ''', unsafe_allow_html=True)
958
+ if st.button("Open", key=f"open_{session['id']}"):
959
+ open_session(session['id'])
960
+ st.experimental_rerun()
961
+ if st.button("Delete", key=f"delete_{session['id']}"):
962
+ remove_session(session['id'])
963
+ st.experimental_rerun()
964
+ st.markdown('</div></div>', unsafe_allow_html=True)
965
+
966
+ if st.session_state['current_session'] is not None:
967
+ session = next((s for s in st.session_state['sessions'] if s['id'] == st.session_state['current_session']), None)
968
+ if session:
969
+ st.subheader("Chat")
970
+
971
+ # Language selection
972
+ languages = {"English": "en", "Spanish": "es", "French": "fr", "German": "de", "Chinese": "zh","Hindi":"hi"}
973
+ selected_language = st.selectbox("Select Language", list(languages.keys()), index=0)
974
+ language = languages[selected_language]
975
+
976
+ # Select the appropriate prompt template based on the selected therapist
977
+ selected_therapist = st.session_state.get('selected_therapist', 'Counsellor')
978
+ therapist_template = therapist_templates.get(selected_therapist, therapist_templates['Counsellor'])
979
+
980
+ CUSTOM_PROMPT = PromptTemplate.from_template(therapist_template)
981
+ # Initialize conversation memory
982
+ if 'flowmessages' not in session:
983
+ session['flowmessages'] = [
984
+ SystemMessage(content=f"Hey there! I'm {selected_therapist}, your AI mental health assistant. How are you feeling?")
985
+ ]
986
+
987
+ memory = ConversationBufferWindowMemory(k=5, return_messages=True)
988
+
989
+ def get_chatmodel_response(question):
990
+ session['flowmessages'].append(HumanMessage(content=question))
991
+ memory.save_context({"input": question}, {"output": ""}) # Save the input question to memory
992
+ chat_history = "\n".join([f"User: {msg.content}" if isinstance(msg, HumanMessage) else f"Bot: {msg.content}" for msg in session['flowmessages']])
993
+ prompt = CUSTOM_PROMPT.format(chat_history=chat_history, user_message=question, language=language)
994
+ messages = [SystemMessage(content=prompt)]
995
+ # Use st.session_state['chat'] here
996
+ answer = st.session_state['chat'](messages) # Pass list of messages to chat
997
+ session['flowmessages'].append(AIMessage(content=answer.content)) # Adjusted to handle response properly
998
+ save_session(session) # Ensure session is saved after adding new messages
999
+ return answer.content
1000
+
1001
+
1002
+ input = st.text_input("Input: ", key="input")
1003
+ submit = st.button("Ask the question")
1004
+
1005
+ if submit:
1006
+ response = get_chatmodel_response(input)
1007
+ save_session(session)
1008
+ st.experimental_rerun()
1009
+ if "flowmessages" in session:
1010
+ st.subheader("Chat")
1011
+ for message in session['flowmessages']:
1012
+ if isinstance(message, HumanMessage):
1013
+ st.write(user_template.replace("{{MSG}}", message.content), unsafe_allow_html=True)
1014
+ elif isinstance(message, AIMessage):
1015
+ st.write(bot_template.replace("{{MSG}}", message.content), unsafe_allow_html=True)
1016
+
1017
+ # Session rename functionality
1018
+ new_title = st.text_input("Rename session:", value=session["title"])
1019
+ if st.button("Rename"):
1020
+ session["title"] = new_title
1021
+ save_session(session)
1022
+ st.experimental_rerun()
1023
+
1024
+ # Save conversation to file
1025
+ if st.button("Download Conversation"):
1026
+ filename = f"{session['title']}.txt"
1027
+ save_conversation_to_file(session['flowmessages'], filename)
1028
+ with open(filename, 'rb') as file:
1029
+ st.download_button(
1030
+ label="Download Conversation",
1031
+ data=file,
1032
+ file_name=filename,
1033
+ mime='text/plain'
1034
+ )
1035
+
1036
+ # Define other tool functions here...
1037
+ def breathing_exercise():
1038
+ st.markdown("""
1039
+ <style>
1040
+ .breathing-page {
1041
+ display: flex;
1042
+ flex-direction: column;
1043
+ align-items: center;
1044
+ justify-content: center;
1045
+ height: 100vh;
1046
+ background: linear-gradient(45deg, #ff9a9e, #fad0c4, #ffecd2);
1047
+ text-align: center;
1048
+ }
1049
+ .breathing-text {
1050
+ font-size: 48px;
1051
+ color: #333;
1052
+ font-weight: bold;
1053
+ text-shadow: 1px 1px 2px rgba(255,255,255,0.5);
1054
+ }
1055
+ .breathing-circle {
1056
+ width: 300px;
1057
+ height: 300px;
1058
+ border-radius: 50%;
1059
+ background: radial-gradient(circle, #ffffff, #f0f0f0);
1060
+ box-shadow: 0 0 50px rgba(255,255,255,0.8);
1061
+ animation: pulse 8s infinite;
1062
+ display: flex;
1063
+ align-items: center;
1064
+ justify-content: center;
1065
+ margin-bottom: 20px;
1066
+ }
1067
+ @keyframes pulse {
1068
+ 0%, 100% { transform: scale(1); }
1069
+ 50% { transform: scale(1.2); }
1070
+ }
1071
+ </style>
1072
+ """, unsafe_allow_html=True)
1073
+
1074
+ breathing_container = st.empty()
1075
+
1076
+ total_duration = 5 * 60 # 5 minutes in seconds
1077
+ phase_duration = 12 # 4 seconds for each phase: inhale, hold, exhale
1078
+ phases = ["Breathe in...", "Hold...", "Breathe out..."]
1079
+
1080
+ for _ in range(total_duration // phase_duration):
1081
+ for text in phases:
1082
+ with breathing_container.container():
1083
+ st.markdown('<div class="breathing-page">', unsafe_allow_html=True)
1084
+ st.markdown(f'<div class="breathing-circle"><p class="breathing-text">{text}</p></div>', unsafe_allow_html=True)
1085
+ st.markdown('</div>', unsafe_allow_html=True)
1086
+ time.sleep(4) # Duration for each phase
1087
+
1088
+ with breathing_container.container():
1089
+ st.markdown('<div class="breathing-page">', unsafe_allow_html=True)
1090
+ st.markdown('<div class="breathing-circle"><p class="breathing-text">Great job! Feel relaxed and refreshed.</p></div>', unsafe_allow_html=True)
1091
+ st.markdown('</div>', unsafe_allow_html=True)
1092
+
1093
+ time.sleep(3)
1094
+ breathing_container.empty()
1095
+
1096
+ if page == "Tools":
1097
+ st.subheader("Tools")
1098
+ st.write("Each tool is an interactive exercise based on cognitive-behavioral therapy and enhanced by the power of AI.")
1099
+
1100
+ tools = [
1101
+ {"title": "Mindfulness", "description": "Breathing exercise for anxiety and stress relief", "time": "5 minutes"},
1102
+ {"title": "\"Perfect day\"", "description": "Discover ways to enhance your daily routine and improve the quality of life", "time": "13 minutes"},
1103
+ {"title": "Goal setting", "description": "Transform your issues and shortcomings into opportunities", "time": "22 minutes"},
1104
+ {"title": "Boundaries", "description": "Separate your own values and priorities from those imposed on you", "time": "23 minutes"},
1105
+ {"title": "Time awareness", "description": "Learn how to spend your time on what matters most", "time": "14 minutes"},
1106
+ {"title": "Descartes square", "description": "Examine hidden pros and cons to be sure you make the right decision", "time": "9 minutes"},
1107
+ ]
1108
+
1109
+ tool_columns = st.columns(3)
1110
+ for index, tool in enumerate(tools):
1111
+ col = tool_columns[index % 3]
1112
+ with col:
1113
+ st.markdown(f'''
1114
+ <div class="tool-card">
1115
+ <div class="tool-title">{tool["title"]}</div>
1116
+ <div class="tool-description">{tool["description"]}</div>
1117
+ <div class="tool-time">πŸ•’ {tool["time"]}</div>
1118
+ </div>
1119
+ ''', unsafe_allow_html=True)
1120
+ if st.button(f"Let's Go {index}", key=f"button_{index}"):
1121
+ if tool["title"] == "Mindfulness":
1122
+ breathing_exercise()
1123
+ else:
1124
+ st.write(f"{tool['title']} tool is not yet implemented.")
1125
+
1126
+ elif page == "Therapists":
1127
+ st.subheader("Choose Your Therapist")
1128
+ st.write("Select a therapist to guide you through your mental health journey !")
1129
+
1130
+ therapist_columns = st.columns(2)
1131
+ for index, therapist in enumerate(therapists):
1132
+ col = therapist_columns[index % 2]
1133
+ with col:
1134
+ st.markdown(f'''
1135
+ <div class="therapist-card">
1136
+ <img src="{therapist["image"]}" alt="{therapist["name"]}">
1137
+ <div class="therapist-name">{therapist["name"]}</div>
1138
+ <div class="therapist-description">{therapist["description"]}</div>
1139
+ <button class="select-button" onclick="alert('Selected {therapist["name"]}')">Select</button>
1140
+ </div>
1141
+ ''', unsafe_allow_html=True)
1142
+ if st.button(f"Select {therapist['name']}", key=f"select_{therapist['name']}"):
1143
+ select_therapist(therapist['name'])
1144
+ st.experimental_rerun()
1145
+
1146
+ elif page == "Insights":
1147
+ st.subheader("Insights")
1148
+
1149
+ session_titles = [session["title"] for session in st.session_state['sessions']]
1150
+ selected_session_title = st.selectbox("Select a session", session_titles)
1151
+
1152
+ if selected_session_title:
1153
+ selected_session = next(session for session in st.session_state['sessions'] if session["title"] == selected_session_title)
1154
+ print(f"Selected session for insights: {selected_session}") # Debug statement
1155
+
1156
+ if selected_session and 'messages' in selected_session:
1157
+ st.write(f"Messages: {selected_session['messages']}")
1158
+ conversation_summary, mood_df = generate_insights(selected_session)
1159
+
1160
+ st.markdown("### Conversation Summary")
1161
+ st.write(conversation_summary)
1162
+
1163
+ if not mood_df.empty:
1164
+ st.markdown("### Mood Analysis")
1165
+ fig, ax = plt.subplots()
1166
+ ax.pie(mood_df['Count'], labels=mood_df['Mood'], autopct='%1.1f%%', startangle=90, colors=['#4CAF50', '#FFC107', '#F44336'])
1167
+ ax.axis('equal')
1168
+ st.pyplot(fig)
1169
+
1170
+ st.markdown("### Mood Over Time")
1171
+ mood_timeline = pd.Series([msg.content.lower() for msg in selected_session['messages'] if isinstance(msg, HumanMessage)]).apply(
1172
+ lambda x: 1 if any(word in x for word in ['happy', 'good', 'great', 'awesome']) else (
1173
+ 0 if any(word in x for word in ['okay', 'fine', 'alright', 'normal']) else -1
1174
+ )
1175
+ )
1176
+ mood_timeline.index = pd.to_datetime(mood_timeline.index, unit='s')
1177
+ mood_timeline_df = mood_timeline.reset_index()
1178
+ mood_timeline_df.columns = ['Time', 'Mood']
1179
+ st.line_chart(mood_timeline_df.set_index('Time'))
1180
+ else:
1181
+ st.write("No mood data to display.")
1182
+ else:
1183
+ st.write("No messages to summarize.")
1184
+
1185
+
1186
+ elif page == "How to use?":
1187
+ st.subheader("How to use?")
1188
+
1189
+ # Embedding HTML content
1190
+ st.markdown(f'''
1191
+ <div class="how-to-use-page">
1192
+ <h2>How to use? πŸš€</h2>
1193
+ <p>Welcome to the Mental Health Support Chat Bot. Here's how to navigate and make the most out of this application:</p>
1194
+ <div class="section">
1195
+ <h3>πŸ“… Today Page:</h3>
1196
+ <ul>
1197
+ <li>Overview of mental health resources.</li>
1198
+ <li>Cards with information on understanding mental health, finding support, and self-care tips.</li>
1199
+ </ul>
1200
+ </div>
1201
+ <div class="section">
1202
+ <h3>πŸ—¨οΈ Sessions:</h3>
1203
+ <ul>
1204
+ <li>View all your chat sessions.</li>
1205
+ <li>Start a new session, open existing ones, or delete sessions you no longer need.</li>
1206
+ <li>In each session, you can chat with the AI and download conversation history.</li>
1207
+ </ul>
1208
+ </div>
1209
+ <div class="section">
1210
+ <h3>πŸ› οΈ Tools:</h3>
1211
+ <ul>
1212
+ <li>Interactive exercises based on cognitive-behavioral therapy.</li>
1213
+ <li>Use these tools to solve problems, set goals, and more.</li>
1214
+ </ul>
1215
+ </div>
1216
+ <div class="section">
1217
+ <h3>πŸ‘₯ Therapists:</h3>
1218
+ <ul>
1219
+ <li>Choose an AI therapist that best suits your needs.</li>
1220
+ <li>Each therapist has a unique approach and style.</li>
1221
+ </ul>
1222
+ </div>
1223
+ <div class="section">
1224
+ <h3>πŸ“Š Insights:</h3>
1225
+ <ul>
1226
+ <li>Analyze your chat sessions.</li>
1227
+ <li>View summaries and mood analysis over time.</li>
1228
+ </ul>
1229
+ </div>
1230
+ <div class="section">
1231
+ <h3>βš™οΈ Settings:</h3>
1232
+ <ul>
1233
+ <li>Configure your preferences and application settings.</li>
1234
+ </ul>
1235
+ </div>
1236
+ <p>If you have any questions, feel free to ask!</p>
1237
+ </div>
1238
+ ''', unsafe_allow_html=True)
1239
+
1240
+ else:
1241
+ st.subheader(f"{page} Page")
1242
+ st.write(f"This is the {page} page.")