File size: 30,929 Bytes
9eda52b
2e984b5
3f8656e
2e984b5
0522ba8
1ffa361
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21d232e
3f8656e
47d5aca
2e984b5
 
3f8656e
21d232e
3f8656e
 
 
 
21d232e
3f8656e
21d232e
3f8656e
 
 
 
21d232e
6c79a25
3f8656e
 
 
 
 
 
 
 
47d5aca
3f8656e
47d5aca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f8656e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47d5aca
 
a96ecda
 
 
47d5aca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ffa361
 
 
 
 
 
 
 
 
 
 
 
 
 
3f8656e
1ffa361
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0522ba8
18b9799
47d5aca
3f8656e
 
 
 
6634ff5
3f8656e
1ffa361
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47d5aca
3f8656e
 
1ffa361
3f8656e
 
1ffa361
 
 
 
 
3f8656e
1ffa361
 
 
 
 
 
 
 
 
 
 
 
 
3f8656e
 
1ffa361
3f8656e
 
1ffa361
3f8656e
 
 
 
 
 
1ffa361
2e984b5
3f8656e
 
 
 
 
 
 
 
 
 
 
6c79a25
21d232e
3f8656e
 
 
2e984b5
 
47d5aca
0522ba8
3f8656e
 
6c79a25
b152c8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152c8ae
b152c8d
 
3f8656e
b152c8d
3f8656e
 
 
 
 
 
 
 
 
 
18b9799
3f8656e
 
47d5aca
3f8656e
 
 
 
 
 
 
 
 
 
 
 
 
 
a96ecda
3f8656e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab314f4
3f8656e
 
1ffa361
 
 
 
 
 
 
 
 
 
 
 
6c79a25
1ffa361
3f8656e
 
 
 
 
 
 
 
 
 
0502402
3f8656e
 
0522ba8
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
from gtts import gTTS
import tempfile
import json
import datetime
import gradio as gr
# ---------- MEMORY FILES ----------
CHAT_FILE = "chat_history.json"
EVENT_FILE = "event_memory.json"
REPORT_FILE = "reports.json"

# ---------- LOAD & SAVE ----------
def load_json(file):
    try:
        with open(file, "r") as f:
            return json.load(f)
    except:
        return []

def save_json(file, data):
    with open(file, "w") as f:
        json.dump(data, f, indent=4)

# Load memory
chat_history = load_json(CHAT_FILE)
event_memory = load_json(EVENT_FILE)
reports = load_json(REPORT_FILE)

# User data
user_info = {"name": "", "age": "", "gender": "", "language": "english" , "Guardian_info": ""}
chat_history = []
journal_entries = []

calm_tips = [
    "Take 3 deep breaths.", "Listen to nature.", "Stretch your body.",
    "Drink water.", "Think of one good thing today.", "Close your eyes for 1 minute.",
    "Write your feelings.", "Smile at yourself.", "Imagine a peaceful place.",
    "Say a positive affirmation."
]

study_tips = [
    "Use Pomodoro: 25min study, 5min break", "Make a daily to-do list",
    "Avoid multitasking", "Use color-coded notes", "Take 10-min exercise breaks",
    "Sleep 7–9 hrs daily", "Drink water during study", "Use active recall",
    "Study hardest topics first", "Test yourself often"
]

tip_index = {"calm": 0, "study": 0}

lang_codes = {
    "english": "en", "hindi": "hi", "marathi": "mr", "bengali": "bn",
    "tamil": "ta", "telugu": "te", "malayalam": "ml", "spanish": "es",
    "french": "fr", "german": "de"
}

