-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathui_testing_4.py
500 lines (426 loc) · 21 KB
/
ui_testing_4.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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'movie_recommender.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
import os
import time
# data science imports
import math
import numpy as np
import pandas as pd
from scipy.sparse import csr_matrix
from sklearn.neighbors import NearestNeighbors
from fuzzywuzzy import fuzz
import pickle
from PIL import Image
# visualization imports
import seaborn as sns
import matplotlib.pyplot as plt
plt.style.use('ggplot')
default_list = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
recommendations_list = []
search_string = 'NULL'
df_movies = pd.read_csv(
'movies.csv',
usecols=['movieId', 'title'],
dtype={'movieId': 'int32', 'title': 'str'})
df_ratings = pd.read_csv(
'ratings.csv',
usecols=['userId', 'movieId', 'rating'],
dtype={'userId': 'int32', 'movieId': 'int32', 'rating': 'float32'})
# print(df_movies.head())
# print(df_ratings.head())
num_users = len(df_ratings.userId.unique())
num_items = len(df_ratings.movieId.unique())
# print('There are {} unique users and {} unique movies in this data set'.format(num_users, num_items))
df_ratings_cnt_tmp = pd.DataFrame(df_ratings.groupby('rating').size(), columns=['count'])
# print(df_ratings_cnt_tmp)
total_cnt = num_users * num_items
rating_zero_cnt = total_cnt - df_ratings.shape[0]
# append counts of zero rating to df_ratings_cnt
df_ratings_cnt = df_ratings_cnt_tmp.append(
pd.DataFrame({'count': rating_zero_cnt}, index=[0.0]),
verify_integrity=True,
).sort_index()
# print(df_ratings_cnt)
# add log count
df_ratings_cnt['log_count'] = np.log(df_ratings_cnt['count'])
# print(df_ratings_cnt)
df_movies_cnt = pd.DataFrame(df_ratings.groupby('movieId').size(), columns=['count'])
# print(df_movies_cnt.head())
# plot rating frequency of all movies
"""ax = df_movies_cnt.sort_values('count', ascending=False).reset_index(drop=True).plot(
figsize=(12, 8),
title='Rating Frequency of All Movies',
fontsize=12
)
ax.set_xlabel("movie Id")
ax.set_ylabel("number of ratings")
plt.show()"""
# filter data
popularity_thres = 10
popular_movies = list(set(df_movies_cnt.query('count >= @popularity_thres').index))
df_ratings_drop_movies = df_ratings[df_ratings.movieId.isin(popular_movies)]
# print('shape of original ratings data: ', df_ratings.shape)
# print('shape of ratings data after dropping unpopular movies: ', df_ratings_drop_movies.shape)
df_users_cnt = pd.DataFrame(df_ratings_drop_movies.groupby('userId').size(), columns=['count'])
# print(df_users_cnt.head())
# plot rating frequency of all movies
"""ax = df_users_cnt \
.sort_values('count', ascending=False) \
.reset_index(drop=True) \
.plot(
figsize=(12, 8),
title='Rating Frequency of All Users',
fontsize=12
)
ax.set_xlabel("user Id")
ax.set_ylabel("number of ratings")
plt.show()"""
# filter data
ratings_thres = 10
active_users = list(set(df_users_cnt.query('count >= @ratings_thres').index))
df_ratings_drop_users = df_ratings_drop_movies[df_ratings_drop_movies.userId.isin(active_users)]
# print('shape of original ratings data: ', df_ratings.shape)
# print('shape of ratings data after dropping both unpopular movies and inactive users: ', df_ratings_drop_users.shape)
# pivot and create movie-user matrix
movie_user_mat = df_ratings_drop_users.pivot(index='movieId', columns='userId', values='rating').fillna(0)
# map movie index to title
movie_to_idx = {
movie: i for i, movie in
enumerate(list(df_movies.set_index('movieId').loc[movie_user_mat.index].title))
}
# transform matrix to scipy sparse matrix
movie_user_mat_sparse = csr_matrix(movie_user_mat.values)
# define model
model_knn = NearestNeighbors(metric='cosine', algorithm='brute', n_neighbors=20, n_jobs=-1)
# fit
# model_knn.fit(movie_user_mat_sparse)
def read_and_clean_data_imdbId(path):
df = pd.read_csv(path, encoding="ISO-8859-1", usecols=["imdbId", "Title"])
df.set_index(["imdbId"], inplace=True)
# print(f"Shape of the original dataset: {df.shape}")
df.dropna(inplace=True)
# print(f"Shape after dropping rows with missing values: {df.shape}")
# df.drop_duplicates(subset="Poster", keep=False, inplace=True)
# print(f"Shape after dropping rows with potentially misleading poster link: {df.shape}\n")
return df
def read_and_clean_data_Title(path):
df = pd.read_csv(path, encoding="ISO-8859-1", usecols=["imdbId", "Title"])
df.set_index(["Title"], inplace=True)
# print(f"Shape of the original dataset: {df.shape}")
df.dropna(inplace=True)
# print(f"Shape after dropping rows with missing values: {df.shape}")
# df.drop_duplicates(subset="Poster", keep=False, inplace=True)
# print(f"Shape after dropping rows with potentially misleading poster link: {df.shape}\n")
return df
movie_imdbId_as_index = read_and_clean_data_imdbId(path="MoviePosterLinks.csv")
movie_Title_as_index = read_and_clean_data_Title(path="MoviePosterLinks.csv")
# print(movie_data)
# print(movie_imdbId_as_index['Title'][114709])
# print(movie_Title_as_index['imdbId']['Toy Story (1995)'])
recommendations_list_pictures = []
def get_imdbId_of_title(title):
"""gets image poster of given movie title through imdbId"""
match_tuple = []
for Title in movie_Title_as_index.index:
ratio = fuzz.ratio(Title.lower(), title.lower())
if ratio >= 50:
match_tuple.append((Title, movie_Title_as_index['imdbId'][Title], ratio))
match_tuple = sorted(match_tuple, key=lambda x: x[2])[::-1]
if not match_tuple:
# print('Oops! No matches found')
return
return match_tuple[0][1]
def get_image_from_imdbId(title):
imdbId = get_imdbId_of_title(title)
# print(imdbId)
file_path = "\\".join(["movie_posters_demo", str(imdbId) + ".jpg"])
if os.path.isfile(file_path):
recommendations_list_pictures.append("movie_posters_demo/" + str(imdbId) + ".jpg")
else:
recommendations_list_pictures.append("movie_posters_demo/No-image-available.jpg")
def fuzzy_matching(movieidx, fav_movie, verbose=True):
"""return the closest match via fuzzy ratio. If no match found, return None"""
match_tuple = []
# get match
for title, idx in movieidx.items():
ratio = fuzz.ratio(title.lower(), fav_movie.lower())
if ratio >= 50:
match_tuple.append((title, idx, ratio))
# sort
match_tuple = sorted(match_tuple, key=lambda x: x[2])[::-1]
if not match_tuple:
print('Oops! No matches found')
return None, None
if verbose:
print('Found possible matches in our database: {0}\n'.format([x[0] for x in match_tuple]))
return match_tuple[0][1], match_tuple[0][0]
def make_recommendation(model_knn, data, movieidx, fav_movie, n_recommendations):
"""return top n similar movie recommendations based on user's input movie"""
model_knn.fit(data)
print('You have input movie:', fav_movie)
idx, title = fuzzy_matching(movieidx, fav_movie, verbose=True)
print('......\n')
if idx != None:
distances, indices = model_knn.kneighbors(data[idx], n_neighbors=n_recommendations+1)
# get list of raw idx of recommendations
raw_recommends = \
sorted(list(zip(indices.squeeze().tolist(), distances.squeeze().tolist())), key=lambda x: x[1])[:0:-1]
# get reverse mapper
reverse_movieidx = {v: k for k, v in movieidx.items()}
print('Recommendations for {}:'.format(fav_movie))
# for i, (idx, dist) in enumerate(raw_recommends):
# get_image_from_imdbId(reverse_movieidx[idx])
for i, (idx, dist) in enumerate(raw_recommends):
file_path = "\\".join(["movie_posters_demo2", str(idx) + ".jpg"])
if os.path.isfile(file_path):
recommendations_list_pictures.append("movie_posters_demo2/" + str(idx) + ".jpg")
else:
recommendations_list_pictures.append("movie_posters_demo2/No-image-available.jpg")
# print(reverse_movieidx[idx] + ', with distance of ' + dist)
recommendations_list.append('{0}: {1}'.format(i+1, reverse_movieidx[idx]))
# recommendations_list.append(str(idx))
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(774, 578)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(230, 60, 251, 20))
self.lineEdit.setObjectName("lineEdit")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(490, 60, 75, 21))
self.pushButton.setObjectName("pushButton")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(10, 150, 61, 101))
self.label.setText("")
self.label.setPixmap(QtGui.QPixmap(default_list[0]))
self.label.setScaledContents(True)
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(180, 150, 61, 101))
self.label_2.setText("")
self.label_2.setPixmap(QtGui.QPixmap(default_list[1]))
self.label_2.setScaledContents(True)
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(350, 150, 61, 101))
self.label_3.setText("")
self.label_3.setPixmap(QtGui.QPixmap(default_list[2]))
self.label_3.setScaledContents(True)
self.label_3.setObjectName("label_3")
self.label_4 = QtWidgets.QLabel(self.centralwidget)
self.label_4.setGeometry(QtCore.QRect(520, 150, 61, 101))
self.label_4.setText("")
self.label_4.setPixmap(QtGui.QPixmap(default_list[3]))
self.label_4.setScaledContents(True)
self.label_4.setObjectName("label_4")
self.label_5 = QtWidgets.QLabel(self.centralwidget)
self.label_5.setGeometry(QtCore.QRect(690, 150, 61, 101))
self.label_5.setText("")
self.label_5.setPixmap(QtGui.QPixmap(default_list[4]))
self.label_5.setScaledContents(True)
self.label_5.setObjectName("label_5")
self.label_6 = QtWidgets.QLabel(self.centralwidget)
self.label_6.setGeometry(QtCore.QRect(10, 320, 60, 101))
self.label_6.setText("")
self.label_6.setPixmap(QtGui.QPixmap(default_list[5]))
self.label_6.setScaledContents(True)
self.label_6.setObjectName("label_6")
self.label_7 = QtWidgets.QLabel(self.centralwidget)
self.label_7.setGeometry(QtCore.QRect(180, 320, 60, 101))
self.label_7.setText("")
self.label_7.setPixmap(QtGui.QPixmap(default_list[6]))
self.label_7.setScaledContents(True)
self.label_7.setObjectName("label_7")
self.label_8 = QtWidgets.QLabel(self.centralwidget)
self.label_8.setGeometry(QtCore.QRect(520, 320, 60, 101))
self.label_8.setText("")
self.label_8.setPixmap(QtGui.QPixmap(default_list[7]))
self.label_8.setScaledContents(True)
self.label_8.setObjectName("label_8")
self.label_9 = QtWidgets.QLabel(self.centralwidget)
self.label_9.setGeometry(QtCore.QRect(690, 320, 60, 101))
self.label_9.setText("")
self.label_9.setPixmap(QtGui.QPixmap(default_list[8]))
self.label_9.setScaledContents(True)
self.label_9.setObjectName("label_9")
self.label_10 = QtWidgets.QLabel(self.centralwidget)
self.label_10.setGeometry(QtCore.QRect(350, 320, 60, 101))
self.label_10.setText("")
self.label_10.setPixmap(QtGui.QPixmap(default_list[9]))
self.label_10.setScaledContents(True)
self.label_10.setObjectName("label_10")
self.label_11 = QtWidgets.QLabel(self.centralwidget)
self.label_11.setGeometry(QtCore.QRect(10, 116, 130, 20))
font = QtGui.QFont()
font.setPointSize(6)
self.label_11.setFont(font)
self.label_11.setObjectName("label_11")
self.label_13 = QtWidgets.QLabel(self.centralwidget)
self.label_13.setGeometry(QtCore.QRect(350, 120, 140, 20))
font = QtGui.QFont()
font.setPointSize(6)
self.label_13.setFont(font)
self.label_13.setObjectName("label_13")
self.label_14 = QtWidgets.QLabel(self.centralwidget)
self.label_14.setGeometry(QtCore.QRect(520, 120, 130, 16))
font = QtGui.QFont()
font.setPointSize(6)
self.label_14.setFont(font)
self.label_14.setObjectName("label_14")
self.label_15 = QtWidgets.QLabel(self.centralwidget)
self.label_15.setGeometry(QtCore.QRect(690, 120, 170, 16))
font = QtGui.QFont()
font.setPointSize(6)
self.label_15.setFont(font)
self.label_15.setObjectName("label_15")
self.label_12 = QtWidgets.QLabel(self.centralwidget)
self.label_12.setGeometry(QtCore.QRect(180, 120, 130, 16))
font = QtGui.QFont()
font.setPointSize(6)
self.label_12.setFont(font)
self.label_12.setObjectName("label_12")
self.label_16 = QtWidgets.QLabel(self.centralwidget)
self.label_16.setGeometry(QtCore.QRect(180, 290, 130, 16))
font = QtGui.QFont()
font.setPointSize(6)
self.label_16.setFont(font)
self.label_16.setObjectName("label_16")
self.label_17 = QtWidgets.QLabel(self.centralwidget)
self.label_17.setGeometry(QtCore.QRect(350, 290, 140, 16))
font = QtGui.QFont()
font.setPointSize(6)
self.label_17.setFont(font)
self.label_17.setObjectName("label_17")
self.label_18 = QtWidgets.QLabel(self.centralwidget)
self.label_18.setGeometry(QtCore.QRect(520, 290, 130, 16))
font = QtGui.QFont()
font.setPointSize(6)
self.label_18.setFont(font)
self.label_18.setObjectName("label_18")
self.label_19 = QtWidgets.QLabel(self.centralwidget)
self.label_19.setGeometry(QtCore.QRect(10, 290, 130, 16))
font = QtGui.QFont()
font.setPointSize(6)
self.label_19.setFont(font)
self.label_19.setObjectName("label_19")
self.label_20 = QtWidgets.QLabel(self.centralwidget)
self.label_20.setGeometry(QtCore.QRect(690, 290, 170, 20))
font = QtGui.QFont()
font.setPointSize(6)
self.label_20.setFont(font)
self.label_20.setObjectName("label_20")
self.label_21 = QtWidgets.QLabel(self.centralwidget)
self.label_21.setGeometry(QtCore.QRect(250, 9, 341, 31))
font = QtGui.QFont()
font.setFamily("OCR A Extended")
font.setPointSize(12)
self.label_21.setFont(font)
self.label_21.setObjectName("label_21")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 774, 22))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.pushButton.clicked.connect(lambda: self.clicked_search_store())
# This is where the entire machine learning program runs: Between these two steps
# self.pushButton.clicked.connect(lambda: self.clicked_search_display())
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "Search"))
self.label_11.setText(_translate("MainWindow", default_list[0]))
self.label_13.setText(_translate("MainWindow", default_list[1]))
self.label_14.setText(_translate("MainWindow", default_list[2]))
self.label_15.setText(_translate("MainWindow", default_list[3]))
self.label_12.setText(_translate("MainWindow", default_list[4]))
self.label_16.setText(_translate("MainWindow", default_list[5]))
self.label_17.setText(_translate("MainWindow", default_list[6]))
self.label_18.setText(_translate("MainWindow", default_list[7]))
self.label_19.setText(_translate("MainWindow", default_list[8]))
self.label_20.setText(_translate("MainWindow", default_list[9]))
self.label_21.setText(_translate("MainWindow", " Movie Recommender"))
#stores the input value from the search bar to the variable search_string
def clicked_search_store(self):
search_string = self.lineEdit.text()
chosen_movie = search_string
recommendations_list.clear()
recommendations_list_pictures.clear()
make_recommendation(
model_knn=model_knn,
data=movie_user_mat_sparse,
fav_movie=chosen_movie,
movieidx=movie_to_idx,
n_recommendations=10)
self.clicked_search_display()
#displays the list of ten movies: list is named recommendations_list- if the length of recommendations_list is 10 or greater
def clicked_search_display(self):
if len(recommendations_list) != 0:
#setting the text of each movie if the list is not empty
self.label_11.setText(recommendations_list[0])
self.label_12.setText(recommendations_list[1])
self.label_13.setText(recommendations_list[2])
self.label_14.setText(recommendations_list[3])
self.label_15.setText(recommendations_list[4])
self.label_16.setText(recommendations_list[6])
self.label_17.setText(recommendations_list[7])
self.label_18.setText(recommendations_list[8])
self.label_19.setText(recommendations_list[5])
self.label_20.setText(recommendations_list[9])
#showing the posters if the list is not empty
self.label.setPixmap(QtGui.QPixmap(recommendations_list_pictures[0]))
self.label_2.setPixmap(QtGui.QPixmap(recommendations_list_pictures[1]))
self.label_3.setPixmap(QtGui.QPixmap(recommendations_list_pictures[2]))
self.label_4.setPixmap(QtGui.QPixmap(recommendations_list_pictures[3]))
self.label_5.setPixmap(QtGui.QPixmap(recommendations_list_pictures[4]))
self.label_6.setPixmap(QtGui.QPixmap(recommendations_list_pictures[5]))
self.label_7.setPixmap(QtGui.QPixmap(recommendations_list_pictures[6]))
self.label_8.setPixmap(QtGui.QPixmap(recommendations_list_pictures[8]))
self.label_9.setPixmap(QtGui.QPixmap(recommendations_list_pictures[9]))
self.label_10.setPixmap(QtGui.QPixmap(recommendations_list_pictures[7]))
elif len(recommendations_list) == 0:
#displaying 'no results found' if the list is empty
self.label_11.setText(default_list[0])
self.label_12.setText(default_list[1])
self.label_13.setText('No Results Found')
self.label_14.setText(default_list[3])
self.label_15.setText(default_list[4])
self.label_16.setText(default_list[5])
self.label_17.setText(default_list[6])
self.label_18.setText(default_list[7])
self.label_19.setText(default_list[8])
self.label_20.setText(default_list[9])
#showing no poster if the list is empty
self.label.setPixmap(QtGui.QPixmap(default_list[0]))
self.label_2.setPixmap(QtGui.QPixmap(default_list[1]))
self.label_3.setPixmap(QtGui.QPixmap(default_list[2]))
self.label_4.setPixmap(QtGui.QPixmap(default_list[3]))
self.label_5.setPixmap(QtGui.QPixmap(default_list[4]))
self.label_6.setPixmap(QtGui.QPixmap(default_list[5]))
self.label_7.setPixmap(QtGui.QPixmap(default_list[6]))
self.label_8.setPixmap(QtGui.QPixmap(default_list[7]))
self.label_9.setPixmap(QtGui.QPixmap(default_list[8]))
self.label_10.setPixmap(QtGui.QPixmap(default_list[9]))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
# making changes after i type this
# first set of changes successful, now next set
# next set