-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathabs_sent.py
193 lines (163 loc) · 5.46 KB
/
abs_sent.py
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
import re
import json
import spacy
import neuralcoref
import pandas as pd
from spacy.matcher import Matcher
from itertools import groupby
class BaseMerger():
def __init__(self, nlp, ent_type, pos='X'):
self.matcher = Matcher(nlp.vocab)
self.ent_type = ent_type
self.pos = pos
def __call__(self, doc):
matches = self.matcher(doc)
spans = []
for match_id, start, end in matches:
spans.append(doc[start:end])
with doc.retokenize() as retokenizer:
for span in spans:
span[0].ent_type_ = self.ent_type
span[0].pos_ = self.pos
try:
retokenizer.merge(span)
except:
print('--not mergining token')
return doc
class NumberComparisonMerger(BaseMerger):
def __init__(self, nlp):
super().__init__(nlp, ent_type='CARDINAL_COMPARISON')
self.matcher.add('XY', None, [{'IS_DIGIT': True},{'LOWER': '-'},{'IS_DIGIT': True}])
for preposition in ['for', 'to', 'by', 'in']:
pattern = [{'IS_DIGIT': True},{'LOWER': '-'},{'LOWER': preposition},{'LOWER': '-'},{'IS_DIGIT': True}]
self.matcher.add(f'X{preposition}Y', None, pattern)
class ShotBreakdownMerger(BaseMerger):
def __init__(self, nlp):
super().__init__(nlp, ent_type='SHOT_BREAKDOWN')
self.matcher.add('SHOT-BREAKDOWN', None, [{'ORTH': 'ShotBreakdown'}])
class TreeExtracter:
# Nodes matching this NER/PoS will be 'abstracted' (replace with tag-label)
special_ents = {
'DATE': set(['SYM', 'NUM', 'PROPN']),
'TIME': set(['SYM', 'NUM', 'PROPN']),
'PERCENT': set(['SYM', 'NUM', 'PROPN']),
'MONEY': set(['SYM', 'NUM', 'PROPN']),
'ORDINAL': set(['SYM', 'NUM', 'PROPN']),
'CARDINAL': set(['SYM', 'NUM', 'PROPN']),
'PERSON': set(['PROPN']),
'NORP': set(['PROPN']),
'FAC': set(['PROPN']),
'ORG': set(['PROPN']),
'GPE': set(['PROPN']),
'LOC': set(['PROPN']),
'PRODUCT': set(['PROPN']),
'EVENT': set(['PROPN']),
'WORK_OF_ART': set(['PROPN']),
'LAW': set(['PROPN']),
'LANGUAGE': set(['PROPN']),
}
def __init__(self):
# Spacy with neural coreference resolution
self.nlp = spacy.load('en_core_web_lg', disable=[])
neuralcoref.add_to_pipe(self.nlp)
self.nlp.add_pipe(NumberComparisonMerger(self.nlp))
self.nlp.add_pipe(ShotBreakdownMerger(self.nlp), last=True)
def spacy_parses_to_abstract_text(self, sents):
tokens = []
for sent in sents:
for token in sent:
if token.ent_type_:
tokens.append(f'{token.pos_}-{token.ent_type_}')
else:
## Need the whole token, instead of just lemma for template purposes
# not now, because using original text for template extraction
tokens.append(f'{token.pos_}-{token.lemma_}')
# tokens.append(f'{token.pos_}-{token}')
# Remove consecutive duplicates. PROPN-GPE PROPN-ORG PROPN-ORG => PROPN-GPE PROPN-ORG (e.g. Portland Trail Blazers)
return ' '.join([x[0] for x in groupby(tokens)])
def raw_sentence(self, sents):
return ' '.join([sent.text for sent in sents])
def spacy_sent_tokenize(self, doc):
# print(f'{doc.text}')
sents = []
all_sents = []
valid_stop = False
for sent in doc.sents:
sents.append(sent)
valid_stop = True if sent[-1].text in ['.', '?', '!'] else False
if valid_stop:
all_sents.append(self.raw_sentence(sents))
sents = []
return all_sents
def process_one_summary(self, summary):
if summary != '':
summary = re.sub('\(\d+-\d+ \w{0,3}, \d+-\d+ \w{0,3}, \d+-\d+ \w{0,3}\)', '(ShotBreakdown)', summary)
summary = re.sub('\s+', ' ', summary)
orig_doc = self.nlp(summary)
doc = self.nlp(orig_doc._.coref_resolved)
sents = []
sent_num = 0
valid_stop = False
abs_sents = []
for sent in doc.sents:
sents.append(sent)
valid_stop = True if sent[-1].text in ['.', '?', '!'] else False
if valid_stop:
raw_sentence = self.raw_sentence(sents)
abstract = self.spacy_parses_to_abstract_text(sents)
abs_sents.append({
"raw_coref": raw_sentence,
"abs": abstract
})
sents = []
sent_num += 1
return abs_sents
def main():
print('constructing...')
extractor = TreeExtracter()
nlp = spacy.load('en_core_web_lg', disable=[])
print('constructed!!!')
# for _, part in enumerate(['test', 'train', 'valid']):
for _, part in enumerate(['train']):
if part == 'train':
seasons = [14, 15, 16]
# seasons = [14]
elif part == 'valid':
seasons = [17]
else:
seasons = [18]
print(part, seasons)
raw_sents = {
'season': [],
'game_id': [],
'raw': [],
'raw_coref': [],
'abs': []
}
for _, season in enumerate(seasons):
print(season)
js = json.load(open(f'./sportsett/data/initial/jsons/{season}.json', 'r'))
summs = [' '.join(i['summary']) for i in js]
for idx, summ in enumerate(summs):
if idx % 100 == 0:
print(idx)
out = extractor.process_one_summary(summ)
doc = nlp(summ)
all_sents = extractor.spacy_sent_tokenize(doc)
# print(idx, len(out), len(all_sents))
# print(out, all_sents)
if len(out) == len(all_sents):
for idx1, sent in enumerate(all_sents):
raw_sents['season'].append(season)
raw_sents['game_id'].append(idx)
raw_sents['raw'].append(sent)
raw_sents['raw_coref'].append(out[idx1]['raw_coref'])
raw_sents['abs'].append(out[idx1]['abs'])
else:
print(idx, len(out), len(all_sents), "ignoring")
df = pd.DataFrame(raw_sents)
# print(df.shape)
# print(df)
df.to_csv(f'./sportsett/data/initial/csvs/{part}.csv', index=False)
if __name__ == '__main__':
main()