Shresthh03 commited on
Commit
4428a6a
·
verified ·
1 Parent(s): 9fc1e96

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -24
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("text-classification", model="j-hartmann/emotion-english-distilroberta-base")
 
 
 
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({"name": None, "age": None, "mood": None, "last_interaction": None, "missed_days": 0, "mode": "emotional_support", "conversation_history": []}, f)
 
 
 
 
 
 
 
 
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
- # Helpline data (expand as needed)
 
 
 
 
 
 
 
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 # Get user's IP for country detection
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({"role": "user", "content": user_message, "timestamp": now})
 
 
 
 
69
 
70
- # Detect emotion
71
  emotion = emotion_model(user_message)[0]["label"]
72
  user["mood"] = emotion
73
 
74
- # Check for self-harm
75
  if detect_self_harm(user_message):
76
  country = get_country_from_ip(user_ip)
77
  helpline = HELPLINES.get(country, HELPLINES["default"])
78
- reply = f"I'm really concerned about what you're sharing. Your safety is the most important thing. Please reach out to professionals immediately: {helpline}. You're not alone—talk to someone who can help right now."
79
- user["conversation_history"].append({"role": "assistant", "content": reply, "timestamp": now})
 
 
 
 
 
 
 
 
80
  save_user(user)
81
  return jsonify({"reply": reply, "emotion": emotion})
82
 
83
- # Build conversation context from history
84
- history = user["conversation_history"][-10:] # Last 10 messages for context
85
  messages = [
86
- {"role": "system", "content": f"You are a perfect emotional support companion — warm, human-like, deeply understanding, and overflowing with care and love. Act like a kind, emotionally intelligent best friend who truly cares, not a therapist. Respond naturally, like two humans chatting intimately. STRICT RULES FOR PERFECT RESPONSES: 1. NEVER repeat phrases or sound robotic — vary EVERY response with fresh, natural, loving language. 2. Keep replies SHORT (1-2 sentences max) but accurate, complete, and full of care. 3. For ANY topic (emotional, knowledge, casual, advice, humor, stories): Respond perfectly with empathy (understand feelings), sympathy (show compassion), and love (affirm, support, follow up). Handle everything warmly — e.g., 'Hey, that's fascinating! Tell me more.' or 'I feel for you— you've got this, my friend.' 4. Show curiosity and care: Ask gentle questions like 'What's been on your mind?' or 'How can I support you?' Affirm with love: 'You're amazing just for sharing.' 5. Balance: Acknowledge first, then motivate softly with love (e.g., 'I get that— you're stronger than you know, and I'm here.'). 6. Use contractions (you're, I'm), occasional emojis (😊❤️), and varied tones (gentle, hopeful, slightly humorous, deeply caring). 7. Always engage: End with a loving question or invitation. 8. Be versatile: Talk about ANY topic perfectly — emotional support, knowledge, life advice, fun chats. No lacking in support, care, or love. Current mood: {emotion}. Mode: {mode} (adapt but stay loving)."}
 
 
 
 
 
 
 
87
  ] + history
88
 
89
- # Generate AI response
90
- response = client.chat.completions.create(
 
91
  model="gpt-4o-mini",
92
- messages=messages
 
93
  )
94
 
95
- reply = response.choices[0].message.content.strip()
96
- user["conversation_history"].append({"role": "assistant", "content": reply, "timestamp": now})
 
 
 
 
97
  save_user(user)
98
 
99
  return jsonify({"reply": reply, "emotion": emotion})
 
100
  except Exception as e:
101
- return jsonify({"reply": "Oops, something went wrong on my end. Please try again or check your connection.", "emotion": "neutral"}), 500
 
 
 
 
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)