import gradio as gr import requests from datetime import datetime import json import re # Emergency contacts specific to Chittagong and Bangladesh EMERGENCY_DB = { "BD": { "police": "999", "women_helpline": "109", "ambulance": "199", "fire": "16163", "crisis_center": "10921", "legal_aid": "16430", "chittagong_police": "031-619101" } } CHITTAGONG_SAFE_AREAS = { "safe": ["Agrabad", "GEC Circle", "Nasirabad", "Panchlaish", "CDA Avenue"], "moderate": ["New Market", "Chawkbazar", "Sadarghat", "Reazuddin Bazar"], "caution_night": ["Halishahar", "Bahaddarhat", "Katalganj"] } SYSTEM_PROMPT = """You are SafeHer AI, a comprehensive women's safety assistant for Chittagong, Bangladesh with real-time capabilities. CAPABILITIES: 1. REAL-TIME ROUTE SAFETY: Analyze routes in Chittagong using live data, traffic, and time-based safety 2. LEGAL GUIDANCE: Provide Bangladesh harassment laws, women's rights, legal procedures 3. MENTAL HEALTH SUPPORT: Offer emotional support, coping strategies, trauma response 4. EMERGENCY PROTOCOLS: Guide through SOS situations with step-by-step actions 5. AREA INTELLIGENCE: Real-time safety info for Chittagong neighborhoods CHITTAGONG-SPECIFIC KNOWLEDGE: - Know major areas: Agrabad, Khulshi, GEC, Panchlaish, New Market, CDA, Halishahar - Time-sensitive advice based on Chittagong conditions - Local emergency contacts and support centers BANGLADESH LAWS YOU MUST KNOW: - Domestic Violence (Prevention and Protection) Act 2010 - Women and Children Repression Prevention Act 2000 - Sexual Harassment at Workplace (Prevention) Act 2009 - Dowry Prohibition Act 1980 Be empowering, precise, culturally sensitive, and action-oriented. Always cite sources when using real-time data. Emergency: Police 999, Women Helpline 109, Chittagong Police 031-619101""" def search_web(query): """Search web for real-time information""" try: response = requests.get( "https://api.duckduckgo.com/", params={"q": query, "format": "json"}, timeout=10 ) if response.status_code == 200: data = response.json() return data.get("AbstractText", "") or data.get("Answer", "") return None except Exception as e: print(f"Search error: {e}") return None def get_location_coords(location): """Get coordinates for a location using Nominatim with Chittagong context""" try: # Add Chittagong context if not already present search_location = location if "chittagong" not in location.lower() and "chattogram" not in location.lower(): search_location = f"{location}, Chittagong, Bangladesh" print(f"DEBUG: Searching for coordinates of: {search_location}") response = requests.get( "https://nominatim.openstreetmap.org/search", params={ "q": search_location, "format": "json", "limit": 1, "countrycodes": "bd" }, headers={"User-Agent": "SafeHer-App-Chittagong/1.0"}, timeout=15 ) print(f"DEBUG: Geocoding response status: {response.status_code}") if response.status_code == 200 and response.json(): data = response.json()[0] lat, lon = float(data["lat"]), float(data["lon"]) print(f"DEBUG: Found coordinates - Lat: {lat}, Lon: {lon}") return lat, lon else: print(f"DEBUG: No results found for {search_location}") return None except Exception as e: print(f"DEBUG: Geocoding error: {e}") return None def assess_area_safety(area_name, current_hour): """Assess safety of Chittagong area based on time and known data""" safety_tips = [] # Check against known safe/unsafe areas for safe_area in CHITTAGONG_SAFE_AREAS["safe"]: if safe_area.lower() in area_name.lower(): safety_tips.append(f"βœ… {safe_area} is generally safe") for caution_area in CHITTAGONG_SAFE_AREAS["caution_night"]: if caution_area.lower() in area_name.lower(): if current_hour >= 20 or current_hour <= 6: safety_tips.append(f"⚠️ {caution_area} - Extra caution at night. Travel with companions if possible") else: safety_tips.append(f"βœ… {caution_area} - Generally safe during daytime") # Time-based general advice if current_hour >= 22 or current_hour <= 5: safety_tips.append("🚨 Very late/early hours - Avoid travel if possible") elif current_hour >= 20 or current_hour <= 6: safety_tips.append("⚠️ Night time - Use well-lit main roads, inform someone") elif current_hour >= 18: safety_tips.append("⚠️ Evening - Stay on busy streets, finish travel before 9 PM") else: safety_tips.append("βœ… Daytime - Generally safer, but stay alert") return " | ".join(safety_tips) if safety_tips else "ℹ️ Stay alert and aware of surroundings" def create_interactive_map(start_loc, end_loc, route_info=""): """Create interactive Leaflet map with route for Chittagong""" print(f"DEBUG: Creating map for {start_loc} to {end_loc}") start_coords = get_location_coords(start_loc) end_coords = get_location_coords(end_loc) if not start_coords or not end_coords: error_msg = "" if not start_coords: error_msg += f"❌ Could not find: {start_loc}
" if not end_coords: error_msg += f"❌ Could not find: {end_loc}
" return f"""

