Jay-Rajput commited on
Commit
a8e6a5d
·
1 Parent(s): c7ca941

new changes

Browse files
Files changed (1) hide show
  1. app.py +87 -43
app.py CHANGED
@@ -4,7 +4,7 @@ import os
4
  import uuid
5
  from datetime import datetime
6
  from pathlib import Path
7
-
8
  import pandas as pd
9
  import pytz
10
  import streamlit as st
@@ -61,25 +61,38 @@ scheduler = CommitScheduler(
61
 
62
  def load_data(file_path):
63
  """
64
- Load data from a JSON or CSV file.
65
 
66
  Args:
67
  file_path (str): The path to the file to load.
68
 
69
  Returns:
70
- pd.DataFrame or dict: The loaded data.
71
  """
72
  try:
73
  if file_path.endswith('.json'):
74
- with open(file_path, 'r') as file:
75
- return json.load(file)
 
 
 
 
76
  elif file_path.endswith('.csv'):
77
- return pd.read_csv(file_path)
 
 
 
 
78
  except FileNotFoundError:
79
  if file_path.endswith('.json'):
80
  return {}
81
  elif file_path.endswith('.csv'):
82
  return pd.DataFrame()
 
 
 
 
 
83
 
84
 
85
  def get_base64_of_image(path):
@@ -211,49 +224,80 @@ def calculate_max_bid_points(user_name):
211
  return max_bid_points
212
 
213
 
214
- def load_users(USERS_JSON):
215
- """Load users data with fallback to Hugging Face"""
216
  try:
217
- # First try local file
218
- if os.path.exists(USERS_JSON):
219
- with open(USERS_JSON, 'r', encoding='utf-8') as file:
220
- return json.load(file)
221
- # If not found, load from Hugging Face
222
- return load_and_process_users()
 
 
 
 
 
 
 
 
 
 
 
 
223
  except Exception as e:
224
- st.error(f"Error loading users data: {e}")
225
  return {}
226
 
227
 
228
  def user_selection_and_prediction():
229
- users = list(load_data(USERS_JSON))
230
- user_name = st.selectbox("Select User", ["Select a user..."] + users)
231
-
232
- max_bid_points = None
233
- if user_name != "Select a user...":
234
- max_bid_points = calculate_max_bid_points(user_name)
235
- st.write(f"Maximum bid points you can submit: {max_bid_points}")
236
-
237
- matches = get_today_matches()
238
- if matches:
239
- match_choice = st.selectbox("Select Today's Match", matches, format_func=lambda match: f"{match['teams'][0]} vs {match['teams'][1]}")
240
- match_id = match_choice['match_id']
241
- teams = match_choice['teams']
242
-
243
- predicted_winner = st.selectbox("Predicted Winner", teams)
244
-
245
- player_list = load_data(PLAYERS_JSON)
246
- predicted_motm = ""
247
- if predicted_winner in player_list:
248
- players = player_list[predicted_winner]
249
- predicted_motm = st.selectbox("Predicted Man of the Match", players)
250
-
251
- bid_points = st.number_input("Bid Points", min_value=0, value=100, format="%d")
252
-
253
- if st.button("Submit Prediction"):
254
- submit_prediction(user_name, match_id, predicted_winner, predicted_motm, bid_points, max_bid_points)
255
- else:
256
- st.write("No matches are scheduled for today.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
 
258
 
259
  def display_predictions():
 
4
  import uuid
5
  from datetime import datetime
6
  from pathlib import Path
7
+ import fcntl
8
  import pandas as pd
9
  import pytz
10
  import streamlit as st
 
61
 
62
  def load_data(file_path):
63
  """
64
+ Load data from a JSON or CSV file with better error handling.
65
 
66
  Args:
67
  file_path (str): The path to the file to load.
68
 
69
  Returns:
70
+ dict or pd.DataFrame: The loaded data. Returns empty dict/DataFrame on error.
71
  """
72
  try:
73
  if file_path.endswith('.json'):
74
+ with open(file_path, 'r', encoding='utf-8') as file:
75
+ try:
76
+ return json.load(file)
77
+ except json.JSONDecodeError:
78
+ st.error(f"Invalid JSON in {file_path}. Loading empty data.")
79
+ return {}
80
  elif file_path.endswith('.csv'):
81
+ try:
82
+ return pd.read_csv(file_path)
83
+ except Exception as e:
84
+ st.error(f"Error reading CSV {file_path}: {e}")
85
+ return pd.DataFrame()
86
  except FileNotFoundError:
87
  if file_path.endswith('.json'):
88
  return {}
89
  elif file_path.endswith('.csv'):
90
  return pd.DataFrame()
91
+ except Exception as e:
92
+ st.error(f"Unexpected error loading {file_path}: {e}")
93
+ if file_path.endswith('.json'):
94
+ return {}
95
+ return pd.DataFrame()
96
 
97
 
98
  def get_base64_of_image(path):
 
224
  return max_bid_points
225
 
226
 
227
+ def load_users(users_json_path):
228
+ """Load users data with file locking to prevent corruption"""
229
  try:
230
+ if not os.path.exists(users_json_path):
231
+ return {}
232
+
233
+ with open(users_json_path, 'r', encoding='utf-8') as f:
234
+ # Acquire shared lock for reading
235
+ fcntl.flock(f, fcntl.LOCK_SH)
236
+ try:
237
+ data = json.load(f)
238
+ # Validate data structure
239
+ if not all(isinstance(v, dict) and 'points' in v for v in data.values()):
240
+ st.error("Invalid users data structure")
241
+ return {}
242
+ return data
243
+ except json.JSONDecodeError:
244
+ st.error("Invalid JSON in users file")
245
+ return {}
246
+ finally:
247
+ fcntl.flock(f, fcntl.LOCK_UN)
248
  except Exception as e:
249
+ st.error(f"Error loading users: {e}")
250
  return {}
251
 
252
 
253
  def user_selection_and_prediction():
254
+ try:
255
+ users_data = load_users(USERS_JSON) # Use our improved load_users function
256
+ if not users_data:
257
+ st.error("Failed to load users data. Please try again later.")
258
+ return
259
+
260
+ users = list(users_data.keys())
261
+ user_name = st.selectbox("Select User", ["Select a user..."] + users)
262
+
263
+ max_bid_points = None
264
+ if user_name != "Select a user...":
265
+ max_bid_points = calculate_max_bid_points(user_name)
266
+ st.write(f"Maximum bid points you can submit: {max_bid_points}")
267
+
268
+ matches = get_today_matches()
269
+ if matches:
270
+ match_choice = st.selectbox(
271
+ "Select Today's Match",
272
+ matches,
273
+ format_func=lambda match: f"{match['teams'][0]} vs {match['teams'][1]}"
274
+ )
275
+ match_id = match_choice['match_id']
276
+ teams = match_choice['teams']
277
+
278
+ predicted_winner = st.selectbox("Predicted Winner", teams)
279
+
280
+ player_list = load_data(PLAYERS_JSON)
281
+ predicted_motm = ""
282
+ if predicted_winner in player_list:
283
+ players = player_list[predicted_winner]
284
+ predicted_motm = st.selectbox("Predicted Man of the Match", players)
285
+
286
+ bid_points = st.number_input("Bid Points", min_value=0, value=100, format="%d")
287
+
288
+ if st.button("Submit Prediction"):
289
+ submit_prediction(
290
+ user_name,
291
+ match_id,
292
+ predicted_winner,
293
+ predicted_motm,
294
+ bid_points,
295
+ max_bid_points
296
+ )
297
+ else:
298
+ st.write("No matches are scheduled for today.")
299
+ except Exception as e:
300
+ st.error(f"Error in prediction submission: {e}")
301
 
302
 
303
  def display_predictions():