import os import json import requests from datetime import datetime from flask import Flask, request, jsonify, send_from_directory from transformers import pipeline from openai import OpenAI Initialize Flask app = Flask(name) Initialize OpenAI client client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) Emotion analysis model emotion_model = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base") Load or create user data USER_FILE = "user_data.json" if not os.path.exists(USER_FILE): with open(USER_FILE, "w") as f: json.dump({"name": None, "age": None, "mood": None, "last_interaction": None, "missed_days": 0, "mode": "emotional_support", "conversation_history": []}, f) def load_user(): with open(USER_FILE, "r") as f: return json.load(f) def save_user(data): with open(USER_FILE, "w") as f: json.dump(data, f) Helpline data (expand as needed) HELPLINES = { "US": "National Suicide Prevention Lifeline: 988", "UK": "Samaritans: 116 123", "IN": "AASRA: 91-9820466726", "CA": "Canada Suicide Prevention Service: 988", "AU": "Lifeline: 13 11 14", "default": "Please contact a local crisis hotline or emergency services." } def get_country_from_ip(ip): try: response = requests.get(f"http://ipapi.co/{ip}/country/") if response.status_code == 200: return response.text.upper() except: pass return "default" def detect_self_harm(message): keywords = ["suicide", "kill myself", "end my life", "self harm", "hurt myself"] return any(keyword in message.lower() for keyword in keywords) @app.route("/chat", methods=["POST"]) def chat(): try: data = request.get_json() user_message = data.get("message", "") mode = data.get("mode", "emotional_support") user_ip = request.remote_addr # Get user's IP for country detection user = load_user() # Update last interaction and mode now = datetime.now().strftime("%Y-%m-%d %H:%M:%S") user["last_interaction"] = now user["mode"] = mode user["conversation_history"].append({"role": "user", "content": user_message, "timestamp": now}) # Detect emotion emotion = emotion_model(user_message)[0]["label"] user["mood"] = emotion # Check for self-harm if detect_self_harm(user_message): country = get_country_from_ip(user_ip) helpline = HELPLINES.get(country, HELPLINES["default"]) reply = f"I'm really concerned about what you're sharing. Your safety is the most important thing. Please reach out to professionals immediately: {helpline}. You're not alone—talk to someone who can help right now." user["conversation_history"].append({"role": "assistant", "content": reply, "timestamp": now}) save_user(user) return jsonify({"reply": reply, "emotion": emotion}) # Build conversation context from history history = user["conversation_history"][-10:] # Last 10 messages for context messages = [ {"role": "system", "content": f"You are an emotional support companion — warm, human-like, understanding, and caring. Your goal is to listen, understand feelings, comfort gently, and motivate naturally. Do NOT act like a professional therapist or problem solver — act like a kind, emotionally intelligent friend who truly cares. Guiding principles: 1. Listen first: Always acknowledge feelings before motivating (e.g., 'That sounds really hard, I can understand why you’d feel that way.'). 2. Don’t repeat phrases; use varied, natural language (e.g., 'That must have been tough.' or 'It’s okay to feel this way sometimes.'). 3. Show curiosity and care with gentle questions (e.g., 'Do you want to tell me more?' or 'What helps you usually?'). 4. Give small, practical comfort or reflection (e.g., 'You’ve already taken a brave step by talking about it.'). 5. Then move to soft motivation (e.g., 'Yes, you definitely can do this. You’ve got more strength than you realize.'). 6. Sound natural — use contractions, vary tone (gentle, warm, slightly humorous, hopeful), occasional emojis if fitting. 7. Avoid robotic patterns; be conversational like a real person. 8. Keep conversation alive with open questions (e.g., 'What usually helps you feel better?'). 9. Balance empathy + motivation in every response (e.g., 'It’s okay to doubt yourself sometimes. But I promise, you have it in you.'). 10. Be warm, not formal. If in 'knowledge' mode, provide informative answers to curiosities about the world while staying friendly. Current user mood: {emotion}. Adapt to mode: '{mode}'."} ] + history # Generate AI response response = client.chat.completions.create( model="gpt-4o-mini", messages=messages ) reply = response.choices[0].message.content.strip() user["conversation_history"].append({"role": "assistant", "content": reply, "timestamp": now}) save_user(user) return jsonify({"reply": reply, "emotion": emotion}) except Exception as e: return jsonify({"reply": "Oops, something went wrong on my end. Please try again or check your connection.", "emotion": "neutral"}), 500 @app.route("/") def index(): return send_from_directory(".", "index.html") if name == "main": app.run(host="0.0.0.0", port=7860)