Strong1Mindtherapist commited on
Commit
d00fa1c
Β·
verified Β·
1 Parent(s): a96ecda

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +255 -316
app.py CHANGED
@@ -4,7 +4,9 @@ import json
4
  import datetime
5
  import gradio as gr
6
 
7
- # User data
 
 
8
  user_info = {"name": "", "age": "", "gender": "", "language": "english" , "Guardian_info": ""}
9
  chat_history = []
10
  journal_entries = []
@@ -31,54 +33,14 @@ lang_codes = {
31
  "french": "fr", "german": "de"
32
  }
33
 
34
- # List of harmful or dangerous keywords
35
  harmful_keywords = [
36
- "abomination", "annihilate", "arson", "ass", "assault", "atrocity",
37
- "backstab", "barbaric", "barbarian", "beast", "belittle", "berserk",
38
- "betray", "betrayal", "bigot", "blacklist", "blood", "bloodbath",
39
- "bloody", "bomb", "bonehead", "brainless", "brutal", "brute", "burn",
40
- "butcher", "cage", "callous", "cancer", "chaos", "cheater", "cold-blooded",
41
- "conman", "corrupt", "cowardly", "crash", "crime", "criminality", "crook",
42
- "cruel", "cruelty", "curseword", "damage", "danger", "dangerous", "deadly",
43
- "deceive", "defame", "defeat", "degenerate", "demon", "despise", "destroy",
44
- "destruction", "destructive", "devastate", "devil", "diabolical", "dictator",
45
- "dirty", "disaster", "dishonor", "disrespect", "disturb", "divisive", "drunk",
46
- "dumbass", "dungeon", "enemies", "enemy", "enrage", "evilness", "exile",
47
- "exploit", "exterminate", "fake", "fanatic", "fascist", "fatal", "fire",
48
- "forgery", "fraud", "fraudster", "freakish", "gang", "gangster", "ghastly",
49
- "ghoul", "gory", "grotesque", "gruesome", "hag", "halfwit", "hardhearted",
50
- "harm", "hateable", "hateful", "havoc", "hell", "hellish", "heretic",
51
- "hideous", "horrid", "horrific", "hostility", "howl", "hypocrite", "illegal",
52
- "illicit", "immoral", "imposter", "injure", "insensitive", "insidious",
53
- "intolerant", "irate", "jerky", "joke", "joker", "kidnap", "killjoy", "liar",
54
- "loath", "loathsome", "lowlife", "madness", "malicious", "malign",
55
- "manipulate", "menace", "monster", "monstrous", "mug", "murderous",
56
- "mutant", "mutiny", "nasty", "nefarious", "neglect", "negative", "offend",
57
- "offender", "ominous", "oppress", "outrage", "outrageous", "parasite",
58
- "penalty", "perish", "pest", "plague", "poison", "poisonous", "pollute",
59
- "psychopath", "punch", "punish", "punishment", "quarrel", "rage", "rat",
60
- "rebellion", "reckless", "repel", "repulsive", "revolt", "revolting",
61
- "rioter", "rob", "robber", "rotten", "ruin", "savage", "scare", "scary",
62
- "schemer", "scold", "scorn", "scoundrel", "scream", "screwed", "serpent",
63
- "shady", "sham", "shameful", "shatter", "shocking", "sin", "sinister",
64
- "slavey", "slimy", "smash", "smite", "snob", "spite", "spiteful", "stab",
65
- "stench", "stink", "strike", "subvert", "suspicious", "target", "tease",
66
- "terrible", "terrify", "thief", "threat", "threaten", "thug", "torment",
67
- "torture", "trap", "trick", "trigger", "trouble", "uncivilized", "undermine",
68
- "unfair", "unjust", "unkind", "usurper", "vandal", "vandalize", "venom",
69
- "venomous", "villain", "villainous", "vindictive", "violent", "viper",
70
- "vulgarity", "war", "warmonger", "waste", "wickedness", "wild", "wound",
71
- "wrath", "wreck", "wrong", "yell", "zombie","suicide", "kill myself", "end my life", "harm myself", "cut myself",
72
- "want to die", "die", "jump off", "self-harm"
73
- "suicide", "kill myself", "end my life", "harm myself", "cut myself",
74
- "want to die", "die", "jump off", "self-harm", "give up", "not worth it",
75
- "ending it all", "self-hate", "suicidal", "tragic", "trauma", "pain",
76
- "painful", "sorrow",
77
- "unworthy", "hurt", "grief", "agony", "doom", "doomed"
78
-
79
  ]
80
 
