Muthuraja18 commited on
Commit
41bc6b4
·
verified ·
1 Parent(s): 15e21f9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -13
app.py CHANGED
@@ -173,6 +173,7 @@ def generate_ai_questions(topic, num_questions=5, gid=None, questions_db=None):
173
  ]
174
 
175
  RULES:
 
176
  - ONLY valid JSON array.
177
  - No extra text.
178
  - No markdown.
@@ -517,7 +518,7 @@ def show_game_leaderboard(game_id):
517
 
518
  # 2️⃣ Online CSV (Global Public CSV File)
519
  try:
520
- ONLINE_CSV_URL = "https://yourdomain.com/leaderboard_online.csv"
521
  online_df = pd.read_csv(ONLINE_CSV_URL)
522
 
523
  if "game_id" in online_df.columns:
@@ -557,17 +558,28 @@ def show_game_leaderboard(game_id):
557
  # ---------------------------
558
  # Get weekly leaderboard
559
  # ---------------------------
560
- def get_weekly_leaderboard(limit=10):
561
  """
562
- Returns top scores for the current week (Mon–Sun UTC)
 
563
  """
 
564
  mode = st.session_state.get("mode_selection", "Offline")
565
  rows = []
566
 
 
567
  if mode == "Online":
568
  ok, _ = init_firebase_if_needed()
569
  if ok:
570
- rows = fb_get("/leaderboard") or []
 
 
 
 
 
 
 
 
571
  else:
572
  try:
573
  rows = pd.read_csv(LEADERBOARD_FILE).to_dict("records")
@@ -577,44 +589,77 @@ def get_weekly_leaderboard(limit=10):
577
  if not rows:
578
  return []
579
 
580
- # Convert timestamps safely to UTC
581
  for r in rows:
582
  ts = r.get("timestamp")
583
- if ts:
584
- r["timestamp"] = pd.to_datetime(ts, errors="coerce", utc=True)
585
 
586
  now = pd.Timestamp.utcnow()
587
- # Start of the current week (Monday)
588
  start_of_week = now - pd.Timedelta(days=now.weekday())
589
 
590
- weekly = [r for r in rows if r.get("timestamp") is not pd.NaT and r["timestamp"] >= start_of_week]
591
- weekly.sort(key=lambda x: x.get("score", 0), reverse=True)
 
 
 
 
 
 
 
 
 
592
  return weekly[:limit]
593
 
594
  # ---------------------------
595
  # Get all-time leaderboard
596
  # ---------------------------
597
- def get_alltime_leaderboard(limit=10):
598
  """
599
  Returns top scores of all time
 
600
  """
 
601
  mode = st.session_state.get("mode_selection", "Offline")
602
  rows = []
603
 
 
604
  if mode == "Online":
605
  ok, _ = init_firebase_if_needed()
 
606
  if ok:
607
- rows = fb_get("/leaderboard") or []
 
 
 
 
 
 
 
 
 
 
 
 
608
  else:
609
  try:
610
  rows = pd.read_csv(LEADERBOARD_FILE).to_dict("records")
611
  except FileNotFoundError:
612
  rows = []
613
 
614
- rows.sort(key=lambda x: x.get("score", 0), reverse=True)
 
 
 
 
 
 
 
 
615
  return rows[:limit]
616
 
617
 
 
 
618
  # ----------------- Session & Presence helpers -----------------
619
  def now_iso():
620
  return datetime.utcnow().isoformat()
@@ -1105,6 +1150,13 @@ def home_page():
1105
 
1106
  unified_set(f"games/{active_game_id}", game)
1107
 
 
 
 
 
 
 
 
1108
 
1109
  def create_game(host=None, topics=[], num_questions=5, auto_close=True, ai_topic=None):
1110
  games = unified_get("games") or {}
 
173
  ]
174
 
175
  RULES:
176
+ -Different questions
177
  - ONLY valid JSON array.
178
  - No extra text.
179
  - No markdown.
 
518
 
519
  # 2️⃣ Online CSV (Global Public CSV File)
520
  try:
521
+ ONLINE_CSV_URL = "leaderboard_online.csv"
522
  online_df = pd.read_csv(ONLINE_CSV_URL)
523
 
524
  if "game_id" in online_df.columns:
 
