File size: 4,398 Bytes
25a2b82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
from transformers import GPT2LMHeadModel, GPT2Tokenizer
from textblob import TextBlob
import language_tool_python
import speech_recognition as sr
import pyttsx3
from gtts import gTTS
import os

# Initialize text-to-speech engine
engine = pyttsx3.init()

# Initialize speech recognition
recognizer = sr.Recognizer()

# Load pre-trained model and tokenizer
model_name = "gpt2"
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
model = GPT2LMHeadModel.from_pretrained(model_name)

# Function to generate a question based on a prompt
def generate_question(prompt):
    inputs = tokenizer.encode(prompt, return_tensors='pt')
    outputs = model.generate(inputs, max_length=50, num_return_sequences=1, pad_token_id=tokenizer.eos_token_id)
    question = tokenizer.decode(outputs[0], skip_special_tokens=True)
    return question

# Function to get voice input and convert to text
def get_voice_input(prompt):
    # Use TTS to say the prompt
    engine.say(prompt)
    engine.runAndWait()
    
    with sr.Microphone() as source:
        print("Listening...")
        audio = recognizer.listen(source)
        try:
            text = recognizer.recognize_google(audio)
            print(f"User said: {text}")
            return text
        except sr.UnknownValueError:
            print("Sorry, I did not understand that.")
            return None
        except sr.RequestError:
            print("Sorry, there was an error with the speech recognition service.")
            return None

# Function to convert text to speech
def text_to_speech(text):
    tts = gTTS(text=text, lang='en')
    tts.save("response.mp3")
    os.system("start response.mp3")  # For Windows; use "afplay response.mp3" on macOS

# Analyze English using TextBlob
def analyze_english_textblob(text):
    blob = TextBlob(text)
    corrected_text = blob.correct().string
    sentiment = blob.sentiment.polarity  # Range: -1 (negative) to 1 (positive)
    
    feedback = "No significant grammar issues detected."
    if corrected_text != text:
        feedback = "Grammar issues detected."

    # Simple scoring based on sentiment and correction
    score = 100
    if feedback == "Grammar issues detected.":
        score -= 20  # Deduct points for grammar issues

    # Adjust score based on sentiment (optional)
    score += int((sentiment + 1) * 10)  # Normalize sentiment from range [-1,1] to [0, 10]
    score = min(max(score, 0), 100)  # Ensure score is between 0 and 100

    return feedback, score

# Analyze English using LanguageTool
def analyze_english_languagetool(text):
    tool = language_tool_python.LanguageTool('en-US')
    matches = tool.check(text)
    
    feedback = "No issues found."
    issues = []
    
    if matches:
        feedback = f"Issues detected: {len(matches)}"
        for match in matches:
            issues.append(f"{match.ruleId}: {match.message} (Suggestion: {match.replacements})")
    
    # Simple scoring based on number of issues
    score = 100
    if len(matches) > 0:
        score -= len(matches) * 2  # Deduct points for each issue

    return feedback, issues, max(score, 0)  # Ensure score is not below 0

# Main process
def main():
    prompt = "Ask a question about grammar or general knowledge."
    question = generate_question(prompt)
    print("Generated Question:", question)
    
    text_to_speech(f"Question: {question}")
    user_answer = get_voice_input(question)
    
    if user_answer:
        # Limit response to 30 words
        user_answer = ' '.join(user_answer.split()[:30])
        
        # Analyze the response
        feedback_textblob, score_textblob = analyze_english_textblob(user_answer)
        feedback_languagetool, issues, score_languagetool = analyze_english_languagetool(user_answer)
        
        # Calculate average score from both tools
        average_score = (score_textblob + score_languagetool) / 2
        
        # Provide feedback
        feedback = f"{feedback_textblob}. {feedback_languagetool}."
        text_to_speech(f"Your response: {user_answer}. {feedback}. Your score is {average_score}.")
        
        # Print detected issues
        print("\nDetected Issues:")
        for issue in issues:
            print(f" - {issue}")
        print("\nAverage Score:", average_score)
    else:
        text_to_speech("Sorry, I did not catch that. Please try again.")

if __name__ == "__main__":
    main()