forked from c-amr/camr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmonthstats.py
214 lines (188 loc) · 7.44 KB
/
monthstats.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
#!/usr/bin/env python3
# encoding=utf-8
# for Python 3 compatibility
from __future__ import print_function
import sys, os, re, json
from collections import defaultdict
class Dict(dict):
def __init__(self, *args, **kwargs):
super(Dict, self).__init__(*args, **kwargs)
self.__dict__ = self
def __getattribute__(self, key):
try:
return super(Dict, self).__getattribute__(key)
except:
return
def __delattr__(self, name):
if name in self:
del self[name]
splitre = re.compile(r'\W+', re.I)
numre = re.compile(r'^\d+$', re.I)
def extract_features(before, after, month):
if type(before) is str:
before = list(x for x in splitre.split(before) if x and not numre.match(x))
else:
before = list(x for x in before if x and not numre.match(x))
if type(after) is str:
after = list(x for x in splitre.split(after) if x and not numre.match(x))
else:
after = list(x for x in after if x and not numre.match(x))
features = {}
for w in before:
features["L:"+w] = '+'
features[":"+w] = '+'
for w in after:
features["R:"+w] = '+'
features[":"+w] = '+'
features["M:"+month] = '+'
return features
def load_rules(filename='monthstats.json'):
try:
with open(filename) as f:
settings = json.load(f, object_hook=Dict)
return settings.rules
except KeyboardInterrupt:
raise
except:
print('Unable to load month rules', file=sys.stderr)
def match(rules, features):
results = defaultdict(float)
for rule in rules:
found = True
for k,v in rule.data.items():
if features.get(k) != v:
found = False
break
if found:
results[rule['class']] += rule.w
max_score = 0
max_cls = None
for cls,score in results.items():
if max_cls is None or score > max_score:
max_cls = cls
max_score = score
return max_cls
if __name__ == "__main__":
import pyd21 as PyC60
import smatch_api
args = sys.argv[1:]
month2num = {
'january': '01',
'february': '02',
'march': '03',
'april': '04',
'may': '05',
'june': '06',
'july': '07',
'august': '08',
'september': '09',
'october': '10',
'november': '11',
'december': '12',
}
# monthnum = re.compile(r'((?:^|(?:[\W]+\w+){0,10})\W+)0000-(\d\d)-(\d\d)(\W+(?:\w+[\W]+){0,10}|$)', re.I)
monthnum = re.compile(r'(?P<left>(?:^|(?:[\W]+\w+){0,10})\W+)(?P<month>'+'|'.join(month2num.keys())+r')(?P<day>)(?P<right>\W+(?:\w+[\W]+){0,10}|$)',
re.I)
true_before = set()
false_before = set()
true_after = set()
false_after = set()
true_counts_before = defaultdict(int)
false_counts_before = defaultdict(int)
true_counts_after = defaultdict(int)
false_counts_after = defaultdict(int)
data = []
datafn = 'monthstats.json'
datafn = os.path.join(os.path.dirname(__file__))
if os.path.isfile(datafn):
with open(datafn) as f:
settings = json.load(f, object_hook=Dict)
# data = json.load(f, object_hook=Dict)
if set(settings.files) == set(args):
data = settings.data
args = settings.files
if not data:
for fn in args:
print('Reading', fn, '...')
with open(fn) as f:
for amr in smatch_api.parse_amr_iter(f):
# print(amr.text)
startpos = 0
# for m in monthnum.finditer(amr.text):
while True:
m = monthnum.search(amr.text, startpos)
if not m:
break
# before = list(x for x in m.group(1).split(' ') if x)
# after = list(x for x in m.group(4).split(' ') if x)
# before = list(x for x in splitre.split(m.group(1)) if x)
# after = list(x for x in splitre.split(m.group(4)) if x)
before = list(x for x in splitre.split(m.group('left')) if x)
after = list(x for x in splitre.split(m.group('right')) if x)
# month = m.group(2)
month = m.group('month')
month = month2num[month.lower()]
# day = m.group(3)
day = m.group('day')
# startpos = m.end(2) # continue right after previously found month
startpos = m.end('month') # continue right after previously found month
is_month = bool(re.search(r'date-entity [()]*:month '+str(int(month)), amr.amr_line))
data.append(Dict(before=before, after=after, is_month=is_month, month=month, day=day))
print(month+'-'+day, is_month, ': ', before, ' :::::: ', after)
# print(amr.amr_line)
# print(amr.amr_line)
with open(datafn, 'w') as f:
json.dump(dict(files=args, data=data), f, ensure_ascii=False, indent=2)
if not data:
print('no input files specified', file=sys.stderr)
sys.exit(1)
classifier = PyC60.Classifier()
classifier.max_features = 4
# classifier.filter_rules = True
skipped = 0
for item in data:
features = extract_features(item.before, item.after, item.month)
if features:
classifier.add(str(item.is_month), features)
elif item.is_month:
skipped += 1
# before_set = set(item.before)
# after_set = set(item.after)
# if item.is_month:
# for w in before_set:
# true_counts_before[w] += 1
# for w in after_set:
# true_counts_after[w] += 1
# true_before |= before_set
# true_after |= after_set
# else:
# for w in before_set:
# false_counts_before[w] += 1
# for w in after_set:
# false_counts_after[w] += 1
# false_before |= before_set
# false_after |= after_set
# print(item.month+'-'+item.day, item.is_month, ': ', item.before, ' :::::: ', item.after)
classifier.train()
rules = classifier.rules()
with open(datafn, 'w') as f:
json.dump(dict(files=args, data=data, rules=rules), f, ensure_ascii=False, indent=2)
import pprint
# pprint.pprint(classifier.rules())
# print(classifier.rules())
classifier.print_classes()
classifier.print()
classifier.print_classes()
print(skipped, 'true classes skipped')
# print('True before:', ','.join(sorted(true_before)))
# for k,c in sorted(true_counts_before.items(), key=lambda item: item[1], reverse=True):
# print(k, '=', c)
# print('True after:', ','.join(sorted(true_after)))
# for k,c in sorted(true_counts_after.items(), key=lambda item: item[1], reverse=True):
# print(k, '=', c)
# print('False before:', ','.join(sorted(false_before)))
# for k,c in sorted(false_counts_before.items(), key=lambda item: item[1], reverse=True):
# print(k, '=', c)
# print('False after:', ','.join(sorted(false_after)))
# for k,c in sorted(false_counts_after.items(), key=lambda item: item[1], reverse=True):
# print(k, '=', c)