quizwhiz / app.py
amitagh's picture
banere
9f704ed verified
import gradio as gr
import random
import os
import json
from PIL import Image
from gradio_client import Client
MAX_ANS_COMP = 30
hf_key = os.environ['HF_API_KEY']
client_url = os.environ['BK_URL']
client = Client(client_url, hf_token=hf_key)
def gen_quiz_ques_local(grade, num_questions):
res = client.predict(
grade=grade, num_questions=num_questions,
api_name="/gen_quiz_ques"
)
print(res)
return json.loads(res)
def generate_quiz(grade, num_questions):
if not grade or not num_questions:
return [[], "Please select both grade and number of questions before generating the quiz."] + [gr.update(visible=False) for _ in range(5)]
if grade == "Any":
grade = 10
else:
grade = int(grade)
num_questions = int(num_questions)
quiz = gen_quiz_ques_local(grade, num_questions)
if quiz == None:
return [[], f"Error please generate again."] + [gr.update(visible=False) for _ in range(MAX_ANS_COMP)]
quiz_html = ""
radio_updates = [gr.update(visible=True, choices=q['options'], label=f"Question {i+1}: {q['question']}") for i, q in enumerate(quiz)]
radio_updates += [gr.update(visible=False) for _ in range(MAX_ANS_COMP - len(quiz))]
return [quiz, quiz_html] + radio_updates
def check_answers(quiz, *answers):
if not quiz:
return "Please generate a quiz first."
if any(ans is None for ans in answers[:len(quiz)]):
return "Please answer all questions before submitting."
results = []
correct_count = 0
for i, (q, ans) in enumerate(zip(quiz, answers), 1):
if ans == q['answer']:
results.append(f"{i}. βœ… Correct")
correct_count += 1
else:
results.append(f"{i}. ❌ Incorrect. You selected: {ans}. The correct answer is: {q['answer']}")
score = f"Score: {correct_count} out of {len(quiz)} correct"
per_cor = (correct_count / len(quiz)) * 100
if per_cor <= 20:
score = "Don't worry, everyone starts somewhere! Keep learning and trying, and you'll get better each time. You've got this!\n" + score
elif per_cor <= 40:
score = "Great effort! You're on the right track. Keep up the good work and continue to challenge yourself. You can do it!\n" + score
elif per_cor <= 60:
score = "Well done! You've got a solid understanding. Keep pushing forward and aiming higher. You're doing awesome!\n" + score
elif per_cor <= 80:
score = "Fantastic job! You're really getting the hang of this. Keep up the excellent work and keep striving for the top!\n" + score
elif per_cor <= 100:
score = "Amazing! You've nailed it! Your hard work and dedication have paid off. Keep up the incredible work!\n" + score
return f"{score}<br><br>" + "<br>".join(results)
def clear_quiz():
return [[], ""] + [gr.update(visible=False, value=None) for _ in range(MAX_ANS_COMP)] + [""]
with gr.Blocks() as app:
with gr.Row():
gr.set_static_paths(paths=["."])
image_path = "bannere.jpg"
gr.HTML(f"""<img src="/file={image_path}" width="500" height="200">""")
#gr.Markdown("# QuizWhiz: Your Quiz Master")
#gr.Markdown("* Welcome to the ultimate trivia challenge! Whether you're a curious kid or a lifelong learner, this app is designed to test your knowledge and keep your mind sharp.")
#gr.Markdown("* Select Kid school grade and number of questions to generate. Choose Any as grade for above 8th Grade or Adults.")
#gr.Markdown("* Press Generate to generate quiz questions. Press Submit once you are done answering. Press Clear to clear the questions.")
#gr.Image(value ="banner.jpg", interactive = False, width=375, height=150, show_download_button=False, show_label=False, show_share_button=False)
#gr.Markdown("Welcome to the ultimate trivia challenge! Whether you're a curious kid or a lifelong learner, this app is designed to test your knowledge and keep your mind sharp.")
#gr.Markdown("Select Kid school grade and number of questions to generate. Choose Any as grade for above 8th Grade or Adults.")
#gr.Markdown("Press Generate to generate quiz questions. Press Submit once you are done answering. Press Clear to clear the questions.")
with gr.Row():
grade = gr.Dropdown(choices=[3,4, 5, 6, 7, 8, "Any"], label="Grade", value=6)
num_questions = gr.Dropdown(choices=[5, 10, 15, 20], label="Number of Questions", value=5)
#num_questions = gr.Slider(minimum=1, maximum=MAX_ANS_COMP, step=1, value=10, label="Number of Questions")
generate_btn = gr.Button("Generate Quiz")
quiz_output = gr.HTML()
quiz_state = gr.State([])
answer_components = [gr.Radio(visible=False, label=f"Question {i+1}") for i in range(MAX_ANS_COMP)]
submit_btn = gr.Button("Submit Answers")
results_output = gr.HTML()
clear_btn = gr.Button("Clear Quiz")
generate_btn.click(
generate_quiz,
inputs=[grade, num_questions],
outputs=[quiz_state, quiz_output] + answer_components
)
submit_btn.click(
check_answers,
inputs=[quiz_state] + answer_components,
outputs=results_output
)
clear_btn.click(
clear_quiz,
outputs=[quiz_state, quiz_output] + answer_components + [results_output]
)
app.launch(debug=True)