import gradio as gr import os import pandas as pd import json from PIL import Image, ImageSequence import io from functools import reduce import numpy as np from datetime import datetime, timedelta import matplotlib.pyplot as plt from leaderboard_utils import ( get_organization, get_mario_planning_leaderboard, get_sokoban_leaderboard, get_2048_leaderboard, get_candy_leaderboard, get_tetris_leaderboard, get_tetris_planning_leaderboard, get_ace_attorney_leaderboard, get_combined_leaderboard, GAME_ORDER ) from data_visualization import ( get_combined_leaderboard_with_group_bar, create_organization_radar_chart, create_top_players_radar_chart, create_player_radar_chart, create_horizontal_bar_chart, normalize_values, get_combined_leaderboard_with_single_radar ) from gallery_tab import create_video_gallery HAS_ENHANCED_LEADERBOARD = True # Define time points and their corresponding data files TIME_POINTS = { "03/25/2025": "rank_data_03_25_2025.json", # Add more time points here as they become available } # Load the initial JSON file with rank data with open(TIME_POINTS["03/25/2025"], "r") as f: rank_data = json.load(f) # Add leaderboard state at the top level leaderboard_state = { "current_game": None, "previous_overall": { # "Super Mario Bros": True, # Commented out "Super Mario Bros (planning only)": True, "Sokoban": True, "2048": True, "Candy Crush": True, # "Tetris (complete)", # Commented out "Tetris (planning only)": True, "Ace Attorney": True }, "previous_details": { # "Super Mario Bros": False, # Commented out "Super Mario Bros (planning only)": False, "Sokoban": False, "2048": False, "Candy Crush": False, # "Tetris (complete)": False, # Commented out "Tetris (planning only)": False, "Ace Attorney": False } } # Load video links and news data with open('assets/game_video_link.json', 'r') as f: VIDEO_LINKS = json.load(f) with open('assets/news.json', 'r') as f: NEWS_DATA = json.load(f) def load_rank_data(time_point): """Load rank data for a specific time point""" if time_point in TIME_POINTS: try: with open(TIME_POINTS[time_point], "r") as f: return json.load(f) except FileNotFoundError: return None return None # Add a note about score values def add_score_note(): return gr.Markdown("*Note: 'n/a' in the table indicates no data point for that model.*", elem_classes="score-note") # Function to prepare DataFrame for display def prepare_dataframe_for_display(df, for_game=None): """Format DataFrame for better display in the UI""" # Clone the DataFrame to avoid modifying the original display_df = df.copy() # Filter out normalized score columns norm_columns = [col for col in display_df.columns if col.startswith('norm_')] if norm_columns: display_df = display_df.drop(columns=norm_columns) # Replace '_' with '-' for better display for col in display_df.columns: if col.endswith(' Score'): display_df[col] = display_df[col].apply(lambda x: '-' if x == '_' else x) # If we're in detailed view, sort by score if for_game: # Sort by relevant score column score_col = f"{for_game} Score" if score_col in display_df.columns: # Convert to numeric for sorting, treating '-' as NaN display_df[score_col] = pd.to_numeric(display_df[score_col], errors='coerce') # Sort by score in descending order display_df = display_df.sort_values(by=score_col, ascending=False) # Filter out models that didn't participate display_df = display_df[~display_df[score_col].isna()] else: # For overall view, sort by average of game scores (implicitly used for ranking) # but we won't add an explicit 'Rank' or 'Average Rank' column to the final display_df # Calculate an internal sorting key based on average scores, but don't add it to the display_df score_cols = [col for col in display_df.columns if col.endswith(' Score')] if score_cols: temp_sort_df = display_df.copy() for col in score_cols: temp_sort_df[col] = pd.to_numeric(temp_sort_df[col], errors='coerce') # Calculate average of the game scores (use mean of ranks from utils for actual ranking logic if different) # For display sorting, let's use a simple average of available scores. # The actual ranking for 'Average Rank' in leaderboard_utils uses mean of ranks, which is more robust. # Here we just need a consistent sort order. # Create a temporary column for sorting temp_sort_df['temp_avg_score_for_sort'] = temp_sort_df[score_cols].mean(axis=1) # Sort by this temporary average score (higher is better for scores) # and then by Player name as a tie-breaker display_df = display_df.loc[temp_sort_df.sort_values(by=['temp_avg_score_for_sort', 'Player'], ascending=[False, True]).index] # Add line breaks to column headers new_columns = {} for col in display_df.columns: if col.endswith(' Score'): # Replace 'Game Name Score' with 'Game Name\nScore' game_name = col.replace(' Score', '') new_col = f"{game_name}\nScore" new_columns[col] = new_col # Rename columns with new line breaks if new_columns: display_df = display_df.rename(columns=new_columns) return display_df # Helper function to ensure leaderboard updates maintain consistent height def update_df_with_height(df): """Update DataFrame with consistent height parameter.""" # Create column widths array col_widths = ["40px"] # Row number column width col_widths.append("230px") # Player column - reduced by 20px col_widths.append("120px") # Organization column # Add game score columns for _ in range(len(df.columns) - 2): col_widths.append("120px") return gr.update(value=df, show_row_numbers=True, show_fullscreen_button=True, line_breaks=True, show_search="search", # max_height=None, # Remove height limitation - COMMENTED OUT column_widths=col_widths) def update_leaderboard(# mario_overall, mario_details, # Commented out mario_plan_overall, mario_plan_details, # Added sokoban_overall, sokoban_details, _2048_overall, _2048_details, candy_overall, candy_details, # tetris_overall, tetris_details, # Commented out tetris_plan_overall, tetris_plan_details, ace_attorney_overall, ace_attorney_details): global leaderboard_state # Convert current checkbox states to dictionary for easier comparison current_overall = { # "Super Mario Bros": mario_overall, # Commented out "Super Mario Bros (planning only)": mario_plan_overall, "Sokoban": sokoban_overall, "2048": _2048_overall, "Candy Crush": candy_overall, # "Tetris (complete)": tetris_overall, # Commented out "Tetris (planning only)": tetris_plan_overall, "Ace Attorney": ace_attorney_overall } current_details = { # "Super Mario Bros": mario_details, # Commented out "Super Mario Bros (planning only)": mario_plan_details, "Sokoban": sokoban_details, "2048": _2048_details, "Candy Crush": candy_details, # "Tetris (complete)": tetris_details, # Commented out "Tetris (planning only)": tetris_plan_details, "Ace Attorney": ace_attorney_details } # Find which game's state changed changed_game = None for game in current_overall.keys(): if (current_overall[game] != leaderboard_state["previous_overall"][game] or current_details[game] != leaderboard_state["previous_details"][game]): changed_game = game break if changed_game: # If a game's details checkbox was checked if current_details[changed_game] and not leaderboard_state["previous_details"][changed_game]: # Reset all other games' states for game in current_overall.keys(): if game != changed_game: current_overall[game] = False current_details[game] = False leaderboard_state["previous_overall"][game] = False leaderboard_state["previous_details"][game] = False # Update state for the selected game leaderboard_state["current_game"] = changed_game leaderboard_state["previous_overall"][changed_game] = True leaderboard_state["previous_details"][changed_game] = True current_overall[changed_game] = True # If a game's overall checkbox was checked elif current_overall[changed_game] and not leaderboard_state["previous_overall"][changed_game]: # If we were in details view for another game, switch to overall view if leaderboard_state["current_game"] and leaderboard_state["previous_details"][leaderboard_state["current_game"]]: # Reset previous game's details leaderboard_state["previous_details"][leaderboard_state["current_game"]] = False current_details[leaderboard_state["current_game"]] = False leaderboard_state["current_game"] = None # Update state leaderboard_state["previous_overall"][changed_game] = True leaderboard_state["previous_details"][changed_game] = False # If a game's overall checkbox was unchecked elif not current_overall[changed_game] and leaderboard_state["previous_overall"][changed_game]: # If we're in details view, don't allow unchecking the overall checkbox if leaderboard_state["current_game"] == changed_game: current_overall[changed_game] = True else: leaderboard_state["previous_overall"][changed_game] = False if leaderboard_state["current_game"] == changed_game: leaderboard_state["current_game"] = None # If a game's details checkbox was unchecked elif not current_details[changed_game] and leaderboard_state["previous_details"][changed_game]: leaderboard_state["previous_details"][changed_game] = False if leaderboard_state["current_game"] == changed_game: leaderboard_state["current_game"] = None # When exiting details view, only reset the current game's state current_overall[changed_game] = True current_details[changed_game] = False leaderboard_state["previous_overall"][changed_game] = True leaderboard_state["previous_details"][changed_game] = False # Special case: If all games are selected and we're trying to view details all_games_selected = all(current_overall.values()) and not any(current_details.values()) if all_games_selected and changed_game and current_details[changed_game]: # Reset all other games' states for game in current_overall.keys(): if game != changed_game: current_overall[game] = False current_details[game] = False leaderboard_state["previous_overall"][game] = False leaderboard_state["previous_details"][game] = False # Update state for the selected game leaderboard_state["current_game"] = changed_game leaderboard_state["previous_overall"][changed_game] = True leaderboard_state["previous_details"][changed_game] = True current_overall[changed_game] = True # Build dictionary for selected games selected_games = { # "Super Mario Bros": current_overall["Super Mario Bros"], # Commented out "Super Mario Bros (planning only)": current_overall["Super Mario Bros (planning only)"], "Sokoban": current_overall["Sokoban"], "2048": current_overall["2048"], "Candy Crush": current_overall["Candy Crush"], # "Tetris (complete)": current_overall["Tetris (complete)"], # Commented out "Tetris (planning only)": current_overall["Tetris (planning only)"], "Ace Attorney": current_overall["Ace Attorney"] } # Get the appropriate DataFrame and charts based on current state if leaderboard_state["current_game"]: # For detailed view # if leaderboard_state["current_game"] == "Super Mario Bros": # Commented out # df = get_mario_leaderboard(rank_data) if leaderboard_state["current_game"] == "Super Mario Bros (planning only)": df = get_mario_planning_leaderboard(rank_data) elif leaderboard_state["current_game"] == "Sokoban": df = get_sokoban_leaderboard(rank_data) elif leaderboard_state["current_game"] == "2048": df = get_2048_leaderboard(rank_data) elif leaderboard_state["current_game"] == "Candy Crush": df = get_candy_leaderboard(rank_data) elif leaderboard_state["current_game"] == "Tetris (planning only)": df = get_tetris_planning_leaderboard(rank_data) elif leaderboard_state["current_game"] == "Ace Attorney": df = get_ace_attorney_leaderboard(rank_data) else: # Should not happen if current_game is one of the known games df = pd.DataFrame() # Empty df display_df = prepare_dataframe_for_display(df, leaderboard_state["current_game"]) chart = create_horizontal_bar_chart(df, leaderboard_state["current_game"]) radar_chart = chart # In detailed view, radar and group bar can be the same as the main chart group_bar_chart = chart else: # For overall view df, group_bar_chart = get_combined_leaderboard_with_group_bar(rank_data, selected_games) display_df = prepare_dataframe_for_display(df) _, radar_chart = get_combined_leaderboard_with_single_radar(rank_data, selected_games) chart = radar_chart # In overall view, the 'detailed' chart can be the radar chart # Return values, including all four plot placeholders return (update_df_with_height(display_df), chart, radar_chart, group_bar_chart, current_overall["Super Mario Bros (planning only)"], current_details["Super Mario Bros (planning only)"], current_overall["Sokoban"], current_details["Sokoban"], current_overall["2048"], current_details["2048"], current_overall["Candy Crush"], current_details["Candy Crush"], current_overall["Tetris (planning only)"], current_details["Tetris (planning only)"], current_overall["Ace Attorney"], current_details["Ace Attorney"]) def update_leaderboard_with_time(time_point, # mario_overall, mario_details, # Commented out mario_plan_overall, mario_plan_details, # Added sokoban_overall, sokoban_details, _2048_overall, _2048_details, candy_overall, candy_details, # tetris_overall, tetris_details, # Commented out tetris_plan_overall, tetris_plan_details, ace_attorney_overall, ace_attorney_details): # Load rank data for the selected time point global rank_data new_rank_data = load_rank_data(time_point) if new_rank_data is not None: rank_data = new_rank_data # Use the existing update_leaderboard function, including Super Mario (planning only) return update_leaderboard(# mario_overall, mario_details, # Commented out mario_plan_overall, mario_plan_details, # Added sokoban_overall, sokoban_details, _2048_overall, _2048_details, candy_overall, candy_details, # tetris_overall, tetris_details, # Commented out tetris_plan_overall, tetris_plan_details, ace_attorney_overall, ace_attorney_details) def get_initial_state(): """Get the initial state for the leaderboard""" return { "current_game": None, "previous_overall": { # "Super Mario Bros": True, # Commented out "Super Mario Bros (planning only)": True, "Sokoban": True, "2048": True, "Candy Crush": True, # "Tetris (complete)", # Commented out "Tetris (planning only)": True, "Ace Attorney": True }, "previous_details": { # "Super Mario Bros": False, # Commented out "Super Mario Bros (planning only)": False, "Sokoban": False, "2048": False, "Candy Crush": False, # "Tetris (complete)": False, # Commented out "Tetris (planning only)": False, "Ace Attorney": False } } def clear_filters(): global leaderboard_state selected_games = { "Super Mario Bros (planning only)": True, "Sokoban": True, "2048": True, "Candy Crush": True, "Tetris (planning only)": True, "Ace Attorney": True } df, group_bar_chart = get_combined_leaderboard_with_group_bar(rank_data, selected_games) display_df = prepare_dataframe_for_display(df) _, radar_chart = get_combined_leaderboard_with_single_radar(rank_data, selected_games) leaderboard_state = get_initial_state() # Return values, including all four plot placeholders return (update_df_with_height(display_df), radar_chart, radar_chart, group_bar_chart, True, False, # mario_plan True, False, # sokoban True, False, # 2048 True, False, # candy True, False, # tetris plan True, False) # ace attorney def create_timeline_slider(): """Create a custom timeline slider component""" timeline_html = """