Spaces:
Sleeping
Sleeping
File size: 30,800 Bytes
18f3eba 2847f48 91f54ca f4adc6b 174d220 2847f48 fb451d5 01b897e 2847f48 3ee7b39 91f54ca 3ee7b39 ee7d5e0 6ab428e 3ee7b39 18f3eba 2847f48 91f54ca ee7d5e0 d79709f d50e2d0 91f54ca 778c06e 91f54ca 6b23196 91f54ca 6b23196 91f54ca 7254a2f 91f54ca ee7d5e0 3ee7b39 f4adc6b 3ee7b39 f4adc6b 3ee7b39 2847f48 3ee7b39 f4adc6b 3ee7b39 f4adc6b 2847f48 3ee7b39 18f3eba 2847f48 3ee7b39 4c15e27 2847f48 70680b5 3ee7b39 70680b5 99601a6 70680b5 2847f48 70680b5 174d220 9cbfc91 70680b5 4c15e27 70680b5 030a527 1eb4ddf 030a527 ac41f6d 70680b5 91f54ca 8204020 2847f48 91f54ca 2847f48 91f54ca 9cbfc91 899dcbd 2847f48 91f54ca 899dcbd 91f54ca 899dcbd 91f54ca 899dcbd 2847f48 70680b5 26dc8de 45f0b1b 70680b5 79c7f0b ac41f6d 174d220 1eb4ddf 220eee2 70680b5 f4adc6b 45c0a23 f4adc6b 45c0a23 6ab428e 45c0a23 3ee7b39 054c4c5 f4adc6b 79c7f0b f4adc6b 79c7f0b 054c4c5 9cbfc91 054c4c5 9cbfc91 f4adc6b b7c9382 5bee751 8cd76bd b7c9382 9cbfc91 f4adc6b 9cbfc91 f4adc6b 3ee7b39 91f54ca 3ee7b39 91f54ca a167043 91f54ca 3ee7b39 5e636bc fb451d5 f4adc6b 1356e88 f4adc6b fb451d5 24ce55b 9cbfc91 d50e2d0 24ce55b 9cbfc91 332f07c d50e2d0 f4adc6b d50e2d0 7254a2f 8501811 1356e88 5e636bc 8501811 d509bf8 5e636bc 8501811 d509bf8 1356e88 9cbfc91 d509bf8 8501811 1356e88 f4adc6b d509bf8 3ee7b39 2847f48 18f3eba c630584 18f3eba c630584 79c7f0b 18f3eba 79c7f0b 18f3eba c630584 18f3eba 2847f48 18f3eba 3ee7b39 2847f48 18f3eba 3ee7b39 2847f48 18f3eba 3ee7b39 2847f48 18f3eba 2847f48 36b88a5 91f54ca 82f926c e0d7127 36b88a5 e0d7127 2847f48 adc5edf 053d053 adc5edf 053d053 adc5edf 053d053 adc5edf 1eb4ddf 053d053 adc5edf 053d053 9cbfc91 053d053 1eb4ddf adc5edf 9cbfc91 adc5edf 9cbfc91 053d053 adc5edf 9cbfc91 adc5edf 9cbfc91 053d053 9cbfc91 adc5edf 79c7f0b 053d053 79c7f0b adc5edf 053d053 9cbfc91 053d053 1eb4ddf 053d053 1eb4ddf 053d053 adc5edf 053d053 adc5edf 053d053 05bf781 18f3eba 2847f48 18f3eba 05bf781 91f54ca 6debba1 91f54ca 05bf781 18f3eba 91f54ca 05bf781 18f3eba 05bf781 25061c7 05bf781 f4adc6b 05bf781 18f3eba 2847f48 18f3eba |
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 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 |
import base64
import json
import os
import uuid
from datetime import datetime
from pathlib import Path
import math
import pandas as pd
import pytz
import streamlit as st
from datasets import Dataset, load_dataset
from huggingface_hub import CommitScheduler
# File paths as constants
USERS_JSON = 'leaders/users.json'
MATCHES_JSON = 'matches.json'
OUTCOMES_JSON = 'match_outcomes.json'
OUTCOMES = 'outcomes/match_outcomes.json'
BONUS_JSON = 'bonus/redistributed_matches.json'
PLAYERS_JSON = 'players.json'
image_path = 'ipl_image.png'
PREDICTIONS_FOLDER = Path("predictions")
PREDICTIONS_FOLDER.mkdir(parents=True, exist_ok=True)
users_file = Path("leaders") / f"users.json"
USERS_FOLDER = users_file.parent
USERS_FOLDER.mkdir(parents=True, exist_ok=True)
outcomes_file = Path("outcomes") / f"match_outcomes.json"
OUTCOMES_FOLDER = outcomes_file.parent
OUTCOMES_FOLDER.mkdir(parents=True, exist_ok=True)
redistribution_file = Path("bonus") / f"redistributed_matches.json"
REDISTRIBUTED_FOLDER = redistribution_file.parent
REDISTRIBUTED_FOLDER.mkdir(parents=True, exist_ok=True)
# Initialize CommitScheduler
scheduler = CommitScheduler(
repo_id="DIS_IPL_Preds",
repo_type="dataset",
folder_path=PREDICTIONS_FOLDER, # Local folder where predictions are saved temporarily
path_in_repo="predictions", # Path in dataset repo where predictions will be saved
every=720, # Push every 240 minutes (4 hours)
)
# Initialize CommitScheduler
scheduler = CommitScheduler(
repo_id="DIS_IPL_Leads",
repo_type="dataset",
folder_path=USERS_FOLDER, # Local folder where users are saved temporarily
path_in_repo="leaders", # Path in dataset repo where predictions will be saved
every=720, # Push every 240 minutes (4 hours)
)
# Initialize CommitScheduler
scheduler = CommitScheduler(
repo_id="DIS_IPL_Outcomes",
repo_type="dataset",
folder_path=OUTCOMES_FOLDER, # Local folder where users are saved temporarily
path_in_repo="outcomes", # Path in dataset repo where predictions will be saved
every=720, # Push every 240 minutes (4 hours)
)
def load_data(file_path):
"""
Load data from a JSON or CSV file.
Args:
file_path (str): The path to the file to load.
Returns:
pd.DataFrame or dict: The loaded data.
"""
try:
if file_path.endswith('.json'):
with open(file_path, 'r') as file:
return json.load(file)
elif file_path.endswith('.csv'):
return pd.read_csv(file_path)
except FileNotFoundError:
if file_path.endswith('.json'):
return {}
elif file_path.endswith('.csv'):
return pd.DataFrame()
def get_base64_of_image(path):
with open(path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode()
# Get today's date in IST to load today's match
def get_current_date_ist():
tz_IST = pytz.timezone('Asia/Kolkata')
datetime_ist = datetime.now(tz_IST)
return datetime_ist.strftime('%Y-%m-%d')
# Function to get matches for today
def get_today_matches():
today = get_current_date_ist()
matches = load_data(MATCHES_JSON)
today_matches = [match for match in matches if match['date'] == today]
return today_matches
# Function to check if prediction submission is allowed
def is_submission_allowed(match_id):
matches = load_data(MATCHES_JSON) # This loads matches correctly with IST times
for match in matches:
if match["match_id"] == match_id:
# Parse the match start time in IST
tz_IST = pytz.timezone('Asia/Kolkata')
match_datetime_str = f'{match["date"]} {match["time"]}'
# The match time string is like "2024-03-21 7:30 PM"
match_datetime = datetime.strptime(match_datetime_str, "%Y-%m-%d %I:%M %p")
match_datetime = tz_IST.localize(match_datetime) # Set the timezone to IST
# Get the current time in IST
current_datetime = datetime.now(tz_IST)
if current_datetime > match_datetime:
return False
else:
return True
return False # If match_id not found, default to False
# Submit prediction function
def submit_prediction(
user_name,
match_id,
predicted_winner,
predicted_motm,
bid_points,
min_bid_points,
max_bid_points,
wildcard_used
):
# Validation for user selection
if user_name == "Select a user...":
st.warning("Please select a valid user.")
return
# Check if prediction submission is allowed for the match
if not is_submission_allowed(match_id):
st.error("Prediction submission time has passed. Predictions can't be submitted after match start.")
return
if bid_points < min_bid_points:
st.error(
f"Oops, your bid is too low! π« Minimum allowed bid is {min_bid_points} (10% of your points)."
)
return
if bid_points > max_bid_points:
st.error(
f"Oops, your bid is too high! π« Maximum allowed bid is {max_bid_points}."
)
return
prediction_id = uuid.uuid4().hex
prediction_time = datetime.now().strftime('%Y-%m-%d')
prediction_data = {
'prediction_id': prediction_id,
'user_name': user_name,
'match_id': match_id,
'predicted_winner': predicted_winner,
'predicted_motm': predicted_motm,
'bid_points': bid_points,
'wildcard_used': wildcard_used if wildcard_used != "None" else None,
'prediction_date': prediction_time # Include the prediction time
}
# Construct the filename to include match_id for easier retrieval
prediction_file_name = f"prediction_{match_id}_{user_name}.json"
prediction_file = PREDICTIONS_FOLDER / prediction_file_name
# Load existing predictions for the user and match, if any
existing_predictions = []
if prediction_file.exists():
with prediction_file.open("r") as file:
for line in file:
existing_predictions.append(json.loads(line.strip()))
# Update existing prediction if it exists for the same user and match
prediction_updated = False
for existing_prediction in existing_predictions:
if existing_prediction['user_name'] == user_name and existing_prediction['match_id'] == match_id:
existing_prediction.update(prediction_data)
prediction_updated = True
break
# Save the updated predictions back to the file
with scheduler.lock:
if not prediction_updated:
# Append the new prediction if it doesn't already exist
with prediction_file.open("a") as file:
file.write(json.dumps(prediction_data))
file.write("\n")
else:
with prediction_file.open("w") as file:
for prediction in existing_predictions:
file.write(json.dumps(prediction))
file.write("\n")
st.success("Prediction submitted successfully!")
def get_user_total_points(user_name):
# users_dataset = load_dataset("Jay-Rajput/DIS_IPL_Leads", split="train")
# users = users_dataset.to_dict()
users = load_users(USERS_JSON)
return users.get(user_name, {}).get('points')
def calculate_min_max_bid_points(user_name):
total_points = get_user_total_points(user_name)
min_bid_points = math.ceil(total_points * 0.10) # round up
max_bid_points = total_points # math.floor(total_points * 0.50) # round down
return int(min_bid_points), int(max_bid_points)
def load_users(USERS_JSON):
try:
with open(USERS_JSON, 'r') as file:
return json.load(file)
except FileNotFoundError:
return {}
def load_bonus(BONUS_JSON):
try:
with open(BONUS_JSON, 'r') as file:
return json.load(file)
except FileNotFoundError:
return []
def user_selection_and_prediction():
users_data = load_users(USERS_JSON)
users = list(users_data)
user_name = st.selectbox("Select User", ["Select a user..."] + users)
min_bid_points, max_bid_points = None, None
if user_name != "Select a user...":
min_bid_points, max_bid_points = calculate_min_max_bid_points(user_name)
st.write(f"Bid points range you can submit: {min_bid_points} to {max_bid_points}")
# Load user wildcard status
user_wildcards = users_data.get(user_name, {}).get('wildcard', [0, 0, 0])
available_wildcards = []
if user_wildcards[0] == 0:
available_wildcards.append("PowerMoM")
if user_wildcards[1] == 0:
available_wildcards.append("TripleE")
if user_wildcards[2] == 0:
available_wildcards.append("SwitchHit")
available_wildcards = ["None"] + available_wildcards
matches = get_today_matches()
if matches:
match_choice = st.selectbox("Select Today's Match", matches, format_func=lambda match: f"{match['teams'][0]} vs {match['teams'][1]}")
match_id = match_choice['match_id']
teams = match_choice['teams']
predicted_winner = st.selectbox("Predicted Winner", teams)
player_list = load_data(PLAYERS_JSON)
predicted_motm = ""
if predicted_winner in player_list:
players = player_list[predicted_winner]
predicted_motm = st.selectbox("Predicted Man of the Match", players)
bid_points = st.number_input(
"Bid Points",
value=0,
step=1,
format="%d"
)
wildcard_used = st.selectbox("Select Wildcard (Optional)", available_wildcards)
if st.button("Submit Prediction"):
submit_prediction(user_name, match_id, predicted_winner, predicted_motm, bid_points, min_bid_points, max_bid_points, wildcard_used)
else:
st.write("No matches are scheduled for today.")
def display_predictions():
if st.button("Show Predictions"):
all_predictions = []
# Check if the directory exists
if not os.path.exists(PREDICTIONS_FOLDER):
st.write("No predictions directory found.")
return
# List all JSON files in the directory
for filename in os.listdir(PREDICTIONS_FOLDER):
if filename.endswith('.json'):
file_path = os.path.join(PREDICTIONS_FOLDER, filename)
# Read each JSON file and append its contents to the list
with open(file_path, 'r') as file:
prediction = json.load(file)
all_predictions.append(prediction)
# Convert the list of dictionaries to a DataFrame
predictions_df = pd.DataFrame(all_predictions)
if not predictions_df.empty:
predictions_df['prediction_date'] = predictions_df.apply(lambda x: datetime.strptime(x['prediction_date'], '%Y-%m-%d'), axis=1)
# Filter for today's predictions
today_str = datetime.now().strftime('%Y-%m-%d')
todays_predictions = predictions_df[predictions_df['prediction_date'] == today_str]
# Remove the 'prediction_id' column if it exists
if 'prediction_id' in todays_predictions.columns:
todays_predictions = todays_predictions.drop(columns=['prediction_id', 'prediction_date'])
st.dataframe(todays_predictions, hide_index=True)
else:
st.write("No predictions for today's matches yet.")
def display_leaderboard():
if st.button("Show Leaderboard"):
try:
# Load the 'leaders' configuration
dataset = load_dataset("Jay-Rajput/DIS_IPL_Leads", split='train')
users_data = []
if dataset:
for user, points_dict in dataset[0].items():
points = points_dict.get("points", 0)
last_5_results = " ".join(points_dict.get("last_5_results", ["βͺ"] * 5)) # Default: 5 white circles
bonus = points_dict.get("redistributed_bonus", 0)
bonus_display = f"+{bonus}" if bonus > 0 else ""
wildcard_flags = points_dict.get("wildcard", [0, 0, 0])
wildcard_display = []
if wildcard_flags[0] == 1:
wildcard_display.append("π‘PM") # PowerMoM
if wildcard_flags[1] == 1:
wildcard_display.append("πΊ3E") # TripleE
if wildcard_flags[2] == 1:
wildcard_display.append("πSH") # SwitchHit
users_data.append({
'User': user,
'Points': points,
'TOLBOG Wallet': bonus_display,
'Wildcards Used': ", ".join(wildcard_display),
'Last 5 Bids': last_5_results
})
else:
st.warning("No leaderboard data found.")
leaderboard = pd.DataFrame(users_data)
# Sort DataFrame by points in descending order
leaderboard = leaderboard.sort_values(by='Points', ascending=False)
# Add a 'Rank' column starting from 1
leaderboard['Rank'] = range(1, len(leaderboard) + 1)
# Select and order the columns for display
leaderboard = leaderboard[['Rank', 'User', 'Points', 'TOLBOG Wallet', 'Wildcards Used', 'Last 5 Bids']]
st.dataframe(leaderboard, hide_index=True)
except Exception as e:
st.write("Failed to load leaderboard data: ", str(e))
# Streamlit UI
encoded_image = get_base64_of_image(image_path)
custom_css = f"""
<style>
.header {{
font-size: 50px;
color: #FFD700; /* Gold */
text-shadow: -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000; /* Black text shadow */
text-align: center;
padding: 10px;
background-image: url('data:image/png;base64,{encoded_image}');
background-size: cover;
}}
</style>
"""
# Apply custom CSS
st.markdown(custom_css, unsafe_allow_html=True)
# Use the custom class in a div with your title
st.markdown('<div class="header">DIS IPL Match Predictions</div>', unsafe_allow_html=True)
st.write("π Predict, Compete, and Win π - Where Every Guess Counts! π")
user_guide_content = """
### π User Guide
#### Submitting Predictions
- **Match Selection**: Choose the match you want to predict from today's available matches.
- **Team and Player Prediction**: Select the team you predict will win and the "Man of the Match".
- **Bid Points**: Enter the number of points you wish to bid on your prediction. Remember, the maximum you can bid is capped at **20% of your total points**.
#### Scoring System
- **Winning Team Prediction**:
- β
**Correct Prediction**: You earn **2000 points** plus your bid amount.
- β **Incorrect Prediction**: You lose **200 points** plus your bid amount.
- **Man of the Match Prediction**:
- β
**Correct Prediction**: You earn **an additional 500 points**.
- β **Incorrect Prediction**: No penalty.
- **No Prediction Submitted**:
- β **You lose 10% of your total points** automatically for not submitting a prediction.
#### Bid Point Constraints
- You cannot bid less then 10% and more than 50% of your current total points.
- Bid points will be doubled if your prediction is correct, and deducted if incorrect.
#### Rules for Submission
- **Predictions must be submitted before the match starts**.
- **Only one prediction per match is allowed**.
- **Review your prediction carefully before submission, as it cannot be changed once submitted**.
#### π΄π’βͺ Match Performance Tracking
- After each match, your last **5 predictions will be tracked** and displayed on the leaderboard:
- π’ **Green** β Correct prediction.
- π΄ **Red** β Wrong prediction.
- βͺ **White** β No prediction submitted.
π **Compete, strategize, and climb the leaderboard!**
"""
# User Guide as an expander
with st.expander("User Guide π"):
st.markdown(user_guide_content)
with st.expander("Submit Prediction π"):
user_selection_and_prediction()
with st.expander("Predictions π"):
display_predictions()
with st.expander("Leaderboard π"):
display_leaderboard()
############################# Admin Panel ##################################
ADMIN_PASSPHRASE = "admin123"
def fetch_latest_predictions(match_id):
dataset = load_dataset("Jay-Rajput/DIS_IPL_Preds", split="train")
# Convert the dataset to a pandas DataFrame
df = pd.DataFrame(dataset)
# Ensure the DataFrame is not empty and contains the required columns
if not df.empty and {'user_name', 'match_id'}.issubset(df.columns):
# Filter rows by 'match_id'
filtered_df = df[df['match_id'] == match_id]
# Drop duplicate rows based on 'user_name'
unique_df = filtered_df.drop_duplicates(subset=['user_name'])
return unique_df
else:
return pd.DataFrame()
def update_leaderboard_and_outcomes(match_id, winning_team, man_of_the_match, outcome_only=False):
outcomes = load_dataset("Jay-Rajput/DIS_IPL_Outcomes", split="train")
outcomes_df = pd.DataFrame(outcomes)
# Update or add match outcome
outcome_exists = False
for idx, outcome in outcomes_df.iterrows():
if outcome['match_id'] == match_id:
outcomes_df.at[idx, 'winning_team'] = winning_team
outcomes_df.at[idx, 'man_of_the_match'] = man_of_the_match
outcome_exists = True
break
if not outcome_exists:
new_outcome = {"match_id": match_id, "winning_team": winning_team, "man_of_the_match": man_of_the_match}
outcomes_df = pd.concat([outcomes_df, pd.DataFrame([new_outcome])], ignore_index=True)
outcomes = Dataset.from_pandas(outcomes_df)
if not outcome_only:
predictions = fetch_latest_predictions(match_id)
users = load_dataset("Jay-Rajput/DIS_IPL_Leads", split="train")
users_df = pd.DataFrame(users)
submitted_users = set(predictions['user_name'])
# Capture previous leaderboard (top 3 users and their points)
prev_scores = [(user, users_df[user][0]['points']) for user in users_df.columns]
prev_scores.sort(key=lambda x: x[1], reverse=True)
prev_top_3 = prev_scores[:3]
top3_usernames = [user for user, _ in prev_top_3]
lost_points_by_top3 = 0
user_outcomes = {}
# Step 1: Apply current match outcomes
for user_name in users_df.columns:
user_data = users_df[user_name][0]
user_points = user_data['points']
user_initial_points = user_points
user_wildcards = user_data.get('wildcard', [0, 0, 0])
if user_name in submitted_users:
prediction = predictions[predictions['user_name'] == user_name].iloc[0]
predicted_winner = prediction['predicted_winner']
predicted_motm = prediction['predicted_motm']
bid_points = prediction['bid_points']
wildcard_used = prediction.get('wildcard_used')
earned_points = 0
if predicted_winner == winning_team:
earned_points += 2000 + bid_points
result_indicator = "π’"
if predicted_motm == man_of_the_match:
earned_points += 500
if wildcard_used == "PowerMoM":
earned_points += 1000 # MOM bonus tripled (500 -> 1500)
# Extra performance logic placeholder (e.g., 1000 for century etc.)
if wildcard_used == "TripleE":
earned_points *= 3
else:
earned_points -= 200 + bid_points
result_indicator = "π΄"
if user_name in top3_usernames:
lost_points_by_top3 += (200 + bid_points)
if wildcard_used == "PowerMoM" and predicted_motm != man_of_the_match:
user_wildcards[0] = 1 # Mark PowerMoM used anyway
elif wildcard_used == "TripleE":
user_wildcards[1] = 1
elif wildcard_used == "SwitchHit":
user_wildcards[2] = 1
user_points += earned_points
else:
penalty = int(0.10 * user_points)
user_points -= penalty
result_indicator = "βͺ"
if user_name in top3_usernames:
lost_points_by_top3 += penalty
user_points = max(user_points, 0)
user_outcomes[user_name] = {
"updated_points": user_points,
"result_indicator": result_indicator,
"initial_points": user_initial_points
}
users_df[user_name][0]['wildcard'] = user_wildcards
# Step 2: Build new leaderboard after applying outcome
new_leaderboard = [(u, d["updated_points"]) for u, d in user_outcomes.items()]
new_leaderboard.sort(key=lambda x: x[1], reverse=True)
third_place_points = new_leaderboard[2][1] if len(new_leaderboard) >= 3 else 0
# Step 3: Redistribute lost points using difference-from-3rd-place logic (only for users who submitted prediction)
redistribution_pool = lost_points_by_top3
redistribution_weights = {}
redistribution_total_weight = 0
for user, data in user_outcomes.items():
if user not in top3_usernames and user in submitted_users:
diff_from_3rd = max(third_place_points - data['updated_points'], 0)
redistribution_weights[user] = diff_from_3rd
redistribution_total_weight += diff_from_3rd
bonus_distribution = {}
for user, weight in redistribution_weights.items():
if redistribution_total_weight == 0:
bonus = 0
else:
bonus = int(redistribution_pool * (weight / redistribution_total_weight))
bonus_distribution[user] = bonus
# Step 4: Apply bonus and update dataset
for user in users_df.columns:
base_points = user_outcomes[user]["updated_points"]
bonus = bonus_distribution.get(user, 0)
final_points = base_points + bonus
users_df[user][0]['points'] = final_points
users_df[user][0]['redistributed_bonus'] = bonus
# Maintain last 5 results
result = user_outcomes[user]["result_indicator"]
if "last_5_results" not in users_df[user][0]:
users_df[user][0]["last_5_results"] = []
users_df[user][0]["last_5_results"].insert(0, result)
users_df[user][0]["last_5_results"] = users_df[user][0]["last_5_results"][:5]
# Save updated leaderboard
users.to_json(USERS_JSON)
updated_dataset = Dataset.from_pandas(users_df)
updated_dataset.push_to_hub("Jay-Rajput/DIS_IPL_Leads", split="train")
# Save match outcome
outcomes.to_json(OUTCOMES)
outcomes.push_to_hub("Jay-Rajput/DIS_IPL_Outcomes", split="train")
# def update_leaderboard_and_outcomes(match_id, winning_team, man_of_the_match, outcome_only=False):
# # Load existing match outcomes
# outcomes = load_dataset("Jay-Rajput/DIS_IPL_Outcomes", split="train")
# outcomes_df = pd.DataFrame(outcomes)
# # Directly update or add the match outcome
# outcome_exists = False
# for idx, outcome in outcomes_df.iterrows():
# if outcome['match_id'] == match_id:
# outcomes_df.at[idx, 'winning_team'] = winning_team
# outcomes_df.at[idx, 'man_of_the_match'] = man_of_the_match
# outcome_exists = True
# break
# if not outcome_exists:
# new_outcome = {"match_id": match_id, "winning_team": winning_team, "man_of_the_match": man_of_the_match}
# outcomes_df = pd.concat([outcomes_df, pd.DataFrame([new_outcome])], ignore_index=True)
# outcomes = Dataset.from_pandas(outcomes_df)
# if not outcome_only: # Update user scores only if outcome_only is False
# # Load predictions only if necessary
# predictions = fetch_latest_predictions(match_id)
# # Load users' data only if necessary
# users = load_dataset("Jay-Rajput/DIS_IPL_Leads", split="train")
# users_df = pd.DataFrame(users)
# # Update user points based on prediction accuracy
# users_with_predictions = set(predictions['user_name'])
# for user_name in users_df.columns:
# user_points = users_df[user_name][0]['points']
# if user_name in users_with_predictions:
# prediction = predictions[predictions['user_name'] == user_name].iloc[0]
# predicted_winner = prediction['predicted_winner']
# predicted_motm = prediction['predicted_motm']
# bid_points = prediction['bid_points']
# # Update points based on prediction accuracy
# if predicted_winner == winning_team:
# user_points += 2000 + bid_points
# result_indicator = "π’" # Correct Prediction
# if predicted_motm == man_of_the_match:
# user_points += 500
# else:
# user_points -= 200 + bid_points
# result_indicator = "π΄" # Wrong Prediction
# else:
# # Deduct 200 points for not submitting a prediction
# user_points -= 200
# result_indicator = "βͺ" # No Prediction
# # Ensure user_points is never negative
# user_points = max(user_points, 0)
# # Update user's points in the DataFrame
# users_df[user_name][0]['points'] = user_points
# users[user_name][0]['points'] = user_points
# # Maintain last 5 prediction results
# if "last_5_results" not in users_df[user_name][0]:
# users_df[user_name][0]["last_5_results"] = []
# users_df[user_name][0]["last_5_results"].insert(0, result_indicator) # Insert at beginning
# users_df[user_name][0]["last_5_results"] = users_df[user_name][0]["last_5_results"][:5] # Keep only last 5
# if "last_5_results" not in users[user_name][0]:
# users[user_name][0]["last_5_results"] = []
# users[user_name][0]["last_5_results"].insert(0, result_indicator) # Insert at beginning
# users[user_name][0]["last_5_results"] = users[user_name][0]["last_5_results"][:5] # Keep only last 5
# users.to_json(USERS_JSON)
# updated_dataset = Dataset.from_pandas(users_df)
# updated_dataset.push_to_hub("Jay-Rajput/DIS_IPL_Leads", split="train")
# outcomes.to_json(OUTCOMES)
# outcomes.push_to_hub("Jay-Rajput/DIS_IPL_Outcomes", split="train")
# Function to fetch matches for a given date
def fetch_matches_by_date(matches, selected_date):
return [match for match in matches if datetime.strptime(match['date'], '%Y-%m-%d').date() == selected_date]
with st.sidebar:
expander = st.expander("Admin Panel", expanded=False)
admin_pass = expander.text_input("Enter admin passphrase:", type="password", key="admin_pass")
if admin_pass == ADMIN_PASSPHRASE:
expander.success("Authenticated")
all_matches = load_data(MATCHES_JSON)
match_outcomes = load_dataset("Jay-Rajput/DIS_IPL_Outcomes", split="train")
submitted_match_ids = [outcome["match_id"] for outcome in match_outcomes]
# Filter matches to those that do not have outcomes submitted yet
matches_without_outcomes = [match for match in all_matches if match["match_id"] not in submitted_match_ids]
# If matches are available, let the admin select one
if matches_without_outcomes:
# Optional: Allow the admin to filter matches by date
selected_date = expander.date_input("Select Match Date", key="match_date")
if selected_date:
filtered_matches = fetch_matches_by_date(matches_without_outcomes, selected_date)
else:
filtered_matches = matches_without_outcomes
if filtered_matches:
match_selection = expander.selectbox("Select Match", filtered_matches, format_func=lambda match: f"{match['teams'][0]} vs {match['teams'][1]} (Match ID: {match['match_id']})", key="match_selection")
selected_match_id = match_selection['match_id']
teams = match_selection['teams']
# Let admin select the winning team
winning_team = expander.selectbox("Winning Team", teams, key="winning_team")
# Fetch and display players for the selected winning team
player_list = load_data(PLAYERS_JSON)
if winning_team in player_list:
players = player_list[winning_team]
man_of_the_match = expander.selectbox("Man of the Match", players, key="man_of_the_match")
else:
players = []
man_of_the_match = expander.text_input("Man of the Match (Type if not listed)", key="man_of_the_match_fallback")
# Add checkbox for outcome only submission
outcome_only = expander.checkbox("Submit Outcome Only", key="outcome_only_checkbox")
if expander.button("Submit Match Outcome", key="submit_outcome"):
if outcome_only:
# Submit match outcome without updating user scores
update_leaderboard_and_outcomes(selected_match_id, winning_team, man_of_the_match, outcome_only=True)
expander.success("Match outcome submitted!")
else:
# Submit match outcome and update user scores
update_leaderboard_and_outcomes(selected_match_id, winning_team, man_of_the_match)
expander.success("Match outcome submitted and leaderboard updated!")
else:
expander.write("No matches available for the selected date.")
else:
expander.write("No matches are available for today.")
else:
if admin_pass: # Show error only if something was typed
expander.error("Not authenticated")
|