-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
218 lines (177 loc) · 8.15 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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# app.py
from flask import Flask, render_template, request, redirect, url_for, flash
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
import os
import secrets
from geocoding import get_latitude_longitude
from textblob import TextBlob
from flask_login import current_user
app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', secrets.token_hex(16))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data2.db'
db = SQLAlchemy(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
chat_history = []
responses = {
"hi": "Hi!, How can I assist you today?",
"hello": "Hi there! How can I support you today?",
"how are you": "I'm an AI, so I don't have feelings, but I'm here to listen to you.",
"bye": "Take care! Remember, I'm here whenever you need to talk.",
"feeling anxious": "I'm here to help. When you're anxious, try taking deep breaths and focusing on the present moment.",
"feeling sad": "I'm here to help. When you're sad, try taking deep breaths and focusing on the present moment.",
"lonely": "You're not alone. Reach out to friends, family, or a support group when you're feeling lonely.",
"depressed": "It's okay to feel down. Consider engaging in activities you enjoy or talking to a professional.",
"suicidal thoughts": "I'm really sorry to hear that, but I can't provide the help you need. Please talk to a mental health professional or a helpline.",
"coping strategies": "When you're stressed, practicing mindfulness and relaxation techniques can be helpful.",
"seeking help": "While I'm here to chat, it's important to consult a mental health expert for personalized guidance.",
"self-care": "Taking care of yourself is important. Make sure you're getting enough rest, eating well, and staying hydrated.",
"challenging times": "Life can be tough, but you have the strength to overcome challenges.",
"positive affirmations": "Repeat positive affirmations to boost your mood and self-esteem.",
"therapy": "Therapy can be a valuable resource. Consider speaking with a therapist who can provide specialized support.",
"reaching out": "Don't hesitate to reach out to a trusted friend or family member when you need to talk.",
"progress": "Every step forward, no matter how small, is a step in the right direction.",
"default": "Sorry, could You please elaborate."
}
def get_bot_response(user_input):
user_input = user_input.lower()
for keyword in responses:
if keyword in user_input:
return responses[keyword]
return responses["default"]
def get_sentiment(text):
analysis = TextBlob(text)
polarity = analysis.sentiment.polarity
if polarity > 0:
return 'positive'
elif polarity < 0:
return 'negative'
else:
return 'neutral'
# Database Models
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), unique=True, nullable=False)
class Location(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), unique=True, nullable=False)
latitude = db.Column(db.Float)
longitude = db.Column(db.Float)
posts = db.relationship('Post', backref='location', lazy=True)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.Text, nullable=False)
location_id = db.Column(db.Integer, db.ForeignKey('location.id'))
author_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
author = db.relationship('User', backref='posts')
sentiment = db.Column(db.String(10))
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
# Routes
@app.route('/')
def index():
return render_template('index.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
user = User.query.filter_by(username=username).first()
if user:
login_user(user)
return redirect(url_for('posts'))
else:
flash('User not found. Please try again with a valid username.', 'error')
return redirect(url_for('login'))
return render_template('login.html')
@app.route('/logout')
@login_required
def logout():
logout_user()
flash('Logged out successfully!', 'success')
return redirect(url_for('index'))
@app.route('/signup', methods=['GET', 'POST'])
def signup():
if request.method == 'POST':
username = request.form['username']
if User.query.filter_by(username=username).first():
flash('Username already exists. Please choose a different username.', 'error')
return redirect(url_for('signup'))
else:
new_user = User(username=username)
db.session.add(new_user)
db.session.commit()
flash('Registration successful! You can now log in with your username.', 'success')
return redirect(url_for('login'))
return render_template('signup.html')
@app.route('/posts', methods=['GET', 'POST'])
@login_required
def posts():
if request.method == 'POST':
content = request.form.get('content')
location_name = request.form.get('location')
location = Location.query.filter_by(name=location_name).first()
if not location:
latitude, longitude = get_latitude_longitude(location_name)
location = Location(name=location_name, latitude=latitude, longitude=longitude)
db.session.add(location)
db.session.commit()
new_post = Post(content=content, location=location, author=current_user) # Set the author to current_user
db.session.add(new_post)
db.session.commit()
posts = Post.query.filter_by(author=current_user) # Filter posts by current user
return render_template('posts.html', posts=posts)
@app.route('/feed')
def feed():
posts = Post.query.all()
for post in posts:
post.sentiment = get_sentiment(post.content)
return render_template('feed.html', posts=posts)
@app.route('/userfeed')
def userfeed():
posts = Post.query.all()
for post in posts:
post.sentiment = get_sentiment(post.content)
return render_template('userfeed.html', posts=posts)
@app.route('/reco')
def reco():
# Update sentiment for each post
posts = Post.query.all()
# Update sentiment for each post
for post in posts:
post.sentiment = get_sentiment(post.content)
# Create a set to track seen locations
seen_locations = set()
# Filter posts with positive sentiment and unique locations
unique_positive_posts = []
for post in posts:
if post.sentiment == 'positive' and post.location not in seen_locations:
unique_positive_posts.append(post)
seen_locations.add(post.location)
return render_template('reco.html', positive_posts=unique_positive_posts)
@app.route('/chat', methods=['GET', 'POST'])
def chatbot():
if request.method == 'POST':
user_message = request.form.get('user_message')
if user_message.strip() != "":
bot_response = get_bot_response(user_message)
chat_history.append({"user": user_message, "bot": bot_response})
return render_template('chatbot.html', chat_history=chat_history)
@app.route('/search', methods=['GET'])
def search():
query = request.args.get('query')
posts = Post.query.filter(Post.content.ilike(f'%{query}%')).all()
for post in posts:
post.sentiment = get_sentiment(post.content)
return render_template('userfeed.html', posts=posts)
@app.route('/post_experience', methods=['POST'])
@login_required
def post_experience():
content = request.form['content']
location = request.form['location']
return redirect(url_for('userfeed'))
if __name__ == "__main__":
with app.app_context():
db.create_all()
app.run(debug=True)