Shresthh03 commited on
Commit
1268cd5
·
verified ·
1 Parent(s): f7f6c1f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -69
app.py CHANGED
@@ -1,7 +1,6 @@
1
  import os
2
  import json
3
  import requests
4
- import time
5
  from datetime import datetime
6
  from flask import Flask, request, jsonify, send_from_directory
7
  from transformers import pipeline
@@ -9,17 +8,14 @@ from openai import OpenAI
9
 
10
  app = Flask(__name__)
11
 
12
- # Load emotion model once
13
  emotion_model = pipeline(
14
  "text-classification",
15
  model="j-hartmann/emotion-english-distilroberta-base"
16
  )
17
 
18
- # Persistent user data
19
  USER_FILE = "user_data.json"
20
- STATE_FILE = "model_state.json"
21
-
22
- # Initialize files
23
  if not os.path.exists(USER_FILE):
24
  with open(USER_FILE, "w") as f:
25
  json.dump({
@@ -32,10 +28,6 @@ if not os.path.exists(USER_FILE):
32
  "conversation_history": []
33
  }, f)
34
 
35
- if not os.path.exists(STATE_FILE):
36
- with open(STATE_FILE, "w") as f:
37
- json.dump({"current_model": "gpt-4o-mini", "last_switch": None}, f)
38
-
39
  def load_user():
40
  with open(USER_FILE, "r") as f:
41
  return json.load(f)
@@ -44,21 +36,17 @@ def save_user(data):
44
  with open(USER_FILE, "w") as f:
45
  json.dump(data, f)
46
 
47
- def load_state():
48
- with open(STATE_FILE, "r") as f:
49
- return json.load(f)
50
-
51
- def save_state(state):
52
- with open(STATE_FILE, "w") as f:
53
- json.dump(state, f)
54
-
55
  def get_client():
56
  api_key = os.getenv("OPENAI_API_KEY")
57
  if not api_key or api_key.strip() == "":
58
- raise ValueError("OpenAI API key missing or empty. Please set it in secrets.")
59
  return OpenAI(api_key=api_key)
60
 
61
- # Suicide helplines by country
 
 
 
