-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
425 lines (353 loc) · 16.6 KB
/
main.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
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
416
417
418
419
420
421
422
423
424
from flask import Flask, render_template, url_for, request, redirect, session, make_response, jsonify
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import desc, func
from hashlib import sha256
from datetime import datetime
import pandas as pd
app = Flask(__name__)
app.secret_key = 'secret_key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///news.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
email = db.Column(db.String(255), nullable=False, unique=True)
password = db.Column(db.Text, nullable=False)
first_name = db.Column(db.String(255), nullable=False)
last_name = db.Column(db.String(255))
favorites = db.relationship('Favourite', backref='users', lazy='dynamic')
def __repr__(self):
return f"<User::{self.id}>"
class Source(db.Model):
__tablename__ = "sources"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(255), nullable=False, unique=True)
articles = db.relationship('Article', backref='sources', lazy='dynamic')
def __repr__(self):
return f"<Source::{self.id}>"
class Category(db.Model):
__tablename__ = "categories"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(255), nullable=False, unique=True)
articles = db.relationship('Article', backref='categories', lazy='dynamic')
def __repr__(self):
return f"<Category::{self.id}>"
class Article(db.Model):
__tablename__ = "articles"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
source_id = db.Column(db.Integer, db.ForeignKey('sources.id'), nullable=False)
category_id = db.Column(db.Integer, db.ForeignKey('categories.id'), nullable=False)
author = db.Column(db.String(255))
title = db.Column(db.String(511), nullable=False)
description = db.Column(db.Text)
url = db.Column(db.Text)
urlToImage = db.Column(db.Text)
publishedAt = db.Column(db.DateTime, default=datetime.utcnow)
content = db.Column(db.Text)
favorites = db.relationship('Favourite', backref='articles', lazy='dynamic')
def __repr__(self):
return f"<Article::{self.id}>"
def as_dict(self):
return {
'id': self.id,
'source_id': self.source_id,
'category_id': self.category_id,
'author': self.author,
'title': self.title,
'description': self.description,
'url': self.url,
'urlToImage': self.urlToImage,
'publishedAt': self.publishedAt,
'content': self.content
}
class Favourite(db.Model):
__tablename__ = "favourites"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
article_id = db.Column(db.Integer, db.ForeignKey('articles.id'), nullable=False)
def __repr__(self):
return f"<Favourite | User::{self.user_id} | Article::{self.article_id}>"
# >>> Main, Categories, Search, Favorite pages
@app.route('/')
def index():
if 'email' in session and 'password' in session:
categories = Category.query.order_by(Category.name).all()
user = User.query.filter_by(email=session['email']).first()
articles = Article.query.order_by(Article.publishedAt.desc()).all()[:20]
favourites = Favourite.query.filter_by(user_id=user.id).all()
favourite_articles = []
for favourite in favourites:
favourite_articles.append(favourite.article_id)
return render_template('main/article.html', categories=categories, articles=articles[:20], user=user, favourite_articles=favourite_articles)
else:
return redirect('/login')
@app.route('/c/<string:name>')
def category(name):
if 'email' in session and 'password' in session:
categories = Category.query.order_by(Category.name).all()
user = User.query.filter_by(email=session['email']).first()
category = Category.query.filter_by(name=name).first()
if category is not None:
articles = Article.query.filter_by(category_id=category.id).order_by(Article.publishedAt.desc()).all()
favourites = Favourite.query.filter_by(user_id=user.id).all()
favourite_articles = []
for favourite in favourites:
favourite_articles.append(favourite.article_id)
return render_template('main/article.html', categories=categories, articles=articles[:20], user=user, favourite_articles=favourite_articles)
else:
errorHeader = 'Not Found This Category'
errors = [f"Category: {name}, doesn't exists"]
return render_template('error.html', errorHeader=errorHeader, errors=errors)
else:
return redirect('/login')
@app.route('/search', methods=['GET'])
def search():
if 'email' in session and 'password' in session:
q = request.args['q'].lower()
q = q.replace("-", " ").split()
categories = Category.query.order_by(Category.name).all()
user = User.query.filter_by(email=session['email']).first()
articles = Article.query.order_by(Article.publishedAt.desc()).all()
favourites = Favourite.query.filter_by(user_id=user.id).all()
favourite_articles = []
for favourite in favourites:
favourite_articles.append(favourite.article_id)
search_articles = []
for article in articles:
txt = article.sources.name.lower() +" "+\
article.categories.name.lower() +" "+\
article.author.lower() +" "+\
article.title.lower() +" "+\
article.description.lower() +" "+\
article.content.lower()
n = 0
for s in q:
if s in txt: n += 1
if len(q) == n:
search_articles.append(article)
return render_template('main/article.html', categories=categories, articles=search_articles[:20], user=user, favourite_articles=favourite_articles)
else:
return redirect('/login')
@app.route('/favorite')
def favorite():
if 'email' in session and 'password' in session:
categories = Category.query.order_by(Category.name).all()
user = User.query.filter_by(email=session['email']).first()
favourites = Favourite.query.filter_by(user_id=user.id).all()
favourite_articles = []
for favourite in favourites:
favourite_articles.append(favourite.article_id)
all_articles = Article.query.order_by(Article.publishedAt.desc()).all()
articles = []
for article in all_articles:
if article.id in favourite_articles:
articles.append(article)
return render_template('main/article.html', categories=categories, articles=articles, user=user, favourite_articles=favourite_articles)
else:
return redirect('/login')
import recommendation as rec
@app.route('/recommendation')
def recommendation():
if 'email' in session and 'password' in session:
categories = Category.query.order_by(Category.name).all()
articles = Article.query.order_by(Article.publishedAt.desc()).all()
df = pd.DataFrame([article.as_dict() for article in articles])
user = User.query.filter_by(email=session['email']).first()
favourites = Favourite.query.filter_by(user_id=user.id).all()
if len(favourites) != 0:
favourite_articles = []
for favourite in favourites:
favourite_articles.append(favourite.article_id)
recommended_articles = rec.get_recommendations(favourite_articles, df)
articles = Article.query.filter(Article.id.in_(recommended_articles)).order_by(Article.publishedAt.desc()).all()
return render_template('main/article.html', categories=categories, articles=articles, user=user, favourite_articles=favourite_articles)
else:
return render_template('main/article.html', categories=categories, user=user)
else:
return redirect('/login')
# >>> Register, Login, Logout
@app.route('/register', methods=['POST', 'GET'])
def register():
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
first_name = request.form['first_name']
last_name = request.form['last_name']
users = User(email=email, password=sha256(password.encode("UTF-8")).hexdigest(), first_name=first_name, last_name=last_name)
try:
db.session.add(users)
db.session.commit()
return redirect('/login')
except Exception as err:
if err.args[0] == '(sqlite3.IntegrityError) UNIQUE constraint failed: users.email':
return render_template('main/register.html', errors=["Email already exists"])
else:
return render_template('main/register.html', errors=["Other problem"])
else:
categories = Category.query.order_by(Category.name).all()
return render_template('main/register.html', categories=categories)
@app.route('/login', methods=['POST', 'GET'])
def login():
if request.method == 'POST':
email = request.form['email']
password = sha256(request.form['password'].encode("UTF-8")).hexdigest()
user = User.query.filter_by(email=email).first()
if user is not None:
if user.password == password:
session['email'] = email
session['password'] = password
return redirect('/')
else:
return render_template('main/login.html', errors=['Password incorrect'])
else:
return render_template('main/login.html', errors=['User not exists'])
else:
categories = Category.query.order_by(Category.name).all()
return render_template('main/login.html', categories=categories)
@app.route('/logout')
def logout():
if 'email' in session:
del session['email']
if 'password' in session:
del session['password']
return redirect('/login')
# >>> Other
@app.route('/addstar', methods=['POST'])
def addstar():
if request.method == 'POST':
req = request.get_json()
favourite = Favourite.query.filter_by(user_id=req['user_id'], article_id=req['article_id']).first()
if favourite is None:
favourite = Favourite(user_id=req['user_id'], article_id=req['article_id'])
try:
db.session.add(favourite)
db.session.commit()
res = make_response(jsonify({'message':"This mark has been added"}), 200)
return res
except Exception as err:
res = make_response(jsonify({'message':"ERROR adding this mark"}), 400)
return res
else:
res = make_response(jsonify({'message':"This mark already exists"}), 300)
return res
else:
res = make_response(jsonify({'message':"not Post"}), 400)
return res
@app.route('/removestar', methods=['POST'])
def removestar():
if request.method == 'POST':
req = request.get_json()
favourite = Favourite.query.filter_by(user_id=req['user_id'], article_id=req['article_id']).first()
if favourite is not None:
try:
db.session.delete(favourite)
db.session.commit()
res = make_response(jsonify({'message':"This mark has been removed"}), 200)
return res
except Exception as err:
res = make_response(jsonify({'message':"ERROR removing this mark"}), 400)
return res
else:
res = make_response(jsonify({'message':"This mark doesn't exist"}), 300)
return res
else:
res = make_response(jsonify({'message':"not Post"}), 400)
return res
from category.prediction import *
@app.route('/predict', methods=['POST'])
def category_prediction():
if request.method == 'POST':
req = request.get_json()
category_name = predict_category(req['content'])
category_id = Category.query.filter_by(name=category_name).first().id
res = make_response(jsonify({'category': category_id}), 200)
return res
else:
res = make_response(jsonify({'message':"not Post"}), 400)
return res
# >>> Admin
@app.route('/admin/articles', methods=['POST', 'GET'])
def admin_article():
if 'admin_email' in session and 'admin_password' in session:
categories = Category.query.order_by(Category.name).all()
if request.method == 'POST':
source_name = request.form['source']
category_id = request.form['category']
author = request.form['author']
title = request.form['title']
description = request.form['description']
url = request.form['url']
urlToImage = request.form['urlToImage']
content = request.form['content']
source = Source.query.filter_by(name=source_name).first()
if source is not None:
source_id = source.id
else:
source = Source(name=source_name)
try:
db.session.add(source)
db.session.commit()
source_id = source.id
except Exception as err:
if err.args[0] == '(sqlite3.IntegrityError) UNIQUE constraint failed: sources.name':
return render_template('admin/article.html', categories=categories, errors=["Source already exists"])
else:
return render_template('admin/article.html', categories=categories, errors=["Other problem"])
article = Article(
source_id = source_id,
category_id = category_id,
author = author,
title = title,
description = description,
url = url,
urlToImage = urlToImage,
content = content
)
try:
db.session.add(article)
db.session.commit()
return redirect('/admin/articles')
except Exception as err:
return render_template('admin/article.html', categories=categories, errors=["Other problem"])
else:
return render_template('admin/article.html', categories=categories)
else:
return redirect('/admin/login')
@app.route('/admin')
@app.route('/admin/dashboard')
def admin_index():
if 'admin_email' in session and 'admin_password' in session:
users = User.query.all()
sources = Source.query.all()
categories = Category.query.all()
articles = Article.query.all()
categories_name__articles_number = []
for category_id__article_number in Article.query.with_entities(Article.category_id, func.count(Article.id).label("number")).group_by(Article.category_id).order_by(desc("number")):
categories_name__articles_number.append( {"name":Category.query.get(category_id__article_number[0]).name, "number":category_id__article_number[1]} )
return render_template('admin/dashboard.html', users=users, sources=sources, categories=categories, articles=articles, categories_name__articles_number=categories_name__articles_number)
else:
return redirect('/admin/login')
@app.route('/admin/login', methods=['POST', 'GET'])
def admin_login():
if request.method == 'POST':
email = request.form['email']
password = sha256(request.form['password'].encode("UTF-8")).hexdigest()
if email == "[email protected]" and password == sha256("admin".encode("UTF-8")).hexdigest():
session['admin_email'] = email
session['admin_password'] = password
return redirect('/admin/dashboard')
else:
return render_template('admin/login.html', errors=['Admin or password incorrect'])
else:
return render_template('admin/login.html')
@app.route('/admin/logout')
def admin_logout():
if 'admin_email' in session:
del session['admin_email']
if 'admin_password' in session:
del session['admin_password']
return redirect('/admin/login')
# >>> Run
if __name__=="__main__":
app.run(debug=True)