_____ / app.py
gowthM23's picture
Create app.py
25a2b82 verified
Raw History Blame Contribute Delete
4.4 kB
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()