# List of harmful or dangerous keywords
harmful_keywords = [
   "abomination", "annihilate", "arson", "ass", "assault", "atrocity",
"backstab", "barbaric", "barbarian", "beast", "belittle", "berserk",
"betray", "betrayal", "bigot", "blacklist", "blood", "bloodbath",
"bloody", "bomb", "bonehead", "brainless", "brutal", "brute", "burn",
"butcher", "cage", "callous", "cancer", "chaos", "cheater", "cold-blooded",
"conman", "corrupt", "cowardly", "crash", "crime", "criminality", "crook",
"cruel", "cruelty", "curseword", "damage", "danger", "dangerous", "deadly",
"deceive", "defame", "defeat", "degenerate", "demon", "despise", "destroy",
"destruction", "destructive", "devastate", "devil", "diabolical", "dictator",
"dirty", "disaster", "dishonor", "disrespect", "disturb", "divisive", "drunk",
"dumbass", "dungeon", "enemies", "enemy", "enrage", "evilness", "exile",
"exploit", "exterminate", "fake", "fanatic", "fascist", "fatal", "fire",
"forgery", "fraud", "fraudster", "freakish", "gang", "gangster", "ghastly",
"ghoul", "gory", "grotesque", "gruesome", "hag", "halfwit", "hardhearted",
"harm", "hateable", "hateful", "havoc", "hell", "hellish", "heretic",
"hideous", "horrid", "horrific", "hostility", "howl", "hypocrite", "illegal",
"illicit", "immoral", "imposter", "injure", "insensitive", "insidious",
"intolerant", "irate", "jerky", "joke", "joker", "kidnap", "killjoy", "liar",
"loath", "loathsome", "lowlife", "madness", "malicious", "malign",
"manipulate", "menace", "monster", "monstrous", "mug", "murderous",
"mutant", "mutiny", "nasty", "nefarious", "neglect", "negative", "offend",
"offender", "ominous", "oppress", "outrage", "outrageous", "parasite",
"penalty", "perish", "pest", "plague", "poison", "poisonous", "pollute",
"psychopath", "punch", "punish", "punishment", "quarrel", "rage", "rat",
"rebellion", "reckless", "repel", "repulsive", "revolt", "revolting",
"rioter", "rob", "robber", "rotten", "ruin", "savage", "scare", "scary",
"schemer", "scold", "scorn", "scoundrel", "scream", "screwed", "serpent",
"shady", "sham", "shameful", "shatter", "shocking", "sin", "sinister",
"slavey", "slimy", "smash", "smite", "snob", "spite", "spiteful", "stab",
"stench", "stink", "strike", "subvert", "suspicious", "target", "tease",
"terrible", "terrify", "thief", "threat", "threaten", "thug", "torment",
"torture", "trap", "trick", "trigger", "trouble", "uncivilized", "undermine",
"unfair", "unjust", "unkind", "usurper", "vandal", "vandalize", "venom",
"venomous", "villain", "villainous", "vindictive", "violent", "viper",
"vulgarity", "war", "warmonger", "waste", "wickedness", "wild", "wound",
"wrath", "wreck", "wrong", "yell", "zombie","suicide", "kill myself", "end my life", "harm myself", "cut myself",
"want to die", "die", "jump off", "self-harm"
"suicide", "kill myself", "end my life", "harm myself", "cut myself",
"want to die", "die", "jump off", "self-harm", "give up", "not worth it",
"ending it all", "self-hate", "suicidal", "tragic", "trauma", "pain",
"painful", "sorrow", 
"unworthy", "hurt", "grief", "agony", "doom", "doomed"

]

# Harmful word detection response
harmful_response = (
    "⚠️ It sounds like you're going through a really tough time.\n\n"
    "Please reach out to a professional:\n\n"
    "🇮🇳 **India Helplines**\n"
    "🧠 *Dr. Rachna Khanna Singh* – +91 99103 90559\n"
    "📞 *iCall Helpline* – +91 9152987821\n"
    "📞 *Vandrevala Foundation* – 1860 266 2345 or 1800 233 3330\n\n"
    "🌍 **International Helplines**\n"
    "📞 *Lifeline (USA)* – 988\n"
    "📞 *Samaritans (UK)* – 116 123\n"
    "📞 *Lifeline (Australia)* – 13 11 14\n\n"
    "You are not alone. There are people who care and want to help 💚"
)

