NSO / app.py
Hidayatmahar's picture
Update app.py
a225a69 verified
import gradio as gr
import json
import random
from fpdf import FPDF
# Load questions (flat list)
with open("questions.json", "r") as f:
all_questions = json.load(f)
# Select 50 random questions
def get_test_questions():
return random.sample(all_questions, 50)
# Store current test questions globally
current_test_questions = get_test_questions()
# Function to grade test
def grade_test(student_name, father_name, roll_no, *answers):
questions = current_test_questions
score = 0
for ans, q in zip(answers, questions):
if ans == q["answer"]:
score += 1
percentage = (score / len(questions)) * 100
# Generate PDF report
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
pdf.cell(200, 10, txt="Test Report", ln=True, align="C")
pdf.ln(10)
pdf.cell(200, 10, txt=f"Student Name: {student_name}", ln=True)
pdf.cell(200, 10, txt=f"Father's Name: {father_name}", ln=True)
pdf.cell(200, 10, txt=f"Roll No: {roll_no}", ln=True)
pdf.cell(200, 10, txt=f"Score: {score} / {len(questions)}", ln=True)
pdf.cell(200, 10, txt=f"Percentage: {percentage:.2f}%", ln=True)
file_name = f"{roll_no}_result.pdf"
pdf.output(file_name)
return f"Score: {score} / {len(questions)}\nPercentage: {percentage:.2f}%", file_name
# Input fields for student info
student_inputs = [
gr.Textbox(label="Student Name", placeholder="Enter your name"),
gr.Textbox(label="Father's Name", placeholder="Enter father's name"),
gr.Textbox(label="Roll No", placeholder="Enter roll no"),
]
# Create dynamic question components
question_components = []
for i, q in enumerate(current_test_questions):
question_components.append(
gr.Radio(choices=q["options"], label=f"Q{i+1}. {q['question']}")
)
# Build Gradio interface
demo = gr.Interface(
fn=grade_test,
inputs=student_inputs + question_components,
outputs=[gr.Textbox(label="Result"), gr.File(label="Download PDF")],
title="Class Test Application",
description="Answer the following 50 questions and download your result as PDF.",
)
if __name__ == "__main__":
demo.launch()