Spaces:
Runtime error
Runtime error
import random | |
import spacy | |
import requests | |
from bs4 import BeautifulSoup | |
import re | |
import spacy | |
import language_tool_python | |
import streamlit as st | |
from gradio_client import Client | |
class SubjectiveTest: | |
def __init__(self, data, noOfQues): | |
self.summary = data | |
self.noOfQues = noOfQues | |
self.nlp = spacy.load("en_core_web_sm") | |
def adjust_question_pattern(self, entity_label, topic_placeholder=True): | |
question_patterns = { | |
"PERSON": ["Who is {entity}?", "Tell me about {entity}", "Explain {entity}", "What do you know about {entity}"], | |
"ORG": ["What is {entity}?", "Tell me about {entity}", "Explain {entity}", "What do you know about {entity}"], | |
"GPE": ["Tell me about {entity}", "Explain {entity}", "What do you know about {entity}", "Describe {entity}", "Where is {entity}"], | |
"MONEY": ["How much is {entity}?", "Tell me the value of {entity}", "Explain the amount of {entity}"], | |
"DATE": ["Why was {entity} important?", "Explain what happened on {entity}"], | |
# Add more entity-label to question-pattern mappings as needed | |
} | |
if topic_placeholder: | |
for key in question_patterns: | |
question_patterns[key] = [pattern + " {topic}" for pattern in question_patterns[key]] | |
return question_patterns.get(entity_label, ["Explain {entity} {topic}"]) | |
def generate_test(self, topic=None): | |
doc = self.nlp(self.summary) | |
question_answer_dict = dict() | |
for sentence in doc.sents: | |
for ent in sentence.ents: | |
entity_label = ent.label_ | |
entity_text = ent.text | |
question_patterns = self.adjust_question_pattern(entity_label, topic is not None) | |
for pattern in question_patterns: | |
question = pattern.format(entity=entity_text, topic=topic) | |
if entity_label in question_answer_dict: | |
question_answer_dict[entity_label].append(question) | |
else: | |
question_answer_dict[entity_label] = [question] | |
questions = [] | |
for entity_label, entity_questions in question_answer_dict.items(): | |
entity_questions = entity_questions[:self.noOfQues] | |
questions.extend(entity_questions) | |
return questions | |
# Initialize LanguageTool | |
tool = language_tool_python.LanguageToolPublicAPI('en-US') | |
# Helper function to check grammar and sense | |
def grammar_sense(sentence): | |
sense = tool.correct(sentence) | |
grammar = "Correct Grammar" if not tool.check(sentence) else "Incorrect Grammar" | |
return "Make Sense" if "Not" not in sense and grammar == "Correct Grammar" else "Not Make Sense" | |
Quiz_Gen = st.form("Quiz Generation") | |
res = Quiz_Gen.text_input("What topic do you want to get quizzed on?") | |
sub = Quiz_Gen.form_submit_button("Submit") | |
while not sub: | |
x=2 | |
if sub: | |
entity = res | |
prefix = "https://wiki.kidzsearch.com/wiki/" | |
page = requests.get(f'{prefix}{entity}') | |
res = BeautifulSoup(page.content, 'html.parser') | |
text = [i.get_text() for i in res.find_all('p')] | |
cleaned_text = ' '.join(text) | |
cleaned_text = re.sub(r'[^a-zA-Z0-9.,]', ' ', cleaned_text) | |
paragraphs = [p.strip() for p in re.split(r'\n', cleaned_text) if p.strip()] | |
# Process text using SpaCy | |
nlp = spacy.load("en_core_web_sm") | |
doc = nlp(cleaned_text) | |
sentences = [sent.text for sent in doc.sents] | |
# Combine sentences into paragraphs | |
paragraphs = [f"{sentences[i]} {sentences[i + 1]}" if i + 1 < len(sentences) else sentences[i] for i in range(0, len(sentences), 2)] | |
# Example usage | |
data = ' '.join(paragraphs) | |
noOfQues = 5 | |
st.toast("Creating Questions", icon='β ') | |
subjective_generator = SubjectiveTest(data, noOfQues) | |
question_list = subjective_generator.generate_test("") | |
questions = [] | |
st.session_state.questions = question_list # Store the generated questions in session state | |
Quiz = st.form("Quiz") | |
st.toast("Filtering Questions", icon='β ') | |
# Check if questions are generated in session state | |
if 'questions' in st.session_state: | |
question_index = 0 | |
while question_index < len(st.session_state.questions): | |
current_question = st.session_state.questions[question_index] | |
# Check if the current question meets your criteria | |
if "Explain" not in current_question and len(tool.check(current_question)) == 0 and grammar_sense(current_question) == "Make Sense": | |
# Get user input for the current question | |
user_answer = Quiz.text_input(f'{current_question}') | |
# Append the user answer to the list | |
ans.append(user_answer) | |
# Move to the next question | |
question_index += 1 | |
submit_button = Quiz.form_submit_button("Submit") | |
while not submit_button: | |
x=1 | |
if submit_button: | |
st.toast("Calculating grade", icon='β ') | |
with st.spinner(text="Calculating Grade"): | |
for i, q in enumerate(st.session_state.questions): | |
st.toast(f'iteration {i} has begun', icon='β ') | |
result = client.predict( | |
f'What would you rate this answer to the question: "{q}" as a percentage? Here is the answer: {ans[i]}. Your percentage grade cannot be negative or over 100%. Additionally, you should also assume that the user is of a 5-7th grade level of intellect.', | |
0.9, | |
256, | |
0.9, | |
1.2, | |
api_name="/chat" | |
) | |
pattern = r'(\d+)%' | |
match = re.search(pattern, result) | |
if match: | |
score = match.group(1) | |
user_scores.append(int(score)) | |
else: | |
user_scores.append(85) # You can set a default score if no score is found | |
# Calculate the average score using the user_scores list | |
average_score = sum(user_scores) / len(user_scores) | |
st.info(f'Your average score for the answers is {average_score}%') | |
st.write(f'Your average score for the answers is {average_score}%') | |
st.balloons() |