# Simplified emotions dictionary
emotions = {
     "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.",
    "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.",
    "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.",
    "lonely": "You are not alone. Talking helps — I’m here to listen.",
    "rejected": "Rejection hurts but it doesn’t define your worth.",
    "exams": "Plan short sessions with breaks. You can do this!",
    "parents": "Family pressure is real. Want to talk more about it?",
    "money": "Finances are tough, but your value isn’t tied to them.",
    "too much": "Pause. Let’s break it into small steps.",
    "friend": "Friendship can be tricky. Want to share what happened?",
    "love": "Love is powerful — and sometimes painful. I’m here to help you reflect.",
    "forced": "You don’t have to do what doesn’t feel right.",
    "compare": "You’re unique. Comparison steals joy.",
    "numb": "It’s okay to feel nothing. Let’s gently bring you back.",
    "instagram": "Let’s take a small break from social media together.",
    "pretend": "You don’t need to pretend here. Be real, be you.",
    "bullied": "You don’t deserve this. You are strong and valuable.",
    "misunderstood": "That can feel frustrating. I understand you.",
    "rainy": "Rainy days can be gloomy. A warm drink and chat may help.",
    "unwell": "Rest, hydrate, and be kind to yourself today.",
    "overthink": "Let’s try to focus on what’s in your control.",
    "who am i": "Great question! Let’s explore that together.",
    "climate": "You care — and that’s powerful. Even small actions help.",
    "pointless": "Your life matters, even when it doesn’t feel like it.",
    "ignored": "You are seen and heard here. Let’s talk.",
    "can’t sleep": "Try breathing deeply. Would soft music help?",
    "stuck": "Let’s look at one thing we *can* do today.",
    "hopeless": "Even small steps forward are progress. Hope grows.",
    "depressed": "You’re not alone in this. Let’s talk through it.",
    "scared": "Let’s face this together, one moment at a time.",
    "afraid": "Fear shows you care. Let’s understand it better.",
    "confused": "It’s okay not to have all the answers yet.",
    "guilty": "Guilt teaches us. Let’s grow from it, not drown in it.",
    "ashamed": "You are more than your mistakes.",
    "failure": "Failure means you tried. That’s strength.",
    "panic": "Breathe with me. Ground yourself. You are okay.",
    "stressed": "Let’s identify your stress and sort it gently.",
    "bored": "Want to do something fun or creative together?",
    "insecure": "You have strengths worth celebrating.",
    "uncertain": "Uncertainty is part of growth. Let’s navigate it.",
    "worried": "What are you worried about? Let’s untangle it.",
    "homesick": "It’s okay to miss home. What comforts you?",
    "crying": "Crying is healing. Let it out if needed.",
    "jealous": "Let’s explore what you truly desire.",
    "envy": "You can build your own journey. You’re enough.",
    "hate": "Let’s turn that strong emotion into understanding.",
    "bitterness": "Bitterness is heavy. Want to release some of it?",
    "regret": "We all have regrets. What can we learn from yours?",
    "betrayed": "That hurts deeply. Let’s process it together.",
    "heartbroken": "Healing takes time. Let’s take the first step.",
    "alone": "You’re not alone here. I’m right with you.",
    "trapped": "There’s always a way out. Let’s look for options.",
    "disappointed": "Disappointment is valid. Let’s reflect and reset.",
    "pressured": "You don’t have to carry it all. Let’s prioritize.",
    "unloved": "You are lovable. Truly. Start with self-kindness.",
    "exhausted": "Rest. That’s productive too.",
    "withdrawn": "It’s okay to pull back. But don’t shut out support.",
    "disrespected": "Respect matters. You deserve it.",
    "avoided": "You matter. Let’s talk about what happened.",
    "insomnia": "Let’s try a gentle nighttime routine.",
    "neglected": "You deserve care and attention.",
    "nervous": "New things are scary. But you’re capable.",
    "frustrated": "Let’s release that pressure gently.",
    "humiliated": "That experience doesn’t define you.",
    "unimportant": "You matter. Just by being you.",
    "abandoned": "That’s painful. You’re not alone anymore.",
    "defeated": "You’re still here. That’s strength.",
    "shy": "Quiet doesn’t mean weak. Your voice matters.",
    "paranoid": "Let’s ground our thoughts in facts and truth.",
    "restless": "Let’s find a healthy outlet together.",
    "gloomy": "Let’s look for a little light together.",
    "anxious": "Let’s name the worry, then tame it.",
    "worthless": "You are worthy — of love, peace, and joy.",
    "invisible": "I see you. You matter.",
    "lethargic": "Small movement helps. Try stretching.",
    "annoyed": "Want to vent? I’m listening.",
    "fomo": "It’s okay not to do everything. Your pace is right.",
    "peer pressure": "Your choices are your own. Stand strong.",
    "embarrassed": "Everyone messes up sometimes. Let it go.",
    "unappreciated": "I appreciate you. Let’s celebrate your efforts.",
    "hollow": "You may feel empty now — but you’re not.",
    "resentful": "Let’s process it before it poisons your peace.",
    "in pain": "Pain hurts, but talking eases it. Let’s talk.",
    "drained": "Rest is fuel. It’s okay to pause.",
    "moody": "Moods pass. Let’s ride this one out together.",
    "isolated": "Let’s reconnect — even one small step helps.",
    "fake": "You can be real here. No masks.",
    "mentally tired": "Mental fatigue is real. Let’s rest and reset.",
    "broken": "Cracks let the light in. You’re still whole inside.",
    "crushed": "That sounds painful. Let’s unpack it together.",
    "troubled": "Name the trouble, then tame it. I’m here.",
    "underestimated": "You are more than they think. Show them. Gently.",
    "burned out": "Burnout needs healing. Step back to move forward.",
    "stress" : "Take 3 deep breaths and relax your shoulders.",
    "stressful" : "Break tasks into smaller steps to feel less overwhelmed.",
     "anxiety" : "Focus on slow breathing for 5 minutes to calm your mind.",
    "panic" : "Ground yourself by naming 5 things you see around you.",
"fear" : "Write down your fear and list why it may not be true.",
"anger" : "Walk away for a moment and count to 10.",
"rage" : "Listen to calming music to release intense anger.",
"sadness" : "Call a friend or talk to someone who cares.",
"grief" : "Allow yourself to cry and express your emotions.",
"trauma" : "Practice grounding exercises like touching nearby objects.",
"abuse" : "Remember, you deserve respect—consider reaching out for help.",
"depression" : "Take a short walk outside and notice nature.",
"loneliness" : "Text someone you trust to connect.",
"hopeless" : "Think of one small goal you can achieve today.",
"exhausted" : "Drink water and rest for at least 10 minutes.",
"overwhelmed" : "Make a priority list and focus on just 1 thing.",
"nervous" : "Practice positive affirmations like 'I can handle this.'",
"tired" : "Take a quick power nap if possible.",
"fatigue" : "Stretch your body to release tension.",
"burnout" : "Take a complete 10-minute break without screens.",
"frustrated" : "Pause and do 5 deep breaths to regain focus.",
"helpless" : "Ask for support—it's okay to seek help.",
"confused" : "Write down your thoughts to organize them.",
"worried" : "Challenge your thoughts by asking 'Is this likely to happen?'",
"lost" : "Take one small step towards clarity, like making a to-do list.",
"crying" : "Drink water and sit in a comfortable position to calm.",
"heartbreak" : "Allow yourself to heal and talk to a trusted friend.",
"guilt" : "Forgive yourself and remind yourself you are human.",
"shame" : "Remind yourself that mistakes do not define you.",
"fearful" : "Focus on your breathing for a few minutes.",
"meltdown" : "Step away and try a 5-minute meditation.",
"pressured" : "Break tasks into smaller, manageable chunks.",
"uneasy" : "Listen to relaxing music or nature sounds.",
"unmotivated" : "Start with one tiny task to build momentum.",
"restless" : "Try a short physical activity like stretching.",
"freaking" : "Count to 10 slowly to calm down.",
"cry" : "Let your tears out—it helps to release emotions.",
"breakdown" : "Sit somewhere quiet and breathe deeply.",
"fail" : "Remind yourself failure is part of learning.",
"failure" : "Focus on what you can improve, not what you lost.",
"pressure" : "Take breaks and drink water to refresh your mind.",
"worry" : "Write down your worries and challenge them logically.",
"trouble" : "Focus on one thing you can solve right now.",
"numb" : "Take a walk outside to feel present.",
"tense" : "Relax your shoulders and stretch for a minute.",
"hurting" : "Talk to someone you trust about your pain.",
"hurt" : "Be kind to yourself and allow healing time.",
"broken" : "Remember that healing is slow but possible.",
"tension" : "Roll your shoulders and take deep breaths.",
"angry" : "Punch a pillow or squeeze a stress ball instead of yelling.",
"pessimistic" : "List 3 things that went well today.",
"scared" : "Remind yourself of times you overcame fear.",
"worn-out" : "Take a 5-minute break and hydrate.",
"mental pain" : "Talk about your feelings with a trusted person.",
"emotional" : "Allow yourself to feel without judging your emotions.",
"upset" : "Pause and do 10 slow breaths.",
"low" : "Do something small that brings joy.",
"bitter" : "Write down 3 positive things about your day.",
"uneasiness" : "Practice slow and mindful breathing.",
"tense" : "Try progressive muscle relaxation.",
"tight" : "Do a gentle body stretch.",
"stressed-out" : "Focus on what you can control right now.",
"paranoid" : "Talk to someone to verify your fears.",
"devastated" : "Give yourself time to heal.",
"crybaby" : "Your tears are valid—let them flow.",
"unhappy" : "List 1 thing that can make you smile.",
"negative" : "Counter each negative thought with a positive one.",
"hopelessness" : "Set one small achievable goal today.",
"unsure" : "Write your pros and cons to gain clarity.",
"self-doubt" : "Remind yourself of your past achievements.",
"hurtful" : "Distance yourself from negativity for a while.",
"unwell" : "Drink water and rest to recover.",
"emotionless" : "Do something creative to spark feelings.",
"lostness" : "Journal your thoughts for clarity.",
"distress" : "Breathe in for 4 seconds, hold 4, out for 4.",
"emergency" : "Call someone you trust immediately.",
"unsettled" : "Meditate for 5 minutes on your breath.",
"chaotic" : "Focus on organizing one small area around you.",
"break" : "Take 10 minutes to step outside.",
"unstable" : "Seek support from a friend or counselor.",
"hopelessly" : "Remind yourself nothing lasts forever.",
"pain" : "Try deep breathing or journaling about your pain.",
"painful" : "Distract yourself with something positive.",
"angsty" : "Express feelings through writing or art.",
"uneasiness" : "Light a candle and focus on the flame for a minute.",
"irritated" : "Do 5 deep breaths to calm irritation.",
"frustration" : "Talk about your frustration instead of bottling it.",
"exhaustion" : "Sleep for at least 15 minutes if possible.",
"mental stress" : "Pause and take a few deep breaths.",
"low mood" : "Listen to uplifting music.",
"discouraged" : "Remind yourself of past successes.",
"confusion" : "Pause, take a breath, and write down thoughts.",
"overthinking" : "Distract yourself with a small physical activity.",
"hurtful words" : "Remind yourself words don’t define your worth.",
"traumatized" : "Seek safe space and talk about your feelings.",
"frantic" : "Slow your breathing and count backwards from 10.",
"chaos" : "Clean or organize something small around you.",
"lost mind" : "Ground yourself by feeling the floor beneath you.",
"hectic" : "Prioritize and focus on one task at a time.",
"unbalanced" : "Sit and take 5 deep breaths.",
"mentally tired" : "Close your eyes for 2 minutes and relax.",
"self-blame" : "Remind yourself that mistakes happen to everyone.",
"failure feeling" : "Focus on one thing you’ve done right today.",
"feeling bad" : "Say one kind thing to yourself.",
"worthless" : "Remember your value is not defined by others.",
"helplessness" : "Ask for support—it’s a sign of strength.",
"emotional pain" : "Talk to someone who cares about you.",
"lack of energy" : "Stretch your arms and drink water.",
"lack of sleep" : "Take a power nap of 10-20 minutes.",
"mood swings" : "Track your mood to find triggers.",
"frightened" : "Hold a comforting object and breathe slowly.",
"self-hate" : "Replace self-criticism with self-kindness.",
"negativity" : "Say one positive affirmation out loud.",
"anxious" : "Practice slow inhaling and exhaling.",
"feeling down" : "Do something you enjoy, even for 5 minutes.",
"unstable mind" : "Pause, breathe, and write what you feel.",
"uneasy feeling" : "Ground yourself by noticing your 5 senses.",
"confusing" : "Write down questions to get clarity.",
"worn out" : "Take a rest break with calm music.",
"pressured" : "Let go of what’s not urgent.",
"nervousness" : "Take 10 deep breaths slowly.",
"mental exhaustion" : "Do a simple 5-min body stretch.",
"crisis" : "Focus on what is in your control right now.",
"melancholy" : "Write or draw to express feelings.",
"mental breakdown" : "Sit down, close your eyes, and breathe.",
"feeling weak" : "Remind yourself you’ve overcome challenges before.",
"shaking" : "Sit still and breathe deeply for 2 minutes.",
"mental fatigue" : "Take a short screen-free break.",
"scared feelings" : "Tell yourself, 'This feeling will pass.'",
"restless mind" : "Do 5 minutes of meditation or yoga.",
"mind chaos" : "Write down your thoughts to clear your mind.",
"uncertain" : "List your options and think calmly.",
"self-harming thoughts" : "Reach out to someone you trust immediately.",
"dark thoughts" : "Remember, you are not your thoughts.",
"mental pressure" : "Pause and breathe for 5 deep breaths.",
"losing hope" : "Focus on one good thing in your day.",
"bad mood" : "Do something fun or silly for 5 minutes.",
"pain inside" : "Talk to someone, don’t hold it in.",
"numb feeling" : "Do a gentle self-massage on your hands.",
"lack of motivation" : "Start with just 1 easy task.",
"mind clutter" : "Write your thoughts on paper.",
"feeling low" : "Listen to uplifting songs or affirmations.",
"irritation" : "Pause and breathe deeply 3 times.",
"disturbed" : "Sit somewhere quiet for 5 minutes.",
"heavy heart" : "Talk about how you feel with someone.",
"mental burden" : "Break it into small, manageable steps.",
"scared mind" : "Repeat to yourself: 'I am safe now.'",
"tension headache" : "Massage your temples gently.",
"mind storm" : "Sit quietly and focus on one thought.",
"mental struggle" : "Write a small gratitude note.",
"mind fatigue" : "Do light stretches or walk for 5 minutes."
}
import datetime

