Files changed (2) hide show
  1. app.py +452 -513
  2. requirements.txt +6 -7
app.py CHANGED
@@ -1,513 +1,452 @@
1
- from gtts import gTTS
2
- import tempfile
3
- 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 = []
11
-
12
- calm_tips = [
13
- "Take 3 deep breaths.", "Listen to nature.", "Stretch your body.",
14
- "Drink water.", "Think of one good thing today.", "Close your eyes for 1 minute.",
15
- "Write your feelings.", "Smile at yourself.", "Imagine a peaceful place.",
16
- "Say a positive affirmation."
17
- ]
18
-
19
- study_tips = [
20
- "Use Pomodoro: 25min study, 5min break", "Make a daily to-do list",
21
- "Avoid multitasking", "Use color-coded notes", "Take 10-min exercise breaks",
22
- "Sleep 7–9 hrs daily", "Drink water during study", "Use active recall",
23
- "Study hardest topics first", "Test yourself often"
24
- ]
25
-
26
- tip_index = {"calm": 0, "study": 0}
27
-
28
- lang_codes = {
29
- "english": "en", "hindi": "hi", "marathi": "mr", "bengali": "bn",
30
- "tamil": "ta", "telugu": "te", "malayalam": "ml", "spanish": "es",
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"
85
- "🇮🇳 **India Helplines**\n"
86
- "🧠 *Dr. Rachna Khanna Singh* +91 99103 90559\n"
87
- "📞 *iCall Helpline* – +91 9152987821\n"
88
- "📞 *Vandrevala Foundation* – 1860 266 2345 or 1800 233 3330\n\n"
89
- "🌍 **International Helplines**\n"
90
- "📞 *Lifeline (USA)* 988\n"
91
- "📞 *Samaritans (UK)* 116 123\n"
92
- "📞 *Lifeline (Australia)* – 13 11 14\n\n"
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:
377
- return "No conversations yet."
378
- return "\n\n".join([f"You: {c['user']}\nBot: {c['bot']}" for c in chat_history])
379
-
380
- def save_journal(entry):
381
- journal_entries.append(entry)
382
- with open("journal.json", "w") as f:
383
- json.dump(journal_entries, f)
384
- return " Journal saved!"
385
-
386
- def show_journal_history():
387
- return "\n---\n".join(journal_entries) if journal_entries else "No journal entries yet."
388
-
389
- def next_calm_tip():
390
- tip = calm_tips[tip_index["calm"] % len(calm_tips)]
391
- tip_index["calm"] += 1
392
- return tip
393
-
394
- def next_study_tip():
395
- tip = study_tips[tip_index["study"] % len(study_tips)]
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)
403
-
404
- with welcome_screen:
405
- gr.HTML("""
406
- <style>
407
- #main-title {
408
- text-align: center;
409
- font-size: 2.5em;
410
- }
411
- #subtitle {
412
- text-align: center;
413
- font-size: 1.2em;
414
- color: #ccc;
415
- margin-bottom: 30px;
416
- }
417
- #start-btn {
418
- background-color: #ff69b4;
419
- color: white;
420
- font-weight: bold;
421
- border: none;
422
- border-radius: 10px;
423
- padding: 14px 45px;
424
- font-size: 1.1em;
425
- cursor: pointer;
426
- display: block;
427
- margin: 0 auto;
428
- }
429
- #start-btn:hover {
430
- background-color: #ff85c1;
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
-
438
- def start_app():
439
- return gr.update(visible=False), gr.update(visible=True)
440
-
441
- start_button.click(start_app, outputs=[welcome_screen, full_app])
442
-
443
- with full_app:
444
- with gr.Tab("1️⃣ Personal Info"):
445
- name = gr.Textbox(label="Name")
446
- age = gr.Textbox(label="Age")
447
- gender = gr.Dropdown(["Male", "Female", "Other"], label="Gender")
448
- language = gr.Dropdown(list(lang_codes.keys()), label="Preferred Language")
449
- Guardian_info = gr.Textbox(label="Guardian information")
450
- btn = gr.Button("Save Info")
451
- popup = gr.Markdown(visible=False, elem_classes="alert-box")
452
- btn.click(set_personal_info, [name, age, gender, language,Guardian_info], [popup, popup])
453
-
454
- with gr.Tab("2️⃣ Personal Info Data"):
455
- show = gr.Button("Show My Info")
456
- info_display = gr.Textbox(lines=6)
457
- show.click(show_personal_data, outputs=info_display)
458
-
459
- with gr.Tab("3️⃣ Chat"):
460
- gr.Markdown("🗣️ Describe your day in one word.")
461
- audio_input = gr.Audio(type="filepath", label="🎧 Say something")
462
- text_input = gr.Textbox(label="⌨️ Or type here")
463
- send = gr.Button("Send")
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")
471
- chat_out = gr.Textbox(lines=20, label="History")
472
- show_history.click(get_chat_history, outputs=chat_out)
473
-
474
- with gr.Tab("5️⃣ Journal"):
475
- journal_input = gr.Textbox(lines=6, label="Write your thoughts")
476
- save = gr.Button("Save")
477
- journal_status = gr.Textbox()
478
- save.click(save_journal, journal_input, journal_status)
479
-
480
- with gr.Tab("6️⃣ Journal History"):
481
- view = gr.Button("View Past Entries")
482
- past = gr.Textbox(lines=15, label="Previous Journals")
483
- view.click(show_journal_history, outputs=past)
484
-
485
- with gr.Tab("7️⃣ Calm Space"):
486
- tip_btn = gr.Button("🌿 Give Me a Calm Tip")
487
- calm_text = gr.Textbox()
488
- tip_btn.click(next_calm_tip, outputs=calm_text)
489
-
490
- with gr.Tab("8️⃣ Study Tips"):
491
- tip_btn2 = gr.Button("📚 Study Tip")
492
- study_text = gr.Textbox()
493
- tip_btn2.click(next_study_tip, outputs=study_text)
494
-
495
- with gr.Tab("9️⃣ Pomodoro"):
496
- gr.Markdown("⏱️ Use 25 min study + 5 min break cycles.\n(For real timer, use front-end JavaScript or Android timers)")
497
-
498
- with gr.Tab("💠 Games"):
499
- gr.Markdown("🎮 Play from the game portal below:")
500
- gr.HTML(
501
- '''
502
- <iframe
503
- src="https://www.onlinegames.io/embed/portal/"
504
- width="100%"
505
- height="600"
506
- frameborder="0"
507
- allowfullscreen>
508
- </iframe>
509
- '''
510
- )
511
-
512
- if __name__ == "__main__":
513
- app.launch()
 
1
+ from gtts import gTTS
2
+ import tempfile
3
+ import json
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 = []
13
+
14
+ calm_tips = [
15
+ "Take 3 deep breaths.", "Listen to nature.", "Stretch your body.",
16
+ "Drink water.", "Think of one good thing today.", "Close your eyes for 1 minute.",
17
+ "Write your feelings.", "Smile at yourself.", "Imagine a peaceful place.",
18
+ "Say a positive affirmation."
19
+ ]
20
+
21
+ study_tips = [
22
+ "Use Pomodoro: 25min study, 5min break", "Make a daily to-do list",
23
+ "Avoid multitasking", "Use color-coded notes", "Take 10-min exercise breaks",
24
+ "Sleep 7–9 hrs daily", "Drink water during study", "Use active recall",
25
+ "Study hardest topics first", "Test yourself often"
26
+ ]
27
+
28
+ tip_index = {"calm": 0, "study": 0}
29
+
30
+ lang_codes = {
31
+ "english": "en", "hindi": "hi", "marathi": "mr", "bengali": "bn",
32
+ "tamil": "ta", "telugu": "te", "malayalam": "ml", "spanish": "es",
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"
47
+ "🇮🇳 **India Helplines**\n"
48
+ "🧠 *Dr. Rachna Khanna Singh* +91 99103 90559\n"
49
+ "📞 *iCall Helpline* +91 9152987821\n"
50
+ "📞 *Vandrevala Foundation* 1860 266 2345 or 1800 233 3330\n\n"
51
+ "🌍 **International Helplines**\n"
52
+ "📞 *Lifeline (USA)* 988\n"
53
+ "📞 *Samaritans (UK)* 116 123\n"
54
+ "📞 *Lifeline (Australia)* 13 11 14\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:
315
+ return "No conversations yet."
316
+ return "\n\n".join([f"You: {c['user']}\nBot: {c['bot']}" for c in chat_history])
317
+
318
+ def save_journal(entry):
319
+ journal_entries.append(entry)
320
+ with open("journal.json", "w") as f:
321
+ json.dump(journal_entries, f)
322
+ return " Journal saved!"
323
+
324
+ def show_journal_history():
325
+ return "\n---\n".join(journal_entries) if journal_entries else "No journal entries yet."
326
+
327
+ def next_calm_tip():
328
+ tip = calm_tips[tip_index["calm"] % len(calm_tips)]
329
+ tip_index["calm"] += 1
330
+ return tip
331
+
332
+ def next_study_tip():
333
+ tip = study_tips[tip_index["study"] % len(study_tips)]
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)
343
+
344
+ with welcome_screen:
345
+ gr.HTML("""
346
+ <style>
347
+ #main-title {
348
+ text-align: center;
349
+ font-size: 2.5em;
350
+ }
351
+ #subtitle {
352
+ text-align: center;
353
+ font-size: 1.2em;
354
+ color: #ccc;
355
+ margin-bottom: 30px;
356
+ }
357
+ #start-btn {
358
+ background-color: #ff69b4;
359
+ color: white;
360
+ font-weight: bold;
361
+ border: none;
362
+ border-radius: 10px;
363
+ padding: 14px 45px;
364
+ font-size: 1.1em;
365
+ cursor: pointer;
366
+ display: block;
367
+ margin: 0 auto;
368
+ }
369
+ #start-btn:hover {
370
+ background-color: #ff85c1;
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
+
378
+ def start_app():
379
+ return gr.update(visible=False), gr.update(visible=True)
380
+
381
+ start_button.click(start_app, outputs=[welcome_screen, full_app])
382
+
383
+ with full_app:
384
+ with gr.Tab("1️⃣ Personal Info"):
385
+ name = gr.Textbox(label="Name")
386
+ age = gr.Textbox(label="Age")
387
+ gender = gr.Dropdown(["Male", "Female", "Other"], label="Gender")
388
+ language = gr.Dropdown(list(lang_codes.keys()), label="Preferred Language")
389
+ Guardian_info = gr.Textbox(label="Guardian information")
390
+ btn = gr.Button("Save Info")
391
+ popup = gr.Markdown(visible=False, elem_classes="alert-box")
392
+ btn.click(set_personal_info, [name, age, gender, language,Guardian_info], [popup, popup])
393
+
394
+ with gr.Tab("2️⃣ Personal Info Data"):
395
+ show = gr.Button("Show My Info")
396
+ info_display = gr.Textbox(lines=6)
397
+ show.click(show_personal_data, outputs=info_display)
398
+
399
+ with gr.Tab("3️⃣ Chat"):
400
+ gr.Markdown("🗣️ Describe your day in one word.")
401
+ audio_input = gr.Audio(type="filepath", label="🎧 Say something")
402
+ text_input = gr.Textbox(label="⌨️ Or type here")
403
+ send = gr.Button("Send")
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")
410
+ chat_out = gr.Textbox(lines=20, label="History")
411
+ show_history.click(get_chat_history, outputs=chat_out)
412
+
413
+ with gr.Tab("5️⃣ Journal"):
414
+ journal_input = gr.Textbox(lines=6, label="Write your thoughts")
415
+ save = gr.Button("Save")
416
+ journal_status = gr.Textbox()
417
+ save.click(save_journal, journal_input, journal_status)
418
+
419
+ with gr.Tab("6️⃣ Journal History"):
420
+ view = gr.Button("View Past Entries")
421
+ past = gr.Textbox(lines=15, label="Previous Journals")
422
+ view.click(show_journal_history, outputs=past)
423
+
424
+ with gr.Tab("7️⃣ Calm Space"):
425
+ tip_btn = gr.Button("🌿 Give Me a Calm Tip")
426
+ calm_text = gr.Textbox()
427
+ tip_btn.click(next_calm_tip, outputs=calm_text)
428
+
429
+ with gr.Tab("8️⃣ Study Tips"):
430
+ tip_btn2 = gr.Button("📚 Study Tip")
431
+ study_text = gr.Textbox()
432
+ tip_btn2.click(next_study_tip, outputs=study_text)
433
+
434
+ with gr.Tab("9️⃣ Pomodoro"):
435
+ gr.Markdown("⏱️ Use 25 min study + 5 min break cycles.\n(For real timer, use front-end JavaScript or Android timers)")
436
+
437
+ with gr.Tab("💠 Games"):
438
+ gr.Markdown("🎮 Play from the game portal below:")
439
+ gr.HTML(
440
+ '''
441
+ <iframe
442
+ src="https://www.onlinegames.io/embed/portal/"
443
+ width="100%"
444
+ height="600"
445
+ frameborder="0"
446
+ allowfullscreen>
447
+ </iframe>
448
+ '''
449
+ )
450
+
451
+ if __name__ == "__main__":
452
+ app.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1,7 +1,6 @@
1
- gradio==4.26.0
2
- gtts==2.5.1
3
- openai==1.30.1
4
- whisper
5
- torch
6
- ffmpeg-python
7
- SpeechRecognition==3.10.0
 
1
+ gradio==4.14.0
2
+ gtts
3
+ pydub
4
+ numpy
5
+ openai-whisper
6
+ torch