Spaces:
Runtime error
Runtime error
adding the options to choose between input text and upload pdf
Browse files
app.py
CHANGED
|
@@ -25,12 +25,16 @@ from sentence_transformers import SentenceTransformer, util
|
|
| 25 |
import textstat
|
| 26 |
from spellchecker import SpellChecker
|
| 27 |
from transformers import pipeline
|
| 28 |
-
|
|
|
|
| 29 |
print("***************************************************************")
|
| 30 |
|
| 31 |
st.set_page_config(
|
| 32 |
page_title="Question Generator",
|
| 33 |
initial_sidebar_state="auto",
|
|
|
|
|
|
|
|
|
|
| 34 |
)
|
| 35 |
|
| 36 |
# Initialize Wikipedia API with a user agent
|
|
@@ -64,7 +68,15 @@ def load_qa_models():
|
|
| 64 |
nlp, s2v = load_nlp_models()
|
| 65 |
model, tokenizer = load_model()
|
| 66 |
similarity_model, spell = load_qa_models()
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
def save_feedback(question, answer,rating):
|
| 69 |
feedback_file = 'question_feedback.json'
|
| 70 |
if os.path.exists(feedback_file):
|
|
@@ -83,6 +95,31 @@ def save_feedback(question, answer,rating):
|
|
| 83 |
with open(feedback_file, 'w') as f:
|
| 84 |
json.dump(feedback_data, f)
|
| 85 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
# Function to extract keywords using combined techniques
|
| 87 |
def extract_keywords(text, extract_all):
|
| 88 |
doc = nlp(text)
|
|
@@ -140,6 +177,17 @@ def get_synonyms(word, n=3):
|
|
| 140 |
def generate_options(answer, context, n=3):
|
| 141 |
options = [answer]
|
| 142 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
# Try to get similar words based on sense2vec
|
| 144 |
similar_words = get_similar_words_sense2vec(answer, n)
|
| 145 |
options.extend(similar_words)
|
|
@@ -159,7 +207,7 @@ def generate_options(answer, context, n=3):
|
|
| 159 |
if len(options) < n + 1:
|
| 160 |
context_words = [token.text for token in nlp(context) if token.is_alpha and token.text.lower() != answer.lower()]
|
| 161 |
options.extend(random.sample(context_words, min(n - len(options) + 1, len(context_words))))
|
| 162 |
-
|
| 163 |
# Ensure we have the correct number of unique options
|
| 164 |
options = list(dict.fromkeys(options))[:n+1]
|
| 165 |
|
|
@@ -172,6 +220,7 @@ def generate_options(answer, context, n=3):
|
|
| 172 |
def map_keywords_to_sentences(text, keywords, context_window_size):
|
| 173 |
sentences = sent_tokenize(text)
|
| 174 |
keyword_sentence_mapping = {}
|
|
|
|
| 175 |
for keyword in keywords:
|
| 176 |
for i, sentence in enumerate(sentences):
|
| 177 |
if keyword in sentence:
|
|
@@ -270,11 +319,10 @@ def main():
|
|
| 270 |
if 'generated_questions' not in st.session_state:
|
| 271 |
st.session_state.generated_questions = []
|
| 272 |
|
| 273 |
-
text = st.text_area("Enter text here:", value="Joe Biden, the current US president is on a weak wicket going in for his reelection later this November against former President Donald Trump.")
|
| 274 |
-
|
| 275 |
with st.sidebar:
|
| 276 |
st.subheader("Customization Options")
|
| 277 |
# Customization options
|
|
|
|
| 278 |
num_beams = st.slider("Select number of beams for question generation", min_value=1, max_value=10, value=5)
|
| 279 |
context_window_size = st.slider("Select context window size (number of sentences before and after)", min_value=1, max_value=5, value=1)
|
| 280 |
num_questions = st.slider("Select number of questions to generate", min_value=1, max_value=1000, value=5)
|
|
@@ -289,31 +337,45 @@ def main():
|
|
| 289 |
extract_all_keywords = st.toggle("Extract Max Keywords",value=False)
|
| 290 |
with col2:
|
| 291 |
enable_feedback_mode = st.toggle("Enable Feedback Mode",False)
|
| 292 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 293 |
generate_questions_button = st.button("Generate Questions")
|
| 294 |
if generate_questions_button and text:
|
| 295 |
st.session_state.generated_questions = []
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 317 |
# Display generated questions
|
| 318 |
if st.session_state.generated_questions:
|
| 319 |
st.header("Generated Questions:",divider='blue')
|
|
|
|
| 25 |
import textstat
|
| 26 |
from spellchecker import SpellChecker
|
| 27 |
from transformers import pipeline
|
| 28 |
+
import re
|
| 29 |
+
import pymupdf
|
| 30 |
print("***************************************************************")
|
| 31 |
|
| 32 |
st.set_page_config(
|
| 33 |
page_title="Question Generator",
|
| 34 |
initial_sidebar_state="auto",
|
| 35 |
+
menu_items={
|
| 36 |
+
"About" : "#Hi this our project."
|
| 37 |
+
}
|
| 38 |
)
|
| 39 |
|
| 40 |
# Initialize Wikipedia API with a user agent
|
|
|
|
| 68 |
nlp, s2v = load_nlp_models()
|
| 69 |
model, tokenizer = load_model()
|
| 70 |
similarity_model, spell = load_qa_models()
|
| 71 |
+
context_model = similarity_model
|
| 72 |
+
|
| 73 |
+
def get_pdf_text(pdf_file):
|
| 74 |
+
doc = pymupdf.open(stream=pdf_file.read(), filetype="pdf")
|
| 75 |
+
text = ""
|
| 76 |
+
for page_num in range(doc.page_count):
|
| 77 |
+
page = doc.load_page(page_num)
|
| 78 |
+
text += page.get_text()
|
| 79 |
+
return text
|
| 80 |
def save_feedback(question, answer,rating):
|
| 81 |
feedback_file = 'question_feedback.json'
|
| 82 |
if os.path.exists(feedback_file):
|
|
|
|
| 95 |
with open(feedback_file, 'w') as f:
|
| 96 |
json.dump(feedback_data, f)
|
| 97 |
|
| 98 |
+
|
| 99 |
+
# Function to clean text
|
| 100 |
+
def clean_text(text):
|
| 101 |
+
text = re.sub(r"[^\x00-\x7F]", " ", text)
|
| 102 |
+
return text
|
| 103 |
+
|
| 104 |
+
# Function to create text chunks
|
| 105 |
+
def segment_text(text, max_segment_length=1000):
|
| 106 |
+
"""Segment the text into smaller chunks."""
|
| 107 |
+
sentences = sent_tokenize(text)
|
| 108 |
+
segments = []
|
| 109 |
+
current_segment = ""
|
| 110 |
+
|
| 111 |
+
for sentence in sentences:
|
| 112 |
+
if len(current_segment) + len(sentence) <= max_segment_length:
|
| 113 |
+
current_segment += sentence + " "
|
| 114 |
+
else:
|
| 115 |
+
segments.append(current_segment.strip())
|
| 116 |
+
current_segment = sentence + " "
|
| 117 |
+
|
| 118 |
+
if current_segment:
|
| 119 |
+
segments.append(current_segment.strip())
|
| 120 |
+
print(f"\n\nSegement Chunks: {segments}\n\n")
|
| 121 |
+
return segments
|
| 122 |
+
|
| 123 |
# Function to extract keywords using combined techniques
|
| 124 |
def extract_keywords(text, extract_all):
|
| 125 |
doc = nlp(text)
|
|
|
|
| 177 |
def generate_options(answer, context, n=3):
|
| 178 |
options = [answer]
|
| 179 |
|
| 180 |
+
|
| 181 |
+
# Add contextually relevant words using a pre-trained model
|
| 182 |
+
context_embedding = context_model.encode(context)
|
| 183 |
+
answer_embedding = context_model.encode(answer)
|
| 184 |
+
context_words = [token.text for token in nlp(context) if token.is_alpha and token.text.lower() != answer.lower()]
|
| 185 |
+
|
| 186 |
+
# Compute similarity scores and sort context words
|
| 187 |
+
similarity_scores = [util.pytorch_cos_sim(context_model.encode(word), answer_embedding).item() for word in context_words]
|
| 188 |
+
sorted_context_words = [word for _, word in sorted(zip(similarity_scores, context_words), reverse=True)]
|
| 189 |
+
options.extend(sorted_context_words[:n])
|
| 190 |
+
|
| 191 |
# Try to get similar words based on sense2vec
|
| 192 |
similar_words = get_similar_words_sense2vec(answer, n)
|
| 193 |
options.extend(similar_words)
|
|
|
|
| 207 |
if len(options) < n + 1:
|
| 208 |
context_words = [token.text for token in nlp(context) if token.is_alpha and token.text.lower() != answer.lower()]
|
| 209 |
options.extend(random.sample(context_words, min(n - len(options) + 1, len(context_words))))
|
| 210 |
+
print(f"\n\nAll Possible Options: {options}\n\n")
|
| 211 |
# Ensure we have the correct number of unique options
|
| 212 |
options = list(dict.fromkeys(options))[:n+1]
|
| 213 |
|
|
|
|
| 220 |
def map_keywords_to_sentences(text, keywords, context_window_size):
|
| 221 |
sentences = sent_tokenize(text)
|
| 222 |
keyword_sentence_mapping = {}
|
| 223 |
+
print(f"\n\nSentences: {sentences}\n\n")
|
| 224 |
for keyword in keywords:
|
| 225 |
for i, sentence in enumerate(sentences):
|
| 226 |
if keyword in sentence:
|
|
|
|
| 319 |
if 'generated_questions' not in st.session_state:
|
| 320 |
st.session_state.generated_questions = []
|
| 321 |
|
|
|
|
|
|
|
| 322 |
with st.sidebar:
|
| 323 |
st.subheader("Customization Options")
|
| 324 |
# Customization options
|
| 325 |
+
input_type = st.radio("Select Input Preference", ("Text Input","Upload PDF"))
|
| 326 |
num_beams = st.slider("Select number of beams for question generation", min_value=1, max_value=10, value=5)
|
| 327 |
context_window_size = st.slider("Select context window size (number of sentences before and after)", min_value=1, max_value=5, value=1)
|
| 328 |
num_questions = st.slider("Select number of questions to generate", min_value=1, max_value=1000, value=5)
|
|
|
|
| 337 |
extract_all_keywords = st.toggle("Extract Max Keywords",value=False)
|
| 338 |
with col2:
|
| 339 |
enable_feedback_mode = st.toggle("Enable Feedback Mode",False)
|
| 340 |
+
text = None
|
| 341 |
+
if input_type == "Text Input":
|
| 342 |
+
text = st.text_area("Enter text here:", value="Joe Biden, the current US president is on a weak wicket going in for his reelection later this November against former President Donald Trump.")
|
| 343 |
+
elif input_type == "Upload PDF":
|
| 344 |
+
file = st.file_uploader("Upload PDF Files")
|
| 345 |
+
if file is not None:
|
| 346 |
+
text = get_pdf_text(file)
|
| 347 |
+
if text:
|
| 348 |
+
text = clean_text(text)
|
| 349 |
+
segments = segment_text(text)
|
| 350 |
generate_questions_button = st.button("Generate Questions")
|
| 351 |
if generate_questions_button and text:
|
| 352 |
st.session_state.generated_questions = []
|
| 353 |
+
for text in segments:
|
| 354 |
+
keywords = extract_keywords(text, extract_all_keywords)
|
| 355 |
+
print(f"\n\nFinal Keywords in Main Function: {keywords}\n\n")
|
| 356 |
+
keyword_sentence_mapping = map_keywords_to_sentences(text, keywords, context_window_size)
|
| 357 |
+
for i, (keyword, context) in enumerate(keyword_sentence_mapping.items()):
|
| 358 |
+
if i >= num_questions:
|
| 359 |
+
break
|
| 360 |
+
question = generate_question(context, keyword, num_beams=num_beams)
|
| 361 |
+
options = generate_options(keyword,context)
|
| 362 |
+
overall_score, relevance_score, complexity_score, spelling_correctness = assess_question_quality(context,question,keyword)
|
| 363 |
+
if overall_score < 0.5:
|
| 364 |
+
continue
|
| 365 |
+
tpl = {
|
| 366 |
+
"question" : question,
|
| 367 |
+
"context" : context,
|
| 368 |
+
"answer" : keyword,
|
| 369 |
+
"options" : options,
|
| 370 |
+
"overall_score" : overall_score,
|
| 371 |
+
"relevance_score" : relevance_score,
|
| 372 |
+
"complexity_score" : complexity_score,
|
| 373 |
+
"spelling_correctness" : spelling_correctness,
|
| 374 |
+
}
|
| 375 |
+
st.session_state.generated_questions.append(tpl)
|
| 376 |
+
|
| 377 |
+
# sort question based on their quality score
|
| 378 |
+
st.session_state.generated_questions = sorted(st.session_state.generated_questions,key = lambda x: x['overall_score'], reverse=True)
|
| 379 |
# Display generated questions
|
| 380 |
if st.session_state.generated_questions:
|
| 381 |
st.header("Generated Questions:",divider='blue')
|