Sammy03 commited on
Commit
118de34
·
1 Parent(s): 1177eab

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +146 -0
app.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import pandas as pd
3
+ import numpy as np
4
+ import re
5
+ import itertools
6
+ import matplotlib.pyplot as plt
7
+ from sklearn.feature_extraction.text import TfidfVectorizer
8
+ from sklearn.metrics.pairwise import linear_kernel
9
+ from fuzzywuzzy import fuzz
10
+ from sklearn.feature_extraction.text import TfidfVectorizer
11
+ import gradio as gr
12
+ #from datasets import load_dataset
13
+ #dataset = load_dataset('csv', data_files="steam-clean-games.csv", streaming=True)
14
+ #df = pd.DataFrame.from_dict(dataset)
15
+ df = pd.read_csv("steam-clean-games.csv", error_bad_lines=False, encoding='utf-8')
16
+ # the function to extract years
17
+ def extract_year(date):
18
+ year = date[:4]
19
+ if year.isnumeric():
20
+ return int(year)
21
+ else:
22
+ return np.nan
23
+ df['year'] = df['release_date'].apply(extract_year)
24
+ df['steamspy_tags'] = df['steamspy_tags'].str.replace(' ','-')
25
+ df['genres'] = df['steamspy_tags'].str.replace(';',' ')
26
+ counts = dict()
27
+ for i in df.index:
28
+ for g in df.loc[i,'genres'].split(' '):
29
+ if g not in counts:
30
+ counts[g] = 1
31
+ else:
32
+ counts[g] = counts[g] + 1
33
+ def create_score(row):
34
+ pos_count = row['positive_ratings']
35
+ neg_count = row['negative_ratings']
36
+ total_count = pos_count + neg_count
37
+ average = pos_count / total_count
38
+ return round(average, 2)
39
+ def total_ratings(row):
40
+ pos_count = row['positive_ratings']
41
+ neg_count = row['negative_ratings']
42
+ total_count = pos_count + neg_count
43
+ return total_count
44
+ df['total_ratings'] = df.apply(total_ratings, axis=1)
45
+ df['score'] = df.apply(create_score, axis=1)
46
+ # Calculate mean of vote average column
47
+ C = df['score'].mean()
48
+ m = df['total_ratings'].quantile(0.90)
49
+ # Function that computes the weighted rating of each game
50
+ def weighted_rating(x, m=m, C=C):
51
+ v = x['total_ratings']
52
+ R = x['score']
53
+ # Calculation based on the IMDB formula
54
+ return round((v/(v+m) * R) + (m/(m+v) * C), 2)
55
+ # Define a new feature 'score' and calculate its value with `weighted_rating()`
56
+ df['weighted_score'] = df.apply(weighted_rating, axis=1)
57
+ # create an object for TfidfVectorizer
58
+ tfidf_vector = TfidfVectorizer(stop_words='english')
59
+ tfidf_matrix = tfidf_vector.fit_transform(df['genres'])
60
+ # create the cosine similarity matrix
61
+ sim_matrix = linear_kernel(tfidf_matrix,tfidf_matrix)
62
+ # create a function to find the closest title
63
+ def matching_score(a,b):
64
+ #fuzz.ratio(a,b) calculates the Levenshtein Distance between a and b, and returns the score for the distance
65
+ return fuzz.ratio(a,b)
66
+ """# Make our Recommendation Engine
67
+ We need combine our formatted dataset with the similarity logic to return recommendations. This is also where we can fine-tune it if we do not like the results.
68
+ """
69
+ ##These functions needed to return different attributes of the recommended game titles
70
+ #Convert index to title_year
71
+ def get_title_year_from_index(index):
72
+ return df[df.index == index]['year'].values[0]
73
+ #Convert index to title
74
+ def get_title_from_index(index):
75
+ return df[df.index == index]['name'].values[0]
76
+ #Convert index to title
77
+ def get_index_from_title(title):
78
+ return df[df.name == title].index.values[0]
79
+ #Convert index to score
80
+ def get_score_from_index(index):
81
+ return df[df.index == index]['score'].values[0]
82
+ #Convert index to weighted score
83
+ def get_weighted_score_from_index(index):
84
+ return df[df.index == index]['weighted_score'].values[0]
85
+ #Convert index to total_ratings
86
+ def get_total_ratings_from_index(index):
87
+ return df[df.index == index]['total_ratings'].values[0]
88
+ #Convert index to platform
89
+ def get_platform_from_index(index):
90
+ return df[df.index == index]['platforms'].values[0]
91
+
92
+ # A function to return the most similar title to the words a user type
93
+ def find_closest_title(title):
94
+ #matching_score(a,b) > a is the current row, b is the title we're trying to match
95
+ leven_scores = list(enumerate(df['name'].apply(matching_score, b=title))) #[(0, 30), (1,95), (2, 19)~~] A tuple of distances per index
96
+ 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)~~]
97
+ closest_title = get_title_from_index(sorted_leven_scores[0][0])
98
+ distance_score = sorted_leven_scores[0][1]
99
+ return closest_title, distance_score
100
+ def gradio_contents_based_recommender_v2(game, how_many, sort_option, min_year, platform, min_score):
101
+ #Return closest game title match
102
+ closest_title, distance_score = find_closest_title(game)
103
+ #Create a Dataframe with these column headers
104
+ recomm_df = pd.DataFrame(columns=['Game Title', 'Year', 'Score', 'Weighted Score', 'Total Ratings'])
105
+ #find the corresponding index of the game title
106
+ games_index = get_index_from_title(closest_title)
107
+ #return a list of the most similar game indexes as a list
108
+ games_list = list(enumerate(sim_matrix[int(games_index)]))
109
+ #Sort list of similar games from top to bottom
110
+ similar_games = list(filter(lambda x:x[0] != int(games_index), sorted(games_list,key=lambda x:x[1], reverse=True)))
111
+ #Print the game title the similarity matrix is based on
112
+ print('Here\'s the list of games similar to '+'\033[1m'+str(closest_title)+'\033[0m'+'.\n')
113
+ #Only return the games that are on selected platform
114
+ n_games = []
115
+ for i,s in similar_games:
116
+ if platform in get_platform_from_index(i):
117
+ n_games.append((i,s))
118
+ #Only return the games that are above the minimum score
119
+ high_scores = []
120
+ for i,s in n_games:
121
+ if get_score_from_index(i) > min_score:
122
+ high_scores.append((i,s))
123
+
124
+ #Return the game tuple (game index, game distance score) and store in a dataframe
125
+ for i,s in n_games[:how_many]:
126
+ #Dataframe will contain attributes based on game index
127
+ row = {'Game Title': get_title_from_index(i), 'Year': get_title_year_from_index(i), 'Score': get_score_from_index(i),
128
+ 'Weighted Score': get_weighted_score_from_index(i),
129
+ 'Total Ratings': get_total_ratings_from_index(i),}
130
+ #Append each row to this dataframe
131
+ recomm_df = recomm_df.append(row, ignore_index = True)
132
+ #Sort dataframe by Sort_Option provided by user
133
+ recomm_df = recomm_df.sort_values(sort_option, ascending=False)
134
+ #Only include games released same or after minimum year selected
135
+ recomm_df = recomm_df[recomm_df['Year'] >= min_year]
136
+ return recomm_df
137
+ #Create list of unique calendar years based on main df column
138
+ years_sorted = sorted(list(df['year'].unique()))
139
+ #Interface will include these buttons based on parameters in the function with a dataframe output
140
+ recommender = gr.Interface(gradio_contents_based_recommender_v2, ["text", gr.inputs.Slider(1, 20, step=int(1)),
141
+ gr.inputs.Radio(['Year','Score','Weighted Score','Total Ratings']),
142
+ gr.inputs.Slider(int(years_sorted[0]), int(years_sorted[-1]), step=int(1)),
143
+ gr.inputs.Radio(['windows','linux','mac']),
144
+ gr.inputs.Slider(0, 10, step=0.1)],
145
+ "dataframe")
146
+ recommender.launch(debug=True)