H3y-sam commited on
Commit
0800a6a
Β·
verified Β·
1 Parent(s): c00fb9c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +153 -228
app.py CHANGED
@@ -9,7 +9,8 @@ Architecture:
9
 
10
  Deployment Steps:
11
  1. Upload this file + all others to your HF Space.
12
- 2. Set Secrets: TELEGRAM_TOKEN, ADMIN_ID, WEBHOOK_URL (your Space URL).
 
13
  3. The Space boots β†’ automatically sets the Telegram webhook.
14
  """
15
 
@@ -39,11 +40,13 @@ logging.basicConfig(
39
  logger = logging.getLogger(__name__)
40
 
41
  # ── Config ───────────────────────────────────────────────────────────────────
42
- TOKEN = os.environ.get("TELEGRAM_TOKEN", "")
43
- ADMIN_ID = int(os.environ.get("ADMIN_ID", "0"))
44
- WEBHOOK_URL = os.environ.get("WEBHOOK_URL", "").rstrip("/")
45
- # Cloudflare Worker proxy URL β€” set this in HF Secrets to bypass outbound blocks.
46
- # Worker must forward to https://api.telegram.org
 
 
47
  # Example: https://dry-flower-3493.h3y-samm.workers.dev/bot
48
  TELEGRAM_API_BASE = os.environ.get(
49
  "TELEGRAM_API_BASE",
@@ -95,8 +98,6 @@ fastapi_app = FastAPI()
95
  async def telegram_webhook(request: Request):
96
  """Receive Telegram update and process it."""
97
  if not _bot_ready:
98
- # Bot hasn't connected to Telegram API yet β€” return 200 so Telegram
99
- # doesn't drop the webhook, but don't process the update yet.
100
  logger.warning("Webhook received before bot is ready β€” ignoring update.")
101
  return Response(content="Not ready yet", status_code=200)
102
  data = await request.json()
@@ -110,26 +111,12 @@ async def health():
110
  return {"status": "ok", "bot_ready": _bot_ready, "db": db.DB_PATH}
111
 
112
 
113
- # ── Admin password (set ADMIN_PASSWORD secret in HF Space) ───────────────────
114
- ADMIN_PASSWORD = os.environ.get("ADMIN_PASSWORD", "admin123")
115
-
116
  # ── Dashboard helper functions ────────────────────────────────────────────────
117
 
118
  def _status_badge(status: str) -> str:
119
  return {"approved": "βœ…", "pending": "⏳", "rejected": "🚫"}.get(status, "❓")
120
 
121
 
122
- def do_login(password: str):
123
- if password.strip() == ADMIN_PASSWORD:
124
- return (
125
- True,
126
- gr.update(visible=False), # hide login panel
127
- gr.update(visible=True), # show dashboard
128
- "", # clear error
129
- )
130
- return False, gr.update(visible=True), gr.update(visible=False), "❌ Wrong password."
131
-
132
-
133
  def get_stats():
134
  groups = db.get_all_groups()
135
  quizzes = db.list_quizzes()
@@ -228,16 +215,16 @@ def do_broadcast(quiz_id_str: str):
228
  return f"❌ Quiz #{qid} not found."
229
  if not _bot_ready:
230
  return "❌ Bot is not connected yet. Wait for 'Bot initialized successfully.' in logs."
231
- # Schedule coroutine on the startup thread's event loop
232
- import threading
233
- for t in threading.enumerate():
234
- if t.name == "startup" and hasattr(t, "_target"):
235
- break
236
- # Post to the background loop via call_soon_threadsafe
237
  _startup_loop.call_soon_threadsafe(
238
  lambda: asyncio.ensure_future(_bq(ptb_app, qid), loop=_startup_loop)
239
  )
240
- return f"πŸ“‘ Broadcast started for quiz #{qid} β€” {len(quiz['questions'])} questions to {len(db.get_approved_groups())} groups!"
 
 
 
 
241
  except Exception as e:
242
  return f"❌ {e}"
243
 
@@ -246,228 +233,170 @@ def get_global_lb_df():
246
  rows = db.get_global_leaderboard()
247
  medals = ["πŸ₯‡", "πŸ₯ˆ", "πŸ₯‰"]
248
  return [
249
- [medals[i] if i < 3 else f"#{i+1}", row.get("username") or "Anonymous",
250
- row.get("score", 0), row.get("total", 0),
 
 
251
  f"{row.get('score',0)/row.get('total',1)*100:.0f}%" if row.get("total") else "β€”"]
252
  for i, row in enumerate(rows)
253
  ]
254
 
255
 
256
- # ── Gradio Dashboard ──────────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
257
 
258
  _DARK_CSS = """
