Technozam commited on
Commit
4ea0ccb
1 Parent(s): 8fd156b

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +348 -0
app.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """QuestionGenerator.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1k0AavzSaNYxe36bk65fsXWzC4xSSwo6X
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
+ nltk.download('punkt')
44
+ nltk.download('brown')
45
+ nltk.download('wordnet')
46
+ from nltk.corpus import wordnet as wn
47
+ from nltk.tokenize import sent_tokenize
48
+
49
+ def postprocesstext (content):
50
+ final=""
51
+ for sent in sent_tokenize(content):
52
+ sent = sent.capitalize()
53
+ final = final +" "+sent
54
+ return final
55
+
56
+
57
+ def summarizer(text,model,tokenizer):
58
+ text = text.strip().replace("\n"," ")
59
+ text = "summarize: "+text
60
+ # print (text)
61
+ max_len = 512
62
+ encoding = tokenizer.encode_plus(text,max_length=max_len, pad_to_max_length=False,truncation=True, return_tensors="pt").to(device)
63
+
64
+ input_ids, attention_mask = encoding["input_ids"], encoding["attention_mask"]
65
+
66
+ outs = model.generate(input_ids=input_ids,
67
+ attention_mask=attention_mask,
68
+ early_stopping=True,
69
+ num_beams=3,
70
+ num_return_sequences=1,
71
+ no_repeat_ngram_size=2,
72
+ min_length = 75,
73
+ max_length=300)
74
+
75
+
76
+ dec = [tokenizer.decode(ids,skip_special_tokens=True) for ids in outs]
77
+ summary = dec[0]
78
+ summary = postprocesstext(summary)
79
+ summary= summary.strip()
80
+
81
+ return summary
82
+
83
+
84
+ summarized_text = summarizer(text,summary_model,summary_tokenizer)
85
+
86
+
87
+ print ("\noriginal Text >>")
88
+ for wrp in wrap(text, 150):
89
+ print (wrp)
90
+ print ("\n")
91
+ print ("Summarized Text >>")
92
+ for wrp in wrap(summarized_text, 150):
93
+ print (wrp)
94
+ print ("\n")
95
+
96
+ total = 10
97
+
98
+ """# **Answer Span Extraction (Keywords and Noun Phrases)**"""
99
+
100
+ import nltk
101
+ nltk.download('stopwords')
102
+ from nltk.corpus import stopwords
103
+ import string
104
+ import pke
105
+ import traceback
106
+
107
+
108
+ def get_nouns_multipartite(content):
109
+ out=[]
110
+ try:
111
+ # extractor = spacy.load("en_core_web_sm")
112
+ extractor = pke.unsupervised.MultipartiteRank()
113
+
114
+ extractor.load_document(input=content,language='en')
115
+
116
+
117
+ # not contain punctuation marks or stopwords as candidates.
118
+ pos = {'PROPN','NOUN'}
119
+ #pos = {'PROPN','NOUN'}
120
+ stoplist = list(string.punctuation)
121
+ stoplist += ['-lrb-', '-rrb-', '-lcb-', '-rcb-', '-lsb-', '-rsb-']
122
+ stoplist += stopwords.words('english')
123
+ # extractor.candidate_selection(pos=pos, stoplist=stoplist)
124
+ extractor.candidate_selection(pos=pos)
125
+ # 4. build the Multipartite graph and rank candidates using random walk,
126
+ # alpha controls the weight adjustment mechanism, see TopicRank for
127
+ # threshold/method parameters.
128
+ extractor.candidate_weighting(alpha=1.1,
129
+ threshold=0.75,
130
+ method='average')
131
+ keyphrases = extractor.get_n_best(n=15)
132
+
133
+
134
+ for val in keyphrases:
135
+ out.append(val[0])
136
+ except:
137
+ out = []
138
+ traceback.print_exc()
139
+
140
+ return out
141
+
142
+ from flashtext import KeywordProcessor
143
+
144
+ def get_keywords(originaltext,summarytext,total):
145
+ keywords = get_nouns_multipartite(originaltext)
146
+ print ("keywords unsummarized: ",keywords)
147
+ keyword_processor = KeywordProcessor()
148
+ for keyword in keywords:
149
+ keyword_processor.add_keyword(keyword)
150
+
151
+ keywords_found = keyword_processor.extract_keywords(summarytext)
152
+ keywords_found = list(set(keywords_found))
153
+ print ("keywords_found in summarized: ",keywords_found)
154
+
155
+ important_keywords =[]
156
+ for keyword in keywords:
157
+ if keyword in keywords_found:
158
+ important_keywords.append(keyword)
159
+
160
+ return important_keywords[:total]
161
+
162
+
163
+ imp_keywords = get_keywords(text,summarized_text,total)
164
+ print (imp_keywords)
165
+
166
+ """# **Question generation using T5**"""
167
+
168
+ question_model = T5ForConditionalGeneration.from_pretrained('ramsrigouthamg/t5_squad_v1')
169
+ question_tokenizer = T5Tokenizer.from_pretrained('ramsrigouthamg/t5_squad_v1')
170
+ question_model = question_model.to(device)
171
+
172
+ def get_question(context,answer,model,tokenizer):
173
+ text = "context: {} answer: {}".format(context,answer)
174
+ encoding = tokenizer.encode_plus(text,max_length=384, pad_to_max_length=False,truncation=True, return_tensors="pt").to(device)
175
+ input_ids, attention_mask = encoding["input_ids"], encoding["attention_mask"]
176
+
177
+ outs = model.generate(input_ids=input_ids,
178
+ attention_mask=attention_mask,
179
+ early_stopping=True,
180
+ num_beams=5,
181
+ num_return_sequences=1,
182
+ no_repeat_ngram_size=2,
183
+ max_length=72)
184
+
185
+
186
+ dec = [tokenizer.decode(ids,skip_special_tokens=True) for ids in outs]
187
+
188
+
189
+ Question = dec[0].replace("question:","")
190
+ Question= Question.strip()
191
+ return Question
192
+
193
+
194
+
195
+ for wrp in wrap(summarized_text, 150):
196
+ print (wrp)
197
+ print ("\n")
198
+
199
+ for answer in imp_keywords:
200
+ ques = get_question(summarized_text,answer,question_model,question_tokenizer)
201
+ print (ques)
202
+ print (answer.capitalize())
203
+ print ("\n")
204
+
205
+ """# **UI by using Gradio**"""
206
+
207
+ import mysql.connector
208
+ import datetime;
209
+
210
+ mydb = mysql.connector.connect(
211
+ host="qtechdb-1.cexugk1h8rui.ap-northeast-1.rds.amazonaws.com",
212
+ user="admin",
213
+ password="F3v2vGWzb8vaniE3nqzi",
214
+ database="spring_social"
215
+ )
216
+
217
+ import gradio as gr
218
+
219
+
220
+ context = gr.Textbox(lines=10, placeholder="Enter paragraph/content here...", label="Text")
221
+ total = gr.Slider(1,10, value=1,step=1, label="Total Number Of Questions")
222
+ subject = gr.Textbox(placeholder="Enter subject/title here...", label="Text")
223
+
224
+ output = gr.Markdown( label="Question and Answers")
225
+
226
+
227
+ def generate_question_text(context,subject,total):
228
+ summary_text = summarizer(context,summary_model,summary_tokenizer)
229
+ for wrp in wrap(summary_text, 150):
230
+ print (wrp)
231
+ np = get_keywords(context,summary_text,total)
232
+ print ("\n\nNoun phrases",np)
233
+ output="<b style='color:black;'>Answer the following short questions.</b><br><br>"
234
+ i=1
235
+ for answer in np:
236
+ ques = get_question(summary_text,answer,question_model,question_tokenizer)
237
+ # output= output + ques + "\n" + "Ans: "+answer.capitalize() + "\n\n"
238
+ output = output + "<b style='color:black;'>Q"+ str(i) + ") " + ques + "</b><br>"
239
+ # output = output + "<br>"
240
+ output = output + "<br>"
241
+ i += 1
242
+
243
+ output = output + "<br><b style='color:black;'>" + "Correct Answer Key:</b><br>"
244
+
245
+ i=1
246
+ for answer in np:
247
+ output = output + "<b style='color:green;'>" + "Ans"+ str(i) + ": " +answer.capitalize()+ "</b>"
248
+ output = output + "<br>"
249
+ i += 1
250
+
251
+ mycursor = mydb.cursor()
252
+ timedate = datetime.datetime.now()
253
+
254
+ sql = "INSERT INTO shorttexts (subject, input, output, timedate) VALUES (%s,%s, %s,%s)"
255
+ val = (subject, context, output, timedate)
256
+ mycursor.execute(sql, val)
257
+
258
+ mydb.commit()
259
+
260
+ print(mycursor.rowcount, "record inserted.")
261
+
262
+ return output
263
+
264
+ iface = gr.Interface(
265
+ fn=generate_question_text,
266
+ inputs=[context,subject, total],
267
+ outputs=output, css=".gradio-container {background-image: url('file=blue.jpg')}",
268
+ allow_flagging="manual",flagging_options=["Save Data"])
269
+
270
+ # iface.launch(debug=True, share=True)
271
+
272
+ def generate_question(context,subject,total):
273
+ summary_text = summarizer(context,summary_model,summary_tokenizer)
274
+ for wrp in wrap(summary_text, 150):
275
+ print (wrp)
276
+ np = get_keywords(context,summary_text,total)
277
+ print ("\n\nNoun phrases",np)
278
+ output="<b style='color:black;'>Answer the following short questions.</b><br><br>"
279
+ i=1
280
+ for answer in np:
281
+ ques = get_question(summary_text,answer,question_model,question_tokenizer)
282
+ # output= output + ques + "\n" + "Ans: "+answer.capitalize() + "\n\n"
283
+ output = output + "<b style='color:black;'>Q"+ str(i) + ") " + ques + "</b><br>"
284
+ # output = output + "<br>"
285
+ output = output + "<br>"
286
+ i += 1
287
+
288
+ output = output + "<br><b style='color:black;'>" + "Correct Answer Key:</b><br>"
289
+
290
+ i=1
291
+ for answer in np:
292
+ output = output + "<b style='color:green;'>" + "Ans"+ str(i) + ": " +answer.capitalize()+ "</b>"
293
+ output = output + "<br>"
294
+ i += 1
295
+
296
+ return output
297
+
298
+ import glob
299
+ import os.path
300
+ import pandas as pd
301
+
302
+ file =None
303
+
304
+ def filecreate(x,subject,total):
305
+
306
+ with open(x.name) as fo:
307
+ text = fo.read()
308
+ # print(text)
309
+ generated = generate_question(text,subject, total)
310
+
311
+ mycursor = mydb.cursor()
312
+
313
+ timedate= datetime.datetime.now()
314
+
315
+ sql = "INSERT INTO shortfiles (subject, input, output, timedate) VALUES (%s,%s, %s,%s)"
316
+ val = (subject, text, generated, timedate)
317
+ mycursor.execute(sql, val)
318
+
319
+ mydb.commit()
320
+
321
+ print(mycursor.rowcount, "record inserted.")
322
+
323
+ return generated
324
+
325
+ # filecreate(file,2)
326
+
327
+ import gradio as gr
328
+
329
+ context = gr.HTML(label="Text")
330
+ file = gr.File()
331
+ subject = gr.Textbox(placeholder="Enter subject/title here...", label="Text")
332
+ total = gr.Slider(1,10, value=1,step=1, label="Total Number Of Questions")
333
+
334
+
335
+ # output = gr.HTML( label="Question and Answers")
336
+
337
+ fface = gr.Interface(
338
+ fn=filecreate,
339
+ inputs=[file,subject,total],
340
+ outputs=context,
341
+ css=".gradio-container {background-image: url('file=blue.jpg')}",
342
+ allow_flagging="manual",flagging_options=["Save Data"])
343
+
344
+
345
+ # fface.launch(debug=True, share=True)
346
+
347
+ demo = gr.TabbedInterface([iface, fface], ["Text", "Upload File"], css=".gradio-container {background-image: url('file=blue.jpg')}")
348
+ demo.launch(debug=True, share=True)