62
  HELPLINES = {
63
  "US": "National Suicide Prevention Lifeline: 988",
64
  "UK": "Samaritans: 116 123",
@@ -72,7 +60,7 @@ def get_country_from_ip(ip):
72
  try:
73
  response = requests.get(f"http://ipapi.co/{ip}/country/")
74
  if response.status_code == 200:
75
- return response.text.strip().upper()
76
  except:
77
  pass
78
  return "default"
@@ -88,23 +76,20 @@ def chat():
88
  message = data.get("message", "").strip()
89
  if not message:
90
  return jsonify({"reply": "Please enter a message.", "emotion": "neutral"}), 400
91
-
92
  mode = data.get("mode", "emotional_support")
93
  user_ip = request.remote_addr
94
 
95
  user = load_user()
96
- state = load_state()
97
  now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
98
-
99
  user["last_interaction"] = now
100
  user["mode"] = mode
101
  user["conversation_history"].append({"role": "user", "content": message, "timestamp": now})
102
 
103
- # Emotion analysis
104
  emotion = emotion_model(message)[0]["label"]
105
  user["mood"] = emotion
106
 
107
- # Self-harm detection
108
  if detect_self_harm(message):
109
  country = get_country_from_ip(user_ip)
110
  helpline = HELPLINES.get(country, HELPLINES["default"])
@@ -116,72 +101,58 @@ def chat():
116
  save_user(user)
117
  return jsonify({"reply": reply, "emotion": emotion})
118
 
119
- # Build system + context
120
  history = user["conversation_history"][-10:]
121
  messages = [
122
  {"role": "system", "content": (
123
  f"You are Serenity — an empathetic, emotionally intelligent best friend. "
124
- f"Be warm, supportive, and natural. Respond briefly (1–2 sentences) with kindness, curiosity, "
125
- f"and a human-like tone. No repetition. Mode: {mode}. User mood: {emotion}."
 
126
  )}
127
  ] + history
128
 
 
129
  client = get_client()
130
- model_order = ["gpt-4o-mini", "gpt-3.5-turbo"]
131
-
132
- # Start with remembered model
133
- active_model = state.get("current_model", "gpt-4o-mini")
134
- model_order.remove(active_model)
135
- model_order.insert(0, active_model)
136
-
137
- for model_name in model_order:
138
  try:
139
- print(f"💬 Using model: {model_name}")
140
  response = client.chat.completions.create(
141
- model=model_name,
142
  messages=messages,
143
  temperature=0.8
144
  )
145
-
146
  reply = response.choices[0].message.content.strip()
147
- user["conversation_history"].append({"role": "assistant", "content": reply, "timestamp": now})
148
- save_user(user)
149
-
150
- # Update remembered model
151
- state["current_model"] = model_name
152
- state["last_switch"] = now
153
- save_state(state)
154
-
155
- return jsonify({"reply": reply, "emotion": emotion})
156
-
157
  except Exception as e:
158
- err_text = str(e).lower()
159
- print(f"⚠️ Error with {model_name}: {err_text}")
160
-
161
- # If rate limited — switch and retry
162
- if "rate limit" in err_text or "429" in err_text:
163
- state["current_model"] = "gpt-3.5-turbo"
164
- state["last_switch"] = now
165
- save_state(state)
166
- print("⏳ Rate limit hit, switching model temporarily...")
167
- time.sleep(1)
168
- continue
169
  else:
170
- raise
 
171
 
172
- # Both failed
173
- return jsonify({
174
- "reply": "I'm taking a small pause looks like the system is busy. Try again in a few minutes ❤️",
175
- "emotion": "neutral"
176
- }), 429
 
 
 
177
 
178
  except ValueError as e:
179
  print(f"❌ API Key Error: {e}")
180
- return jsonify({"reply": "API key missing or invalid. Please check settings.", "emotion": "neutral"}), 500
 
 
 
181
  except Exception as e:
182
  print(f"❌ Chat error: {e}")
183
  return jsonify({
184
- "reply": "Something went wrong (network or system issue). Try again shortly ❤️",
185
  "emotion": "neutral"
186
  }), 500
187
 
 
1
  import os
2
  import json
3
  import requests
 
4
  from datetime import datetime
5
  from flask import Flask, request, jsonify, send_from_directory
6
  from transformers import pipeline
 
8
 
9
  app = Flask(__name__)
10
 
11
+ # Load emotion model
12
  emotion_model = pipeline(
13
  "text-classification",
14
  model="j-hartmann/emotion-english-distilroberta-base"
15
  )
16
 
17
+ # Ensure user data file
18
  USER_FILE = "user_data.json"
 
 
 
19
  if not os.path.exists(USER_FILE):
20
  with open(USER_FILE, "w") as f:
21
  json.dump({
 
28
  "conversation_history": []
29
  }, f)
30
 
 
 
 
 
31
  def load_user():
32
  with open(USER_FILE, "r") as f:
33
  return json.load(f)
 
36
  with open(USER_FILE, "w") as f:
37
  json.dump(data, f)
38
 
39
+ # Safe OpenAI client initialization
 
 
 
 
 
 
 
40
  def get_client():
41
  api_key = os.getenv("OPENAI_API_KEY")
42
  if not api_key or api_key.strip() == "":
43
+ raise ValueError("OpenAI API key is missing or empty. Please set OPENAI_API_KEY in Hugging Face Secrets.")
44
  return OpenAI(api_key=api_key)
45
 
46
+ # Model priority list for fallbacks
47
+ MODEL_LIST = ["gpt-4o-mini", "gpt-3.5-turbo", "gpt-3.5-turbo-16k"]
48
+
49
+ # Helpline numbers
50
  HELPLINES = {
51
  "US": "National Suicide Prevention Lifeline: 988",
52
  "UK": "Samaritans: 116 123",
 
60
  try:
61
  response = requests.get(f"http://ipapi.co/{ip}/country/")
62
  if response.status_code == 200:
63
+ return response.text.upper()
64
  except:
65
  pass
66
  return "default"
 
76
  message = data.get("message", "").strip()
77
  if not message:
78
  return jsonify({"reply": "Please enter a message.", "emotion": "neutral"}), 400
 
79
  mode = data.get("mode", "emotional_support")
80
  user_ip = request.remote_addr
81
 
82
  user = load_user()
 
83
  now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
 
84
  user["last_interaction"] = now
85
  user["mode"] = mode
86
  user["conversation_history"].append({"role": "user", "content": message, "timestamp": now})
87
 
88
+ # Emotion detection
89
  emotion = emotion_model(message)[0]["label"]
90
  user["mood"] = emotion
91
 
92
+ # Self-harm check
93
  if detect_self_harm(message):
94
  country = get_country_from_ip(user_ip)
95
  helpline = HELPLINES.get(country, HELPLINES["default"])
 
101
  save_user(user)
102
  return jsonify({"reply": reply, "emotion": emotion})
103
 
104
+ # Build context for chat
105
  history = user["conversation_history"][-10:]
106
  messages = [
107
  {"role": "system", "content": (
108
  f"You are Serenity — an empathetic, emotionally intelligent best friend. "
109
+ f"Be warm, caring, supportive, and human-like. Respond briefly (1–2 sentences), "
110
+ f"showing love, empathy, and curiosity. Never sound robotic or repetitive. "
111
+ f"Current mood: {emotion}. Mode: {mode}."
112
  )}
113
  ] + history
114
 
115
+ # Try models in priority order
116
  client = get_client()
117
+ reply = None
118
+ for model in MODEL_LIST:
 
 
 
 
 
 
119
  try:
 
120
  response = client.chat.completions.create(
121
+ model=model,
122
  messages=messages,
123
  temperature=0.8
124
  )
 
125
  reply = response.choices[0].message.content.strip()
126
+ print(f" Used model: {model}")
127
+ break # Success, stop trying other models
 
 
 
 
 
 
 
 
128
  except Exception as e:
129
+ error_str = str(e).lower()
130
+ if "rate_limit" in error_str or "429" in error_str or "quota" in error_str:
131
+ print(f"⚠️ Rate limit on {model}, trying next model...")
132
+ continue # Try next model
 
 
 
 
 
 
 
133
  else:
134
+ # Non-rate-limit error, re-raise
135
+ raise e
136
 
137
+ if reply is None:
138
+ # All models failed
139
+ reply = "All models are currently rate-limited. Please try again later or check your OpenAI account."
140
+
141
+ user["conversation_history"].append({"role": "assistant", "content": reply, "timestamp": now})
142
+ save_user(user)
143
+
144
+ return jsonify({"reply": reply, "emotion": emotion})
145
 
146
  except ValueError as e:
147
  print(f"❌ API Key Error: {e}")
148
+ return jsonify({
149
+ "reply": "API key is missing or invalid. Please check your Hugging Face Secrets and ensure it's a valid OpenAI key.",
150
+ "emotion": "neutral"
151
+ }), 500
152
  except Exception as e:
153
  print(f"❌ Chat error: {e}")
154
  return jsonify({
155
+ "reply": "Something went wrong (e.g., network issue). Try again later.",
156
  "emotion": "neutral"
157
  }), 500
158