Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

run_textrank_ver4.py 20 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
  1. import pandas as pd
  2. import argparse
  3. import os
  4. import re
  5. import csv
  6. import spacy
  7. import json
  8. import numpy as np
  9. import logging
  10. import traceback
  11. from summa.summarizer import summarize
  12. from gensim.models import Word2Vec
  13. from gensim.utils import simple_preprocess
  14. from gensim.parsing.preprocessing import remove_stopwords
  15. from rouge import Rouge
  16. from nltk.corpus import stopwords
  17. from sklearn.feature_extraction.text import TfidfVectorizer
  18. stopwords = set(stopwords.words('english'))
  19. nlp = spacy.load('en_core_web_sm')
  20. cache = {}
  21. class NpEncoder(json.JSONEncoder):
  22. def default(self, obj):
  23. if isinstance(obj, np.integer):
  24. return int(obj)
  25. elif isinstance(obj, np.floating):
  26. return float(obj)
  27. elif isinstance(obj, np.ndarray):
  28. return obj.tolist()
  29. else:
  30. return super(NpEncoder, self).default(obj)
  31. def build_vectorizer(path):
  32. """Create the idf, bigram indices and train the word2vec model
  33. Args:
  34. path (string): the path to the directory that contains
  35. 'questions.csv' and 'answers.csv'
  36. Returns:
  37. Dict: a dictionary whose keys are the unigrams and bigrams
  38. (>=2 occurrence); the values are the idf scores
  39. Word2Vec: the trained gensim Word2Vec model
  40. """
  41. # questions
  42. corpus = []
  43. for filename in os.listdir(path):
  44. filepath = os.path.join(path, filename)
  45. with open(filepath) as json_file:
  46. try:
  47. question = json.load(json_file)
  48. except Exception as ee:
  49. continue
  50. question_text = question['question_text']
  51. corpus.append(question_text)
  52. answers = question['answers']
  53. for idx in range(len(answers)):
  54. answer = answers[idx]
  55. answer_text = answer['answer_text']
  56. corpus.append(answer_text)
  57. # train w2v
  58. model = Word2Vec([simple_preprocess(text.lower()) for text in corpus],
  59. size=300, window=10)
  60. # find bigrams, idf
  61. vectorizer = TfidfVectorizer(ngram_range=(1,2), min_df=2, stop_words='english')
  62. vectorizer.fit(corpus)
  63. vocab = vectorizer.vocabulary_
  64. idf = vectorizer.idf_
  65. idf_dict = dict([(word, idf[vocab[word]]) for word in vocab])
  66. return idf_dict, model
  67. def find_similar_phrases(phrase_vectors_a, phrase_vectors_b, phrase_similarity_threshold=0.85):
  68. """Return similar phrases
  69. """
  70. similar_phrases = {}
  71. for word_vector_pair_a in phrase_vectors_a:
  72. word_a, pv_a = word_vector_pair_a
  73. for word_vector_pair_b in phrase_vectors_b:
  74. word_b, pv_b = word_vector_pair_b
  75. cs = cosine_sim(pv_a, pv_b)
  76. if cs > phrase_similarity_threshold:
  77. if word_b in similar_phrases:
  78. cs_old = similar_phrases[word_b]
  79. if cs > cs_old:
  80. similar_phrases[word_b] = cs
  81. else:
  82. similar_phrases[word_b] = cs
  83. return [(w,similar_phrases[w]) for w in similar_phrases]
  84. def cosine_sim(veca, vecb):
  85. """Cosine similarity of two vectors
  86. """
  87. lena = np.linalg.norm(veca)
  88. lenb = np.linalg.norm(vecb)
  89. if lena < 1e-6 or lenb < 1e-6:
  90. return 0.0
  91. else:
  92. return np.dot(veca, vecb) / lena / lenb
  93. def phrase2vec(phrase, idf, w2v):
  94. """Compute the vector representation of a phrase.
  95. Sum of word vectors weighted by their idf's
  96. Args:
  97. phrase (string): the input phrase (space separated)
  98. idf (Dict): the idf dictionary
  99. w2v (Word2Vec): the word2vec model
  100. Returns:
  101. ndarray: a 300d representation vector
  102. """
  103. global cache
  104. phrase = phrase.lower()
  105. if phrase in cache:
  106. return cache[phrase]
  107. result = np.zeros(300)
  108. for token in phrase.split(' '):
  109. if token in w2v.wv and token in idf:
  110. result += w2v.wv[token] * idf[token]
  111. return result
  112. def text2vec(text, idf, w2v):
  113. """Compute the vector representation of a paragraph.
  114. Sum of the unigrams and bigrams' phrase vectors. Preprocess
  115. with gensim.utils.simple_preprocess (dropping puncts)
  116. Args:
  117. text (string): the input text
  118. idf (Dict): the idf dictionary
  119. w2v (Word2Vec): the word2vec model
  120. Returns:
  121. ndarray: a 300d representation vector
  122. """
  123. if text in cache:
  124. return cache[text]
  125. tokens = simple_preprocess(remove_stopwords(text.lower()))
  126. bigrams = []
  127. for idx in range(len(tokens) - 1):
  128. bigram = tokens[idx] + ' ' + tokens[idx + 1]
  129. if bigram in idf:
  130. bigrams.append(bigram)
  131. ngrams = tokens + bigrams
  132. phrase_vectors = [phrase2vec(phrase, idf, w2v) for phrase in ngrams]
  133. phrase_vector_pairs = [(ngrams[i], phrase_vectors[i]) for i in range(len(ngrams))]
  134. text_vector = sum([np.zeros(300)] + phrase_vectors)
  135. cache[text] = (text_vector, phrase_vector_pairs)
  136. return (text_vector, phrase_vector_pairs)
  137. def get_coverage(summaries, answer_text, answer_ids, phrase_similarity_threshold=0.85, sentence_similarity_threshold=0.5):
  138. """ Compute the coverage of each summary line.
  139. Args:
  140. summaries (List of str): the summary lines
  141. answer_text (List of str): the answers' original text
  142. answer_ids (List of str): the answers' id
  143. Returns:
  144. List of List of str: the answerId that each summary covered
  145. List of List of str: the informative tokens of each line
  146. """
  147. results = []
  148. informative_tokens = []
  149. for summary in summaries:
  150. summary_results = []
  151. summary_informative_tokens = {}
  152. logging.debug('Summary: {}'.format(summary))
  153. for cand_answer_text, aid in zip(answer_text, answer_ids):
  154. summary_vector, summary_phrase_vectors = text2vec(summary, idf, w2v)
  155. cand_answer_vector, cand_answer_phrase_vectors = text2vec(cand_answer_text, idf, w2v)
  156. logging.debug('Answer ID: {}'.format(aid))
  157. logging.debug('Answer : {}'.format(cand_answer_text))
  158. sentence_similarity = cosine_sim(summary_vector, cand_answer_vector)
  159. logging.debug('Sentence Similarity : {}'.format(sentence_similarity))
  160. if sentence_similarity >= sentence_similarity_threshold:
  161. summary_results.append((aid, sentence_similarity))
  162. similar_phrases = find_similar_phrases(summary_phrase_vectors, cand_answer_phrase_vectors, phrase_similarity_threshold=phrase_similarity_threshold)
  163. summary_informative_tokens[aid] = [re.sub('\s+', '_', phrase_score_pair[0]) for phrase_score_pair in similar_phrases]
  164. results.append(summary_results)
  165. informative_tokens.append(summary_informative_tokens)
  166. # def get_tokens(text):
  167. # unigrams = simple_preprocess(text.lower())
  168. # bigrams = [unigrams[i] + '_' + unigrams[i + 1]
  169. # for i in range(len(unigrams) - 1)]
  170. # return [token for token in unigrams + bigrams if token not in stopwords]
  171. #
  172. # all_tokens = [get_tokens(line) for line in summaries]
  173. # informative_tokens = []
  174. # for sid, tokens in enumerate(all_tokens):
  175. # other_tokens = set([])
  176. # for oid, others in enumerate(all_tokens):
  177. # if oid != sid:
  178. # other_tokens |= set(others)
  179. # informative_tokens.append(list(set(tokens) - other_tokens))
  180. #
  181. # results = [[] for _ in summaries]
  182. # for sid, tokens in enumerate(informative_tokens):
  183. # for text, aid in zip(answer_text, answer_ids):
  184. # answer_tokens = get_tokens(text)
  185. # if len(set(tokens) & set(answer_tokens)) > 0:
  186. # results[sid].append(aid)
  187. #
  188. # # clean the informative tokens
  189. # for sid, tokens in enumerate(informative_tokens):
  190. # new_tokens = []
  191. # for token in tokens:
  192. # if len(set(token.split('_')) & stopwords) == 0:
  193. # new_tokens.append(token)
  194. # informative_tokens[sid] = new_tokens
  195. #
  196. # print(results)
  197. # print(informative_tokens)
  198. return results, informative_tokens
  199. def clean_sentence(text):
  200. """ Clean an input sentence
  201. Args:
  202. text (str): the sentence
  203. Returns:
  204. text (str): the cleaned sentence
  205. """
  206. sent = nlp(text)
  207. # clean the first few characters
  208. result = text
  209. for i, token in enumerate(sent):
  210. if token.pos_ not in ['PUNCT', 'X', 'SYM']:
  211. result = sent[i:].text
  212. break
  213. # capitalize the first character
  214. if len(result) > 0:
  215. result = result[0].upper() + result[1:]
  216. return result
  217. def drop_unwanted_sentences(answers):
  218. """ Remove unwanted sentences and concatenate into one string
  219. Args:
  220. answers (list of str): the answers to be cleaned
  221. Returns:
  222. str: the cleaned and concatenated string
  223. """
  224. all_sents = []
  225. for text in answers:
  226. sents = nlp(text, disable=['tagger', 'ner']).sents
  227. for sent in sents:
  228. if len(sent) <= 30:
  229. all_sents.append(sent.text)
  230. return '\n'.join(all_sents)
  231. def do_textrank(question, num_sent=5, num_words=100, phrase_similarity_threshold=0.85, sentence_similarity_threshold=0.5):
  232. """ Perform TextRank to generate the summary items with coverage information
  233. Args:
  234. question (json): question and answers
  235. {
  236. "question_id": "1dsbhnd88nrea800",
  237. "question_text": "I have an interview on Thursday what questions will they ask, if anyone has applied there in San Diego",
  238. "question_code": "",
  239. "question_topics": ["INTERVIEW"],
  240. "company_id": 11180,
  241. "company": "Sam's Club",
  242. "num_answers": 1,
  243. "answers": [{
  244. "answer_id": "1e0rqjv09q45d800",
  245. "answer_date": "2020-02-12T04:30:51.913",
  246. "job_title": "Inventory Control Supervisor",
  247. "job_location": "Princeton, NJ",
  248. "answer_text": "Tell us of the most difficult interaction you had with a customer and how did you positively turn the customer around?",
  249. "votes": []
  250. }]
  251. }
  252. num_sent (int, optional): the maximal number of sentences in the summary
  253. num_words (int, optional): the maximal number of words in the summary
  254. Returns:
  255. Dict: the summary result containing the summary items,
  256. coverage info, and related answers.
  257. """
  258. qid = question['question_id']
  259. question_text = question['question_text']
  260. question_code = question['question_code']
  261. question_topics = question['question_topics']
  262. answers = question['answers']
  263. if len(answers) < num_sent:
  264. return None
  265. answer_dict = {}
  266. for idx in range(len(answers)):
  267. answer = answers[idx]
  268. answer_id = answer['answer_id']
  269. answer_text = answer['answer_text']
  270. answer_dict[answer_id] = answer_text
  271. answer_ids = list(answer_dict.keys())
  272. answer_texts = list(answer_dict.values())
  273. result = {'question_id': qid,
  274. 'question_text': question_text,
  275. 'question_code': question_code,
  276. 'question_topics': question_topics,
  277. 'num_answers': len(answers)}
  278. # print(result)
  279. # input('press any key to continue')
  280. logging.debug("Input:" + str(answer_texts))
  281. full_text = drop_unwanted_sentences(answer_texts)
  282. logging.debug("Text:" + full_text)
  283. ans = summarize(full_text, words=num_words * 2)
  284. summary = []
  285. summary_lines = []
  286. stats = {}
  287. stats['num_summaries'] = 0
  288. stats['num_answers'] = len(answers)
  289. stats['num_supporting_answers'] = 0
  290. stats['num_summaries_with_zero_supporting_answers'] = 0
  291. stats['num_answers_with_zero_matching_tokens'] = 0
  292. for idx, line in enumerate(ans.split('\n')[:num_sent]):
  293. summary_lines.append(clean_sentence(line))
  294. stats['num_summaries'] = len(summary_lines)
  295. coverage, tokens = get_coverage(summary_lines, answer_texts, answer_ids, phrase_similarity_threshold=phrase_similarity_threshold, sentence_similarity_threshold=sentence_similarity_threshold)
  296. for idx, line in enumerate(summary_lines):
  297. support = len(coverage[idx])
  298. stats['num_supporting_answers'] = stats['num_supporting_answers'] + support
  299. if support == 0:
  300. stats['num_summaries_with_zero_supporting_answers'] = stats['num_summaries_with_zero_supporting_answers'] + 1
  301. summary_item = {}
  302. summary_item['text'] = line
  303. summary_item['support'] = support
  304. summary_item['coverage'] = []
  305. for aid, similarity in coverage[idx]:
  306. answer_item = {}
  307. answer_text = answer_dict[aid]
  308. answer_item['answer_id'] = aid
  309. answer_item['similarity'] = similarity
  310. answer_item['answer_text'] = answer_text
  311. summary_item['coverage'].append(answer_item)
  312. # Identify matching tokens
  313. answer_matching_tokens = []
  314. for token in tokens[idx][aid]:
  315. tre = token.lower().replace('_','\s+')
  316. matching_token = {}
  317. matching_token['token'] = token
  318. spans = []
  319. matching_token['spans'] = spans
  320. for m in re.finditer(tre, answer_text.lower()):
  321. span = {}
  322. span['text'] = answer_text[m.start():m.end()]
  323. span['start'] = m.start()
  324. span['end'] = m.end()
  325. spans.append(span)
  326. if len(spans) > 0:
  327. answer_matching_tokens.append(matching_token)
  328. answer_item['matching_tokens'] = answer_matching_tokens
  329. if len(answer_matching_tokens) == 0:
  330. stats['num_answers_with_zero_matching_tokens'] = stats['num_answers_with_zero_matching_tokens'] + 1
  331. # summary_item['tokens'] = tokens[idx]
  332. summary.append(summary_item)
  333. result['summary'] = summary
  334. rouge = Rouge()
  335. scores = rouge.get_scores(ans, full_text)[0]
  336. stats['ROUGE-1'] = scores['rouge-1']['f']
  337. stats['ROUGE-2'] = scores['rouge-2']['f']
  338. stats['ROUGE-L'] = scores['rouge-l']['f']
  339. result['stats'] = stats
  340. logging.debug(result)
  341. return result
  342. def find_questions(keywords, topics, qids):
  343. c = questions['content'].str.contains('')
  344. if len(keywords) > 0:
  345. ck = questions['content'].str.contains('')
  346. for keyword in keywords:
  347. ck = ck & questions['content'].str.contains(keyword)
  348. c = c & ck
  349. if len(topics) > 0:
  350. ct = questions['topics'].str.contains(topics[0]) | questions['questionCode'].str.contains(topics[0])
  351. for topic in topics[1:]:
  352. ct = ct | ( questions['topics'].str.contains(topic) | questions['questionCode'].str.contains(topic) )
  353. c = c & ct
  354. if len(qids) > 0:
  355. qt = questions['questionId'].str.contains('')
  356. for qid in qids:
  357. qt = qt & questions['questionId'].str.contains(qid)
  358. c = c & qt
  359. return questions[c]
  360. def write_json_to_file(data, file_name):
  361. with open(file_name, 'w') as fo:
  362. json.dump(data, fo, cls=NpEncoder)
  363. def summarize_with_textrank(path,
  364. num_sent=5,
  365. num_words=100,
  366. phrase_similarity_threshold=0.725,
  367. sentence_similarity_threshold=0.65):
  368. results = []
  369. stats = {}
  370. stats['question_count'] = 0
  371. stats['summarized_question_count'] = 0
  372. stats['total_num_summaries'] = 0
  373. stats['total_num_answers'] = 0
  374. stats['total_num_supporting_answers'] = 0
  375. stats['total_num_summaries_with_zero_supporting_answers'] = 0
  376. stats['total_num_answers_with_zero_matching_tokens'] = 0
  377. stats['avg_ROUGE-1'] = 0
  378. stats['avg_ROUGE-2'] = 0
  379. stats['avg_ROUGE-L'] = 0
  380. for filename in os.listdir(path):
  381. filepath = os.path.join(path, filename)
  382. with open(filepath) as json_file:
  383. try:
  384. question = json.load(json_file)
  385. except Exception as ee:
  386. continue
  387. qid = question['question_id']
  388. if stats['question_count'] % 100 == 0:
  389. logging.info("Processed {} questions summarized {}".format(stats['question_count'],stats['summarized_question_count']))
  390. stats['question_count'] = stats['question_count'] + 1
  391. try:
  392. result = do_textrank(question, num_sent, num_words, phrase_similarity_threshold=phrase_similarity_threshold, sentence_similarity_threshold=sentence_similarity_threshold)
  393. if result != None:
  394. stats['avg_ROUGE-1'] = ( stats['avg_ROUGE-1'] * stats['summarized_question_count'] + result['stats']['ROUGE-1'] ) / ( stats['summarized_question_count'] + 1)
  395. stats['avg_ROUGE-2'] = ( stats['avg_ROUGE-2'] * stats['summarized_question_count'] + result['stats']['ROUGE-2'] ) / ( stats['summarized_question_count'] + 1)
  396. stats['avg_ROUGE-L'] = ( stats['avg_ROUGE-L'] * stats['summarized_question_count'] + result['stats']['ROUGE-L'] ) / ( stats['summarized_question_count'] + 1)
  397. stats['summarized_question_count'] = stats['summarized_question_count'] + 1
  398. stats['total_num_summaries'] = stats['total_num_summaries'] + result['stats']['num_summaries']
  399. stats['total_num_answers'] = stats['total_num_answers'] + result['stats']['num_answers']
  400. stats['total_num_supporting_answers'] = stats['total_num_supporting_answers'] + result['stats']['num_supporting_answers']
  401. stats['total_num_summaries_with_zero_supporting_answers'] = stats['total_num_summaries_with_zero_supporting_answers'] + result['stats']['num_summaries_with_zero_supporting_answers']
  402. stats['total_num_answers_with_zero_matching_tokens'] = stats['total_num_answers_with_zero_matching_tokens'] + result['stats']['num_answers_with_zero_matching_tokens']
  403. results.append(result)
  404. write_json_to_file(result, "output/" + qid + ".json")
  405. else:
  406. continue
  407. # write_json_to_file({"message": "no summary created"}, "../data/output/" + qid + ".json")
  408. except Exception as exception:
  409. traceback.print_exc()
  410. logging.error("Exception on question: " + qid)
  411. logging.info("Final statistics {}".format(stats))
  412. if __name__ == '__main__':
  413. # python run_textrank.py --keywords interview,precefiss --num_sentences 5 --num_words 100
  414. parser = argparse.ArgumentParser()
  415. parser.add_argument("--num_sentences", type=int, default=5)
  416. parser.add_argument("--num_words", type=int, default=100)
  417. parser.add_argument("--phrase_similarity_threshold", type=float, default=0.85)
  418. parser.add_argument("--sentence_similarity_threshold", type=float, default=0.5)
  419. parser.add_argument("--log", type=str, default=None)
  420. hp = parser.parse_args()
  421. # Initialize logging
  422. logging_level = logging.INFO if hp.log is None else hp.log.upper()
  423. logging.basicConfig(format='%(levelname)s:%(message)s', level=logging_level)
  424. # build idf and w2v models if necessary
  425. if os.path.exists('models/idf.json') and os.path.exists('models/indeed_qa.model'):
  426. idf = json.load(open('models/idf.json'))
  427. w2v = Word2Vec.load('models/indeed_qa.model')
  428. else:
  429. idf, w2v = build_vectorizer('data')
  430. json.dump(idf, open('models/idf.json', 'w'))
  431. w2v.save('models/indeed_qa.model')
  432. # summarize
  433. summarize_with_textrank('data',
  434. num_sent=hp.num_sentences,
  435. num_words=hp.num_words,
  436. phrase_similarity_threshold=hp.phrase_similarity_threshold,
  437. sentence_similarity_threshold=hp.sentence_similarity_threshold)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...