Jay-Rajput commited on
Commit
3ee7b39
Β·
1 Parent(s): f5e49ed

Enhanced script

Browse files
Files changed (2) hide show
  1. app.py +125 -128
  2. predictions.csv +12 -4
app.py CHANGED
@@ -6,11 +6,12 @@ import pandas as pd
6
  import pytz
7
  import streamlit as st
8
 
9
- # File paths
10
- predictions_csv = 'predictions.csv'
11
- users_json = 'users.json'
12
- matches_json = 'matches.json'
13
- outcomes_json = 'match_outcomes.json'
 
14
  image_path = 'ipl_image.png'
15
 
16
 
@@ -18,43 +19,34 @@ image_path = 'ipl_image.png'
18
  def initialize_files():
19
  # Initialize predictions CSV
20
  try:
21
- pd.read_csv(predictions_csv)
22
  except FileNotFoundError:
23
  df = pd.DataFrame(columns=['user_name', 'match_id', 'predicted_winner', 'predicted_motm', 'bid_points'])
24
- df.to_csv(predictions_csv, index=False)
25
-
26
-
27
- # Load users from JSON
28
- def get_users():
29
- try:
30
- with open(users_json, 'r') as file:
31
- users = json.load(file)
32
- return list(users.keys())
33
- except FileNotFoundError:
34
- return []
35
-
36
-
37
- # Load matches from JSON
38
- def load_matches():
39
  try:
40
- with open(matches_json, 'r') as f:
41
- return json.load(f)
 
 
 
42
  except FileNotFoundError:
43
- return []
44
-
45
-
46
- def load_match_outcomes():
47
- try:
48
- with open(outcomes_json, 'r') as file:
49
- return json.load(file)
50
- except FileNotFoundError:
51
- return []
52
-
53
-
54
- # Load the player list from the JSON file
55
- def load_player_list():
56
- with open('players.json', 'r') as file:
57
- return json.load(file)
58
 
59
 
60
  def get_base64_of_image(path):
@@ -72,14 +64,14 @@ def get_current_date_ist():
72
  # Function to get matches for today
73
  def get_today_matches():
74
  today = get_current_date_ist()
75
- matches = load_matches()
76
  today_matches = [match for match in matches if match['date'] == today]
77
  return today_matches
78
 
79
 
80
  # Function to check if prediction submission is allowed
81
  def is_submission_allowed(match_id):
82
- matches = load_matches() # This loads matches correctly with IST times
83
 
84
  for match in matches:
85
  if match["match_id"] == match_id:
