import json from datetime import datetime import pandas as pd import pytz import streamlit as st # File paths predictions_csv = 'predictions.csv' users_json = 'users.json' matches_json = 'matches.json' outcomes_json = 'match_outcomes.json' # Initialize CSV and JSON files if they don't exist def initialize_files(): # Initialize predictions CSV try: pd.read_csv(predictions_csv) except FileNotFoundError: df = pd.DataFrame(columns=['user_name', 'match_id', 'predicted_winner', 'predicted_motm', 'bid_points']) df.to_csv(predictions_csv, index=False) # Load users from JSON def get_users(): try: with open(users_json, 'r') as file: users = json.load(file) return list(users.keys()) except FileNotFoundError: return [] # Load matches from JSON def load_matches(): try: with open(matches_json, 'r') as f: return json.load(f) except FileNotFoundError: return [] def load_match_outcomes(): try: with open(outcomes_json, 'r') as file: return json.load(file) except FileNotFoundError: return [] # 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_matches() today_matches = [match for match in matches if match['date'] == today] return today_matches # Submit prediction function def submit_prediction(user_name, match_id, predicted_winner, predicted_motm, bid_points): # Ensure predictions DataFrame is loaded or initialized correctly try: predictions = pd.read_csv(predictions_csv) # Check if all expected columns are present, if not, reinitialize the DataFrame expected_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 user if user_name == "Select a user...": st.warning("Please select a valid user.") return else: 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 prediction new_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!") # Streamlit UI st.title("DIS IPL Match Predictions") # Prediction form with st.expander("Submit Prediction"): # User selection user_name = st.selectbox("Select User", ["Select a user..."] + get_users()) # Match selection 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'] else: st.write("No matches are scheduled for today.") st.stop() # Predictions predicted_winner = st.selectbox("Predicted Winner", teams) predicted_motm = st.text_input("Predicted Man of the Match") bid_points = st.number_input("Bid Points", min_value=1, value=100) # Submit button if st.button("Submit Prediction"): submit_prediction(user_name, match_id, predicted_winner, predicted_motm, bid_points) # Show predictions with st.expander("Predictions"): # Display predictions if st.button("Show Predictions"): try: df = pd.read_csv(predictions_csv) st.dataframe(df) except FileNotFoundError: st.write("No predictions have been submitted yet.") # Show leaderboard with st.expander("Leaderboard"): # Display leaderboard if st.button("Show Leaderboard"): try: with open(users_json, 'r') as f: users = json.load(f) leaderboard = sorted(users.items(), key=lambda x: x[1], reverse=True) df_leaderboard = pd.DataFrame(leaderboard, columns=['User', 'Points']) # Add a 'Rank' column starting from 1 df_leaderboard['Rank'] = range(1, len(df_leaderboard) + 1) # Reorder DataFrame columns so 'Rank' is first df_leaderboard = df_leaderboard[['Rank', 'User', 'Points']] st.dataframe(df_leaderboard) except FileNotFoundError: st.write("Leaderboard data not available.") ADMIN_PASSPHRASE = "admin123" def load_predictions(): # loading predictions from 'predictions.csv' try: return pd.read_csv(predictions_csv) except FileNotFoundError: return pd.DataFrame(columns=['user_name', 'match_id', 'predicted_winner', 'predicted_motm', 'bid_points']) def load_users(): with open(users_json, 'r') as file: return json.load(file) def save_users(users): with open(users_json, 'w') as file: json.dump(users, file, indent=4) def save_match_outcomes(outcomes): with open(outcomes_json, 'w') as file: json.dump(outcomes, file, indent=4) def update_leaderboard_and_outcomes(match_id, winning_team, man_of_the_match): outcomes = load_match_outcomes() # Load existing match outcomes predictions = load_predictions() # Load existing predictions users = load_users() # Load existing user points # Update match outcomes match_outcome = next((outcome for outcome in outcomes if outcome['match_id'] == match_id), None) if match_outcome: match_outcome['winning_team'] = winning_team match_outcome['man_of_the_match'] = man_of_the_match else: outcomes.append({ "match_id": match_id, "winning_team": winning_team, "man_of_the_match": man_of_the_match }) # Update user points based on prediction accuracy match_predictions = predictions[predictions['match_id'] == match_id] for _, prediction in match_predictions.iterrows(): user_name = prediction['user_name'] # Initialize user points if not present users[user_name] = users.get(user_name, 1000) if prediction['predicted_winner'] == winning_team: users[user_name] += prediction['bid_points'] * 2 # Correct team prediction else: users[user_name] -= prediction['bid_points'] # Deduct points for incorrect prediction if prediction['predicted_motm'] == man_of_the_match: users[user_name] += 100 # Correct man of the match prediction # Save updated outcomes and user points save_match_outcomes(outcomes) save_users(users) with st.sidebar.expander("Admin Panel", expanded=False): admin_pass = st.text_input("Enter admin passphrase:", type="password") if admin_pass == ADMIN_PASSPHRASE: st.success("Authenticated") matches = get_today_matches() # this function gets matches for today match_id_selection = st.selectbox("Select Match ID", [match['match_id'] for match in matches]) winning_team = st.text_input("Winning Team") man_of_the_match = st.text_input("Man of the Match") if st.button("Submit Match Outcome"): update_leaderboard_and_outcomes(match_id_selection, winning_team, man_of_the_match) st.success("Match outcome submitted and leaderboard updated!") else: st.error("Not authenticated")