81
- # Harmful word detection response
82
  harmful_response = (
83
  "⚠️ It sounds like you're going through a really tough time.\n\n"
84
  "Please reach out to a professional:\n\n"
@@ -93,284 +55,260 @@ harmful_response = (
93
  "You are not alone. There are people who care and want to help πŸ’š"
94
  )
95
 
96
- # Simplified emotions dictionary
97
  emotions = {
98
- "sad": "I hear you πŸ’™. I’m really sorry you’re feeling sad right now.Do you want to tell me what’s making you feel this way, or would you rather I just try to gently cheer you up?Here are a few small things that sometimes help when sadness feels heavy:🌬️ Take 3 deep, slow breaths β€” it really calms the body.✍️ Write down what you’re feeling in a notebook (or even here with me). Sometimes just letting it out helps.🎧 Put on a calming or favorite song β€” music can shift your mood more than we realize.🌳 Step outside for 5 minutes and notice something simple in nature, like the sky, trees, or birds.πŸ’‘ You don’t have to fight sadness alone β€” it’s okay to feel it and also okay to lean on others when it’s too much.",
99
- "anxiety": "It’s okay β€” anxiety can feel overwhelming, like your mind is running a race it didn’t sign up for.Try slowing down your breathing: inhale for 4 seconds, hold for 4, exhale for 6.Your thoughts are not facts β€” they’re just passing clouds, and you are the sky.",
100
- "angry": "It’s normal to feel angry β€” it’s your mind’s way of telling you something feels unfair or hurtful.Before reacting, give yourself space: take a deep breath, unclench your jaw, and let your shoulders drop.Once you feel calmer, you can decide how to express your feelings in a way that helps, not hurts.",
101
- "lonely": "You are not alone. Talking helps β€” I’m here to listen.",
102
- "rejected": "Rejection hurts but it doesn’t define your worth.",
103
- "exams": "Plan short sessions with breaks. You can do this!",
104
- "parents": "Family pressure is real. Want to talk more about it?",
105
- "money": "Finances are tough, but your value isn’t tied to them.",
106
- "too much": "Pause. Let’s break it into small steps.",
107
- "friend": "Friendship can be tricky. Want to share what happened?",
108
- "love": "Love is powerful β€” and sometimes painful. I’m here to help you reflect.",
109
- "forced": "You don’t have to do what doesn’t feel right.",
110
- "compare": "You’re unique. Comparison steals joy.",
111
- "numb": "It’s okay to feel nothing. Let’s gently bring you back.",
112
- "instagram": "Let’s take a small break from social media together.",
113
- "pretend": "You don’t need to pretend here. Be real, be you.",
114
- "bullied": "You don’t deserve this. You are strong and valuable.",
115
- "misunderstood": "That can feel frustrating. I understand you.",
116
- "rainy": "Rainy days can be gloomy. A warm drink and chat may help.",
117
- "unwell": "Rest, hydrate, and be kind to yourself today.",
118
- "overthink": "Let’s try to focus on what’s in your control.",
119
- "who am i": "Great question! Let’s explore that together.",
120
- "climate": "You care β€” and that’s powerful. Even small actions help.",
121
- "pointless": "Your life matters, even when it doesn’t feel like it.",
122
- "ignored": "You are seen and heard here. Let’s talk.",
123
- "can’t sleep": "Try breathing deeply. Would soft music help?",
124
- "stuck": "Let’s look at one thing we *can* do today.",
125
- "hopeless": "Even small steps forward are progress. Hope grows.",
126
- "depressed": "You’re not alone in this. Let’s talk through it.",
127
- "scared": "Let’s face this together, one moment at a time.",
128
- "afraid": "Fear shows you care. Let’s understand it better.",
129
- "confused": "It’s okay not to have all the answers yet.",
130
- "guilty": "Guilt teaches us. Let’s grow from it, not drown in it.",
131
- "ashamed": "You are more than your mistakes.",
132
- "failure": "Failure means you tried. That’s strength.",
133
- "panic": "Breathe with me. Ground yourself. You are okay.",
134
- "stressed": "Let’s identify your stress and sort it gently.",
135
- "bored": "Want to do something fun or creative together?",
136
- "insecure": "You have strengths worth celebrating.",
137
- "uncertain": "Uncertainty is part of growth. Let’s navigate it.",
138
- "worried": "What are you worried about? Let’s untangle it.",
139
- "homesick": "It’s okay to miss home. What comforts you?",
140
- "crying": "Crying is healing. Let it out if needed.",
141
- "jealous": "Let’s explore what you truly desire.",
142
- "envy": "You can build your own journey. You’re enough.",
143
- "hate": "Let’s turn that strong emotion into understanding.",
144
- "bitterness": "Bitterness is heavy. Want to release some of it?",
145
- "regret": "We all have regrets. What can we learn from yours?",
146
- "betrayed": "That hurts deeply. Let’s process it together.",
147
- "heartbroken": "Healing takes time. Let’s take the first step.",
148
- "alone": "You’re not alone here. I’m right with you.",
149
- "trapped": "There’s always a way out. Let’s look for options.",
150
- "disappointed": "Disappointment is valid. Let’s reflect and reset.",
151
- "pressured": "You don’t have to carry it all. Let’s prioritize.",
152
- "unloved": "You are lovable. Truly. Start with self-kindness.",
153
- "exhausted": "Rest. That’s productive too.",
154
- "withdrawn": "It’s okay to pull back. But don’t shut out support.",
155
- "disrespected": "Respect matters. You deserve it.",
156
- "avoided": "You matter. Let’s talk about what happened.",
157
- "insomnia": "Let’s try a gentle nighttime routine.",
158
- "neglected": "You deserve care and attention.",
159
- "nervous": "New things are scary. But you’re capable.",
160
- "frustrated": "Let’s release that pressure gently.",
161
- "humiliated": "That experience doesn’t define you.",
162
- "unimportant": "You matter. Just by being you.",
163
- "abandoned": "That’s painful. You’re not alone anymore.",
164
- "defeated": "You’re still here. That’s strength.",
165
- "shy": "Quiet doesn’t mean weak. Your voice matters.",
166
- "paranoid": "Let’s ground our thoughts in facts and truth.",
167
- "restless": "Let’s find a healthy outlet together.",
168
- "gloomy": "Let’s look for a little light together.",
169
- "anxious": "Let’s name the worry, then tame it.",
170
- "worthless": "You are worthy β€” of love, peace, and joy.",
171
- "invisible": "I see you. You matter.",
172
- "lethargic": "Small movement helps. Try stretching.",
173
- "annoyed": "Want to vent? I’m listening.",
174
- "fomo": "It’s okay not to do everything. Your pace is right.",
175
- "peer pressure": "Your choices are your own. Stand strong.",
176
- "embarrassed": "Everyone messes up sometimes. Let it go.",
177
- "unappreciated": "I appreciate you. Let’s celebrate your efforts.",
178
- "hollow": "You may feel empty now β€” but you’re not.",
179
- "resentful": "Let’s process it before it poisons your peace.",
180
- "in pain": "Pain hurts, but talking eases it. Let’s talk.",
181
- "drained": "Rest is fuel. It’s okay to pause.",
182
- "moody": "Moods pass. Let’s ride this one out together.",
183
- "isolated": "Let’s reconnect β€” even one small step helps.",
184
- "fake": "You can be real here. No masks.",
185
- "mentally tired": "Mental fatigue is real. Let’s rest and reset.",
186
- "broken": "Cracks let the light in. You’re still whole inside.",
187
- "crushed": "That sounds painful. Let’s unpack it together.",
188
- "troubled": "Name the trouble, then tame it. I’m here.",
189
- "underestimated": "You are more than they think. Show them. Gently.",
190
- "burned out": "Burnout needs healing. Step back to move forward.",
191
- "stress" : "Take 3 deep breaths and relax your shoulders.",
192
- "stressful" : "Break tasks into smaller steps to feel less overwhelmed.",
193
- "anxiety" : "Focus on slow breathing for 5 minutes to calm your mind.",
194
- "panic" : "Ground yourself by naming 5 things you see around you.",
195
- "fear" : "Write down your fear and list why it may not be true.",
196
- "anger" : "Walk away for a moment and count to 10.",
197
- "rage" : "Listen to calming music to release intense anger.",
198
- "sadness" : "Call a friend or talk to someone who cares.",
199
- "grief" : "Allow yourself to cry and express your emotions.",
200
- "trauma" : "Practice grounding exercises like touching nearby objects.",
201
- "abuse" : "Remember, you deserve respectβ€”consider reaching out for help.",
202
- "depression" : "Take a short walk outside and notice nature.",
203
- "loneliness" : "Text someone you trust to connect.",
204
- "hopeless" : "Think of one small goal you can achieve today.",
205
- "exhausted" : "Drink water and rest for at least 10 minutes.",
206
- "overwhelmed" : "Make a priority list and focus on just 1 thing.",
207
- "nervous" : "Practice positive affirmations like 'I can handle this.'",
208
- "tired" : "Take a quick power nap if possible.",
209
- "fatigue" : "Stretch your body to release tension.",
210
- "burnout" : "Take a complete 10-minute break without screens.",
211
- "frustrated" : "Pause and do 5 deep breaths to regain focus.",
212
- "helpless" : "Ask for supportβ€”it's okay to seek help.",
213
- "confused" : "Write down your thoughts to organize them.",
214
- "worried" : "Challenge your thoughts by asking 'Is this likely to happen?'",
215
- "lost" : "Take one small step towards clarity, like making a to-do list.",
216
- "crying" : "Drink water and sit in a comfortable position to calm.",
217
- "heartbreak" : "Allow yourself to heal and talk to a trusted friend.",
218
- "guilt" : "Forgive yourself and remind yourself you are human.",
219
- "shame" : "Remind yourself that mistakes do not define you.",
220
- "fearful" : "Focus on your breathing for a few minutes.",
221
- "meltdown" : "Step away and try a 5-minute meditation.",
222
- "pressured" : "Break tasks into smaller, manageable chunks.",
223
- "uneasy" : "Listen to relaxing music or nature sounds.",
224
- "unmotivated" : "Start with one tiny task to build momentum.",
225
- "restless" : "Try a short physical activity like stretching.",
226
- "freaking" : "Count to 10 slowly to calm down.",
227
- "cry" : "Let your tears outβ€”it helps to release emotions.",
228
- "breakdown" : "Sit somewhere quiet and breathe deeply.",
229
- "fail" : "Remind yourself failure is part of learning.",
230
- "failure" : "Focus on what you can improve, not what you lost.",
231
- "pressure" : "Take breaks and drink water to refresh your mind.",
232
- "worry" : "Write down your worries and challenge them logically.",
233
- "trouble" : "Focus on one thing you can solve right now.",
234
- "numb" : "Take a walk outside to feel present.",
235
- "tense" : "Relax your shoulders and stretch for a minute.",
236
- "hurting" : "Talk to someone you trust about your pain.",
237
- "hurt" : "Be kind to yourself and allow healing time.",
238
- "broken" : "Remember that healing is slow but possible.",
239
- "tension" : "Roll your shoulders and take deep breaths.",
240
- "angry" : "Punch a pillow or squeeze a stress ball instead of yelling.",
241
- "pessimistic" : "List 3 things that went well today.",
242
- "scared" : "Remind yourself of times you overcame fear.",
243
- "worn-out" : "Take a 5-minute break and hydrate.",
244
- "mental pain" : "Talk about your feelings with a trusted person.",
245
- "emotional" : "Allow yourself to feel without judging your emotions.",
246
- "upset" : "Pause and do 10 slow breaths.",
247
- "low" : "Do something small that brings joy.",
248
- "bitter" : "Write down 3 positive things about your day.",
249
- "uneasiness" : "Practice slow and mindful breathing.",
250
- "tense" : "Try progressive muscle relaxation.",
251
- "tight" : "Do a gentle body stretch.",
252
- "stressed-out" : "Focus on what you can control right now.",
253
- "paranoid" : "Talk to someone to verify your fears.",
254
- "devastated" : "Give yourself time to heal.",
255
- "crybaby" : "Your tears are validβ€”let them flow.",
256
- "unhappy" : "List 1 thing that can make you smile.",
257
- "negative" : "Counter each negative thought with a positive one.",
258
- "hopelessness" : "Set one small achievable goal today.",
259
- "unsure" : "Write your pros and cons to gain clarity.",
260
- "self-doubt" : "Remind yourself of your past achievements.",
261
- "hurtful" : "Distance yourself from negativity for a while.",
262
- "unwell" : "Drink water and rest to recover.",
263
- "emotionless" : "Do something creative to spark feelings.",
264
- "lostness" : "Journal your thoughts for clarity.",
265
- "distress" : "Breathe in for 4 seconds, hold 4, out for 4.",
266
- "emergency" : "Call someone you trust immediately.",
267
- "unsettled" : "Meditate for 5 minutes on your breath.",
268
- "chaotic" : "Focus on organizing one small area around you.",
269
- "break" : "Take 10 minutes to step outside.",
270
- "unstable" : "Seek support from a friend or counselor.",
271
- "hopelessly" : "Remind yourself nothing lasts forever.",
272
- "pain" : "Try deep breathing or journaling about your pain.",
273
- "painful" : "Distract yourself with something positive.",
274
- "angsty" : "Express feelings through writing or art.",
275
- "uneasiness" : "Light a candle and focus on the flame for a minute.",
276
- "irritated" : "Do 5 deep breaths to calm irritation.",
277
- "frustration" : "Talk about your frustration instead of bottling it.",
278
- "exhaustion" : "Sleep for at least 15 minutes if possible.",
279
- "mental stress" : "Pause and take a few deep breaths.",
280
- "low mood" : "Listen to uplifting music.",
281
- "discouraged" : "Remind yourself of past successes.",
282
- "confusion" : "Pause, take a breath, and write down thoughts.",
283
- "overthinking" : "Distract yourself with a small physical activity.",
284
- "hurtful words" : "Remind yourself words don’t define your worth.",
285
- "traumatized" : "Seek safe space and talk about your feelings.",
286
- "frantic" : "Slow your breathing and count backwards from 10.",
287
- "chaos" : "Clean or organize something small around you.",
288
- "lost mind" : "Ground yourself by feeling the floor beneath you.",
289
- "hectic" : "Prioritize and focus on one task at a time.",
290
- "unbalanced" : "Sit and take 5 deep breaths.",
291
- "mentally tired" : "Close your eyes for 2 minutes and relax.",
292
- "self-blame" : "Remind yourself that mistakes happen to everyone.",
293
- "failure feeling" : "Focus on one thing you’ve done right today.",
294
- "feeling bad" : "Say one kind thing to yourself.",
295
- "worthless" : "Remember your value is not defined by others.",
296
- "helplessness" : "Ask for supportβ€”it’s a sign of strength.",
297
- "emotional pain" : "Talk to someone who cares about you.",
298
- "lack of energy" : "Stretch your arms and drink water.",
299
- "lack of sleep" : "Take a power nap of 10-20 minutes.",
300
- "mood swings" : "Track your mood to find triggers.",
301
- "frightened" : "Hold a comforting object and breathe slowly.",
302
- "self-hate" : "Replace self-criticism with self-kindness.",
303
- "negativity" : "Say one positive affirmation out loud.",
304
- "anxious" : "Practice slow inhaling and exhaling.",
305
- "feeling down" : "Do something you enjoy, even for 5 minutes.",
306
- "unstable mind" : "Pause, breathe, and write what you feel.",
307
- "uneasy feeling" : "Ground yourself by noticing your 5 senses.",
308
- "confusing" : "Write down questions to get clarity.",
309
- "worn out" : "Take a rest break with calm music.",
310
- "pressured" : "Let go of what’s not urgent.",
311
- "nervousness" : "Take 10 deep breaths slowly.",
312
- "mental exhaustion" : "Do a simple 5-min body stretch.",
313
- "crisis" : "Focus on what is in your control right now.",
314
- "melancholy" : "Write or draw to express feelings.",
315
- "mental breakdown" : "Sit down, close your eyes, and breathe.",
316
- "feeling weak" : "Remind yourself you’ve overcome challenges before.",
317
- "shaking" : "Sit still and breathe deeply for 2 minutes.",
318
- "mental fatigue" : "Take a short screen-free break.",
319
- "scared feelings" : "Tell yourself, 'This feeling will pass.'",
320
- "restless mind" : "Do 5 minutes of meditation or yoga.",
321
- "mind chaos" : "Write down your thoughts to clear your mind.",
322
- "uncertain" : "List your options and think calmly.",
323
- "self-harming thoughts" : "Reach out to someone you trust immediately.",
324
- "dark thoughts" : "Remember, you are not your thoughts.",
325
- "mental pressure" : "Pause and breathe for 5 deep breaths.",
326
- "losing hope" : "Focus on one good thing in your day.",
327
- "bad mood" : "Do something fun or silly for 5 minutes.",
328
- "pain inside" : "Talk to someone, don’t hold it in.",
329
- "numb feeling" : "Do a gentle self-massage on your hands.",
330
- "lack of motivation" : "Start with just 1 easy task.",
331
- "mind clutter" : "Write your thoughts on paper.",
332
- "feeling low" : "Listen to uplifting songs or affirmations.",
333
- "irritation" : "Pause and breathe deeply 3 times.",
334
- "disturbed" : "Sit somewhere quiet for 5 minutes.",
335
- "heavy heart" : "Talk about how you feel with someone.",
336
- "mental burden" : "Break it into small, manageable steps.",
337
- "scared mind" : "Repeat to yourself: 'I am safe now.'",
338
- "tension headache" : "Massage your temples gently.",
339
- "mind storm" : "Sit quietly and focus on one thought.",
340
- "mental struggle" : "Write a small gratitude note.",
341
- "mind fatigue" : "Do light stretches or walk for 5 minutes."
342
  }
343
 
344
- # Functions
345
- def set_personal_info(name, age, gender, language, Guardian_info):
346
- user_info.update({"name": name, "age": age, "gender": gender, "language": language, "Guardian_info": Guardian_info,})
347
- return gr.update(visible=True), f"βœ… Welcome {name}! Preferences saved."
 
 
 
 
 
348
 
349
- def show_personal_data():
350
- today = datetime.date.today().strftime("%Y-%m-%d (%A)")
351
- return f"πŸ“… {today}\nπŸ‘€ Name: {user_info['name']}\nπŸŽ‚ Age: {user_info['age']}\n♀ Gender: {user_info['gender']}\n🌐 Language: {user_info['language']}\n Guardian_info: {user_info['Guardian_info']}"
 
 
 
 
 
 
352
 
353
- def generate_reply(input_text):
354
- text = input_text.lower()
355
- for word in harmful_keywords:
356
- if word in text:
357
- return harmful_response
358
- for word, reply in emotions.items():
359
- if word in text:
360
- return reply
361
- return "Tell me more about your day."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
363
  def chat_function(audio_input, text_input):
364
- user_text = text_input.strip()
 
365
  if not user_text:
366
  return "Please type something.", None
 
367
  reply = generate_reply(user_text)
368
- chat_history.append({"user": user_text, "bot": reply})
 
 
 
 
369
  lang_code = lang_codes.get(user_info["language"], "en")
370
- tts = gTTS(reply, lang=lang_code)
371
- audio_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
372
- tts.save(audio_file.name)
373
- return reply, audio_file.name
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
374
 
375
  def get_chat_history():
376
  if not chat_history:
@@ -396,7 +334,9 @@ def next_study_tip():
396
  tip_index["study"] += 1
397
  return tip
398
 
399
- # -------------- Gradio App --------------
 
 
400
  with gr.Blocks() as app:
401
  welcome_screen = gr.Column(visible=True)
402
  full_app = gr.Tabs(visible=False)
@@ -431,7 +371,7 @@ with gr.Blocks() as app:
431
  }
