Shresthh03 commited on
Commit
946720d
·
verified ·
1 Parent(s): b680d56

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -0
app.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from datetime import datetime
4
+ from flask import Flask, request, jsonify, send_from_directory
5
+ from transformers import pipeline
6
+ from openai import OpenAI
7
+
8
+ # Initialize Flask
9
+ app = Flask(__name__)
10
+
11
+ # Initialize OpenAI client
12
+ client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
13
+
14
+ # Emotion analysis model
15
+ emotion_model = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base")
16
+
17
+ # Load or create user data
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({"name": None, "age": None, "mood": None, "last_interaction": None, "missed_days": 0}, f)
22
+
23
+ def load_user():
24
+ with open(USER_FILE, "r") as f:
25
+ return json.load(f)
26
+
27
+ def save_user(data):
28
+ with open(USER_FILE, "w") as f:
29
+ json.dump(data, f)
30
+
31
+ @app.route("/chat", methods=["POST"])
32
+ def chat():
33
+ data = request.get_json()
34
+ user_message = data.get("message", "")
35
+ user = load_user()
36
+
37
+ # Update last interaction time
38
+ now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
39
+ user["last_interaction"] = now
40
+ save_user(user)
41
+
42
+ # Detect emotion
43
+ emotion = emotion_model(user_message)[0]["label"]
44
+
45
+ # Generate AI response
46
+ response = client.chat.completions.create(
47
+ model="gpt-4o-mini",
48
+ messages=[
49
+ {"role": "system", "content": "You are an empathetic emotional support assistant. Be friendly, warm, and encouraging, but not a therapist."},
50
+ {"role": "user", "content": user_message}
51
+ ]
52
+ )
53
+
54
+ reply = response.choices[0].message.content.strip()
55
+
56
+ return jsonify({"reply": reply, "emotion": emotion})
57
+
58
+
59
+ @app.route("/")
60
+ def index():
61
+ return send_from_directory(".", "index.html")
62
+
63
+
64
+ if __name__ == "__main__":
65
+ app.run(host="0.0.0.0", port=7860)