259
- /* ── Base ── */
260
  body, .gradio-container { background: #0f1117 !important; color: #e2e8f0 !important; }
261
  .gradio-container { max-width: 1100px !important; }
262
 
263
- /* ── Login card ── */
264
- #login-card {
265
- background: linear-gradient(135deg, #1e1b4b 0%, #1a1a2e 100%);
266
- border: 1px solid #3730a3;
267
- border-radius: 20px;
268
- padding: 40px;
269
- max-width: 420px;
270
- margin: 80px auto;
271
- box-shadow: 0 25px 60px rgba(79,70,229,0.3);
272
- }
273
- #login-card h1 { text-align: center; color: #a5b4fc; font-size: 2rem; margin-bottom: 8px; }
274
- #login-card p { text-align: center; color: #6b7280; margin-bottom: 28px; }
275
-
276
- /* ── Header ── */
277
  #dash-header { border-bottom: 1px solid #1e293b; padding-bottom: 16px; margin-bottom: 24px; }
278
- #dash-header h1 { color: #a5b4fc; font-size: 1.8rem; }
279
- #dash-header p { color: #6b7280; }
280
 
281
- /* ── Stat card ── */
282
  .stat-md table { width: 100%; border-collapse: collapse; }
283
  .stat-md th { color: #6b7280; font-size: 0.78rem; text-transform: uppercase; padding: 6px 12px; border-bottom: 1px solid #1e293b; }
284
  .stat-md td { padding: 10px 12px; border-bottom: 1px solid #111827; }
285
  .stat-md tr:hover td { background: #1e293b; }
286
 
287
- /* ── Tabs ── */
288
  .tab-nav button { color: #94a3b8 !important; border-radius: 8px !important; }
289
  .tab-nav button.selected { background: #3730a3 !important; color: #fff !important; }
290
 
291
- /* ── Buttons ── */
292
- button.primary { background: linear-gradient(135deg,#4f46e5,#7c3aed) !important; border-radius: 10px !important; font-weight: 600 !important; }
293
- button.stop { background: linear-gradient(135deg,#dc2626,#b91c1c) !important; border-radius: 10px !important; }
294
  button.secondary { background: #1e293b !important; border: 1px solid #334155 !important; border-radius: 10px !important; }
295
 
296
- /* ── Inputs ── */
297
  textarea, input[type=text], input[type=password] {
298
  background: #1e293b !important;
299
  border: 1px solid #334155 !important;
300
  border-radius: 10px !important;
301
  color: #e2e8f0 !important;
302
  }
303
-
304
- /* ── Dataframe ── */
305
- .svelte-table th { background: #1e293b !important; color: #94a3b8 !important; }
306
- .svelte-table tr:hover td { background: #1e293b !important; }
307
-
308
- /* ── Error text ── */
309
- .error-text { color: #f87171 !important; font-size: 0.9rem; margin-top: 8px; }
310
  """
311
 
312
- SAMPLE_CHAPTERS = load_sample_chapters()
313
-
314
  with gr.Blocks(title="CLQuizMaster Admin", css=_DARK_CSS) as dashboard:
315
 
316
- auth_state = gr.State(False)
317
-
318
- # ── LOGIN PANEL ──────────────────────────────────────────────────────────
319
- with gr.Column(visible=True, elem_id="login-card") as login_panel:
320
- gr.HTML("<h1>πŸŽ“ CLQuizMaster</h1><p>Admin Dashboard β€” Private Access</p>")
321
- pwd_input = gr.Textbox(
322
- label="Password", type="password",
323
- placeholder="Enter admin password…", show_label=False,
324
  )
325
- login_btn = gr.Button("πŸ” Login", variant="primary", size="lg")
326
- login_err = gr.Markdown("", elem_classes=["error-text"])
327
 
328
- # ── DASHBOARD PANEL ──────────────────────────────────────────────────────
329
- with gr.Column(visible=False) as dash_panel:
330
 
331
- with gr.Row(elem_id="dash-header"):
332
- gr.HTML(
333
- "<h1>πŸŽ“ CLQuizMaster Admin</h1>"
334
- "<p>JEE/NEET Multi-Group Quiz Bot Control Panel</p>"
 
335
  )
336
 
337
- with gr.Tabs():
338
-
339
- # ── πŸ“Š Overview ──────────────────────────────────────────────��──
340
- with gr.Tab("πŸ“Š Overview"):
341
- stats_md = gr.Markdown(get_stats(), elem_classes=["stat-md"])
342
- gr.Button("πŸ”„ Refresh Stats", variant="secondary").click(
343
- fn=get_stats, outputs=stats_md
344
- )
345
-
346
- # ── πŸ‘₯ Groups ───────────────────────────────────────────────────
347
- with gr.Tab("πŸ‘₯ Groups"):
348
- gr.Markdown("### All Registered Groups")
349
- groups_table = gr.Dataframe(
350
- value=get_groups_df(),
351
- headers=["ID", "Status", "Title", "Chat ID", "Owner ID", "Added At"],
352
- interactive=False,
353
- wrap=True,
354
- )
355
- gr.Button("πŸ”„ Refresh", variant="secondary").click(
356
- fn=get_groups_df, outputs=groups_table
357
- )
358
-
359
- gr.Markdown("---\n### Approve / Reject Group")
360
- with gr.Row():
361
- gid_box = gr.Textbox(label="Chat ID", placeholder="-1001234567890", scale=3)
362
- appr_btn = gr.Button("βœ… Approve", variant="primary", scale=1)
363
- rejt_btn = gr.Button("🚫 Reject", variant="stop", scale=1)
364
- grp_result = gr.Textbox(label="Result", interactive=False)
365
- appr_btn.click(fn=do_approve, inputs=gid_box, outputs=[grp_result, groups_table])
366
- rejt_btn.click(fn=do_reject, inputs=gid_box, outputs=[grp_result, groups_table])
367
-
368
- # ── πŸ“š Quiz Manager ─────────────────────────────────────────────
369
- with gr.Tab("πŸ“š Quiz Manager"):
370
-
371
- with gr.Tabs():
372
-
373
- with gr.Tab("πŸ“‹ Saved Quizzes"):
374
- quizzes_table = gr.Dataframe(
375
- value=get_quizzes_df(),
376
- headers=["ID", "Chapter", "Scheduled Time", "Created At"],
377
- interactive=False,
378
- )
379
- gr.Button("πŸ”„ Refresh", variant="secondary").click(
380
- fn=get_quizzes_df, outputs=quizzes_table
381
- )
382
-
383
- with gr.Tab("πŸ“‚ Load Sample Quiz"):
384
- gr.Markdown(
385
- "Choose a chapter from the preloaded **sample_quizzes.json** "
386
- "(50 JEE/NEET questions). The questions JSON will auto-fill below."
387
- )
388
- chapter_dd = gr.Dropdown(
389
- choices=SAMPLE_CHAPTERS,
390
- label="Select Chapter",
391
- interactive=True,
392
- )
393
- load_btn = gr.Button("πŸ“₯ Load Questions", variant="secondary")
394
-
395
- chapter_box2 = gr.Textbox(label="Chapter Name (editable)", interactive=True)
396
- questions_box2 = gr.Textbox(label="Questions JSON", lines=10, interactive=True)
397
- save_btn2 = gr.Button("πŸ’Ύ Save Quiz", variant="primary")
398
- save_out2 = gr.Textbox(label="Result", interactive=False)
399
-
400
- load_btn.click(
401
- fn=load_sample_quiz,
402
- inputs=chapter_dd,
403
- outputs=[chapter_box2, questions_box2],
404
- )
405
- save_btn2.click(
406
- fn=do_save_quiz,
407
- inputs=[chapter_box2, questions_box2],
408
- outputs=[save_out2, quizzes_table],
409
- )
410
-
411
- with gr.Tab("✏️ Custom Quiz"):
412
- gr.Markdown(
413
- "Paste your own questions JSON array.\n\n"
414
- "Format: `[{\"q\":\"Question?\", \"opts\":[\"A\",\"B\",\"C\",\"D\"], \"ans\":0}]`\n\n"
415
- "`ans` is the **0-based** index of the correct option."
416
- )
417
- chapter_box = gr.Textbox(label="Chapter Name", placeholder="Physics - Laws of Motion")
418
- questions_box = gr.Textbox(
419
- label="Questions JSON",
420
- placeholder='[{"q":"Q?","opts":["A","B","C","D"],"ans":0}]',
421
- lines=8,
422
- )
423
- save_btn = gr.Button("πŸ’Ύ Save Quiz", variant="primary")
424
- save_out = gr.Textbox(label="Result", interactive=False)
425
- save_btn.click(
426
- fn=do_save_quiz,
427
- inputs=[chapter_box, questions_box],
428
- outputs=[save_out, quizzes_table],
429
- )
430
-
431
- # ── πŸ“‘ Broadcast ───���────────────────────────────────────────────
432
- with gr.Tab("πŸ“‘ Broadcast"):
433
- gr.Markdown(
434
- "### πŸš€ Send Quiz to All Approved Groups\n"
435
- "Enter the Quiz ID. The bot will announce, send all questions as polls, "
436
- "then post leaderboards automatically."
437
- )
438
- with gr.Row():
439
- bcast_id = gr.Textbox(label="Quiz ID", placeholder="1", scale=2)
440
- bcast_btn = gr.Button("πŸš€ Broadcast Now", variant="primary", scale=1)
441
- bcast_out = gr.Textbox(label="Result", interactive=False, lines=3)
442
- bcast_btn.click(fn=do_broadcast, inputs=bcast_id, outputs=bcast_out)
443
-
444
- gr.Markdown("---")
445
- gr.Markdown("**Approved groups that will receive the quiz:**")
446
- def list_approved():
447
- groups = db.get_approved_groups()
448
- if not groups:
449
- return "No approved groups yet."
450
- return "\n".join(f"β€’ {g['title']} (`{g['chat_id']}`)" for g in groups)
451
- approved_list = gr.Markdown(list_approved())
452
- gr.Button("πŸ”„ Refresh List", variant="secondary").click(
453
- fn=list_approved, outputs=approved_list
454
- )
455
-
456
- # ── πŸ† Leaderboard ──────────────────────────────────────────────
457
- with gr.Tab("πŸ† Leaderboard"):
458
- gr.Markdown("### 🌍 Global Top 10")
459
- lb_table = gr.Dataframe(
460
- value=get_global_lb_df(),
461
- headers=["Rank", "Username", "Score", "Total Qs", "Accuracy"],
462
- interactive=False,
463
- )
464
- gr.Button("πŸ”„ Refresh", variant="secondary").click(
465
- fn=get_global_lb_df, outputs=lb_table
466
- )
467
-
468
- # ── ℹ️ Bot Info ──────────────────────────────────────────────────
469
- with gr.Tab("ℹ️ Info"):
470
- gr.Markdown(f"""
471
  ### Bot Commands Reference
472
 
473
  | Command | Description |
@@ -488,19 +417,7 @@ with gr.Blocks(title="CLQuizMaster Admin", css=_DARK_CSS) as dashboard:
488
  - Webhook endpoint: `{WEBHOOK_URL}/webhook`
489
  - Health check: `{WEBHOOK_URL}/health`
490
  - Telegram proxy: `{TELEGRAM_API_BASE}`
491
- """)
492
-
493
- # ── Wire login ───────────────────────────────────────────────────────────
494
- login_btn.click(
495
- fn=do_login,
496
- inputs=pwd_input,
497
- outputs=[auth_state, login_panel, dash_panel, login_err],
498
- )
499
- pwd_input.submit(
500
- fn=do_login,
501
- inputs=pwd_input,
502
- outputs=[auth_state, login_panel, dash_panel, login_err],
503
- )
504
 
505
 
506
  # ── Startup: set webhook and start scheduler ──────────────────────────────────
@@ -560,7 +477,15 @@ startup_thread = threading.Thread(target=_run_startup, daemon=True, name="startu
560
  startup_thread.start()
561
 
562
  # ── Mount FastAPI into Gradio and launch ──────────────────────────────────────
563
- app = mount_gradio_app(fastapi_app, dashboard, path="/")
 
 
 
 
 
 
 
 
564
 
565
  if __name__ == "__main__":
566
  import uvicorn
 
9
 
10
  Deployment Steps:
11
  1. Upload this file + all others to your HF Space.
12
+ 2. Set Secrets: TELEGRAM_TOKEN, ADMIN_ID, WEBHOOK_URL (your Space URL),
13
+ TELEGRAM_API_BASE (Cloudflare Worker), ADMIN_PASSWORD.
14
  3. The Space boots β†’ automatically sets the Telegram webhook.
15
  """
16
 
 
40
  logger = logging.getLogger(__name__)
41
 
42
  # ── Config ───────────────────────────────────────────────────────────────────
43
+ TOKEN = os.environ.get("TELEGRAM_TOKEN", "")
44
+ ADMIN_ID = int(os.environ.get("ADMIN_ID", "0"))
45
+ WEBHOOK_URL = os.environ.get("WEBHOOK_URL", "").rstrip("/")
46
+ ADMIN_PASSWORD = os.environ.get("ADMIN_PASSWORD", "admin123")
47
+
48
+ # Cloudflare Worker proxy β€” set TELEGRAM_API_BASE secret to bypass HF outbound blocks.
49
+ # Worker forwards requests to https://api.telegram.org
50
  # Example: https://dry-flower-3493.h3y-samm.workers.dev/bot
51
  TELEGRAM_API_BASE = os.environ.get(
52
  "TELEGRAM_API_BASE",
 
98
  async def telegram_webhook(request: Request):
99
  """Receive Telegram update and process it."""
100
  if not _bot_ready:
 
 
101
  logger.warning("Webhook received before bot is ready β€” ignoring update.")
102
  return Response(content="Not ready yet", status_code=200)
103
  data = await request.json()
 
111
  return {"status": "ok", "bot_ready": _bot_ready, "db": db.DB_PATH}
112
 
113
 
 
 
 
114
  # ── Dashboard helper functions ────────────────────────────────────────────────
115
 
116
  def _status_badge(status: str) -> str:
117
  return {"approved": "βœ…", "pending": "⏳", "rejected": "🚫"}.get(status, "❓")
118
 
119
 
 
 
 
 
 
 
 
 
 
 
 
120
  def get_stats():
121
  groups = db.get_all_groups()
122
  quizzes = db.list_quizzes()
 
215
  return f"❌ Quiz #{qid} not found."
216
  if not _bot_ready:
217
  return "❌ Bot is not connected yet. Wait for 'Bot initialized successfully.' in logs."
218
+ if _startup_loop is None:
219
+ return "❌ Startup loop not ready yet."
 
 
 
 
220
  _startup_loop.call_soon_threadsafe(
221
  lambda: asyncio.ensure_future(_bq(ptb_app, qid), loop=_startup_loop)
222
  )
223
+ approved = db.get_approved_groups()
224
+ return (
225
+ f"πŸ“‘ Broadcast started for quiz #{qid} β€” "
226
+ f"{len(quiz['questions'])} questions to {len(approved)} groups!"
227
+ )
228
  except Exception as e:
229
  return f"❌ {e}"
230
 
 
233
  rows = db.get_global_leaderboard()
234
  medals = ["πŸ₯‡", "πŸ₯ˆ", "πŸ₯‰"]
235
  return [
236
+ [medals[i] if i < 3 else f"#{i+1}",
237
+ row.get("username") or "Anonymous",
238
+ row.get("score", 0),
239
+ row.get("total", 0),
240
  f"{row.get('score',0)/row.get('total',1)*100:.0f}%" if row.get("total") else "β€”"]
241
  for i, row in enumerate(rows)
242
  ]
243
 
244
 
245
+ def list_approved():
246
+ groups = db.get_approved_groups()
247
+ if not groups:
248
+ return "No approved groups yet."
249
+ return "\n".join(f"β€’ {g['title']} (`{g['chat_id']}`)" for g in groups)
250
+
251
+
252
+ # ── Gradio Dashboard (login handled by Gradio native auth) ───────────────────
253
+
254
+ SAMPLE_CHAPTERS = load_sample_chapters()
255
 
256
  _DARK_CSS = """
 
257
  body, .gradio-container { background: #0f1117 !important; color: #e2e8f0 !important; }
258
  .gradio-container { max-width: 1100px !important; }
259
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
260
  #dash-header { border-bottom: 1px solid #1e293b; padding-bottom: 16px; margin-bottom: 24px; }
261
+ #dash-header h1 { color: #a5b4fc; font-size: 1.8rem; margin: 0; }
262
+ #dash-header p { color: #6b7280; margin: 4px 0 0; }
263
 
 
264
  .stat-md table { width: 100%; border-collapse: collapse; }
265
  .stat-md th { color: #6b7280; font-size: 0.78rem; text-transform: uppercase; padding: 6px 12px; border-bottom: 1px solid #1e293b; }
266
  .stat-md td { padding: 10px 12px; border-bottom: 1px solid #111827; }
267
  .stat-md tr:hover td { background: #1e293b; }
268
 
 
269
  .tab-nav button { color: #94a3b8 !important; border-radius: 8px !important; }
270
  .tab-nav button.selected { background: #3730a3 !important; color: #fff !important; }
271
 
272
+ button.primary { background: linear-gradient(135deg,#4f46e5,#7c3aed) !important; border-radius: 10px !important; font-weight: 600 !important; }
273
+ button.stop { background: linear-gradient(135deg,#dc2626,#b91c1c) !important; border-radius: 10px !important; }
 
274
  button.secondary { background: #1e293b !important; border: 1px solid #334155 !important; border-radius: 10px !important; }
275
 
 
276
  textarea, input[type=text], input[type=password] {
277
  background: #1e293b !important;
278
  border: 1px solid #334155 !important;
279
  border-radius: 10px !important;
280
  color: #e2e8f0 !important;
281
  }
 
 
 
 
 
 
 
282
  """
283
 
 
 
284
  with gr.Blocks(title="CLQuizMaster Admin", css=_DARK_CSS) as dashboard:
285
 
286
+ with gr.Row(elem_id="dash-header"):
287
+ gr.HTML(
288
+ "<h1>πŸŽ“ CLQuizMaster Admin</h1>"
289
+ "<p>JEE/NEET Multi-Group Quiz Bot Control Panel</p>"
 
 
 
 
290
  )
 
 
291
 
292
+ with gr.Tabs():
 
293
 
294
+ # ── πŸ“Š Overview ──────────────────────────────────────────────────────
295
+ with gr.Tab("πŸ“Š Overview"):
296
+ stats_md = gr.Markdown(get_stats(), elem_classes=["stat-md"])
297
+ gr.Button("πŸ”„ Refresh Stats", variant="secondary").click(
298
+ fn=get_stats, outputs=stats_md
299
  )
300
 
301
+ # ── πŸ‘₯ Groups ────────────────────────────────────────────────────────
302
+ with gr.Tab("πŸ‘₯ Groups"):
303
+ gr.Markdown("### All Registered Groups")
304
+ groups_table = gr.Dataframe(
305
+ value=get_groups_df(),
306
+ headers=["ID", "Status", "Title", "Chat ID", "Owner ID", "Added At"],
307
+ interactive=False,
308
+ wrap=True,
309
+ )
310
+ gr.Button("πŸ”„ Refresh", variant="secondary").click(
311
+ fn=get_groups_df, outputs=groups_table
312
+ )
313
+ gr.Markdown("---\n### Approve / Reject Group")
314
+ with gr.Row():
315
+ gid_box = gr.Textbox(label="Chat ID", placeholder="-1001234567890", scale=3)
316
+ appr_btn = gr.Button("βœ… Approve", variant="primary", scale=1)
317
+ rejt_btn = gr.Button("🚫 Reject", variant="stop", scale=1)
318
+ grp_result = gr.Textbox(label="Result", interactive=False)
319
+ appr_btn.click(fn=do_approve, inputs=gid_box, outputs=[grp_result, groups_table])
320
+ rejt_btn.click(fn=do_reject, inputs=gid_box, outputs=[grp_result, groups_table])
321
+
322
+ # ── πŸ“š Quiz Manager ──────────────────────────────────────────────────
323
+ with gr.Tab("πŸ“š Quiz Manager"):
324
+ with gr.Tabs():
325
+
326
+ with gr.Tab("πŸ“‹ Saved Quizzes"):
327
+ quizzes_table = gr.Dataframe(
328
+ value=get_quizzes_df(),
329
+ headers=["ID", "Chapter", "Scheduled Time", "Created At"],
330
+ interactive=False,
331
+ )
332
+ gr.Button("πŸ”„ Refresh", variant="secondary").click(
333
+ fn=get_quizzes_df, outputs=quizzes_table
334
+ )
335
+
336
+ with gr.Tab("πŸ“‚ Load Sample Quiz"):
337
+ gr.Markdown(
338
+ "Choose a chapter from **sample_quizzes.json** "
339
+ "(JEE/NEET questions). The JSON will auto-fill below."
340
+ )
341
+ chapter_dd = gr.Dropdown(choices=SAMPLE_CHAPTERS, label="Select Chapter", interactive=True)
342
+ load_btn = gr.Button("πŸ“₯ Load Questions", variant="secondary")
343
+ chapter_box2 = gr.Textbox(label="Chapter Name (editable)", interactive=True)
344
+ questions_box2 = gr.Textbox(label="Questions JSON", lines=10, interactive=True)
345
+ save_btn2 = gr.Button("πŸ’Ύ Save Quiz", variant="primary")
346
+ save_out2 = gr.Textbox(label="Result", interactive=False)
347
+ load_btn.click(fn=load_sample_quiz, inputs=chapter_dd, outputs=[chapter_box2, questions_box2])
348
+ save_btn2.click(fn=do_save_quiz, inputs=[chapter_box2, questions_box2], outputs=[save_out2, quizzes_table])
349
+
350
+ with gr.Tab("✏️ Custom Quiz"):
351
+ gr.Markdown(
352
+ "Paste your own questions JSON.\n\n"
353
+ "Format: `[{\"q\":\"Question?\", \"opts\":[\"A\",\"B\",\"C\",\"D\"], \"ans\":0}]`\n\n"
354
+ "`ans` is the **0-based** index of the correct option."
355
+ )
356
+ chapter_box = gr.Textbox(label="Chapter Name", placeholder="Physics - Laws of Motion")
357
+ questions_box = gr.Textbox(
358
+ label="Questions JSON",
359
+ placeholder='[{"q":"Q?","opts":["A","B","C","D"],"ans":0}]',
360
+ lines=8,
361
+ )
362
+ save_btn = gr.Button("πŸ’Ύ Save Quiz", variant="primary")
363
+ save_out = gr.Textbox(label="Result", interactive=False)
364
+ save_btn.click(fn=do_save_quiz, inputs=[chapter_box, questions_box], outputs=[save_out, quizzes_table])
365
+
366
+ # ── πŸ“‘ Broadcast ─────────────────────────────────────────────────────
367
+ with gr.Tab("πŸ“‘ Broadcast"):
368
+ gr.Markdown(
369
+ "### πŸš€ Send Quiz to All Approved Groups\n"
370
+ "The bot will announce, send all questions as polls, "
371
+ "then post leaderboards automatically."
372
+ )
373
+ with gr.Row():
374
+ bcast_id = gr.Textbox(label="Quiz ID", placeholder="1", scale=2)
375
+ bcast_btn = gr.Button("πŸš€ Broadcast Now", variant="primary", scale=1)
376
+ bcast_out = gr.Textbox(label="Result", interactive=False, lines=3)
377
+ bcast_btn.click(fn=do_broadcast, inputs=bcast_id, outputs=bcast_out)
378
+
379
+ gr.Markdown("---\n**Approved groups that will receive the quiz:**")
380
+ approved_list = gr.Markdown(list_approved())
381
+ gr.Button("πŸ”„ Refresh List", variant="secondary").click(
382
+ fn=list_approved, outputs=approved_list
383
+ )
384
+
385
+ # ── πŸ† Leaderboard ───────────────────────────────────────────────────
386
+ with gr.Tab("πŸ† Leaderboard"):
387
+ gr.Markdown("### 🌍 Global Top 10")
388
+ lb_table = gr.Dataframe(
389
+ value=get_global_lb_df(),
390
+ headers=["Rank", "Username", "Score", "Total Qs", "Accuracy"],
391
+ interactive=False,
392
+ )
393
+ gr.Button("πŸ”„ Refresh", variant="secondary").click(
394
+ fn=get_global_lb_df, outputs=lb_table
395
+ )
396
+
397
+ # ── ℹ️ Info ───────────────────────────────────────────────────────────
398
+ with gr.Tab("ℹ️ Info"):
399
+ gr.Markdown(f"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
400
  ### Bot Commands Reference
401
 
402
  | Command | Description |
 
417
  - Webhook endpoint: `{WEBHOOK_URL}/webhook`
418
  - Health check: `{WEBHOOK_URL}/health`
419
  - Telegram proxy: `{TELEGRAM_API_BASE}`
420
+ """)
 
 
 
 
 
 
 
 
 
 
 
 
421
 
422
 
423
  # ── Startup: set webhook and start scheduler ──────────────────────────────────
 
477
  startup_thread.start()
478
 
479
  # ── Mount FastAPI into Gradio and launch ──────────────────────────────────────
480
+ # auth= uses Gradio's native login screen β€” clean, no dual-panel bugs.
481
+ # Username is "admin", password is the ADMIN_PASSWORD secret.
482
+ app = mount_gradio_app(
483
+ fastapi_app,
484
+ dashboard,
485
+ path="/",
486
+ auth=[("admin", ADMIN_PASSWORD)],
487
+ auth_message="πŸ” CLQuizMaster Admin β€” Private Access",
488
+ )
489
 
490
  if __name__ == "__main__":
491
  import uvicorn