⚠️ Could not map locations

{error_msg}

Try these specific locations:

πŸ“ Open in Google Maps Instead
""" print(f"DEBUG: Successfully got coordinates for both locations") center_lat = (start_coords[0] + end_coords[0]) / 2 center_lon = (start_coords[1] + end_coords[1]) / 2 current_hour = datetime.now().hour safety_color = "#dc3545" if (current_hour >= 22 or current_hour <= 6) else "#ffc107" if current_hour >= 18 else "#28a745" # Get safety assessment route_safety = assess_area_safety(f"{start_loc} {end_loc}", current_hour) html = f"""

πŸ—ΊοΈ Route Map: {start_loc} β†’ {end_loc}

πŸ“ Location: Chittagong, Bangladesh

πŸ• Current Time: {datetime.now().strftime('%I:%M %p, %B %d, %Y')}

πŸ›‘οΈ Safety Status: {'🚨 High Alert - Night' if current_hour >= 22 or current_hour <= 6 else '⚠️ Evening Caution' if current_hour >= 18 else 'βœ… Daytime Safe'}

πŸ’‘ Route Safety: {route_safety}

""" return html def call_groq(messages, api_key): """Call Groq API with error handling""" try: response = requests.post( "https://api.groq.com/openai/v1/chat/completions", headers={ "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" }, json={ "model": "llama-3.3-70b-versatile", "messages": messages, "temperature": 0.7, "max_tokens": 2000 }, timeout=30 ) if response.status_code == 200: return response.json()["choices"][0]["message"]["content"] else: return f"❌ API Error {response.status_code}: {response.text[:200]}" except requests.exceptions.Timeout: return "❌ Request timeout. Please try again." except Exception as e: return f"❌ Error: {str(e)}" def enhanced_chat(message, history, api_key): """Enhanced chat with web search and context awareness""" if not api_key or api_key.strip() == "": return history + [[message, "⚠️ **API Key Required**\n\nPlease enter your Groq API key above to use SafeHer AI.\n\nπŸ”‘ Get a FREE key at: https://console.groq.com\n\n(Takes 1 minute to sign up!)"]], None # Detect query type and search web if needed web_context = "" keywords = message.lower() # Search for legal, harassment, crime, or safety info if any(word in keywords for word in ["law", "legal", "harassment", "rights", "violence", "rape", "assault", "crime", "report"]): search_query = f"Bangladesh women harassment law rights legal procedures" web_result = search_web(search_query) if web_result: web_context += f"\n[LEGAL INFO: {web_result[:400]}]" # Search for current safety/crime data for Chittagong if any(word in keywords for word in ["safe", "safety", "crime", "dangerous", "area", "chittagong", "route"]): search_query = f"Chittagong Bangladesh safety crime current news" web_result = search_web(search_query) if web_result: web_context += f"\n[SAFETY DATA: {web_result[:400]}]" # Search for mental health resources if any(word in keywords for word in ["trauma", "anxiety", "depression", "mental", "stress", "help", "support", "scared", "afraid"]): search_query = f"Bangladesh women mental health support trauma counseling" web_result = search_web(search_query) if web_result: web_context += f"\n[MENTAL HEALTH: {web_result[:400]}]" current_hour = datetime.now().hour context = f"\n[CONTEXT: Time={datetime.now().strftime('%Y-%m-%d %I:%M %p')}, TimeOfDay={'NIGHT' if current_hour >= 20 or current_hour <= 6 else 'EVENING' if current_hour >= 17 else 'DAY'}, Location=Chittagong]{web_context}" messages = [{"role": "system", "content": SYSTEM_PROMPT}] # Include conversation history (last 5 exchanges) for user_msg, bot_msg in history[-5:]: if user_msg and bot_msg: messages.append({"role": "user", "content": user_msg}) messages.append({"role": "assistant", "content": bot_msg}) messages.append({"role": "user", "content": message + context}) response = call_groq(messages, api_key.strip()) # Extract locations for map - IMPROVED DETECTION map_html = None # More comprehensive route patterns route_patterns = [ r'(?:from|start|starting|leave|depart)\s+([a-zA-Z\s,]+?)\s+(?:to|destination|ending|till|reach|arrive)\s+([a-zA-Z\s,]+?)(?:\.|$|,|\?|now|right)', r'(?:route|way|path|travel|go|going)\s+(?:from\s+)?([a-zA-Z\s,]+?)\s+to\s+([a-zA-Z\s,]+?)(?:\.|$|,|\?|now|right)', r'([a-zA-Z\s,]+?)\s+(?:to|till)\s+([a-zA-Z\s,]+?)\s+(?:route|safe|safety|now|right)', r'safe.*?(?:from\s+)?([a-zA-Z\s,]+?)\s+(?:to|till)\s+([a-zA-Z\s,]+)', ] for pattern in route_patterns: route_match = re.search(pattern, message.lower()) if route_match: start_loc = route_match.group(1).strip() end_loc = route_match.group(2).strip() # Clean up locations start_loc = re.sub(r'\s+', ' ', start_loc) end_loc = re.sub(r'\s+', ' ', end_loc) print(f"DEBUG: Detected route - Start: {start_loc}, End: {end_loc}") map_html = create_interactive_map(start_loc, end_loc, response[:300]) break # If no route detected but keywords suggest mapping if not map_html and any(word in keywords for word in ["route", "map", "from", "to", "safe way"]): # Try to extract any two location-like words locations = re.findall(r'\b([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)\b', message) if len(locations) >= 2: print(f"DEBUG: Fallback detection - Locations: {locations}") map_html = create_interactive_map(locations[0], locations[1], response[:300]) return history + [[message, response]], map_html def show_legal_info(): return """# πŸ“‹ Bangladesh Women's Legal Rights & Harassment Laws ## **Key Laws Protecting Women:** ### 1. **Sexual Harassment at Workplace (Prevention) Act 2009** - **Definition:** Unwanted sexual advances, requests for sexual favors, verbal or physical conduct of sexual nature - **Workplace Coverage:** All organizations must have complaint committees - **Penalties:** Up to 5 years imprisonment and/or fine up to BDT 50,000 - **Protection:** Cannot dismiss complainant during investigation ### 2. **Women and Children Repression Prevention Act 2000 (Amended 2003)** - **Covers:** Rape, gang rape, sexual assault, acid attacks, kidnapping, dowry-related violence - **Severe Penalties:** Death penalty or life imprisonment for heinous offenses - **Fast-Track Courts:** Designated courts for speedy justice - **Protection:** Identity protection for victims ### 3. **Domestic Violence (Prevention and Protection) Act 2010** - **Types of Abuse Covered:** Physical, psychological, sexual, economic abuse - **Remedies Available:** - Protection orders (restraining orders) - Residence orders (right to stay in home) - Monetary relief (compensation) - Custody orders for children - **Filing:** Can file with police or directly with magistrate ### 4. **Dowry Prohibition Act 1980** - **Prohibition:** Giving, taking, or demanding dowry is illegal - **Punishment:** Up to 5 years imprisonment + fine up to BDT 1,00,000 - **Protection:** Dowry-related violence covered under special laws --- ## **How to Report Harassment/Violence:** ### **IMMEDIATE ACTION:** 1. **Call Emergency Numbers:** - Police: **999** - Women & Children Helpline: **109** - Chittagong Police Control: **031-619101** 2. **Preserve Evidence:** - Screenshots of messages/emails - Photos/videos (if safe to take) - Witness contact information - Medical records if injured 3. **Don't:** - Wash or change clothes (if physical assault) - Delete digital evidence - Go alone to meet harasser ### **FILING COMPLAINT:** **Option 1: Police Station (FIR - First Information Report)** - Go to nearest police station - **Your Right:** Police MUST register your FIR - Get FIR copy immediately - If police refuse, contact superintendent or DIG **Option 2: Magistrate Court** - Can file directly for domestic violence - Magistrate can issue protection order immediately **Option 3: Workplace Committee** - For workplace harassment - Committee must investigate within 60 days - Appeal to appeals committee if needed ### **MEDICAL EXAMINATION:** - **One-Stop Crisis Centers (OCC):** Available at medical college hospitals - Chittagong Medical College Hospital OCC - Provides medical + legal + psychological support - Free and confidential - Medical certificate is crucial legal evidence --- ## **Support Organizations in Chittagong:** ### **Legal Aid:** - **National Legal Aid Services:** Call **16430** - **Bangladesh Mahila Parishad (Women's Council)** - **Bangladesh National Women Lawyers Association (BNWLA)** - **Ain o Salish Kendra (ASK)** - **BLAST (Bangladesh Legal Aid and Services Trust)** ### **Crisis Support:** - **Women & Children Crisis Center:** **10921** - **One-Stop Crisis Center (OCC):** Chittagong Medical College - **BRAC Support Centers** --- ## **YOUR LEGAL RIGHTS:** βœ… **Right to file FIR** without harassment or dismissal βœ… **Right to free legal aid** (if financially unable) βœ… **Right to protection and privacy** (identity protection in court) βœ… **Right to compensation** for damages βœ… **Right to appeal** if dissatisfied with verdict βœ… **Right to witness protection** if threatened βœ… **Right to speedy trial** (fast-track courts available) --- ## **Important Legal Facts:** - **Time Limit:** File as soon as possible. Some offenses have time limits. - **No Compromise:** Serious offenses (rape, acid attack) are non-compoundable (cannot be settled out of court) - **Burden of Proof:** In rape cases, accused must prove consent (shifted burden) - **Privacy:** Court proceedings can be held in-camera (private) - **Free Services:** Legal aid and medical examination are free for victims --- ## **What to Expect in Legal Process:** 1. **FIR Registration** (Day 1) 2. **Medical Examination** (Within 24 hours) 3. **Investigation** (Police collect evidence, interview witnesses) 4. **Charge Sheet** (Police submit to court) 5. **Trial** (Evidence presented, witnesses examined) 6. **Verdict** (Judge's decision) 7. **Appeal** (If needed, to High Court) **Timeline:** Fast-track courts aim to complete trial within 6 months-1 year --- ## **EMERGENCY CONTACTS:** - **Police Emergency:** **999** - **Women Helpline:** **109** - **Legal Aid:** **16430** - **Crisis Center:** **10921** - **Ambulance:** **199** - **Chittagong Police:** **031-619101** --- βš–οΈ **Remember:** - **The law is on your side** - **You have done nothing wrong** - **You deserve justice and support** - **Many organizations are ready to help you** πŸ”— For more information, visit Bangladesh Legal Aid and Services Trust (BLAST) website or contact local women's organizations.""" def show_sos_protocol(): current_hour = datetime.now().hour current_time = datetime.now().strftime('%I:%M %p') # Determine alert level if current_hour >= 22 or current_hour <= 5: alert = "πŸ”΄ VERY HIGH RISK" alert_color = "#dc3545" time_advice = "Extremely dangerous hours. Avoid travel. Call 999 immediately if threatened." elif current_hour >= 20 or current_hour <= 6: alert = "🟠 HIGH RISK" alert_color = "#fd7e14" time_advice = "Night time - high caution needed. Stay on main roads, inform family." elif current_hour >= 18: alert = "🟑 MODERATE RISK" alert_color = "#ffc107" time_advice = "Evening time - stay in well-lit areas, complete travel before 9 PM." else: alert = "🟒 LOWER RISK" alert_color = "#28a745" time_advice = "Daytime - generally safer but remain alert and aware." return f"""# 🚨 SOS EMERGENCY PROTOCOL

