jarajpu commited on
Commit
91f54ca
·
1 Parent(s): edfdf87

enhanced admin panel

Browse files
Files changed (6) hide show
  1. README.md +4 -48
  2. app.py +120 -69
  3. dis_predictions.csv +6 -0
  4. leaders/users.json +17 -0
  5. match_outcomes.json +5 -0
  6. requirements.txt +3 -0
README.md CHANGED
@@ -1,8 +1,8 @@
1
  ---
2
- title: DIS IPL Predictions
3
- emoji: 🦀
4
  colorFrom: red
5
- colorTo: pink
6
  sdk: streamlit
7
  sdk_version: 1.32.2
8
  app_file: app.py
@@ -10,48 +10,4 @@ pinned: false
10
  license: apache-2.0
11
  ---
12
 
13
- # DIS IPL Match Predictions App
14
-
15
- > "Predict, Compete, and Win 🏏 - Where Every Guess Counts! 🏆"
16
-
17
- 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.
18
-
19
- ## Getting Started
20
-
21
- ### Prerequisites
22
-
23
- - Python 3.x installed on your system
24
- - Git installed on your system
25
- - Pip package manager
26
-
27
- ### Installation
28
-
29
- 1. Clone this repository to your local machine using Git:
30
-
31
- ```bash
32
- git clone <repository_url>
33
- ```
34
-
35
- 2. Navigate to the cloned repository directory:
36
-
37
- ```bash
38
- cd ipl-match-predictions-app
39
- ```
40
-
41
- 3. Install the required Python dependencies using Pip:
42
-
43
- ```bash
44
- pip install -r requirements.txt
45
- ```
46
-
47
- ### Running The APP
48
-
49
- 1. After installing the dependencies, you can run the Streamlit app using the following command:
50
-
51
- ```bash
52
- streamlit run app.py
53
- ```
54
-
55
- 2. The app will start running locally and open in your default web browser.
56
-
57
- Thanks
 
1
  ---
2
+ title: Testing
3
+ emoji: 📈
4
  colorFrom: red
5
+ colorTo: red
6
  sdk: streamlit
7
  sdk_version: 1.32.2
8
  app_file: app.py
 
10
  license: apache-2.0
11
  ---
12
 
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py CHANGED
@@ -1,20 +1,52 @@
1
  import base64
 
2
  import json
3
- from datetime import datetime, timedelta
 
 
 
4
 
5
  import pandas as pd
6
  import pytz
7
  import streamlit as st
 
 
8
 
9
  # File paths as constants
10
  PREDICTIONS_CSV = 'dis_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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  # Initialize CSV and JSON files if they don't exist
19
  def initialize_files():
20
  # Initialize predictions CSV