def extract_event(user_text):
    import random

def get_emotional_response(emotion):
    responses = {
        "sad": ["I'm really sorry you're feeling this way 💙", "That sounds heavy… I'm here for you"],
        "anxiety": ["That sounds stressful 🌿", "Let’s slow things down together"],
        "angry": ["I can sense your frustration", "It’s okay to feel angry"],
        "lonely": ["You’re not alone 🤍", "I’m here with you"]
    }
    return random.choice(responses.get(emotion, ["I understand."]))


def humanize_reply(base_reply):
    starters = ["I hear you.", "I’m really glad you shared that.", "I’m here with you."]
    empathy = ["That must feel tough.", "I understand how that can feel."]
    follow = ["Do you want to tell me more?", "I’m listening 💙"]

    return f"{random.choice(starters)}\n{random.choice(empathy)}\n\n{base_reply}\n\n{random.choice(follow)}"
    text = user_text.lower()
    keywords = ["exam", "test", "fight", "friend", "family", "school", "stress"]

    for word in keywords:
        if word in text:
            event = {
                "event": user_text,
                "keyword": word,
                "time": str(datetime.datetime.now())
            }
            event_memory.append(event)
            save_json(EVENT_FILE, event_memory)
            return event
    return None
    
# Functions
def set_personal_info(name, age, gender, language, Guardian_info):
    user_info.update({"name": name, "age": age, "gender": gender, "language": language, "Guardian_info": Guardian_info,})
    return gr.update(visible=True), f"✅ Welcome {name}! Preferences saved."

