seyia92coding commited on
Commit
1158955
1 Parent(s): 009aa51

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +178 -0
app.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """HS_Text_REC_Games_Gradio_Blocks.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/19yJ8RC70IDljwSmPlqtOzWz192gwLAHF
8
+ """
9
+
10
+ import pandas as pd
11
+ import numpy as np
12
+ from fuzzywuzzy import fuzz
13
+ from sklearn.feature_extraction.text import TfidfVectorizer
14
+ from sklearn.metrics.pairwise import cosine_similarity
15
+ import gradio as gr
16
+
17
+ df = pd.read_csv("Metacritic_Reviews_Only.csv", error_bad_lines=False, encoding='utf-8')
18
+
19
+ #Remove title from review
20
+ def remove_title(row):
21
+ game_title = row['Game Title']
22
+ body_text = row['Reviews']
23
+ new_doc = body_text.replace(game_title, "")
24
+ return new_doc
25
+
26
+ df['Reviews'] = df.apply(remove_title, axis=1)
27
+ #drop redundant column
28
+ df = df.drop(['Unnamed: 0'], axis=1)
29
+
30
+ df.dropna(inplace=True) #Drop Null Reviews
31
+
32
+ # Instantiate the vectorizer object to the vectorizer variable
33
+ #Minimum word count 2 to be included, words that appear in over 70% of docs should not be included
34
+ vectorizer = TfidfVectorizer(min_df=2, max_df=0.7)
35
+
36
+ # Fit and transform the plot column
37
+ vectorized_data = vectorizer.fit_transform(df['Reviews'])
38
+
39
+ # Create Dataframe from TF-IDFarray
40
+ tfidf_df = pd.DataFrame(vectorized_data.toarray(), columns=vectorizer.get_feature_names())
41
+
42
+ # Assign the game titles to the index
43
+ tfidf_df.index = df['Game Title']
44
+
45
+ # Find the cosine similarity measures between all game and assign the results to cosine_similarity_array.
46
+ cosine_similarity_array = cosine_similarity(tfidf_df)
47
+
48
+ # Create a DataFrame from the cosine_similarity_array with tfidf_df.index as its rows and columns.
49
+ cosine_similarity_df = pd.DataFrame(cosine_similarity_array, index=tfidf_df.index, columns=tfidf_df.index)
50
+
51
+ # Find the values for the game Batman: Arkham City
52
+ cosine_similarity_series = cosine_similarity_df.loc['Batman: Arkham City']
53
+
54
+ # Sort these values highest to lowest
55
+ ordered_similarities = cosine_similarity_series.sort_values(ascending=False)
56
+
57
+ # Print the results
58
+ print(ordered_similarities)
59
+
60
+ # create a function to find the closest title
61
+ def matching_score(a,b):
62
+ #fuzz.ratio(a,b) calculates the Levenshtein Distance between a and b, and returns the score for the distance
63
+ return fuzz.ratio(a,b)
64
+ # exactly the same, the score becomes 100
65
+
66
+ #Convert index to title_year
67
+ def get_title_from_index(index):
68
+ return df[df.index == index]['Game Title'].values[0]
69
+
70
+ # A function to return the most similar title to the words a user type
71
+ # Without this, the recommender only works when a user enters the exact title which the data has.
72
+ def find_closest_title(title):
73
+ #matching_score(a,b) > a is the current row, b is the title we're trying to match
74
+ leven_scores = list(enumerate(df['Game Title'].apply(matching_score, b=title))) #[(0, 30), (1,95), (2, 19)~~] A tuple of distances per index
75
+ sorted_leven_scores = sorted(leven_scores, key=lambda x: x[1], reverse=True) #Sorts list of tuples by distance [(1, 95), (3, 49), (0, 30)~~]
76
+ closest_title = get_title_from_index(sorted_leven_scores[0][0])
77
+ distance_score = sorted_leven_scores[0][1]
78
+ return closest_title, distance_score
79
+ # Bejeweled Twist, 100
80
+
81
+ def find_closest_titles(title):
82
+ leven_scores = list(enumerate(df['Game Title'].apply(matching_score, b=title))) #[(0, 30), (1,95), (2, 19)~~] A tuple of distances per index
83
+ sorted_leven_scores = sorted(leven_scores, key=lambda x: x[1], reverse=True) #Sorts list of tuples by distance [(1, 95), (3, 49), (0, 30)~~]
84
+ closest_titles = [get_title_from_index(sorted_leven_scores[i][0]) for i in range(5)]
85
+ distance_scores = [sorted_leven_scores[i][1] for i in range(5)]
86
+ return closest_titles, distance_scores
87
+ # Bejeweled Twist, 100
88
+
89
+ def recommend_games_v1(game1, game2, game3, max_results):
90
+ #Counter for Ranking
91
+ number = 1
92
+ print('Recommended because you played {}, {} and {}:\n'.format(game1, game2, game3))
93
+
94
+ list_of_games_enjoyed = [game1, game2, game3]
95
+ games_enjoyed_df = tfidf_df.reindex(list_of_games_enjoyed)
96
+ user_prof = games_enjoyed_df.mean()
97
+
98
+ tfidf_subset_df = tfidf_df.drop([game1, game2, game3], axis=0)
99
+ similarity_array = cosine_similarity(user_prof.values.reshape(1, -1), tfidf_subset_df)
100
+ similarity_df = pd.DataFrame(similarity_array.T, index=tfidf_subset_df.index, columns=["similarity_score"])
101
+
102
+ # Sort the values from high to low by the values in the similarity_score
103
+ sorted_similarity_df = similarity_df.sort_values(by="similarity_score", ascending=False)
104
+
105
+ number = 0
106
+ rank = 1
107
+ rank_range = []
108
+ name_list = []
109
+ score_list = []
110
+ for n in sorted_similarity_df.index:
111
+ if rank <= max_results:
112
+ rank_range.append(rank)
113
+ name_list.append(n)
114
+ score_list.append(str(round(sorted_similarity_df.iloc[number]['similarity_score']*100,2)) + "% ") #format score as a percentage
115
+ number+=1
116
+ rank +=1
117
+ #Turn lists into a dictionary
118
+ data = {'Rank': rank_range, 'Game Title': name_list, '% Match': score_list}
119
+ rec_table = pd.DataFrame.from_dict(data) #Convert dictionary into dataframe
120
+ rec_table.set_index('Rank', inplace=True) #Make Rank column the index
121
+ return rec_table
122
+
123
+ demo = gr.Blocks()
124
+
125
+ with demo:
126
+ gr.Markdown(
127
+ """
128
+ # Game Recommendations
129
+ Input 3 games you enjoyed playing and use the dropdown to confirm your selections. Hopefully they are registered in the database. Once all 3 have been chosen, please generate your recommendations.
130
+ """
131
+ )
132
+
133
+ options = ['Dragonball', 'Batman', 'Tekken']
134
+ def Dropdown_list(x):
135
+ new_options = [*options, x + " Remastered", x + ": The Remake", x + ": Game of the Year Edition", x + " Steelbook Edition"]
136
+ return gr.Dropdown.update(choices=new_options)
137
+
138
+ with gr.Column(visible=True):
139
+ first_entry = gr.Textbox(label="Game Title 1")
140
+ first_dropdown = gr.Dropdown(choices=[], label="Closest Matches")
141
+ update_first = gr.Button("Match Closest Title 1")
142
+
143
+ with gr.Column(visible=True):
144
+ second_entry = gr.Textbox(label="Game Title 2")
145
+ second_dropdown = gr.Dropdown(label="Closest Matches")
146
+ update_second = gr.Button("Match Closest Title 2")
147
+
148
+ with gr.Column(visible=True):
149
+ third_entry = gr.Textbox(label="Game Title 3")
150
+ third_dropdown = gr.Dropdown(label="Closest Matches")
151
+ update_third = gr.Button("Match Closest Title 3")
152
+
153
+ with gr.Row():
154
+ slider = gr.Slider(1, 20, step=1)
155
+
156
+ with gr.Row():
157
+ generate = gr.Button("Generate")
158
+ results = gr.Dataframe(label="Top Results")
159
+
160
+ def filter_matches(entry):
161
+ top_matches = find_closest_titles(entry)
162
+ top_matches = list(top_matches[0])
163
+ return gr.Dropdown.update(choices=top_matches) #, gr.update(visible=True)
164
+
165
+ def new_match(text):
166
+ top_match = find_closest_title(text)
167
+ return text
168
+
169
+ first_entry.change(new_match, inputs=first_entry, outputs=first_dropdown)
170
+ update_first.click(filter_matches, inputs=first_dropdown, outputs=first_dropdown)
171
+ second_entry.change(new_match, inputs=second_entry, outputs=second_dropdown)
172
+ update_second.click(filter_matches, inputs=second_dropdown, outputs=second_dropdown)
173
+ third_entry.change(new_match, inputs=third_entry, outputs=third_dropdown)
174
+ update_third.click(filter_matches, inputs=third_dropdown, outputs=third_dropdown)
175
+
176
+
177
+ generate.click(recommend_games_v1, inputs=[first_dropdown, second_dropdown, third_dropdown, slider], outputs=results)
178
+ demo.launch()