QuizWhiz-Quest / app.py
amitagh's picture
trucate text
a2b22b4 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(ctxt_txt,ques_type, num_questions):
res = client.predict(
ctxt_txt=ctxt_txt,
ques_type=ques_type,
num_questions=num_questions,
api_name="/gen_tryme_quiz_ques_llm_rem"
)
print(res)
return json.loads(res)
def generate_quiz(ctxt_txt,ques_type, num_questions):
if not ctxt_txt or not num_questions:
return [[], "Please select both Context Text and number of questions before generating the quiz."] + [gr.update(visible=False) for _ in range(2 * MAX_ANS_COMP)]
num_questions = int(num_questions)
if len(ctxt_txt) > 10000:
ctxt_txt = ctxt_txt[:10000]
quiz = gen_quiz_ques_local(ctxt_txt, ques_type, 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)] + [""]
default_ctxt_txt = """APJ Abdul Kalam (15 October 1931 – 27 July 2015) was an Indian aerospace scientist and statesman who served as the 11th president of India from 2002 to 2007. Born and raised in a Muslim family in Rameswaram, Tamil Nadu, he studied physics and aerospace engineering. He spent the next four decades as a scientist and science administrator, mainly at the Defence Research and Development Organisation (DRDO) and Indian Space Research Organisation (ISRO) and was intimately involved in India's civilian space programme and military missile development efforts.[1] He thus came to be known as the Missile Man of India for his work on the development of ballistic missile and launch vehicle technology. He also played a pivotal organisational, technical, and political role in India's Pokhran-II nuclear tests in 1998, the first since the original nuclear test by India in 1974.
Kalam was elected as the 11th president of India in 2002 with the support of both the ruling Bharatiya Janata Party and the then-opposition Indian National Congress. Widely referred to as the "People's President", he returned to his civilian life of education, writing and public service after a single term. He was a recipient of several prestigious awards, including the Bharat Ratna, India's highest civilian honour."""
with gr.Blocks() as app:
with gr.Row():
gr.set_static_paths(paths=["."])
image_path = "quiz-quest-banner.jpg"
gr.HTML(f"""<img src="/file={image_path}" width="500" height="200">""")
context_txt = gr.Textbox(label="Enter Text to build the quiz on:", value=default_ctxt_txt)
with gr.Row():
ques_type = gr.Dropdown(choices=["MCQ"], label="Question Type", value="MCQ") #, "True/False", "Fill-blanks"
num_questions = gr.Dropdown(choices=[5, 10, 15, 20], label="Number of Questions", value=10)
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=[context_txt, ques_type, 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)