-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathapp.py
126 lines (105 loc) Β· 4.5 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
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
60
61
62
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
from flask import Flask, render_template, request
import joblib
import os
import random
import tweepy
from dotenv import load_dotenv
import os
from flask_limiter import Limiter
load_dotenv()
TWITTER_BEARER_TOKEN = os.getenv("TWITTER_BEARER_TOKEN")
def get_twitter_client():
return tweepy.Client(bearer_token=TWITTER_BEARER_TOKEN)
app = Flask(__name__)
# Load the trained emotion detection model safely
model_path = os.path.join(os.path.dirname(__file__), "emotion_pipeline_model.pkl")
try:
model = joblib.load(model_path)
except Exception as e:
print(f"Error loading model: {e}")
model = None # Prevent crashes if model is missing
# Define emotion mapping with corresponding emojis
emotion_mapping = {
1: ("happy", "π"),
2: ("sad", "π’"),
3: ("angry", "π‘"),
0: ("neutral", "π")
}
# Function to get chatbot responses
def get_emotion_response(emotion):
responses = {
"happy": [
"I'm glad you're feeling happy! Keep spreading positivity! π",
"Happiness is contagious! Keep smiling! π",
"Enjoy the moment! Life is beautiful. π"
],
"sad": [
"I'm here for you. Remember, tough times don't last. π",
"It's okay to feel sad sometimes. You're not alone. π€",
"Try to do something you enjoyβit might lift your mood! βοΈ"
],
"angry": [
"Take a deep breath. Maybe a short walk can help calm your mind. πΏ",
"I understand anger can be tough. Try writing your thoughts down. βοΈ",
"Listening to calming music might help. Stay strong! π΅"
],
"neutral": [
"Got it! Let me know if I can assist you with anything. π",
"Neutral is good. Howβs your day going? β",
"Would you like to talk about something fun? π"
]
}
return random.choice(responses.get(emotion, ["I'm here to help, no matter what you're feeling! π"]))
@app.route("/")
def home():
return render_template("index.html")
@app.route("/predict", methods=["POST"])
def predict():
if request.method == "POST":
if not model:
return render_template("error.html", message="Model not found or failed to load.")
user_input = request.form.get("user_input", "").strip()
if not user_input:
return render_template("error.html", message="Please enter some text.")
try:
predicted_label = model.predict([user_input])[0] # Predict emotion
predicted_emotion, emoji = emotion_mapping.get(int(predicted_label), ("neutral", "π€"))
response = get_emotion_response(predicted_emotion)
except Exception as e:
return render_template("error.html", message=f"Prediction failed: {str(e)}")
return render_template("result.html", user_input=user_input, emotion=predicted_emotion, emoji=emoji, response=response)
@app.route("/analyze_tweets", methods=["GET", "POST"])
def analyze_tweets():
if request.method == "POST":
search_query = request.form.get("search_query", "")
if not search_query:
return render_template("error.html", message="Please enter a search term.")
try:
client = get_twitter_client()
tweets = client.search_recent_tweets(
query=search_query,
max_results=50,
tweet_fields=["created_at"]
)
if not tweets.data:
return render_template("error.html", message="No tweets found.")
processed_tweets = []
for tweet in tweets.data:
text = tweet.text
prediction = model.predict([text])[0]
emotion, emoji = emotion_mapping.get(int(prediction), ("neutral", "π€"))
processed_tweets.append({
"text": text,
"emotion": emotion,
"emoji": emoji
})
return render_template("tweet_results.html",
tweets=processed_tweets,
search_term=search_query)
except Exception as e:
return render_template("error.html", message=f"Twitter error: {str(e)}")
return render_template("tweet_search.html")
limiter = Limiter(app=app, key_func=lambda: request.remote_addr)
limiter.limit("10 per minute")(analyze_tweets)
if __name__ == "__main__":
app.run(debug=True)