558
  # ---------------------------
559
  # Get weekly leaderboard
560
  # ---------------------------
561
+ def get_weekly_leaderboard(limit=10, game_id=None):
562
  """
563
+ Returns top scores for current week (UTC)
564
+ Optional: filter by game_id
565
  """
566
+
567
  mode = st.session_state.get("mode_selection", "Offline")
568
  rows = []
569
 
570
+ # ---------------- ONLINE MODE ----------------
571
  if mode == "Online":
572
  ok, _ = init_firebase_if_needed()
573
  if ok:
574
+ fb_rows = fb_get("/leaderboard") or []
575
+
576
+ # 🔥 FIX: Convert dict → list safely
577
+ if isinstance(fb_rows, dict):
578
+ fb_rows = list(fb_rows.values())
579
+
580
+ rows.extend(fb_rows)
581
+
582
+ # ---------------- OFFLINE MODE ----------------
583
  else:
584
  try:
585
  rows = pd.read_csv(LEADERBOARD_FILE).to_dict("records")
 
589
  if not rows:
590
  return []
591
 
592
+ # 🔥 Convert timestamps safely
593
  for r in rows:
594
  ts = r.get("timestamp")
595
+ r["timestamp"] = pd.to_datetime(ts, errors="coerce", utc=True)
 
596
 
597
  now = pd.Timestamp.utcnow()
 
598
  start_of_week = now - pd.Timedelta(days=now.weekday())
599
 
600
+ weekly = [
601
+ r for r in rows
602
+ if pd.notna(r["timestamp"]) and r["timestamp"] >= start_of_week
603
+ ]
604
+
605
+ # Optional filter by game
606
+ if game_id:
607
+ weekly = [r for r in weekly if r.get("game_id") == game_id]
608
+
609
+ weekly.sort(key=lambda x: float(x.get("score", 0)), reverse=True)
610
+
611
  return weekly[:limit]
612
 
613
  # ---------------------------
614
  # Get all-time leaderboard
615
  # ---------------------------
616
+ def get_alltime_leaderboard(limit=10, game_id=None):
617
  """
618
  Returns top scores of all time
619
+ Optional: filter by game_id
620
  """
621
+
622
  mode = st.session_state.get("mode_selection", "Offline")
623
  rows = []
624
 
625
+ # ---------------- ONLINE MODE ----------------
626
  if mode == "Online":
627
  ok, _ = init_firebase_if_needed()
628
+
629
  if ok:
630
+ fb_rows = fb_get("/leaderboard") or []
631
+ if isinstance(fb_rows, dict):
632
+ fb_rows = list(fb_rows.values())
633
+ rows.extend(fb_rows)
634
+
635
+ # Optional online CSV
636
+ try:
637
+ online_df = pd.read_csv("leaderboard_online.csv")
638
+ rows.extend(online_df.to_dict("records"))
639
+ except:
640
+ pass
641
+
642
+ # ---------------- OFFLINE MODE ----------------
643
  else:
644
  try:
645
  rows = pd.read_csv(LEADERBOARD_FILE).to_dict("records")
646
  except FileNotFoundError:
647
  rows = []
648
 
649
+ if not rows:
650
+ return []
651
+
652
+ # Optional filter
653
+ if game_id:
654
+ rows = [r for r in rows if r.get("game_id") == game_id]
655
+
656
+ rows.sort(key=lambda x: float(x.get("score", 0)), reverse=True)
657
+
658
  return rows[:limit]
659
 
660
 
661
+
662
+
663
  # ----------------- Session & Presence helpers -----------------
664
  def now_iso():
665
  return datetime.utcnow().isoformat()
 
1150
 
1151
  unified_set(f"games/{active_game_id}", game)
1152
 
1153
+ st.subheader("🏆 All-Time Global Top 10")
1154
+ alltime = get_alltime_leaderboard()
1155
+
1156
+ for i, r in enumerate(alltime, 1):
1157
+ st.write(f"{i}. {r.get('avatar','🎮')} **{r['name']}** — {r['score']} pts")
1158
+
1159
+
1160
 
1161
  def create_game(host=None, topics=[], num_questions=5, auto_close=True, ai_topic=None):
1162
  games = unified_get("games") or {}