Spaces:
No application file
No application file
Download Code from udhayakumarj85/MCQ: direct link, hf CLI and curl.
- Browser
- Download file 4.53 kB
-
https://huggingface.co/spaces/udhayakumarj85/MCQ/resolve/main/Code
- Command line
-
hf download hf://spaces/udhayakumarj85/MCQ/Code
-
curl -L -o Code https://huggingface.co/spaces/udhayakumarj85/MCQ/resolve/main/Code
4.53 kB
| !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: | |