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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""True-FalseGenerator.ipynb
|
3 |
+
|
4 |
+
Automatically generated by Colaboratory.
|
5 |
+
|
6 |
+
Original file is located at
|
7 |
+
https://colab.research.google.com/drive/1unGjdSsz_ay3oVQyYChtJUQXcgXc0VO8
|
8 |
+
"""
|
9 |
+
|
10 |
+
from textwrap3 import wrap
|
11 |
+
|
12 |
+
text = """A Lion lay asleep in the forest, his great head resting on his paws. A timid little Mouse came upon him unexpectedly, and in her fright and haste to
|
13 |
+
get away, ran across the Lion's nose. Roused from his nap, the Lion laid his huge paw angrily on the tiny creature to kill her. "Spare me!" begged
|
14 |
+
the poor Mouse. "Please let me go and some day I will surely repay you." The Lion was much amused to think that a Mouse could ever help him. But he
|
15 |
+
was generous and finally let the Mouse go. Some days later, while stalking his prey in the forest, the Lion was caught in the toils of a hunter's
|
16 |
+
net. Unable to free himself, he filled the forest with his angry roaring. The Mouse knew the voice and quickly found the Lion struggling in the net.
|
17 |
+
Running to one of the great ropes that bound him, she gnawed it until it parted, and soon the Lion was free. "You laughed when I said I would repay
|
18 |
+
you," said the Mouse. "Now you see that even a Mouse can help a Lion." """
|
19 |
+
for wrp in wrap(text, 150):
|
20 |
+
print (wrp)
|
21 |
+
print ("\n")
|
22 |
+
|
23 |
+
import torch
|
24 |
+
from transformers import T5ForConditionalGeneration,T5Tokenizer
|
25 |
+
summary_model = T5ForConditionalGeneration.from_pretrained('t5-base')
|
26 |
+
summary_tokenizer = T5Tokenizer.from_pretrained('t5-base')
|
27 |
+
|
28 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
29 |
+
summary_model = summary_model.to(device)
|
30 |
+
|
31 |
+
import random
|
32 |
+
import numpy as np
|
33 |
+
|
34 |
+
def set_seed(seed: int):
|
35 |
+
random.seed(seed)
|
36 |
+
np.random.seed(seed)
|
37 |
+
torch.manual_seed(seed)
|
38 |
+
torch.cuda.manual_seed_all(seed)
|
39 |
+
|
40 |
+
set_seed(42)
|
41 |
+
|
42 |
+
import nltk
|
43 |
+
from nltk.corpus import wordnet as wn
|
44 |
+
from nltk.tokenize import sent_tokenize
|
45 |
+
|
46 |
+
def postprocesstext (content):
|
47 |
+
final=""
|
48 |
+
for sent in sent_tokenize(content):
|
49 |
+
sent = sent.capitalize()
|
50 |
+
final = final +" "+sent
|
51 |
+
return final
|
52 |
+
|
53 |
+
|
54 |
+
def summarizer(text,model,tokenizer):
|
55 |
+
text = text.strip().replace("\n"," ")
|
56 |
+
text = "summarize: "+text
|
57 |
+
# print (text)
|
58 |
+
max_len = 512
|
59 |
+
encoding = tokenizer.encode_plus(text,max_length=max_len, pad_to_max_length=False,truncation=True, return_tensors="pt").to(device)
|
60 |
+
|
61 |
+
input_ids, attention_mask = encoding["input_ids"], encoding["attention_mask"]
|
62 |
+
|
63 |
+
outs = model.generate(input_ids=input_ids,
|
64 |
+
attention_mask=attention_mask,
|
65 |
+
early_stopping=True,
|
66 |
+
num_beams=3,
|
67 |
+
num_return_sequences=1,
|
68 |
+
no_repeat_ngram_size=2,
|
69 |
+
min_length = 75,
|
70 |
+
max_length=300)
|
71 |
+
|
72 |
+
|
73 |
+
dec = [tokenizer.decode(ids,skip_special_tokens=True) for ids in outs]
|
74 |
+
summary = dec[0]
|
75 |
+
summary = postprocesstext(summary)
|
76 |
+
summary= summary.strip()
|
77 |
+
|
78 |
+
return summary
|
79 |
+
|
80 |
+
|
81 |
+
summarized_text = summarizer(text,summary_model,summary_tokenizer)
|
82 |
+
|
83 |
+
total = 10
|
84 |
+
|
85 |
+
"""# **Answer Span Extraction (Keywords and Noun Phrases)**"""
|
86 |
+
|
87 |
+
import nltk
|
88 |
+
nltk.download('stopwords')
|
89 |
+
from nltk.corpus import stopwords
|
90 |
+
import string
|
91 |
+
import pke
|
92 |
+
import traceback
|
93 |
+
|
94 |
+
|
95 |
+
def get_nouns_multipartite(content):
|
96 |
+
out=[]
|
97 |
+
try:
|
98 |
+
# extractor = spacy.load("en_core_web_sm")
|
99 |
+
extractor = pke.unsupervised.MultipartiteRank()
|
100 |
+
|
101 |
+
extractor.load_document(input=content,language='en')
|
102 |
+
|
103 |
+
|
104 |
+
# not contain punctuation marks or stopwords as candidates.
|
105 |
+
pos = {'PROPN','NOUN'}
|
106 |
+
#pos = {'PROPN','NOUN'}
|
107 |
+
stoplist = list(string.punctuation)
|
108 |
+
stoplist += ['-lrb-', '-rrb-', '-lcb-', '-rcb-', '-lsb-', '-rsb-']
|
109 |
+
stoplist += stopwords.words('english')
|
110 |
+
# extractor.candidate_selection(pos=pos, stoplist=stoplist)
|
111 |
+
extractor.candidate_selection(pos=pos)
|
112 |
+
# 4. build the Multipartite graph and rank candidates using random walk,
|
113 |
+
# alpha controls the weight adjustment mechanism, see TopicRank for
|
114 |
+
# threshold/method parameters.
|
115 |
+
extractor.candidate_weighting(alpha=1.1,
|
116 |
+
threshold=0.75,
|
117 |
+
method='average')
|
118 |
+
keyphrases = extractor.get_n_best(n=15)
|
119 |
+
|
120 |
+
|
121 |
+
for val in keyphrases:
|
122 |
+
out.append(val[0])
|
123 |
+
except:
|
124 |
+
out = []
|
125 |
+
traceback.print_exc()
|
126 |
+
|
127 |
+
return out
|
128 |
+
|
129 |
+
from flashtext import KeywordProcessor
|
130 |
+
|
131 |
+
def get_keywords(originaltext,summarytext,total):
|
132 |
+
keywords = get_nouns_multipartite(originaltext)
|
133 |
+
print ("keywords unsummarized: ",keywords)
|
134 |
+
keyword_processor = KeywordProcessor()
|
135 |
+
for keyword in keywords:
|
136 |
+
keyword_processor.add_keyword(keyword)
|
137 |
+
|
138 |
+
keywords_found = keyword_processor.extract_keywords(summarytext)
|
139 |
+
keywords_found = list(set(keywords_found))
|
140 |
+
print ("keywords_found in summarized: ",keywords_found)
|
141 |
+
|
142 |
+
important_keywords =[]
|
143 |
+
for keyword in keywords:
|
144 |
+
if keyword in keywords_found:
|
145 |
+
important_keywords.append(keyword)
|
146 |
+
|
147 |
+
return important_keywords[:total]
|
148 |
+
|
149 |
+
|
150 |
+
imp_keywords = get_keywords(text,summarized_text,total)
|
151 |
+
print (imp_keywords)
|
152 |
+
|
153 |
+
"""# **Question generation using T5**"""
|
154 |
+
|
155 |
+
question_model = T5ForConditionalGeneration.from_pretrained('ramsrigouthamg/t5_boolean_questions')
|
156 |
+
question_tokenizer = T5Tokenizer.from_pretrained('ramsrigouthamg/t5_boolean_questions')
|
157 |
+
question_model = question_model.to(device)
|
158 |
+
|
159 |
+
def get_question(context,answer,model,tokenizer):
|
160 |
+
text = "context: {} answer: {}".format(context,answer)
|
161 |
+
encoding = tokenizer.encode_plus(text,max_length=384, pad_to_max_length=False,truncation=True, return_tensors="pt").to(device)
|
162 |
+
input_ids, attention_mask = encoding["input_ids"], encoding["attention_mask"]
|
163 |
+
|
164 |
+
outs = model.generate(input_ids=input_ids,
|
165 |
+
attention_mask=attention_mask,
|
166 |
+
early_stopping=True,
|
167 |
+
num_beams=5,
|
168 |
+
num_return_sequences=1,
|
169 |
+
no_repeat_ngram_size=2,
|
170 |
+
max_length=72)
|
171 |
+
|
172 |
+
|
173 |
+
dec = [tokenizer.decode(ids,skip_special_tokens=True) for ids in outs]
|
174 |
+
|
175 |
+
|
176 |
+
Question = dec[0].replace("question:","")
|
177 |
+
Question= Question.strip()
|
178 |
+
return Question
|
179 |
+
|
180 |
+
"""# **UI by using Gradio**"""
|
181 |
+
|
182 |
+
import mysql.connector
|
183 |
+
import datetime;
|
184 |
+
|
185 |
+
mydb = mysql.connector.connect(
|
186 |
+
host="qtechdb-1.cexugk1h8rui.ap-northeast-1.rds.amazonaws.com",
|
187 |
+
user="admin",
|
188 |
+
password="F3v2vGWzb8vaniE3nqzi",
|
189 |
+
database="spring_social"
|
190 |
+
)
|
191 |
+
|
192 |
+
import gradio as gr
|
193 |
+
|
194 |
+
context = gr.Textbox(lines=10, placeholder="Enter paragraph/content here...", label="Text")
|
195 |
+
total = gr.Slider(1,10, value=1,step=1, label="Total Number Of Questions")
|
196 |
+
subject = gr.Textbox(placeholder="Enter subject/title here...", label="Text")
|
197 |
+
|
198 |
+
|
199 |
+
output = gr.Markdown( label="Question and Answers")
|
200 |
+
|
201 |
+
|
202 |
+
def generate_question_text(context,subject,total):
|
203 |
+
summary_text = summarizer(context,summary_model,summary_tokenizer)
|
204 |
+
for wrp in wrap(summary_text, 150):
|
205 |
+
print (wrp)
|
206 |
+
np = get_keywords(context,summary_text,total)
|
207 |
+
print ("\n\nNoun phrases",np)
|
208 |
+
output="<b style='color:black;'>Answer the following true/false questions. Select the correct answer.</b><br><br>"
|
209 |
+
|
210 |
+
i=1
|
211 |
+
for answer in np:
|
212 |
+
ques = get_question(summary_text,answer,question_model,question_tokenizer)
|
213 |
+
# output= output + ques + "\n" + "Ans: "+answer.capitalize() + "\n\n"
|
214 |
+
output = output + "<b style='color:black;'>Q"+ str(i) + ") " + ques + "</b> <br>"
|
215 |
+
# output = output + "<br>"
|
216 |
+
output = output + "<b>" + "a) True <br></b>"
|
217 |
+
output = output + "<b>" + "b) False </b>"
|
218 |
+
|
219 |
+
output = output + "<br>"
|
220 |
+
i += 1
|
221 |
+
|
222 |
+
mycursor = mydb.cursor()
|
223 |
+
timedate = datetime.datetime.now()
|
224 |
+
|
225 |
+
sql = "INSERT INTO truetexts (subject, input, output, timedate) VALUES (%s,%s, %s,%s)"
|
226 |
+
val = (subject, context, output, timedate)
|
227 |
+
mycursor.execute(sql, val)
|
228 |
+
|
229 |
+
mydb.commit()
|
230 |
+
|
231 |
+
print(mycursor.rowcount, "record inserted.")
|
232 |
+
return output
|
233 |
+
|
234 |
+
iface = gr.Interface(
|
235 |
+
fn=generate_question_text,
|
236 |
+
inputs=[context,subject, total],
|
237 |
+
outputs=output,
|
238 |
+
css=".gradio-container {background-image: url('file=blue.jpg')}",
|
239 |
+
allow_flagging="manual",flagging_options=["Save Data"])
|
240 |
+
|
241 |
+
# iface.launch(debug=True, share=True)
|
242 |
+
|
243 |
+
def generate_question(context,subject,total):
|
244 |
+
summary_text = summarizer(context,summary_model,summary_tokenizer)
|
245 |
+
for wrp in wrap(summary_text, 150):
|
246 |
+
print (wrp)
|
247 |
+
np = get_keywords(context,summary_text,total)
|
248 |
+
print ("\n\nNoun phrases",np)
|
249 |
+
output="<b style='color:black;'>Answer the following true/false questions. Select the correct answer.</b><br><br>"
|
250 |
+
|
251 |
+
i=1
|
252 |
+
for answer in np:
|
253 |
+
ques = get_question(summary_text,answer,question_model,question_tokenizer)
|
254 |
+
# output= output + ques + "\n" + "Ans: "+answer.capitalize() + "\n\n"
|
255 |
+
output = output + "<b style='color:black;'>Q"+ str(i) + ") " + ques + "</b> <br>"
|
256 |
+
# output = output + "<br>"
|
257 |
+
output = output + "<b>" + "a) True <br></b>"
|
258 |
+
output = output + "<b>" + "b) False </b>"
|
259 |
+
|
260 |
+
output = output + "<br>"
|
261 |
+
i += 1
|
262 |
+
|
263 |
+
return output
|
264 |
+
|
265 |
+
import glob
|
266 |
+
import os.path
|
267 |
+
import pandas as pd
|
268 |
+
|
269 |
+
file =None
|
270 |
+
|
271 |
+
def filecreate(x,subject,total):
|
272 |
+
|
273 |
+
with open(x.name) as fo:
|
274 |
+
text = fo.read()
|
275 |
+
# print(text)
|
276 |
+
generated = generate_question(text,subject, total)
|
277 |
+
|
278 |
+
mycursor = mydb.cursor()
|
279 |
+
|
280 |
+
timedate= datetime.datetime.now()
|
281 |
+
|
282 |
+
sql = "INSERT INTO truefiles (subject, input, output, timedate) VALUES (%s,%s, %s,%s)"
|
283 |
+
val = (subject, text, generated, timedate)
|
284 |
+
mycursor.execute(sql, val)
|
285 |
+
|
286 |
+
mydb.commit()
|
287 |
+
|
288 |
+
print(mycursor.rowcount, "record inserted.")
|
289 |
+
|
290 |
+
# return text
|
291 |
+
return generated
|
292 |
+
|
293 |
+
import gradio as gr
|
294 |
+
|
295 |
+
context = gr.HTML(label="Text")
|
296 |
+
file = gr.File()
|
297 |
+
total = gr.Slider(1,10, value=1,step=1, label="Total Number Of Questions")
|
298 |
+
subject = gr.Textbox(placeholder="Enter subject/title here...", label="Text")
|
299 |
+
|
300 |
+
fface = gr.Interface(
|
301 |
+
fn=filecreate,
|
302 |
+
inputs=[file,subject,total],
|
303 |
+
outputs=context,
|
304 |
+
css=".gradio-container {background-image: url('file=blue.jpg')}",
|
305 |
+
allow_flagging="manual",flagging_options=["Save Data"])
|
306 |
+
|
307 |
+
# fface.launch(debug=True, share=True)
|
308 |
+
|
309 |
+
demo = gr.TabbedInterface([iface, fface], ["Text", "Upload File"], css=".gradio-container {background-image: url('file=blue.jpg')}")
|
310 |
+
demo.launch(debug=True, share=True)
|