Technozam commited on
Commit
0622724
1 Parent(s): 838f2aa

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +365 -0
app.py ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """MatchingGenerator.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1drOrBUfaj_UMytwxar_keRWNm5ScaBi7
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
+ # not contain punctuation marks or stopwords as candidates.
117
+ pos = {'PROPN','NOUN'}
118
+ #pos = {'PROPN','NOUN'}
119
+ stoplist = list(string.punctuation)
120
+ stoplist += ['-lrb-', '-rrb-', '-lcb-', '-rcb-', '-lsb-', '-rsb-']
121
+ stoplist += stopwords.words('english')
122
+ # extractor.candidate_selection(pos=pos, stoplist=stoplist)
123
+ extractor.candidate_selection(pos=pos)
124
+ # 4. build the Multipartite graph and rank candidates using random walk,
125
+ # alpha controls the weight adjustment mechanism, see TopicRank for
126
+ # threshold/method parameters.
127
+ extractor.candidate_weighting(alpha=1.1,
128
+ threshold=0.75,
129
+ method='average')
130
+ keyphrases = extractor.get_n_best(n=15)
131
+
132
+
133
+ for val in keyphrases:
134
+ out.append(val[0])
135
+ except:
136
+ out = []
137
+ traceback.print_exc()
138
+
139
+ return out
140
+
141
+ from flashtext import KeywordProcessor
142
+
143
+ def get_keywords(originaltext,summarytext,total):
144
+ keywords = get_nouns_multipartite(originaltext)
145
+ print ("keywords unsummarized: ",keywords)
146
+ keyword_processor = KeywordProcessor()
147
+ for keyword in keywords:
148
+ keyword_processor.add_keyword(keyword)
149
+
150
+ keywords_found = keyword_processor.extract_keywords(summarytext)
151
+ keywords_found = list(set(keywords_found))
152
+ print ("keywords_found in summarized: ",keywords_found)
153
+
154
+ important_keywords =[]
155
+ for keyword in keywords:
156
+ if keyword in keywords_found:
157
+ important_keywords.append(keyword)
158
+
159
+ return important_keywords[:total]
160
+
161
+
162
+ imp_keywords = get_keywords(text,summarized_text,total)
163
+ print (imp_keywords)
164
+
165
+ """# **Question generation using T5**"""
166
+
167
+ question_model = T5ForConditionalGeneration.from_pretrained('ramsrigouthamg/t5_squad_v1')
168
+ question_tokenizer = T5Tokenizer.from_pretrained('ramsrigouthamg/t5_squad_v1')
169
+ question_model = question_model.to(device)
170
+
171
+ def get_question(context,answer,model,tokenizer):
172
+ text = "context: {} answer: {}".format(context,answer)
173
+ encoding = tokenizer.encode_plus(text,max_length=384, pad_to_max_length=False,truncation=True, return_tensors="pt").to(device)
174
+ input_ids, attention_mask = encoding["input_ids"], encoding["attention_mask"]
175
+
176
+ outs = model.generate(input_ids=input_ids,
177
+ attention_mask=attention_mask,
178
+ early_stopping=True,
179
+ num_beams=5,
180
+ num_return_sequences=1,
181
+ no_repeat_ngram_size=2,
182
+ max_length=72)
183
+
184
+
185
+ dec = [tokenizer.decode(ids,skip_special_tokens=True) for ids in outs]
186
+
187
+
188
+ Question = dec[0].replace("question:","")
189
+ Question= Question.strip()
190
+ return Question
191
+
192
+ # for wrp in wrap(summarized_text, 150):
193
+ # print (wrp)
194
+ # print ("\n")
195
+
196
+ # for answer in imp_keywords:
197
+ # ques = get_question(summarized_text,answer,question_model,question_tokenizer)
198
+ # print (ques)
199
+ # print (answer.capitalize())
200
+ # print ("\n")
201
+
202
+ """# **UI by using Gradio**"""
203
+
204
+ import mysql.connector
205
+ import datetime;
206
+
207
+ mydb = mysql.connector.connect(
208
+ host="qtechdb-1.cexugk1h8rui.ap-northeast-1.rds.amazonaws.com",
209
+ user="admin",
210
+ password="F3v2vGWzb8vaniE3nqzi",
211
+ database="spring_social"
212
+ )
213
+
214
+ import gradio as gr
215
+ import random
216
+
217
+ context = gr.Textbox(lines=10, placeholder="Enter paragraph/content here...", label="Text")
218
+ total = gr.Slider(1,10, value=1,step=1, label="Total Number Of Questions")
219
+ subject = gr.Textbox(placeholder="Enter subject/title here...", label="Text")
220
+ output = gr.Markdown( label="Question and Answers")
221
+
222
+
223
+ def generate_question_text(context,subject,total):
224
+ summary_text = summarizer(context,summary_model,summary_tokenizer)
225
+ for wrp in wrap(summary_text, 150):
226
+ print (wrp)
227
+ np = get_keywords(context,summary_text,total)
228
+ random.shuffle(np)
229
+ print ("\n\nNoun phrases",np)
230
+
231
+ output="<b>Select/Match the correct answers to the given questions.</b><br/>"
232
+ answerlist=[]
233
+
234
+ for answer in np:
235
+ answerlist.append(answer)
236
+ random.shuffle(answerlist)
237
+ print(answerlist)
238
+
239
+ for answer in answerlist:
240
+ output = output + "<b style='margin-right:30px;'>" + " "*5 +answer.capitalize()+ "</b>"
241
+ output = output + "<br/>"
242
+
243
+ i=1
244
+ for answer in np:
245
+ ques = get_question(summary_text,answer,question_model,question_tokenizer)
246
+ # output= output + ques + "\n" + "Ans: "+answer.capitalize() + "\n\n"
247
+ output = output + "<b> Q "+ str(i) + ") " + ques + "</b><br/>"
248
+ i += 1
249
+
250
+ output = output + "<br/><b>" + "Correct Answer Key:</b><br/>"
251
+
252
+ i=1
253
+ for answer in np:
254
+ # output= output + ques + "\n" + "Ans: "+answer.capitalize() + "\n\n"
255
+ output = output + "<b style='color:green;'>Ans "+ str(i) + ": " +answer.capitalize()+ "</b>"
256
+ # random.shuffle(output)
257
+ output = output + "<br/>"
258
+ i += 1
259
+
260
+ mycursor = mydb.cursor()
261
+ timedate = datetime.datetime.now()
262
+
263
+ sql = "INSERT INTO matchtexts (subject, input, output, timedate) VALUES (%s,%s, %s,%s)"
264
+ val = (subject, context, output, timedate)
265
+ mycursor.execute(sql, val)
266
+
267
+ mydb.commit()
268
+
269
+ print(mycursor.rowcount, "record inserted.")
270
+
271
+ return output
272
+
273
+ iface = gr.Interface(
274
+ fn=generate_question_text,
275
+ inputs=[context,subject, total],
276
+ outputs=output, css=".gradio-container {background-image: url('file=blue.jpg')}",
277
+ allow_flagging="manual",flagging_options=["Save Data"])
278
+
279
+ # iface.launch(debug=True, share=True)
280
+
281
+ def generate_question(context,subject,total):
282
+ summary_text = summarizer(context,summary_model,summary_tokenizer)
283
+ for wrp in wrap(summary_text, 150):
284
+ print (wrp)
285
+ np = get_keywords(context,summary_text,total)
286
+ random.shuffle(np)
287
+ print ("\n\nNoun phrases",np)
288
+
289
+ output="<b>Select/Match the correct answers to the given questions.</b><br/>"
290
+ answerlist=[]
291
+
292
+ for answer in np:
293
+ answerlist.append(answer)
294
+ random.shuffle(answerlist)
295
+ print(answerlist)
296
+
297
+ for answer in answerlist:
298
+ output = output + "<b style='margin-right:30px;'>" + " "*5 +answer.capitalize()+ "</b>"
299
+ output = output + "<br/>"
300
+
301
+ i=1
302
+ for answer in np:
303
+ ques = get_question(summary_text,answer,question_model,question_tokenizer)
304
+ # output= output + ques + "\n" + "Ans: "+answer.capitalize() + "\n\n"
305
+ output = output + "<b> Q "+ str(i) + ") " + ques + "</b><br/>"
306
+ i += 1
307
+
308
+ output = output + "<br/><b>" + "Correct Answer Key:</b><br/>"
309
+
310
+ i=1
311
+ for answer in np:
312
+ # output= output + ques + "\n" + "Ans: "+answer.capitalize() + "\n\n"
313
+ output = output + "<b style='color:green;'>Ans "+ str(i) + ": " +answer.capitalize()+ "</b>"
314
+ # random.shuffle(output)
315
+ output = output + "<br/>"
316
+ i += 1
317
+
318
+ return output
319
+
320
+ import glob
321
+ import os.path
322
+ import pandas as pd
323
+
324
+ file =None
325
+
326
+ def filecreate(x,subject,total):
327
+
328
+ with open(x.name) as fo:
329
+ text = fo.read()
330
+ # print(text)
331
+ generated = generate_question(text,subject, total)
332
+
333
+ mycursor = mydb.cursor()
334
+ timedate= datetime.datetime.now()
335
+
336
+ sql = "INSERT INTO matchfiles (subject, input, output, timedate) VALUES (%s,%s, %s,%s)"
337
+ val = (subject, text, generated, timedate)
338
+ mycursor.execute(sql, val)
339
+
340
+ mydb.commit()
341
+
342
+ print(mycursor.rowcount, "record inserted.")
343
+
344
+ return generated
345
+
346
+ # filecreate(file,2)
347
+
348
+ import gradio as gr
349
+
350
+ context = gr.HTML(label="Text")
351
+ file = gr.File()
352
+ total = gr.Slider(1,10, value=1,step=1, label="Total Number Of Questions")
353
+ subject = gr.Textbox(placeholder="Enter subject/title here...", label="Text")
354
+
355
+ fface = gr.Interface(
356
+ fn=filecreate,
357
+ inputs=[file,subject,total],
358
+ outputs=context,
359
+ css=".gradio-container {background-image: url('file=blue.jpg')}",
360
+ allow_flagging="manual",flagging_options=["Save Data"])
361
+
362
+ # fface.launch(debug=True, share=True)
363
+
364
+ demo = gr.TabbedInterface([iface, fface], ["Text", "Upload File"], css=".gradio-container {background-image: url('file=blue.jpg')}")
365
+ demo.launch(debug=True, share=True)