@@ -122,34 +154,28 @@ def submit_prediction(
122
  st.error(f"Your bid points exceed the 20% limit of your total points. Maximum allowed bid points: {max_bid_points}")
123
  return
124
 
125
- # Ensure predictions DataFrame is loaded or initialized correctly
126
- try:
127
- predictions = load_predictions(PREDICTIONS_CSV)
128
- # Check if all expected columns are present, if not, reinitialize the DataFrame
129
- expected_columns = ['user_name', 'match_id', 'predicted_winner', 'predicted_motm', 'bid_points']
130
- if not all(column in predictions.columns for column in expected_columns):
131
- raise ValueError("CSV file missing one or more columns; Reinitializing.")
132
- except (FileNotFoundError, ValueError) as e:
133
- predictions = pd.DataFrame(columns=expected_columns)
134
-
135
- # Check for duplicate prediction for the same match by the same user
136
- if user_name != "Select a user...":
137
- existing_predictions = predictions[(predictions['user_name'] == user_name) & (predictions['match_id'] == match_id)]
138
- if not existing_predictions.empty:
139
- st.error("You've already submitted a prediction for this match.")
140
- return
141
 
142
- # Append new prediction
143
- new_prediction = {
144
  'user_name': user_name,
145
  'match_id': match_id,
146
  'predicted_winner': predicted_winner,
147
  'predicted_motm': predicted_motm,
148
- 'bid_points': bid_points
 
149
  }
 
 
 
 
 
 
 
 
 
150
 
151
- predictions = pd.concat([predictions, pd.DataFrame([new_prediction])], ignore_index=True)
152
- predictions.to_csv(PREDICTIONS_CSV, index=False)
153
  st.success("Prediction submitted successfully!")
154
 
155
 
@@ -203,16 +229,44 @@ def user_selection_and_prediction():
203
  else:
204
  st.write("No matches are scheduled for today.")
205
 
 
206
  def display_predictions():
207
  if st.button("Show Predictions"):
208
- try:
209
- todays_predictions = show_todays_match_predictions()
210
- if not todays_predictions.empty:
211
- st.dataframe(todays_predictions, hide_index=True)
212
- else:
213
- st.write("No predictions for today's matches yet.")
214
- except FileNotFoundError:
215
- st.write("No predictions have been submitted yet.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
 
217
  def display_leaderboard():
218
  if st.button("Show Leaderboard"):
@@ -232,21 +286,6 @@ def display_leaderboard():
232
  st.write("Leaderboard data not available.")
233
 
234
 
235
- # Show Predictions functionality
236
- def show_todays_match_predictions():
237
- # Get today's matches
238
- today_matches = get_today_matches()
239
- today_match_ids = [match['match_id'] for match in today_matches]
240
-
241
- # Load all predictions
242
- predictions = load_predictions(PREDICTIONS_CSV)
243
-
244
- # Filter predictions for today's matches
245
- today_predictions = predictions[predictions['match_id'].isin(today_match_ids)]
246
-
247
- return today_predictions
248
-
249
-
250
  # Streamlit UI
251
  encoded_image = get_base64_of_image(image_path)
252
  custom_css = f"""
@@ -309,9 +348,10 @@ with st.expander("Leaderboard 🏆"):
309
  ############################# Admin Panel ##################################
310
  ADMIN_PASSPHRASE = "admin123"
311
 
312
- def save_users(users):
313
- with open(USERS_JSON, 'w') as file:
314
- json.dump(users, file, indent=4)
 
315
 
316
 
317
  def save_match_outcomes(outcomes):
@@ -320,9 +360,13 @@ def save_match_outcomes(outcomes):
320
 
321
 
322
  def update_leaderboard_and_outcomes(match_id, winning_team, man_of_the_match):
 
 
 
323
  outcomes = load_data(OUTCOMES_JSON) # Load existing match outcomes
324
- predictions = load_predictions(PREDICTIONS_CSV) # Load existing predictions
325
- users = load_users(USERS_JSON) # Load existing user points
 
326
 
327
  # Directly update or add the match outcome
328
  outcome_exists = False
@@ -335,22 +379,23 @@ def update_leaderboard_and_outcomes(match_id, winning_team, man_of_the_match):
335
  outcomes.append({"match_id": match_id, "winning_team": winning_team, "man_of_the_match": man_of_the_match})
336
 
337
  # Update user points based on prediction accuracy
338
- for _, prediction in predictions.iterrows():
339
- if prediction['match_id'] == match_id:
340
- user_name = prediction['user_name']
341
- users[user_name] = users.get(user_name, 0) # Initialize user points if not present
342
-
343
- # Update points based on prediction accuracy
344
- if prediction['predicted_winner'] == winning_team:
345
- users[user_name] += 1000
346
- users[user_name] += prediction['bid_points']
347
- if prediction['predicted_motm'] == man_of_the_match:
348
- users[user_name] += 400 # Bonus for both correct predictions
349
- else:
350
- users[user_name] -= 200 + prediction['bid_points'] # Penalty for wrong team prediction
 
351
 
352
  save_match_outcomes(outcomes)
353
- save_users(users)
354
 
355
 
356
  with st.sidebar:
@@ -359,11 +404,17 @@ with st.sidebar:
359
 
360
  if admin_pass == ADMIN_PASSPHRASE:
361
  expander.success("Authenticated")
362
- matches = get_today_matches() # This function fetches today's matches
363
-
 
 
 
 
 
 
364
  # If matches are available, let the admin select one
365
- if matches:
366
- match_selection = expander.selectbox("Select Match", matches, format_func=lambda match: f"{match['teams'][0]} vs {match['teams'][1]}", key="match_selection")
367
  selected_match_id = match_selection['match_id']
368
  teams = match_selection['teams']
369
 
 
1
  import base64
2
+ import io
3
  import json
4
+ import os
5
+ import uuid
6
+ from datetime import datetime
7
+ from pathlib import Path
8
 
9
  import pandas as pd
10
  import pytz
11
  import streamlit as st
12
+ from datasets import load_dataset
13
+ from huggingface_hub import CommitScheduler, HfApi
14
 
15
  # File paths as constants
16
  PREDICTIONS_CSV = 'dis_predictions.csv'
17
+ USERS_JSON = 'leaders/users.json'
18
  MATCHES_JSON = 'matches.json'
19
  OUTCOMES_JSON = 'match_outcomes.json'
20
  PLAYERS_JSON = 'players.json'
21
  image_path = 'ipl_image.png'
22
 
23
 
24
+ PREDICTIONS_FOLDER = Path("predictions")
25
+ PREDICTIONS_FOLDER.mkdir(parents=True, exist_ok=True)
26
+
27
+ users_file = Path("leaders") / f"users.json"
28
+ USERS_FOLDER = users_file.parent
29
+ USERS_FOLDER.mkdir(parents=True, exist_ok=True)
30
+
31
+ # Initialize CommitScheduler
32
+ scheduler = CommitScheduler(
33
+ repo_id="DIS_IPL_Dataset",
34
+ repo_type="dataset",
35
+ folder_path=PREDICTIONS_FOLDER, # Local folder where predictions are saved temporarily
36
+ path_in_repo="predictions", # Path in dataset repo where predictions will be saved
37
+ every=120, # Push every 240 minutes (4 hours)
38
+ )
39
+
40
+ # Initialize CommitScheduler
41
+ scheduler = CommitScheduler(
42
+ repo_id="DIS_IPL_Dataset",
43
+ repo_type="dataset",
44
+ folder_path=USERS_FOLDER, # Local folder where users are saved temporarily
45
+ path_in_repo="leaders", # Path in dataset repo where predictions will be saved
46
+ every=120, # Push every 240 minutes (4 hours)
47
+ )
48
+
49
+
50
  # Initialize CSV and JSON files if they don't exist
51
  def initialize_files():
52
  # Initialize predictions CSV
 
154
  st.error(f"Your bid points exceed the 20% limit of your total points. Maximum allowed bid points: {max_bid_points}")
155
  return
156
 
157
+ prediction_id = uuid.uuid4().hex
158
+ prediction_date = datetime.now().strftime('%Y-%m-%d')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
 
160
+ prediction_data = {
161
+ 'prediction_id': prediction_id,
162
  'user_name': user_name,
163
  'match_id': match_id,
164
  'predicted_winner': predicted_winner,
165
  'predicted_motm': predicted_motm,
166
+ 'bid_points': bid_points,
167
+ 'prediction_date': prediction_date # Include the prediction date
168
  }
169
+
170
+ # Construct the filename to include match_id for easier retrieval
171
+ prediction_file_name = f"prediction_{match_id}_{prediction_id}.json"
172
+ prediction_file = PREDICTIONS_FOLDER / prediction_file_name
173
+
174
+ with scheduler.lock:
175
+ with prediction_file.open("a") as file:
176
+ file.write(json.dumps(prediction_data))
177
+ file.write("\n")
178
 
 
 
179
  st.success("Prediction submitted successfully!")
180
 
181
 
 
229
  else:
230
  st.write("No matches are scheduled for today.")
231
 
232
+
233
  def display_predictions():
234
  if st.button("Show Predictions"):
235
+ all_predictions = []
236
+
237
+ # Check if the directory exists
238
+ if not os.path.exists(PREDICTIONS_FOLDER):
239
+ st.write("No predictions directory found.")
240
+ return
241
+
242
+ # List all JSON files in the directory
243
+ for filename in os.listdir(PREDICTIONS_FOLDER):
244
+ if filename.endswith('.json'):
245
+ file_path = os.path.join(PREDICTIONS_FOLDER, filename)
246
+ # Read each JSON file and append its contents to the list
247
+ with open(file_path, 'r') as file:
248
+ prediction = json.load(file)
249
+ all_predictions.append(prediction)
250
+
251
+ # Convert the list of dictionaries to a DataFrame
252
+ predictions_df = pd.DataFrame(all_predictions)
253
+
254
+ if not predictions_df.empty:
255
+ predictions_df['prediction_date'] = predictions_df.apply(lambda x: datetime.strptime(x['prediction_date'], '%Y-%m-%d'), axis=1)
256
+
257
+ # Filter for today's predictions
258
+ today_str = datetime.now().strftime('%Y-%m-%d')
259
+ todays_predictions = predictions_df[predictions_df['prediction_date'] == today_str]
260
+
261
+ # Remove the 'prediction_id' column if it exists
262
+ if 'prediction_id' in todays_predictions.columns:
263
+ todays_predictions = todays_predictions.drop(columns=['prediction_id', 'prediction_date'])
264
+
265
+
266
+ st.dataframe(todays_predictions, hide_index=True)
267
+ else:
268
+ st.write("No predictions for today's matches yet.")
269
+
270
 
271
  def display_leaderboard():
272
  if st.button("Show Leaderboard"):
 
286
  st.write("Leaderboard data not available.")
287
 
288
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289
  # Streamlit UI
290
  encoded_image = get_base64_of_image(image_path)
291
  custom_css = f"""
 
348
  ############################# Admin Panel ##################################
349
  ADMIN_PASSPHRASE = "admin123"
350
 
351
+ def fetch_latest_predictions(match_id):
352
+ dataset = load_dataset("Jay-Rajput/DIS_IPL_Dataset", config_name="predictions")
353
+ predictions = dataset['train'].filter(lambda example: example['match_id'] == match_id)
354
+ return predictions
355
 
356
 
357
  def save_match_outcomes(outcomes):
 
360
 
361
 
362
  def update_leaderboard_and_outcomes(match_id, winning_team, man_of_the_match):
363
+ # Fetch latest predictions from the dataset repo
364
+ predictions = fetch_latest_predictions(match_id)
365
+
366
  outcomes = load_data(OUTCOMES_JSON) # Load existing match outcomes
367
+ # Load existing match outcomes and user data from the test split
368
+ dataset = load_dataset("Jay-Rajput/DIS_IPL_Dataset", config_name="leaders")
369
+ users = {item['user_name']: item for item in dataset['train']}
370
 
371
  # Directly update or add the match outcome
372
  outcome_exists = False
 
379
  outcomes.append({"match_id": match_id, "winning_team": winning_team, "man_of_the_match": man_of_the_match})
380
 
381
  # Update user points based on prediction accuracy
382
+ for prediction in predictions:
383
+ user_name = prediction['user_name']
384
+ # Initialize user points if not present
385
+ if user_name not in users:
386
+ users[user_name] = {'user_name': user_name, 'points': 0}
387
+
388
+ # Update points based on prediction accuracy
389
+ if prediction['predicted_winner'] == winning_team:
390
+ users[user_name] += 1000
391
+ users[user_name] += prediction['bid_points']
392
+ if prediction['predicted_motm'] == man_of_the_match:
393
+ users[user_name] += 400 # Bonus for both correct predictions
394
+ else:
395
+ users[user_name] -= 200 + prediction['bid_points'] # Penalty for wrong team prediction
396
 
397
  save_match_outcomes(outcomes)
398
+ users.save_to_disk(USERS_JSON)
399
 
400
 
401
  with st.sidebar:
 
404
 
405
  if admin_pass == ADMIN_PASSPHRASE:
406
  expander.success("Authenticated")
407
+
408
+ all_matches = load_data(MATCHES_JSON)
409
+ match_outcomes = load_data(OUTCOMES_JSON)
410
+ submitted_match_ids = [outcome["match_id"] for outcome in match_outcomes]
411
+
412
+ # Filter matches to those that do not have outcomes submitted yet
413
+ matches_without_outcomes = [match for match in all_matches if match["match_id"] not in submitted_match_ids]
414
+
415
  # If matches are available, let the admin select one
416
+ if matches_without_outcomes:
417
+ match_selection = expander.selectbox("Select Match", matches_without_outcomes, format_func=lambda match: f"{match['teams'][0]} vs {match['teams'][1]}", key="match_selection")
418
  selected_match_id = match_selection['match_id']
419
  teams = match_selection['teams']
420
 
dis_predictions.csv CHANGED
@@ -3,3 +3,9 @@ Sunil,20240325_6,RCB,Glenn Maxwell,900
3
  Sahil,20240325_6,RCB,Virat Kohli,350
4
  Vinay,20240325_6,RCB,Faf du Plessis,200
5
  Megha,20240325_6,RCB,Virat Kohli,500
 
 
 
 
 
 
 
3
  Sahil,20240325_6,RCB,Virat Kohli,350
4
  Vinay,20240325_6,RCB,Faf du Plessis,200
5
  Megha,20240325_6,RCB,Virat Kohli,500
6
+ Jay,20240325_6,RCB,Virat Kohli,200
7
+ Sai,20240325_6,RCB,Glenn Maxwell,620
8
+ Haaris,20240325_6,RCB,Virat Kohli,1200
9
+ Naveein,20240325_6,RCB,Faf du Plessis,500
10
+ Praveen,20240325_6,RCB,Faf du Plessis,1800
11
+ Kishore,20240325_6,RCB,Glenn Maxwell,500
leaders/users.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "Arpit": 11300,
3
+ "Ganesh": 5750,
4
+ "Haaris": 6000,
5
+ "Jay": 6500,
6
+ "Kishore": 5700,
7
+ "Megha": 5900,
8
+ "Naveein": 6300,
9
+ "Neha": 5600,
10
+ "Praveen": 9000,
11
+ "Rakesh": 6500,
12
+ "Sai": 3100,
13
+ "Sahil": 6600,
14
+ "Sunil": 4501,
15
+ "Vaibhav": 5600,
16
+ "Vinay": 5300
17
+ }
match_outcomes.json CHANGED
@@ -23,5 +23,10 @@
23
  "match_id": "20240324_5",
24
  "winning_team": "GT",
25
  "man_of_the_match": "B Sai Sudharsan"
 
 
 
 
 
26
  }
27
  ]
 
23
  "match_id": "20240324_5",
24
  "winning_team": "GT",
25
  "man_of_the_match": "B Sai Sudharsan"
26
+ },
27
+ {
28
+ "match_id": "20240325_6",
29
+ "winning_team": "RCB",
30
+ "man_of_the_match": "Virat Kohli"
31
  }
32
  ]
requirements.txt CHANGED
@@ -1,3 +1,6 @@
 
 
1
  pandas
2
  pytz
 
3
  streamlit
 
1
+ datasets
2
+ huggingface_hub
3
  pandas
4
  pytz
5
+ requests
6
  streamlit