Spaces:
Runtime error
Runtime error
Update app.py
Browse files31 unmodified lines32333435363738394041424344454647484950515253545556575859606162636423 unmodified lines888990919293944 unmodified lines9910010110210310436 unmodified lines1411421431441451461471 unmodified line1491501511521531541551561571581591601611621631641654 unmodified lines17017117217317417517617717817918018121 unmodified lines20320420520620720820921021121212 unmodified lines2252262272282292302312322332344 unmodified lines23924024124224324424524631 unmodified lineselse:data[feature] = data[feature].fillna(0) # Numeric columns# Combine featuresdata['combined_features'] = (data['genres'].astype(str) + ' ' +data['categories'].astype(str) + ' ' +data['steamspy_tags'].astype(str) + ' ' +data['platforms'].astype(str))# Vectorizetry:vectorizer = TfidfVectorizer(stop_words='english', ngram_range=(1, 2), max_features=5000)feature_vectors = vectorizer.fit_transform(data['combined_features'])print(f"Vectorization complete. Shape: {feature_vectors.shape}")except Exception as e:print(f"Vectorization error: {e}")feature_vectors = np.zeros((len(data), 1))# Normalize positive ratingsif 'positive_ratings' in data.columns and len(data) > 0:scaler = MinMaxScaler()data['positive_ratings_scaled'] = scaler.fit_transform(data[['positive_ratings']].clip(lower=0))else:data['positive_ratings_scaled'] = 0# Compute similarity matrixif feature_vectors.shape[0] > 1:try:if len(data) > 5000:23 unmodified linesgame_similarity = np.zeros((0, 0))list_of_all_titles = []# Platform detection function without emojisdef detect_platforms(platforms_str):platforms_str = str(platforms_str).lower()platforms = []4 unmodified linesplatforms.append("macOS")if 'linux' in platforms_str:platforms.append("Linux")return platforms if platforms else ["Unknown"]36 unmodified linesreturn fig# Function to get game recommendationsdef recommend_games(user_game_name_input):if not user_game_name_input or not list_of_all_titles:return "Please enter a game name and ensure the dataset is loaded.", [], None1 unmodified line# Normalize input for better matchinguser_input_cleaned = user_game_name_input.strip().lower()# First try exact matchexact_matches = [title for title in list_of_all_titles if title.lower() == user_input_cleaned]if exact_matches:closest_match = exact_matches[0]else:# Try fuzzy matching if no exact matchfind_close_match = difflib.get_close_matches(user_game_name_input, list_of_all_titles, n=1, cutoff=0.6)if not find_close_match:return f"No match found for '{user_game_name_input}'. Please try another game name.", [], Noneclosest_match = find_close_match[0]try:index_of_the_game = data.loc[data['name'] == closest_match].index[0]4 unmodified linessimilarity_scores = list(enumerate(game_similarity[index_of_the_game]))# Sort by similarity and then by ratings as a tiebreakersorted_similar_games = sorted(similarity_scores,key=lambda x: (x[1], data.iloc[x[0]]['positive_ratings_scaled']),reverse=True)recommendations = []game_list = []21 unmodified lines# Get prices for similar games (for gauge visualization)similar_games_prices = []# Process recommendationsfor i, (index, score) in enumerate(sorted_similar_games[1:6]): # Get top 5 recommendationsif score < 0.2: # Minimum threshold for qualitycontinuegame_name = data.iloc[index]['name']12 unmodified linesgenres_display = ", ".join([g for g in genres if g])# Calculate match percentagematch_percentage = int(score * 100)# Format recommendation with clean stylingposition = i + 1recommendation = (f"### {position}. {game_name}\n" +f"**Match:** {match_percentage}%\n" +4 unmodified linesrecommendations.append(recommendation)game_list.append(game_name)if len(recommendations) >= 7: # searched game + divider + 5 recommendationsbreak# Create price gauge visualization31 unmodified lines32333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878823 unmodified lines1121131141151161171184 unmodified lines12312412512612712812913036 unmodified lines1671681691701711721731 unmodified line1751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052064 unmodified lines21121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324421 unmodified lines26626726826927027127227327427527627727827928028128228328428528628728828929012 unmodified lines3033043053063073083093103113124 unmodified lines31731831932032132232332432531 unmodified lineselse:data[feature] = data[feature].fillna(0) # Numeric columns# Add derived features for better recommendationsif 'positive_ratings' in data.columns and 'negative_ratings' in data.columns:data['rating_ratio'] = data['positive_ratings'] / (data['positive_ratings'] + data['negative_ratings'] + 1)else:data['rating_ratio'] = 0.5 # Default neutral rating# Create a more comprehensive combined feature set with weighted componentsdata['combined_features'] = ''# Add name with higher weight for better keyword matchingif 'name' in data.columns:data['combined_features'] += data['name'].astype(str) + ' ' + data['name'].astype(str) + ' '# Add genres with higher weight (repeat to increase importance)if 'genres' in data.columns:data['combined_features'] += data['genres'].astype(str) + ' ' + data['genres'].astype(str) + ' '# Add other featuresfor feature in ['categories', 'steamspy_tags', 'platforms']:if feature in data.columns:data['combined_features'] += data[feature].astype(str) + ' '# Clean the combined featuresdata['combined_features'] = data['combined_features'].str.replace(';', ' ').str.lower()# Vectorize with improved parameterstry:# Use more n-grams and increased max_features for better semantic understandingvectorizer = TfidfVectorizer(stop_words='english',ngram_range=(1, 3), # Capture phrases up to 3 wordsmax_features=10000, # Increase features for more nuanced relationshipsmin_df=2, # Ignore very rare termsmax_df=0.9 # Ignore very common terms)feature_vectors = vectorizer.fit_transform(data['combined_features'])print(f"Vectorization complete. Shape: {feature_vectors.shape}")except Exception as e:print(f"Vectorization error: {e}")feature_vectors = np.zeros((len(data), 1))# Normalize ratings with sigmoid-like scaling for better differentiationif 'positive_ratings' in data.columns and len(data) > 0:# Log transform to handle skewed distribution of ratingsdata['log_ratings'] = np.log1p(data['positive_ratings'])scaler = MinMaxScaler()data['positive_ratings_scaled'] = scaler.fit_transform(data[['log_ratings']])else:data['positive_ratings_scaled'] = 0# Compute similarity matrix with optimizationsif feature_vectors.shape[0] > 1:try:if len(data) > 5000:23 unmodified linesgame_similarity = np.zeros((0, 0))list_of_all_titles = []# Improved platform detection functiondef detect_platforms(platforms_str):platforms_str = str(platforms_str).lower()platforms = []4 unmodified linesplatforms.append("macOS")if 'linux' in platforms_str:platforms.append("Linux")if any(mobile_term in platforms_str for mobile_term in ['android', 'ios', 'mobile']):platforms.append("Mobile")return platforms if platforms else ["Unknown"]36 unmodified linesreturn fig# Enhanced game recommendation functiondef recommend_games(user_game_name_input):if not user_game_name_input or not list_of_all_titles:return "Please enter a game name and ensure the dataset is loaded.", [], None1 unmodified line# Normalize input for better matchinguser_input_cleaned = user_game_name_input.strip().lower()# First try exact match (case insensitive)exact_matches = [title for title in list_of_all_titles if title.lower() == user_input_cleaned]if exact_matches:closest_match = exact_matches[0]else:# Try partial match before fuzzy matchingpartial_matches = [title for title in list_of_all_titles if user_input_cleaned in title.lower()]if partial_matches:# Sort by length to prefer shorter (more exact) matchesclosest_match = sorted(partial_matches, key=len)[0]else:# Try fuzzy matching with improved parametersfind_close_match = difflib.get_close_matches(user_game_name_input,list_of_all_titles,n=5, # Get more candidatescutoff=0.5 # Lower threshold for more possibilities)if not find_close_match:return f"No match found for '{user_game_name_input}'. Please try another game name.", [], None# Take the closest matchclosest_match = find_close_match[0]try:index_of_the_game = data.loc[data['name'] == closest_match].index[0]4 unmodified linessimilarity_scores = list(enumerate(game_similarity[index_of_the_game]))# Enhanced ranking with hybrid scoringgame_rankings = []for idx, sim_score in similarity_scores:if idx == index_of_the_game: # Skip the game itselfcontinue# Get additional factors for hybrid scoringrating_factor = data.iloc[idx]['positive_ratings_scaled']# Calculate genre similarity separatelysearched_game_genres = str(data.iloc[index_of_the_game].get('genres', '')).lower().split(';')current_game_genres = str(data.iloc[idx].get('genres', '')).lower().split(';')# Count matching genresmatching_genres = len(set(searched_game_genres) & set(current_game_genres))genre_factor = matching_genres / max(len(searched_game_genres), 1)# Create hybrid score with weightshybrid_score = (0.65 * sim_score + # Base similarity from TF-IDF vectors0.20 * rating_factor + # Rating popularity0.15 * genre_factor # Genre match)game_rankings.append((idx, hybrid_score))# Sort by the hybrid scoresorted_similar_games = sorted(game_rankings, key=lambda x: x[1], reverse=True)recommendations = []game_list = []21 unmodified lines# Get prices for similar games (for gauge visualization)similar_games_prices = []# Process recommendations with diversity enforcementseen_publishers = set()if 'publisher' in data.columns:searched_game_publisher = str(searched_game.get('publisher', '')).lower()seen_publishers.add(searched_game_publisher)recommended_count = 0# Process recommendationsfor i, (index, score) in enumerate(sorted_similar_games):if score < 0.15: # Minimum threshold for qualitycontinue# Enforce diversity by limiting games from same publisherif 'publisher' in data.columns:current_publisher = str(data.iloc[index].get('publisher', '')).lower()if current_publisher in seen_publishers and len(seen_publishers) > 2:continueseen_publishers.add(current_publisher)game_name = data.iloc[index]['name']12 unmodified linesgenres_display = ", ".join([g for g in genres if g])# Calculate match percentagematch_percentage = min(int(score * 100), 100) # Cap at 100%# Format recommendation with clean stylingposition = recommended_count + 1recommendation = (f"### {position}. {game_name}\n" +f"**Match:** {match_percentage}%\n" +4 unmodified linesrecommendations.append(recommendation)game_list.append(game_name)recommended_count += 1if recommended_count >= 5: # Stop after 5 recommendationsbreak# Create price gauge visualization
app.py+112-33