File size: 12,872 Bytes
7fcd557 d24563e 6bcbc7b d24563e 24a059f e109361 24a059f d24563e 24a059f e109361 d24563e 7fcd557 c308901 d24563e e109361 fb73da9 e109361 fb73da9 e109361 6bcbc7b e109361 6bcbc7b e109361 6bcbc7b e109361 24a059f 9f7748a e109361 9f7748a e109361 9f7748a e109361 9f7748a e109361 9f7748a e109361 9f7748a 1fe4357 8f89713 1fe4357 8f89713 d24563e 8f89713 104bf5a 8f89713 d24563e 8f89713 6bcbc7b 8f89713 6bcbc7b 8f89713 1fe4357 8f89713 1fe4357 8f89713 e109361 6bcbc7b 7fcd557 e109361 d24563e 7fcd557 8f89713 7fcd557 1fe4357 7fcd557 104bf5a ca6bd07 8f89713 ca6bd07 8f89713 7fcd557 1fe4357 104bf5a 7fcd557 d24563e 8f89713 7fcd557 8f89713 7fcd557 d24563e |
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 |
# # demo.launch()
# import gradio as gr
# import pandas as pd
# import os
# import re
# from datetime import datetime
# LEADERBOARD_FILE = "leaderboard.csv" # File to store all submissions persistently
# LAST_UPDATED = datetime.now().strftime("%B %d, %Y")
# def initialize_leaderboard_file():
# """
# Ensure the leaderboard file exists and has the correct headers.
# """
# if not os.path.exists(LEADERBOARD_FILE):
# # Create the file with headers
# pd.DataFrame(columns=[
# "Model Name", "Overall Accuracy", "Valid Accuracy",
# "Correct Predictions", "Total Questions", "Timestamp"
# ]).to_csv(LEADERBOARD_FILE, index=False)
# else:
# # Check if the file is empty and write headers if needed
# if os.stat(LEADERBOARD_FILE).st_size == 0:
# pd.DataFrame(columns=[
# "Model Name", "Overall Accuracy", "Valid Accuracy",
# "Correct Predictions", "Total Questions", "Timestamp"
# ]).to_csv(LEADERBOARD_FILE, index=False)
# def clean_answer(answer):
# """
# Clean and normalize the predicted answers.
# """
# if pd.isna(answer):
# return None
# answer = str(answer)
# clean = re.sub(r'[^A-Da-d]', '', answer)
# if clean:
# return clean[0].upper()
# return None
# def update_leaderboard(results):
# """
# Append new submission results to the leaderboard file.
# """
# new_entry = {
# "Model Name": results['model_name'],
# "Overall Accuracy": round(results['overall_accuracy'] * 100, 2),
# "Valid Accuracy": round(results['valid_accuracy'] * 100, 2),
# "Correct Predictions": results['correct_predictions'],
# "Total Questions": results['total_questions'],
# "Timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
# }
# new_entry_df = pd.DataFrame([new_entry])
# new_entry_df.to_csv(LEADERBOARD_FILE, mode='a', index=False, header=False)
# def load_leaderboard():
# """
# Load all submissions from the leaderboard file.
# """
# if not os.path.exists(LEADERBOARD_FILE) or os.stat(LEADERBOARD_FILE).st_size == 0:
# return pd.DataFrame({
# "Model Name": [],
# "Overall Accuracy": [],
# "Valid Accuracy": [],
# "Correct Predictions": [],
# "Total Questions": [],
# "Timestamp": [],
# })
# return pd.read_csv(LEADERBOARD_FILE)
# def evaluate_predictions(prediction_file, model_name, add_to_leaderboard):
# """
# Evaluate predictions and optionally add results to the leaderboard.
# """
# ground_truth_file = "ground_truth.csv"
# if not os.path.exists(ground_truth_file):
# return "Ground truth file not found.", load_leaderboard()
# if not prediction_file:
# return "Prediction file not uploaded.", load_leaderboard()
# try:
# # Load predictions and ground truth
# predictions_df = pd.read_csv(prediction_file.name)
# ground_truth_df = pd.read_csv(ground_truth_file)
# # Merge predictions with ground truth
# merged_df = pd.merge(predictions_df, ground_truth_df, on='question_id', how='inner')
# merged_df['pred_answer'] = merged_df['predicted_answer'].apply(clean_answer)
# # Evaluate predictions
# valid_predictions = merged_df.dropna(subset=['pred_answer'])
# correct_predictions = (valid_predictions['pred_answer'] == valid_predictions['Answer']).sum()
# total_predictions = len(merged_df)
# total_valid_predictions = len(valid_predictions)
# # Calculate accuracy
# overall_accuracy = correct_predictions / total_predictions if total_predictions > 0 else 0
# valid_accuracy = correct_predictions / total_valid_predictions if total_valid_predictions > 0 else 0
# results = {
# 'model_name': model_name if model_name else "Unknown Model",
# 'overall_accuracy': overall_accuracy,
# 'valid_accuracy': valid_accuracy,
# 'correct_predictions': correct_predictions,
# 'total_questions': total_predictions,
# }
# # Update leaderboard only if opted in
# if add_to_leaderboard:
# update_leaderboard(results)
# return "Evaluation completed and added to leaderboard.", load_leaderboard()
# else:
# return "Evaluation completed but not added to leaderboard.", load_leaderboard()
# except Exception as e:
# return f"Error during evaluation: {str(e)}", load_leaderboard()
# # Initialize leaderboard file
# initialize_leaderboard_file()
# # Gradio Interface
# with gr.Blocks() as demo:
# gr.Markdown("# Prediction Evaluation Tool with Leaderboard")
# with gr.Tabs():
# # Submission Tab
# with gr.TabItem("π
Submission"):
# file_input = gr.File(label="Upload Prediction CSV")
# model_name_input = gr.Textbox(label="Model Name", placeholder="Enter your model name")
# add_to_leaderboard_checkbox = gr.Checkbox(label="Add to Leaderboard?", value=True)
# eval_status = gr.Textbox(label="Evaluation Status", interactive=False)
# leaderboard_table_preview = gr.Dataframe(
# value=load_leaderboard(),
# label="Leaderboard (Preview)",
# interactive=False,
# wrap=True,
# )
# eval_button = gr.Button("Evaluate and Update Leaderboard")
# eval_button.click(
# evaluate_predictions,
# inputs=[file_input, model_name_input, add_to_leaderboard_checkbox],
# outputs=[eval_status, leaderboard_table_preview],
# )
# # Leaderboard Tab
# with gr.TabItem("π
Leaderboard"):
# leaderboard_table = gr.Dataframe(
# value=load_leaderboard(),
# label="Leaderboard",
# interactive=False,
# wrap=True,
# )
# refresh_button = gr.Button("Refresh Leaderboard")
# refresh_button.click(
# lambda: load_leaderboard(),
# inputs=[],
# outputs=[leaderboard_table],
# )
# gr.Markdown(f"Last updated on **{LAST_UPDATED}**")
# demo.launch()
import gradio as gr
import pandas as pd
import os
import re
from datetime import datetime
from huggingface_hub import hf_hub_download
LEADERBOARD_FILE = "leaderboard.csv" # File to store all submissions persistently
GROUND_TRUTH_FILE = "ground_truth.csv" # File for ground truth data
LAST_UPDATED = datetime.now().strftime("%B %d, %Y")
# Disable symlink warnings
os.environ["HF_HUB_DISABLE_SYMLINKS_WARNING"] = "1"
def initialize_leaderboard_file():
"""
Ensure the leaderboard file exists and has the correct headers.
"""
if not os.path.exists(LEADERBOARD_FILE):
# Create the file with headers
pd.DataFrame(columns=[
"Model Name", "Overall Accuracy", "Valid Accuracy",
"Correct Predictions", "Total Questions", "Timestamp"
]).to_csv(LEADERBOARD_FILE, index=False)
else:
# Check if the file is empty and write headers if needed
if os.stat(LEADERBOARD_FILE).st_size == 0:
pd.DataFrame(columns=[
"Model Name", "Overall Accuracy", "Valid Accuracy",
"Correct Predictions", "Total Questions", "Timestamp"
]).to_csv(LEADERBOARD_FILE, index=False)
def clean_answer(answer):
"""
Clean and normalize the predicted answers.
"""
if pd.isna(answer):
return None
answer = str(answer)
clean = re.sub(r'[^A-Da-d]', '', answer)
if clean:
return clean[0].upper()
return None
def update_leaderboard(results):
"""
Append new submission results to the leaderboard file.
"""
new_entry = {
"Model Name": results['model_name'],
"Overall Accuracy": round(results['overall_accuracy'] * 100, 2),
"Valid Accuracy": round(results['valid_accuracy'] * 100, 2),
"Correct Predictions": results['correct_predictions'],
"Total Questions": results['total_questions'],
"Timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
}
new_entry_df = pd.DataFrame([new_entry])
new_entry_df.to_csv(LEADERBOARD_FILE, mode='a', index=False, header=False)
def load_leaderboard():
"""
Load all submissions from the leaderboard file.
"""
if not os.path.exists(LEADERBOARD_FILE) or os.stat(LEADERBOARD_FILE).st_size == 0:
return pd.DataFrame({
"Model Name": [],
"Overall Accuracy": [],
"Valid Accuracy": [],
"Correct Predictions": [],
"Total Questions": [],
"Timestamp": [],
})
return pd.read_csv(LEADERBOARD_FILE)
def evaluate_predictions(prediction_file, model_name, add_to_leaderboard):
"""
Evaluate predictions and optionally add results to the leaderboard.
"""
try:
# Load ground truth data
ground_truth_path = hf_hub_download(
repo_id="SondosMB/ground-truth-dataset",
filename=GROUND_TRUTH_FILE,
use_auth_token=True
)
ground_truth_df = pd.read_csv(ground_truth_path)
except Exception as e:
return f"Error loading ground truth: {e}", load_leaderboard()
if not prediction_file:
return "Prediction file not uploaded.", load_leaderboard()
try:
# Load predictions and merge with ground truth
predictions_df = pd.read_csv(prediction_file.name)
merged_df = pd.merge(predictions_df, ground_truth_df, on='question_id', how='inner')
merged_df['pred_answer'] = merged_df['predicted_answer'].apply(clean_answer)
# Evaluate predictions
valid_predictions = merged_df.dropna(subset=['pred_answer'])
correct_predictions = (valid_predictions['pred_answer'] == valid_predictions['Answer']).sum()
total_predictions = len(merged_df)
total_valid_predictions = len(valid_predictions)
# Calculate accuracy
overall_accuracy = correct_predictions / total_predictions if total_predictions > 0 else 0
valid_accuracy = correct_predictions / total_valid_predictions if total_valid_predictions > 0 else 0
results = {
'model_name': model_name if model_name else "Unknown Model",
'overall_accuracy': overall_accuracy,
'valid_accuracy': valid_accuracy,
'correct_predictions': correct_predictions,
'total_questions': total_predictions,
}
# Update leaderboard only if opted in
if add_to_leaderboard:
update_leaderboard(results)
return "Evaluation completed and added to leaderboard.", load_leaderboard()
else:
return "Evaluation completed but not added to leaderboard.", load_leaderboard()
except Exception as e:
return f"Error during evaluation: {str(e)}", load_leaderboard()
# Initialize leaderboard file
initialize_leaderboard_file()
# Gradio Interface
with gr.Blocks() as demo:
gr.Markdown("# Prediction Evaluation Tool with Leaderboard")
with gr.Tabs():
# Submission Tab
with gr.TabItem("π
Submission"):
file_input = gr.File(label="Upload Prediction CSV")
model_name_input = gr.Textbox(label="Model Name", placeholder="Enter your model name")
add_to_leaderboard_checkbox = gr.Checkbox(label="Add to Leaderboard?", value=True)
eval_status = gr.Textbox(label="Evaluation Status", interactive=False)
leaderboard_table_preview = gr.Dataframe(
value=load_leaderboard(),
label="Leaderboard (Preview)",
interactive=False,
wrap=True,
)
eval_button = gr.Button("Evaluate and Update Leaderboard")
eval_button.click(
evaluate_predictions,
inputs=[file_input, model_name_input, add_to_leaderboard_checkbox],
outputs=[eval_status, leaderboard_table_preview],
)
# Leaderboard Tab
with gr.TabItem("π
Leaderboard"):
leaderboard_table = gr.Dataframe(
value=load_leaderboard(),
label="Leaderboard",
interactive=False,
wrap=True,
)
refresh_button = gr.Button("Refresh Leaderboard")
refresh_button.click(
lambda: load_leaderboard(),
inputs=[],
outputs=[leaderboard_table],
)
gr.Markdown(f"Last updated on **{LAST_UPDATED}**")
demo.launch()
|