File size: 4,252 Bytes
0d20fc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
import random
from transformers import pipeline, AutoModelForQuestionAnswering, AutoTokenizer

class QuestionGenerator:
    def __init__(self, model_name='deepset/roberta-base-squad2'):
        """
        Initialize question generation system
        """
        self.device = 'cuda' if torch.cuda.is_available() else 'cpu' # Detect and set device
        self.model = AutoModelForQuestionAnswering.from_pretrained(model_name)        # Load model and tokenizer
        self.tokenizer = AutoTokenizer.from_pretrained(model_name)
        
        # Create QA pipeline
        self.qa_pipeline = pipeline('question-answering', model=self.model, tokenizer=self.tokenizer,device=0 if self.device == 'cuda' else -1)
        
        # Question templates
        self.question_templates = ["What is the main idea of","Who is responsible for","When did this occur","Where does this take place","Why is this important","How does this work","What are the key features of","Explain the significance of","What is the purpose of","Describe the process of"]

    def generate_questions(self, context, num_questions=3, difficulty='medium'):
        """
        Generate multiple questions from context
        """
        generated_questions = []
        attempts = 0
        max_attempts = num_questions * 10

        while len(generated_questions) < num_questions and attempts < max_attempts:
            try:
                template = random.choice(self.question_templates)    # Select random template
                words = context.split()      # Create question
                start_index = random.randint(0, max(0, len(words) - 5))
                full_question = f"{template} {' '.join(words[start_index:start_index+5])}?"
                result = self.qa_pipeline(question=full_question, context=context)   # Get answer
                
                # Validate result
                if (result['answer'] and len(result['answer']) > 3 and result['score'] > 0.5 and not any(q['answer'] == result['answer'] for q in generated_questions)):
                    generated_questions.append({'question': full_question,'answer': result['answer'],'confidence': result['score']})
                attempts += 1
            
            except Exception as e:
                print(f"Question generation error: {e}")
                attempts += 1
        return generated_questions

    def display_questions(self, questions):
        """
        Display generated questions
        """
        print("\n--- Generated Questions ---")
        for idx, q in enumerate(questions, 1):
            print(f"Q{idx}: {q['question']}")
            print(f"Expected keyword: {q['answer']} \n")

def get_user_input():
    """
    Get user input for question generation
    """
    print("\n--- Interactive Question Generator ---")
    print("\n>> Enter the context for question generation: ")  # Context input
    context = input().strip()
    
    # Number of questions
    while True:
        try:
            num_questions = int(input("\n>> How many questions do you want? (1-10): "))
            if 1 <= num_questions <= 10:
                break
            else:
                print("Please enter a number between 1 and 10.")
        except ValueError:
            print("Invalid input. Please enter a number.")
    return context, num_questions

def main():
    # Initialize generator
    generator = QuestionGenerator()
    
    while True:
        try:
            context, num_questions = get_user_input()          # Get user input
            questions = generator.generate_questions(context, num_questions=num_questions)    # Generate questions
            if questions:                          # Display questions
                generator.display_questions(questions)
            else:
                print("Could not generate questions. Please try a different context.")
            
            # Continue option
            continue_choice = input("Generate more questions? (yes/no): ").lower()
            if continue_choice not in ['yes', 'y']:
                break
        except Exception as e:
            print(f"An error occurred: {e}")
    print("Thank you for using the Question Generator!")

if __name__ == "__main__":
    main()