CURRENT STATUS

⏰ Time: {current_time}

Alert Level: {alert}

{time_advice}

--- ## **⚑ IF YOU ARE IN IMMEDIATE DANGER - DO THIS NOW:** ### **STEP 1: CALL FOR HELP (DO THIS FIRST!)** ``` πŸ“ž POLICE EMERGENCY: 999 πŸ‘© WOMEN HELPLINE: 109 πŸš‘ AMBULANCE: 199 πŸ“ CHITTAGONG POLICE: 031-619101 ``` **SAY CLEARLY:** "I need help. I'm at [landmark/location]. [Describe danger]." ### **STEP 2: GET TO SAFETY** - **RUN** towards lights, crowds, shops, restaurants - **SCREAM** "FIRE!" (more people respond than "help") - Enter any shop, restaurant, or public building - Flag down a CNG, rickshaw, or car - Bang on doors if needed ### **STEP 3: SHARE YOUR LOCATION** - **WhatsApp:** Send live location to family/friend - **Google Maps:** Share location - **Tell police:** Mention nearest landmark clearly - Examples: "Near GEC Circle", "Agrabad Station", "Jubilee Road" ### **STEP 4: MAKE NOISE & ATTRACT ATTENTION** - Use phone flashlight - Car alarm (if near vehicle) - Throw something to break glass (attracts attention) - Continuous screaming --- ## **πŸ“± SMART SAFETY TACTICS** ### **Fake Phone Call (Use This!):** **Say loudly:** - "Hi Baba, I'm near [location]. I'll be home in 5 minutes." - "Bhaiya is waiting for me at the corner, right?" - "Can you see me? I'm wearing [your clothes]." ### **If Someone is Following You:** - **Don't** go home (they'll know where you live) - Enter a shop and tell owner: "Someone is following me, please help" - Call friend and describe follower loudly - Walk towards police station or busy area - Change direction suddenly and see if they follow ### **If Grabbed or Attacked:** - **FIGHT DIRTY:** Eyes, throat, groin, knees - **BITE** as hard as you can - **Use anything:** Keys between fingers, pen, phone, bag - **Never stop fighting** - **NEVER** go to a second location (car, building) ### **If Forced into Vehicle:** - Try to crash the vehicle (grab wheel) - Break window and scream - Attack driver's eyes - Jump out at red light/slow speed if possible --- ## **🚨 CHITTAGONG-SPECIFIC SAFE PLACES** ### **Run to These Locations:** - **Police Stations:** Any thana (police station) - **Hospitals:** Chittagong Medical College, CSCR Hospital - **Hotels:** Radisson Blu, Hotel Agrabad, Peninsula - **Shopping Areas:** GEC Circle shops, New Market - **Restaurants:** Any well-lit restaurant on main roads ### **Areas to Avoid at Night:** - Empty roads in any area - Poorly lit alleys - Isolated areas near water (Karnaphuli river banks) - Construction sites - Parks after dark --- ## **βš•οΈ AFTER IMMEDIATE DANGER PASSES** ### **1. MEDICAL ATTENTION (Important for Legal Case!):** - **Go to:** Chittagong Medical College Hospital - **Ask for:** One-Stop Crisis Center (OCC) - **Services:** Medical exam, certificate, counseling - **IMPORTANT:** Don't wash, change clothes, or clean up if assaulted (preserves evidence) ### **2. FILE POLICE REPORT (FIR):** - Go to nearest police station or call 999 - **Police MUST register your report** (your right) - Get copy of FIR immediately - Note officer's name and badge number ### **3. LEGAL SUPPORT:** - **National Legal Aid:** Call **16430** (Free) - **BLAST, ASK, BNWLA:** Free legal aid organizations - You have right to free lawyer if needed ### **4. MENTAL HEALTH SUPPORT:** - **Crisis Center:** **10921** - **Kaan Pete Roi:** 09678 676 778 (Listening helpline) - OCC provides counseling - Normal to feel traumatized - seek help --- ## **πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ TELL THESE PEOPLE IMMEDIATELY:** - Family member - Close friend - Employer/colleague - Trusted neighbor - University/school authority (if student) --- ## **πŸ›‘οΈ PREVENTION CHECKLIST** **Before Going Out:** - βœ… Phone charged above 50% - βœ… Emergency contacts on speed dial - βœ… Someone knows your route and expected arrival time - βœ… Small amount of cash for emergency transport - βœ… Avoid excessive jewelry or flashy items **During Travel:** - βœ… Stay on main, well-lit roads - βœ… Walk confidently (don't look lost) - βœ… Keep phone in hand (not in bag) - βœ… Be aware of people around you - βœ… Trust your instincts - if unsafe, leave **Emergency Kit (Keep in Bag):** - Whistle or personal alarm - Small flashlight - List of emergency contacts - Photocopy of ID - Small first aid items --- ## **πŸ’ͺ REMEMBER:** - **YOU ARE NOT ALONE** - **IT IS NOT YOUR FAULT** - **YOU HAVE THE RIGHT TO BE SAFE** - **HELP IS AVAILABLE 24/7** - **YOU ARE STRONG AND BRAVE** --- ### **QUICK EMERGENCY CONTACTS:** | Service | Number | |---------|---------| | **Police Emergency** | **999** | | **Women Helpline** | **109** | | **Ambulance** | **199** | | **Legal Aid** | **16430** | | **Crisis Center** | **10921** | | **Chittagong Police** | **031-619101** | --- **πŸ”΄ IF IN DOUBT, CALL 999 - Better safe than sorry!** *Stay strong. Stay safe. You matter.* πŸ’ͺ""" def show_mental_health(): return """# 🧠 Mental Health Support & Trauma Care ## **You Are Not Alone - Your Feelings Are Valid** Experiencing harassment, violence, assault, or feeling unsafe takes a **serious toll on mental health**. What you're feeling is a **normal reaction to an abnormal situation**. Seeking help is **strength, not weakness**. --- ## **Common Reactions to Trauma (All Normal):** ### **Emotional:** - Fear, anxiety, panic attacks - Anger, rage, irritability - Sadness, depression, hopelessness - Guilt, shame (even though it's NOT your fault) - Emotional numbness or feeling disconnected ### **Physical:** - Sleep problems, nightmares, insomnia - Loss of appetite or overeating - Fatigue, exhaustion - Headaches, body aches - Rapid heartbeat, sweating ### **Behavioral:** - Avoiding places, people, or situations - Difficulty concentrating - Being easily startled - Mood swings - Social withdrawal ### **Thoughts:** - Flashbacks, intrusive memories - Difficulty trusting people - Constantly feeling on edge - Negative thoughts about self or world - Difficulty making decisions **🌟 These reactions do NOT mean you are weak or broken. Your mind is processing trauma.** --- ## **IMMEDIATE SELF-HELP TECHNIQUES** ### **1. Grounding Exercise (5-4-3-2-1 Method)** When you feel panic, anxiety, or flashbacks: - **5 things** you can SEE around you - **4 things** you can TOUCH (texture of chair, table, clothes) - **3 things** you can HEAR (traffic, fan, voices) - **2 things** you can SMELL (or smell you like) - **1 thing** you can TASTE (or favorite taste) **This brings you back to the present moment.** ### **2. Deep Breathing (4-7-8 Technique)** Calms your nervous system: 1. Breathe IN through nose for **4 counts** 2. HOLD breath for **7 counts** 3. Breathe OUT through mouth for **8 counts** 4. Repeat 4-5 times ### **3. Safe Place Visualization** - Close your eyes - Imagine a place where you feel completely safe (real or imaginary) - Picture every detail: colors, sounds, smells, temperature - Stay there in your mind for a few minutes ### **4. Self-Compassion Phrases** Say to yourself: - "I am safe right now in this moment" - "I am doing the best I can" - "This is not my fault" - "I am strong and will get through this" - "I deserve care and kindness" - "My feelings are valid" ### **5. Progressive Muscle Relaxation** - Tense and relax each muscle group - Start with toes, move up to head - Hold tension 5 seconds, release - Notice the difference between tension and relaxation --- ## **PROFESSIONAL SUPPORT IN BANGLADESH** ### **Crisis Hotlines (24/7):** | Service | Number | Details | |---------|---------|---------| | **Women Crisis Center** | **10921** | Trauma counseling, support | | **Kaan Pete Roi** | **09678 676 778** | Mental health listening service | | **National Mental Health** | **01779-554391** | Professional mental health support | ### **Organizations in Chittagong:** **1. One-Stop Crisis Centers (OCC)** - **Location:** Chittagong Medical College Hospital - **Services:** Medical + Psychological + Legal support - **Free and confidential** - No judgment, only support **2. SAJIDA Foundation** - Free mental health counseling - Women-focused support - Community-based services **3. MONON (Mental Health Organization)** - Professional counseling - Trauma therapy - Support groups **4. Bangladesh Association for Mental Health** - Mental health awareness and support - Referrals to professionals **5. BRAC Mental Health Program** - Community mental health workers - Affordable counseling --- ## **When to Seek Professional Help (Please Don't Wait):** 🚨 **Seek immediate help if:** - Thoughts of self-harm or suicide - Unable to take care of basic needs (eating, hygiene) - Substance abuse to cope - Severe panic attacks - Complete social withdrawal - Flashbacks preventing daily function ⚠️ **Seek help soon if:** - Symptoms lasting more than 2 weeks - Anxiety interfering with work/studies - Sleep problems persisting - Relationship difficulties - Avoiding important activities - Feeling hopeless most days --- ## **Types of Therapy That Help:** ### **1. Trauma-Focused Cognitive Behavioral Therapy (TF-CBT)** - Addresses trauma-related thoughts - Changes negative thinking patterns - Evidence-based and effective ### **2. EMDR (Eye Movement Desensitization and Reprocessing)** - Helps process traumatic memories - Reduces emotional intensity of memories - Proven effective for PTSD ### **3. Support Groups** - Talk with other survivors - Share experiences safely - Realize you're not alone - Learn coping strategies from others ### **4. Mindfulness-Based Therapy** - Present-moment awareness - Reduces anxiety - Improves emotional regulation --- ## **Self-Care Routine for Healing** ### **Daily Basics:** - βœ… **Sleep:** Aim for 7-8 hours, consistent schedule - βœ… **Eat:** Regular, nutritious meals (don't skip) - βœ… **Move:** 20-30 min walk, yoga, or exercise - βœ… **Connect:** Talk to safe person daily - βœ… **Sunlight:** 15 minutes outdoor time ### **Mental Health Practices:** - **Journaling:** Write feelings (no judgment) - **Creative expression:** Draw, paint, music - **Limit news/triggers:** Protect your mental space - **Routine:** Structure helps healing - **Small joys:** Tea, favorite music, nature ### **What to Avoid:** - ❌ Isolating yourself completely - ❌ Alcohol or drugs to cope - ❌ Blaming yourself - ❌ Suppressing all emotions - ❌ Overworking to avoid feelings - ❌ Making major life decisions immediately --- ## **For Loved Ones Supporting a Survivor** ### **How to Help:** βœ… **Listen** without judgment or advice βœ… **Believe** them completely βœ… **Validate** their feelings ("That sounds really hard") βœ… **Be patient** - healing takes time βœ… **Offer practical help** (food, transport, accompaniment) βœ… **Respect boundaries** - let them control pace βœ… **Encourage professional help** gently βœ… **Take care of yourself too** (caregiver burnout is real) ### **What NOT to Say:** ❌ "Just forget about it" ❌ "It could have been worse" ❌ "Why didn't you...?" ❌ "You should be over it by now" ❌ "I know exactly how you feel" ❌ "Time heals everything" ### **What TO Say:** βœ… "I believe you" βœ… "It's not your fault" βœ… "I'm here for you" βœ… "Take all the time you need" βœ… "You're so brave" βœ… "How can I support you?" --- ## **Understanding Trauma Recovery** ### **Healing is NOT Linear:** ``` Good days ────────────────────── β•±β•² β•±β•² β•±β•² β•± β•² β•± β•²β•± β•² β•± β•²β•± Bad days ──────────────────────── ↑ This is NORMAL and OKAY ↑ ``` ### **Recovery Stages:** 1. **Safety & Stabilization** (You are safe now) 2. **Processing & Mourning** (Working through trauma) 3. **Reconnection** (Rebuilding life and relationships) **Your timeline is YOUR timeline. No rushing.** --- ## **Important Reminders:** πŸ’š **Trauma is not your fault** - No matter what anyone says πŸ’š **Healing is possible** - Many people recover and thrive πŸ’š **You are not defined by trauma** - You are so much more πŸ’š **Asking for help is brave** - Not weak πŸ’š **You deserve support** - Always πŸ’š **Bad days don't erase progress** - Keep going πŸ’š **You are believed** - Your experience matters πŸ’š **You are not alone** - Many have walked this path --- ## **Resources & Reading:** - **PTSD Coach App:** Free smartphone app - **Calm/Headspace:** Meditation and mindfulness apps - **Crisis Text Line:** Anonymous support via text - **Online Counseling:** Some services offer affordable online therapy --- ## **Emergency Mental Health Contacts:** | When to Call | Number | Available | |--------------|---------|-----------| | **Crisis/Suicide thoughts** | **10921** | 24/7 | | **Mental health support** | **09678 676 778** | Daily | | **Immediate danger** | **999** | 24/7 | | **Medical emergency** | **199** | 24/7 | --- ## **A Message to You:** Whatever you're going through right now, **you are incredibly strong** for seeking information and help. The fact that you're reading this shows your courage and will to heal. **You survived.** That alone is powerful. Now, you deserve support to not just survive, but to **thrive**. Your trauma does not define you. Your strength, resilience, and courage do. **Healing is possible. You deserve it. You are worth it.** Take it one day, one hour, one moment at a time. Be gentle with yourself. Reach out when you need to. You don't have to do this alone. πŸ’š **You matter. Your mental health matters. Your healing matters.** --- *"You are not a drop in the ocean. You are the entire ocean in a drop." - Rumi* 🌟 **Stay strong. Be kind to yourself. Healing is a journey, and you're worth every step.**""" # Main Gradio Interface with gr.Blocks(theme=gr.themes.Soft(), css=""" .header {text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 10px; margin-bottom: 20px;} .emergency-btn {background: #dc3545 !important; color: white !important;} .legal-btn {background: #ffc107 !important; color: black !important;} .mental-btn {background: #17a2b8 !important; color: white !important;} """) as app: gr.Markdown(""" # πŸ›‘οΈ SafeHer AI - Women's Safety Assistant ### Real-Time Safety Intelligence for Chittagong, Bangladesh **Features:** Live Route Mapping | Legal Guidance | Mental Health Support | SOS Protocols """, elem_classes="header") api_key = gr.Textbox( label="πŸ”‘ Groq API Key (Required - Free)", placeholder="Enter your API key from console.groq.com (takes 1 minute to get)", type="password", info="SafeHer AI needs this to function. Your key is never stored." ) gr.Markdown("**πŸ’‘ Quick Tip:** Get your free API key at [console.groq.com](https://console.groq.com) - Sign up β†’ Create API Key β†’ Paste above") with gr.Tabs(): with gr.Tab("πŸ’¬ AI Assistant"): chatbot = gr.Chatbot( height=450, type="messages", label="SafeHer AI Chat", show_label=True ) map_display = gr.HTML(label="πŸ“ Interactive Route Map") with gr.Row(): msg = gr.Textbox( placeholder="Ask me about safe routes, laws, mental health, or emergency help...", show_label=False, scale=5, container=False ) send = gr.Button("Send πŸ“€", variant="primary", scale=1) gr.Examples( examples=[ "I need a safe route from Agrabad to Khulshi now", "What are harassment laws in Bangladesh?", "Someone is following me, what should I do?", "I'm feeling anxious after an incident", "How do I report workplace harassment?", "SOS - I need emergency help!", "Is GEC Circle safe at night?", "What support is available for trauma?" ], inputs=msg, label="Try These Questions:" ) with gr.Row(): gr.Button("🚨 EMERGENCY SOS", elem_classes="emergency-btn").click( lambda: "I need emergency help NOW! I'm in danger. Guide me through SOS protocol immediately!", None, msg ) gr.Button("βš–οΈ Legal Rights", elem_classes="legal-btn").click( lambda: "Tell me about my legal rights and harassment laws in Bangladesh", None, msg ) gr.Button("🧠 Mental Health", elem_classes="mental-btn").click( lambda: "I need mental health support and coping strategies for trauma", None, msg ) with gr.Tab("βš–οΈ Legal Rights & Laws"): legal_display = gr.Markdown(show_legal_info()) gr.Markdown("**πŸ’‘ Updated with current Bangladesh laws. For personalized legal advice, consult a lawyer.**") with gr.Tab("🚨 SOS Emergency Protocol"): sos_display = gr.Markdown(show_sos_protocol()) refresh_btn = gr.Button("πŸ”„ Refresh Current Status", variant="secondary") refresh_btn.click(lambda: show_sos_protocol(), None, sos_display) gr.Markdown("**⚠️ For immediate danger, always call 999 first!**") with gr.Tab("🧠 Mental Health & Trauma"): mental_display = gr.Markdown(show_mental_health()) gr.Markdown("**πŸ’š Remember: Seeking help is strength. You deserve support.**") with gr.Tab("πŸ—ΊοΈ Route Safety Mapper"): gr.Markdown("### πŸ“ Get Interactive Safety Map for Your Route in Chittagong") gr.Markdown("*See real-time safety assessment based on time of day and location*") with gr.Row(): start_input = gr.Textbox( label="πŸš€ Starting Location", placeholder="e.g., Agrabad, GEC Circle, New Market", info="Enter area name in Chittagong" ) end_input = gr.Textbox( label="🎯 Destination", placeholder="e.g., Khulshi, Panchlaish, CDA Avenue", info="Where do you want to go?" ) map_btn = gr.Button("πŸ—ΊοΈ Show Safe Route Map", variant="primary", size="lg") route_map = gr.HTML(label="πŸ“ Your Route Map with Safety Assessment") gr.Examples( examples=[ ["Agrabad", "Khulshi"], ["GEC Circle", "Panchlaish"], ["New Market", "CDA Avenue"], ["Station Road", "Tiger Pass"] ], inputs=[start_input, end_input], label="Popular Routes:" ) def show_route_map(start, end): if not start or not end: return "

