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_ver1.py 8.9 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
  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. import dagshub
  12. from summa.summarizer import summarize
  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. stopwords = set(stopwords.words('english'))
  18. nlp = spacy.load('en_core_web_sm')
  19. cache = {}
  20. class NpEncoder(json.JSONEncoder):
  21. def default(self, obj):
  22. if isinstance(obj, np.integer):
  23. return int(obj)
  24. elif isinstance(obj, np.floating):
  25. return float(obj)
  26. elif isinstance(obj, np.ndarray):
  27. return obj.tolist()
  28. else:
  29. return super(NpEncoder, self).default(obj)
  30. def clean_sentence(text):
  31. """ Clean an input sentence
  32. Args:
  33. text (str): the sentence
  34. Returns:
  35. text (str): the cleaned sentence
  36. """
  37. sent = nlp(text)
  38. # clean the first few characters
  39. result = text
  40. for i, token in enumerate(sent):
  41. if token.pos_ not in ['PUNCT', 'X', 'SYM']:
  42. result = sent[i:].text
  43. break
  44. # capitalize the first character
  45. if len(result) > 0:
  46. result = result[0].upper() + result[1:]
  47. return result
  48. def drop_unwanted_sentences(answers):
  49. """ Remove unwanted sentences and concatenate into one string
  50. Args:
  51. answers (list of str): the answers to be cleaned
  52. Returns:
  53. str: the cleaned and concatenated string
  54. """
  55. all_sents = []
  56. for text in answers:
  57. sents = nlp(text, disable=['tagger', 'ner']).sents
  58. for sent in sents:
  59. if len(sent) <= 30:
  60. all_sents.append(sent.text)
  61. return '\n'.join(all_sents)
  62. def do_textrank(qid, num_sent=5, num_words=100):
  63. """ Perform TextRank to generate the summary items with coverage information
  64. Args:
  65. qid (str): the question_id to be summarized
  66. num_sent (int, optional): the maximal number of sentences in the summary
  67. num_words (int, optional): the maximal number of words in the summary
  68. Returns:
  69. Dict: the summary result containing the summary items,
  70. coverage info, and related answers.
  71. """
  72. answers = df.loc[df['questionId'] == qid]
  73. if len(answers) <= num_sent:
  74. return None
  75. company_id = answers['fccompanyId'].iloc[0]
  76. company_name = answers['companyName'].iloc[0].strip()
  77. answer_ids = list(answers['answerId'])
  78. answer_text = list(answers['content_answer'])
  79. answer_dict = dict(zip(answer_ids, answer_text))
  80. question_text = answers['content_question'].iloc[0]
  81. question_code = answers['questionCode'].iloc[0]
  82. if answers['questionCode'].isna().iloc[0]:
  83. question_code = ''
  84. question_topics = answers['topics'].iloc[0]
  85. result = {'question_id': qid,
  86. 'question_text': question_text,
  87. 'question_code': question_code,
  88. 'question_topics': question_topics,
  89. 'company_id': company_id,
  90. 'company': company_name,
  91. 'num_answers': len(answers)}
  92. # print(result)
  93. # input('press any key to continue')
  94. logging.debug("Input:" + str(answer_text))
  95. full_text = drop_unwanted_sentences(answer_text)
  96. logging.debug("Text:" + full_text)
  97. ans = summarize(full_text, words=num_words * 2)
  98. summary = []
  99. summary_lines = []
  100. stats = {}
  101. stats['num_summaries'] = 0
  102. stats['num_answers'] = len(answers)
  103. for idx, line in enumerate(ans.split('\n')[:num_sent]):
  104. summary_lines.append(clean_sentence(line))
  105. stats['num_summaries'] = len(summary_lines)
  106. for idx, line in enumerate(summary_lines):
  107. summary_item = {}
  108. summary_item['text'] = line
  109. summary.append(summary_item)
  110. result['summary'] = summary
  111. rouge = Rouge()
  112. scores = rouge.get_scores(ans, full_text)[0]
  113. stats['ROUGE-1'] = scores['rouge-1']['f']
  114. stats['ROUGE-2'] = scores['rouge-2']['f']
  115. stats['ROUGE-L'] = scores['rouge-l']['f']
  116. result['stats'] = stats
  117. logging.debug(result)
  118. return result
  119. def find_questions(keywords, topics, qids):
  120. c = questions['content'].str.contains('')
  121. if len(keywords) > 0:
  122. ck = questions['content'].str.contains('')
  123. for keyword in keywords:
  124. ck = ck & questions['content'].str.contains(keyword)
  125. c = c & ck
  126. if len(topics) > 0:
  127. ct = questions['topics'].str.contains(topics[0]) | questions['questionCode'].str.contains(topics[0])
  128. for topic in topics[1:]:
  129. ct = ct | ( questions['topics'].str.contains(topic) | questions['questionCode'].str.contains(topic) )
  130. c = c & ct
  131. if len(qids) > 0:
  132. qt = questions['questionId'].str.contains('')
  133. for qid in qids:
  134. qt = qt & questions['questionId'].str.contains(qid)
  135. c = c & qt
  136. return questions[c]
  137. def write_json_to_file(data, file_name):
  138. with open(file_name, 'w') as fo:
  139. json.dump(data, fo, cls=NpEncoder)
  140. def summarize_with_textrank(questions,
  141. num_sent=5,
  142. num_words=100):
  143. results = []
  144. stats = {}
  145. stats['question_count'] = 0
  146. stats['summarized_question_count'] = 0
  147. stats['total_num_summaries'] = 0
  148. stats['total_num_answers'] = 0
  149. stats['avg_ROUGE-1'] = 0
  150. stats['avg_ROUGE-2'] = 0
  151. stats['avg_ROUGE-L'] = 0
  152. for qid in questions['questionId']:
  153. if stats['question_count'] % 100 == 0:
  154. logging.info("Processed {} questions summarized {}".format(stats['question_count'],stats['summarized_question_count']))
  155. stats['question_count'] = stats['question_count'] + 1
  156. try:
  157. result = do_textrank(qid, num_sent, num_words)
  158. if result != None:
  159. stats['avg_ROUGE-1'] = ( stats['avg_ROUGE-1'] * stats['summarized_question_count'] + result['stats']['ROUGE-1'] ) / ( stats['summarized_question_count'] + 1)
  160. stats['avg_ROUGE-2'] = ( stats['avg_ROUGE-2'] * stats['summarized_question_count'] + result['stats']['ROUGE-2'] ) / ( stats['summarized_question_count'] + 1)
  161. stats['avg_ROUGE-L'] = ( stats['avg_ROUGE-L'] * stats['summarized_question_count'] + result['stats']['ROUGE-L'] ) / ( stats['summarized_question_count'] + 1)
  162. stats['summarized_question_count'] = stats['summarized_question_count'] + 1
  163. stats['total_num_summaries'] = stats['total_num_summaries'] + result['stats']['num_summaries']
  164. stats['total_num_answers'] = stats['total_num_answers'] + result['stats']['num_answers']
  165. results.append(result)
  166. #with dagshub.dagshub_logger() as logger:
  167. logger.log_metrics(stats)
  168. write_json_to_file(result, "data/output/" + qid + ".json")
  169. else:
  170. continue
  171. # write_json_to_file({"message": "no summary created"}, "../data/output/" + qid + ".json")
  172. except Exception as exception:
  173. traceback.print_exc()
  174. logging.error("Exception on question: " + qid)
  175. logging.info("Final statistics {}".format(stats))
  176. if __name__ == '__main__':
  177. # python run_textrank.py --keywords interview,precefiss --num_sentences 5 --num_words 100
  178. parser = argparse.ArgumentParser()
  179. parser.add_argument("--keywords", type=str, default=None)
  180. parser.add_argument("--num_sentences", type=int, default=5)
  181. parser.add_argument("--num_words", type=int, default=100)
  182. parser.add_argument("--topics", type=str, default=None)
  183. parser.add_argument("--questions", type=str, default=None)
  184. parser.add_argument("--log", type=str, default=None)
  185. hp = parser.parse_args()
  186. # Initialize logging
  187. logging_level = logging.INFO if hp.log is None else hp.log.upper()
  188. logging.basicConfig(format='%(levelname)s:%(message)s', level=logging_level)
  189. # read csv into dataframes
  190. questions = pd.read_csv('data/questions.csv', warn_bad_lines=True, error_bad_lines=False, verbose=True)
  191. answers = pd.read_csv('data/answers.csv', warn_bad_lines=True, error_bad_lines=False, verbose=True)
  192. companies = pd.read_csv('data/fccid-companyName.csv', warn_bad_lines=True, error_bad_lines=False, verbose=True)
  193. df = pd.merge(answers, questions, on='questionId', suffixes=('_answer','_question'))
  194. df = pd.merge(df, companies, on='fccompanyId')
  195. # filter questions based on keywords, topics, and/or quesstion ids
  196. keywords = [] if hp.keywords is None else hp.keywords.split(',')
  197. topics = [] if hp.topics is None else hp.topics.split(',')
  198. qids = [] if hp.questions is None else hp.questions.split(',')
  199. filtered_questions = find_questions(keywords, topics, qids)
  200. print(vars(hp))
  201. with dagshub.dagshub_logger() as logger:
  202. logger.log_hyperparams(vars(hp))
  203. # summarize
  204. summarize_with_textrank(filtered_questions,
  205. num_sent=hp.num_sentences,
  206. num_words=hp.num_words)
Tip!

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

Comments

Loading...