@@ -126,7 +118,7 @@ def submit_prediction(
126
 
127
  # Ensure predictions DataFrame is loaded or initialized correctly
128
  try:
129
- predictions = pd.read_csv(predictions_csv)
130
  # Check if all expected columns are present, if not, reinitialize the DataFrame
131
  expected_columns = ['user_name', 'match_id', 'predicted_winner', 'predicted_motm', 'bid_points']
132
  if not all(column in predictions.columns for column in expected_columns):
@@ -151,13 +143,12 @@ def submit_prediction(
151
  }
152
 
153
  predictions = pd.concat([predictions, pd.DataFrame([new_prediction])], ignore_index=True)
154
- predictions.to_csv(predictions_csv, index=False)
155
  st.success("Prediction submitted successfully!")
156
 
157
 
158
  def get_user_total_points(user_name):
159
- with open(users_json, 'r') as file:
160
- users = json.load(file)
161
  return users.get(user_name, 0)
162
 
163
 
@@ -168,6 +159,87 @@ def calculate_max_bid_points(user_name):
168
  return max_bid_points
169
 
170
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
  # Streamlit UI
172
  encoded_image = get_base64_of_image(image_path)
173
  custom_css = f"""
@@ -217,84 +289,14 @@ user_guide_content = """
217
  with st.expander("User Guide πŸ“˜"):
218
  st.markdown(user_guide_content)
219
 
220
- # Prediction form
221
  with st.expander("Submit Prediction πŸ“"):
 
222
 
223
- # User selection
224
- user_name = st.selectbox("Select User", ["Select a user..."] + get_users())
225
-
226
- # Initialize max_bid_points to None
227
- max_bid_points = None
228
-
229
- if user_name != "Select a user...":
230
- max_bid_points = calculate_max_bid_points(user_name)
231
- # Display the max bid points
232
- st.write(f"Maximum bid points you can submit: {max_bid_points}")
233
-
234
- # Match selection
235
- matches = get_today_matches()
236
- if matches:
237
- match_choice = st.selectbox("Select Today's Match", matches, format_func=lambda match: f"{match['teams'][0]} vs {match['teams'][1]}")
238
- match_id = match_choice['match_id']
239
- teams = match_choice['teams']
240
- else:
241
- st.write("No matches are scheduled for today.")
242
- st.stop()
243
-
244
- # Predictions
245
- predicted_winner = st.selectbox("Predicted Winner", teams)
246
-
247
- # Load the player list and populate the dropdown based on the selected team
248
- predicted_motm = ""
249
- player_list = load_player_list()
250
- if predicted_winner in player_list:
251
- players = player_list[predicted_winner]
252
- predicted_motm = st.selectbox("Predicted Man of the Match", players)
253
- # predicted_motm = st.text_input("Predicted Man of the Match")
254
-
255
- bid_points = st.number_input("Bid Points", min_value=1, value=100, format="%d")
256
-
257
- # Submit button
258
- if st.button("Submit Prediction"):
259
- if user_name != "Select a user...":
260
- submit_prediction(user_name, match_id, predicted_winner, predicted_motm, bid_points, max_bid_points)
261
-
262
-
263
- # Show predictions
264
  with st.expander("Predictions πŸ”"):
 
265
 
266
- # Display predictions
267
- if st.button("Show Predictions"):
268
- try:
269
- df = pd.read_csv(predictions_csv)
270
- st.dataframe(df, hide_index=True)
271
- except FileNotFoundError:
272
- st.write("No predictions have been submitted yet.")
273
-
274
-
275
- # Show leaderboard
276
  with st.expander("Leaderboard πŸ†"):
277
-
278
- # Display leaderboard
279
- if st.button("Show Leaderboard"):
280
- try:
281
- with open(users_json, 'r') as f:
282
- users = json.load(f)
283
- leaderboard = sorted(users.items(), key=lambda x: x[1], reverse=True)
284
- df_leaderboard = pd.DataFrame(leaderboard, columns=['User', 'Points'])
285
-
286
- # Add a 'Rank' column starting from 1
287
- df_leaderboard['Rank'] = range(1, len(df_leaderboard) + 1)
288
-
289
- # Reorder DataFrame columns so 'Rank' is first
290
- df_leaderboard = df_leaderboard[['Rank', 'User', 'Points']]
291
-
292
- # Reset index to remove the default index column
293
- df_leaderboard.reset_index(drop=True, inplace=True)
294
-
295
- st.dataframe(df_leaderboard, hide_index=True)
296
- except FileNotFoundError:
297
- st.write("Leaderboard data not available.")
298
 
299
 
300
  ############################# Admin Panel ##################################
@@ -304,30 +306,25 @@ ADMIN_PASSPHRASE = "admin123"
304
  def load_predictions():
305
  # loading predictions from 'predictions.csv'
306
  try:
307
- return pd.read_csv(predictions_csv)
308
  except FileNotFoundError:
309
  return pd.DataFrame(columns=['user_name', 'match_id', 'predicted_winner', 'predicted_motm', 'bid_points'])
310
 
311
 
312
- def load_users():
313
- with open(users_json, 'r') as file:
314
- return json.load(file)
315
-
316
-
317
  def save_users(users):
318
- with open(users_json, 'w') as file:
319
  json.dump(users, file, indent=4)
320
 
321
 
322
  def save_match_outcomes(outcomes):
323
- with open(outcomes_json, 'w') as file:
324
  json.dump(outcomes, file, indent=4)
325
 
326
 
327
  def update_leaderboard_and_outcomes(match_id, winning_team, man_of_the_match):
328
- outcomes = load_match_outcomes() # Load existing match outcomes
329
  predictions = load_predictions() # Load existing predictions
330
- users = load_users() # Load existing user points
331
 
332
  # Update match outcomes
333
  match_outcome = next((outcome for outcome in outcomes if outcome['match_id'] == match_id), None)
@@ -387,7 +384,7 @@ with st.sidebar:
387
  winning_team = expander.selectbox("Winning Team", teams, key="winning_team")
388
 
389
  # Fetch and display players for the selected winning team
390
- player_list = load_player_list()
391
  if winning_team in player_list:
392
  players = player_list[winning_team]
393
  man_of_the_match = expander.selectbox("Man of the Match", players, key="man_of_the_match")
 
6
  import pytz
7
  import streamlit as st
8
 
9
+ # File paths as constants
10
+ PREDICTIONS_CSV = 'predictions.csv'
11
+ USERS_JSON = 'users.json'
12
+ MATCHES_JSON = 'matches.json'
13
+ OUTCOMES_JSON = 'match_outcomes.json'
14
+ PLAYERS_JSON = 'players.json'
15
  image_path = 'ipl_image.png'
16
 
17
 
 
19
  def initialize_files():
20
  # Initialize predictions CSV
21
  try:
22
+ pd.read_csv(PREDICTIONS_CSV)
23
  except FileNotFoundError:
24
  df = pd.DataFrame(columns=['user_name', 'match_id', 'predicted_winner', 'predicted_motm', 'bid_points'])
25
+ df.to_csv(PREDICTIONS_CSV, index=False)
26
+
27
+
28
+ @st.cache_data
29
+ def load_data(file_path):
30
+ """
31
+ Load data from a JSON or CSV file.
32
+
33
+ Args:
34
+ file_path (str): The path to the file to load.
35
+
36
+ Returns:
37
+ pd.DataFrame or dict: The loaded data.
38
+ """
 
39
  try:
40
+ if file_path.endswith('.json'):
41
+ with open(file_path, 'r') as file:
42
+ return json.load(file)
43
+ elif file_path.endswith('.csv'):
44
+ return pd.read_csv(file_path)
45
  except FileNotFoundError:
46
+ if file_path.endswith('.json'):
47
+ return {}
48
+ elif file_path.endswith('.csv'):
49
+ return pd.DataFrame()
 
 
 
 
 
 
 
 
 
 
 
50
 
51
 
52
  def get_base64_of_image(path):
 
64
  # Function to get matches for today
65
  def get_today_matches():
66
  today = get_current_date_ist()
67
+ matches = load_data(MATCHES_JSON)
68
  today_matches = [match for match in matches if match['date'] == today]
69
  return today_matches
70
 
71
 
72
  # Function to check if prediction submission is allowed
73
  def is_submission_allowed(match_id):
74
+ matches = load_data(MATCHES_JSON) # This loads matches correctly with IST times
75
 
76
  for match in matches:
77
  if match["match_id"] == match_id:
 
118
 
119
  # Ensure predictions DataFrame is loaded or initialized correctly
120
  try:
121
+ predictions = load_data(PREDICTIONS_CSV)
122
  # Check if all expected columns are present, if not, reinitialize the DataFrame
123
  expected_columns = ['user_name', 'match_id', 'predicted_winner', 'predicted_motm', 'bid_points']
124
  if not all(column in predictions.columns for column in expected_columns):
 
143
  }