def show_personal_data():
    today = datetime.date.today().strftime("%Y-%m-%d (%A)")
    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']}"

def generate_report():
    today = str(datetime.date.today())

    emotions_seen = []
    topics = []

    for chat in chat_history[-20:]:
        text = chat["user"].lower()

        for word in emotions:
            if word in text:
                emotions_seen.append(word)

        if "exam" in text:
            topics.append("studies")
        if "friend" in text:
            topics.append("friends")
        if "family" in text:
            topics.append("family")

    summary = f"🧠 Report - {today}\n\n"

    if emotions_seen:
        summary += f"💭 Emotions: {', '.join(set(emotions_seen))}\n"
    else:
        summary += "💭 Emotions: Stable\n"

    if topics:
        summary += f"📚 Focus: {topics[-1]}\n"

    summary += "\n💡 Suggestion: Take care of your mental health 💙"

    reports.append({"date": today, "report": summary})
    save_json(REPORT_FILE, reports)

    return summary

def chat_function(audio_input, text_input):
    user_text = text_input.strip()

    if not user_text:
        return "Please type something.", None

    # 🧠 Extract event
    extract_event(user_text)

    # 🧠 Generate reply
    reply = generate_reply(user_text)

    # 💾 Save chat
    chat_history.append({
        "user": user_text,
        "bot": reply,
        "time": str(datetime.datetime.now())
    })
    save_json(CHAT_FILE, chat_history)

    # 📊 Update report
    generate_report()

    # 🔊 Voice
    lang_code = lang_codes.get(user_info["language"], "en")
    tts = gTTS(reply, lang=lang_code)

    audio_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
    tts.save(audio_file.name)

    return reply, audio_file.name

