Spaces:
Sleeping
Sleeping
jarajpu commited on
Commit ·
ed5c84d
1
Parent(s): 30a0fcd
enhanced admin panel
Browse filesFiles changed (6)
- README.md+4-48
- app.py+120-69
- dis_predictions.csv+6
- leaders/users.jsonAdded+17
- match_outcomes.json+5
- requirements.txt+3
123456781 unmodified line101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657---title: DIS IPL Predictionsemoji: 🦀colorFrom: redcolorTo: pinksdk: streamlitsdk_version: 1.32.2app_file: app.py1 unmodified linelicense: apache-2.0---# DIS IPL Match Predictions App> "Predict, Compete, and Win 🏏 - Where Every Guess Counts! 🏆"Welcome to the DIS IPL Match Predictions App! This app allows you to predict the outcomes of IPL matches and compete with your colleagues to win exciting prizes.## Getting Started### Prerequisites- Python 3.x installed on your system- Git installed on your system- Pip package manager### Installation1. Clone this repository to your local machine using Git:```bashgit clone <repository_url>```2. Navigate to the cloned repository directory:```bashcd ipl-match-predictions-app```3. Install the required Python dependencies using Pip:```bashpip install -r requirements.txt```### Running The APP1. After installing the dependencies, you can run the Streamlit app using the following command:```bashstreamlit run app.py```2. The app will start running locally and open in your default web browser.Thanks123456781 unmodified line10111213---title: Testingemoji: 📈colorFrom: redcolorTo: redsdk: streamlitsdk_version: 1.32.2app_file: app.py1 unmodified linelicense: apache-2.0---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
1234567891011121314151617181920101 unmodified lines12212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415547 unmodified lines20320420520620720820921021121221321421521621721813 unmodified lines23223323423523623723823924024124224324424524624724824925025125256 unmodified lines3093103113123133143153163172 unmodified lines3203213223233243253263273286 unmodified lines3353363373383393403413423433443453463473483493503513523533543553562 unmodified lines359360361362363364365366367368369import base64import jsonfrom datetime import datetime, timedeltaimport pandas as pdimport pytzimport streamlit as st# File paths as constantsPREDICTIONS_CSV = 'dis_predictions.csv'USERS_JSON = 'users.json'MATCHES_JSON = 'matches.json'OUTCOMES_JSON = 'match_outcomes.json'PLAYERS_JSON = 'players.json'image_path = 'ipl_image.png'# Initialize CSV and JSON files if they don't existdef initialize_files():# Initialize predictions CSV101 unmodified linesst.error(f"Your bid points exceed the 20% limit of your total points. Maximum allowed bid points: {max_bid_points}")return# Ensure predictions DataFrame is loaded or initialized correctlytry:predictions = load_predictions(PREDICTIONS_CSV)# Check if all expected columns are present, if not, reinitialize the DataFrameexpected_columns = ['user_name', 'match_id', 'predicted_winner', 'predicted_motm', 'bid_points']if not all(column in predictions.columns for column in expected_columns):raise ValueError("CSV file missing one or more columns; Reinitializing.")except (FileNotFoundError, ValueError) as e:predictions = pd.DataFrame(columns=expected_columns)# Check for duplicate prediction for the same match by the same userif user_name != "Select a user...":existing_predictions = predictions[(predictions['user_name'] == user_name) & (predictions['match_id'] == match_id)]if not existing_predictions.empty:st.error("You've already submitted a prediction for this match.")return# Append new predictionnew_prediction = {'user_name': user_name,'match_id': match_id,'predicted_winner': predicted_winner,'predicted_motm': predicted_motm,'bid_points': bid_points}predictions = pd.concat([predictions, pd.DataFrame([new_prediction])], ignore_index=True)predictions.to_csv(PREDICTIONS_CSV, index=False)st.success("Prediction submitted successfully!")47 unmodified lineselse:st.write("No matches are scheduled for today.")def display_predictions():if st.button("Show Predictions"):try:todays_predictions = show_todays_match_predictions()if not todays_predictions.empty:st.dataframe(todays_predictions, hide_index=True)else:st.write("No predictions for today's matches yet.")except FileNotFoundError:st.write("No predictions have been submitted yet.")def display_leaderboard():if st.button("Show Leaderboard"):13 unmodified linesst.write("Leaderboard data not available.")# Show Predictions functionalitydef show_todays_match_predictions():# Get today's matchestoday_matches = get_today_matches()today_match_ids = [match['match_id'] for match in today_matches]# Load all predictionspredictions = load_predictions(PREDICTIONS_CSV)# Filter predictions for today's matchestoday_predictions = predictions[predictions['match_id'].isin(today_match_ids)]return today_predictions# Streamlit UIencoded_image = get_base64_of_image(image_path)custom_css = f"""56 unmodified lines############################# Admin Panel ##################################ADMIN_PASSPHRASE = "admin123"def save_users(users):with open(USERS_JSON, 'w') as file:json.dump(users, file, indent=4)def save_match_outcomes(outcomes):2 unmodified linesdef update_leaderboard_and_outcomes(match_id, winning_team, man_of_the_match):outcomes = load_data(OUTCOMES_JSON) # Load existing match outcomespredictions = load_predictions(PREDICTIONS_CSV) # Load existing predictionsusers = load_users(USERS_JSON) # Load existing user points# Directly update or add the match outcomeoutcome_exists = False6 unmodified linesoutcomes.append({"match_id": match_id, "winning_team": winning_team, "man_of_the_match": man_of_the_match})# Update user points based on prediction accuracyfor _, prediction in predictions.iterrows():if prediction['match_id'] == match_id:user_name = prediction['user_name']users[user_name] = users.get(user_name, 0) # Initialize user points if not present# Update points based on prediction accuracyif prediction['predicted_winner'] == winning_team:users[user_name] += 1000users[user_name] += prediction['bid_points']if prediction['predicted_motm'] == man_of_the_match:users[user_name] += 400 # Bonus for both correct predictionselse:users[user_name] -= 200 + prediction['bid_points'] # Penalty for wrong team predictionsave_match_outcomes(outcomes)save_users(users)with st.sidebar:2 unmodified linesif admin_pass == ADMIN_PASSPHRASE:expander.success("Authenticated")matches = get_today_matches() # This function fetches today's matches# If matches are available, let the admin select oneif matches:match_selection = expander.selectbox("Select Match", matches, format_func=lambda match: f"{match['teams'][0]} vs {match['teams'][1]}", key="match_selection")selected_match_id = match_selection['match_id']teams = match_selection['teams']12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152101 unmodified lines15415515615715815916016116216316416516616716816917017117217317417517617717817918018147 unmodified lines22923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127213 unmodified lines28628728828929029156 unmodified lines3483493503513523533543553563572 unmodified lines3603613623633643653663673683693703713726 unmodified lines3793803813823833843853863873883893903913923933943953963973983994004012 unmodified lines404405406407408409410411412413414415416417418419420import base64import ioimport jsonimport osimport uuidfrom datetime import datetimefrom pathlib import Pathimport pandas as pdimport pytzimport streamlit as stfrom datasets import load_datasetfrom huggingface_hub import CommitScheduler, HfApi# File paths as constantsPREDICTIONS_CSV = 'dis_predictions.csv'USERS_JSON = 'leaders/users.json'MATCHES_JSON = 'matches.json'OUTCOMES_JSON = 'match_outcomes.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.parentUSERS_FOLDER.mkdir(parents=True, exist_ok=True)# Initialize CommitSchedulerscheduler = CommitScheduler(repo_id="DIS_IPL_Dataset",repo_type="dataset",folder_path=PREDICTIONS_FOLDER, # Local folder where predictions are saved temporarilypath_in_repo="predictions", # Path in dataset repo where predictions will be savedevery=120, # Push every 240 minutes (4 hours))# Initialize CommitSchedulerscheduler = CommitScheduler(repo_id="DIS_IPL_Dataset",repo_type="dataset",folder_path=USERS_FOLDER, # Local folder where users are saved temporarilypath_in_repo="leaders", # Path in dataset repo where predictions will be savedevery=120, # Push every 240 minutes (4 hours))# Initialize CSV and JSON files if they don't existdef initialize_files():# Initialize predictions CSV101 unmodified linesst.error(f"Your bid points exceed the 20% limit of your total points. Maximum allowed bid points: {max_bid_points}")returnprediction_id = uuid.uuid4().hexprediction_date = 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,'prediction_date': prediction_date # Include the prediction date}# Construct the filename to include match_id for easier retrievalprediction_file_name = f"prediction_{match_id}_{prediction_id}.json"prediction_file = PREDICTIONS_FOLDER / prediction_file_namewith scheduler.lock:with prediction_file.open("a") as file:file.write(json.dumps(prediction_data))file.write("\n")st.success("Prediction submitted successfully!")47 unmodified lineselse:st.write("No matches are scheduled for today.")def display_predictions():if st.button("Show Predictions"):all_predictions = []# Check if the directory existsif not os.path.exists(PREDICTIONS_FOLDER):st.write("No predictions directory found.")return# List all JSON files in the directoryfor 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 listwith open(file_path, 'r') as file:prediction = json.load(file)all_predictions.append(prediction)# Convert the list of dictionaries to a DataFramepredictions_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 predictionstoday_str = datetime.now().strftime('%Y-%m-%d')todays_predictions = predictions_df[predictions_df['prediction_date'] == today_str]# Remove the 'prediction_id' column if it existsif '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"):13 unmodified linesst.write("Leaderboard data not available.")# Streamlit UIencoded_image = get_base64_of_image(image_path)custom_css = f"""56 unmodified lines############################# Admin Panel ##################################ADMIN_PASSPHRASE = "admin123"def fetch_latest_predictions(match_id):dataset = load_dataset("Jay-Rajput/DIS_IPL_Dataset", config_name="predictions")predictions = dataset['train'].filter(lambda example: example['match_id'] == match_id)return predictionsdef save_match_outcomes(outcomes):2 unmodified linesdef update_leaderboard_and_outcomes(match_id, winning_team, man_of_the_match):# Fetch latest predictions from the dataset repopredictions = fetch_latest_predictions(match_id)outcomes = load_data(OUTCOMES_JSON) # Load existing match outcomes# Load existing match outcomes and user data from the test splitdataset = load_dataset("Jay-Rajput/DIS_IPL_Dataset", config_name="leaders")users = {item['user_name']: item for item in dataset['train']}# Directly update or add the match outcomeoutcome_exists = False6 unmodified linesoutcomes.append({"match_id": match_id, "winning_team": winning_team, "man_of_the_match": man_of_the_match})# Update user points based on prediction accuracyfor prediction in predictions:user_name = prediction['user_name']# Initialize user points if not presentif user_name not in users:users[user_name] = {'user_name': user_name, 'points': 0}# Update points based on prediction accuracyif prediction['predicted_winner'] == winning_team:users[user_name] += 1000users[user_name] += prediction['bid_points']if prediction['predicted_motm'] == man_of_the_match:users[user_name] += 400 # Bonus for both correct predictionselse:users[user_name] -= 200 + prediction['bid_points'] # Penalty for wrong team predictionsave_match_outcomes(outcomes)users.save_to_disk(USERS_JSON)with st.sidebar:2 unmodified linesif admin_pass == ADMIN_PASSPHRASE:expander.success("Authenticated")all_matches = load_data(MATCHES_JSON)match_outcomes = load_data(OUTCOMES_JSON)submitted_match_ids = [outcome["match_id"] for outcome in match_outcomes]# Filter matches to those that do not have outcomes submitted yetmatches_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 oneif matches_without_outcomes:match_selection = expander.selectbox("Select Match", matches_without_outcomes, format_func=lambda match: f"{match['teams'][0]} vs {match['teams'][1]}", key="match_selection")selected_match_id = match_selection['match_id']teams = match_selection['teams']
2 unmodified lines3452 unmodified linesSahil,20240325_6,RCB,Virat Kohli,350Vinay,20240325_6,RCB,Faf du Plessis,200Megha,20240325_6,RCB,Virat Kohli,5002 unmodified lines345678910112 unmodified linesSahil,20240325_6,RCB,Virat Kohli,350Vinay,20240325_6,RCB,Faf du Plessis,200Megha,20240325_6,RCB,Virat Kohli,500Jay,20240325_6,RCB,Virat Kohli,200Sai,20240325_6,RCB,Glenn Maxwell,620Haaris,20240325_6,RCB,Virat Kohli,1200Naveein,20240325_6,RCB,Faf du Plessis,500Praveen,20240325_6,RCB,Faf du Plessis,1800Kishore,20240325_6,RCB,Glenn Maxwell,500
1234567891011121314151617{ "Arpit": 11300, "Ganesh": 5750, "Haaris": 6000, "Jay": 6500, "Kishore": 5700, "Megha": 5900, "Naveein": 6300, "Neha": 5600, "Praveen": 9000, "Rakesh": 6500, "Sai": 3100, "Sahil": 6600, "Sunil": 4501, "Vaibhav": 5600, "Vinay": 5300}22 unmodified lines232425262722 unmodified lines"match_id": "20240324_5","winning_team": "GT","man_of_the_match": "B Sai Sudharsan"}]22 unmodified lines2324252627282930313222 unmodified lines"match_id": "20240324_5","winning_team": "GT","man_of_the_match": "B Sai Sudharsan"},{"match_id": "20240325_6","winning_team": "RCB","man_of_the_match": "Virat Kohli"}]
123pandaspytzstreamlit123456datasetshuggingface_hubpandaspytzrequestsstreamlit
README.md+4-48
app.py+120-69
dis_predictions.csv+6
leaders/users.jsonAdded+17
match_outcomes.json+5
requirements.txt+3