Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -10,10 +10,17 @@ from openai import OpenAI
|
|
| 10 |
app = Flask(__name__)
|
| 11 |
|
| 12 |
# Initialize OpenAI client
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
# Emotion analysis model
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
# Load or create user data
|
| 19 |
USER_FILE = "user_data.json"
|
|
@@ -29,7 +36,7 @@ def save_user(data):
|
|
| 29 |
with open(USER_FILE, "w") as f:
|
| 30 |
json.dump(data, f)
|
| 31 |
|
| 32 |
-
# Helpline data
|
| 33 |
HELPLINES = {
|
| 34 |
"US": "National Suicide Prevention Lifeline: 988",
|
| 35 |
"UK": "Samaritans: 116 123",
|
|
@@ -54,57 +61,70 @@ def detect_critical_situation(message):
|
|
| 54 |
keywords = ["suicide", "kill myself", "end my life", "self harm", "hurt myself", "crisis", "emergency", "harm others", "panic attack", "overdose"]
|
| 55 |
return any(keyword in message.lower() for keyword in keywords)
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
@app.route("/chat", methods=["POST"])
|
| 58 |
def chat():
|
| 59 |
try:
|
| 60 |
data = request.get_json()
|
| 61 |
user_message = data.get("message", "")
|
| 62 |
mode = data.get("mode", "emotional_support")
|
| 63 |
-
voice_tone = data.get("voice_tone", "neutral tone")
|
| 64 |
-
user_ip = request.remote_addr
|
| 65 |
user = load_user()
|
| 66 |
|
| 67 |
-
# Update last interaction, mode, and collect IP if not set
|
| 68 |
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 69 |
user["last_interaction"] = now
|
| 70 |
user["mode"] = mode
|
| 71 |
user["ip"] = user_ip
|
| 72 |
user["conversation_history"].append({"role": "user", "content": user_message, "timestamp": now})
|
| 73 |
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
user["mood"] = emotion
|
| 77 |
|
| 78 |
-
# Check for critical situation
|
| 79 |
if detect_critical_situation(user_message):
|
| 80 |
country = get_country_from_ip(user_ip)
|
| 81 |
helpline = HELPLINES.get(country, HELPLINES["default"])
|
| 82 |
-
reply = f"I'm
|
| 83 |
user["conversation_history"].append({"role": "assistant", "content": reply, "timestamp": now})
|
| 84 |
save_user(user)
|
| 85 |
return jsonify({"reply": reply, "emotion": emotion})
|
| 86 |
|
| 87 |
-
# Build conversation context from history (limit to last 10 for precision)
|
| 88 |
history = user["conversation_history"][-10:]
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
user["conversation_history"].append({"role": "assistant", "content": reply, "timestamp": now})
|
| 103 |
save_user(user)
|
| 104 |
|
| 105 |
return jsonify({"reply": reply, "emotion": emotion})
|
| 106 |
except Exception as e:
|
| 107 |
-
|
|
|
|
| 108 |
|
| 109 |
@app.route("/")
|
| 110 |
def index():
|
|
|
|
| 10 |
app = Flask(__name__)
|
| 11 |
|
| 12 |
# Initialize OpenAI client
|
| 13 |
+
api_key = os.getenv("OPENAI_API_KEY")
|
| 14 |
+
if not api_key:
|
| 15 |
+
print("Warning: OPENAI_API_KEY not set. Fallback responses will be used.")
|
| 16 |
+
client = OpenAI(api_key=api_key) if api_key else None
|
| 17 |
|
| 18 |
# Emotion analysis model
|
| 19 |
+
try:
|
| 20 |
+
emotion_model = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base")
|
| 21 |
+
except Exception as e:
|
| 22 |
+
print(f"Emotion model error: {e}. Using fallback.")
|
| 23 |
+
emotion_model = None
|
| 24 |
|
| 25 |
# Load or create user data
|
| 26 |
USER_FILE = "user_data.json"
|
|
|
|
| 36 |
with open(USER_FILE, "w") as f:
|
| 37 |
json.dump(data, f)
|
| 38 |
|
| 39 |
+
# Helpline data
|
| 40 |
HELPLINES = {
|
| 41 |
"US": "National Suicide Prevention Lifeline: 988",
|
| 42 |
"UK": "Samaritans: 116 123",
|
|
|
|
| 61 |
keywords = ["suicide", "kill myself", "end my life", "self harm", "hurt myself", "crisis", "emergency", "harm others", "panic attack", "overdose"]
|
| 62 |
return any(keyword in message.lower() for keyword in keywords)
|
| 63 |
|
| 64 |
+
def get_fallback_reply(mode, emotion):
|
| 65 |
+
if mode == "emotional_support":
|
| 66 |
+
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."
|
| 67 |
+
else:
|
| 68 |
+
return "For knowledge, ask a specific question. I'm here to help."
|
| 69 |
+
|
| 70 |
@app.route("/chat", methods=["POST"])
|
| 71 |
def chat():
|
| 72 |
try:
|
| 73 |
data = request.get_json()
|
| 74 |
user_message = data.get("message", "")
|
| 75 |
mode = data.get("mode", "emotional_support")
|
| 76 |
+
voice_tone = data.get("voice_tone", "neutral tone")
|
| 77 |
+
user_ip = request.remote_addr
|
| 78 |
user = load_user()
|
| 79 |
|
|
|
|
| 80 |
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 81 |
user["last_interaction"] = now
|
| 82 |
user["mode"] = mode
|
| 83 |
user["ip"] = user_ip
|
| 84 |
user["conversation_history"].append({"role": "user", "content": user_message, "timestamp": now})
|
| 85 |
|
| 86 |
+
emotion = "neutral"
|
| 87 |
+
if emotion_model:
|
| 88 |
+
try:
|
| 89 |
+
emotion = emotion_model(user_message)[0]["label"]
|
| 90 |
+
except Exception as e:
|
| 91 |
+
print(f"Emotion analysis error: {e}")
|
| 92 |
user["mood"] = emotion
|
| 93 |
|
|
|
|
| 94 |
if detect_critical_situation(user_message):
|
| 95 |
country = get_country_from_ip(user_ip)
|
| 96 |
helpline = HELPLINES.get(country, HELPLINES["default"])
|
| 97 |
+
reply = f"I'm concerned. Call {helpline} now. Talk to someone."
|
| 98 |
user["conversation_history"].append({"role": "assistant", "content": reply, "timestamp": now})
|
| 99 |
save_user(user)
|
| 100 |
return jsonify({"reply": reply, "emotion": emotion})
|
| 101 |
|
|
|
|
| 102 |
history = user["conversation_history"][-10:]
|
| 103 |
+
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}."
|
| 104 |
+
messages = [{"role": "system", "content": system_prompt}] + history
|
| 105 |
+
|
| 106 |
+
if client:
|
| 107 |
+
try:
|
| 108 |
+
response = client.chat.completions.create(
|
| 109 |
+
model="gpt-3.5-turbo",
|
| 110 |
+
messages=messages,
|
| 111 |
+
max_tokens=80,
|
| 112 |
+
temperature=0.5
|
| 113 |
+
)
|
| 114 |
+
reply = response.choices[0].message.content.strip()
|
| 115 |
+
except Exception as e:
|
| 116 |
+
print(f"OpenAI API error: {e}. Using fallback.")
|
| 117 |
+
reply = get_fallback_reply(mode, emotion)
|
| 118 |
+
else:
|
| 119 |
+
reply = get_fallback_reply(mode, emotion)
|
| 120 |
+
|
| 121 |
user["conversation_history"].append({"role": "assistant", "content": reply, "timestamp": now})
|
| 122 |
save_user(user)
|
| 123 |
|
| 124 |
return jsonify({"reply": reply, "emotion": emotion})
|
| 125 |
except Exception as e:
|
| 126 |
+
print(f"General error: {e}")
|
| 127 |
+
return jsonify({"reply": "Something went wrong. Please check your setup and try again.", "emotion": "neutral"}), 500
|
| 128 |
|
| 129 |
@app.route("/")
|
| 130 |
def index():
|