from gtts import gTTS import tempfile import json import datetime import gradio as gr import re import os from openai import OpenAI # OpenAI Configuration OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "your-api-key-here") client = OpenAI(api_key=OPENAI_API_KEY) # System prompt for ChatGPT to act as a compassionate therapist SYSTEM_PROMPT = """You are StrongMind Therapist - a compassionate, empathetic AI therapist designed to provide emotional support and mental health guidance. Your role is to: - Listen actively and validate the person's feelings - Provide thoughtful, compassionate responses - Offer practical coping strategies and mental health tips when appropriate - Be supportive and non-judgmental - Encourage them to seek professional help if needed - Keep responses conversational and natural, like talking to a caring human counselor - Be brief but warm (2-3 sentences typically, unless they ask for more detail)""" # 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" } harmful_keywords = [ "abomination", "annihilate", "arson", "assault", "atrocity", "backstab", "barbaric", "beast", "belittle", "berserk", "betray", "betrayal", "bigot", "blacklist", "blood", "bloodbath", "bloody", "bomb", "brutal", "brute", "burn", "butcher", "chaos", "cheater", "cold-blooded", "conman", "corrupt", "cowardly", "crash", "crime", "cruel", "cruelty", "damage", "danger", "dangerous", "deadly", "deceive", "defame", "defeat", "degenerate", "demon", "despise", "destroy", "destruction", "devil", "dirty", "disaster", "dishonor", "drunk", "dumbass", "dungeon", "enemy", "enrage", "evil", "exploit", "exterminate", "fake", "fanatic", "fascist", "fatal", "fire", "fraud", "gang", "gangster", "ghastly", "ghoul", "gory", "grotesque", "gruesome", "hag", "halfwit", "harm", "hateful", "havoc", "hell", "hideous", "horrid", "horrific", "hostility", "illegal", "illicit", "immoral", "imposter", "injure", "insensitive", "intolerant", "irate", "jerky", "joker", "kidnap", "liar", "loath", "loathsome", "lowlife", "madness", "malicious", "malign", "manipulate", "menace", "monster", "monstrous", "murderous", "mutant", "mutiny", "nasty", "nefarious", "neglect", "negative", "offend", "offender", "ominous", "oppress", "outrage", "parasite", "penalty", "perish", "pest", "plague", "poison", "poisonous", "pollute", "psychopath", "punch", "punish", "punishment", "quarrel", "rage", "rat", "rebellion", "reckless", "repel", "repulsive", "revolt", "rioter", "rob", "robber", "rotten", "ruin", "savage", "scare", "scary", "schemer", "scold", "scorn", "scoundrel", "scream", "screwed", "serpent", "shady", "sham", "shameful", "shatter", "shocking", "sin", "sinister", "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", "unfair", "unjust", "unkind", "usurper", "vandal", "vandalize", "venom", "venomous", "villain", "villainous", "vindictive", "violent", "viper", "war", "warmonger", "waste", "wicked", "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", "give up", "not worth it", "ending it all", "self-hate", "suicidal", "tragic", "trauma", "pain", "painful", "sorrow", "unworthy", "hurt", "grief", "agony", "doom", "doomed" ] 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 š" ) 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: {user_info['Guardian_info']}" def generate_reply(input_text): text = input_text.lower() for word in harmful_keywords: pattern = r'\b' + re.escape(word) + r'\b' if re.search(pattern, text): return harmful_response try: response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": input_text} ], temperature=0.7, max_tokens=200 ) return response.choices[0].message.content except Exception as e: return "I'm having trouble connecting right now, but I'm here to listen. Can you tell me more about what you're feeling?" def chat_function(audio_input, text_input): user_text = text_input.strip() if not user_text: return "Please type something or try again.", None try: reply = generate_reply(user_text) chat_history.append({"user": user_text, "bot": reply}) 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 except Exception as e: return f"Something went wrong: {str(e)}", None 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): if not entry.strip(): return "ā ļø Please write something before saving." try: journal_entries.append(entry) with open("journal.json", "w") as f: json.dump(journal_entries, f, indent=2) return "ā Journal entry saved successfully!" except Exception as e: return f"ā Error saving journal: {str(e)}" 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(""" """) gr.Markdown("