seyia92coding commited on
Commit
b1469d4
·
1 Parent(s): a44e249

Create app.py

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