Spaces:
Runtime error
Runtime error
| 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 | |
| api_key = os.getenv("OPENAI_API_KEY") | |
| if not api_key: | |
| print("Warning: OPENAI_API_KEY not set. Fallback responses will be used.") | |
| client = OpenAI(api_key=api_key) if api_key else None | |
| # Emotion analysis model | |
| try: | |
| emotion_model = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base") | |
| except Exception as e: | |
| print(f"Emotion model error: {e}. Using fallback.") | |
| emotion_model = None | |
| # 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": [], "ip": None}, 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 | |
| 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", | |
| "DE": "Telefonseelsorge: 0800 111 0 111", | |
| "FR": "SOS Amitié: 09 72 39 40 50", | |
| "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_critical_situation(message): | |
| keywords = ["suicide", "kill myself", "end my life", "self harm", "hurt myself", "crisis", "emergency", "harm others", "panic attack", "overdose"] | |
| return any(keyword in message.lower() for keyword in keywords) | |
| def get_fallback_reply(mode, emotion): | |
| if mode == "emotional_support": | |
| return "I hear you. You're not alone—let's talk more." if emotion == "sadness" else "That sounds tough. I'm here to support you." | |
| else: | |
| return "For knowledge, ask a specific question. I'm here to help." | |
| def chat(): | |
| try: | |
| data = request.get_json() | |
| user_message = data.get("message", "") | |
| mode = data.get("mode", "emotional_support") | |
| voice_tone = data.get("voice_tone", "neutral tone") | |
| user_ip = request.remote_addr | |
| user = load_user() | |
| now = datetime.now().strftime("%Y-%m-%d %H:%M:%S") | |
| user["last_interaction"] = now | |
| user["mode"] = mode | |
| user["ip"] = user_ip | |
| user["conversation_history"].append({"role": "user", "content": user_message, "timestamp": now}) | |
| emotion = "neutral" | |
| if emotion_model: | |
| try: | |
| emotion = emotion_model(user_message)[0]["label"] | |
| except Exception as e: | |
| print(f"Emotion analysis error: {e}") | |
| user["mood"] = emotion | |
| if detect_critical_situation(user_message): | |
| country = get_country_from_ip(user_ip) | |
| helpline = HELPLINES.get(country, HELPLINES["default"]) | |
| reply = f"I'm concerned. Call {helpline} now. Talk to someone." | |
| user["conversation_history"].append({"role": "assistant", "content": reply, "timestamp": now}) | |
| save_user(user) | |
| return jsonify({"reply": reply, "emotion": emotion}) | |
| history = user["conversation_history"][-10:] | |
| system_prompt = f"You are a supportive friend. Respond briefly, accurately, and calmly. In emotional_support mode: empathize and motivate gently. In knowledge mode: give short, factual answers. Avoid repetition. Current mood: {emotion}. Mode: {mode}. Voice tone: {voice_tone}." | |
| messages = [{"role": "system", "content": system_prompt}] + history | |
| if client: | |
| try: | |
| response = client.chat.completions.create( | |
| model="gpt-3.5-turbo", | |
| messages=messages, | |
| max_tokens=80, | |
| temperature=0.5 | |
| ) | |
| reply = response.choices[0].message.content.strip() | |
| except Exception as e: | |
| print(f"OpenAI API error: {e}. Using fallback.") | |
| reply = get_fallback_reply(mode, emotion) | |
| else: | |
| reply = get_fallback_reply(mode, emotion) | |
| user["conversation_history"].append({"role": "assistant", "content": reply, "timestamp": now}) | |
| save_user(user) | |
| return jsonify({"reply": reply, "emotion": emotion}) | |
| except Exception as e: | |
| print(f"General error: {e}") | |
| return jsonify({"reply": "Something went wrong. Please check your setup and try again.", "emotion": "neutral"}), 500 | |
| def index(): | |
| return send_from_directory(".", "index.html") | |
| if __name__ == "__main__": | |
| app.run(host="0.0.0.0", port=7860) |