import json import gradio as gr def process_json_file(file): try: # Read and print the file content for debugging print("File received:", file.name) # Read the JSON file with open(file.name, 'r') as f: print("Reading file contents...") json_data = json.load(f) # Print the structure of the JSON data print("\nJSON Structure:") print("Available sections:", list(json_data.keys())) # Process each section output_text = "" # Process header if exists if 'header' in json_data: output_text += "=== EXAM DETAILS ===\n" for key, value in json_data['header'].items(): output_text += f"{key.replace('_', ' ').title()}: {value}\n" output_text += "\n" # Process multiple choice questions if 'multiple_choice_questions' in json_data: output_text += "=== MULTIPLE CHOICE QUESTIONS ===\n" for q_num, q_data in json_data['multiple_choice_questions'].items(): output_text += f"\nQuestion {q_num.replace('question', '')}:\n" output_text += f"{q_data['question']}\n" for opt_key, opt_val in q_data['options'].items(): output_text += f"{opt_key}) {opt_val}\n" output_text += f"Answer: {q_data['answer']}\n" # Process short answer questions if 'short_answer_questions' in json_data: output_text += "\n=== SHORT ANSWER QUESTIONS ===\n" for q_num, q_data in json_data['short_answer_questions'].items(): output_text += f"\nQuestion {q_num.replace('question', '')}:\n" output_text += f"{q_data['question']}\n" output_text += f"Answer: {q_data['answer']}\n" # Process long answer questions if 'long_answer_questions' in json_data: output_text += "\n=== LONG ANSWER QUESTIONS ===\n" for q_num, q_data in json_data['long_answer_questions'].items(): output_text += f"\nQuestion {q_num.replace('question', '')}:\n" output_text += f"{q_data['question']}\n" output_text += f"Answer: {q_data['answer']}\n" print("\nProcessing complete!") return output_text except json.JSONDecodeError as e: error_msg = f"Error decoding JSON: {str(e)}" print(error_msg) return error_msg except Exception as e: error_msg = f"Error processing file: {str(e)}" print(error_msg) return error_msg # Create Gradio interface with gr.Blocks() as iface: gr.Markdown("# Exam Question Viewer") with gr.Row(): file_input = gr.File( label="Upload JSON Exam File", file_types=[".json"] ) with gr.Row(): output_text = gr.Textbox( label="Processed Questions", lines=20, max_lines=30 ) file_input.upload( fn=process_json_file, inputs=[file_input], outputs=[output_text] ) # Launch the interface iface.launch()