import gradio as gr import json import random import datetime # Load questions from JSON file with open("questions.json", "r", encoding="utf-8") as f: all_questions = json.load(f) # Global storage for session sessions = {} def start_test(name, father_name, roll_number): # Pick 50 random questions questions = random.sample(all_questions, 50) session_id = roll_number + "_" + str(datetime.datetime.now().timestamp()) # Save session data sessions[session_id] = { "name": name, "father_name": father_name, "roll_number": roll_number, "questions": questions, "current": 0, "score": 0, "answers": [] } q = questions[0] return session_id, f"Q1: {q['question']}", gr.Radio(choices=q["options"], value=None, label="Choose your answer"), f"Question 1 of 50" def next_question(session_id, answer): data = sessions[session_id] # Record answer current_q = data["questions"][data["current"]] data["answers"].append({"question": current_q["question"], "your_answer": answer, "correct": current_q["answer"]}) if answer == current_q["answer"]: data["score"] += 1 data["current"] += 1 if data["current"] >= len(data["questions"]): # Test finished result_text = ( f"Result Card\n" f"Name: {data['name']}\n" f"Father's Name: {data['father_name']}\n" f"Roll No: {data['roll_number']}\n" f"Total Questions: 50\n" f"Correct: {data['score']}\n" f"Wrong: {50 - data['score']}\n" f"Percentage: {data['score'] * 100 / 50:.2f}%\n" ) file_name = f"result_{data['roll_number']}.txt" with open(file_name, "w", encoding="utf-8") as f: f.write(result_text) return "Test Completed!", None, None, result_text, file_name # Show next question q = data["questions"][data["current"]] return ( session_id, f"Q{data['current']+1}: {q['question']}", gr.Radio(choices=q["options"], value=None, label="Choose your answer"), f"Question {data['current']+1} of 50", ) with gr.Blocks() as demo: gr.Markdown("## 📝 5th Class Intelligence Test (50 Questions)") with gr.Tab("Start Test"): name = gr.Textbox(label="Your Name") father_name = gr.Textbox(label="Father's Name") roll_number = gr.Textbox(label="Roll Number") start_btn = gr.Button("Start Test") session_id = gr.State() question_text = gr.Textbox(label="Question", interactive=False) options = gr.Radio(label="Options") q_count = gr.Textbox(label="Progress", interactive=False) next_btn = gr.Button("Next") result_box = gr.Textbox(label="Result", interactive=False) result_file = gr.File(label="Download Result") start_btn.click( start_test, inputs=[name, father_name, roll_number], outputs=[session_id, question_text, options, q_count] ) next_btn.click( next_question, inputs=[session_id, options], outputs=[session_id, question_text, options, q_count, result_box, result_file] ) demo.launch()