Joffrey Thomas commited on
Commit
add3bed
·
1 Parent(s): 02817fd

update upload logic

Browse files
Files changed (2) hide show
  1. app.py +18 -17
  2. data_manager.py +51 -30
app.py CHANGED
@@ -873,6 +873,22 @@ with gr.Blocks(css=APP_CSS, title="LLM GeoGuessr") as demo:
873
  rnd['ai_score'] = score_from_distance_km(ai_dist_km)
874
  # Store the AI analysis text for later recording
875
  rnd['ai_analysis'] = last_text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
876
  except Exception as e:
877
  yield "", txt + f"\n\n[Error] {e}"
878
  return
@@ -946,23 +962,8 @@ with gr.Blocks(css=APP_CSS, title="LLM GeoGuessr") as demo:
946
  total_human = sum(float(r.get('human_score', 0.0)) for r in sess.get('rounds', []))
947
  total_ai = sum(float(r.get('ai_score', 0.0)) for r in sess.get('rounds', []))
948
 
949
- # Prepare detailed rounds data for recording
950
- rounds_data = []
951
- for i, r in enumerate(sess.get('rounds', [])):
952
- round_record = {
953
- "round_number": i + 1,
954
- "actual_location": {"lat": r.get('lat'), "lng": r.get('lng')},
955
- "human_guess": r.get('human_guess'),
956
- "human_distance_km": r.get('human_distance_km'),
957
- "human_score": r.get('human_score'),
958
- "ai_guess": r.get('ai_guess'),
959
- "ai_distance_km": r.get('ai_distance_km'),
960
- "ai_score": r.get('ai_score'),
961
- "ai_analysis": r.get('ai_analysis', ''),
962
- }
963
- rounds_data.append(round_record)
964
-
965
- data_manager.record_game(username, total_human, rounds_data)
966
 
967
  winner_message = "It's a tie!"
968
  if total_human > total_ai:
 
873
  rnd['ai_score'] = score_from_distance_km(ai_dist_km)
874
  # Store the AI analysis text for later recording
875
  rnd['ai_analysis'] = last_text
876
+
877
+ # Record this round's data immediately to prevent abuse
878
+ sess = user_sessions.get(username, {})
879
+ round_idx = next((i for i, rr in enumerate(sess.get('rounds', [])) if rr['id'] == rid), 0) + 1
880
+ round_record = {
881
+ "round_number": round_idx,
882
+ "actual_location": {"lat": rnd.get('lat'), "lng": rnd.get('lng')},
883
+ "human_guess": rnd.get('human_guess'),
884
+ "human_distance_km": rnd.get('human_distance_km'),
885
+ "human_score": rnd.get('human_score'),
886
+ "ai_guess": rnd.get('ai_guess'),
887
+ "ai_distance_km": rnd.get('ai_distance_km'),
888
+ "ai_score": rnd.get('ai_score'),
889
+ "ai_analysis": rnd.get('ai_analysis', ''),
890
+ }
891
+ data_manager.update_game_record(username, round_data=round_record)
892
  except Exception as e:
893
  yield "", txt + f"\n\n[Error] {e}"
894
  return
 
962
  total_human = sum(float(r.get('human_score', 0.0)) for r in sess.get('rounds', []))
963
  total_ai = sum(float(r.get('ai_score', 0.0)) for r in sess.get('rounds', []))
964
 
965
+ # Update the final score (rounds already recorded incrementally)
966
+ data_manager.update_game_record(username, final_score=total_human)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
967
 
968
  winner_message = "It's a tie!"
969
  if total_human > total_ai:
data_manager.py CHANGED
@@ -41,46 +41,60 @@ def get_todays_games(token: str) -> list:
41
  return []
42
 
43
  def has_user_played_today(username: str, todays_games: list) -> bool:
44
- """Checks if a user's record already exists in today's games."""
45
- return any(game.get("username") == username for game in todays_games)
 
 
 
46
 
47
- def record_game(username: str, score: float, rounds_data: list = None):
 
 
 
 
 
 
 
48
  """
49
- Records a completed game to the daily records file on the HF Hub.
50
- This function reads the existing file, appends the new record, and uploads it back.
51
- It uses the server's write token from environment variables.
52
 
53
  Args:
54
  username: The player's username
55
- score: Total score for the game
56
- rounds_data: List of round details including guesses, scores, and AI analysis
57
  """
58
  write_token = os.getenv("HF_TOKEN", "")
