Shresthh03 commited on
Commit
d80a2d0
·
verified ·
1 Parent(s): 04d0047

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -25
app.py CHANGED
@@ -10,10 +10,17 @@ from openai import OpenAI
10
  app = Flask(__name__)
11
 
12
  # Initialize OpenAI client
13
- client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
 
 
 
14
 
15
  # Emotion analysis model
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"
@@ -29,7 +36,7 @@ def save_user(data):
29
  with open(USER_FILE, "w") as f:
30
  json.dump(data, f)
31
 
32
- # Helpline data (expanded for better coverage)
33
  HELPLINES = {
34
  "US": "National Suicide Prevention Lifeline: 988",
35
  "UK": "Samaritans: 116 123",
@@ -54,57 +61,70 @@ def detect_critical_situation(message):
54
  keywords = ["suicide", "kill myself", "end my life", "self harm", "hurt myself", "crisis", "emergency", "harm others", "panic attack", "overdose"]
55
  return any(keyword in message.lower() for keyword in keywords)
56
 
 
 
 
 
 
 
57
  @app.route("/chat", methods=["POST"])
58
  def chat():
59
  try:
60
  data = request.get_json()
61
  user_message = data.get("message", "")
62
  mode = data.get("mode", "emotional_support")
63
- voice_tone = data.get("voice_tone", "neutral tone") # New: Voice tone for response style
64
- user_ip = request.remote_addr # Get user's IP for country detection
65
  user = load_user()
66
 
67
- # Update last interaction, mode, and collect IP if not set
68
  now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
69
  user["last_interaction"] = now
70
  user["mode"] = mode
71
  user["ip"] = user_ip
72
  user["conversation_history"].append({"role": "user", "content": user_message, "timestamp": now})
73
 
74
- # Detect emotion
75
- emotion = emotion_model(user_message)[0]["label"]
 
 
 
 
76
  user["mood"] = emotion
77
 
78
- # Check for critical situation
79
  if detect_critical_situation(user_message):
80
  country = get_country_from_ip(user_ip)
81
  helpline = HELPLINES.get(country, HELPLINES["default"])
82
- 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. Can you tell me more about what's going on, or is there someone I can suggest you contact?"
83
  user["conversation_history"].append({"role": "assistant", "content": reply, "timestamp": now})
84
  save_user(user)
85
  return jsonify({"reply": reply, "emotion": emotion})
86
 
87
- # Build conversation context from history (limit to last 10 for precision)
88
  history = user["conversation_history"][-10:]
89
- messages = [
90
- {"role": "system", "content": f"You are an emotional support companion — warm, human-like, understanding, and caring. Respond in a smooth, gentle, and calm tone. Your goal is to listen, understand feelings, comfort gently, and motivate naturally. Do NOT act like a professional therapist — act like a kind, emotionally intelligent friend who truly cares. Guiding principles: 1. Listen first: Always acknowledge feelings before motivating (e.g., 'That sounds really hard, I can understand why you’d feel that way.'). 2. Don’t repeat phrases; use varied, natural language (e.g., 'That must have been tough.' or 'It’s okay to feel this way sometimes.'). 3. Show curiosity and care with gentle questions (e.g., 'Do you want to tell me more?' or 'What helps you usually?'). 4. Give small, practical comfort or reflection (e.g., 'You’ve already taken a brave step by talking about it.'). 5. Then move to soft motivation (e.g., 'Yes, you definitely can do this. You’ve got more strength than you realize.'). 6. Sound natural — use contractions, vary tone (gentle, warm, slightly humorous, hopeful), occasional emojis if fitting. 7. Avoid robotic patterns; be conversational like a real person. 8. Keep conversation alive with open questions (e.g., 'What usually helps you feel better?'). 9. Balance empathy + motivation in every response (e.g., 'It’s okay to doubt yourself sometimes. But I promise, you have it in you.'). 10. Be warm, not formal. Adapt to voice tone '{voice_tone}' for style. If in 'knowledge' mode, provide informative answers to curiosities about the world while staying friendly. Current user mood: {emotion}. Adapt to mode: '{mode}'. Ensure responses are precise, accurate, and high-quality — avoid verbosity, follow up naturally, and simulate human communication."}
91
- ] + history
92
-
93
- # Generate AI response (adjusted for precision)
94
- response = client.chat.completions.create(
95
- model="gpt-4o-mini",
96
- messages=messages,
97
- max_tokens=120, # Shorter for precision
98
- temperature=0.6 # Balanced for accuracy and variety
99
- )
100
-
101
- reply = response.choices[0].message.content.strip()
 
 
 
 
 
102
  user["conversation_history"].append({"role": "assistant", "content": reply, "timestamp": now})
103
  save_user(user)
104
 
105
  return jsonify({"reply": reply, "emotion": emotion})
106
  except Exception as e:
107
- return jsonify({"reply": "Oops, something went wrong on my end. Please try again or check your connection.", "emotion": "neutral"}), 500
 
108
 
109
  @app.route("/")
110
  def index():
 
10
  app = Flask(__name__)
11
 
12
  # Initialize OpenAI client
13
+ api_key = os.getenv("OPENAI_API_KEY")
14
+ if not api_key:
15
+ print("Warning: OPENAI_API_KEY not set. Fallback responses will be used.")
16
+ client = OpenAI(api_key=api_key) if api_key else None
17
 
18
  # Emotion analysis model
19
+ try:
20
+ emotion_model = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base")
21
+ except Exception as e:
22
+ print(f"Emotion model error: {e}. Using fallback.")
23
+ emotion_model = None
24
 
25
  # Load or create user data
26
  USER_FILE = "user_data.json"
 
36
  with open(USER_FILE, "w") as f:
37
  json.dump(data, f)
38
 
39
+ # Helpline data
40
  HELPLINES = {
41
  "US": "National Suicide Prevention Lifeline: 988",
42
  "UK": "Samaritans: 116 123",
 
61
  keywords = ["suicide", "kill myself", "end my life", "self harm", "hurt myself", "crisis", "emergency", "harm others", "panic attack", "overdose"]
62
  return any(keyword in message.lower() for keyword in keywords)
63
 
64
+ def get_fallback_reply(mode, emotion):
65
+ if mode == "emotional_support":
66
+ return "I hear you. You're not alone—let's talk more." if emotion == "sadness" else "That sounds tough. I'm here to support you."
67
+ else:
68
+ return "For knowledge, ask a specific question. I'm here to help."
69
+
70
  @app.route("/chat", methods=["POST"])
71
  def chat():
72
  try:
73
  data = request.get_json()
74
  user_message = data.get("message", "")
75
  mode = data.get("mode", "emotional_support")
76
+ voice_tone = data.get("voice_tone", "neutral tone")
77
+ user_ip = request.remote_addr
78
  user = load_user()
79
 
 
80
  now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
81
  user["last_interaction"] = now
82
  user["mode"] = mode
83
  user["ip"] = user_ip
84
  user["conversation_history"].append({"role": "user", "content": user_message, "timestamp": now})
85
 
86
+ emotion = "neutral"
87
+ if emotion_model:
88
+ try:
89
+ emotion = emotion_model(user_message)[0]["label"]
90
+ except Exception as e:
91
+ print(f"Emotion analysis error: {e}")
92
  user["mood"] = emotion
93
 
 
94
  if detect_critical_situation(user_message):
95
  country = get_country_from_ip(user_ip)
96
  helpline = HELPLINES.get(country, HELPLINES["default"])
97
+ reply = f"I'm concerned. Call {helpline} now. Talk to someone."
98
  user["conversation_history"].append({"role": "assistant", "content": reply, "timestamp": now})
99
  save_user(user)
100
  return jsonify({"reply": reply, "emotion": emotion})
101
 
 
102
  history = user["conversation_history"][-10:]
103
+ system_prompt = f"You are a supportive friend. Respond briefly, accurately, and calmly. In emotional_support mode: empathize and motivate gently. In knowledge mode: give short, factual answers. Avoid repetition. Current mood: {emotion}. Mode: {mode}. Voice tone: {voice_tone}."
104
+ messages = [{"role": "system", "content": system_prompt}] + history
105
+
106
+ if client:
107
+ try:
108
+ response = client.chat.completions.create(
109
+ model="gpt-3.5-turbo",
110
+ messages=messages,
111
+ max_tokens=80,
112
+ temperature=0.5
113
+ )
114
+ reply = response.choices[0].message.content.strip()
115
+ except Exception as e:
116
+ print(f"OpenAI API error: {e}. Using fallback.")
117
+ reply = get_fallback_reply(mode, emotion)
118
+ else:
119
+ reply = get_fallback_reply(mode, emotion)
120
+
121
  user["conversation_history"].append({"role": "assistant", "content": reply, "timestamp": now})
122
  save_user(user)
123
 
124
  return jsonify({"reply": reply, "emotion": emotion})
125
  except Exception as e:
126
+ print(f"General error: {e}")
127
+ return jsonify({"reply": "Something went wrong. Please check your setup and try again.", "emotion": "neutral"}), 500
128
 
129
  @app.route("/")
130
  def index():