How to Automate Exam Paper Creation Using Python and Google Generative AI

How to Automate Exam Paper Creation Using Python and Google Generative AI

Creating an exam paper manually can be time-consuming, especially when you need to generate a variety of questions, each requiring a different format or approach. However, with the power of Python, Google Generative AI, and some basic user input, we can automate this process. In this blog, I’ll walk through how we can build a Python script that generates exam questions based on the user's choice of question types, styles, and subject matter, saving it directly into a .txt file.


Prerequisites:

  1. Basic knowledge of Python: You should be comfortable with writing Python code and handling files.

  2. Google Generative AI API access: You’ll need an API key from Google to access its generative models.

  3. Environment Setup: Install the python-dotenv library to manage API keys securely.

To get started, install the required dependencies using the command:

pip install python-dotenv google-generativeai

Step 1: Setting Up Environment Variables

We will store our API key securely in a .env file to keep our credentials safe. Here’s a basic example of what your .env file should look like:

API_KEY=your-google-generative-ai-api-key-here

The dotenv module will load this file in the script. Make sure that this .env file is never exposed in your code repository.

Step 2: Code Overview

The main functions in our script include:

  1. generate_question(): This function calls the Google Generative AI model to generate a question based on the user-defined style.

  2. calculate_num_questions(): Based on the total marks and the marks per question type (MCQ, SAQ, LAQ), this function determines how many questions should be included.

  3. generate_exam(): This is the core function that integrates everything. It asks the user for inputs, such as the subject name, total marks, selected question types, and styles (e.g., theoretical, analytical, etc.). The questions are then written into a text file.

Code Implementation:

pythonCopy codefrom dotenv import load_dotenv
import os
import google.generativeai as genai

# Load environment variables from .env file
load_dotenv()

# Configure API key for Google Generative AI
genai.configure(api_key=os.environ["API_KEY"])

# Function to generate a question from AI
def generate_question(prompt):
    model = genai.GenerativeModel("gemini-1.5-flash")
    response = model.generate_content(prompt)
    return response.text.strip()

# Function to automatically calculate the number of questions based on total marks and marks per type
def calculate_num_questions(total_marks, question_types):
    num_questions = {}
    remaining_marks = total_marks

    for q_type, marks in question_types.items():
        num_questions[q_type] = remaining_marks // marks
        remaining_marks -= num_questions[q_type] * marks

    return num_questions

# Function to generate the exam paper
def generate_exam(subject_name, total_marks, selected_types, question_styles, question_types):
    # File path for saving the exam as a .txt file
    txt_file_path = f"{subject_name}_exam_paper.txt"

    # Open the text file for writing
    with open(txt_file_path, 'w', encoding='utf-8') as txt_file:
        # Write the exam title and details
        txt_file.write(f"Exam Paper\n")
        txt_file.write(f"Subject: {subject_name}\n")
        txt_file.write(f"Total Marks: {total_marks}\n")
        txt_file.write("\n")

        # Calculate number of questions based on marks
        num_questions = calculate_num_questions(total_marks, {k: question_types[k] for k in selected_types})
        remaining_marks = total_marks
        question_number = 1

        # Generate questions for each selected type
        for q_type in selected_types:
            marks = question_types[q_type]
            for _ in range(num_questions[q_type]):
                if remaining_marks <= 0:
                    break

                # Select prompt based on the question style
                style_prompt = f"{question_styles[q_type]} on {subject_name}."

                # Set question prompt based on question type and style
                if q_type == 'MCQ':
                    prompt = f"Create a multiple-choice {style_prompt}"
                elif q_type == 'SAQ':
                    prompt = f"Create a short answer {style_prompt}"

                # Generate the question text
                question_text = generate_question(prompt)

                # Write the question to the text file
                txt_file.write(f"Q{question_number}. {question_text} [{marks} Marks]\n\n")

                # Update the remaining marks and question number
                remaining_marks -= marks
                question_number += 1

    print(f"Exam paper generated and saved as {txt_file_path}")

# Example input for generating the exam paper
subject_name = input("Enter the subject name: ")
total_marks = int(input("Enter the total marks for the exam: "))

# Define question types with corresponding marks per question
question_types = {
    "MCQ": 2,   # Multiple Choice Questions worth 2 marks each
    "VSAQ": 2,  # Very Short Answer Questions worth 2 marks each
    "SAQ": 5,   # Short Answer Questions worth 5 marks each
    "LAQ": 10   # Long Answer Questions worth 10 marks each
}

# Prompt user to select which question types to include
available_types = ["MCQ", "VSAQ", "SAQ", "LAQ"]
selected_types = []
print("Select the question types to include (MCQ, VSAQ, SAQ, LAQ). You can choose any combination.")
for q_type in available_types:
    include = input(f"Include {q_type}? (yes/no): ").strip().lower()
    if include == 'yes':
        selected_types.append(q_type)

# Define question styles (Theoretical, Numerical, Analytical, etc.)
question_styles = {}
for q_type in selected_types:
    question_styles[q_type] = input(f"Enter style for {q_type} (e.g., Theoretical, Numerical, Analytical): ")

# Generate the exam paper and save as a text file
generate_exam(subject_name, total_marks, selected_types, question_styles, question_types)

Step 3: How It Works

  1. Prompting the User: The user is asked to input the subject name, total marks, types of questions (MCQ, VSAQ, SAQ, LAQ), and the style of the questions (e.g., Theoretical, Analytical).

  2. Generating Questions: Based on these inputs, the script generates the number of questions needed to meet the total marks. For each question, it calls the Google Generative AI API to get a question prompt fitting the criteria.

  3. Saving to a Text File: The generated exam paper is saved as a .txt file with all the questions, their corresponding marks, and question numbers.

Example Output:

Here’s an example of what the generated exam might look like:

Exam Paper
Subject: Computer Science
Total Marks: 50

Q1. What is the primary function of the CPU in a computer system? [2 Marks]

Q2. How does a binary search algorithm improve search time compared to linear search? [5 Marks]

Q3. Write a program to find the largest of three numbers using C language. [5 Marks]

Q4. What are the differences between RAM and ROM in a computer system? [2 Marks]

...

Conclusion:

By using Python and Google Generative AI, this script allows for the automation of generating well-structured exam papers. It not only saves time but also ensures diversity and customization of questions. Feel free to modify and extend the script for different use cases like quizzes, assignments, or even interview question sets.

This approach can significantly reduce the manual effort in paper setting and ensure consistent quality in question generation.