Spaces:
Sleeping
Sleeping
| 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() | |