Spaces:
Sleeping
Sleeping
import streamlit as st | |
from transformers import pipeline | |
import random | |
# Load the pipeline with caching | |
def load_pipeline(): | |
return pipeline("text2text-generation", model="valhalla/t5-small-e2e-qg") | |
# Initialize the pipeline | |
qg_pipeline = load_pipeline() | |
# UI Header | |
st.markdown("# Text-to-Quiz Generator") | |
st.markdown("Enter a passage below and let AI create an interactive quiz for you!") | |
st.markdown("---") | |
# Input section | |
passage = st.text_area("Paste your text here:", height=150) | |
if st.button("Generate Quiz"): | |
with st.spinner("Generating your quiz..."): | |
# Generate question-answer pairs (adjust based on actual model output format) | |
generated = qg_pipeline(passage, max_length=512) | |
# For this example, assume the model outputs a list of strings like "Q: ... A: ..." | |
# Parse the output into questions and answers (modify this based on your model's actual output) | |
quiz_data = [] | |
for item in generated: | |
if "Q:" in item["generated_text"] and "A:" in item["generated_text"]: | |
q, a = item["generated_text"].split("A:") | |
question = q.replace("Q:", "").strip() | |
answer = a.strip() | |
quiz_data.append({"question": question, "answer": answer}) | |
if not quiz_data: | |
st.error("No valid questions generated. Please try a different passage.") | |
else: | |
# Store quiz data in session state | |
st.session_state["quiz_data"] = quiz_data | |
st.session_state["user_answers"] = {} | |
# Display quiz | |
if "quiz_data" in st.session_state: | |
st.markdown("### Your Quiz") | |
questions = [item["question"] for item in st.session_state["quiz_data"]] | |
answers = [item["answer"] for item in st.session_state["quiz_data"]] | |
# Generate distractors for each question | |
for i, question in enumerate(questions): | |
correct_answer = answers[i] | |
distractors = [a for j, a in enumerate(answers) if j != i] | |
options = [correct_answer] + random.sample(distractors, min(3, len(distractors))) | |
random.shuffle(options) | |
st.write(f"**Question {i+1}:** {question}") | |
st.session_state["user_answers"][question] = st.radio( | |
"Select your answer:", options, key=f"q{i}" | |
) | |
# Submit button | |
if st.button("Submit Answers"): | |
score = 0 | |
for i, question in enumerate(questions): | |
user_answer = st.session_state["user_answers"][question] | |
correct_answer = answers[i] | |
if user_answer == correct_answer: | |
st.success(f"**Question {i+1}:** Correct! The answer is '{correct_answer}'.") | |
score += 1 | |
else: | |
st.error(f"**Question {i+1}:** Incorrect. The correct answer is '{correct_answer}', not '{user_answer}'.") | |
st.markdown(f"### Your Score: {score}/{len(questions)}") |