Spaces:
Runtime error
Runtime error
| import pandas as pd | |
| import gradio as gr | |
| import plotly.express as px | |
| from sklearn.feature_extraction.text import TfidfVectorizer | |
| from sklearn.metrics.pairwise import cosine_similarity | |
| from sklearn.preprocessing import MinMaxScaler | |
| import difflib | |
| # Load dataset | |
| data = pd.read_csv('steam.csv', quotechar='"', on_bad_lines='skip', nrows=10000) | |
| data.fillna('', inplace=True) | |
| # Combine features | |
| selected_features = ['genres', 'categories', 'tags'] | |
| for feature in selected_features: | |
| if feature not in data.columns: | |
| data[feature] = '' | |
| data['combined_features'] = data['genres'] + ' ' + data['categories'] + ' ' + data['tags'] | |
| # Vectorize | |
| vectorizer = TfidfVectorizer(stop_words='english', ngram_range=(1, 2), max_features=8000) | |
| feature_vectors = vectorizer.fit_transform(data['combined_features']) | |
| # Normalize positive ratings | |
| scaler = MinMaxScaler() | |
| data['positive_ratings_scaled'] = scaler.fit_transform(data[['positive_ratings']]) | |
| # Similarity matrix | |
| game_similarity = cosine_similarity(feature_vectors) | |
| list_of_all_titles = data['name'].tolist() | |
| # Recommend function | |
| def recommend_games(user_game_name_input): | |
| find_close_match = difflib.get_close_matches(user_game_name_input, list_of_all_titles, n=1) | |
| if not find_close_match: | |
| return "No close match found. Please try another game name.", None | |
| closest_match = find_close_match[0] | |
| index_of_the_game = data.loc[data['name'] == closest_match].index[0] | |
| similarity_scores = list(enumerate(game_similarity[index_of_the_game])) | |
| sorted_similar_games = sorted( | |
| similarity_scores, | |
| key=lambda x: (x[1], data.iloc[x[0]]['positive_ratings_scaled']), | |
| reverse=True | |
| ) | |
| recommendations = [] | |
| chart_data = [] | |
| for i, (index, score) in enumerate(sorted_similar_games[1:21]): | |
| if score < 0.3: | |
| continue | |
| game_name = data.iloc[index]['name'] | |
| recommendations.append(f"{i+1}. {game_name} (Similarity: {score:.2f})") | |
| chart_data.append({'Game': game_name, 'Similarity': score}) | |
| if len(recommendations) >= 10: | |
| break | |
| chart_df = pd.DataFrame(chart_data) | |
| return "\n".join(recommendations), chart_df | |
| # Precision@5 | |
| def evaluate_precision(user_game_name_input): | |
| find_close_match = difflib.get_close_matches(user_game_name_input, list_of_all_titles, n=1) | |
| if not find_close_match: | |
| return 0.0 | |
| closest_match = find_close_match[0] | |
| index_of_the_game = data.loc[data['name'] == closest_match].index[0] | |
| similarity_scores = list(enumerate(game_similarity[index_of_the_game])) | |
| sorted_similar_games = sorted( | |
| similarity_scores, | |
| key=lambda x: (x[1], data.iloc[x[0]]['positive_ratings_scaled']), | |
| reverse=True | |
| ) | |
| top_5 = [data.iloc[idx]['genres'] for idx, _ in sorted_similar_games[1:6]] | |
| original_genre = data.iloc[index_of_the_game]['genres'] | |
| hits = sum(1 for genre in top_5 if genre == original_genre) | |
| return round(hits / 5, 2) | |
| # Combined Gradio function | |
| def recommend_and_visualize(user_input): | |
| recommendations, chart_df = recommend_games(user_input) | |
| precision = evaluate_precision(user_input) | |
| chart = None | |
| if chart_df is not None and not chart_df.empty: | |
| chart = px.bar(chart_df, x="Game", y="Similarity", title="Top Game Recommendations", | |
| labels={"Similarity": "Cosine Similarity Score"}, height=400) | |
| return recommendations + f"\n\nPrecision@5 (approx): {precision}", chart | |
| # Gradio UI | |
| with gr.Blocks() as demo: | |
| gr.Markdown("## 🎮 Steam Game Recommender") | |
| gr.Markdown("Enter the name of a game you like and get recommendations based on similarity!") | |
| with gr.Row(): | |
| input_box = gr.Textbox(label="Your Favorite Game", placeholder="e.g., Portal 2") | |
| with gr.Row(): | |
| output_text = gr.Textbox(label="Recommendations", lines=12, interactive=False) | |
| output_chart = gr.Plot(label="Recommendation Chart") | |
| run_button = gr.Button("Recommend") | |
| run_button.click(fn=recommend_and_visualize, inputs=input_box, outputs=[output_text, output_chart]) | |
| demo.launch() | |