turtle / app.py
papuk0047's picture
restored old
fdbbdd2
Raw History Blame Contribute Delete
3.13 kB
import gradio as gr
import random
def generate_question(mode, upper, lower):
x = random.randint(lower, upper)
y = random.randint(lower, upper)
if mode == "subtract" and y > x:
x, y = y, x
if mode == "add":
answer = x + y
symbol = "+"
elif mode == "subtract":
answer = x - y
symbol = "-"
else:
answer = x * y
symbol = "×"
question_text = f"{x} {symbol} {y}"
return question_text, answer
def start_quiz(mode, amount, sizeB, sizeS):
try:
amount = int(amount)
sizeB = int(sizeB)
sizeS = int(sizeS)
except ValueError:
return "Error: All number inputs must be integers."
lower = min(sizeB, sizeS)
upper = max(sizeB, sizeS)
questions = []
answers = []
for _ in range(amount):
q, a = generate_question(mode, upper, lower)
questions.append(q)
answers.append(a)
session_data = {
"mode": mode,
"questions": questions,
"answers": answers,
"user_answers": [""] * amount
}
return gr.update(visible=True), session_data, "\n".join([f"{i+1}. {q}" for i, q in enumerate(questions)])
def submit_answers(session_data, user_input):
try:
user_answers = user_input.strip().split("\n")
correct = 0
total = len(session_data["answers"])
feedback = []
for i in range(total):
try:
ua = int(user_answers[i].strip())
ca = session_data["answers"][i]
if ua == ca:
feedback.append(f"✅ Q{i+1}: Correct")
correct += 1
else:
feedback.append(f"❌ Q{i+1}: Wrong (Your answer: {ua}, Correct: {ca})")
except:
feedback.append(f"❌ Q{i+1}: Invalid input")
score = f"Score: {correct}/{total}"
return "\n".join(feedback) + f"\n\n{score}"
except Exception as e:
return f"Error processing answers: {e}"
with gr.Blocks() as demo:
gr.Markdown("## 🧠 Math Quiz (Add / Subtract / Multiply)")
with gr.Row():
mode = gr.Radio(["add", "subtract", "multiply"], label="Operation")
amount = gr.Textbox(label="Number of Questions", value="5")
sizeB = gr.Textbox(label="Maximum Number", value="10")
sizeS = gr.Textbox(label="Minimum Number", value="1")
start_btn = gr.Button("Start Quiz")
quiz_display = gr.Textbox(label="Your Questions", lines=10, interactive=False)
session_state = gr.State()
with gr.Column(visible=False) as quiz_interface:
answers_input = gr.Textbox(label="Enter Your Answers (one per line)", lines=10)
submit_btn = gr.Button("Submit Answers")
results = gr.Textbox(label="Results", lines=10, interactive=False)
start_btn.click(
start_quiz,
inputs=[mode, amount, sizeB, sizeS],
outputs=[quiz_interface, session_state, quiz_display]
)
submit_btn.click(
submit_answers,
inputs=[session_state, answers_input],
outputs=results
)
demo.launch()