Spaces:
Sleeping
Sleeping
File size: 15,933 Bytes
300f197 | 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 | import re
import nltk
import logging
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
from nltk.tag import pos_tag
import torch
from transformers import pipeline
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# NLTK data setup
def setup_nltk():
"""Download required NLTK data."""
try:
nltk.data.find('tokenizers/punkt')
nltk.data.find('corpora/stopwords')
nltk.data.find('taggers/averaged_perceptron_tagger')
nltk.data.find('corpora/wordnet')
nltk.data.find('corpora/omw-1.4')
logger.info("NLTK data is already set up.")
return True
except LookupError:
logger.info("Downloading required NLTK data...")
try:
nltk.download('punkt', quiet=True)
nltk.download('stopwords', quiet=True)
nltk.download('averaged_perceptron_tagger', quiet=True)
nltk.download('wordnet', quiet=True)
nltk.download('omw-1.4', quiet=True)
logger.info("NLTK data downloaded successfully.")
return True
except Exception as e:
logger.error(f"Error downloading NLTK data: {str(e)}")
return False
# Initialize NLTK
if not setup_nltk():
logger.warning("NLTK data not available. Some features may not work properly.")
class QuestionGenerator:
def __init__(self, model_name="valhalla/t5-small-qa-qg-hl", use_transformers=False):
"""Initialize the question generator with enhanced capabilities."""
self.use_transformers = use_transformers
self.stop_words = set(stopwords.words('english'))
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
# Initialize rule-based system
self._init_rule_based_system()
# Initialize transformer model if requested
if use_transformers:
try:
logger.info("Loading transformer model...")
self.qg_model = pipeline(
"text2text-generation",
model=model_name,
device=0 if self.device == 'cuda' else -1
)
logger.info("Transformer model loaded successfully.")
except Exception as e:
logger.error(f"Error loading transformer model: {str(e)}")
self.use_transformers = False
logger.info("Falling back to rule-based generation.")
def _init_rule_based_system(self):
"""Initialize the rule-based question generation system."""
self.wh_words = ['what', 'when', 'where', 'who', 'whom', 'whose', 'which', 'why', 'how']
self.aux_verbs = ['is', 'are', 'was', 'were', 'do', 'does', 'did', 'have', 'has', 'had',
'can', 'could', 'will', 'would', 'shall', 'should', 'may', 'might', 'must']
self.common_nouns = {'time', 'year', 'people', 'way', 'day', 'man', 'thing', 'woman', 'life', 'child',
'world', 'school', 'state', 'family', 'student', 'group', 'country', 'problem'}
def _is_good_sentence(self, sentence):
"""Check if a sentence is suitable for question generation."""
try:
if not sentence or not isinstance(sentence, str):
return False
# Basic length checks
words = word_tokenize(sentence)
if len(words) < 4: # At least 4 words
return False
# Check for question mark
if '?' in sentence:
return False
# Check for proper sentence ending
if not sentence.strip().endswith(('.', '!', ';', ':')):
return False
# Check for at least one noun and one verb
pos_tags = pos_tag(words)
has_noun = any(tag.startswith('NN') for word, tag in pos_tags)
has_verb = any(tag.startswith('VB') for word, tag in pos_tags)
return has_noun and has_verb
except Exception as e:
logger.error(f"Error in _is_good_sentence: {str(e)}")
return False
def _generate_question_what_is(self, words, pos_tags):
"""Generate 'What is...?' questions."""
for i, (word, tag) in enumerate(pos_tags):
if tag.startswith('NN'):
return f"What is {word}?"
return ""
def _generate_question_verb_subject(self, words, pos_tags):
"""Generate questions by inverting subject and verb."""
for i, (word, tag) in enumerate(pos_tags):
if tag.startswith('VB') and i > 0:
subject = ' '.join(words[:i])
verb = word
rest = ' '.join(words[i+1:])
return f"{verb.capitalize()} {subject} {rest}?"
return ""
def _generate_question_wh_word(self, words, pos_tags):
"""Generate questions using WH-words."""
for i, (word, tag) in enumerate(pos_tags):
if tag.startswith('VB') and i > 0:
wh_word = "What"
if i > 0 and pos_tags[i-1][1].startswith('NNP'):
wh_word = "Who"
return f"{wh_word} {word} {' '.join(words[:i])}?"
return ""
def _generate_question_from_statement(self, sentence):
"""Generate a question from a statement using multiple strategies."""
try:
if not sentence or not isinstance(sentence, str):
return ""
# Clean the sentence
sentence = sentence.strip()
if sentence.endswith('.'):
sentence = sentence[:-1].strip()
words = word_tokenize(sentence)
if len(words) < 4: # Too short for a good question
return ""
pos_tags = pos_tag(words)
# Try different question generation strategies
strategies = [
self._generate_question_what_is,
self._generate_question_verb_subject,
self._generate_question_wh_word
]
for strategy in strategies:
question = strategy(words, pos_tags)
if question:
return question
# Fallback: ask about the whole sentence
return f"Can you explain: {sentence[:100]}...?"
except Exception as e:
logger.error(f"Error in _generate_question_from_statement: {str(e)}")
return ""
def generate_question_from_sentence(self, sentence):
"""Generate a question from a given sentence."""
if not self._is_good_sentence(sentence):
return ""
try:
# Use transformer model if available
if self.use_transformers and hasattr(self, 'qg_model'):
try:
# Prepare input for e2e model
input_text = f"generate questions: {sentence}"
outputs = self.qg_model(input_text)
if outputs and len(outputs) > 0:
generated_text = outputs[0]['generated_text']
# The model might generate multiple questions separated by <sep>
questions = generated_text.split('<sep>')
if questions:
return questions[0].strip()
except Exception as e:
logger.error(f"Transformer generation failed: {e}")
# Fallback to rule-based
# First try rule-based generation
question = self._generate_question_from_statement(sentence)
if question:
return question
# Fallback to simple question generation
words = word_tokenize(sentence)
if len(words) < 4:
return ""
# Try to make a simple question
return f"What is the main point about: {sentence[:100]}...?"
except Exception as e:
logger.error(f"Error generating question: {str(e)}")
return ""
def _score_sentence(self, sentence):
"""Score a sentence based on its quality for question generation."""
try:
if not self._is_good_sentence(sentence):
return 0
words = word_tokenize(sentence)
pos_tags = pos_tag(words)
# Start with base score
score = 1.0
# Check for content words
has_noun = any(tag.startswith('NN') for _, tag in pos_tags)
has_verb = any(tag.startswith('VB') for _, tag in pos_tags)
has_adj = any(tag.startswith('JJ') for _, tag in pos_tags)
# Increase score based on content
if has_noun and has_verb:
score += 2.0
elif has_noun or has_verb:
score += 1.0
if has_adj:
score += 0.5
# Adjust for sentence length
word_count = len(words)
if 8 <= word_count <= 25: # Ideal length
score += 1.0
# Bonus for proper nouns or numbers
if any(tag in {'NNP', 'NNPS', 'CD'} for _, tag in pos_tags):
score += 1.0
return max(0.5, score) # Ensure minimum score
except Exception as e:
logger.error(f"Error in _score_sentence: {str(e)}")
return 0.5
def generate_questions(self, text, num_questions=5):
"""Generate questions from the given text."""
if not text or not text.strip():
logger.warning("Empty text provided for question generation")
return []
try:
# Split text into sentences
sentences = sent_tokenize(text)
return self.generate_multiple_questions(sentences, num_questions)
except Exception as e:
logger.error(f"Error in generate_questions: {str(e)}")
return []
def generate_multiple_questions(self, inputs, max_questions=5):
"""
Generate multiple questions from a list of inputs (context/answer pairs).
Args:
inputs: List of dicts {'context': str, 'answer': str} or list of strings
max_questions: Maximum number of questions to generate
Returns:
List of generated questions with metadata
"""
if not inputs or max_questions <= 0:
logger.warning("No inputs provided or invalid max_questions")
return []
questions = []
used_contexts = set()
logger.info(f"Generating up to {max_questions} questions from {len(inputs)} inputs")
for item in inputs:
try:
if len(questions) >= max_questions:
break
# Handle different input types
if isinstance(item, dict):
context = item.get('context', '')
answer = item.get('answer')
else:
context = str(item)
answer = None
if not context or not context.strip():
continue
context = context.strip()
# Skip if we've already used this context
if context in used_contexts:
continue
question_text = ""
# Use transformer model if available
if self.use_transformers and hasattr(self, 'qg_model'):
try:
if answer:
input_text = f"answer: {answer} context: {context}"
else:
input_text = f"generate questions: {context}"
outputs = self.qg_model(input_text)
if outputs and len(outputs) > 0:
question_text = outputs[0]['generated_text']
except Exception as e:
logger.error(f"Transformer generation failed: {e}")
# Fallback to rule-based if transformer failed or not available
if not question_text:
question_text = self.generate_question_from_sentence(context)
if question_text and question_text not in [q.get('question', '') for q in questions]:
q_data = {
'question': question_text,
'context': context,
'score': 1.0,
'type': 'short_answer'
}
# If we have a known answer, use it for options later
if answer:
q_data['correct_answer'] = answer
questions.append(q_data)
used_contexts.add(context)
except Exception as e:
logger.error(f"Error processing input: {str(e)}")
continue
# If we still don't have enough questions, create simple ones
if len(questions) < max_questions:
logger.info(f"Creating simple questions to reach {max_questions} total")
for i in range(len(questions), max_questions):
# Try to find an unused context or reuse one
fallback_context = "General knowledge about the topic"
if inputs:
# Pick a random input to generate a question from
import random
item = random.choice(inputs)
if isinstance(item, dict):
fallback_context = item.get('context', fallback_context)
else:
fallback_context = str(item)
# Create a more specific fallback question
words = fallback_context.split()
topic_snippet = " ".join(words[:5]) + "..." if len(words) > 5 else fallback_context
questions.append({
'question': f"Explain the significance of: {topic_snippet}",
'context': fallback_context,
'score': 0.5,
'type': 'short_answer'
})
logger.info(f"Successfully generated {len(questions)} questions")
return questions[:max_questions]
# Example usage
if __name__ == "__main__":
# Test the question generator
qg = QuestionGenerator(use_transformers=False)
test_text = """
Machine learning is a branch of artificial intelligence that focuses on building systems
that learn from data. These systems can improve their performance over time without being
explicitly programmed. There are three main types of machine learning: supervised learning,
unsupervised learning, and reinforcement learning.
"""
print("\nGenerating questions...")
questions = qg.generate_questions(test_text, 3)
print("\nGenerated Questions:")
for i, q in enumerate(questions, 1):
print(f"{i}. {q.get('question', 'No question generated')}")
print(f" Context: {q.get('context', 'No context')[:100]}...")
print()
|