Spaces:
Running
Running
File size: 10,773 Bytes
ef71549 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 |
import gradio as gr
import pandas as pd
from typing import List, Dict, Union, Optional
class SmartSelectColumns(gr.SelectColumns):
"""
Enhanced SelectColumns component that supports substring matching and column mapping.
Inherits from gr.SelectColumns but adds additional filtering capabilities.
"""
def __init__(
self,
*args,
column_filters: Optional[Dict[str, List[str]]] = None,
column_mapping: Optional[Dict[str, str]] = None,
**kwargs
):
"""
Initialize the SmartSelectColumns component.
Args:
column_filters: Dict mapping filter names to lists of substrings to match
column_mapping: Dict mapping display names to actual column names
*args, **kwargs: Arguments passed to parent SelectColumns
"""
super().__init__(*args, **kwargs)
self.column_filters = column_filters or {}
self.column_mapping = column_mapping or {}
def preprocess(self, x: List[str]) -> List[str]:
"""Transform selected display names back to actual column names."""
if self.column_mapping:
reverse_mapping = {v: k for k, v in self.column_mapping.items()}
return [reverse_mapping.get(col, col) for col in x]
return x
def get_filtered_columns(self, df: pd.DataFrame) -> Dict[str, List[str]]:
"""
Get columns filtered by substring matches.
Args:
df: Input DataFrame
Returns:
Dict mapping filter names to lists of matching columns
"""
filtered_cols = {}
for filter_name, substrings in self.column_filters.items():
matching_cols = []
for col in df.columns:
if any(substr.lower() in col.lower() for substr in substrings):
matching_cols.append(col)
filtered_cols[filter_name] = matching_cols
return filtered_cols
def update(
self,
value: Union[pd.DataFrame, Dict[str, List[str]]],
interactive: Optional[bool] = None
) -> Dict:
"""
Update the component with new values.
Args:
value: Either a DataFrame or dict of predefined column groups
interactive: Whether the component should be interactive
Returns:
Dict containing the update configuration
"""
if isinstance(value, pd.DataFrame):
# Get filtered column groups
filtered_cols = self.get_filtered_columns(value)
# Create display names for columns if mapping exists
choices = list(value.columns)
if self.column_mapping:
choices = [self.column_mapping.get(col, col) for col in choices]
return {
"choices": choices,
"filtered_cols": filtered_cols,
"interactive": interactive if interactive is not None else self.interactive
}
return super().update(value, interactive)
# Example usage
if __name__ == "__main__":
df = pd.DataFrame({
"ioi_score_1": [1, 2, 3],
"ioi_score_2": [4, 5, 6],
"other_metric": [7, 8, 9],
"performance_1": [10, 11, 12]
})
# Define filters and mappings
column_filters = {
"IOI Metrics": ["ioi"],
"Performance Metrics": ["performance"]
}
column_mapping = {
"ioi_score_1": "IOI Score (Type 1)",
"ioi_score_2": "IOI Score (Type 2)",
"other_metric": "Other Metric",
"performance_1": "Performance Metric 1"
}
# Create interface
with gr.Blocks() as demo:
select_cols = SmartSelectColumns(
column_filters=column_filters,
column_mapping=column_mapping,
multiselect=True
)
# Update component with DataFrame
select_cols.update(df)
demo.launch()
import gradio as gr
import pandas as pd
from typing import List, Dict, Union, Optional, Any
from dataclasses import fields
class SmartSelectColumns(gr.SelectColumns):
"""
Enhanced SelectColumns component for Gradio Leaderboard with smart filtering and mapping capabilities.
"""
def __init__(
self,
column_filters: Optional[Dict[str, List[str]]] = None,
column_mapping: Optional[Dict[str, str]] = None,
initial_selected: Optional[List[str]] = None,
*args,
**kwargs
):
"""
Initialize SmartSelectColumns with enhanced functionality.
Args:
column_filters: Dict mapping filter names to lists of substrings to match
column_mapping: Dict mapping actual column names to display names
initial_selected: List of column names to be initially selected
*args, **kwargs: Additional arguments passed to parent SelectColumns
"""
super().__init__(*args, **kwargs)
self.column_filters = column_filters or {}
self.column_mapping = column_mapping or {}
self.reverse_mapping = {v: k for k, v in self.column_mapping.items()} if column_mapping else {}
self.initial_selected = initial_selected or []
def preprocess(self, x: List[str]) -> List[str]:
"""
Transform selected display names back to actual column names.
Args:
x: List of selected display names
Returns:
List of actual column names
"""
return [self.reverse_mapping.get(col, col) for col in x]
def postprocess(self, y: List[str]) -> List[str]:
"""
Transform actual column names to display names.
Args:
y: List of actual column names
Returns:
List of display names
"""
return [self.column_mapping.get(col, col) for col in y]
def get_filtered_columns(self, df: pd.DataFrame) -> Dict[str, List[str]]:
"""
Get columns filtered by substring matches.
Args:
df: Input DataFrame
Returns:
Dict mapping filter names to lists of matching display names
"""
filtered_cols = {}
for filter_name, substrings in self.column_filters.items():
matching_cols = []
for col in df.columns:
if any(substr.lower() in col.lower() for substr in substrings):
display_name = self.column_mapping.get(col, col)
matching_cols.append(display_name)
filtered_cols[filter_name] = matching_cols
return filtered_cols
def update(
self,
value: Union[pd.DataFrame, Dict[str, List[str]], Any],
interactive: Optional[bool] = None
) -> Dict:
"""
Update component with new values, supporting DataFrame fields.
Args:
value: DataFrame, dict of columns, or fields object
interactive: Whether component should be interactive
Returns:
Dict containing update configuration
"""
if isinstance(value, pd.DataFrame):
filtered_cols = self.get_filtered_columns(value)
choices = [self.column_mapping.get(col, col) for col in value.columns]
# Set initial selection if provided
value = self.initial_selected if self.initial_selected else choices
return {
"choices": choices,
"value": value,
"filtered_cols": filtered_cols,
"interactive": interactive if interactive is not None else self.interactive
}
# Handle fields object (e.g., from dataclass)
if hasattr(value, '__dataclass_fields__'):
field_names = [field.name for field in fields(value)]
choices = [self.column_mapping.get(name, name) for name in field_names]
return {
"choices": choices,
"value": self.initial_selected if self.initial_selected else choices,
"interactive": interactive if interactive is not None else self.interactive
}
return super().update(value, interactive)
def initialize_leaderboard(df: pd.DataFrame, column_class: Any,
filters: Dict[str, List[str]],
mappings: Dict[str, str],
initial_columns: Optional[List[str]] = None) -> gr.Leaderboard:
"""
Initialize a Gradio Leaderboard with SmartSelectColumns.
Args:
df: Input DataFrame
column_class: Class containing column definitions (e.g., AutoEvalColumn_mib_subgraph)
filters: Column filters for substring matching
mappings: Column name mappings (actual -> display)
initial_columns: List of columns to show initially
Returns:
Configured Leaderboard instance
"""
# Create renamed DataFrame with display names
renamed_df = df.rename(columns=mappings)
# Initialize SmartSelectColumns
smart_columns = SmartSelectColumns(
column_filters=filters,
column_mapping=mappings,
initial_selected=initial_columns,
multiselect=True
)
return gr.Leaderboard(
value=renamed_df,
datatype=[c.type for c in fields(column_class)],
select_columns=smart_columns,
search_columns=["Method"],
hide_columns=[],
interactive=False
)
# Example usage
if __name__ == "__main__":
# Sample data
df = pd.DataFrame({
"ioi_score_1": [1, 2, 3],
"ioi_score_2": [4, 5, 6],
"other_metric": [7, 8, 9],
"performance_1": [10, 11, 12],
"Method": ["A", "B", "C"]
})
# Define filters and mappings
filters = {
"IOI Metrics": ["ioi"],
"Performance Metrics": ["performance"]
}
mappings = {
"ioi_score_1": "IOI Score (Type 1)",
"ioi_score_2": "IOI Score (Type 2)",
"other_metric": "Other Metric",
"performance_1": "Performance Metric 1"
}
# Create demo interface
with gr.Blocks() as demo:
# Initialize leaderboard with smart columns
leaderboard = initialize_leaderboard(
df=df,
column_class=None, # Replace with your actual column class
filters=filters,
mappings=mappings,
initial_columns=["Method", "IOI Score (Type 1)"]
)
demo.launch() |