import gradio as gr import json import xml.etree.ElementTree as ET import os from typing import List, Dict, Any class QuizApp: def __init__(self): self.questions = [] self.current_quiz = None def parse_json_file(self, file_path: str) -> List[Dict[str, Any]]: """Parse JSON file containing quiz questions""" try: with open(file_path, 'r', encoding='utf-8') as f: data = json.load(f) questions = [] # Handle different JSON structures if isinstance(data, list): questions = data elif isinstance(data, dict): if 'questions' in data: questions = data['questions'] else: questions = [data] # Validate question format validated_questions = [] for q in questions: if all(key in q for key in ['question', 'options', 'answer']): validated_questions.append({ 'question': q['question'], 'options': q['options'] if isinstance(q['options'], list) else [q['options']], 'answer': q['answer'] }) return validated_questions except Exception as e: raise Exception(f"Error parsing JSON file: {str(e)}") def parse_xml_file(self, file_path: str) -> List[Dict[str, Any]]: """Parse XML file containing quiz questions""" try: tree = ET.parse(file_path) root = tree.getroot() questions = [] # Handle different XML structures question_elements = root.findall('.//question') or root.findall('.//item') for q_elem in question_elements: question_text = q_elem.find('text') or q_elem.find('question') options_elem = q_elem.find('options') or q_elem.find('choices') answer_elem = q_elem.find('answer') or q_elem.find('correct') if question_text is not None and options_elem is not None and answer_elem is not None: options = [] for option in options_elem.findall('option') or options_elem.findall('choice'): if option.text: options.append(option.text.strip()) if len(options) >= 2: # At least 2 options required questions.append({ 'question': question_text.text.strip(), 'options': options, 'answer': answer_elem.text.strip() }) return questions except Exception as e: raise Exception(f"Error parsing XML file: {str(e)}") def load_quiz_file(self, file) -> str: """Load and parse quiz file""" if file is None: return "Please upload a file first." try: file_path = file.name file_extension = os.path.splitext(file_path)[1].lower() if file_extension == '.json': self.questions = self.parse_json_file(file_path) elif file_extension == '.xml': self.questions = self.parse_xml_file(file_path) else: return "Unsupported file format. Please upload a JSON or XML file." if not self.questions: return "No valid questions found in the file. Please check the file format." return f"✅ Successfully loaded {len(self.questions)} questions! Click 'Start Quiz' to begin." except Exception as e: return f"❌ Error loading file: {str(e)}" def generate_quiz_html(self) -> str: """Generate HTML for the quiz interface""" if not self.questions: return "
No questions loaded. Please upload a quiz file first.
" # Create JSON data for JavaScript quiz_data_json = json.dumps(self.questions).replace('"', '"') html = f"""Test your knowledge with {len(self.questions)} questions