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_ver2.py 19 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
  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 dagshub
  11. import traceback
  12. from summa.summarizer import summarize
  13. from gensim.models import Word2Vec
  14. from gensim.utils import simple_preprocess
  15. from gensim.parsing.preprocessing import remove_stopwords
  16. from rouge import Rouge
  17. from nltk.corpus import stopwords
  18. from sklearn.feature_extraction.text import TfidfVectorizer
  19. stopwords = set(stopwords.words('english'))
  20. nlp = spacy.load('en_core_web_sm')
  21. cache = {}
  22. class NpEncoder(json.JSONEncoder):
  23. def default(self, obj):
  24. if isinstance(obj, np.integer):
  25. return int(obj)
  26. elif isinstance(obj, np.floating):
  27. return float(obj)
  28. elif isinstance(obj, np.ndarray):
  29. return obj.tolist()
  30. else:
  31. return super(NpEncoder, self).default(obj)
  32. def build_vectorizer(path):
  33. """Create the idf, bigram indices and train the word2vec model
  34. Args:
  35. path (string): the path to the directory that contains
  36. 'questions.csv' and 'answers.csv'
  37. Returns:
  38. Dict: a dictionary whose keys are the unigrams and bigrams
  39. (>=2 occurrence); the values are the idf scores
  40. Word2Vec: the trained gensim Word2Vec model
  41. """
  42. # questions
  43. corpus = []
  44. for fn in ['questions.csv', 'answers.csv']:
  45. fn = os.path.join(path, fn)
  46. with open(fn) as fin:
  47. reader = csv.DictReader(fin)
  48. for row in reader:
  49. content = row['content']
  50. if content is None:
  51. continue
  52. corpus.append(content)
  53. # train w2v
  54. model = Word2Vec([simple_preprocess(text.lower()) for text in corpus],
  55. size=300, window=10)
  56. # find bigrams, idf
  57. vectorizer = TfidfVectorizer(ngram_range=(1,2), min_df=2, stop_words='english')
  58. vectorizer.fit(corpus)
  59. vocab = vectorizer.vocabulary_
  60. idf = vectorizer.idf_
  61. idf_dict = dict([(word, idf[vocab[word]]) for word in vocab])
  62. return idf_dict, model
  63. def find_similar_phrases(phrase_vectors_a, phrase_vectors_b, phrase_similarity_threshold=0.85):
  64. """Return similar phrases
  65. """
  66. similar_phrases = {}
  67. for word_vector_pair_a in phrase_vectors_a:
  68. word_a, pv_a = word_vector_pair_a
  69. for word_vector_pair_b in phrase_vectors_b:
  70. word_b, pv_b = word_vector_pair_b
  71. cs = cosine_sim(pv_a, pv_b)
  72. if cs > phrase_similarity_threshold:
  73. if word_b in similar_phrases:
  74. cs_old = similar_phrases[word_b]
  75. if cs > cs_old:
  76. similar_phrases[word_b] = cs
  77. else:
  78. similar_phrases[word_b] = cs
  79. return [(w,similar_phrases[w]) for w in similar_phrases]
  80. def cosine_sim(veca, vecb):
  81. """Cosine similarity of two vectors
  82. """
  83. lena = np.linalg.norm(veca)
  84. lenb = np.linalg.norm(vecb)
  85. if lena < 1e-6 or lenb < 1e-6:
  86. return 0.0
  87. else:
  88. return np.dot(veca, vecb) / lena / lenb
  89. def phrase2vec(phrase, idf, w2v):
  90. """Compute the vector representation of a phrase.
  91. Sum of word vectors weighted by their idf's
  92. Args:
  93. phrase (string): the input phrase (space separated)
  94. idf (Dict): the idf dictionary
  95. w2v (Word2Vec): the word2vec model
  96. Returns:
  97. ndarray: a 300d representation vector
  98. """
  99. global cache
  100. phrase = phrase.lower()
  101. if phrase in cache:
  102. return cache[phrase]
  103. result = np.zeros(300)
  104. for token in phrase.split(' '):
  105. if token in w2v.wv and token in idf:
  106. result += w2v.wv[token] * idf[token]
  107. return result
  108. def text2vec(text, idf, w2v):
  109. """Compute the vector representation of a paragraph.
  110. Sum of the unigrams and bigrams' phrase vectors. Preprocess
  111. with gensim.utils.simple_preprocess (dropping puncts)
  112. Args:
  113. text (string): the input text
  114. idf (Dict): the idf dictionary
  115. w2v (Word2Vec): the word2vec model
  116. Returns:
  117. ndarray: a 300d representation vector
  118. """
  119. if text in cache:
  120. return cache[text]
  121. tokens = simple_preprocess(remove_stopwords(text.lower()))
  122. ngrams = tokens
  123. phrase_vectors = [phrase2vec(phrase, idf, w2v) for phrase in ngrams]
  124. phrase_vector_pairs = [(ngrams[i], phrase_vectors[i]) for i in range(len(ngrams))]
  125. text_vector = sum([np.zeros(300)] + phrase_vectors)
  126. cache[text] = (text_vector, phrase_vector_pairs)
  127. return (text_vector, phrase_vector_pairs)
  128. def get_coverage(summaries, answer_text, answer_ids, phrase_similarity_threshold=0.85, sentence_similarity_threshold=0.5):
  129. """ Compute the coverage of each summary line.
  130. Args:
  131. summaries (List of str): the summary lines
  132. answer_text (List of str): the answers' original text
  133. answer_ids (List of str): the answers' id
  134. Returns:
  135. List of List of str: the answerId that each summary covered
  136. List of List of str: the informative tokens of each line
  137. """
  138. results = []
  139. informative_tokens = []
  140. for summary in summaries:
  141. summary_results = []
  142. summary_informative_tokens = {}
  143. logging.debug('Summary: {}'.format(summary))
  144. for cand_answer_text, aid in zip(answer_text, answer_ids):
  145. summary_vector, summary_phrase_vectors = text2vec(summary, idf, w2v)
  146. cand_answer_vector, cand_answer_phrase_vectors = text2vec(cand_answer_text, idf, w2v)
  147. logging.debug('Answer ID: {}'.format(aid))
  148. logging.debug('Answer : {}'.format(cand_answer_text))
  149. sentence_similarity = cosine_sim(summary_vector, cand_answer_vector)
  150. logging.debug('Sentence Similarity : {}'.format(sentence_similarity))
  151. if sentence_similarity >= sentence_similarity_threshold:
  152. summary_results.append((aid, sentence_similarity))
  153. similar_phrases = find_similar_phrases(summary_phrase_vectors, cand_answer_phrase_vectors, phrase_similarity_threshold=phrase_similarity_threshold)
  154. summary_informative_tokens[aid] = [re.sub('\s+', '_', phrase_score_pair[0]) for phrase_score_pair in similar_phrases]
  155. results.append(summary_results)
  156. informative_tokens.append(summary_informative_tokens)
  157. # def get_tokens(text):
  158. # unigrams = simple_preprocess(text.lower())
  159. # bigrams = [unigrams[i] + '_' + unigrams[i + 1]
  160. # for i in range(len(unigrams) - 1)]
  161. # return [token for token in unigrams + bigrams if token not in stopwords]
  162. #
  163. # all_tokens = [get_tokens(line) for line in summaries]
  164. # informative_tokens = []
  165. # for sid, tokens in enumerate(all_tokens):
  166. # other_tokens = set([])
  167. # for oid, others in enumerate(all_tokens):
  168. # if oid != sid:
  169. # other_tokens |= set(others)
  170. # informative_tokens.append(list(set(tokens) - other_tokens))
  171. #
  172. # results = [[] for _ in summaries]
  173. # for sid, tokens in enumerate(informative_tokens):
  174. # for text, aid in zip(answer_text, answer_ids):
  175. # answer_tokens = get_tokens(text)
  176. # if len(set(tokens) & set(answer_tokens)) > 0:
  177. # results[sid].append(aid)
  178. #
  179. # # clean the informative tokens
  180. # for sid, tokens in enumerate(informative_tokens):
  181. # new_tokens = []
  182. # for token in tokens:
  183. # if len(set(token.split('_')) & stopwords) == 0:
  184. # new_tokens.append(token)
  185. # informative_tokens[sid] = new_tokens
  186. #
  187. # print(results)
  188. # print(informative_tokens)
  189. return results, informative_tokens
  190. def clean_sentence(text):
  191. """ Clean an input sentence
  192. Args:
  193. text (str): the sentence
  194. Returns:
  195. text (str): the cleaned sentence
  196. """
  197. sent = nlp(text)
  198. # clean the first few characters
  199. result = text
  200. for i, token in enumerate(sent):
  201. if token.pos_ not in ['PUNCT', 'X', 'SYM']:
  202. result = sent[i:].text
  203. break
  204. # capitalize the first character
  205. if len(result) > 0:
  206. result = result[0].upper() + result[1:]
  207. return result
  208. def drop_unwanted_sentences(answers):
  209. """ Remove unwanted sentences and concatenate into one string
  210. Args:
  211. answers (list of str): the answers to be cleaned
  212. Returns:
  213. str: the cleaned and concatenated string
  214. """
  215. all_sents = []
  216. for text in answers:
  217. sents = nlp(text, disable=['tagger', 'ner']).sents
  218. for sent in sents:
  219. if len(sent) <= 30:
  220. all_sents.append(sent.text)
  221. return '\n'.join(all_sents)
  222. def do_textrank(qid, num_sent=5, num_words=100, phrase_similarity_threshold=0.85, sentence_similarity_threshold=0.5):
  223. """ Perform TextRank to generate the summary items with coverage information
  224. Args:
  225. qid (str): the question_id to be summarized
  226. num_sent (int, optional): the maximal number of sentences in the summary
  227. num_words (int, optional): the maximal number of words in the summary
  228. Returns:
  229. Dict: the summary result containing the summary items,
  230. coverage info, and related answers.
  231. """
  232. answers = df.loc[df['questionId'] == qid]
  233. if len(answers) <= num_sent:
  234. return None
  235. company_id = answers['fccompanyId'].iloc[0]
  236. company_name = answers['companyName'].iloc[0].strip()
  237. answer_ids = list(answers['answerId'])
  238. answer_text = list(answers['content_answer'])
  239. answer_dict = dict(zip(answer_ids, answer_text))
  240. question_text = answers['content_question'].iloc[0]
  241. question_code = answers['questionCode'].iloc[0]
  242. if answers['questionCode'].isna().iloc[0]:
  243. question_code = ''
  244. question_topics = answers['topics'].iloc[0]
  245. result = {'question_id': qid,
  246. 'question_text': question_text,
  247. 'question_code': question_code,
  248. 'question_topics': question_topics,
  249. 'company_id': company_id,
  250. 'company': company_name,
  251. 'num_answers': len(answers)}
  252. # print(result)
  253. # input('press any key to continue')
  254. logging.debug("Input:" + str(answer_text))
  255. full_text = drop_unwanted_sentences(answer_text)
  256. logging.debug("Text:" + full_text)
  257. ans = summarize(full_text, words=num_words * 2)
  258. summary = []
  259. summary_lines = []
  260. stats = {}
  261. stats['num_summaries'] = 0
  262. stats['num_answers'] = len(answers)
  263. stats['num_supporting_answers'] = 0
  264. stats['num_summaries_with_zero_supporting_answers'] = 0
  265. stats['num_answers_with_zero_matching_tokens'] = 0
  266. for idx, line in enumerate(ans.split('\n')[:num_sent]):
  267. summary_lines.append(clean_sentence(line))
  268. stats['num_summaries'] = len(summary_lines)
  269. coverage, tokens = get_coverage(summary_lines, answer_text, answer_ids, phrase_similarity_threshold=phrase_similarity_threshold, sentence_similarity_threshold=sentence_similarity_threshold)
  270. for idx, line in enumerate(summary_lines):
  271. support = len(coverage[idx])
  272. stats['num_supporting_answers'] = stats['num_supporting_answers'] + support
  273. if support == 0:
  274. stats['num_summaries_with_zero_supporting_answers'] = stats['num_summaries_with_zero_supporting_answers'] + 1
  275. summary_item = {}
  276. summary_item['text'] = line
  277. summary_item['support'] = support
  278. summary_item['coverage'] = []
  279. for aid, similarity in coverage[idx]:
  280. answer_item = {}
  281. answer_text = answer_dict[aid]
  282. answer_item['answer_id'] = aid
  283. answer_item['similarity'] = similarity
  284. answer_item['answer_text'] = answer_text
  285. summary_item['coverage'].append(answer_item)
  286. # Identify matching tokens
  287. answer_matching_tokens = []
  288. for token in tokens[idx][aid]:
  289. tre = token.lower().replace('_','\s+')
  290. matching_token = {}
  291. matching_token['token'] = token
  292. spans = []
  293. matching_token['spans'] = spans
  294. for m in re.finditer(tre, answer_text.lower()):
  295. span = {}
  296. span['text'] = answer_text[m.start():m.end()]
  297. span['start'] = m.start()
  298. span['end'] = m.end()
  299. spans.append(span)
  300. if len(spans) > 0:
  301. answer_matching_tokens.append(matching_token)
  302. answer_item['matching_tokens'] = answer_matching_tokens
  303. if len(answer_matching_tokens) == 0:
  304. stats['num_answers_with_zero_matching_tokens'] = stats['num_answers_with_zero_matching_tokens'] + 1
  305. # summary_item['tokens'] = tokens[idx]
  306. summary.append(summary_item)
  307. result['summary'] = summary
  308. rouge = Rouge()
  309. scores = rouge.get_scores(ans, full_text)[0]
  310. stats['ROUGE-1'] = scores['rouge-1']['f']
  311. stats['ROUGE-2'] = scores['rouge-2']['f']
  312. stats['ROUGE-L'] = scores['rouge-l']['f']
  313. result['stats'] = stats
  314. logging.debug(result)
  315. return result
  316. def find_questions(keywords, topics, qids):
  317. c = questions['content'].str.contains('')
  318. if len(keywords) > 0:
  319. ck = questions['content'].str.contains('')
  320. for keyword in keywords:
  321. ck = ck & questions['content'].str.contains(keyword)
  322. c = c & ck
  323. if len(topics) > 0:
  324. ct = questions['topics'].str.contains(topics[0]) | questions['questionCode'].str.contains(topics[0])
  325. for topic in topics[1:]:
  326. ct = ct | ( questions['topics'].str.contains(topic) | questions['questionCode'].str.contains(topic) )
  327. c = c & ct
  328. if len(qids) > 0:
  329. qt = questions['questionId'].str.contains('')
  330. for qid in qids:
  331. qt = qt & questions['questionId'].str.contains(qid)
  332. c = c & qt
  333. return questions[c]
  334. def write_json_to_file(data, file_name):
  335. with open(file_name, 'w') as fo:
  336. json.dump(data, fo, cls=NpEncoder)
  337. def summarize_with_textrank(questions,
  338. num_sent=5,
  339. num_words=100,
  340. phrase_similarity_threshold=0.725,
  341. sentence_similarity_threshold=0.65):
  342. results = []
  343. stats = {}
  344. stats['question_count'] = 0
  345. stats['summarized_question_count'] = 0
  346. stats['total_num_summaries'] = 0
  347. stats['total_num_answers'] = 0
  348. stats['total_num_supporting_answers'] = 0
  349. stats['total_num_summaries_with_zero_supporting_answers'] = 0
  350. stats['total_num_answers_with_zero_matching_tokens'] = 0
  351. stats['avg_ROUGE-1'] = 0
  352. stats['avg_ROUGE-2'] = 0
  353. stats['avg_ROUGE-L'] = 0
  354. for qid in questions['questionId']:
  355. if stats['question_count'] % 100 == 0:
  356. logging.info("Processed {} questions summarized {}".format(stats['question_count'],stats['summarized_question_count']))
  357. stats['question_count'] = stats['question_count'] + 1
  358. try:
  359. result = do_textrank(qid, num_sent, num_words, phrase_similarity_threshold=phrase_similarity_threshold, sentence_similarity_threshold=sentence_similarity_threshold)
  360. if result != None:
  361. stats['avg_ROUGE-1'] = ( stats['avg_ROUGE-1'] * stats['summarized_question_count'] + result['stats']['ROUGE-1'] ) / ( stats['summarized_question_count'] + 1)
  362. stats['avg_ROUGE-2'] = ( stats['avg_ROUGE-2'] * stats['summarized_question_count'] + result['stats']['ROUGE-2'] ) / ( stats['summarized_question_count'] + 1)
  363. stats['avg_ROUGE-L'] = ( stats['avg_ROUGE-L'] * stats['summarized_question_count'] + result['stats']['ROUGE-L'] ) / ( stats['summarized_question_count'] + 1)
  364. stats['summarized_question_count'] = stats['summarized_question_count'] + 1
  365. stats['total_num_summaries'] = stats['total_num_summaries'] + result['stats']['num_summaries']
  366. stats['total_num_answers'] = stats['total_num_answers'] + result['stats']['num_answers']
  367. stats['total_num_supporting_answers'] = stats['total_num_supporting_answers'] + result['stats']['num_supporting_answers']
  368. stats['total_num_summaries_with_zero_supporting_answers'] = stats['total_num_summaries_with_zero_supporting_answers'] + result['stats']['num_summaries_with_zero_supporting_answers']
  369. stats['total_num_answers_with_zero_matching_tokens'] = stats['total_num_answers_with_zero_matching_tokens'] + result['stats']['num_answers_with_zero_matching_tokens']
  370. results.append(result)
  371. logger.log_metrics(stats)
  372. write_json_to_file(result, "{}/output/".format(data_loc) + qid + ".json")
  373. else:
  374. continue
  375. # write_json_to_file({"message": "no summary created"}, "../data/output/" + qid + ".json")
  376. except Exception as exception:
  377. traceback.print_exc()
  378. logging.error("Exception on question: " + qid)
  379. logging.info("Final statistics {}".format(stats))
  380. if __name__ == '__main__':
  381. # python run_textrank.py --keywords interview,precefiss --num_sentences 5 --num_words 100
  382. parser = argparse.ArgumentParser()
  383. parser.add_argument("--keywords", type=str, default=None)
  384. parser.add_argument("--num_sentences", type=int, default=5)
  385. parser.add_argument("--num_words", type=int, default=100)
  386. parser.add_argument("--topics", type=str, default=None)
  387. parser.add_argument("--questions", type=str, default=None)
  388. parser.add_argument("--phrase_similarity_threshold", type=float, default=0.85)
  389. parser.add_argument("--sentence_similarity_threshold", type=float, default=0.5)
  390. parser.add_argument("--log", type=str, default=None)
  391. hp = parser.parse_args()
  392. # Initialize logging
  393. logging_level = logging.INFO if hp.log is None else hp.log.upper()
  394. logging.basicConfig(format='%(levelname)s:%(message)s', level=logging_level)
  395. # read csv into dataframes
  396. data_loc = 'data_v2'
  397. questions = pd.read_csv('{}/questions.csv'.format(data_loc), warn_bad_lines=True, error_bad_lines=False, verbose=True)
  398. answers = pd.read_csv('{}/answers.csv'.format(data_loc), warn_bad_lines=True, error_bad_lines=False, verbose=True)
  399. companies = pd.read_csv('{}/fccid-companyName.csv'.format(data_loc), warn_bad_lines=True, error_bad_lines=False, verbose=True)
  400. df = pd.merge(answers, questions, on='questionId'.format(data_loc), suffixes=('_answer','_question'))
  401. df = pd.merge(df, companies, on='fccompanyId')
  402. # filter questions based on keywords, topics, and/or quesstion ids
  403. keywords = [] if hp.keywords is None else hp.keywords.split(',')
  404. topics = [] if hp.topics is None else hp.topics.split(',')
  405. qids = [] if hp.questions is None else hp.questions.split(',')
  406. filtered_questions = find_questions(keywords, topics, qids)
  407. # build idf and w2v models if necessary
  408. if os.path.exists('models/idf.json') and os.path.exists('models/indeed_qa.model'):
  409. idf = json.load(open('models/idf.json'))
  410. w2v = Word2Vec.load('models/indeed_qa.model')
  411. else:
  412. idf, w2v = build_vectorizer('data')
  413. json.dump(idf, open('models/idf.json', 'w'))
  414. w2v.save('models/indeed_qa.model')
  415. params_log = vars(hp)
  416. params_log['ver'] = 'ver2'
  417. with dagshub.dagshub_logger() as logger:
  418. logger.log_hyperparams(params_log)
  419. # summarize
  420. summarize_with_textrank(filtered_questions,
  421. num_sent=hp.num_sentences,
  422. num_words=hp.num_words,
  423. phrase_similarity_threshold=hp.phrase_similarity_threshold,
  424. 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...