144
 
145
  predictions = pd.concat([predictions, pd.DataFrame([new_prediction])], ignore_index=True)
146
+ predictions.to_csv(PREDICTIONS_CSV, index=False)
147
  st.success("Prediction submitted successfully!")
148
 
149
 
150
  def get_user_total_points(user_name):
151
+ users = load_data(USERS_JSON)
 
152
  return users.get(user_name, 0)
153
 
154
 
 
159
  return max_bid_points
160
 
161
 
162
+ def user_selection_and_prediction():
163
+ users = list(load_data(USERS_JSON))
164
+ user_name = st.selectbox("Select User", ["Select a user..."] + users)
165
+
166
+ max_bid_points = None
167
+ if user_name != "Select a user...":
168
+ max_bid_points = calculate_max_bid_points(user_name)
169
+ st.write(f"Maximum bid points you can submit: {max_bid_points}")
170
+
171
+ matches = get_today_matches()
172
+ if matches:
173
+ match_choice = st.selectbox("Select Today's Match", matches, format_func=lambda match: f"{match['teams'][0]} vs {match['teams'][1]}")
174
+ match_id = match_choice['match_id']
175
+ teams = match_choice['teams']
176
+
177
+ predicted_winner = st.selectbox("Predicted Winner", teams)
178
+
179
+ player_list = load_data(PLAYERS_JSON)
180
+ predicted_motm = ""
181
+ if predicted_winner in player_list:
182
+ players = player_list[predicted_winner]
183
+ predicted_motm = st.selectbox("Predicted Man of the Match", players)
184
+
185
+ bid_points = st.number_input("Bid Points", min_value=1, value=100, format="%d")
186
+
187
+ if st.button("Submit Prediction"):
188
+ submit_prediction(user_name, match_id, predicted_winner, predicted_motm, bid_points, max_bid_points)
189
+ else:
190
+ st.write("No matches are scheduled for today.")
191
+
192
+ def display_predictions():
193
+ if st.button("Show Predictions"):
194
+ try:
195
+ todays_predictions = show_todays_match_predictions()
196
+ if not todays_predictions.empty:
197
+ st.dataframe(todays_predictions, hide_index=True)
198
+ else:
199
+ st.write("No predictions for today's matches yet.")
200
+ except FileNotFoundError:
201
+ st.write("No predictions have been submitted yet.")
202
+
203
+ def display_leaderboard():
204
+ if st.button("Show Leaderboard"):
205
+ try:
206
+ users = load_data(USERS_JSON) # Adjusted for the new load_data function
207
+ leaderboard = sorted(users.items(), key=lambda x: x[1], reverse=True)
208
+
209
+ # Generate a list of dictionaries, each representing a row in the leaderboard
210
+ leaderboard_dicts = [{"Rank": rank+1, "User": user[0], "Points": user[1]}
211
+ for rank, user in enumerate(leaderboard)]
212
+
213
+ # Convert the list of dictionaries to a DataFrame
214
+ df_leaderboard = pd.DataFrame(leaderboard_dicts)
215
+
216
+ st.dataframe(df_leaderboard, hide_index=True)
217
+ except FileNotFoundError:
218
+ st.write("Leaderboard data not available.")
219
+
220
+
221
+ def load_predictions(PREDICTIONS_CSV):
222
+ try:
223
+ return pd.read_csv(PREDICTIONS_CSV)
224
+ except FileNotFoundError:
225
+ return pd.DataFrame()
226
+
227
+
228
+ # Show Predictions functionality
229
+ def show_todays_match_predictions():
230
+ # Get today's matches
231
+ today_matches = get_today_matches()
232
+ today_match_ids = [match['match_id'] for match in today_matches]
233
+
234
+ # Load all predictions
235
+ predictions = load_predictions(PREDICTIONS_CSV)
236
+
237
+ # Filter predictions for today's matches
238
+ today_predictions = predictions[predictions['match_id'].isin(today_match_ids)]
239
+
240
+ return today_predictions
241
+
242
+
243
  # Streamlit UI
