-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
415 lines (347 loc) · 14.7 KB
/
Copy pathapp.py
File metadata and controls
415 lines (347 loc) · 14.7 KB
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
from flask import Flask, render_template, request, redirect, url_for, session, flash, jsonify, send_file
import pymysql
from pymysql import Error
from flask_bcrypt import Bcrypt
from datetime import datetime
import csv
import io
import requests
app = Flask(__name__)
app.secret_key = "3f1a8e6b9c0d2f5a7e1d44abefc23998b7d4e61f2a0cd8ef3c3b7e22a9a5f6d9" # change this in production
bcrypt = Bcrypt(app)
# ------------------ DATABASE CONNECTION ------------------ #
def get_db_connection():
try:
conn = pymysql.connect(
host="localhost",
user="root",
password="",
database="DropZero",
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)
return conn
except Error as e:
print("Error while connecting to MySQL", e)
return None
# ------------------ HOME / LOGIN ------------------ #
from flask import render_template, request, redirect, url_for, session, flash
@app.route("/", methods=["GET", "POST"])
def login():
if request.method == "POST":
email = request.form["email"]
password = request.form["password"]
role = request.form.get("role", "user") # Get role from form, default to user
conn = get_db_connection()
if not conn:
flash("Database connection failed. Please try again.", "danger")
return render_template("login.html")
cursor = conn.cursor()
try:
if role == "admin":
# Check admin table
cursor.execute("SELECT * FROM admin WHERE email = %s", (email,))
admin_account = cursor.fetchone()
if admin_account and bcrypt.check_password_hash(admin_account["password_hash"], password):
session["admin_id"] = admin_account["admin_id"]
flash("Welcome Admin!", "success")
return redirect(url_for("admin_dashboard"))
else:
# Check users table
cursor.execute("SELECT * FROM users WHERE email = %s", (email,))
user_account = cursor.fetchone()
if user_account and bcrypt.check_password_hash(user_account["password_hash"], password):
session["user_id"] = user_account["user_id"]
flash("Welcome User!", "success")
return redirect(url_for("user_dashboard"))
flash("Invalid email or password", "danger")
except Error as e:
flash("An error occurred during login. Please try again.", "danger")
print(f"Database error: {e}")
finally:
cursor.close()
conn.close()
return render_template("login.html")
# ------------------ REGISTER ------------------ #
@app.route("/register", methods=["GET", "POST"])
def register():
if request.method == "POST":
name = request.form["name"]
email = request.form["email"]
password = request.form["password"]
conn = get_db_connection()
if not conn:
flash("Database connection failed. Please try again.", "danger")
return render_template("register.html")
cursor = conn.cursor()
try:
# check if email already exists
cursor.execute("SELECT * FROM users WHERE email = %s", (email,))
existing_user = cursor.fetchone()
if existing_user:
flash("Email already registered!", "warning")
return redirect(url_for("register"))
hashed_password = bcrypt.generate_password_hash(password).decode("utf-8")
created_at = datetime.now()
cursor.execute(
"INSERT INTO users (name, email, password_hash, created_at) VALUES (%s, %s, %s, %s)",
(name, email, hashed_password, created_at),
)
conn.commit()
flash("Account created successfully! Please log in.", "success")
return redirect(url_for("login"))
except Error as e:
flash("An error occurred during registration. Please try again.", "danger")
print(f"Database error: {e}")
finally:
cursor.close()
conn.close()
return render_template("register.html")
# ------------------ DASHBOARDS ------------------ #
@app.route("/admin/dashboard")
def admin_dashboard():
if "admin_id" not in session:
flash("Please log in as admin first", "warning")
return redirect(url_for("login"))
return render_template("admin_dashboard.html")
@app.route("/user/dashboard")
def user_dashboard():
if "user_id" not in session:
flash("Please log in as user first", "warning")
return redirect(url_for("login"))
return render_template("user_dashboard.html")
# ------------------ ADMIN FEATURES ------------------ #
@app.route("/admin/monitor_users", methods=["GET", "POST"])
def monitor_users():
if "admin_id" not in session:
flash("Please log in as admin first", "warning")
return redirect(url_for("login"))
if request.method == "POST":
user_id = request.form.get("user_id")
if user_id:
conn = get_db_connection()
if not conn:
flash("Database connection failed. Please try again.", "danger")
return redirect(url_for("admin_dashboard"))
cursor = conn.cursor()
try:
cursor.execute("DELETE FROM users WHERE user_id = %s", (user_id,))
conn.commit()
flash("User deleted successfully!", "success")
except Error as e:
flash("An error occurred while deleting user. Please try again.", "danger")
print(f"Database error: {e}")
finally:
cursor.close()
conn.close()
return redirect(url_for("admin_dashboard"))
# GET request - return JSON for AJAX
conn = get_db_connection()
if not conn:
return jsonify({"error": "Database connection failed"}), 500
cursor = conn.cursor()
try:
cursor.execute("SELECT user_id, name, email, created_at FROM users")
users = cursor.fetchall()
return jsonify(users)
except Error as e:
print(f"Database error: {e}")
return jsonify({"error": "Failed to fetch users"}), 500
finally:
cursor.close()
conn.close()
@app.route("/admin/view_users")
def view_users():
if "admin_id" not in session:
flash("Please log in as admin first", "warning")
return redirect(url_for("login"))
conn = get_db_connection()
if not conn:
flash("Database connection failed. Please try again.", "danger")
return redirect(url_for("admin_dashboard"))
cursor = conn.cursor()
try:
cursor.execute("SELECT user_id, name, email, created_at FROM users")
users = cursor.fetchall()
return render_template("view_users.html", users=users)
except Error as e:
flash("An error occurred while fetching users. Please try again.", "danger")
print(f"Database error: {e}")
return redirect(url_for("admin_dashboard"))
finally:
cursor.close()
conn.close()
@app.route("/admin/add_discussion", methods=["POST"])
def add_discussion():
if "admin_id" not in session:
flash("Please log in as admin first", "warning")
return redirect(url_for("login"))
if "csv_file" not in request.files:
flash("No file uploaded", "danger")
return redirect(url_for("admin_dashboard"))
file = request.files["csv_file"]
if file.filename == "":
flash("No file selected", "danger")
return redirect(url_for("admin_dashboard"))
if file and file.filename.endswith(".csv"):
try:
stream = io.StringIO(file.stream.read().decode("UTF8"), newline=None)
csv_reader = csv.reader(stream)
conn = get_db_connection()
if not conn:
flash("Database connection failed. Please try again.", "danger")
return redirect(url_for("admin_dashboard"))
cursor = conn.cursor()
# Skip header row
next(csv_reader, None)
for row in csv_reader:
if len(row) >= 3:
username, comment, discussion_topic = row[0], row[1], row[2]
cursor.execute(
"INSERT INTO comment (username, comment, discussion_topic) VALUES (%s, %s, %s)",
(username, comment, discussion_topic)
)
conn.commit()
flash("Discussion data uploaded successfully!", "success")
except Error as e:
flash("An error occurred while uploading data. Please try again.", "danger")
print(f"Database error: {e}")
except Exception as e:
flash("An error occurred while processing the file. Please check the file format.", "danger")
print(f"File processing error: {e}")
finally:
if 'cursor' in locals():
cursor.close()
if 'conn' in locals():
conn.close()
else:
flash("Invalid file format. Please upload a CSV file.", "danger")
return redirect(url_for("admin_dashboard"))
@app.route("/admin/generate_summary", methods=["POST"])
def generate_summary():
if "admin_id" not in session:
flash("Please log in as admin first", "warning")
return redirect(url_for("login"))
# TODO: Integrate sentiments.py and summary.py here
# For now, just a placeholder
flash("Summary generation feature will be implemented once sentiments.py and summary.py are provided.", "info")
return redirect(url_for("admin_dashboard"))
@app.route('/generate_sentiment', methods=['POST'])
def generate_sentiment():
if "admin_id" not in session:
flash("Access denied!", "danger")
return redirect(url_for("login"))
# Define the API endpoint URL
# In app.py
api_url = "https://743f20591f86.ngrok-free.app/analyze"
try:
# Make a POST request to the sentiment analysis API
response = requests.post(api_url, timeout=60) # timeout of 5 seconds
# Check if the API call was accepted
if response.status_code == 200:
flash("Sentiment analysis has been successfully started! The results will be available shortly.", "success")
else:
# Handle cases where the API might be down or returned an error
flash(f"Failed to start sentiment analysis. API returned status: {response.status_code}", "danger")
print(f"API Error: {response.text}")
except requests.exceptions.RequestException as e:
# Handle network-related errors (e.g., the API server is not running)
flash("Could not connect to the sentiment analysis service. Please ensure it is running.", "danger")
print(f"Connection Error: {e}")
# Redirect back to the dashboard immediately
return redirect(url_for("admin_dashboard"))
@app.route("/admin/get_word_cloud")
def get_word_cloud():
if "admin_id" not in session:
flash("Please log in as admin first", "warning")
return redirect(url_for("login"))
# TODO: Implement word cloud generation from summaries
# For now, just a placeholder
flash("Word cloud generation feature will be implemented.", "info")
return redirect(url_for("admin_dashboard"))
@app.route("/admin/view_summary")
def view_summary():
if "admin_id" not in session:
flash("Please log in as admin first", "warning")
return redirect(url_for("login"))
# TODO: Implement summary viewing functionality
# For now, just a placeholder
flash("Summary viewing feature will be implemented.", "info")
return redirect(url_for("admin_dashboard"))
@app.route('/view_sentiment_score')
def view_sentiment_score():
if "admin_id" not in session:
flash("Please log in as admin first", "warning")
return redirect(url_for("login"))
conn = get_db_connection()
if not conn:
flash("Database connection failed", "danger")
return redirect(url_for("admin_dashboard"))
cursor = conn.cursor()
try:
cursor.execute("SELECT * FROM sentiment_score ORDER BY sentiment_score DESC")
results = cursor.fetchall()
except Error as e:
flash("Error fetching sentiment results", "danger")
print("Database error:", e)
results = []
finally:
cursor.close()
conn.close()
return render_template("view_sentiment_score.html", results=results)
@app.route("/admin/view_comments")
def view_comments():
if "admin_id" not in session:
flash("Please log in as admin first", "warning")
return redirect(url_for("login"))
conn = get_db_connection()
if not conn:
flash("Database connection failed. Please try again.", "danger")
return redirect(url_for("admin_dashboard"))
cursor = conn.cursor()
try:
# Get all comments grouped by discussion topic
cursor.execute("""
SELECT discussion_topic,
COUNT(*) as comment_count,
GROUP_CONCAT(CONCAT(username, ': ', comment) SEPARATOR '|||') as comments
FROM comment
GROUP BY discussion_topic
ORDER BY discussion_topic
""")
topics_data = cursor.fetchall()
# Process the data for better display
processed_topics = []
for topic in topics_data:
comments_list = []
if topic['comments']:
comments = topic['comments'].split('|||')
for comment in comments:
if ':' in comment:
username, comment_text = comment.split(':', 1)
comments_list.append({
'username': username.strip(),
'comment': comment_text.strip()
})
processed_topics.append({
'topic': topic['discussion_topic'],
'comment_count': topic['comment_count'],
'comments': comments_list
})
return render_template("view_comments.html", topics=processed_topics)
except Error as e:
flash("An error occurred while fetching comments. Please try again.", "danger")
print(f"Database error: {e}")
return redirect(url_for("admin_dashboard"))
finally:
cursor.close()
conn.close()
# ------------------ LOGOUT ------------------ #
@app.route("/logout")
def logout():
session.clear()
flash("You have been logged out!", "info")
return redirect(url_for("login"))
# ------------------ MAIN ------------------ #
if __name__ == "__main__":
app.run(debug=True)