Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,128 +1,216 @@
|
|
| 1 |
-
#
|
| 2 |
-
#
|
|
|
|
|
|
|
| 3 |
|
| 4 |
-
from flask import Flask, request, jsonify, render_template
|
| 5 |
-
from flask_cors import CORS
|
| 6 |
-
import openai
|
| 7 |
import os
|
| 8 |
import json
|
|
|
|
| 9 |
from datetime import datetime
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
CORS(app)
|
| 14 |
|
| 15 |
-
#
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
"
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
return jsonify({"message": "🌸 Serenity Emotional Support Chatbot API is running!"})
|
| 60 |
|
|
|
|
| 61 |
@app.route("/chat", methods=["POST"])
|
| 62 |
def chat():
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
"""
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
|
|
|
|
| 125 |
|
| 126 |
-
# --- Run App ---
|
| 127 |
if __name__ == "__main__":
|
| 128 |
-
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
# Minimal Serenity backend that serves index.html and a /chat endpoint.
|
| 3 |
+
# If OPENAI_API_KEY is set it will use OpenAI (gpt-3.5-turbo) for nicer replies;
|
| 4 |
+
# otherwise it uses a small local fallback so chat still works.
|
| 5 |
|
|
|
|
|
|
|
|
|
|
| 6 |
import os
|
| 7 |
import json
|
| 8 |
+
import random
|
| 9 |
from datetime import datetime
|
| 10 |
+
from flask import Flask, request, jsonify, send_from_directory
|
| 11 |
+
from flask_cors import CORS
|
| 12 |
|
| 13 |
+
# Optional OpenAI usage
|
| 14 |
+
try:
|
| 15 |
+
import openai
|
| 16 |
+
OPENAI_PRESENT = True
|
| 17 |
+
OPENAI_KEY = os.getenv("OPENAI_API_KEY")
|
| 18 |
+
if OPENAI_KEY:
|
| 19 |
+
openai.api_key = OPENAI_KEY
|
| 20 |
+
else:
|
| 21 |
+
OPENAI_PRESENT = False
|
| 22 |
+
except Exception:
|
| 23 |
+
OPENAI_PRESENT = False
|
| 24 |
+
|
| 25 |
+
app = Flask(__name__, static_folder=".", static_url_path="/")
|
| 26 |
CORS(app)
|
| 27 |
|
| 28 |
+
# Simple memory (session -> data) kept in memory + optionally saved to file
|
| 29 |
+
MEM_FILE = "memory.json"
|
| 30 |
+
try:
|
| 31 |
+
if os.path.exists(MEM_FILE):
|
| 32 |
+
with open(MEM_FILE, "r", encoding="utf-8") as f:
|
| 33 |
+
MEMORY = json.load(f)
|
| 34 |
+
else:
|
| 35 |
+
MEMORY = {}
|
| 36 |
+
except Exception:
|
| 37 |
+
MEMORY = {}
|
| 38 |
+
|
| 39 |
+
def save_memory():
|
| 40 |
+
try:
|
| 41 |
+
with open(MEM_FILE, "w", encoding="utf-8") as f:
|
| 42 |
+
json.dump(MEMORY, f, indent=2, ensure_ascii=False)
|
| 43 |
+
except Exception:
|
| 44 |
+
pass
|
| 45 |
+
|
| 46 |
+
# Simple emotion heuristic (fallback)
|
| 47 |
+
def simple_emotion(text: str) -> str:
|
| 48 |
+
t = text.lower()
|
| 49 |
+
if any(w in t for w in ["happy","great","good","awesome","yay","joy"]): return "happy"
|
| 50 |
+
if any(w in t for w in ["sad","down","depress","lonely","cry"]): return "sad"
|
| 51 |
+
if any(w in t for w in ["angry","mad","furious"]): return "angry"
|
| 52 |
+
if any(w in t for w in ["scared","afraid","anxious","panic","worried"]): return "worried"
|
| 53 |
+
if any(w in t for w in ["calm","fine","okay","ok","relaxed"]): return "calm"
|
| 54 |
+
if any(w in t for w in ["motivate","motivation","guidance","inspire"]): return "motivated"
|
| 55 |
+
return "neutral"
|
| 56 |
+
|
| 57 |
+
# Basic fallback reply generator (when OpenAI not available)
|
| 58 |
+
def fallback_reply(user_text: str, persona: str, name: str = None) -> str:
|
| 59 |
+
greetings = [
|
| 60 |
+
"Thanks for sharing — I'm here with you.",
|
| 61 |
+
"I hear you. Tell me more if you'd like.",
|
| 62 |
+
"That matters. Would you like to say more about it?"
|
| 63 |
+
]
|
| 64 |
+
casual = [
|
| 65 |
+
"Haha, nice! What's new with you?",
|
| 66 |
+
"I’m here — how’s your day going?",
|
| 67 |
+
"That sounds fun — tell me more!"
|
| 68 |
+
]
|
| 69 |
+
motivate = [
|
| 70 |
+
"You’ve got this — small steps add up.",
|
| 71 |
+
"Take one small step today; it can make a difference.",
|
| 72 |
+
"I believe in you. What is one tiny thing you can try now?"
|
| 73 |
+
]
|
| 74 |
+
# choose style based on keywords
|
| 75 |
+
txt = user_text.lower()
|
| 76 |
+
if any(k in txt for k in ["motivate","motivation","guidance","inspire","quote"]):
|
| 77 |
+
return random.choice(motivate)
|
| 78 |
+
if any(k in txt for k in ["hi","hello","hey","how are you","sup","what's up"]):
|
| 79 |
+
return random.choice(casual)
|
| 80 |
+
# emotional catch
|
| 81 |
+
if any(k in txt for k in ["sad","depress","lonely","upset","not good","terrible","bad"]):
|
| 82 |
+
return random.choice(greetings)
|
| 83 |
+
return random.choice(greetings)
|
| 84 |
+
|
| 85 |
+
# Serve the frontend (IMPORTANT: this serves index.html at root)
|
| 86 |
+
@app.route("/", methods=["GET"])
|
| 87 |
+
def index():
|
| 88 |
+
# Serve index.html from same directory
|
| 89 |
+
return send_from_directory(".", "index.html")
|
| 90 |
+
|
| 91 |
+
# Optional small status endpoint (not the app root)
|
| 92 |
+
@app.route("/status", methods=["GET"])
|
| 93 |
+
def status():
|
| 94 |
return jsonify({"message": "🌸 Serenity Emotional Support Chatbot API is running!"})
|
| 95 |
|
| 96 |
+
# Main chat endpoint
|
| 97 |
@app.route("/chat", methods=["POST"])
|
| 98 |
def chat():
|
| 99 |
+
"""
|
| 100 |
+
Expected JSON:
|
| 101 |
+
{
|
| 102 |
+
"session": "optional-session-id",
|
| 103 |
+
"message": "user text",
|
| 104 |
+
"personality": "calm" (optional)
|
| 105 |
+
}
|
| 106 |
+
Response JSON:
|
| 107 |
+
{
|
| 108 |
+
"reply": "...",
|
| 109 |
+
"emotion": "sad|happy|calm|... ",
|
| 110 |
+
"voice": "calm_male" (suggested voice key for frontend)
|
| 111 |
+
}
|
| 112 |
+
"""
|
| 113 |
+
data = request.get_json(force=True) or {}
|
| 114 |
+
session = data.get("session") or request.remote_addr or "default"
|
| 115 |
+
text = (data.get("message") or "").strip()
|
| 116 |
+
personality = (data.get("personality") or "calm").lower()
|
| 117 |
+
|
| 118 |
+
if not text:
|
| 119 |
+
return jsonify({"reply":"Please send a message.", "emotion":"neutral", "voice":"neutral"})
|
| 120 |
+
|
| 121 |
+
# initialize session data
|
| 122 |
+
slot = MEMORY.get(session, {"name": None, "age": None, "last_mood": None, "history": []})
|
| 123 |
+
# optional: try to detect a name
|
| 124 |
+
if not slot.get("name"):
|
| 125 |
+
# very naive name detection
|
| 126 |
+
if text.lower().startswith("i am ") or text.lower().startswith("i'm "):
|
| 127 |
+
name = text.split()[2:3]
|
| 128 |
+
if name:
|
| 129 |
+
slot["name"] = name[0].capitalize()
|
| 130 |
+
|
| 131 |
+
# Use OpenAI if available
|
| 132 |
+
reply_text = None
|
| 133 |
+
emotion_label = None
|
| 134 |
+
voice_key = "neutral"
|
| 135 |
+
|
| 136 |
+
if OPENAI_PRESENT:
|
| 137 |
+
try:
|
| 138 |
+
# Compose a short system prompt that balances support + casual + knowledge
|
| 139 |
+
persona_text = {
|
| 140 |
+
"calm": "You are calm, gentle, and concise.",
|
| 141 |
+
"friendly": "You are warm, friendly and playful when appropriate.",
|
| 142 |
+
"motivational": "You are upbeat, encouraging, motivational.",
|
| 143 |
+
"spiritual": "You are nurturing, mindful, non-denominational.",
|
| 144 |
+
"neutral": "You are neutral, clear, and friendly."
|
| 145 |
+
}.get(personality, "You are calm and supportive.")
|
| 146 |
+
|
| 147 |
+
system_msg = (
|
| 148 |
+
f"You are Serenity, an empathetic emotional-support assistant. {persona_text} "
|
| 149 |
+
"Do not act like a therapist. If the user asks factual questions, answer clearly and then check in emotionally. "
|
| 150 |
+
"Vary phrasing; avoid repeating the same canned sentences."
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
# ask OpenAI to both classify emotion and reply in a friendly supportive tone
|
| 154 |
+
# We'll call chat completion twice cheaply: classify then reply (keeps prompt simpler)
|
| 155 |
+
classify_prompt = (
|
| 156 |
+
"Classify the primary emotion from the short user message. "
|
| 157 |
+
"Respond with one word from: happy, sad, angry, worried, calm, neutral, motivated, fearful, love.\n\n"
|
| 158 |
+
f"Message: {text}"
|
| 159 |
+
)
|
| 160 |
+
classification = openai.ChatCompletion.create(
|
| 161 |
+
model="gpt-3.5-turbo",
|
| 162 |
+
messages=[{"role":"system","content":"You are a concise classifier."},
|
| 163 |
+
{"role":"user","content":classify_prompt}],
|
| 164 |
+
temperature=0.0,
|
| 165 |
+
max_tokens=6
|
| 166 |
+
)
|
| 167 |
+
emotion_label = (classification.choices[0].message.content.strip().split()[0].lower())[:20]
|
| 168 |
+
except Exception:
|
| 169 |
+
# fallback classification
|
| 170 |
+
emotion_label = simple_emotion(text)
|
| 171 |
+
|
| 172 |
+
try:
|
| 173 |
+
# Now produce a reply using the persona/system prompt
|
| 174 |
+
user_msg_for_ai = f"User: {text}"
|
| 175 |
+
ai_resp = openai.ChatCompletion.create(
|
| 176 |
+
model="gpt-3.5-turbo",
|
| 177 |
+
messages=[
|
| 178 |
+
{"role":"system","content":system_msg},
|
| 179 |
+
{"role":"user","content":user_msg_for_ai}
|
| 180 |
+
],
|
| 181 |
+
temperature=0.8,
|
| 182 |
+
max_tokens=250
|
| 183 |
+
)
|
| 184 |
+
reply_text = ai_resp.choices[0].message.content.strip()
|
| 185 |
+
except Exception as e:
|
| 186 |
+
# fallback to simple reply if OpenAI fails
|
| 187 |
+
reply_text = fallback_reply(text, personality, slot.get("name"))
|
| 188 |
+
if not emotion_label:
|
| 189 |
+
emotion_label = simple_emotion(text)
|
| 190 |
+
else:
|
| 191 |
+
# OpenAI not available — fallback behavior
|
| 192 |
+
emotion_label = simple_emotion(text)
|
| 193 |
+
reply_text = fallback_reply(text, personality, slot.get("name"))
|
| 194 |
+
|
| 195 |
+
# choose a voice key suggestion for frontend to map to browser voices
|
| 196 |
+
voice_map = {
|
| 197 |
+
"calm": "calm_male",
|
| 198 |
+
"friendly": "friendly_female",
|
| 199 |
+
"motivational": "deep_male",
|
| 200 |
+
"spiritual": "soothing_female",
|
| 201 |
+
"neutral": "neutral"
|
| 202 |
+
}
|
| 203 |
+
voice_key = voice_map.get(personality, "neutral")
|
| 204 |
+
|
| 205 |
+
# update memory
|
| 206 |
+
slot["last_mood"] = emotion_label
|
| 207 |
+
slot.setdefault("history", []).append({"user": text, "bot": reply_text, "ts": datetime.utcnow().isoformat()})
|
| 208 |
+
slot["history"] = slot["history"][-50:]
|
| 209 |
+
MEMORY[session] = slot
|
| 210 |
+
save_memory()
|
| 211 |
|
| 212 |
+
return jsonify({"reply": reply_text, "emotion": emotion_label, "voice": voice_key})
|
| 213 |
|
|
|
|
| 214 |
if __name__ == "__main__":
|
| 215 |
+
port = int(os.getenv("PORT", 7860))
|
| 216 |
+
app.run(host="0.0.0.0", port=port)
|