-
Notifications
You must be signed in to change notification settings - Fork 1
/
TAC_ILP_baseline.py
505 lines (383 loc) · 14.9 KB
/
TAC_ILP_baseline.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
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
import fio
import json
import sys
import porter
import NLTKWrapper
import os
import json
import ILP_MC
import numpy
from Survey import punctuations
ngramTag = "___"
stopwords = [line.lower().strip() for line in fio.ReadFile("../../../Fall2014/summarization/ROUGE-1.5.5/data/smart_common_words.txt")]
stopwordswithpunctuations = stopwords + punctuations
#stopwords = stopwords + punctuations
#stopwords = [porter.getStemming(w) for w in stopwords]
#fio.SaveList(stopwords, "../../../Fall2014/summarization/ROUGE-1.5.5/data/smart_common_words_stemmed.txt")
#Stemming
phraseext = ".key" #a list
studentext = ".keys.source" #json
countext = ".dict" #a dictionary
lpext = ".lp"
lpsolext = ".sol"
def getRouges(input):
head, body = fio.ReadMatrix(input, hasHead=True)
return body[-1][1:]
def getRougesWithAverage(input):
head, body = fio.ReadMatrix(input, hasHead=True)
N = len(head)
single_N = N / 3
head += head[(N-single_N):-1]
new_body = []
for row in body:
pass
return head, new_body
def removeStopWords(tokens):
newTokens = [token for token in tokens if token.lower() not in stopwordswithpunctuations]
return newTokens
def isMalformed(phrase):
N = len(phrase.split())
if N == 1: #single stop words
if phrase.lower() in stopwords: return True
if phrase.isdigit(): return True
if len(phrase) > 0:
if phrase[0] in punctuations: return True
return False
def WriteConstraint1(PhraseBeta, L):
#$\sum_{j=1}^P y_j \beta _j \le L$
lines = []
constraint = []
for phrase, beta in PhraseBeta.items():
constraint.append(" ".join([str(beta), phrase]))
lines.append(" "+ " + ".join(constraint) + " <= " + str(L))
return lines
#print " ", " + ".join(constraint), ">=", L-10
def WriteConstraint2(BigramPhrase):
#$\sum_{j=1} {y_j Occ_{ij}} \ge x_i$
lines = []
for bigram, phrases in BigramPhrase.items():
lines.append(" "+ " + ".join(phrases) + " - " + bigram+ " >= " + str(0))
return lines
def WriteConstraint3(PhraseBigram):
#$y_j Occ_{ij} \le x_i$
lines = []
for phrase, bigrams in PhraseBigram.items():
for bigram in bigrams:
lines.append(" " + phrase + " - " + bigram + " <= " + '0')
return lines
def WriteConstraint4(StudentPhrase):
#$\sum_{j=1}^P {y_j Occ_{jk}} \ge z_k$
lines = []
for student, phrases in StudentPhrase.items():
lines.append(" " + " + ".join(phrases) + " - " + student + " >= " + '0')
return lines
def formulate_problem(BigramTheta, PhraseBeta, BigramPhrase, PhraseBigram, L, lpfileprefix, student_coverage, StudentGamma, StudentPhrase, student_lambda):
lines = []
#write objective
lines.append("Maximize")
objective = []
if student_coverage:
for bigram, theta in BigramTheta.items():
objective.append(" ".join([str(theta*student_lambda), bigram]))
for student, grama in StudentGamma.items():
objective.append(" ".join([str(grama*(1-student_lambda)), student]))
else:
for bigram, theta in BigramTheta.items():
objective.append(" ".join([str(theta), bigram]))
lines.append(" " + " + ".join(objective))
#write constraints
lines.append("Subject To")
lines += WriteConstraint1(PhraseBeta, L)
lines += WriteConstraint2(BigramPhrase)
lines += WriteConstraint3(PhraseBigram)
if student_coverage:
lines += WriteConstraint4(StudentPhrase)
indicators = []
for bigram in BigramTheta.keys():
indicators.append(bigram)
for phrase in PhraseBeta.keys():
indicators.append(phrase)
if student_coverage:
for student in StudentGamma.keys():
indicators.append(student)
#write Bounds
lines.append("Bounds")
for indicator in indicators:
lines.append(" " + indicator + " <= " + '1')
#write Integers
lines.append("Integers")
lines.append(" " + " ".join(indicators))
#write End
lines.append("End")
fio.SaveList(lines, lpfileprefix + lpext)
def SloveILP(lpfileprefix):
input = lpfileprefix + lpext
output = lpfileprefix + lpsolext
fio.remove(output)
cmd = "gurobi_cl ResultFile=" + lpfileprefix + lpsolext + " " + input
os.system(cmd)
def ExtractSummaryfromILP(lpfileprefix, phrases, output):
summaries = []
sol = lpfileprefix + lpsolext
lines = fio.ReadFile(sol)
for line in lines:
line = line.strip()
if line.startswith('#'): continue
tokens = line.split()
assert(len(tokens) == 2)
key = tokens[0]
value = tokens[1]
if key in phrases:
if value == '1':
summaries.append(phrases[key])
fio.SaveList(summaries, output)
def getNgramTokenized(tokens, n, NoStopWords=False, Stemmed=False, ngramTag = " "):
#n is the number of grams, such as 1 means unigram
ngrams = []
N = len(tokens)
for i in range(N):
if i+n > N: continue
ngram = tokens[i:i+n]
if Stemmed:
stemmed_ngram = []
for w in ngram:
stemmed_ngram.append(porter.getStemming(w))
if not NoStopWords:
if Stemmed:
ngrams.append(ngramTag.join(stemmed_ngram))
else:
ngrams.append(ngramTag.join(ngram))
else:
removed = True
for w in ngram:
if w not in stopwords:
removed = False
if not removed:
if Stemmed:
ngrams.append(ngramTag.join(stemmed_ngram))
else:
ngrams.append(ngramTag.join(ngram))
return ngrams
def getPhraseBigram(phrasefile, Ngram=[1,2], MalformedFlilter=False, svdfile=None, NoStopWords=True, Stemmed=True):
if svdfile != None:
bigramDict = ILP_MC.LoadMC(svdfile)
#get phrases
lines = fio.ReadFile(phrasefile)
phrases = [line.strip() for line in lines]
newPhrases = []
for phrase in phrases:
#phrase = ProcessLine(phrase)
if MalformedFlilter and isMalformed(phrase.lower()): continue
newPhrases.append(phrase)
phrases = newPhrases
PhraseBigram = {}
#get index of phrase
j = 1
phraseIndex = {}
for phrase in phrases:
if phrase not in phraseIndex:
index = 'Y' + str(j)
phraseIndex[phrase] = index
PhraseBigram[index] = []
j = j + 1
#get bigram index and PhraseBigram
bigramIndex = {}
i = 1
for phrase in phrases:
pKey = phraseIndex[phrase]
tokens = phrase.lower().split()
#tokens = list(gensim.utils.tokenize(phrase, lower=True, errors='ignore'))
ngrams = []
for n in Ngram:
grams = getNgramTokenized(tokens, n, NoStopWords=NoStopWords, Stemmed=Stemmed)
#grams = NLTKWrapper.getNgram(phrase, n)
ngrams = ngrams + grams
for bigram in ngrams:
if svdfile != None:
if bigram not in bigramDict: continue
if bigram not in bigramIndex:
bKey = 'X' + str(i)
bigramIndex[bigram] = bKey
i = i + 1
else:
bKey = bigramIndex[bigram]
PhraseBigram[pKey].append(bKey)
IndexPhrase = {}
for k,v in phraseIndex.items():
IndexPhrase[v] = k
IndexBigram = {}
for k,v in bigramIndex.items():
IndexBigram[v] = k
return IndexPhrase, IndexBigram, PhraseBigram
def getPhraseBigram2(phrasefile, Ngram=[1,2], MalformedFlilter=False, svdfile=None, NoStopWords=True, Stemmed=True):
if svdfile != None:
bigramDict = ILP_MC.LoadMC(svdfile)
#get phrases
lines = fio.ReadFile(phrasefile)
phrases = [line.strip() for line in lines]
newPhrases = []
for phrase in phrases:
#phrase = ProcessLine(phrase)
if MalformedFlilter and isMalformed(phrase.lower()): continue
newPhrases.append(phrase)
phrases = newPhrases
PhraseBigram = {}
#get index of phrase
j = 1
phraseIndex = {}
for phrase in phrases:
if phrase not in phraseIndex:
index = 'Y' + str(j)
phraseIndex[phrase] = index
PhraseBigram[index] = []
j = j + 1
#get bigram index and PhraseBigram
bigramIndex = {}
i = 1
for phrase in phrases:
pKey = phraseIndex[phrase]
tokens = phrase.lower().split()
#tokens = list(gensim.utils.tokenize(phrase, lower=True, errors='ignore'))
ngrams = []
for n in Ngram:
grams = getNgramTokenized(tokens, n, NoStopWords=NoStopWords, Stemmed=Stemmed)
#grams = NLTKWrapper.getNgram(phrase, n)
ngrams = ngrams + grams
for bigram in ngrams:
if svdfile != None:
if bigram not in bigramDict: continue
if bigram not in bigramIndex:
bKey = 'X' + str(i)
bigramIndex[bigram] = bKey
i = i + 1
else:
bKey = bigramIndex[bigram]
PhraseBigram[pKey].append(bKey)
IndexPhrase = {}
for k,v in phraseIndex.items():
IndexPhrase[v] = k
IndexBigram = {}
for k,v in bigramIndex.items():
IndexBigram[v] = k
return IndexPhrase, IndexBigram, PhraseBigram
def getBigramWeight_TF(PhraseBigram, PhraseIndex, CountFile):
BigramTheta = {}
CountDict = {}#fio.LoadDict(CountFile, 'float')
for phrase, bigrams in PhraseBigram.items():
assert(phrase in PhraseIndex)
p = PhraseIndex[phrase]
try:
fequency = 1.0#CountDict[p]
except Exception as e:
print p
exit()
for bigram in bigrams:
if bigram not in BigramTheta:
BigramTheta[bigram] = 0
BigramTheta[bigram] = BigramTheta[bigram] + fequency
return BigramTheta
def getBigramWeight_StudentNo(PhraseBigram, PhraseIndex, CountFile):
BigramTheta = {}
CountDict = fio.LoadDict(CountFile, 'float')
for phrase, bigrams in PhraseBigram.items():
assert(phrase in PhraseIndex)
p = PhraseIndex[phrase]
try:
fequency = CountDict[p]
except Exception as e:
print p
exit()
unique_bigram = set(bigrams)
for bigram in unique_bigram:
if bigram not in BigramTheta:
BigramTheta[bigram] = 0
BigramTheta[bigram] = BigramTheta[bigram] + fequency
return BigramTheta
def getWordCounts(phrases):
PhraseBeta = {}
for index, phrase in phrases.items():
N = len(phrase.split())
PhraseBeta[index] = N
return PhraseBeta
def getBigramPhrase(PhraseBigram):
BigramPhrase = {}
for phrase, bigrams in PhraseBigram.items():
for bigram in bigrams:
if bigram not in BigramPhrase:
BigramPhrase[bigram] = []
BigramPhrase[bigram].append(phrase)
return BigramPhrase
def getStudentPhrase(phrases, sourcefile):
with open(sourcefile, "r") as infile:
PhraseStduent = json.load(infile)
indexPhrase = {}
for index, phrase in phrases.items():
indexPhrase[phrase] = index
StudentPhrase = {}
k = 1
studentIndex = {}
for phrase, students in PhraseStduent.items():
if phrase not in indexPhrase: continue
pKey = indexPhrase[phrase]
for student in students:
if student not in studentIndex:
sKey = 'Z' + str(k)
studentIndex[student] = sKey
k = k + 1
else:
sKey = studentIndex[student]
if sKey not in StudentPhrase:
StudentPhrase[sKey] = []
StudentPhrase[sKey].append(pKey)
IndexStudent = {}
for student, index in studentIndex.items():
IndexStudent[index] = student
return IndexStudent, StudentPhrase
def getStudentWeight_One(StudentPhrase):
#assume every student is equally important
StudentGamma = {}
for student in StudentPhrase:
StudentGamma[student] = 1.0
return StudentGamma
def ILP1(prefix, L, Ngram = [1,2], student_coverage = False, student_lambda = None):
# get each stemmed bigram, sequence the bigram and the phrase
# bigrams: {index:bigram}, a dictionary of bigram index, X
# phrases: {index:phrase}, is a dictionary of phrase index, Y
#PhraseBigram: {phrase, [bigram]}
IndexPhrase, IndexBigram, PhraseBigram = getPhraseBigram(prefix + phraseext, Ngram=Ngram)
fio.SaveDict(IndexPhrase, prefix + ".phrase_index.dict")
fio.SaveDict(IndexBigram, prefix + ".bigram_index.dict")
#get weight of bigrams
BigramTheta = getBigramWeight_TF(PhraseBigram, IndexPhrase, prefix + countext) # return a dictionary
fio.SaveDict(BigramTheta, prefix + ".bigram_theta.dict")
#get word count of phrases
PhraseBeta = getWordCounts(IndexPhrase)
#get {bigram:[phrase]} dictionary
BigramPhrase = getBigramPhrase(PhraseBigram)
#students, StudentPhrase = getStudentPhrase(IndexPhrase, prefix + studentext)
StudentGamma = None#getStudentWeight_One(StudentPhrase)
StudentPhrase = None
lpfile = prefix
formulate_problem(BigramTheta, PhraseBeta, BigramPhrase, PhraseBigram, L, lpfile, student_coverage, StudentGamma, StudentPhrase, student_lambda)
m = SloveILP(lpfile)
output = lpfile + '.L' + str(L) + ".summary"
ExtractSummaryfromILP(lpfile, IndexPhrase, output)
def iter_folder(folder, extension):
for subdir, dirs, files in os.walk(folder):
for file in sorted(files):
if not file.endswith(extension): continue
yield subdir, file
def ILP_Summarizer(ilpdir, np, L, Ngram = [1,2], student_coverage = False, student_lambda = None):
for year in ['s08', 's09', 's10', 's11']:
path = os.path.join(ilpdir, year)
for subdir, file in iter_folder(path, '.key'):
prefix = os.path.join(path, file[:-4])
ILP1(prefix, L, Ngram=Ngram, student_coverage = student_coverage, student_lambda = student_lambda)
if __name__ == '__main__':
ilpdir = "../../data/TAC_ILP_Sentence/"
from config import ConfigFile
config = ConfigFile(config_file_name='tac_config.txt')
for L in [config.get_length_limit()]:
for np in ['sentence']:
ILP_Summarizer(ilpdir, np, L, Ngram = config.get_ngrams(), student_coverage = config.get_student_coverage(), student_lambda = config.get_student_lambda())
print "done"