Spaces:
Runtime error
Runtime error
Added Chart Display
Browse files
app.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
import pandas as pd
|
| 2 |
import gradio as gr
|
|
|
|
| 3 |
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 4 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 5 |
from sklearn.preprocessing import MinMaxScaler
|
|
@@ -9,43 +10,35 @@ import difflib
|
|
| 9 |
data = pd.read_csv('steam.csv', quotechar='"', on_bad_lines='skip', nrows=10000)
|
| 10 |
data.fillna('', inplace=True)
|
| 11 |
|
| 12 |
-
# Combine
|
| 13 |
selected_features = ['genres', 'categories', 'tags']
|
| 14 |
for feature in selected_features:
|
| 15 |
if feature not in data.columns:
|
| 16 |
data[feature] = ''
|
| 17 |
-
|
| 18 |
data['combined_features'] = data['genres'] + ' ' + data['categories'] + ' ' + data['tags']
|
| 19 |
|
| 20 |
-
#
|
| 21 |
-
vectorizer = TfidfVectorizer(
|
| 22 |
-
stop_words='english',
|
| 23 |
-
ngram_range=(1, 2),
|
| 24 |
-
max_features=8000
|
| 25 |
-
)
|
| 26 |
feature_vectors = vectorizer.fit_transform(data['combined_features'])
|
| 27 |
|
| 28 |
-
# Normalize positive ratings
|
| 29 |
scaler = MinMaxScaler()
|
| 30 |
data['positive_ratings_scaled'] = scaler.fit_transform(data[['positive_ratings']])
|
| 31 |
|
| 32 |
-
#
|
| 33 |
game_similarity = cosine_similarity(feature_vectors)
|
| 34 |
-
|
| 35 |
-
# List of titles
|
| 36 |
list_of_all_titles = data['name'].tolist()
|
| 37 |
|
|
|
|
| 38 |
def recommend_games(user_game_name_input):
|
| 39 |
find_close_match = difflib.get_close_matches(user_game_name_input, list_of_all_titles, n=1)
|
| 40 |
if not find_close_match:
|
| 41 |
-
return "No close match found. Please try another game name."
|
| 42 |
-
|
| 43 |
closest_match = find_close_match[0]
|
| 44 |
index_of_the_game = data.loc[data['name'] == closest_match].index[0]
|
| 45 |
|
| 46 |
similarity_scores = list(enumerate(game_similarity[index_of_the_game]))
|
| 47 |
-
|
| 48 |
-
# Sort by similarity and positive ratings
|
| 49 |
sorted_similar_games = sorted(
|
| 50 |
similarity_scores,
|
| 51 |
key=lambda x: (x[1], data.iloc[x[0]]['positive_ratings_scaled']),
|
|
@@ -53,22 +46,24 @@ def recommend_games(user_game_name_input):
|
|
| 53 |
)
|
| 54 |
|
| 55 |
recommendations = []
|
| 56 |
-
|
|
|
|
| 57 |
if score < 0.3:
|
| 58 |
-
continue
|
| 59 |
game_name = data.iloc[index]['name']
|
| 60 |
recommendations.append(f"{i+1}. {game_name} (Similarity: {score:.2f})")
|
|
|
|
| 61 |
if len(recommendations) >= 10:
|
| 62 |
break
|
| 63 |
|
| 64 |
-
|
|
|
|
| 65 |
|
| 66 |
-
#
|
| 67 |
def evaluate_precision(user_game_name_input):
|
| 68 |
find_close_match = difflib.get_close_matches(user_game_name_input, list_of_all_titles, n=1)
|
| 69 |
if not find_close_match:
|
| 70 |
return 0.0
|
| 71 |
-
|
| 72 |
closest_match = find_close_match[0]
|
| 73 |
index_of_the_game = data.loc[data['name'] == closest_match].index[0]
|
| 74 |
similarity_scores = list(enumerate(game_similarity[index_of_the_game]))
|
|
@@ -77,25 +72,37 @@ def evaluate_precision(user_game_name_input):
|
|
| 77 |
key=lambda x: (x[1], data.iloc[x[0]]['positive_ratings_scaled']),
|
| 78 |
reverse=True
|
| 79 |
)
|
| 80 |
-
|
| 81 |
top_5 = [data.iloc[idx]['genres'] for idx, _ in sorted_similar_games[1:6]]
|
| 82 |
original_genre = data.iloc[index_of_the_game]['genres']
|
| 83 |
hits = sum(1 for genre in top_5 if genre == original_genre)
|
| 84 |
-
|
| 85 |
-
return round(precision_at_5, 2)
|
| 86 |
|
| 87 |
-
# Gradio
|
| 88 |
-
def
|
| 89 |
-
recommendations = recommend_games(user_input)
|
| 90 |
precision = evaluate_precision(user_input)
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
demo.launch()
|
|
|
|
| 1 |
import pandas as pd
|
| 2 |
import gradio as gr
|
| 3 |
+
import plotly.express as px
|
| 4 |
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 5 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 6 |
from sklearn.preprocessing import MinMaxScaler
|
|
|
|
| 10 |
data = pd.read_csv('steam.csv', quotechar='"', on_bad_lines='skip', nrows=10000)
|
| 11 |
data.fillna('', inplace=True)
|
| 12 |
|
| 13 |
+
# Combine features
|
| 14 |
selected_features = ['genres', 'categories', 'tags']
|
| 15 |
for feature in selected_features:
|
| 16 |
if feature not in data.columns:
|
| 17 |
data[feature] = ''
|
|
|
|
| 18 |
data['combined_features'] = data['genres'] + ' ' + data['categories'] + ' ' + data['tags']
|
| 19 |
|
| 20 |
+
# Vectorize
|
| 21 |
+
vectorizer = TfidfVectorizer(stop_words='english', ngram_range=(1, 2), max_features=8000)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
feature_vectors = vectorizer.fit_transform(data['combined_features'])
|
| 23 |
|
| 24 |
+
# Normalize positive ratings
|
| 25 |
scaler = MinMaxScaler()
|
| 26 |
data['positive_ratings_scaled'] = scaler.fit_transform(data[['positive_ratings']])
|
| 27 |
|
| 28 |
+
# Similarity matrix
|
| 29 |
game_similarity = cosine_similarity(feature_vectors)
|
|
|
|
|
|
|
| 30 |
list_of_all_titles = data['name'].tolist()
|
| 31 |
|
| 32 |
+
# Recommend function
|
| 33 |
def recommend_games(user_game_name_input):
|
| 34 |
find_close_match = difflib.get_close_matches(user_game_name_input, list_of_all_titles, n=1)
|
| 35 |
if not find_close_match:
|
| 36 |
+
return "No close match found. Please try another game name.", None
|
| 37 |
+
|
| 38 |
closest_match = find_close_match[0]
|
| 39 |
index_of_the_game = data.loc[data['name'] == closest_match].index[0]
|
| 40 |
|
| 41 |
similarity_scores = list(enumerate(game_similarity[index_of_the_game]))
|
|
|
|
|
|
|
| 42 |
sorted_similar_games = sorted(
|
| 43 |
similarity_scores,
|
| 44 |
key=lambda x: (x[1], data.iloc[x[0]]['positive_ratings_scaled']),
|
|
|
|
| 46 |
)
|
| 47 |
|
| 48 |
recommendations = []
|
| 49 |
+
chart_data = []
|
| 50 |
+
for i, (index, score) in enumerate(sorted_similar_games[1:21]):
|
| 51 |
if score < 0.3:
|
| 52 |
+
continue
|
| 53 |
game_name = data.iloc[index]['name']
|
| 54 |
recommendations.append(f"{i+1}. {game_name} (Similarity: {score:.2f})")
|
| 55 |
+
chart_data.append({'Game': game_name, 'Similarity': score})
|
| 56 |
if len(recommendations) >= 10:
|
| 57 |
break
|
| 58 |
|
| 59 |
+
chart_df = pd.DataFrame(chart_data)
|
| 60 |
+
return "\n".join(recommendations), chart_df
|
| 61 |
|
| 62 |
+
# Precision@5
|
| 63 |
def evaluate_precision(user_game_name_input):
|
| 64 |
find_close_match = difflib.get_close_matches(user_game_name_input, list_of_all_titles, n=1)
|
| 65 |
if not find_close_match:
|
| 66 |
return 0.0
|
|
|
|
| 67 |
closest_match = find_close_match[0]
|
| 68 |
index_of_the_game = data.loc[data['name'] == closest_match].index[0]
|
| 69 |
similarity_scores = list(enumerate(game_similarity[index_of_the_game]))
|
|
|
|
| 72 |
key=lambda x: (x[1], data.iloc[x[0]]['positive_ratings_scaled']),
|
| 73 |
reverse=True
|
| 74 |
)
|
|
|
|
| 75 |
top_5 = [data.iloc[idx]['genres'] for idx, _ in sorted_similar_games[1:6]]
|
| 76 |
original_genre = data.iloc[index_of_the_game]['genres']
|
| 77 |
hits = sum(1 for genre in top_5 if genre == original_genre)
|
| 78 |
+
return round(hits / 5, 2)
|
|
|
|
| 79 |
|
| 80 |
+
# Combined Gradio function
|
| 81 |
+
def recommend_and_visualize(user_input):
|
| 82 |
+
recommendations, chart_df = recommend_games(user_input)
|
| 83 |
precision = evaluate_precision(user_input)
|
| 84 |
+
chart = None
|
| 85 |
+
|
| 86 |
+
if chart_df is not None and not chart_df.empty:
|
| 87 |
+
chart = px.bar(chart_df, x="Game", y="Similarity", title="Top Game Recommendations",
|
| 88 |
+
labels={"Similarity": "Cosine Similarity Score"}, height=400)
|
| 89 |
+
|
| 90 |
+
return recommendations + f"\n\nPrecision@5 (approx): {precision}", chart
|
| 91 |
+
|
| 92 |
+
# Gradio UI
|
| 93 |
+
with gr.Blocks() as demo:
|
| 94 |
+
gr.Markdown("## 🎮 Steam Game Recommender")
|
| 95 |
+
gr.Markdown("Enter the name of a game you like and get recommendations based on similarity!")
|
| 96 |
+
|
| 97 |
+
with gr.Row():
|
| 98 |
+
input_box = gr.Textbox(label="Your Favorite Game", placeholder="e.g., Portal 2")
|
| 99 |
+
|
| 100 |
+
with gr.Row():
|
| 101 |
+
output_text = gr.Textbox(label="Recommendations", lines=12, interactive=False)
|
| 102 |
+
output_chart = gr.Plot(label="Recommendation Chart")
|
| 103 |
+
|
| 104 |
+
run_button = gr.Button("Recommend")
|
| 105 |
+
|
| 106 |
+
run_button.click(fn=recommend_and_visualize, inputs=input_box, outputs=[output_text, output_chart])
|
| 107 |
|
| 108 |
demo.launch()
|