-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproj_v0_01.py
473 lines (423 loc) · 15.3 KB
/
proj_v0_01.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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
import cx_Oracle
from flask import Flask, request, session, render_template, redirect, url_for, make_response, jsonify
from hashlib import sha256
try:
conn = cx_Oracle.connect('ora_proj2/hr@//localhost:1521/XE')
except Exception as err:
print('Error while creating the connection ', err)
app = Flask(__name__)
app.secret_key = "secret_key"
def select_from_users():
users = []
try:
cur = conn.cursor()
sql_select = "SELECT * FROM TABLE ( users_pkg.select_all_users() )"
cur.execute(sql_select)
users = cur.fetchall()
except Exception as err:
print('Exception occured while fetching the records ', err)
else:
print('Query Completed.')
finally:
cur.close()
return users
def select_user_where(*user_credentials):
users = []
try:
cur = conn.cursor()
p_email, p_password = ':1', ':2'
sql_select = f"SELECT * FROM TABLE ( users_pkg.select_user_where({p_email}, {p_password}) )"
cur.execute(sql_select, user_credentials)
users = cur.fetchall()
except Exception as err:
print('Exception occured while fetching the records ', err)
else:
print('Query Completed.')
finally:
cur.close()
return users
def insert_into_users(*user_data):
err = []
email, password, first_name, last_name = user_data
try:
cur = conn.cursor()
password = sha256(password.encode("UTF-8")).hexdigest()
user_data = (email, password, first_name, last_name)
cur.callproc('users_pkg.insert_user', user_data)
except cx_Oracle.IntegrityError as e:
errorObj, = e.args
print('ERROR while inserting the data ', errorObj)
err.append("Username already exists.")
else:
print('Insert Completed.')
finally:
cur.close()
return err
def select_from_categories():
categories = []
try:
cur = conn.cursor()
sql_select = "SELECT * FROM TABLE ( categories_pkg.select_all_categories() )"
cur.execute(sql_select)
categories = cur.fetchall()
except Exception as err:
print('Exception occured while fetching the records ', err)
else:
print('Query Completed.')
finally:
cur.close()
return categories
def select_from_articles(select):
articles = []
try:
cur = conn.cursor()
sql_select = f"SELECT {select} FROM ARTICLES1, SOURCES1, CATEGORIES1 WHERE ARTICLES1.source_id=SOURCES1.id AND ARTICLES1.category_id=CATEGORIES1.id ORDER BY publishedAt DESC"
cur.execute(sql_select)
articles = cur.fetchall()
except Exception as err:
print('Exception occured while fetching the records ', err)
else:
print('Query Completed.')
finally:
cur.close()
return articles
def select_from_articles_where(select, where, *data):
articles = []
try:
cur = conn.cursor()
sql_select = f"SELECT {select} FROM ARTICLES1, SOURCES1, CATEGORIES1 WHERE ARTICLES1.source_id=SOURCES1.id AND ARTICLES1.category_id=CATEGORIES1.id AND {where} ORDER BY publishedAt DESC"
cur.execute(sql_select, data)
articles = cur.fetchall()
except Exception as err:
print('Exception occured while fetching the records ', err)
else:
print('Query Completed.')
finally:
cur.close()
return articles
def insert_into_articles(*user_data):
err = []
source, category, author, title, description, url, urlToImage, content = user_data
try:
cur = conn.cursor()
user_data = (source, category, author, title, description, url, urlToImage, content)
cur.callproc('articles_pkg.insert_article', user_data)
except cx_Oracle.IntegrityError as e:
errorObj, = e.args
err.append("ERROR: " + str(errorObj))
print('ERROR while inserting the data ', errorObj)
else:
print('Insert Completed.')
finally:
cur.close()
return err
def insert_into_users_articles(*user_data):
err = []
user_id, article_id = user_data
try:
cur = conn.cursor()
user_data = (user_id, article_id)
cur.callproc('users_articles_pkg.insert_users_articles', user_data)
except cx_Oracle.IntegrityError as e:
errorObj, = e.args
print('ERROR while inserting the data ', errorObj)
err.append("Star already exists.")
else:
print('Insert Completed.')
finally:
cur.close()
return err
def delete_from_users_articles(*user_data):
err = []
user_id, article_id = user_data
try:
cur = conn.cursor()
user_data = (user_id, article_id)
cur.callproc('users_articles_pkg.delete_users_articles', user_data)
except cx_Oracle.IntegrityError as e:
errorObj, = e.args
print('ERROR while inserting the data ', errorObj)
err.append("Star already exists.")
else:
print('Insert Completed.')
finally:
cur.close()
return err
def select_users_articles_where(*user_id_credentials):
users_articles = []
try:
cur = conn.cursor()
p_user_id = ':1'
sql_select = f"SELECT * FROM TABLE ( users_articles_pkg.select_users_articles_where({p_user_id}) )"
cur.execute(sql_select, user_id_credentials)
users_articles = cur.fetchall()
except Exception as err:
print('Exception occured while fetching the records ', err)
else:
print('Query Completed.')
finally:
cur.close()
return users_articles
@app.route('/')
@app.route('/home')
def index():
err = []
if 'email' in session and 'password' in session:
email = session['email']
password = session['password']
users = select_user_where(email, password)
if len(users) <= 0:
err.append("Username OR password is incorrect.")
return render_template('login.html', errors=err)
users_articles = select_users_articles_where(users[0][0])
articles_id_ls = []
for x in users_articles:
articles_id_ls.append(x[1])
articles = select_from_articles('articles1.id, sources1.name, categories1.name, author, title, description, url, urlToImage, publishedAt, content')
categories = select_from_categories()
return render_template('home.html', session=session, users=users, articles=articles, categories=categories, articles_id_ls=articles_id_ls)
else:
return redirect('/login')
@app.route('/c/<string:name>')
def category_page(name):
err = []
if 'email' in session and 'password' in session:
email = session['email']
password = session['password']
users = select_user_where(email, password)
if len(users) <= 0:
err.append("Username OR password is incorrect.")
return render_template('login.html', errors=err)
users_articles = select_users_articles_where(users[0][0])
articles_id_ls = []
for x in users_articles:
articles_id_ls.append(x[1])
categories = select_from_categories()
articles = select_from_articles_where('articles1.id, sources1.name, categories1.name, author, title, description, url, urlToImage, publishedAt, content', 'categories1.name=:1', name)
return render_template('home.html', session=session, users=users, categories=categories, articles=articles, articles_id_ls=articles_id_ls)
else:
return redirect('/login')
@app.route('/search', methods=['GET'])
def search():
err = []
if 'email' in session and 'password' in session:
email = session['email']
password = session['password']
if request.method == 'GET':
q = request.args['q'].lower()
users = select_user_where(email, password)
if len(users) <= 0:
err.append("Username OR password is incorrect.")
return render_template('login.html', errors=err)
users_articles = select_users_articles_where(users[0][0])
articles_id_ls = []
for x in users_articles:
articles_id_ls.append(x[1])
articles = select_from_articles_where(
'articles1.id, sources1.name, categories1.name, author, title, description, url, urlToImage, publishedAt, content',
f"(LOWER(title) LIKE '%{q}%' OR LOWER(description) LIKE '%{q}%' OR LOWER(categories1.name) LIKE '%{q}%' OR LOWER(sources1.name) LIKE '%{q}%' OR LOWER(author) LIKE '%{q}%' OR LOWER(content) LIKE '%{q}%' )"
)
categories = select_from_categories()
return render_template('home.html', session=session, users=users, articles=articles, categories=categories, articles_id_ls=articles_id_ls)
else:
return redirect('/login')
@app.route('/register', methods=['POST', 'GET'])
def register():
err = []
categories = select_from_categories()
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
first_name = request.form['first_name']
last_name = request.form['last_name']
err = insert_into_users(
email, password, first_name, last_name
)
if len(err) <= 0:
return redirect(url_for('login'))
else:
return render_template('register.html', categories=categories, errors=err)
else:
return render_template('register.html', categories=categories)
@app.route('/login', methods=['POST', 'GET'])
def login():
err = []
if request.method == 'POST':
email = request.form['email']
password = sha256(request.form['password'].encode("UTF-8")).hexdigest()
users = select_user_where(email, password)
categories = select_from_categories()
if len(users) > 0:
session['email'] = email
session['password'] = password
if session['email']=='[email protected]' \
and session['password']==sha256('admin'.encode("UTF-8")).hexdigest():
return redirect("/admin")
return redirect("/")
else:
err.append("Username OR password is incorrect.")
return render_template('login.html', categories=categories, errors=err)
# return redirect('/login')
else:
categories = select_from_categories()
return render_template('login.html', categories=categories)
@app.route('/logout')
def logout():
if 'email' in session and 'password' in session:
del session['email']
del session['password']
return redirect('/login')
@app.route('/admin', methods=['POST', 'GET'])
def admin():
err = []
categories = select_from_categories()
if request.method == 'POST':
source = request.form['source']
category = 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']
err = insert_into_articles(source, category, author, title, description, url, urlToImage, content)
if len(err) <= 0:
return redirect(url_for('index'))
else:
return render_template('admin.html', categories=categories, errors=err)
else:
if 'email' in session \
and 'password' in session \
and session['email']=='[email protected]' \
and session['password']==sha256('admin'.encode("UTF-8")).hexdigest():
categories = select_from_categories()
return render_template('admin.html', session=session, categories=categories)
else:
return redirect('/logout')
@app.route('/addstar', methods=['POST', 'GET'])
def addstar():
if request.method == 'POST':
req = request.get_json()
err = insert_into_users_articles(
req['user_id'], req['article_id']
)
if len(err) <= 0:
res = make_response(jsonify({'message':"ok"}), 200)
return res;
else:
res = make_response(jsonify({'message':"not ok"}), 400)
return res;
else:
res = make_response(jsonify({'message':"not Post"}), 400)
return res;
@app.route('/removestar', methods=['POST', 'GET'])
def removestar():
if request.method == 'POST':
req = request.get_json()
print(req)
err = delete_from_users_articles(
req['user_id'], req['article_id']
)
if len(err) <= 0:
res = make_response(jsonify({'message':"ok"}), 200)
return res;
else:
res = make_response(jsonify({'message':"not ok"}), 400)
return res;
else:
res = make_response(jsonify({'message':"not Post"}), 400)
return res;
@app.route('/favorite')
def favorite():
err = []
articles = []
if 'email' in session and 'password' in session:
email = session['email']
password = session['password']
users = select_user_where(email, password)
if len(users) <= 0:
err.append("Username OR password is incorrect.")
return render_template('login.html', errors=err)
users_articles = select_users_articles_where(users[0][0])
if len(users_articles) > 0:
articles_num = ':1'
for i in range(2, len(users_articles)+1):
articles_num += ', :'+ str(i)
articles_id_ls = []
for x in users_articles:
articles_id_ls.append(x[1])
articles = select_from_articles_where('articles1.id, sources1.name, categories1.name, author, title, description, url, urlToImage, publishedAt, content', f'articles1.id IN ({articles_num})', *articles_id_ls)
categories = select_from_categories()
return render_template('home.html', session=session, users=users, articles=articles, categories=categories, articles_id_ls=articles_id_ls)
else:
categories = select_from_categories()
return render_template('home.html', session=session, users=users, articles=articles, categories=categories)
else:
return redirect('/login')
@app.route('/predict', methods=['POST'])
def predict_category():
if request.method == 'POST':
req = request.get_json()
from ml import predict
category = predict(req['content'])
res = make_response(jsonify({'category': category[0]}), 200)
return res
else:
res = make_response(jsonify({'message':"not Post"}), 400)
return res;
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.metrics.pairwise import linear_kernel, cosine_similarity
def get_recommendations(cosine_sim, titles, article_ids):
id = article_ids
sim_scores = []
for idx in id:
sim_scores = sim_scores + list(enumerate(cosine_sim[idx]))
sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
project_indices = [i[0] for i in sim_scores]
return titles.iloc[project_indices][len(id):]
@app.route('/recommendation')
def recommendation():
err = []
articles = []
if 'email' in session and 'password' in session:
email = session['email']
password = session['password']
users = select_user_where(email, password)
if len(users) <= 0:
err.append("Username OR password is incorrect.")
return render_template('login.html', errors=err)
categories = select_from_categories()
users_articles = select_users_articles_where(users[0][0])
if len(users_articles) > 0:
articles_id_ls = []
for x in users_articles:
articles_id_ls.append(x[1])
articles = select_from_articles('articles1.id, sources1.name, categories1.name, author, title, description, url, urlToImage, publishedAt, content')
df = pd.DataFrame(np.array(articles), columns=['id', 'source', 'category', 'author', 'title', 'description', 'url', 'urlToImage', 'publishedAt', 'content'])
df = df.set_index('id')
df['text'] = df['category'] + " " + df['title'] + " " + df['description']
tf = TfidfVectorizer(analyzer='word',ngram_range=(1, 2),min_df=0, stop_words='english')
tfidf_matrix = tf.fit_transform(df['text'])
cosine_sim = linear_kernel(tfidf_matrix, tfidf_matrix)
titles = df['title']
indices = pd.Series(df.index, index=df['title'])
recommended = get_recommendations(cosine_sim, titles, articles_id_ls).head(25)
recommended = recommended.index.values.tolist()
if len(recommended) > 0:
articles_num = ':1'
for i in range(2, len(recommended)+1):
articles_num += ', :'+ str(i)
print(recommended)
articles = select_from_articles_where('articles1.id, sources1.name, categories1.name, author, title, description, url, urlToImage, publishedAt, content', f'articles1.id IN ({articles_num})', *recommended)
return render_template('home.html', session=session, users=users, articles=articles, categories=categories, articles_id_ls=articles_id_ls)
else:
return render_template('home.html', session=session, users=users, articles=articles, categories=categories)
else:
return render_template('home.html', session=session, users=users, articles=articles, categories=categories)
else:
return redirect('/login')
if __name__=="__main__":
app.run(debug=True)
conn.close()