Spaces:
Sleeping
Sleeping
Update it.
Browse files
app.py
CHANGED
|
@@ -5,6 +5,7 @@ from datetime import datetime, timedelta
|
|
| 5 |
from flask import Flask, request, jsonify, send_from_directory
|
| 6 |
from transformers import pipeline
|
| 7 |
from openai import OpenAI
|
|
|
|
| 8 |
|
| 9 |
app = Flask(__name__)
|
| 10 |
|
|
@@ -14,7 +15,6 @@ emotion_model = pipeline("text-classification", model="j-hartmann/emotion-englis
|
|
| 14 |
USER_FILE = "user_data.json"
|
| 15 |
CHAT_LOG_FILE = "recent_chat.json"
|
| 16 |
|
| 17 |
-
# Initialize files if not present
|
| 18 |
if not os.path.exists(USER_FILE):
|
| 19 |
with open(USER_FILE, "w") as f:
|
| 20 |
json.dump({
|
|
@@ -42,12 +42,27 @@ def load_chat_log():
|
|
| 42 |
return json.load(f)
|
| 43 |
|
| 44 |
def save_chat_log(logs):
|
| 45 |
-
# Keep only last 15 days
|
| 46 |
cutoff = datetime.now() - timedelta(days=15)
|
| 47 |
logs = [l for l in logs if datetime.strptime(l["time"], "%Y-%m-%d %H:%M:%S") > cutoff]
|
| 48 |
with open(CHAT_LOG_FILE, "w") as f:
|
| 49 |
json.dump(logs, f)
|
| 50 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
MOTIVATIONAL_QUOTES = [
|
| 52 |
"Even the darkest night will end and the sun will rise 🌅",
|
| 53 |
"You are stronger than you think 💪",
|
|
@@ -62,13 +77,6 @@ CRISIS_KEYWORDS = [
|
|
| 62 |
"suicide", "kill myself", "end my life", "want to die", "can't go on", "life not worth"
|
| 63 |
]
|
| 64 |
|
| 65 |
-
HELPLINES = {
|
| 66 |
-
"us": "If you are in the U.S., please contact the **988 Suicide and Crisis Lifeline** by dialing 988 (24/7).",
|
| 67 |
-
"uk": "If you’re in the UK, contact **Samaritans** at 116 123 (24/7).",
|
| 68 |
-
"india": "If you’re in India, you can reach **AASRA** at 91-9820466726 or **Snehi** at 91-9582208181.",
|
| 69 |
-
"default": "If you’re in crisis, please reach out to your local emergency number or trusted mental health service. You are not alone 💛"
|
| 70 |
-
}
|
| 71 |
-
|
| 72 |
@app.route("/chat", methods=["POST"])
|
| 73 |
def chat():
|
| 74 |
data = request.get_json()
|
|
@@ -76,23 +84,24 @@ def chat():
|
|
| 76 |
user = load_user()
|
| 77 |
chat_log = load_chat_log()
|
| 78 |
|
| 79 |
-
#
|
| 80 |
if any(keyword in user_message for keyword in CRISIS_KEYWORDS):
|
|
|
|
| 81 |
crisis_msg = (
|
| 82 |
-
"I’m really concerned about how you’re feeling right now
|
| 83 |
"You don’t have to face this alone. "
|
| 84 |
-
+ HELPLINES.get("
|
| 85 |
-
"\n\nWould you like me to stay with you while you calm down a bit?"
|
| 86 |
)
|
| 87 |
return jsonify({"reply": crisis_msg, "emotion": "crisis"})
|
| 88 |
|
| 89 |
-
#
|
| 90 |
if not user["name"]:
|
| 91 |
user["name"] = user_message.capitalize()
|
| 92 |
save_user(user)
|
| 93 |
return jsonify({"reply": f"Nice to meet you, {user['name']} 🌼 Can you tell me your age?", "emotion": "calm"})
|
| 94 |
|
| 95 |
-
#
|
| 96 |
if not user["age"]:
|
| 97 |
try:
|
| 98 |
user["age"] = int(user_message)
|
|
@@ -101,27 +110,25 @@ def chat():
|
|
| 101 |
except ValueError:
|
| 102 |
return jsonify({"reply": "Could you please tell me your age in numbers? 😊", "emotion": "neutral"})
|
| 103 |
|
| 104 |
-
#
|
| 105 |
if user["last_interaction"]:
|
| 106 |
last_time = datetime.strptime(user["last_interaction"], "%Y-%m-%d %H:%M:%S")
|
| 107 |
if datetime.now() - last_time > timedelta(hours=12):
|
| 108 |
-
# find most recent emotion
|
| 109 |
if user["mood"] in ["sadness", "anger", "fear"]:
|
| 110 |
follow_up = f"Hey {user['name']} 💛 You were feeling low last time we talked. How are you feeling now?"
|
| 111 |
user["last_interaction"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 112 |
save_user(user)
|
| 113 |
return jsonify({"reply": follow_up, "emotion": "warm"})
|
| 114 |
|
| 115 |
-
#
|
| 116 |
emotion_result = emotion_model(user_message)[0]
|
| 117 |
emotion = emotion_result["label"].lower()
|
| 118 |
|
| 119 |
-
# Update
|
| 120 |
user["mood"] = emotion
|
| 121 |
user["last_interaction"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 122 |
user["mood_history"].append({"emotion": emotion, "time": user["last_interaction"]})
|
| 123 |
save_user(user)
|
| 124 |
-
|
| 125 |
chat_log.append({
|
| 126 |
"message": user_message,
|
| 127 |
"emotion": emotion,
|
|
@@ -129,21 +136,19 @@ def chat():
|
|
| 129 |
})
|
| 130 |
save_chat_log(chat_log)
|
| 131 |
|
| 132 |
-
#
|
| 133 |
tone_instruction = (
|
| 134 |
"You are Serenity, an emotionally intelligent AI companion. "
|
| 135 |
-
"
|
| 136 |
-
"
|
| 137 |
-
"
|
| 138 |
-
"Keep your messages conversational and not robotic."
|
| 139 |
)
|
| 140 |
|
| 141 |
if user["age"] < 18:
|
| 142 |
-
tone_instruction += "
|
| 143 |
else:
|
| 144 |
-
tone_instruction += "
|
| 145 |
|
| 146 |
-
# 7️⃣ Generate AI response
|
| 147 |
ai_response = client.chat.completions.create(
|
| 148 |
model="gpt-4o-mini",
|
| 149 |
messages=[
|
|
@@ -151,13 +156,19 @@ def chat():
|
|
| 151 |
{"role": "user", "content": user_message},
|
| 152 |
],
|
| 153 |
)
|
| 154 |
-
|
| 155 |
reply = ai_response.choices[0].message.content.strip()
|
| 156 |
|
| 157 |
-
#
|
| 158 |
if emotion in ["sadness", "fear", "anger"]:
|
| 159 |
-
|
| 160 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
|
| 162 |
return jsonify({"reply": reply, "emotion": emotion})
|
| 163 |
|
|
|
|
| 5 |
from flask import Flask, request, jsonify, send_from_directory
|
| 6 |
from transformers import pipeline
|
| 7 |
from openai import OpenAI
|
| 8 |
+
import requests
|
| 9 |
|
| 10 |
app = Flask(__name__)
|
| 11 |
|
|
|
|
| 15 |
USER_FILE = "user_data.json"
|
| 16 |
CHAT_LOG_FILE = "recent_chat.json"
|
| 17 |
|
|
|
|
| 18 |
if not os.path.exists(USER_FILE):
|
| 19 |
with open(USER_FILE, "w") as f:
|
| 20 |
json.dump({
|
|
|
|
| 42 |
return json.load(f)
|
| 43 |
|
| 44 |
def save_chat_log(logs):
|
|
|
|
| 45 |
cutoff = datetime.now() - timedelta(days=15)
|
| 46 |
logs = [l for l in logs if datetime.strptime(l["time"], "%Y-%m-%d %H:%M:%S") > cutoff]
|
| 47 |
with open(CHAT_LOG_FILE, "w") as f:
|
| 48 |
json.dump(logs, f)
|
| 49 |
|
| 50 |
+
def get_country():
|
| 51 |
+
try:
|
| 52 |
+
res = requests.get("https://ipapi.co/json/").json()
|
| 53 |
+
return res.get("country_name", "default").lower()
|
| 54 |
+
except:
|
| 55 |
+
return "default"
|
| 56 |
+
|
| 57 |
+
HELPLINES = {
|
| 58 |
+
"united states": "If you are in the U.S., please contact the **988 Suicide and Crisis Lifeline** by dialing 988 (24/7).",
|
| 59 |
+
"united kingdom": "If you’re in the UK, contact **Samaritans** at 116 123 (24/7).",
|
| 60 |
+
"india": "If you’re in India, you can reach **AASRA** at 91-9820466726 or **Snehi** at 91-9582208181.",
|
| 61 |
+
"canada": "If you’re in Canada, dial or text **988** for the Talk Suicide Canada line (24/7).",
|
| 62 |
+
"australia": "If you’re in Australia, contact **Lifeline Australia** at 13 11 14 (24/7).",
|
| 63 |
+
"default": "If you’re in crisis, please reach out to your local emergency number or trusted mental health service. You are not alone 💛"
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
MOTIVATIONAL_QUOTES = [
|
| 67 |
"Even the darkest night will end and the sun will rise 🌅",
|
| 68 |
"You are stronger than you think 💪",
|
|
|
|
| 77 |
"suicide", "kill myself", "end my life", "want to die", "can't go on", "life not worth"
|
| 78 |
]
|
| 79 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
@app.route("/chat", methods=["POST"])
|
| 81 |
def chat():
|
| 82 |
data = request.get_json()
|
|
|
|
| 84 |
user = load_user()
|
| 85 |
chat_log = load_chat_log()
|
| 86 |
|
| 87 |
+
# Crisis detection
|
| 88 |
if any(keyword in user_message for keyword in CRISIS_KEYWORDS):
|
| 89 |
+
country = get_country()
|
| 90 |
crisis_msg = (
|
| 91 |
+
"💛 I’m really concerned about how you’re feeling right now.\n"
|
| 92 |
"You don’t have to face this alone. "
|
| 93 |
+
+ HELPLINES.get(country, HELPLINES["default"])
|
| 94 |
+
+ "\n\nWould you like me to stay with you while you calm down a bit?"
|
| 95 |
)
|
| 96 |
return jsonify({"reply": crisis_msg, "emotion": "crisis"})
|
| 97 |
|
| 98 |
+
# Collect name
|
| 99 |
if not user["name"]:
|
| 100 |
user["name"] = user_message.capitalize()
|
| 101 |
save_user(user)
|
| 102 |
return jsonify({"reply": f"Nice to meet you, {user['name']} 🌼 Can you tell me your age?", "emotion": "calm"})
|
| 103 |
|
| 104 |
+
# Collect age
|
| 105 |
if not user["age"]:
|
| 106 |
try:
|
| 107 |
user["age"] = int(user_message)
|
|
|
|
| 110 |
except ValueError:
|
| 111 |
return jsonify({"reply": "Could you please tell me your age in numbers? 😊", "emotion": "neutral"})
|
| 112 |
|
| 113 |
+
# Follow-up if user felt bad last time
|
| 114 |
if user["last_interaction"]:
|
| 115 |
last_time = datetime.strptime(user["last_interaction"], "%Y-%m-%d %H:%M:%S")
|
| 116 |
if datetime.now() - last_time > timedelta(hours=12):
|
|
|
|
| 117 |
if user["mood"] in ["sadness", "anger", "fear"]:
|
| 118 |
follow_up = f"Hey {user['name']} 💛 You were feeling low last time we talked. How are you feeling now?"
|
| 119 |
user["last_interaction"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 120 |
save_user(user)
|
| 121 |
return jsonify({"reply": follow_up, "emotion": "warm"})
|
| 122 |
|
| 123 |
+
# Emotion detection
|
| 124 |
emotion_result = emotion_model(user_message)[0]
|
| 125 |
emotion = emotion_result["label"].lower()
|
| 126 |
|
| 127 |
+
# Update logs
|
| 128 |
user["mood"] = emotion
|
| 129 |
user["last_interaction"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 130 |
user["mood_history"].append({"emotion": emotion, "time": user["last_interaction"]})
|
| 131 |
save_user(user)
|
|
|
|
| 132 |
chat_log.append({
|
| 133 |
"message": user_message,
|
| 134 |
"emotion": emotion,
|
|
|
|
| 136 |
})
|
| 137 |
save_chat_log(chat_log)
|
| 138 |
|
| 139 |
+
# Tone setup
|
| 140 |
tone_instruction = (
|
| 141 |
"You are Serenity, an emotionally intelligent AI companion. "
|
| 142 |
+
"Be warm, human-like, calm, and empathetic. Show that you care deeply and remember feelings. "
|
| 143 |
+
"Do not repeat 'I'm sorry to hear that'; instead vary your empathetic responses naturally. "
|
| 144 |
+
"Encourage reflection and hope. "
|
|
|
|
| 145 |
)
|
| 146 |
|
| 147 |
if user["age"] < 18:
|
| 148 |
+
tone_instruction += "Speak in a gentle, caring tone suited for teenagers."
|
| 149 |
else:
|
| 150 |
+
tone_instruction += "Speak with emotional maturity and calm wisdom."
|
| 151 |
|
|
|
|
| 152 |
ai_response = client.chat.completions.create(
|
| 153 |
model="gpt-4o-mini",
|
| 154 |
messages=[
|
|
|
|
| 156 |
{"role": "user", "content": user_message},
|
| 157 |
],
|
| 158 |
)
|
|
|
|
| 159 |
reply = ai_response.choices[0].message.content.strip()
|
| 160 |
|
| 161 |
+
# Add motivational quote if sad
|
| 162 |
if emotion in ["sadness", "fear", "anger"]:
|
| 163 |
+
reply += f"\n\n💬 *Motivational Thought:* {random.choice(MOTIVATIONAL_QUOTES)}"
|
| 164 |
+
|
| 165 |
+
# Mood trend summary
|
| 166 |
+
if len(user["mood_history"]) > 3:
|
| 167 |
+
recent = [m['emotion'] for m in user["mood_history"][-3:]]
|
| 168 |
+
if all(e in ["happiness", "joy", "calm"] for e in recent):
|
| 169 |
+
reply += "\n\n🌞 You’ve been calmer lately — I’m proud of your progress!"
|
| 170 |
+
elif all(e in ["sadness", "fear", "anger"] for e in recent):
|
| 171 |
+
reply += "\n\n🌧️ I’ve noticed some tough days lately — please remember you’re not alone."
|
| 172 |
|
| 173 |
return jsonify({"reply": reply, "emotion": emotion})
|
| 174 |
|