def get_chat_history():
    if not chat_history:
        return "No conversations yet."
    return "\n\n".join([f"You: {c['user']}\nBot: {c['bot']}" for c in chat_history])
    
def save_journal(entry):
    journal_entries.append(entry)
    with open("journal.json", "w") as f:
        json.dump(journal_entries, f)
    return "✅ Journal saved!"

def show_journal_history():
    return "\n---\n".join(journal_entries) if journal_entries else "No journal entries yet."

def next_calm_tip():
    tip = calm_tips[tip_index["calm"] % len(calm_tips)]
    tip_index["calm"] += 1
    return tip

def next_study_tip():
    tip = study_tips[tip_index["study"] % len(study_tips)]
    tip_index["study"] += 1
    return tip

# -------------- Gradio App --------------
with gr.Blocks() as app:
    welcome_screen = gr.Column(visible=True)
    full_app = gr.Tabs(visible=False)

    with welcome_screen:
        gr.HTML("""
            <style>
                #main-title {
                    text-align: center;
                    font-size: 2.5em;
                }
                #subtitle {
                    text-align: center;
                    font-size: 1.2em;
                    color: #ccc;
                    margin-bottom: 30px;
                }
                #start-btn {
                    background-color: #ff69b4;
                    color: white;
                    font-weight: bold;
                    border: none;
                    border-radius: 10px;
                    padding: 14px 45px;
                    font-size: 1.1em;
                    cursor: pointer;
                    display: block;
                    margin: 0 auto;
                }
                #start-btn:hover {
                    background-color: #ff85c1;
                }
            </style>
        """)
        gr.Markdown("<h1 id='main-title'>StrongMind Therapist 2.0</h1>")
        gr.Markdown("<h3 id='subtitle'>Your peaceful space to talk, journal, and focus.</h3>")
        start_button = gr.Button("🌸 Get Started", elem_id="start-btn")

    def start_app():
        return gr.update(visible=False), gr.update(visible=True)

    start_button.click(start_app, outputs=[welcome_screen, full_app])

    with full_app:
        with gr.Tab("1️⃣ Personal Info"):
            name = gr.Textbox(label="Name")
            age = gr.Textbox(label="Age")
            gender = gr.Dropdown(["Male", "Female", "Other"], label="Gender")
            language = gr.Dropdown(list(lang_codes.keys()), label="Preferred Language")
            Guardian_info = gr.Textbox(label="Guardian information")
            btn = gr.Button("Save Info")
            popup = gr.Markdown(visible=False, elem_classes="alert-box")
            btn.click(set_personal_info, [name, age, gender, language,Guardian_info], [popup, popup])

        with gr.Tab("2️⃣ Personal Info Data"):
            show = gr.Button("Show My Info")
            info_display = gr.Textbox(lines=6)
            show.click(show_personal_data, outputs=info_display)

        with gr.Tab("3️⃣ Chat"):
            gr.Markdown("🗣️ Describe your day in one word.")
            audio_input = gr.Audio(type="filepath", label="🎧 Say something")
            text_input = gr.Textbox(label="⌨️ Or type here")
            send = gr.Button("Send")
            bot_reply = gr.Textbox(label="🧠 Therapist")
            voice = gr.Audio(label="🔊 Voice Reply")
            send.click(chat_function, [audio_input, text_input], [bot_reply, voice])
        

        with gr.Tab("4️⃣ Chat History"):
            show_history = gr.Button("📜 Show Chats")
            chat_out = gr.Textbox(lines=20, label="History")
            show_history.click(get_chat_history, outputs=chat_out)

        with gr.Tab("5️⃣ Journal"):
            journal_input = gr.Textbox(lines=6, label="Write your thoughts")
            save = gr.Button("Save")
            journal_status = gr.Textbox()
            save.click(save_journal, journal_input, journal_status)

        with gr.Tab("6️⃣ Journal History"):
            view = gr.Button("View Past Entries")
            past = gr.Textbox(lines=15, label="Previous Journals")
            view.click(show_journal_history, outputs=past)

        with gr.Tab("7️⃣ Calm Space"):
            tip_btn = gr.Button("🌿 Give Me a Calm Tip")
            calm_text = gr.Textbox()
            tip_btn.click(next_calm_tip, outputs=calm_text)

        with gr.Tab("8️⃣ Study Tips"):
            tip_btn2 = gr.Button("📚 Study Tip")
            study_text = gr.Textbox()
            tip_btn2.click(next_study_tip, outputs=study_text)

        with gr.Tab("9️⃣ Pomodoro"):
            gr.Markdown("⏱️ Use 25 min study + 5 min break cycles.\n(For real timer, use front-end JavaScript or Android timers)")
            
with gr.Tab("📊 Daily Report"):
    report_btn = gr.Button("Generate Report")
    report_box = gr.Textbox(lines=10)

    history_btn = gr.Button("View Past Reports")
    history_box = gr.Textbox(lines=15)

    report_btn.click(generate_report, outputs=report_box)

    def show_reports():
        return "\n\n---\n\n".join([r["report"] for r in reports])

    history_btn.click(show_reports, outputs=history_box)
        with gr.Tab("💠 Games"):
            gr.Markdown("🎮 Play from the game portal below:")
            gr.HTML(
                '''
                <iframe
                  src="https://www.onlinegames.io/embed/portal/"
                  width="100%"
                  height="600"
                  frameborder="0"
                  allowfullscreen>
                </iframe> 
                '''
            )

if __name__ == "__main__":
    app.launch()