rameshmoorthy commited on
Commit
66e8448
·
verified ·
1 Parent(s): f936c1d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -1171
app.py CHANGED
@@ -226,1175 +226,4 @@ with gr.Blocks(title="Quiz Maker", theme=colorful_theme) as QUIZBOT:
226
 
227
  if __name__ == "__main__":
228
  QUIZBOT.queue().launch(server_name="0.0.0.0", server_port=7860)# import gradio as gr
229
- # from pathlib import Path
230
- # from sentence_transformers import CrossEncoder
231
- # import numpy as np
232
- # from time import perf_counter
233
- # from pydantic import BaseModel, Field
234
- # from phi.agent import Agent
235
- # from phi.model.groq import Groq
236
- # import os
237
- # import logging
238
-
239
- # # Set up logging
240
- # logging.basicConfig(level=logging.INFO)
241
- # logger = logging.getLogger(__name__)
242
-
243
- # # API Key setup
244
- # api_key = os.getenv("GROQ_API_KEY")
245
- # if not api_key:
246
- # gr.Warning("GROQ_API_KEY not found. Set it in 'Repository secrets'.")
247
- # logger.error("GROQ_API_KEY not found.")
248
- # else:
249
- # os.environ["GROQ_API_KEY"] = api_key
250
-
251
- # # Pydantic Model for Quiz Structure
252
- # class QuizItem(BaseModel):
253
- # question: str = Field(..., description="The quiz question")
254
- # choices: list[str] = Field(..., description="List of 4 multiple-choice options")
255
- # correct_answer: str = Field(..., description="The correct choice (e.g., 'C1')")
256
-
257
- # class QuizOutput(BaseModel):
258
- # items: list[QuizItem] = Field(..., description="List of 10 quiz items")
259
-
260
- # # Initialize Agents
261
- # groq_agent = Agent(model=Groq(model="llama3-70b-8192", api_key=api_key), markdown=True)
262
-
263
- # quiz_generator = Agent(
264
- # name="Quiz Generator",
265
- # role="Generates structured quiz questions and answers",
266
- # instructions=[
267
- # "Create 10 questions with 4 choices each based on the provided topic and documents.",
268
- # "Use the specified difficulty level (easy, average, hard) to adjust question complexity.",
269
- # "Ensure questions are derived only from the provided documents.",
270
- # "Return the output in a structured format using the QuizOutput Pydantic model.",
271
- # "Each question should have a unique correct answer from the choices (labeled C1, C2, C3, C4)."
272
- # ],
273
- # model=Groq(id="llama3-70b-8192", api_key=api_key),
274
- # response_model=QuizOutput,
275
- # markdown=True
276
- # )
277
-
278
- # VECTOR_COLUMN_NAME = "vector"
279
- # TEXT_COLUMN_NAME = "text"
280
- # proj_dir = Path.cwd()
281
-
282
- # # Calling functions from backend (assuming they exist)
283
- # from backend.semantic_search import table, retriever
284
-
285
- # def generate_quiz_data(question_difficulty, topic, documents_str):
286
- # prompt = f"""Generate a quiz with {question_difficulty} difficulty on topic '{topic}' using only the following documents:\n{documents_str}"""
287
- # try:
288
- # response = quiz_generator.run(prompt)
289
- # return response.content
290
- # except Exception as e:
291
- # logger.error(f"Failed to generate quiz: {e}")
292
- # return None
293
-
294
- # def retrieve_and_generate_quiz(question_difficulty, topic):
295
- # gr.Warning('Generating quiz may take 1-2 minutes. Please wait.', duration=60)
296
- # top_k_rank = 10
297
- # documents = []
298
-
299
- # document_start = perf_counter()
300
- # query_vec = retriever.encode(topic)
301
- # documents = [doc[TEXT_COLUMN_NAME] for doc in table.search(query_vec, vector_column_name=VECTOR_COLUMN_NAME).limit(top_k_rank).to_list()]
302
-
303
- # # Apply BGE reranker
304
- # cross_encoder = CrossEncoder('BAAI/bge-reranker-base')
305
- # query_doc_pair = [[topic, doc] for doc in documents]
306
- # cross_scores = cross_encoder.predict(query_doc_pair)
307
- # sim_scores_argsort = list(reversed(np.argsort(cross_scores)))
308
- # documents = [documents[idx] for idx in sim_scores_argsort[:top_k_rank]]
309
-
310
- # documents_str = '\n'.join(documents)
311
- # quiz_data = generate_quiz_data(question_difficulty, topic, documents_str)
312
- # return quiz_data
313
-
314
- # def update_quiz_components(quiz_data):
315
- # if not quiz_data or not quiz_data.items:
316
- # return [gr.update(visible=False) for _ in range(10)] + [gr.update(value="Error: Failed to generate quiz.", visible=True)]
317
-
318
- # radio_updates = []
319
- # for i, item in enumerate(quiz_data.items[:10]):
320
- # choices = item.choices
321
- # radio_update = gr.update(visible=True, choices=choices, label=item.question, value=None)
322
- # radio_updates.append(radio_update)
323
- # return radio_updates + [gr.update(value="Please select answers and click 'Check Score'.", visible=True)]
324
-
325
- # # FIXED FUNCTION: Changed parameter signature to accept all arguments positionally
326
- # def collect_answers_and_calculate(*all_inputs):
327
- # print(f"Total inputs received: {len(all_inputs)}") # Debug print
328
-
329
- # # The last input is quiz_data, the first 10 are radio values
330
- # radio_values = all_inputs[:10] # First 10 inputs are radio button values
331
- # quiz_data = all_inputs[10] # Last input is quiz_data
332
-
333
- # print(f"Received radio_values: {radio_values}") # Debug print
334
- # print(f"Received quiz_data: {quiz_data}") # Debug print
335
-
336
- # # Filter out None values but keep track of positions
337
- # user_answer_list = list(radio_values)
338
- # correct_answers = [item.correct_answer for item in quiz_data.items[:10]]
339
-
340
- # print(f"User answers: {user_answer_list}") # Debug print
341
- # print(f"Correct answers: {correct_answers}") # Debug print
342
-
343
- # # Calculate score - only count answered questions
344
- # score = 0
345
- # answered_questions = 0
346
- # for u, c in zip(user_answer_list, correct_answers):
347
- # if u is not None: # Only count if user answered
348
- # answered_questions += 1
349
- # if u == c:
350
- # score += 1
351
-
352
- # print(f"Calculated score: {score}/{answered_questions}") # Debug print
353
-
354
- # if answered_questions == 0:
355
- # message = "### Please answer at least one question!"
356
- # elif score == answered_questions:
357
- # message = f"### Perfect! You got {score} out of {answered_questions} correct!"
358
- # elif score > answered_questions * 0.7:
359
- # message = f"### Excellent! You got {score} out of {answered_questions} correct!"
360
- # elif score > answered_questions * 0.5:
361
- # message = f"### Good! You got {score} out of {answered_questions} correct!"
362
- # else:
363
- # message = f"### You got {score} out of {answered_questions} correct! Don't worry. You can prepare well and try better next time!"
364
-
365
- # return message
366
-
367
- # # Define a colorful theme
368
- # colorful_theme = gr.themes.Default(primary_hue="cyan", secondary_hue="yellow", neutral_hue="purple")
369
-
370
- # with gr.Blocks(title="Quiz Maker", theme=colorful_theme) as QUIZBOT:
371
- # # Create a single row for the HTML and Image
372
- # with gr.Row():
373
- # with gr.Column(scale=2):
374
- # gr.Image(value='logo.png', height=200, width=200)
375
- # with gr.Column(scale=6):
376
- # gr.HTML("""
377
- # <center>
378
- # <h1><span style="color: purple;">GOVERNMENT HIGH SCHOOL,SUTHUKENY</span> STUDENTS QUIZBOT </h1>
379
- # <h2>Generative AI-powered Capacity building for STUDENTS</h2>
380
- # <i>⚠️ Students can create quiz from any topic from 10th Science and evaluate themselves! ⚠️</i>
381
- # </center>
382
- # """)
383
-
384
- # topic = gr.Textbox(label="Enter the Topic for Quiz", placeholder="Write any CHAPTER NAME")
385
-
386
- # with gr.Row():
387
- # difficulty_radio = gr.Radio(["easy", "average", "hard"], label="How difficult should the quiz be?")
388
- # model_radio = gr.Radio(choices=['(ACCURATE) BGE reranker'], value='(ACCURATE) BGE reranker', label="Embeddings")
389
-
390
- # generate_quiz_btn = gr.Button("Generate Quiz!🚀")
391
- # quiz_msg = gr.Textbox(label="Status", interactive=False)
392
-
393
- # # Pre-defined radio buttons for 10 questions
394
- # question_radios = [gr.Radio(visible=False, label="", choices=[""], value=None) for _ in range(10)]
395
- # quiz_data_state = gr.State(value=None)
396
- # check_score_btn = gr.Button("Check Score")
397
- # score_output = gr.Markdown(visible=False)
398
-
399
- # # Register the click event for Generate Quiz without @ decorator
400
- # generate_quiz_btn.click(
401
- # fn=retrieve_and_generate_quiz,
402
- # inputs=[difficulty_radio, topic],
403
- # outputs=[quiz_data_state]
404
- # ).then(
405
- # fn=update_quiz_components,
406
- # inputs=[quiz_data_state],
407
- # outputs=question_radios + [quiz_msg]
408
- # )
409
-
410
- # # FIXED: Register the click event for Check Score with correct input handling
411
- # check_score_btn.click(
412
- # fn=collect_answers_and_calculate,
413
- # inputs=question_radios + [quiz_data_state], # This creates a list of 11 inputs
414
- # outputs=[score_output],
415
- # api_name="check_score"
416
- # )
417
-
418
- # if __name__ == "__main__":
419
- # QUIZBOT.queue().launch(server_name="0.0.0.0", server_port=7860)
420
- # from pathlib import Path
421
- # from sentence_transformers import CrossEncoder
422
- # import numpy as np
423
- # from time import perf_counter
424
- # from pydantic import BaseModel, Field
425
- # from phi.agent import Agent
426
- # from phi.model.groq import Groq
427
- # import os
428
- # import logging
429
-
430
- # # Set up logging
431
- # logging.basicConfig(level=logging.INFO)
432
- # logger = logging.getLogger(__name__)
433
-
434
- # # API Key setup
435
- # api_key = os.getenv("GROQ_API_KEY")
436
- # if not api_key:
437
- # gr.Warning("GROQ_API_KEY not found. Set it in 'Repository secrets'.")
438
- # logger.error("GROQ_API_KEY not found.")
439
- # else:
440
- # os.environ["GROQ_API_KEY"] = api_key
441
-
442
- # # Pydantic Model for Quiz Structure
443
- # class QuizItem(BaseModel):
444
- # question: str = Field(..., description="The quiz question")
445
- # choices: list[str] = Field(..., description="List of 4 multiple-choice options")
446
- # correct_answer: str = Field(..., description="The correct choice (e.g., 'C1')")
447
-
448
- # class QuizOutput(BaseModel):
449
- # items: list[QuizItem] = Field(..., description="List of 10 quiz items")
450
-
451
- # # Initialize Agents
452
- # groq_agent = Agent(model=Groq(model="llama3-70b-8192", api_key=api_key), markdown=True)
453
-
454
- # quiz_generator = Agent(
455
- # name="Quiz Generator",
456
- # role="Generates structured quiz questions and answers",
457
- # instructions=[
458
- # "Create 10 questions with 4 choices each based on the provided topic and documents.",
459
- # "Use the specified difficulty level (easy, average, hard) to adjust question complexity.",
460
- # "Ensure questions are derived only from the provided documents.",
461
- # "Return the output in a structured format using the QuizOutput Pydantic model.",
462
- # "Each question should have a unique correct answer from the choices (labeled C1, C2, C3, C4)."
463
- # ],
464
- # model=Groq(id="llama3-70b-8192", api_key=api_key),
465
- # response_model=QuizOutput,
466
- # markdown=True
467
- # )
468
-
469
- # VECTOR_COLUMN_NAME = "vector"
470
- # TEXT_COLUMN_NAME = "text"
471
- # proj_dir = Path.cwd()
472
-
473
- # # Calling functions from backend (assuming they exist)
474
- # from backend.semantic_search import table, retriever
475
-
476
- # def generate_quiz_data(question_difficulty, topic, documents_str):
477
- # prompt = f"""Generate a quiz with {question_difficulty} difficulty on topic '{topic}' using only the following documents:\n{documents_str}"""
478
- # try:
479
- # response = quiz_generator.run(prompt)
480
- # return response.content
481
- # except Exception as e:
482
- # logger.error(f"Failed to generate quiz: {e}")
483
- # return None
484
-
485
- # def retrieve_and_generate_quiz(question_difficulty, topic):
486
- # gr.Warning('Generating quiz may take 1-2 minutes. Please wait.', duration=60)
487
- # top_k_rank = 10
488
- # documents = []
489
-
490
- # document_start = perf_counter()
491
- # query_vec = retriever.encode(topic)
492
- # documents = [doc[TEXT_COLUMN_NAME] for doc in table.search(query_vec, vector_column_name=VECTOR_COLUMN_NAME).limit(top_k_rank).to_list()]
493
-
494
- # # Apply BGE reranker
495
- # cross_encoder = CrossEncoder('BAAI/bge-reranker-base')
496
- # query_doc_pair = [[topic, doc] for doc in documents]
497
- # cross_scores = cross_encoder.predict(query_doc_pair)
498
- # sim_scores_argsort = list(reversed(np.argsort(cross_scores)))
499
- # documents = [documents[idx] for idx in sim_scores_argsort[:top_k_rank]]
500
-
501
- # documents_str = '\n'.join(documents)
502
- # quiz_data = generate_quiz_data(question_difficulty, topic, documents_str)
503
- # return quiz_data
504
-
505
- # def update_quiz_components(quiz_data):
506
- # if not quiz_data or not quiz_data.items:
507
- # return [gr.update(visible=False) for _ in range(10)] + [gr.update(value="Error: Failed to generate quiz.", visible=True)]
508
-
509
- # radio_updates = []
510
- # for i, item in enumerate(quiz_data.items[:10]):
511
- # choices = item.choices
512
- # radio_update = gr.update(visible=True, choices=choices, label=item.question, value=None)
513
- # radio_updates.append(radio_update)
514
- # return radio_updates + [gr.update(value="Please select answers and click 'Check Score'.", visible=True)]
515
-
516
- # def calculate_score(*user_answers, quiz_data): # quiz_data as a positional argument after *user_answers
517
- # if not quiz_data or not quiz_data.items:
518
- # return "Please generate a quiz first."
519
- # user_answer_list = [ans for ans in user_answers[:-1] if ans] # Exclude quiz_data from user_answers
520
- # correct_answers = [item.correct_answer for item in quiz_data.items[:10]]
521
- # score = sum(1 for u, c in zip(user_answer_list, correct_answers) if u == c)
522
- # if score > 7:
523
- # message = f"### Excellent! You got {score} out of 10!"
524
- # elif score > 5:
525
- # message = f"### Good! You got {score} out of 10!"
526
- # else:
527
- # message = f"### You got {score} out of 10! Don't worry. You can prepare well and try better next time!"
528
- # return message
529
-
530
- # # Define a colorful theme
531
- # colorful_theme = gr.themes.Default(primary_hue="cyan", secondary_hue="yellow", neutral_hue="purple")
532
-
533
- # with gr.Blocks(title="Quiz Maker", theme=colorful_theme) as QUIZBOT:
534
- # # Create a single row for the HTML and Image
535
- # with gr.Row():
536
- # with gr.Column(scale=2):
537
- # gr.Image(value='logo.png', height=200, width=200)
538
- # with gr.Column(scale=6):
539
- # gr.HTML("""
540
- # <center>
541
- # <h1><span style="color: purple;">GOVERNMENT HIGH SCHOOL,SUTHUKENY</span> STUDENTS QUIZBOT </h1>
542
- # <h2>Generative AI-powered Capacity building for STUDENTS</h2>
543
- # <i>⚠️ Students can create quiz from any topic from 10th Science and evaluate themselves! ⚠️</i>
544
- # </center>
545
- # """)
546
-
547
- # topic = gr.Textbox(label="Enter the Topic for Quiz", placeholder="Write any CHAPTER NAME")
548
-
549
- # with gr.Row():
550
- # difficulty_radio = gr.Radio(["easy", "average", "hard"], label="How difficult should the quiz be?")
551
- # model_radio = gr.Radio(choices=['(ACCURATE) BGE reranker'], value='(ACCURATE) BGE reranker', label="Embeddings")
552
-
553
- # generate_quiz_btn = gr.Button("Generate Quiz!🚀")
554
- # quiz_msg = gr.Textbox(label="Status", interactive=False)
555
-
556
- # # Pre-defined radio buttons for 10 questions
557
- # question_radios = [gr.Radio(visible=False, label="", choices=[""], value=None) for _ in range(10)]
558
- # quiz_data_state = gr.State(value=None)
559
- # check_score_btn = gr.Button("Check Score")
560
- # score_output = gr.Markdown(visible=False)
561
-
562
- # # Register the click event for Generate Quiz without @ decorator
563
- # generate_quiz_btn.click(
564
- # fn=retrieve_and_generate_quiz,
565
- # inputs=[difficulty_radio, topic],
566
- # outputs=[quiz_data_state]
567
- # ).then(
568
- # fn=update_quiz_components,
569
- # inputs=[quiz_data_state],
570
- # outputs=question_radios + [quiz_msg]
571
- # )
572
-
573
- # # Register the click event for Check Score with explicit input mapping
574
- # check_score_btn.click(
575
- # fn=calculate_score,
576
- # inputs=question_radios + [quiz_data_state],
577
- # outputs=[score_output],
578
- # api_name="check_score" # Optional: for clarity
579
- # )
580
-
581
- # if __name__ == "__main__":
582
- # QUIZBOT.queue().launch(server_name="0.0.0.0", server_port=7860)# import gradio as gr
583
- # # from pathlib import Path
584
- # from sentence_transformers import CrossEncoder
585
- # import numpy as np
586
- # from time import perf_counter
587
- # from pydantic import BaseModel, Field
588
- # from phi.agent import Agent
589
- # from phi.model.groq import Groq
590
- # import os
591
- # import logging
592
-
593
- # # Set up logging
594
- # logging.basicConfig(level=logging.INFO)
595
- # logger = logging.getLogger(__name__)
596
-
597
- # # API Key setup
598
- # api_key = os.getenv("GROQ_API_KEY")
599
- # if not api_key:
600
- # gr.Warning("GROQ_API_KEY not found. Set it in 'Repository secrets'.")
601
- # logger.error("GROQ_API_KEY not found.")
602
- # else:
603
- # os.environ["GROQ_API_KEY"] = api_key
604
-
605
- # # Pydantic Model for Quiz Structure
606
- # class QuizItem(BaseModel):
607
- # question: str = Field(..., description="The quiz question")
608
- # choices: list[str] = Field(..., description="List of 4 multiple-choice options")
609
- # correct_answer: str = Field(..., description="The correct choice (e.g., 'C1')")
610
-
611
- # class QuizOutput(BaseModel):
612
- # items: list[QuizItem] = Field(..., description="List of 10 quiz items")
613
-
614
- # # Initialize Agents
615
- # groq_agent = Agent(model=Groq(model="llama3-70b-8192", api_key=api_key), markdown=True)
616
-
617
- # quiz_generator = Agent(
618
- # name="Quiz Generator",
619
- # role="Generates structured quiz questions and answers",
620
- # instructions=[
621
- # "Create 10 questions with 4 choices each based on the provided topic and documents.",
622
- # "Use the specified difficulty level (easy, average, hard) to adjust question complexity.",
623
- # "Ensure questions are derived only from the provided documents.",
624
- # "Return the output in a structured format using the QuizOutput Pydantic model.",
625
- # "Each question should have a unique correct answer from the choices (labeled C1, C2, C3, C4)."
626
- # ],
627
- # model=Groq(id="llama3-70b-8192", api_key=api_key),
628
- # response_model=QuizOutput,
629
- # markdown=True
630
- # )
631
-
632
- # VECTOR_COLUMN_NAME = "vector"
633
- # TEXT_COLUMN_NAME = "text"
634
- # proj_dir = Path.cwd()
635
-
636
- # # Calling functions from backend (assuming they exist)
637
- # from backend.semantic_search import table, retriever
638
-
639
- # def generate_quiz_data(question_difficulty, topic, documents_str):
640
- # prompt = f"""Generate a quiz with {question_difficulty} difficulty on topic '{topic}' using only the following documents:\n{documents_str}"""
641
- # try:
642
- # response = quiz_generator.run(prompt)
643
- # return response.content
644
- # except Exception as e:
645
- # logger.error(f"Failed to generate quiz: {e}")
646
- # return None
647
-
648
- # def retrieve_and_generate_quiz(question_difficulty, topic):
649
- # gr.Warning('Generating quiz may take 1-2 minutes. Please wait.', duration=60)
650
- # top_k_rank = 10
651
- # documents = []
652
-
653
- # document_start = perf_counter()
654
- # query_vec = retriever.encode(topic)
655
- # documents = [doc[TEXT_COLUMN_NAME] for doc in table.search(query_vec, vector_column_name=VECTOR_COLUMN_NAME).limit(top_k_rank).to_list()]
656
-
657
- # # Apply BGE reranker
658
- # cross_encoder = CrossEncoder('BAAI/bge-reranker-base')
659
- # query_doc_pair = [[topic, doc] for doc in documents]
660
- # cross_scores = cross_encoder.predict(query_doc_pair)
661
- # sim_scores_argsort = list(reversed(np.argsort(cross_scores)))
662
- # documents = [documents[idx] for idx in sim_scores_argsort[:top_k_rank]]
663
-
664
- # documents_str = '\n'.join(documents)
665
- # quiz_data = generate_quiz_data(question_difficulty, topic, documents_str)
666
- # return quiz_data
667
-
668
- # def update_quiz_components(quiz_data):
669
- # if not quiz_data or not quiz_data.items:
670
- # return [gr.update(visible=False) for _ in range(10)] + [gr.update(value="Error: Failed to generate quiz.", visible=True)]
671
-
672
- # radio_updates = []
673
- # for i, item in enumerate(quiz_data.items[:10]):
674
- # choices = item.choices
675
- # radio_update = gr.update(visible=True, choices=choices, label=item.question, value=None)
676
- # radio_updates.append(radio_update)
677
- # return radio_updates + [gr.update(value="Please select answers and click 'Check Score'.", visible=True)]
678
-
679
- # def calculate_score(*user_answers, quiz_data):
680
- # if not quiz_data or not quiz_data.items:
681
- # return "Please generate a quiz first."
682
- # user_answer_list = [ans for ans in user_answers[:-1] if ans] # Exclude quiz_data from user_answers
683
- # correct_answers = [item.correct_answer for item in quiz_data.items[:10]]
684
- # score = sum(1 for u, c in zip(user_answer_list, correct_answers) if u == c)
685
- # if score > 7:
686
- # message = f"### Excellent! You got {score} out of 10!"
687
- # elif score > 5:
688
- # message = f"### Good! You got {score} out of 10!"
689
- # else:
690
- # message = f"### You got {score} out of 10! Don't worry. You can prepare well and try better next time!"
691
- # return message
692
-
693
- # # Define a colorful theme
694
- # colorful_theme = gr.themes.Default(primary_hue="cyan", secondary_hue="yellow", neutral_hue="purple")
695
-
696
- # with gr.Blocks(title="Quiz Maker", theme=colorful_theme) as QUIZBOT:
697
- # # Create a single row for the HTML and Image
698
- # with gr.Row():
699
- # with gr.Column(scale=2):
700
- # gr.Image(value='logo.png', height=200, width=200)
701
- # with gr.Column(scale=6):
702
- # gr.HTML("""
703
- # <center>
704
- # <h1><span style="color: purple;">GOVERNMENT HIGH SCHOOL,SUTHUKENY</span> STUDENTS QUIZBOT </h1>
705
- # <h2>Generative AI-powered Capacity building for STUDENTS</h2>
706
- # <i>⚠️ Students can create quiz from any topic from 10th Science and evaluate themselves! ⚠️</i>
707
- # </center>
708
- # """)
709
-
710
- # topic = gr.Textbox(label="Enter the Topic for Quiz", placeholder="Write any CHAPTER NAME")
711
-
712
- # with gr.Row():
713
- # difficulty_radio = gr.Radio(["easy", "average", "hard"], label="How difficult should the quiz be?")
714
- # model_radio = gr.Radio(choices=['(ACCURATE) BGE reranker'], value='(ACCURATE) BGE reranker', label="Embeddings")
715
-
716
- # generate_quiz_btn = gr.Button("Generate Quiz!🚀")
717
- # quiz_msg = gr.Textbox(label="Status", interactive=False)
718
-
719
- # # Pre-defined radio buttons for 10 questions
720
- # question_radios = [gr.Radio(visible=False, label="", choices=[""], value=None) for _ in range(10)]
721
- # quiz_data_state = gr.State(value=None)
722
- # check_score_btn = gr.Button("Check Score")
723
- # score_output = gr.Markdown(visible=False)
724
-
725
- # # Register the click event for Generate Quiz without @ decorator
726
- # generate_quiz_btn.click(
727
- # fn=retrieve_and_generate_quiz,
728
- # inputs=[difficulty_radio, topic],
729
- # outputs=[quiz_data_state]
730
- # ).then(
731
- # fn=update_quiz_components,
732
- # inputs=[quiz_data_state],
733
- # outputs=question_radios + [quiz_msg]
734
- # )
735
-
736
- # # Register the click event for Check Score without @ decorator
737
- # check_score_btn.click(
738
- # fn=calculate_score,
739
- # inputs=question_radios + [quiz_data_state],
740
- # outputs=[score_output]
741
- # )
742
-
743
- # if __name__ == "__main__":
744
- # QUIZBOT.queue().launch(server_name="0.0.0.0", server_port=7860)# import gradio as gr
745
- # from pathlib import Path
746
- # from sentence_transformers import CrossEncoder
747
- # import numpy as np
748
- # from time import perf_counter
749
- # from pydantic import BaseModel, Field
750
- # from phi.agent import Agent
751
- # from phi.model.groq import Groq
752
- # import os
753
- # import logging
754
-
755
- # # Set up logging
756
- # logging.basicConfig(level=logging.INFO)
757
- # logger = logging.getLogger(__name__)
758
-
759
- # # API Key setup
760
- # api_key = os.getenv("GROQ_API_KEY")
761
- # if not api_key:
762
- # gr.Warning("GROQ_API_KEY not found. Set it in 'Repository secrets'.")
763
- # logger.error("GROQ_API_KEY not found.")
764
- # else:
765
- # os.environ["GROQ_API_KEY"] = api_key
766
-
767
- # # Pydantic Model for Quiz Structure
768
- # class QuizItem(BaseModel):
769
- # question: str = Field(..., description="The quiz question")
770
- # choices: list[str] = Field(..., description="List of 4 multiple-choice options")
771
- # correct_answer: str = Field(..., description="The correct choice (e.g., 'C1')")
772
-
773
- # class QuizOutput(BaseModel):
774
- # items: list[QuizItem] = Field(..., description="List of 10 quiz items")
775
-
776
- # # Initialize Agents
777
- # groq_agent = Agent(model=Groq(model="llama3-70b-8192", api_key=api_key), markdown=True)
778
-
779
- # quiz_generator = Agent(
780
- # name="Quiz Generator",
781
- # role="Generates structured quiz questions and answers",
782
- # instructions=[
783
- # "Create 10 questions with 4 choices each based on the provided topic and documents.",
784
- # "Use the specified difficulty level (easy, average, hard) to adjust question complexity.",
785
- # "Ensure questions are derived only from the provided documents.",
786
- # "Return the output in a structured format using the QuizOutput Pydantic model.",
787
- # "Each question should have a unique correct answer from the choices (labeled C1, C2, C3, C4)."
788
- # ],
789
- # model=Groq(id="llama3-70b-8192", api_key=api_key),
790
- # response_model=QuizOutput,
791
- # markdown=True
792
- # )
793
-
794
- # VECTOR_COLUMN_NAME = "vector"
795
- # TEXT_COLUMN_NAME = "text"
796
- # proj_dir = Path.cwd()
797
-
798
- # # Calling functions from backend (assuming they exist)
799
- # from backend.semantic_search import table, retriever
800
-
801
- # def generate_quiz_data(question_difficulty, topic, documents_str):
802
- # prompt = f"""Generate a quiz with {question_difficulty} difficulty on topic '{topic}' using only the following documents:\n{documents_str}"""
803
- # try:
804
- # response = quiz_generator.run(prompt)
805
- # return response.content
806
- # except Exception as e:
807
- # logger.error(f"Failed to generate quiz: {e}")
808
- # return None
809
-
810
- # def retrieve_and_generate_quiz(question_difficulty, topic):
811
- # gr.Warning('Generating quiz may take 1-2 minutes. Please wait.', duration=60)
812
- # top_k_rank = 10
813
- # documents = []
814
-
815
- # document_start = perf_counter()
816
- # query_vec = retriever.encode(topic)
817
- # documents = [doc[TEXT_COLUMN_NAME] for doc in table.search(query_vec, vector_column_name=VECTOR_COLUMN_NAME).limit(top_k_rank).to_list()]
818
-
819
- # # Apply BGE reranker
820
- # cross_encoder = CrossEncoder('BAAI/bge-reranker-base')
821
- # query_doc_pair = [[topic, doc] for doc in documents]
822
- # cross_scores = cross_encoder.predict(query_doc_pair)
823
- # sim_scores_argsort = list(reversed(np.argsort(cross_scores)))
824
- # documents = [documents[idx] for idx in sim_scores_argsort[:top_k_rank]]
825
-
826
- # documents_str = '\n'.join(documents)
827
- # quiz_data = generate_quiz_data(question_difficulty, topic, documents_str)
828
- # return quiz_data
829
-
830
- # def update_quiz_components(quiz_data):
831
- # if not quiz_data or not quiz_data.items:
832
- # return [gr.update(visible=False) for _ in range(10)] + [gr.update(value="Error: Failed to generate quiz.", visible=True)]
833
-
834
- # radio_updates = []
835
- # for i, item in enumerate(quiz_data.items[:10]):
836
- # choices = item.choices
837
- # radio_update = gr.update(visible=True, choices=choices, label=item.question, value=None)
838
- # radio_updates.append(radio_update)
839
- # return radio_updates + [gr.update(value="Please select answers and click 'Check Score'.", visible=True)]
840
-
841
- # def calculate_score(*user_answers, quiz_data):
842
- # if not quiz_data or not quiz_data.items:
843
- # return "Please generate a quiz first."
844
- # user_answer_list = [ans for ans in user_answers if ans]
845
- # correct_answers = [item.correct_answer for item in quiz_data.items[:10]]
846
- # score = sum(1 for u, c in zip(user_answer_list, correct_answers) if u == c)
847
- # if score > 7:
848
- # message = f"### Excellent! You got {score} out of 10!"
849
- # elif score > 5:
850
- # message = f"### Good! You got {score} out of 10!"
851
- # else:
852
- # message = f"### You got {score} out of 10! Don't worry. You can prepare well and try better next time!"
853
- # return message
854
-
855
- # with gr.Blocks(title="Quiz Generator Test") as QUIZBOT:
856
- # with gr.Row():
857
- # gr.Markdown("# Quiz Generator Test")
858
-
859
- # topic = gr.Textbox(label="Enter Topic", placeholder="Write any topic from 9th Science CBSE")
860
- # difficulty_radio = gr.Radio(["easy", "average", "hard"], label="How difficult should the quiz be?")
861
-
862
- # generate_quiz_btn = gr.Button("Generate Quiz")
863
- # check_score_btn = gr.Button("Check Score")
864
-
865
- # # Pre-defined radio buttons for 10 questions
866
- # question_radios = [gr.Radio(visible=False, label="", choices=[""], value=None) for _ in range(10)]
867
- # quiz_data_state = gr.State(value=None)
868
- # score_output = gr.Markdown(visible=False)
869
-
870
- # # Register the click event for Generate Quiz without @ decorator
871
- # generate_quiz_btn.click(
872
- # fn=retrieve_and_generate_quiz,
873
- # inputs=[difficulty_radio, topic],
874
- # outputs=[quiz_data_state]
875
- # ).then(
876
- # fn=update_quiz_components,
877
- # inputs=[quiz_data_state],
878
- # outputs=question_radios + [score_output]
879
- # )
880
-
881
- # # Register the click event for Check Score without @ decorator
882
- # check_score_btn.click(
883
- # fn=calculate_score,
884
- # inputs=question_radios + [quiz_data_state],
885
- # outputs=[score_output]
886
- # )
887
-
888
- # if __name__ == "__main__":
889
- # QUIZBOT.queue().launch(server_name="0.0.0.0", server_port=7860)# import gradio as gr
890
- # # from pathlib import Path
891
- # # from sentence_transformers import CrossEncoder
892
- # # import numpy as np
893
- # # from time import perf_counter
894
- # # from pydantic import BaseModel, Field
895
- # # from phi.agent import Agent
896
- # # from phi.model.groq import Groq
897
- # # import os
898
- # # import logging
899
-
900
- # # # Set up logging
901
- # # logging.basicConfig(level=logging.INFO)
902
- # # logger = logging.getLogger(__name__)
903
-
904
- # # # API Key setup
905
- # # api_key = os.getenv("GROQ_API_KEY")
906
- # # if not api_key:
907
- # # gr.Warning("GROQ_API_KEY not found. Set it in 'Repository secrets'.")
908
- # # logger.error("GROQ_API_KEY not found.")
909
- # # else:
910
- # # os.environ["GROQ_API_KEY"] = api_key
911
-
912
- # # # Pydantic Model for Quiz Structure
913
- # # class QuizItem(BaseModel):
914
- # # question: str = Field(..., description="The quiz question")
915
- # # choices: list[str] = Field(..., description="List of 4 multiple-choice options")
916
- # # correct_answer: str = Field(..., description="The correct choice (e.g., 'C1')")
917
-
918
- # # class QuizOutput(BaseModel):
919
- # # items: list[QuizItem] = Field(..., description="List of 10 quiz items")
920
-
921
- # # # Initialize Agents
922
- # # groq_agent = Agent(model=Groq(model="llama3-70b-8192", api_key=api_key), markdown=True)
923
-
924
- # # quiz_generator = Agent(
925
- # # name="Quiz Generator",
926
- # # role="Generates structured quiz questions and answers",
927
- # # instructions=[
928
- # # "Create 10 questions with 4 choices each based on the provided topic and documents.",
929
- # # "Use the specified difficulty level (easy, average, hard) to adjust question complexity.",
930
- # # "Ensure questions are derived only from the provided documents.",
931
- # # "Return the output in a structured format using the QuizOutput Pydantic model.",
932
- # # "Each question should have a unique correct answer from the choices (labeled C1, C2, C3, C4)."
933
- # # ],
934
- # # model=Groq(id="llama3-70b-8192", api_key=api_key),
935
- # # response_model=QuizOutput,
936
- # # markdown=True
937
- # # )
938
-
939
- # # VECTOR_COLUMN_NAME = "vector"
940
- # # TEXT_COLUMN_NAME = "text"
941
- # # proj_dir = Path.cwd()
942
-
943
- # # # Calling functions from backend (assuming they exist)
944
- # # from backend.semantic_search import table, retriever
945
-
946
- # # def generate_quiz_data(question_difficulty, topic, documents_str):
947
- # # prompt = f"""Generate a quiz with {question_difficulty} difficulty on topic '{topic}' using only the following documents:\n{documents_str}"""
948
- # # try:
949
- # # response = quiz_generator.run(prompt)
950
- # # return response.content
951
- # # except Exception as e:
952
- # # logger.error(f"Failed to generate quiz: {e}")
953
- # # return None
954
-
955
- # # def retrieve_and_generate_quiz(question_difficulty, topic):
956
- # # gr.Warning('Generating quiz may take 1-2 minutes. Please wait.', duration=60)
957
- # # top_k_rank = 10
958
- # # documents = []
959
-
960
- # # document_start = perf_counter()
961
- # # query_vec = retriever.encode(topic)
962
- # # documents = [doc[TEXT_COLUMN_NAME] for doc in table.search(query_vec, vector_column_name=VECTOR_COLUMN_NAME).limit(top_k_rank).to_list()]
963
-
964
- # # # Apply BGE reranker
965
- # # cross_encoder = CrossEncoder('BAAI/bge-reranker-base')
966
- # # query_doc_pair = [[topic, doc] for doc in documents]
967
- # # cross_scores = cross_encoder.predict(query_doc_pair)
968
- # # sim_scores_argsort = list(reversed(np.argsort(cross_scores)))
969
- # # documents = [documents[idx] for idx in sim_scores_argsort[:top_k_rank]]
970
-
971
- # # documents_str = '\n'.join(documents)
972
- # # quiz_data = generate_quiz_data(question_difficulty, topic, documents_str)
973
- # # if not quiz_data or not quiz_data.items:
974
- # # return gr.update(value="Error: Failed to generate quiz.", visible=True)
975
-
976
- # # # Generate HTML for questions and choices
977
- # # html_content = "<div style='font-family: Arial, sans-serif; padding: 10px;'>"
978
- # # for i, item in enumerate(quiz_data.items[:10], 1):
979
- # # html_content += f"<h3>Question {i}: {item.question}</h3>"
980
- # # html_content += "<ul style='list-style-type: none;'>"
981
- # # for j, choice in enumerate(item.choices, 1):
982
- # # html_content += f"<li>C{j}: {choice}</li>"
983
- # # html_content += "</ul>"
984
- # # html_content += "</div>"
985
-
986
- # # return gr.update(value=html_content, visible=True)
987
-
988
- # # with gr.Blocks(title="Quiz Generator Test") as QUIZBOT:
989
- # # with gr.Row():
990
- # # gr.Markdown("# Quiz Generator Test")
991
-
992
- # # topic = gr.Textbox(label="Enter Topic", placeholder="Write any topic from 9th Science CBSE")
993
- # # difficulty_radio = gr.Radio(["easy", "average", "hard"], label="How difficult should the quiz be?")
994
-
995
- # # generate_quiz_btn = gr.Button("Generate Quiz")
996
- # # quiz_output = gr.HTML(visible=False)
997
-
998
- # # # Register the click event without @ decorator
999
- # # generate_quiz_btn.click(
1000
- # # fn=retrieve_and_generate_quiz,
1001
- # # inputs=[difficulty_radio, topic],
1002
- # # outputs=[quiz_output]
1003
- # # )
1004
-
1005
- # # if __name__ == "__main__":
1006
- # # QUIZBOT.queue().launch(server_name="0.0.0.0", server_port=7860)
1007
-
1008
- # # import gradio as gr
1009
- # # from pathlib import Path
1010
- # # from tempfile import NamedTemporaryFile
1011
- # # from sentence_transformers import CrossEncoder
1012
- # # import numpy as np
1013
- # # from time import perf_counter
1014
- # # import pandas as pd
1015
- # # from pydantic import BaseModel, Field
1016
- # # from phi.agent import Agent
1017
- # # from phi.model.groq import Groq
1018
- # # import os
1019
- # # import logging
1020
-
1021
- # # # Set up logging
1022
- # # logging.basicConfig(level=logging.INFO)
1023
- # # logger = logging.getLogger(__name__)
1024
-
1025
- # # # API Key setup
1026
- # # api_key = os.getenv("GROQ_API_KEY")
1027
- # # if not api_key:
1028
- # # gr.Warning("GROQ_API_KEY not found. Set it in 'Repository secrets'.")
1029
- # # logger.error("GROQ_API_KEY not found.")
1030
- # # else:
1031
- # # os.environ["GROQ_API_KEY"] = api_key
1032
-
1033
- # # # Pydantic Model for Quiz Structure
1034
- # # class QuizItem(BaseModel):
1035
- # # question: str = Field(..., description="The quiz question")
1036
- # # choices: list[str] = Field(..., description="List of 4 multiple-choice options")
1037
- # # correct_answer: str = Field(..., description="The correct choice (e.g., 'C1')")
1038
-
1039
- # # class QuizOutput(BaseModel):
1040
- # # items: list[QuizItem] = Field(..., description="List of 10 quiz items")
1041
-
1042
- # # # Initialize Agents
1043
- # # groq_agent = Agent(model=Groq(model="llama3-70b-8192", api_key=api_key), markdown=True)
1044
-
1045
- # # quiz_generator = Agent(
1046
- # # name="Quiz Generator",
1047
- # # role="Generates structured quiz questions and answers",
1048
- # # instructions=[
1049
- # # "Create 10 questions with 4 choices each based on the provided topic and documents.",
1050
- # # "Use the specified difficulty level (easy, average, hard) to adjust question complexity.",
1051
- # # "Ensure questions are derived only from the provided documents.",
1052
- # # "Return the output in a structured format using the QuizOutput Pydantic model.",
1053
- # # "Each question should have a unique correct answer from the choices (labeled C1, C2, C3, C4)."
1054
- # # ],
1055
- # # model=Groq(id="llama3-70b-8192", api_key=api_key),
1056
- # # response_model=QuizOutput,
1057
- # # markdown=True
1058
- # # )
1059
-
1060
- # # VECTOR_COLUMN_NAME = "vector"
1061
- # # TEXT_COLUMN_NAME = "text"
1062
- # # proj_dir = Path.cwd()
1063
-
1064
- # # # Calling functions from backend (assuming they exist)
1065
- # # from backend.semantic_search import table, retriever
1066
-
1067
- # # def generate_quiz_data(question_difficulty, topic, documents_str):
1068
- # # prompt = f"""Generate a quiz with {question_difficulty} difficulty on topic '{topic}' using only the following documents:\n{documents_str}"""
1069
- # # try:
1070
- # # response = quiz_generator.run(prompt)
1071
- # # return response.content
1072
- # # except Exception as e:
1073
- # # logger.error(f"Failed to generate quiz: {e}")
1074
- # # return None
1075
-
1076
- # # def json_to_excel(quiz_data):
1077
- # # data = []
1078
- # # gr.Warning('Generating Shareable file link..', duration=30)
1079
- # # for i, item in enumerate(quiz_data.items, 1):
1080
- # # data.append([
1081
- # # item.question,
1082
- # # "Multiple Choice",
1083
- # # item.choices[0],
1084
- # # item.choices[1],
1085
- # # item.choices[2],
1086
- # # item.choices[3],
1087
- # # '', # Option 5 (empty)
1088
- # # item.correct_answer.replace('C', ''),
1089
- # # 30,
1090
- # # ''
1091
- # # ])
1092
- # # df = pd.DataFrame(data, columns=[
1093
- # # "Question Text", "Question Type", "Option 1", "Option 2", "Option 3", "Option 4", "Option 5", "Correct Answer", "Time in seconds", "Image Link"
1094
- # # ])
1095
- # # temp_file = NamedTemporaryFile(delete=True, suffix=".xlsx")
1096
- # # df.to_excel(temp_file.name, index=False)
1097
- # # return temp_file.name
1098
-
1099
- # # colorful_theme = gr.themes.Default(primary_hue="cyan", secondary_hue="yellow", neutral_hue="purple")
1100
-
1101
- # # with gr.Blocks(title="Quiz Maker", theme=colorful_theme) as QUIZBOT:
1102
- # # with gr.Row():
1103
- # # with gr.Column(scale=2):
1104
- # # gr.Image(value='logo.png', height=200, width=200)
1105
- # # with gr.Column(scale=6):
1106
- # # gr.HTML("""
1107
- # # <center>
1108
- # # <h1><span style="color: purple;">GOVERNMENT HIGH SCHOOL,SUTHUKENY</span> STUDENTS QUIZBOT </h1>
1109
- # # <h2>Generative AI-powered Capacity building for STUDENTS</h2>
1110
- # # <i>⚠️ Students can create quiz from any topic from 9th Science and evaluate themselves! ⚠️</i>
1111
- # # </center>
1112
- # # """)
1113
-
1114
- # # topic = gr.Textbox(label="Enter the Topic for Quiz", placeholder="Write any topic/details from 9TH Science CBSE")
1115
- # # with gr.Row():
1116
- # # difficulty_radio = gr.Radio(["easy", "average", "hard"], label="How difficult should the quiz be?")
1117
- # # model_radio = gr.Radio(choices=['(ACCURATE) BGE reranker'], value='(ACCURATE) BGE reranker', label="Embeddings") # Removed ColBERT option
1118
-
1119
- # # generate_quiz_btn = gr.Button("Generate Quiz!🚀")
1120
- # # quiz_msg = gr.Textbox(label="Status", interactive=False)
1121
- # # question_display = gr.HTML(visible=False)
1122
- # # download_excel = gr.File(label="Download Excel")
1123
-
1124
- # # @generate_quiz_btn.click(inputs=[difficulty_radio, topic, model_radio], outputs=[quiz_msg, question_display, download_excel])
1125
- # # def generate_quiz(question_difficulty, topic, cross_encoder):
1126
- # # top_k_rank = 10
1127
- # # documents = []
1128
- # # gr.Warning('Generating Quiz may take 1-2 minutes. Please wait.', duration=60)
1129
-
1130
- # # document_start = perf_counter()
1131
- # # query_vec = retriever.encode(topic)
1132
- # # documents = [doc[TEXT_COLUMN_NAME] for doc in table.search(query_vec, vector_column_name=VECTOR_COLUMN_NAME).limit(top_k_rank).to_list()]
1133
- # # if cross_encoder == '(ACCURATE) BGE reranker':
1134
- # # cross_encoder1 = CrossEncoder('BAAI/bge-reranker-base')
1135
- # # query_doc_pair = [[topic, doc] for doc in documents]
1136
- # # cross_scores = cross_encoder1.predict(query_doc_pair)
1137
- # # sim_scores_argsort = list(reversed(np.argsort(cross_scores)))
1138
- # # documents = [documents[idx] for idx in sim_scores_argsort[:top_k_rank]]
1139
-
1140
- # # documents_str = '\n'.join(documents)
1141
- # # quiz_data = generate_quiz_data(question_difficulty, topic, documents_str)
1142
- # # if not quiz_data or not quiz_data.items:
1143
- # # return ["Error: Failed to generate quiz.", gr.HTML(visible=False), None]
1144
-
1145
- # # excel_file = json_to_excel(quiz_data)
1146
- # # html_content = "<div>" + "".join(f"<h3>{i}. {item.question}</h3><p>{'<br>'.join(item.choices)}</p>" for i, item in enumerate(quiz_data.items[:10], 1)) + "</div>"
1147
- # # return ["Quiz Generated!", gr.HTML(value=html_content, visible=True), excel_file]
1148
-
1149
- # # check_button = gr.Button("Check Score")
1150
- # # score_textbox = gr.Markdown()
1151
-
1152
- # # @check_button.click(inputs=question_display, outputs=score_textbox)
1153
- # # def compare_answers(html_content):
1154
- # # if not quiz_data or not quiz_data.items:
1155
- # # return "Please generate a quiz first."
1156
- # # # Placeholder for user answers (adjust based on actual UI implementation)
1157
- # # user_answers = [] # Implement parsing logic if using radio inputs
1158
- # # correct_answers = [item.correct_answer for item in quiz_data.items[:10]]
1159
- # # score = sum(1 for u, c in zip(user_answers, correct_answers) if u == c)
1160
- # # if score > 7:
1161
- # # message = f"### Excellent! You got {score} out of 10!"
1162
- # # elif score > 5:
1163
- # # message = f"### Good! You got {score} out of 10!"
1164
- # # else:
1165
- # # message = f"### You got {score} out of 10! Don't worry. You can prepare well and try better next time!"
1166
- # # return message
1167
-
1168
- # # if __name__ == "__main__":
1169
- # # QUIZBOT.queue().launch(debug=True)
1170
-
1171
- # # # # Importing libraries
1172
- # # # import pandas as pd
1173
- # # # import json
1174
- # # # import gradio as gr
1175
- # # # from pathlib import Path
1176
- # # # from ragatouille import RAGPretrainedModel
1177
- # # # from gradio_client import Client
1178
- # # # from tempfile import NamedTemporaryFile
1179
- # # # from sentence_transformers import CrossEncoder
1180
- # # # import numpy as np
1181
- # # # from time import perf_counter
1182
- # # # from sentence_transformers import CrossEncoder
1183
-
1184
- # # # #calling functions from other files - to call the knowledge database tables (lancedb for accurate mode) for creating quiz
1185
- # # # from backend.semantic_search import table, retriever
1186
-
1187
- # # # VECTOR_COLUMN_NAME = "vector"
1188
- # # # TEXT_COLUMN_NAME = "text"
1189
- # # # proj_dir = Path.cwd()
1190
-
1191
- # # # # Set up logging
1192
- # # # import logging
1193
- # # # logging.basicConfig(level=logging.INFO)
1194
- # # # logger = logging.getLogger(__name__)
1195
-
1196
- # # # # Replace Mixtral client with Qwen Client
1197
- # # # client = Client("Qwen/Qwen1.5-110B-Chat-demo")
1198
-
1199
- # # # def system_instructions(question_difficulty, topic, documents_str):
1200
- # # # return f"""<s> [INST] You are a great teacher and your task is to create 10 questions with 4 choices with {question_difficulty} difficulty about the topic request "{topic}" only from the below given documents, {documents_str}. Then create answers. Index in JSON format, the questions as "Q#":"" to "Q#":"", the four choices as "Q#:C1":"" to "Q#:C4":"", and the answers as "A#":"Q#:C#" to "A#":"Q#:C#". Example: 'A10':'Q10:C3' [/INST]"""
1201
-
1202
- # # # # Ragatouille database for Colbert ie highly accurate mode
1203
- # # # RAG_db = gr.State()
1204
- # # # quiz_data = None
1205
-
1206
-
1207
- # # # #defining a function to convert json file to excel file
1208
- # # # def json_to_excel(output_json):
1209
- # # # # Initialize list for DataFrame
1210
- # # # data = []
1211
- # # # gr.Warning('Generating Shareable file link..', duration=30)
1212
- # # # for i in range(1, 11): # Assuming there are 10 questions
1213
- # # # question_key = f"Q{i}"
1214
- # # # answer_key = f"A{i}"
1215
-
1216
- # # # question = output_json.get(question_key, '')
1217
- # # # correct_answer_key = output_json.get(answer_key, '')
1218
- # # # #correct_answer = correct_answer_key.split(':')[-1] if correct_answer_key else ''
1219
- # # # correct_answer = correct_answer_key.split(':')[-1].replace('C', '').strip() if correct_answer_key else ''
1220
-
1221
- # # # # Extract options
1222
- # # # option_keys = [f"{question_key}:C{i}" for i in range(1, 6)]
1223
- # # # options = [output_json.get(key, '') for key in option_keys]
1224
-
1225
- # # # # Add data row
1226
- # # # data.append([
1227
- # # # question, # Question Text
1228
- # # # "Multiple Choice", # Question Type
1229
- # # # options[0], # Option 1
1230
- # # # options[1], # Option 2
1231
- # # # options[2] if len(options) > 2 else '', # Option 3
1232
- # # # options[3] if len(options) > 3 else '', # Option 4
1233
- # # # options[4] if len(options) > 4 else '', # Option 5
1234
- # # # correct_answer, # Correct Answer
1235
- # # # 30, # Time in seconds
1236
- # # # '' # Image Link
1237
- # # # ])
1238
-
1239
- # # # # Create DataFrame
1240
- # # # df = pd.DataFrame(data, columns=[
1241
- # # # "Question Text",
1242
- # # # "Question Type",
1243
- # # # "Option 1",
1244
- # # # "Option 2",
1245
- # # # "Option 3",
1246
- # # # "Option 4",
1247
- # # # "Option 5",
1248
- # # # "Correct Answer",
1249
- # # # "Time in seconds",
1250
- # # # "Image Link"
1251
- # # # ])
1252
-
1253
- # # # temp_file = NamedTemporaryFile(delete=False, suffix=".xlsx")
1254
- # # # df.to_excel(temp_file.name, index=False)
1255
- # # # return temp_file.name
1256
- # # # # Define a colorful theme
1257
- # # # colorful_theme = gr.themes.Default(
1258
- # # # primary_hue="cyan", # Set a bright cyan as primary color
1259
- # # # secondary_hue="yellow", # Set a bright magenta as secondary color
1260
- # # # neutral_hue="purple" # Optionally set a neutral color
1261
-
1262
- # # # )
1263
-
1264
- # # # #gradio app creation for a user interface
1265
- # # # with gr.Blocks(title="Quiz Maker", theme=colorful_theme) as QUIZBOT:
1266
-
1267
-
1268
- # # # # Create a single row for the HTML and Image
1269
- # # # with gr.Row():
1270
- # # # with gr.Column(scale=2):
1271
- # # # gr.Image(value='logo.png', height=200, width=200)
1272
- # # # with gr.Column(scale=6):
1273
- # # # gr.HTML("""
1274
- # # # <center>
1275
- # # # <h1><span style="color: purple;">GOVERNMENT HIGH SCHOOL,SUTHUKENY</span> STUDENTS QUIZBOT </h1>
1276
- # # # <h2>Generative AI-powered Capacity building for STUDENTS</h2>
1277
- # # # <i>⚠️ Students can create quiz from any topic from 10 science and evaluate themselves! ⚠️</i>
1278
- # # # </center>
1279
- # # # """)
1280
-
1281
-
1282
-
1283
-
1284
- # # # topic = gr.Textbox(label="Enter the Topic for Quiz", placeholder="Write any CHAPTER NAME")
1285
-
1286
- # # # with gr.Row():
1287
- # # # difficulty_radio = gr.Radio(["easy", "average", "hard"], label="How difficult should the quiz be?")
1288
- # # # model_radio = gr.Radio(choices=[ '(ACCURATE) BGE reranker', '(HIGH ACCURATE) ColBERT'],
1289
- # # # value='(ACCURATE) BGE reranker', label="Embeddings",
1290
- # # # info="First query to ColBERT may take a little time")
1291
-
1292
- # # # generate_quiz_btn = gr.Button("Generate Quiz!🚀")
1293
- # # # quiz_msg = gr.Textbox()
1294
-
1295
- # # # question_radios = [gr.Radio(visible=False) for _ in range(10)]
1296
-
1297
- # # # @generate_quiz_btn.click(inputs=[difficulty_radio, topic, model_radio], outputs=[quiz_msg] + question_radios + [gr.File(label="Download Excel")])
1298
- # # # def generate_quiz(question_difficulty, topic, cross_encoder):
1299
- # # # top_k_rank = 10
1300
- # # # documents = []
1301
- # # # gr.Warning('Generating Quiz may take 1-2 minutes. Please wait.', duration=60)
1302
-
1303
- # # # if cross_encoder == '(HIGH ACCURATE) ColBERT':
1304
- # # # gr.Warning('Retrieving using ColBERT.. First-time query will take 2 minute for model to load.. please wait',duration=100)
1305
- # # # RAG = RAGPretrainedModel.from_pretrained("colbert-ir/colbertv2.0")
1306
- # # # RAG_db.value = RAG.from_index('.ragatouille/colbert/indexes/cbseclass10index')
1307
- # # # documents_full = RAG_db.value.search(topic, k=top_k_rank)
1308
- # # # documents = [item['content'] for item in documents_full]
1309
-
1310
- # # # else:
1311
- # # # document_start = perf_counter()
1312
- # # # query_vec = retriever.encode(topic)
1313
- # # # doc1 = table.search(query_vec, vector_column_name=VECTOR_COLUMN_NAME).limit(top_k_rank)
1314
-
1315
- # # # documents = table.search(query_vec, vector_column_name=VECTOR_COLUMN_NAME).limit(top_k_rank).to_list()
1316
- # # # documents = [doc[TEXT_COLUMN_NAME] for doc in documents]
1317
-
1318
- # # # query_doc_pair = [[topic, doc] for doc in documents]
1319
-
1320
- # # # # if cross_encoder == '(FAST) MiniLM-L6v2':
1321
- # # # # cross_encoder1 = CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2')
1322
- # # # if cross_encoder == '(ACCURATE) BGE reranker':
1323
- # # # cross_encoder1 = CrossEncoder('BAAI/bge-reranker-base')
1324
-
1325
- # # # cross_scores = cross_encoder1.predict(query_doc_pair)
1326
- # # # sim_scores_argsort = list(reversed(np.argsort(cross_scores)))
1327
- # # # documents = [documents[idx] for idx in sim_scores_argsort[:top_k_rank]]
1328
-
1329
- # # # #creating a text prompt to Qwen model combining the documents and system instruction
1330
- # # # formatted_prompt = system_instructions(question_difficulty, topic, '\n'.join(documents))
1331
- # # # print(' Formatted Prompt : ' ,formatted_prompt)
1332
- # # # try:
1333
- # # # response = client.predict(query=formatted_prompt, history=[], system="You are a helpful assistant.", api_name="/model_chat")
1334
- # # # response1 = response[1][0][1]
1335
-
1336
- # # # # Extract JSON
1337
- # # # start_index = response1.find('{')
1338
- # # # end_index = response1.rfind('}')
1339
- # # # cleaned_response = response1[start_index:end_index + 1] if start_index != -1 and end_index != -1 else ''
1340
- # # # print('Cleaned Response :',cleaned_response)
1341
- # # # output_json = json.loads(cleaned_response)
1342
- # # # # Assign the extracted JSON to quiz_data for use in the comparison function
1343
- # # # global quiz_data
1344
- # # # quiz_data = output_json
1345
- # # # # Generate the Excel file
1346
- # # # excel_file = json_to_excel(output_json)
1347
-
1348
-
1349
- # # # #Create a Quiz display in app
1350
- # # # question_radio_list = []
1351
- # # # for question_num in range(1, 11):
1352
- # # # question_key = f"Q{question_num}"
1353
- # # # answer_key = f"A{question_num}"
1354
-
1355
- # # # question = output_json.get(question_key)
1356
- # # # answer = output_json.get(output_json.get(answer_key))
1357
-
1358
- # # # if not question or not answer:
1359
- # # # continue
1360
-
1361
- # # # choice_keys = [f"{question_key}:C{i}" for i in range(1, 5)]
1362
- # # # choice_list = [output_json.get(choice_key, "Choice not found") for choice_key in choice_keys]
1363
-
1364
- # # # radio = gr.Radio(choices=choice_list, label=question, visible=True, interactive=True)
1365
- # # # question_radio_list.append(radio)
1366
-
1367
- # # # return ['Quiz Generated!'] + question_radio_list + [excel_file]
1368
-
1369
- # # # except json.JSONDecodeError as e:
1370
- # # # print(f"Failed to decode JSON: {e}")
1371
-
1372
- # # # check_button = gr.Button("Check Score")
1373
- # # # score_textbox = gr.Markdown()
1374
-
1375
- # # # @check_button.click(inputs=question_radios, outputs=score_textbox)
1376
- # # # def compare_answers(*user_answers):
1377
- # # # user_answer_list = list(user_answers)
1378
- # # # answers_list = []
1379
-
1380
- # # # for question_num in range(1, 11):
1381
- # # # answer_key = f"A{question_num}"
1382
- # # # answer = quiz_data.get(quiz_data.get(answer_key))
1383
- # # # if not answer:
1384
- # # # break
1385
- # # # answers_list.append(answer)
1386
-
1387
- # # # score = sum(1 for item in user_answer_list if item in answers_list)
1388
-
1389
- # # # if score > 7:
1390
- # # # message = f"### Excellent! You got {score} out of 10!"
1391
- # # # elif score > 5:
1392
- # # # message = f"### Good! You got {score} out of 10!"
1393
- # # # else:
1394
- # # # message = f"### You got {score} out of 10! Don't worry. You can prepare well and try better next time!"
1395
-
1396
- # # # return message
1397
-
1398
- # # # QUIZBOT.queue()
1399
- # # # QUIZBOT.launch(debug=True)
1400
 
 
226
 
227
  if __name__ == "__main__":
228
  QUIZBOT.queue().launch(server_name="0.0.0.0", server_port=7860)# import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229