59
  if not write_token:
60
- print("Warning: Server HF_TOKEN not set. Cannot record game score.")
61
  return
62
 
63
  try:
64
- # Fetch the latest records using the write token to ensure we have the most recent data
65
  todays_games = get_todays_games(token=write_token)
66
-
67
- # Final check to prevent duplicate entries in case of concurrent games
68
- # Only check if BLOCK_MULTIPLE_GAMES is enabled
69
- if BLOCK_MULTIPLE_GAMES and has_user_played_today(username, todays_games):
70
- print(f"User {username} has already played today. Skipping record.")
71
- return
72
-
73
- game_record = {
74
- "username": username,
75
- "score": score,
76
- "timestamp": datetime.now(timezone.utc).isoformat(),
77
- }
78
 
79
- # Add detailed rounds data if provided
80
- if rounds_data:
81
- game_record["rounds"] = rounds_data
82
-
83
- todays_games.append(game_record)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
  filepath_in_repo = get_todays_records_path()
86
 
@@ -94,12 +108,19 @@ def record_game(username: str, score: float, rounds_data: list = None):
94
  repo_id=DATASET_REPO,
95
  repo_type="dataset",
96
  token=write_token,
97
- commit_message=f"Game result for {username}"
98
  )
99
- print(f"Successfully recorded game for {username} with score {score}")
100
 
101
  except Exception as e:
102
- print(f"Error recording game for {username}: {e}")
103
  finally:
104
  if 'tmp_file_path' in locals() and os.path.exists(tmp_file_path):
105
  os.remove(tmp_file_path)
 
 
 
 
 
 
 
 
41
  return []
42
 
43
  def has_user_played_today(username: str, todays_games: list) -> bool:
44
+ """Checks if a user has completed a game today."""
45
+ for game in todays_games:
46
+ if game.get("username") == username and game.get("completed", False):
47
+ return True
48
+ return False
49
 
50
+ def get_user_game_today(username: str, todays_games: list) -> dict:
51
+ """Gets the user's game record for today, if it exists."""
52
+ for game in todays_games:
53
+ if game.get("username") == username:
54
+ return game
55
+ return None
56
+
57
+ def update_game_record(username: str, round_data: dict = None, final_score: float = None):
58
  """
59
+ Updates or creates a game record for a user after each round.
60
+ This ensures data is recorded incrementally and prevents abuse.
 
61
 
62
  Args:
63
  username: The player's username
64
+ round_data: Single round details to append to the record
65
+ final_score: Final total score (only set when game is complete)
66
  """
67
  write_token = os.getenv("HF_TOKEN", "")
68
  if not write_token:
69
+ print("Warning: Server HF_TOKEN not set. Cannot record game data.")
70
  return
71
 
72
  try:
73
+ # Fetch the latest records
74
  todays_games = get_todays_games(token=write_token)
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
+ # Find existing game record for this user today
77
+ existing_game = get_user_game_today(username, todays_games)
78
+
79
+ if existing_game:
80
+ # Update existing record
81
+ if round_data:
82
+ if "rounds" not in existing_game:
83
+ existing_game["rounds"] = []
84
+ existing_game["rounds"].append(round_data)
85
+ if final_score is not None:
86
+ existing_game["score"] = final_score
87
+ existing_game["completed"] = True
88
+ else:
89
+ # Create new game record
90
+ game_record = {
91
+ "username": username,
92
+ "score": 0, # Will be updated when game completes
93
+ "timestamp": datetime.now(timezone.utc).isoformat(),
94
+ "rounds": [round_data] if round_data else [],
95
+ "completed": False
96
+ }
97
+ todays_games.append(game_record)
98
 
99
  filepath_in_repo = get_todays_records_path()
100
 
 
108
  repo_id=DATASET_REPO,
109
  repo_type="dataset",
110
  token=write_token,
111
+ commit_message=f"Update game for {username}"
112
  )
113
+ print(f"Successfully updated game record for {username}")
114
 
115
  except Exception as e:
116
+ print(f"Error updating game record for {username}: {e}")
117
  finally:
118
  if 'tmp_file_path' in locals() and os.path.exists(tmp_file_path):
119
  os.remove(tmp_file_path)
120
+
121
+ def record_game(username: str, score: float, rounds_data: list = None):
122
+ """
123
+ Legacy function - now just calls update_game_record with final score.
124
+ Kept for backwards compatibility.
125
+ """
126
+ update_game_record(username, final_score=score)