File size: 4,530 Bytes
abad164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
!pip install pypdf google-genai pydantic

import os
from google import genai
from google.genai import types
from pypdf import PdfReader
from pydantic import BaseModel, Field
from google.colab import files  # Added for easy Colab file uploading

# =====================================================================
# 1. Define the Strict JSON Schema for the Output
# =====================================================================
class MCQ(BaseModel):
    question: str = Field(description="The multiple-choice question based on the text.")
    options: list[str] = Field(description="Exactly 4 distinct options/choices for the answer.")
    correct_answer: str = Field(description="The correct option, matching exactly one of the options in the list.")
    explanation: str = Field(description="A brief explanation of why this answer is correct based on the text.")

class MCQQuiz(BaseModel):
    quiz: list[MCQ] = Field(description="A list of generated multiple-choice questions.")

# =====================================================================
# 2. Helper Function to Extract Text from PDF
# =====================================================================
def extract_text_from_pdf(pdf_path: str) -> str:
    """Reads a PDF file and extracts all raw text content."""
    if not os.path.exists(pdf_path):
        raise FileNotFoundError(f"Could not find PDF file at: {pdf_path}")
        
    print(f"Reading PDF: {pdf_path}...")
    reader = PdfReader(pdf_path)
    extracted_text = ""
    
    for i, page in enumerate(reader.pages):
        text = page.extract_text()
        if text:
            extracted_text += f"\n--- Page {i+1} ---\n{text}"
            
    return extracted_text.strip()

# =====================================================================
# 3. Main Tool Function to Generate MCQs
# =====================================================================
def generate_mcqs_from_pdf(pdf_path: str, num_questions: int = 5) -> MCQQuiz:
    """Extracts text from a PDF and uses Gemini to generate structured MCQs."""
    source_text = extract_text_from_pdf(pdf_path)
    
    if not source_text:
        raise ValueError("The provided PDF appears to be empty or unscannable.")
        
    print(f"Initializing Gemini Client & generating {num_questions} questions...")
    
    # Initialize the client. Make sure to set your GEMINI_API_KEY in Colab Secrets!
    client = genai.Client()
    
    system_instruction = (
        "You are an expert educator. Your task is to analyze the provided source text "
        "and generate high-quality, conceptual, and factually accurate multiple-choice questions. "
        "Ensure distractors (incorrect options) are plausible but clearly incorrect based on the text."
    )
    
    user_prompt = f"""
    Analyze the following source text and generate exactly {num_questions} multiple-choice questions.
    
    Source Text:
    {source_text}
    """
    
    # Call the model using Structured Outputs
    response = client.models.generate_content(
        model="gemini-2.5-flash",  # Recommended default model for multimodal/text tasks
        contents=user_prompt,
        config=types.GenerateContentConfig(
            system_instruction=system_instruction,
            temperature=0.3,  # Low temperature keeps the model tightly bound to the facts in the PDF
            response_mime_type="application/json",
            response_schema=MCQQuiz,
        ),
    )
    
    return response.parsed

# =====================================================================
# 4. Execution Flow
# =====================================================================
if __name__ == "__main__":
    print("Please upload your PDF file:")
    uploaded = files.upload()
    
    if uploaded:
        # Get the filename of the uploaded file
        uploaded_pdf_path = list(uploaded.keys())[0]
        
        try:
            # Generate 5 questions from your uploaded document
            quiz_data = generate_mcqs_from_pdf(uploaded_pdf_path, num_questions=5)
            
            print("\n=== GENERATED QUIZ ===\n")
            for idx, mcq in enumerate(quiz_data.quiz, 1):
                print(f"Q{idx}: {mcq.question}")
                for opt in mcq.options:
                    print(f"  [ ] {opt}")
                print(f"\n👉 Correct Answer: {mcq.correct_answer}")
                print(f"💡 Explanation: {mcq.explanation}")
                print("-" * 50)
                
        except Exception as e:
            print