File size: 14,887 Bytes
aa3fdef e82864c aa3fdef e82864c aa3fdef 40ad63a aa3fdef 40ad63a aa3fdef e82864c aa3fdef e82864c aa3fdef e82864c aa3fdef e82864c aa3fdef e82864c aa3fdef e82864c aa3fdef e82864c aa3fdef e82864c aa3fdef e82864c aa3fdef |
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 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 |
# -*- coding: utf-8 -*-
"""
Quiz Tools - AI-Powered Quiz Generation from Flashcards
Supports multiple question types and uses OpenAI API for intelligent quiz creation
"""
import json
import os
import random
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Any, Optional
from .config import get_user_dir
from .flashcards_tools import load_deck, list_user_decks
# Try to import OpenAI
try:
from openai import OpenAI
HAS_OPENAI = True
except ImportError:
HAS_OPENAI = False
class QuizGenerator:
"""Generate intelligent quizzes using OpenAI API"""
QUESTION_TYPES = [
'multiple_choice',
'fill_in_blank',
'true_false',
'matching',
'short_answer'
]
def __init__(self, api_key: Optional[str] = None, model: str = "gpt-4o-mini"):
"""
Initialize the quiz generator
Args:
api_key: OpenAI API key (uses env var if not provided)
model: Model to use for quiz generation
"""
self.api_key = api_key or os.environ.get("OPENAI_API_KEY")
self.model = model
self.client = None
if HAS_OPENAI and self.api_key:
try:
self.client = OpenAI(api_key=self.api_key)
except Exception as e:
print(f"[QuizGenerator] OpenAI init failed: {e}")
def _prepare_flashcard_context(self, flashcards: List[Dict], max_cards: int = 20) -> str:
"""Prepare flashcard data as context for AI"""
selected_cards = flashcards[:max_cards] if len(flashcards) > max_cards else flashcards
context_parts = []
for idx, card in enumerate(selected_cards, 1):
card_info = (
f"{idx}. Word: {card.get('front', '')}\n"
f" Translation: {card.get('back', '')}\n"
f" Language: {card.get('language', 'unknown')}\n"
f" Context: {card.get('context', 'N/A')}"
)
context_parts.append(card_info)
return "\n\n".join(context_parts)
def _create_quiz_prompt(self, flashcards: List[Dict], num_questions: int = 30) -> str:
"""Create the prompt for AI quiz generation"""
flashcard_context = self._prepare_flashcard_context(flashcards)
prompt = f"""You are an expert language teacher creating a QUESTION BANK to test students' knowledge of vocabulary.
Based on the following flashcards, generate exactly {num_questions} diverse quiz questions.
FLASHCARDS:
{flashcard_context}
REQUIREMENTS:
1. Generate exactly {num_questions} questions
2. Use different question types: multiple_choice, fill_in_blank, true_false, matching, short_answer
3. Questions should test different aspects: vocabulary recall, context understanding, usage
4. Each question must include the correct answer
5. For multiple choice questions, provide 4 options with one correct answer
6. For matching questions, provide 4 word-translation pairs
7. Make questions challenging but fair
8. Vary difficulty levels across questions
OUTPUT FORMAT (JSON):
{{
"quiz_title": "Vocabulary Quiz",
"total_questions": {num_questions},
"questions": [
{{
"question_number": 1,
"type": "multiple_choice",
"question": "What does 'word' mean?",
"options": ["Option A", "Option B", "Option C", "Option D"],
"correct_answer": "Option B",
"explanation": "Brief explanation."
}},
{{
"question_number": 2,
"type": "fill_in_blank",
"question": "Complete: The ___ ran quickly.",
"correct_answer": "cat",
"explanation": "Brief explanation."
}},
{{
"question_number": 3,
"type": "true_false",
"question": "'Word' means 'definition' in English.",
"correct_answer": false,
"explanation": "Brief explanation."
}},
{{
"question_number": 4,
"type": "matching",
"question": "Match the words to their correct translations",
"pairs": [
{{"word": "word1", "translation": "translation1"}},
{{"word": "word2", "translation": "translation2"}},
{{"word": "word3", "translation": "translation3"}},
{{"word": "word4", "translation": "translation4"}}
],
"correct_answer": "All pairs are correctly matched",
"explanation": "Brief explanation."
}},
{{
"question_number": 5,
"type": "short_answer",
"question": "Explain the usage of 'word'.",
"correct_answer": "Model answer here.",
"explanation": "Brief explanation."
}}
]
}}
Generate the quiz now:"""
return prompt
def generate_quiz_with_ai(self, flashcards: List[Dict], num_questions: int = 30) -> Dict[str, Any]:
"""Generate quiz using OpenAI API"""
if not self.client:
raise ValueError("OpenAI client not initialized. Check API key.")
if not flashcards:
raise ValueError("No flashcards provided for quiz generation")
prompt = self._create_quiz_prompt(flashcards, num_questions)
try:
response = self.client.chat.completions.create(
model=self.model,
messages=[
{
"role": "system",
"content": "You are an expert language teacher who creates engaging, educational quizzes. Always respond with valid JSON."
},
{
"role": "user",
"content": prompt
}
],
response_format={"type": "json_object"},
temperature=0.7,
max_tokens=4000
)
quiz_content = response.choices[0].message.content
quiz_data = json.loads(quiz_content)
quiz_data['metadata'] = {
'generator': 'AI-Powered Quiz Generator',
'model': self.model,
'source_flashcards': len(flashcards),
'tokens_used': response.usage.total_tokens if response.usage else 0
}
return quiz_data
except Exception as e:
print(f"[QuizGenerator] AI generation failed: {e}")
raise
def generate_simple_quiz(self, flashcards: List[Dict], num_questions: int = 5) -> Dict[str, Any]:
"""Generate a simple quiz without AI (fallback)"""
if not flashcards:
raise ValueError("No flashcards provided")
questions = []
used_cards = random.sample(flashcards, min(num_questions * 2, len(flashcards)))
for i, card in enumerate(used_cards[:num_questions]):
q_type = random.choice(['multiple_choice', 'fill_in_blank', 'true_false'])
if q_type == 'multiple_choice':
# Create wrong options from other cards
other_cards = [c for c in flashcards if c != card]
wrong_options = random.sample(
[c.get('back', 'Unknown') for c in other_cards],
min(3, len(other_cards))
)
while len(wrong_options) < 3:
wrong_options.append(f"Not {card.get('back', 'this')}")
options = wrong_options + [card.get('back', '')]
random.shuffle(options)
questions.append({
"question_number": i + 1,
"type": "multiple_choice",
"question": f"What does '{card.get('front', '')}' mean?",
"options": options,
"correct_answer": card.get('back', ''),
"explanation": f"'{card.get('front', '')}' translates to '{card.get('back', '')}'."
})
elif q_type == 'fill_in_blank':
questions.append({
"question_number": i + 1,
"type": "fill_in_blank",
"question": f"Translate: '{card.get('front', '')}' = _____",
"correct_answer": card.get('back', ''),
"explanation": f"The correct translation is '{card.get('back', '')}'."
})
elif q_type == 'true_false':
is_true = random.choice([True, False])
if is_true:
shown_answer = card.get('back', '')
else:
other_cards = [c for c in flashcards if c != card]
if other_cards:
shown_answer = random.choice(other_cards).get('back', 'something else')
else:
shown_answer = f"Not {card.get('back', 'this')}"
questions.append({
"question_number": i + 1,
"type": "true_false",
"question": f"'{card.get('front', '')}' means '{shown_answer}'.",
"correct_answer": is_true,
"explanation": f"'{card.get('front', '')}' actually means '{card.get('back', '')}'."
})
return {
"quiz_title": "Vocabulary Quiz",
"total_questions": len(questions),
"questions": questions,
"metadata": {
"generator": "Simple Quiz Generator",
"source_flashcards": len(flashcards)
}
}
def create_quiz_from_deck(
username: str,
deck_name: str,
num_questions: int = 5,
use_ai: bool = True,
api_key: Optional[str] = None
) -> Dict[str, Any]:
"""
Create a quiz from a user's flashcard deck
Args:
username: User identifier
deck_name: Name of the deck to create quiz from
num_questions: Number of questions for the quiz session
use_ai: Whether to use AI for quiz generation
api_key: Optional OpenAI API key
Returns:
Quiz dictionary with questions
"""
decks = list_user_decks(username)
if deck_name not in decks:
raise ValueError(f"Deck '{deck_name}' not found")
deck = load_deck(decks[deck_name])
flashcards = deck.get('cards', [])
if not flashcards:
raise ValueError(f"Deck '{deck_name}' has no cards")
generator = QuizGenerator(api_key=api_key)
try:
if use_ai and generator.client:
# Generate larger question bank with AI
quiz = generator.generate_quiz_with_ai(flashcards, num_questions=30)
else:
# Use simple generator
quiz = generator.generate_simple_quiz(flashcards, num_questions=num_questions)
except Exception as e:
print(f"[quiz_tools] AI quiz generation failed: {e}, using simple generator")
quiz = generator.generate_simple_quiz(flashcards, num_questions=num_questions)
# Add quiz metadata
ts = datetime.utcnow().strftime("%Y-%m-%dT%H-%M-%SZ")
quiz['id'] = f"quiz_{ts}"
quiz['created_at'] = ts
quiz['deck_name'] = deck_name
quiz['questions_per_session'] = num_questions
return quiz
def create_semantic_quiz_for_user(username: str, topic: str, num_questions: int = 5) -> Dict[str, Any]:
"""
Create a semantic quiz based on a topic (for conversation practice)
Args:
username: User identifier
topic: Topic for the quiz
num_questions: Number of questions
Returns:
Quiz dictionary
"""
reading_passages = [
f"{topic.capitalize()} is important in daily life. Many people enjoy talking about it.",
f"Here is a short story based on the topic '{topic}'.",
f"In this short description, you will learn more about {topic}.",
]
questions = []
for i in range(num_questions):
passage = random.choice(reading_passages)
q_type = random.choice(["translate_phrase", "summarize", "interpret"])
if q_type == "translate_phrase":
questions.append({
"question_number": i + 1,
"type": "semantic_translate_phrase",
"prompt": f"Translate:\n\n'{passage}'",
"answer": "(model evaluated)",
"explanation": f"Checks ability to translate topic '{topic}'."
})
elif q_type == "summarize":
questions.append({
"question_number": i + 1,
"type": "semantic_summarize",
"prompt": f"Summarize:\n\n{passage}",
"answer": "(model evaluated)",
"explanation": f"Checks comprehension of topic '{topic}'."
})
elif q_type == "interpret":
questions.append({
"question_number": i + 1,
"type": "semantic_interpret",
"prompt": f"Interpret meaning:\n\n{passage}",
"answer": "(model evaluated)",
"explanation": f"Checks conceptual understanding of '{topic}'."
})
ts = datetime.utcnow().strftime("%Y-%m-%dT%H-%M-%SZ")
quiz_id = f"semantic_quiz_{ts}"
return {
"id": quiz_id,
"created_at": ts,
"topic": topic,
"total_questions": len(questions),
"questions": questions,
}
def save_quiz(username: str, quiz: Dict[str, Any]) -> Path:
"""Save a quiz to the user's directory"""
user_dir = get_user_dir(username)
quizzes_dir = user_dir / "quizzes"
quizzes_dir.mkdir(parents=True, exist_ok=True)
quiz_id = quiz.get('id', f"quiz_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}")
quiz_path = quizzes_dir / f"{quiz_id}.json"
with open(quiz_path, 'w', encoding='utf-8') as f:
json.dump(quiz, f, ensure_ascii=False, indent=2)
return quiz_path
def load_quiz(username: str, quiz_id: str) -> Dict[str, Any]:
"""Load a saved quiz"""
user_dir = get_user_dir(username)
quiz_path = user_dir / "quizzes" / f"{quiz_id}.json"
if not quiz_path.exists():
raise FileNotFoundError(f"Quiz '{quiz_id}' not found")
with open(quiz_path, 'r', encoding='utf-8') as f:
return json.load(f)
def list_user_quizzes(username: str) -> List[Dict[str, Any]]:
"""List all quizzes for a user"""
user_dir = get_user_dir(username)
quizzes_dir = user_dir / "quizzes"
if not quizzes_dir.exists():
return []
quizzes = []
for quiz_file in sorted(quizzes_dir.glob("*.json"), reverse=True):
try:
with open(quiz_file, 'r', encoding='utf-8') as f:
quiz = json.load(f)
quizzes.append({
'id': quiz.get('id', quiz_file.stem),
'title': quiz.get('quiz_title', 'Untitled Quiz'),
'created_at': quiz.get('created_at', ''),
'total_questions': quiz.get('total_questions', 0),
'deck_name': quiz.get('deck_name', ''),
})
except Exception:
continue
return quizzes
|