-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
264 lines (218 loc) · 9.52 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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
from flask import Flask, render_template, request, redirect, url_for, flash, session, jsonify
from flask_session import Session
from werkzeug.security import check_password_hash, generate_password_hash
from helpers import login_required, get_db_connection
from groq_api import get_model_response
import os
# Configure application
app = Flask(__name__)
# Configure session to use filesystem (instead of signed cookies)
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
@app.after_request
def after_request(response):
"""Ensure responses aren't cached"""
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
@app.route("/")
def index():
"""Show index page"""
return render_template("index.html")
@app.route("/myplan")
def myplan():
"""Show subscription plans page"""
return render_template("myplan.html")
@app.route("/usage")
def usage():
"""Show usage page"""
return render_template("usage.html")
@app.route("/contact")
def contact():
"""Show contact page"""
return render_template("contact.html")
@app.route("/login", methods=["GET", "POST"])
def login():
"""Log user in"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure username was submitted
username = request.form.get("username")
password = request.form.get("password")
# Ensure username and password were submitted
if not username or not password:
flash("Must provide username and password", "warning")
return render_template("login.html")
# Query database for username
conn = get_db_connection("users.db")
user = conn.execute("SELECT * FROM users WHERE username = ?", (request.form.get("username"),)).fetchone()
conn.close()
# Ensure username exists and password is correct
if user is None or not check_password_hash(user["password"], request.form.get("password")):
flash("Invalid username and/or password")
return render_template("login.html")
# Remember which user has logged in
session["user_id"] = user["id"]
session["username"] = user["username"]
# Redirect user to home page
flash("You have successfully logged in")
return redirect("/learn")
else:
return render_template("login.html")
@app.route("/logout")
def logout():
"""Log user out"""
# Forget any user_id
session.clear()
# Redirect user to home page
flash("You have successfully logged out")
return redirect("/")
@app.route("/register", methods=["GET", "POST"])
def register():
"""Register user"""
if request.method == "POST":
username = request.form.get("username")
password = request.form.get("password")
confirmation = request.form.get("confirmation")
# Ensure username and password were submitted
if not username or not password:
flash("Must provide username and password", "warning")
return render_template("register.html")
# Ensure password and confirmation match
if password != confirmation:
flash("Password and confirmation must match", "warning")
return render_template("register.html")
# Query database for username to ensure it does not already exist
conn = get_db_connection("users.db")
cur = conn.cursor() # Create a cursor object using the connection
cur.execute("SELECT * FROM users WHERE username = ?", (username,))
user_check = cur.fetchone()
if user_check:
conn.close()
flash("Username already exists", "warning")
return render_template("register.html")
# Insert new user into the database
cur.execute("INSERT INTO users (username, password) VALUES (?, ?)",
(username, generate_password_hash(password)))
conn.commit()
user_id = cur.lastrowid # Get the last inserted ID using the cursor
conn.close()
# Set user_id and username in session
session["user_id"] = user_id
session["username"] = username
# Redirect user to the form page to continue registration process
flash("You have successfully registered. Please complete your profile.")
return redirect(url_for("profile"))
else:
return render_template("register.html")
#FORM IS NOT USED IN THIS VERSION OF THE APP
'''
@app.route("/form", methods=["GET", "POST"])
@login_required
def form():
if request.method == "POST":
age = int(request.form.get("age")) # Ensure age is correctly formatted as integer
likes = request.form.getlist("likes") # Retrieves all values from checkboxes named 'likes'
learning_preference = int(request.form.get("learning_preference")) # Retrieves the slider value as integer
# Save this information to your database
conn = get_db_connection("users.db")
cursor = conn.cursor()
try:
# Update the user's data in the database
cursor.execute("UPDATE users SET age = ?, likes = ?, learning_preference = ? WHERE id = ?",
(age, ','.join(likes), learning_preference, session['user_id']))
conn.commit()
flash("Information saved successfully!")
except Exception as e:
conn.rollback()
flash(f"An error occurred: {str(e)}", "error")
finally:
conn.close()
# Redirect to user profile upon successful submission
return redirect(url_for("profile"))
else:
# Render the form page if the request is GET
return render_template("form.html")
'''
@app.route("/profile", methods=["GET", "POST"])
@login_required
def profile():
conn = get_db_connection("users.db")
cursor = conn.cursor()
if request.method == "POST":
username = request.form['username']
age = request.form['age']
likes = ','.join(request.form.getlist('likes'))
learning_preference = request.form['learning_preference']
# Check for new interests
new_interest = request.form.get('new_interest')
if new_interest:
likes += f",{new_interest}"
try:
cursor.execute("UPDATE users SET username = ?, age = ?, likes = ?, learning_preference = ? WHERE id = ?",
(username, age, likes, learning_preference, session['user_id']))
conn.commit()
flash("Profile updated successfully", "info")
finally:
conn.close()
return redirect(url_for('learn_mathematics'))
else:
cursor.execute("SELECT * FROM users WHERE id = ?", (session['user_id'],))
user = dict(cursor.fetchone())
user['likes'] = user['likes'].split(',') if user['likes'] else []
conn.close()
return render_template("profile.html", user=user)
# Route to display mathematics topics
@app.route('/learn', methods=['GET'])
@login_required
def learn_mathematics():
# Define a list of mathematics topics
math_topics = [
"Algebra",
"Calculus",
"Geometry",
"Trigonometry",
"Statistics",
"Probability",
"Number Theory",
"Discrete Mathematics"
]
# Render the learn.html template, passing in the math_topics list
return render_template('learn.html', math_topics=math_topics)
@app.route('/chat/<topic>', methods=['GET', 'POST'])
@login_required
def chat(topic):
if request.method == 'POST':
user_input = request.form['user_input']
conn = get_db_connection("users.db")
cursor = conn.cursor()
user_data = cursor.execute("SELECT * FROM users WHERE id = ?", (session['user_id'],)).fetchone()
# Update chats_opened if this is the first message in this chat session
if 'chat_opened' not in session:
cursor.execute("UPDATE users SET chats_opened = chats_opened + 1 WHERE id = ?", (session['user_id'],))
conn.commit()
session['chat_opened'] = True
# Increment the requests_made count
cursor.execute("UPDATE users SET requests_made = requests_made + 1 WHERE id = ?", (session['user_id'],))
conn.commit()
if user_data:
user_data = dict(user_data)
# Initialize or retrieve history from session
if 'history' not in session:
session['history'] = []
if user_input == "":
return jsonify({'response': "Please enter a message."})
# Generate a response using the updated function with memory
response = get_model_response(user_input, session['history'], user_data)
# Save user input and bot response to session for memory
session['history'].append({'role': 'user', 'content': user_input})
session['history'].append({'role': 'assistant', 'content': response})
return jsonify({'response': response})
return render_template('chat.html', initial_topic=topic)
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(debug=False, host='0.0.0.0', port=port)