Aakash Goel commited on
Commit
3d95564
·
1 Parent(s): e1d618b

spacy changes 5

Browse files
Files changed (3) hide show
  1. code/quiz_gen_new.py +1 -0
  2. code/quiz_gen_new2.py +290 -0
  3. requirements.txt +0 -0
code/quiz_gen_new.py CHANGED
@@ -225,6 +225,7 @@ if raw_text != None and raw_text != '':
225
  summary_text = summarizer(raw_text,summary_model,summary_tokenizer)
226
  ans_list = get_keywords(raw_text,summary_text)
227
  questions = []
 
228
  for ans in ans_list:
229
  ques = get_question(summary_text,ans,question_model,question_tokenizer)
230
  if ques not in questions:
 
225
  summary_text = summarizer(raw_text,summary_model,summary_tokenizer)
226
  ans_list = get_keywords(raw_text,summary_text)
227
  questions = []
228
+
229
  for ans in ans_list:
230
  ques = get_question(summary_text,ans,question_model,question_tokenizer)
231
  if ques not in questions:
code/quiz_gen_new2.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # !pip install --quiet transformers==4.5.0
2
+ # !pip install --quiet sentencepiece==0.1.95
3
+ # !pip install --quiet git+https://github.com/boudinfl/pke.git@dc4d5f21e0ffe64c4df93c46146d29d1c522476b
4
+ # pip install git+https://github.com/boudinfl/pke.git
5
+ # !pip install --quiet nltk==3.2.5
6
+
7
+
8
+ # pip install git+https://github.com/boudinfl/pke.git@dc4d5f21e0ffe64c4df93c46146d29d1c522476b
9
+ # pip install spacy==3.1.3
10
+ # pip install textwrap3==0.9.2
11
+ # pip install flashtext==2.7
12
+
13
+
14
+ import streamlit as st
15
+ from textwrap3 import wrap
16
+ from flashtext import KeywordProcessor
17
+ import torch, random, nltk, string, traceback, sys, os, requests, datetime
18
+ import numpy as np
19
+ import pandas as pd
20
+ from transformers import T5ForConditionalGeneration,T5Tokenizer
21
+ # st.write("Import pke")
22
+ import pke
23
+
24
+ def set_seed(seed: int):
25
+ random.seed(seed)
26
+ np.random.seed(seed)
27
+ torch.manual_seed(seed)
28
+ torch.cuda.manual_seed_all(seed)
29
+
30
+ set_seed(42)
31
+
32
+
33
+ @st.cache(allow_output_mutation = True)
34
+ def load_model():
35
+ nltk.download('punkt')
36
+ nltk.download('brown')
37
+ nltk.download('wordnet')
38
+ nltk.download('stopwords')
39
+ nltk.download('wordnet')
40
+ nltk.download('omw-1.4')
41
+ summary_model = T5ForConditionalGeneration.from_pretrained('t5-base')
42
+ summary_tokenizer = T5Tokenizer.from_pretrained('t5-base')
43
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
44
+ summary_model = summary_model.to(device)
45
+ question_model = T5ForConditionalGeneration.from_pretrained('ramsrigouthamg/t5_squad_v1')
46
+ question_tokenizer = T5Tokenizer.from_pretrained('ramsrigouthamg/t5_squad_v1')
47
+ question_model = question_model.to(device)
48
+ return summary_model, summary_tokenizer, question_tokenizer, question_model
49
+
50
+ from nltk.corpus import wordnet as wn
51
+ from nltk.tokenize import sent_tokenize
52
+ from nltk.corpus import stopwords
53
+
54
+ def postprocesstext (content):
55
+ final=""
56
+ for sent in sent_tokenize(content):
57
+ sent = sent.capitalize()
58
+ final = final +" "+sent
59
+ return final
60
+
61
+ def summarizer(text,model,tokenizer):
62
+ text = text.strip().replace("\n"," ")
63
+ text = "summarize: "+text
64
+ # print (text)
65
+ max_len = 512
66
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
67
+ encoding = tokenizer.encode_plus(text,max_length=max_len, pad_to_max_length=False,\
68
+ truncation=True, return_tensors="pt").to(device)
69
+ input_ids, attention_mask = encoding["input_ids"], encoding["attention_mask"]
70
+ outs = model.generate(input_ids=input_ids,
71
+ attention_mask=attention_mask,
72
+ early_stopping=True,
73
+ num_beams=3,
74
+ num_return_sequences=1,
75
+ no_repeat_ngram_size=2,
76
+ min_length = 75,
77
+ max_length=300)
78
+ dec = [tokenizer.decode(ids,skip_special_tokens=True) for ids in outs]
79
+ summary = dec[0]
80
+ summary = postprocesstext(summary)
81
+ summary= summary.strip()
82
+ return summary
83
+
84
+
85
+ def get_nouns_multipartite(content):
86
+ out=[]
87
+ try:
88
+ extractor = pke.unsupervised.MultipartiteRank()
89
+ extractor.load_document(input=content)
90
+ # not contain punctuation marks or stopwords as candidates.
91
+ pos = {'PROPN','NOUN'}
92
+ #pos = {'PROPN','NOUN'}
93
+ stoplist = list(string.punctuation)
94
+ stoplist += ['-lrb-', '-rrb-', '-lcb-', '-rcb-', '-lsb-', '-rsb-']
95
+ stoplist += stopwords.words('english')
96
+ # extractor.candidate_selection(pos=pos, stoplist=stoplist)
97
+ extractor.candidate_selection(pos=pos)
98
+ # 4. build the Multipartite graph and rank candidates using random walk,
99
+ # alpha controls the weight adjustment mechanism, see TopicRank for
100
+ # threshold/method parameters.
101
+ extractor.candidate_weighting(alpha=1.1,
102
+ threshold=0.75,
103
+ method='average')
104
+ keyphrases = extractor.get_n_best(n=15)
105
+ for val in keyphrases:
106
+ out.append(val[0])
107
+ except Exception as e:
108
+ out = []
109
+ traceback.print_exc()
110
+ print("EXCEPTION: {}".format(e))
111
+ return out
112
+
113
+ def get_keywords(originaltext,summarytext):
114
+ keywords = get_nouns_multipartite(originaltext)
115
+ print ("keywords unsummarized: ",keywords)
116
+ keyword_processor = KeywordProcessor()
117
+ for keyword in keywords:
118
+ keyword_processor.add_keyword(keyword)
119
+ keywords_found = keyword_processor.extract_keywords(summarytext)
120
+ keywords_found = list(set(keywords_found))
121
+ print("keywords_found in summarized: ",keywords_found)
122
+ important_keywords =[]
123
+ for keyword in keywords:
124
+ if keyword in keywords_found:
125
+ important_keywords.append(keyword)
126
+ return important_keywords[:5]
127
+
128
+ def get_question(context,answer,model,tokenizer):
129
+ text = "context: {} answer: {}".format(context,answer)
130
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
131
+ encoding = tokenizer.encode_plus(text,max_length=384, pad_to_max_length=False,\
132
+ truncation=True, return_tensors="pt").to(device)
133
+ input_ids, attention_mask = encoding["input_ids"], encoding["attention_mask"]
134
+ outs = model.generate(input_ids=input_ids,
135
+ attention_mask=attention_mask,
136
+ early_stopping=True,
137
+ num_beams=5,
138
+ num_return_sequences=1,
139
+ no_repeat_ngram_size=2,
140
+ max_length=72)
141
+ dec = [tokenizer.decode(ids,skip_special_tokens=True) for ids in outs]
142
+ Question = dec[0].replace("question:","")
143
+ Question= Question.strip()
144
+ return Question
145
+
146
+
147
+ def csv_downloader(df):
148
+ res = df.to_csv(index=False,sep="\t").encode('utf-8')
149
+ st.download_button(
150
+ label="Download logs data as CSV separated by tab",
151
+ data=res,
152
+ file_name='df_quiz_log_file.csv',
153
+ mime='text/csv')
154
+
155
+ def load_file():
156
+ """Load text from file"""
157
+ uploaded_file = st.file_uploader("Upload Files",type=['txt'])
158
+ if uploaded_file is not None:
159
+ if uploaded_file.type == "text/plain":
160
+ raw_text = str(uploaded_file.read(),"utf-8")
161
+ return raw_text
162
+
163
+
164
+ def get_related_word(word):
165
+ url = "https://api.datamuse.com/words"
166
+ querystring = {"ml":word}
167
+ responses = requests.request("GET", url, params=querystring)
168
+ related_words = []
169
+ count = 0
170
+ responses = responses.json()
171
+ for res in responses:
172
+ if count >= 4:
173
+ break
174
+ if res["word"]!=word and res["word"]!="":
175
+ related_words.append(res["word"])
176
+ count += 1
177
+ return related_words
178
+
179
+
180
+ def get_final_option_list(ans,other_options):
181
+ option1 = ans
182
+ option2,option3,option4 = "dummy","dummy","dummy"
183
+ try:
184
+ option2 = other_options[0]
185
+ except:
186
+ pass
187
+ try:
188
+ option3 = other_options[1]
189
+ except:
190
+ pass
191
+ try:
192
+ option4 = other_options[2]
193
+ except:
194
+ pass
195
+ final_options = [option1,option2,option3,option4]
196
+ random.shuffle(final_options)
197
+ final_options = tuple(final_options)
198
+ ans_index= 0
199
+ for i in range(4):
200
+ if final_options[i] == ans:
201
+ ans_index = i
202
+ return final_options, ans_index
203
+
204
+ def load_raw_text():
205
+ return " Elon Musk has shown again he can influence the digital currency market with just his tweets. After saying that his electric vehicle-making company Tesla will not accept payments in Bitcoin because of environmental concerns, he tweeted that he was working with developers of Dogecoin to improve system transaction efficiency. Following the two distinct statements from him, the world's largest cryptocurrency hit a two-month low, while Dogecoin rallied by about 20 percent. The SpaceX CEO has in recent months often tweeted in support of Dogecoin, but rarely for Bitcoin. In a recent tweet, Musk put out a statement from Tesla that it was concerned about the rapidly increasing use of fossil fuels for Bitcoin (price in India) mining and transaction, and hence was suspending vehicle purchases using the cryptocurrency. A day later he again tweeted saying, To be clear, I strongly believe in crypto, but it can't drive a massive increase in fossil fuel use, especially coal. It triggered a downward spiral for Bitcoin value but the cryptocurrency has stabilised since. A number of Twitter users welcomed Musk's statement. One of them said it's time people started realising that Dogecoin is here to stay and another referred to Musk's previous assertion that crypto could become the world's future currency."
206
+
207
+ # def get_final_option_list(ans,other_options):
208
+ # option1 = ans
209
+ # option2,option3,option4 = "dummy","dummy","dummy"
210
+ # try:
211
+ # option2 = other_options[0]
212
+ # except:
213
+ # pass
214
+ # try:
215
+ # option3 = other_options[1]
216
+ # except:
217
+ # pass
218
+ # try:
219
+ # option4 = other_options[2]
220
+ # except:
221
+ # pass
222
+ # final_options = [option1,option2,option3,option4]
223
+ # #st.write(final_options)
224
+ # random.shuffle(final_options)
225
+ # #st.write(final_options)
226
+ # final_options = [None]+final_options
227
+ # final_options = tuple(final_options)
228
+ # #st.write(final_options)
229
+ # return final_options
230
+
231
+ st.markdown('![Visitor count](https://shields-io-visitor-counter.herokuapp.com/badge?page=https://share.streamlit.io/https://huggingface.co/spaces/aakashgoel12/getmcq&label=VisitorsCount&labelColor=000000&logo=GitHub&logoColor=FFFFFF&color=1D70B8&style=for-the-badge)')
232
+
233
+ # Loading Model
234
+ summary_model, summary_tokenizer, question_tokenizer, question_model =load_model()
235
+
236
+ # App title and description
237
+ st.title("Exam Assistant")
238
+ st.write("Upload text, Get ready for answering autogenerated questions")
239
+
240
+ # Load file
241
+ st.text("Disclaimer: This app stores user's input for model improvement purposes !!")
242
+
243
+ # Load file
244
+
245
+ default_text = load_raw_text()
246
+ raw_text = st.text_area("Enter text here", default_text, height=400, max_chars=1000000, )
247
+
248
+ # raw_text = load_file()
249
+ start_time = str(datetime.datetime.now())
250
+ if raw_text != None and raw_text != '':
251
+
252
+ # Display text
253
+ # with st.expander("See text"):
254
+ # st.write(raw_text)
255
+
256
+ summary_text = summarizer(raw_text,summary_model,summary_tokenizer)
257
+ ans_list = get_keywords(raw_text,summary_text)
258
+ questions = []
259
+
260
+ for idx,ans in enumerate(ans_list):
261
+ ques = get_question(summary_text,ans,question_model,question_tokenizer)
262
+ if ques not in questions:
263
+ other_options = get_related_word(ans)
264
+ final_options = get_final_option_list(ans,other_options)
265
+ final_options, ans_index = get_final_option_list(ans,other_options)
266
+ # st.write(final_options)
267
+ html_str = f"""
268
+ <div>
269
+ <p>
270
+ {idx+1}: <b> {ques} </b>
271
+ </p>
272
+ </div>
273
+ """
274
+ html_str += f' <p style="color:Green;"><b> {final_options[0]} </b></p> ' if ans_index == 0 else f' <p><b> {final_options[0]} </b></p> '
275
+ html_str += f' <p style="color:Green;"><b> {final_options[1]} </b></p> ' if ans_index == 1 else f' <p><b> {final_options[1]} </b></p> '
276
+ html_str += f' <p style="color:Green;"><b> {final_options[2]} </b></p> ' if ans_index == 2 else f' <p><b> {final_options[2]} </b></p> '
277
+ html_str += f' <p style="color:Green;"><b> {final_options[3]} </b></p> ' if ans_index == 3 else f' <p><b> {final_options[3]} </b></p> '
278
+ html_str += f"""
279
+ """
280
+ st.markdown(html_str , unsafe_allow_html=True)
281
+ st.markdown("-----")
282
+ # st.write("="*50)
283
+ questions.append(ques)
284
+ output_path = "results/df_quiz_log_file.csv"
285
+ res_df = pd.DataFrame({"TimeStamp":[start_time]*len(questions),\
286
+ "Input":[str(raw_text)]*len(questions),\
287
+ "Question":questions,"Answer":ans_list})
288
+ # res_df.to_csv(output_path, mode='a', index=False, sep="\t", header= not os.path.exists(output_path))
289
+ # st.dataframe(pd.read_csv(output_path,sep="\t").tail(5))
290
+ # csv_downloader(pd.read_csv(output_path,sep="\t"))
requirements.txt CHANGED
Binary files a/requirements.txt and b/requirements.txt differ