432
  </style>
433
  """)
434
- gr.Markdown("<h1 id='main-title'>StrongMind Therapist 2.0</h1>")
435
  gr.Markdown("<h3 id='subtitle'>Your peaceful space to talk, journal, and focus.</h3>")
436
  start_button = gr.Button("🌸 Get Started", elem_id="start-btn")
437
 
@@ -464,7 +404,6 @@ with gr.Blocks() as app:
464
  bot_reply = gr.Textbox(label="🧠 Therapist")
465
  voice = gr.Audio(label="πŸ”Š Voice Reply")
466
  send.click(chat_function, [audio_input, text_input], [bot_reply, voice])
467
-
468
 
469
  with gr.Tab("4️⃣ Chat History"):
470
  show_history = gr.Button("πŸ“œ Show Chats")
 
4
  import datetime
5
  import gradio as gr
6
 
7
+ # ----------------------------
8
+ # User data & existing lists
9
+ # ----------------------------
10
  user_info = {"name": "", "age": "", "gender": "", "language": "english" , "Guardian_info": ""}
11
  chat_history = []
12
  journal_entries = []
 
33
  "french": "fr", "german": "de"
34
  }
35
 
36
+ # (Keep your harmful_keywords and emotions as-is β€” shortened here for clarity)
37
  harmful_keywords = [
38
+ # ... (keep the full list from your original file) ...
39
+ "suicide", "kill myself", "end my life", "harm myself", "cut myself",
40
+ "want to die", "die", "jump off", "self-harm", "self-hate", "suicidal",
41
+ # etc.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  ]
43
 
 
44
  harmful_response = (
45
  "⚠️ It sounds like you're going through a really tough time.\n\n"
46
  "Please reach out to a professional:\n\n"
 
55
  "You are not alone. There are people who care and want to help πŸ’š"
56
  )
57
 
58
+ # Simplified emotions dictionary (keep your full mapping; trimmed in this view)
59
  emotions = {
60
+ "sad": "I hear you πŸ’™. I’m really sorry you’re feeling sad right now. Do you want to tell me what’s making you feel this way, or would you rather I just try to gently cheer you up?",
61
+ "anxiety": "It’s okay β€” anxiety can feel overwhelming, like your mind is running a race it didn’t sign up for. Try slowing down your breathing: inhale for 4 seconds, hold for 4, exhale for 6.",
62
+ "angry": "It’s normal to feel angry β€” it’s your mind’s way of telling you something feels unfair or hurtful.",
63
+ # ... keep the rest of your emotion replies ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  }
65
 
66
+ # ----------------------------
67
+ # Conversation state for Hybrid (C) memory model
68
+ # ----------------------------
69
+ conversation_state = {
70
+ "emotion": None, # e.g., "sad"
71
+ "context": None, # e.g., "school", "parents", "friend", "exam"
72
+ "followup_stage": 0, # how many follow-ups we've done for this emotion
73
+ "turns_since_set": 0 # used to expire after a small idle period if needed
74
+ }
75
 
76
+ # Keywords to detect context quickly
77
+ context_markers = {
78
+ "school": ["school", "exam", "test", "teacher", "class"],
79
+ "parents": ["parent", "mom", "dad", "parents", "home"],
80
+ "friend": ["friend", "friends", "bully", "shouted", "argument", "fight"],
81
+ "health": ["sick", "unwell", "hospital", "doctor"],
82
+ "love": ["crush", "boyfriend", "girlfriend", "heartbroken", "love"],
83
+ # add more markers as needed
84
+ }
85
 
86
+ # Follow-up templates (3 steps each, then action suggestions)
87
+ followups = {
88
+ "sad": [
89
+ "I’m really sorry you’re feeling sad. Can you tell me if this happened recently or is it been building up?",
90
+ "Thank you for sharing. How did that make you feel β€” more hurt, embarrassed, or something else?",
91
+ "That sounds heavy. Would you like a calming exercise, to write about it in the journal, or to talk more?"
92
+ ],
93
+ "anxiety": [
94
+ "Anxiety can be overwhelming. Is it about something specific like exams or relationships?",
95
+ "When your anxiety spikes, do you notice physical signs like a racing heart or trouble breathing?",
96
+ "Would you like to try a short breathing exercise now, or do you want to talk about what’s triggering it?"
97
+ ],
98
+ "angry": [
99
+ "Anger is a valid response. Do you want to share what caused this anger?",
100
+ "When you feel angry, what usually helps β€” space, talking, or doing something active?",
101
+ "Would you like ideas to safely express the anger, or would you prefer calming techniques first?"
102
+ ],
103
+ # fallback for other emotions:
104
+ "default": [
105
+ "Tell me more about that β€” when did you start feeling this way?",
106
+ "How strong does this feeling feel on a scale of 1 to 10?",
107
+ "Would you like a calming activity, a journal prompt, or to continue talking?"
108
+ ]
109
+ }
110
+
111
+ # Reset phrases (user indicates they are fine or want to change topic)
112
+ reset_phrases = [
113
+ "i'm fine", "i am fine", "i'm okay", "i am okay", "i feel better",
114
+ "thank you", "thanks", "that's all", "let's talk about something else",
115
+ "stop", "no", "I'm good", "im good"
116
+ ]
117
 
118
+ # ----------------------------
119
+ # Helper functions
120
+ # ----------------------------
121
+ def _contains_any(text, keywords):
122
+ text = text.lower()
123
+ for kw in keywords:
124
+ if kw in text:
125
+ return True
126
+ return False
127
+
128
+ def detect_harmful(text):
129
+ t = text.lower()
130
+ for kw in harmful_keywords:
131
+ if kw in t:
132
+ return True
133
+ return False
134
+
135
+ def detect_emotion_in_text(text):
136
+ t = text.lower()
137
+ # Prefer longer keys first (to avoid 'sad' matching inside other words) β€” optional improvement
138
+ sorted_keys = sorted(emotions.keys(), key=lambda x: -len(x))
139
+ for key in sorted_keys:
140
+ if key in t:
141
+ return key
142
+ return None
143
+
144
+ def detect_context_in_text(text):
145
+ t = text.lower()
146
+ for ctx, markers in context_markers.items():
147
+ for m in markers:
148
+ if m in t:
149
+ return ctx
150
+ return None
151
+
152
+ def is_reset_phrase(text):
153
+ t = text.lower()
154
+ for phrase in reset_phrases:
155
+ if phrase in t:
156
+ return True
157
+ return False
158
+
159
+ def build_empathy_reply(emotion):
160
+ # Base empathy from emotions dict, plus a gentle follow-up question from followups
161
+ base = emotions.get(emotion, "")
162
+ # Pick a gentle opener if no followups defined
163
+ return base
164
+
165
+ # ----------------------------
166
+ # Upgraded reply generator with memory, context, multi-turn flow
167
+ # ----------------------------
168
+ def generate_reply(input_text):
169
+ text = input_text.strip()
170
+ if not text:
171
+ return "Please say or type something when you are ready."
172
+
173
+ lower = text.lower()
174
+
175
+ # 1) Immediate harmful check (escalate without delay)
176
+ if detect_harmful(lower):
177
+ # Reset conversation state because we escalate
178
+ conversation_state["emotion"] = None
179
+ conversation_state["context"] = None
180
+ conversation_state["followup_stage"] = 0
181
+ conversation_state["turns_since_set"] = 0
182
+ return harmful_response
183
+
184
+ # 2) User reset intent β€” end current flow politely
185
+ if is_reset_phrase(lower):
186
+ conversation_state["emotion"] = None
187
+ conversation_state["context"] = None
188
+ conversation_state["followup_stage"] = 0
189
+ conversation_state["turns_since_set"] = 0
190
+ return "That's ok β€” we can pause here. If you'd like to talk again later, I'm right here."
191
+
192
+ # 3) Detect if user explicitly states a new emotion -> override current state
193
+ new_emotion = detect_emotion_in_text(lower)
194
+ if new_emotion and new_emotion != conversation_state["emotion"]:
195
+ # start new flow
196
+ conversation_state["emotion"] = new_emotion
197
+ conversation_state["context"] = detect_context_in_text(lower)
198
+ conversation_state["followup_stage"] = 0
199
+ conversation_state["turns_since_set"] = 0
200
+ # Compose reply: empathy + first follow-up
201
+ empathy = build_empathy_reply(new_emotion)
202
+ # get followup prompt
203
+ prompts = followups.get(new_emotion, followups["default"])
204
+ follow = prompts[0] if prompts else ""
205
+ # Combine neatly
206
+ combined = f"{empathy}\n\n{follow}"
207
+ return combined
208
+
209
+ # 4) If an emotion is already active, continue that flow
210
+ if conversation_state["emotion"]:
211
+ emotion = conversation_state["emotion"]
212
+ # Update context if we find context in this message
213
+ ctx = detect_context_in_text(lower)
214
+ if ctx:
215
+ conversation_state["context"] = ctx
216
+
217
+ # If the user provided details (short heuristic: message length > 20 or contains certain markers),
218
+ # treat this as progress and advance the follow-up stage
219
+ provided_detail = (len(lower) > 20) or any(w in lower for w in ["because", "so", "then", "after", "today", "yesterday", "last", "friend", "parents", "teacher", "exam", "test"])
220
+
221
+ stage = conversation_state["followup_stage"]
222
+ prompts = followups.get(emotion, followups["default"])
223
+
224
+ # If user asked a question (contains '?'), attempt to respond empathetically referencing emotion/context
225
+ if "?" in lower:
226
+ # Respond referencing emotion and context
227
+ ctx_text = f" about {conversation_state['context']}" if conversation_state["context"] else ""
228
+ response = f"I hear your question{ctx_text}. Let's look at that together. {emotions.get(emotion,'')}"
229
+ # do not advance stage on simple question
230
+ conversation_state["turns_since_set"] += 1
231
+ return response
232
+
233
+ if provided_detail:
234
+ # Provide a reply that references the emotion and context and then advance
235
+ ctx_text = ""
236
+ if conversation_state["context"]:
237
+ ctx_text = f" because of {conversation_state['context']}"
238
+ # Construct reflective reply
239
+ if stage < len(prompts):
240
+ response = f"I understand β€” it makes sense you'd feel {emotion}{ctx_text}. {prompts[stage]}"
241
+ conversation_state["followup_stage"] += 1
242
+ conversation_state["turns_since_set"] = 0
243
+ return response
244
+ else:
245
+ # Follow-ups exhausted; offer actionable choices
246
+ conversation_state["turns_since_set"] += 1
247
+ return ("You have shared a lot β€” would you like to: \n"
248
+ "1) Try a calming exercise now\n"
249
+ "2) Write this in your journal\n"
250
+ "3) Talk more about it\n\n"
251
+ "Type '1', '2', or '3' to choose, or tell me if you want a helpline.")
252
+ else:
253
+ # User gave a short reply β€” ask a clarifying / gentle follow-up without advancing too far
254
+ if stage < len(prompts):
255
+ response = prompts[stage]
256
+ # only advance if we already showed that prompt previously
257
+ conversation_state["turns_since_set"] += 1
258
+ # If we had asked the same prompt previously and user still gives short replies, advance stage
259
+ if conversation_state["turns_since_set"] > 1:
260
+ conversation_state["followup_stage"] = min(len(prompts), stage + 1)
261
+ conversation_state["turns_since_set"] = 0
262
+ return response
263
+ else:
264
+ # if stages done but no detail, ask for choice
265
+ return ("I’m listening. If it's hard to describe, choose: 1) calming exercise 2) journal 3) talk more. "
266
+ "Or say 'I'm fine' to stop.")
267
+ # 5) No active emotion and no new emotion detected -> try to detect context or ask to elaborate
268
+ ctx = detect_context_in_text(lower)
269
+ if ctx:
270
+ # Gentle probing
271
+ return f"You mentioned {ctx}. Is this making you feel upset or worried? How does it make you feel?"
272
+ # Default fallback
273
+ return "Tell me more about your day β€” what happened, or how are you feeling right now?"
274
+
275
+ # ----------------------------
276
+ # Chat function (uses TTS + conversation_state)
277
+ # ----------------------------
278
  def chat_function(audio_input, text_input):
279
+ # We ignore audio_input here for text-only flow; you can add speech-to-text to use it.
280
+ user_text = (text_input or "").strip()
281
  if not user_text:
282
  return "Please type something.", None
283
+
284
  reply = generate_reply(user_text)
285
+
286
+ # Save conversation to history
287
+ chat_history.append({"user": user_text, "bot": reply, "emotion": conversation_state.get("emotion"), "context": conversation_state.get("context")})
288
+
289
+ # Text-to-speech (language selection)
290
  lang_code = lang_codes.get(user_info["language"], "en")
291
+ try:
292
+ tts = gTTS(reply, lang=lang_code)
293
+ audio_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
294
+ tts.save(audio_file.name)
295
+ voice_path = audio_file.name
296
+ except Exception as e:
297
+ # If TTS fails, still return the reply and no voice
298
+ voice_path = None
299
+
300
+ return reply, voice_path
301
+
302
+ # ----------------------------
303
+ # Remaining utility functions (unchanged)
304
+ # ----------------------------
305
+ def set_personal_info(name, age, gender, language, Guardian_info):
306
+ user_info.update({"name": name, "age": age, "gender": gender, "language": language, "Guardian_info": Guardian_info,})
307
+ return gr.update(visible=True), f"βœ… Welcome {name}! Preferences saved."
308
+
309
+ def show_personal_data():
310
+ today = datetime.date.today().strftime("%Y-%m-%d (%A)")
311
+ return f"πŸ“… {today}\nπŸ‘€ Name: {user_info['name']}\nπŸŽ‚ Age: {user_info['age']}\n♀ Gender: {user_info['gender']}\n🌐 Language: {user_info['language']}\n Guardian_info: {user_info['Guardian_info']}"
312
 
313
  def get_chat_history():
314
  if not chat_history:
 
334
  tip_index["study"] += 1
335
  return tip
336
 
337
+ # ----------------------------
338
+ # Gradio UI (kept same as your original file)
339
+ # ----------------------------
340
  with gr.Blocks() as app:
341
  welcome_screen = gr.Column(visible=True)
342
  full_app = gr.Tabs(visible=False)
 
371
  }
372
  </style>
373
  """)
374
+ gr.Markdown("<h1 id='main-title'>StrongMind Therapist 3.0</h1>")
375
  gr.Markdown("<h3 id='subtitle'>Your peaceful space to talk, journal, and focus.</h3>")
376
  start_button = gr.Button("🌸 Get Started", elem_id="start-btn")
377
 
 
404
  bot_reply = gr.Textbox(label="🧠 Therapist")
405
  voice = gr.Audio(label="πŸ”Š Voice Reply")
406
  send.click(chat_function, [audio_input, text_input], [bot_reply, voice])
 
407
 
408
  with gr.Tab("4️⃣ Chat History"):
409
  show_history = gr.Button("πŸ“œ Show Chats")