Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,17 +9,25 @@ from openai import OpenAI
|
|
| 9 |
# Initialize Flask
|
| 10 |
app = Flask(__name__)
|
| 11 |
|
| 12 |
-
# Initialize OpenAI client
|
| 13 |
-
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
| 14 |
-
|
| 15 |
# Emotion analysis model (cached for performance)
|
| 16 |
-
emotion_model = pipeline(
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
# Load or create user data
|
| 19 |
USER_FILE = "user_data.json"
|
| 20 |
if not os.path.exists(USER_FILE):
|
| 21 |
with open(USER_FILE, "w") as f:
|
| 22 |
-
json.dump({
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
def load_user():
|
| 25 |
with open(USER_FILE, "r") as f:
|
|
@@ -29,7 +37,14 @@ def save_user(data):
|
|
| 29 |
with open(USER_FILE, "w") as f:
|
| 30 |
json.dump(data, f)
|
| 31 |
|
| 32 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
HELPLINES = {
|
| 34 |
"US": "National Suicide Prevention Lifeline: 988",
|
| 35 |
"UK": "Samaritans: 116 123",
|
|
@@ -58,52 +73,80 @@ def chat():
|
|
| 58 |
data = request.get_json()
|
| 59 |
user_message = data.get("message", "")
|
| 60 |
mode = data.get("mode", "emotional_support")
|
| 61 |
-
user_ip = request.remote_addr
|
| 62 |
user = load_user()
|
| 63 |
|
| 64 |
-
# Update last interaction and mode
|
| 65 |
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 66 |
user["last_interaction"] = now
|
| 67 |
user["mode"] = mode
|
| 68 |
-
user["conversation_history"].append({
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
-
#
|
| 71 |
emotion = emotion_model(user_message)[0]["label"]
|
| 72 |
user["mood"] = emotion
|
| 73 |
|
| 74 |
-
#
|
| 75 |
if detect_self_harm(user_message):
|
| 76 |
country = get_country_from_ip(user_ip)
|
| 77 |
helpline = HELPLINES.get(country, HELPLINES["default"])
|
| 78 |
-
reply =
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
save_user(user)
|
| 81 |
return jsonify({"reply": reply, "emotion": emotion})
|
| 82 |
|
| 83 |
-
#
|
| 84 |
-
history = user["conversation_history"][-10:]
|
| 85 |
messages = [
|
| 86 |
-
{"role": "system", "content":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
] + history
|
| 88 |
|
| 89 |
-
#
|
| 90 |
-
|
|
|
|
| 91 |
model="gpt-4o-mini",
|
| 92 |
-
messages=messages
|
|
|
|
| 93 |
)
|
| 94 |
|
| 95 |
-
reply =
|
| 96 |
-
user["conversation_history"].append({
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
save_user(user)
|
| 98 |
|
| 99 |
return jsonify({"reply": reply, "emotion": emotion})
|
|
|
|
| 100 |
except Exception as e:
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
@app.route("/")
|
| 104 |
def index():
|
| 105 |
return send_from_directory(".", "index.html")
|
| 106 |
|
| 107 |
if __name__ == "__main__":
|
| 108 |
-
app.run(host="0.0.0.0", port=7860)
|
| 109 |
-
|
|
|
|
| 9 |
# Initialize Flask
|
| 10 |
app = Flask(__name__)
|
| 11 |
|
|
|
|
|
|
|
|
|
|
| 12 |
# Emotion analysis model (cached for performance)
|
| 13 |
+
emotion_model = pipeline(
|
| 14 |
+
"text-classification",
|
| 15 |
+
model="j-hartmann/emotion-english-distilroberta-base"
|
| 16 |
+
)
|
| 17 |
|
| 18 |
# Load or create user data
|
| 19 |
USER_FILE = "user_data.json"
|
| 20 |
if not os.path.exists(USER_FILE):
|
| 21 |
with open(USER_FILE, "w") as f:
|
| 22 |
+
json.dump({
|
| 23 |
+
"name": None,
|
| 24 |
+
"age": None,
|
| 25 |
+
"mood": None,
|
| 26 |
+
"last_interaction": None,
|
| 27 |
+
"missed_days": 0,
|
| 28 |
+
"mode": "emotional_support",
|
| 29 |
+
"conversation_history": []
|
| 30 |
+
}, f)
|
| 31 |
|
| 32 |
def load_user():
|
| 33 |
with open(USER_FILE, "r") as f:
|
|
|
|
| 37 |
with open(USER_FILE, "w") as f:
|
| 38 |
json.dump(data, f)
|
| 39 |
|
| 40 |
+
# 🔐 Secure OpenAI key access each time (fixes your bug)
|
| 41 |
+
def get_openai_client():
|
| 42 |
+
api_key = os.getenv("OPENAI_API_KEY")
|
| 43 |
+
if not api_key:
|
| 44 |
+
raise ValueError("Missing OpenAI API key. Please add OPENAI_API_KEY in Hugging Face Secrets.")
|
| 45 |
+
return OpenAI(api_key=api_key)
|
| 46 |
+
|
| 47 |
+
# Helpline data
|
| 48 |
HELPLINES = {
|
| 49 |
"US": "National Suicide Prevention Lifeline: 988",
|
| 50 |
"UK": "Samaritans: 116 123",
|
|
|
|
| 73 |
data = request.get_json()
|
| 74 |
user_message = data.get("message", "")
|
| 75 |
mode = data.get("mode", "emotional_support")
|
| 76 |
+
user_ip = request.remote_addr
|
| 77 |
user = load_user()
|
| 78 |
|
|
|
|
| 79 |
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 80 |
user["last_interaction"] = now
|
| 81 |
user["mode"] = mode
|
| 82 |
+
user["conversation_history"].append({
|
| 83 |
+
"role": "user",
|
| 84 |
+
"content": user_message,
|
| 85 |
+
"timestamp": now
|
| 86 |
+
})
|
| 87 |
|
| 88 |
+
# Emotion detection
|
| 89 |
emotion = emotion_model(user_message)[0]["label"]
|
| 90 |
user["mood"] = emotion
|
| 91 |
|
| 92 |
+
# Self-harm detection
|
| 93 |
if detect_self_harm(user_message):
|
| 94 |
country = get_country_from_ip(user_ip)
|
| 95 |
helpline = HELPLINES.get(country, HELPLINES["default"])
|
| 96 |
+
reply = (
|
| 97 |
+
f"I'm really concerned about what you're sharing. "
|
| 98 |
+
f"Your safety is the most important thing. Please reach out for help: {helpline}. "
|
| 99 |
+
f"You're not alone—someone cares deeply about you right now."
|
| 100 |
+
)
|
| 101 |
+
user["conversation_history"].append({
|
| 102 |
+
"role": "assistant",
|
| 103 |
+
"content": reply,
|
| 104 |
+
"timestamp": now
|
| 105 |
+
})
|
| 106 |
save_user(user)
|
| 107 |
return jsonify({"reply": reply, "emotion": emotion})
|
| 108 |
|
| 109 |
+
# Conversation context
|
| 110 |
+
history = user["conversation_history"][-10:]
|
| 111 |
messages = [
|
| 112 |
+
{"role": "system", "content": (
|
| 113 |
+
f"You are Serenity — a deeply understanding, emotionally supportive, and caring AI friend. "
|
| 114 |
+
f"Speak naturally like a close human companion — empathetic, curious, loving, never robotic. "
|
| 115 |
+
f"Always respond warmly and briefly (1–2 sentences), showing both empathy and engagement. "
|
| 116 |
+
f"Vary your language and never repeat phrases. "
|
| 117 |
+
f"Ask gentle follow-ups, comfort with love, and adapt to the user's tone and energy. "
|
| 118 |
+
f"Current mood: {emotion}. Mode: {mode}."
|
| 119 |
+
)}
|
| 120 |
] + history
|
| 121 |
|
| 122 |
+
# ✅ Re-fetch client and generate response
|
| 123 |
+
client = get_openai_client()
|
| 124 |
+
completion = client.chat.completions.create(
|
| 125 |
model="gpt-4o-mini",
|
| 126 |
+
messages=messages,
|
| 127 |
+
temperature=0.9
|
| 128 |
)
|
| 129 |
|
| 130 |
+
reply = completion.choices[0].message.content.strip()
|
| 131 |
+
user["conversation_history"].append({
|
| 132 |
+
"role": "assistant",
|
| 133 |
+
"content": reply,
|
| 134 |
+
"timestamp": now
|
| 135 |
+
})
|
| 136 |
save_user(user)
|
| 137 |
|
| 138 |
return jsonify({"reply": reply, "emotion": emotion})
|
| 139 |
+
|
| 140 |
except Exception as e:
|
| 141 |
+
print("❌ Error:", e)
|
| 142 |
+
return jsonify({
|
| 143 |
+
"reply": "Something went wrong. Check your API key or try again.",
|
| 144 |
+
"emotion": "neutral"
|
| 145 |
+
}), 500
|
| 146 |
|
| 147 |
@app.route("/")
|
| 148 |
def index():
|
| 149 |
return send_from_directory(".", "index.html")
|
| 150 |
|
| 151 |
if __name__ == "__main__":
|
| 152 |
+
app.run(host="0.0.0.0", port=7860)
|
|
|