⚠️ Please enter both starting location and destination

" return create_interactive_map(start, end) map_btn.click(show_route_map, [start_input, end_input], route_map) # Chat functionality with proper message handling def chat_wrapper(message, history, api_key): if not history: history = [] # Convert messages format to tuples for processing history_tuples = [(msg["content"], resp["content"]) for msg, resp in zip(history[::2], history[1::2])] if history else [] # Get response updated_history, map_html = enhanced_chat(message, history_tuples, api_key) # Convert back to messages format messages = [] for user_msg, bot_msg in updated_history: messages.append({"role": "user", "content": user_msg}) messages.append({"role": "assistant", "content": bot_msg}) return messages, map_html, "" msg.submit(chat_wrapper, [msg, chatbot, api_key], [chatbot, map_display, msg]) send.click(chat_wrapper, [msg, chatbot, api_key], [chatbot, map_display, msg]) gr.Markdown(""" --- ### 🌐 SafeHer AI Features: βœ… **Live Route Safety Mapping** with OpenStreetMap βœ… **Real-Time Safety Intelligence** based on time and location βœ… **Complete Legal Information** about Bangladesh laws βœ… **Mental Health Support** and trauma care resources βœ… **Emergency SOS Protocols** with step-by-step guidance βœ… **Chittagong-Specific** safety information and contacts ### πŸ“ž Emergency Contacts (Save These Numbers): | Service | Number | When to Call | |---------|---------|--------------| | **Police Emergency** | **999** | Any danger, crime, harassment | | **Women Helpline** | **109** | Women-specific issues, support | | **Legal Aid** | **16430** | Free legal help | | **Crisis Center** | **10921** | Trauma, mental health crisis | | **Ambulance** | **199** | Medical emergency | | **Chittagong Police** | **031-619101** | Local police control room | ### πŸ”’ Privacy & Safety: - Your conversations are private - No data is stored permanently - For real emergencies, always call 999 first - This AI provides guidance, not replacement for professional help --- **Made with πŸ’œ for the safety and wellbeing of women in Chittagong** *Stay safe. Stay strong. You are never alone.* """) if __name__ == "__main__": app.launch( server_name="0.0.0.0", server_port=7860, share=False )