244
  encoded_image = get_base64_of_image(image_path)
245
  custom_css = f"""
 
289
  with st.expander("User Guide πŸ“˜"):
290
  st.markdown(user_guide_content)
291
 
 
292
  with st.expander("Submit Prediction πŸ“"):
293
+ user_selection_and_prediction()
294
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
295
  with st.expander("Predictions πŸ”"):
296
+ display_predictions()
297
 
 
 
 
 
 
 
 
 
 
 
298
  with st.expander("Leaderboard πŸ†"):
299
+ display_leaderboard()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300
 
301
 
302
  ############################# Admin Panel ##################################
 
306
  def load_predictions():
307
  # loading predictions from 'predictions.csv'
308
  try:
309
+ return load_data(PREDICTIONS_CSV)
310
  except FileNotFoundError:
311
  return pd.DataFrame(columns=['user_name', 'match_id', 'predicted_winner', 'predicted_motm', 'bid_points'])
312
 
313
 
 
 
 
 
 
314
  def save_users(users):
315
+ with open(USERS_JSON, 'w') as file:
316
  json.dump(users, file, indent=4)
317
 
318
 
319
  def save_match_outcomes(outcomes):
320
+ with open(OUTCOMES_JSON, 'w') as file:
321
  json.dump(outcomes, file, indent=4)
322
 
323
 
324
  def update_leaderboard_and_outcomes(match_id, winning_team, man_of_the_match):
325
+ outcomes = load_data(OUTCOMES_JSON) # Load existing match outcomes
326
  predictions = load_predictions() # Load existing predictions
327
+ users = load_data(USERS_JSON) # Load existing user points
328
 
329
  # Update match outcomes
330
  match_outcome = next((outcome for outcome in outcomes if outcome['match_id'] == match_id), None)
 
384
  winning_team = expander.selectbox("Winning Team", teams, key="winning_team")
385
 
386
  # Fetch and display players for the selected winning team
387
+ player_list = load_data(PLAYERS_JSON)
388
  if winning_team in player_list:
389
  players = player_list[winning_team]
390
  man_of_the_match = expander.selectbox("Man of the Match", players, key="man_of_the_match")
predictions.csv CHANGED
@@ -1,5 +1,13 @@
1
  user_name,match_id,predicted_winner,predicted_motm,bid_points
2
- Sahil,20240322_2,CSK,Ruturaj Gaikwad,250
3
- Naveein,20240322_2,CSK,Rachin Ravindra,1000
4
- Ganesh,20240322_2,CSK,Ruturaj Gaikwad,300
5
- Jay,20240322_2,CSK,Ruturaj Gaikwad,500
 
 
 
 
 
 
 
 
 
1
  user_name,match_id,predicted_winner,predicted_motm,bid_points
2
+ Sahil,20240322_1,CSK,Ruturaj Gaikwad,250
3
+ Naveein,20240322_1,CSK,Rachin Ravindra,1000
4
+ Ganesh,20240322_1,CSK,Ruturaj Gaikwad,300
5
+ Jay,20240322_1,CSK,Ruturaj Gaikwad,500
6
+ Megha,20240322_1,RCB,Virat Kohli,500
7
+ Arpit,20240322_1,CSK,Ravindra Jadeja,1000
8
+ Sunil,20240322_1,RCB,Virat Kohli,299
9
+ Praveen,20240322_1,CSK,Ravindra Jadeja,1000
10
+ Vinay,20240322_1,CSK,Rachin Ravindra,216
11
+ Kichu,20240322_1,CSK,MS Dhoni,500
12
+ Haaris,20240322_1,CSK,MS Dhoni,500
13
+ Rakesh,20240322_1,CSK,MS Dhoni,500