Source

upparse / scripts / chunk.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
506
507
508
509
510
511
512
513
514
515
#!/usr/bin/env python

'''
Wrapper around upparse.jar chunk
'''

import sys
from os.path import dirname, basename, exists
from os import makedirs, listdir, sep
from shutil import rmtree
from optparse import OptionParser
from subprocess import Popen, PIPE, STDOUT
from collections import defaultdict
from filecmp import cmp as filecmp
from glob import glob

class PhrasalTerms:

  def __init__(self, output_fname):
    d = defaultdict(lambda:0)
    for line in open(output_fname):
      for chunk in line.split():
        for word in chunk.split('_'):
          d[word] += 1
    self._dict = d

  def term(self, chunk):
    words = chunk.split('_')
    if len(words) == 1:
      return words[0]

    elif len(words) > 1:
      return '=' + self._argmax(words)

    else:
      raise RuntimeError('unexpected number of terms ' + str(words))

  def write_new_dataset(self, in_fname, out_fname):
    out_fh = open(out_fname, 'w')
    for sentence in open(in_fname):
      for chunk in sentence.split():
        print >>out_fh, self.term(chunk),
      print >>out_fh
    out_fh.close()

  def _argmax(self, terms):
    maxval = 0
    argmax = ''
    for term in terms:
      val = self._dict[term]
      if val >= maxval:
        maxval, argmax = val, term
    return argmax
    

def guess_input_type(fname):
  if fname.endswith('.mrg'): 
    return 'WSJ'
  
  elif fname.endswith('.penn'):
    return 'NEGRA'

  elif fname.endswith('.fid'):
    return 'CTB'

  else:
    return 'SPL'

def run_cmd(cmd, fh=None, verbose=False):
  if verbose: log('cmd: ' + cmd)
  p = Popen(cmd, **dict(stdout=PIPE, shell=True))
  while True:
    o = p.stdout.read(1)
    if o == '':
      break
    else:
      sys.stdout.write(o)
      if fh is not None:
        fh.write(o)

  p.wait()
  assert p.returncode == 0

def log(st):
  print >>sys.stderr, st

class OptionHelper:
  
  def __init__(self):
    op = OptionParser()
  
    op.add_option('-t', '--train')
    op.add_option('-T', '--input_type')
    op.add_option('-s', '--test')
    op.add_option('-U', '--test_input_type')
    op.add_option('-o', '--output')
    op.add_option('-r', '--reverse', action='store_true')
    op.add_option('-f', '--filter_test', type='int', default='-1')
    op.add_option('-m', '--model', default='prlg-uni')
    op.add_option('-M', '--memflag', default='-Xmx1g')
    op.add_option('-c', '--coding', default='BIO')
    op.add_option('-p', '--pos', action='store_true')
    op.add_option('-P', '--nopunc', action='store_true')
    op.add_option('-E', '--emdelta', type='float', default=.0001)
    op.add_option('-C', '--cascade', action='store_true')
    op.add_option('-S', '--smooth', type='float', default=.1)
    op.add_option('-I', '--iter', type='int', default=-1)
    op.add_option('-v', '--verbose', action='store_true')
    op.add_option('-O', '--stdout', action='store_true')
    op.add_option('-x', '--output_type', default='CLUMP')
    op.add_option('-N', '--numtrain', type='int', default=-1)
    op.add_option('-A', '--output_all', action='store_true')
    op.add_option('-X', '--continuous_eval', action='store_true')
    op.add_option('-D', '--dont_overwrite', action='store_true')
    op.add_option('-W', '--do_overwrite', action='store_true')
    op.add_option('-V', '--stats', action='store_true')
    op.add_option('-w', '--model_out')
    op.add_option('-l', '--model_in')
  
    opt, args = op.parse_args()

    self.opt = opt

    self._input_type = None

  def verbose(self):
    return self.opt.verbose

  def stdout(self):
    return self.opt.stdout

  def cascade(self):
    return self.opt.cascade

  def output(self):
    return self.opt.output

  def output_type(self):
    return self.opt.output_type

  def set_output(self, outp):
    self.opt.output = outp

  def input_type(self):
    input_type_map = {'wsj':'WSJ', 'negra':'NEGRA', 'ctb':'CTB', 'brown':'WSJ'}
    try:
      return input_type_map[self.opt.input_type]
    except KeyError:
      input_type = guess_input_type(self._get_test_str())
      log('guessing input type = ' + input_type)
      return input_type

  def test_input_type(self):
    if self.opt.test_input_type == None:
      return self.input_type()
    input_type_map = {'wsj':'WSJ', 'negra':'NEGRA', 'ctb':'CTB', 'brown':'WSJ'}
    try:
      return input_type_map[self.opt.test_input_type]
    except KeyError:
      input_type = guess_input_type(self._get_test_str())
      log('guessing input type = ' + input_type)
      return input_type




  def check_output(self):
    opt = self.opt
    if opt.output is not None:
      if exists(opt.output):
        if opt.dont_overwrite:
          answer = 'n'
        
        elif opt.do_overwrite:
          answer = 'y'

        else:
          answer = 'x'

        yn = ['y','n']
        while answer not in yn:
          answer = raw_input("Overwrite diretory '" \
                             + opt.output + "'? [y/n] ").strip()
          if answer not in yn:
            print "Answer 'y' or 'n'"
  
        if answer == 'n':
          sys.exit(0)
  
        else:
          rmtree(opt.output)

  def numtrain_flag(self):
    n = self.opt.numtrain
    return n >= 0 and (' -numtrain %d' % n) or ''

  def filter_flag(self):
    n = self.opt.filter_test
    return n >= 0 and (' -filterTest %d' % n) or ''
  
  def seg_flag(self):
    return self.opt.nopunc and ' -noSeg ' or ''

  def model_flag(self):
    opt = self.opt
    if opt.model == 'prlg-uni':
      model_flag = ' -chunkerType PRLG -chunkingStrategy UNIFORM '
    elif opt.model == 'hmm-uni':
      model_flag = ' -chunkerType HMM -chunkingStrategy UNIFORM '
    elif opt.model == 'prlg-rand':
      model_flag = ' -chunkerType PRLG -chunkingStrategy RANDOM '
    elif opt.model == 'hmm-rand':
      model_flag = ' -chunkerType HMM -chunkingStrategy RANDOM '
    elif opt.model == 'prlg-rand':
      model_flag = ' -chunkerType PRLG -chunkingStrategy TWOSTAGE -F 2 '
    elif opt.model == 'hmm-2st':
      model_flag = ' -chunkerType HMM -chunkingStrategy TWOSTAGE -F 2 '
    elif opt.model == 'prlg-2st-pachinko':
      model_flag = ' -chunkerType PRLG -chunkingStrategy TWOSTAGE -F 2,1 '
    elif opt.model == 'hmm-2st-pachinko':
      model_flag = ' -chunkertype hmm -chunkingstrategy twostage -f 2,1 '
    elif opt.model == 'bigram-heuristic':
      model_flag = ' -chunkingStrategy HEURISTIC -F 2 '
    elif opt.model == 'pachinko-heuristic':
      model_flag = ' -chunkingStrategy HEURISTIC -F 2,1 '
    elif opt.model == 'prlg-sup-clump':
      model_flag = ' -chunkerType PRLG -chunkingStrategy SUPERVISED_CLUMP -iterations 0 '
    elif opt.model == 'hmm-sup-clump':
      model_flag = ' -chunkerType HMM -chunkingStrategy SUPERVISED_CLUMP -iterations 0 '
    elif opt.model == 'prlg-sup-nps':
      model_flag = ' -chunkerType PRLG -chunkingStrategy SUPERVISED_NPS -iterations 0 '
    elif opt.model == 'hmm-sup-nps':
      model_flag = ' -chunkerType HMM -chunkingStrategy SUPERVISED_NPS -iterations 0 '
    else:
      print >>sys.stderr, 'Unexpected model option:', opt.model
      sys.exit(1)

    if opt.iter >= 0:
      model_flag += ' -iterations %d' % opt.iter

    return model_flag

  def coding_flag(self):
    opt = self.opt
    coding_flag = ' -G ' + opt.coding
    return coding_flag

  def java_cmd(self):
    return 'java -ea ' + self.opt.memflag + ' -jar upparse.jar'

  def chunk_cmd(self):
    return self.java_cmd() + ' chunk'

  def eval_cmd(self):
    return self.java_cmd() + ' cclp-eval -E PRCL '

  def emdelta_flag(self):
    if self.opt.iter >= 0:
      return ' -emdelta 1E-100'
    else:
      return ' -emdelta %f' % self.opt.emdelta

  def smooth_flag(self):
    return ' -smooth %f' % self.opt.smooth

  def reverse_flag(self):
    return self.opt.reverse and ' -reverse' or ''

  def pos_flag(self):
    return self.opt.pos and ' -outputPos' or ''

  def output_all_flag(self):
    return self.opt.output_all and ' -outputAll' or ''

  def continuous_eval_flag(self):
    return self.opt.continuous_eval and ' -continuousEval' or ''

  def basic_cmd(self):
    cmd = self.chunk_cmd()
    cmd += self.model_flag()
    cmd += self.coding_flag()
    cmd += self.seg_flag()
    cmd += self.output_all_flag()
    cmd += self.continuous_eval_flag()
    cmd += self.emdelta_flag()
    cmd += self.smooth_flag()
    cmd += self.reverse_flag()
    cmd += self.pos_flag()
    cmd += self.numtrain_flag()
    return cmd

  def _get_train_str(self):
    return self._get_glob_expanded(self.opt.train)

  def _get_test_str(self):
    if self.opt.test is None:
      self.opt.test = self.opt.train

    return self._get_glob_expanded(self.opt.test)

  def _get_glob_expanded(self, fname_glob):
    fnames = []
    for g in fname_glob.split():
      fnames.extend(glob(g))
    fnames.sort()
    return ' '.join(fnames)

  def starter_train(self):
    assert self.opt.train is not None or self.opt.model_in is not None
    if self.opt.train:
      cmd = ' -train ' + self._get_train_str()
      cmd += ' -trainFileType ' + self.input_type()
    elif self.opt.model_in:
      cmd = ' -loadModel ' + self.opt.model_in
    return cmd

  def starter_test(self):
    if self.opt.stats:
      return ' -stats '
    if self.opt.test is self.opt.train and self.opt.model_out is not None:
      return ' -writeModel ' + self.opt.model_out
    cmd = ' -test ' + self._get_test_str()
    cmd += ' -testFileType ' + self.test_input_type()
    return cmd

  def starter_train_out(self):
    cmd = ' -test ' + self._get_train_str()
    cmd += ' -testFileType ' + self.input_type()
    return cmd

  def model_out(self):
    if self.opt.model_out is not None:
      return ' -writeModel ' + self.opt.model_out
    else:
      return ''

def get_output_fname(output_dir):
  return output_dir + '/OUTPUT'
   
def main():

  opt_h = OptionHelper()

  if opt_h.cascade():
    input_type = opt_h.input_type()
    verbose = opt_h.verbose()

    if opt_h.output() is None:
      opt_h.set_output('out')
    opt_h.check_output()
    cascade_dir = '%s/cascade00' % opt_h.output()
    makedirs(cascade_dir)
    results_fh = open('%s/results' % opt_h.output(), 'w')
    cascade_train_out = '%s/train-out' % cascade_dir
    cascade_train_out_model = '%s/model.ser' % cascade_dir
    cascade_test_out = '%s/test-out' % cascade_dir

    basic_cmd = opt_h.basic_cmd()
    output_file_type = ' -outputType UNDERSCORE4CCL'

    if verbose: log('running initial chunking')
    if verbose: log('writing model to ' + cascade_train_out_model)
    run_cmd(basic_cmd \
            + opt_h.starter_train() \
            + opt_h.starter_train_out() \
            + output_file_type \
            + ' -writeModel ' + cascade_train_out_model \
            + ' -output ' + cascade_train_out, \
            verbose=verbose)

    if verbose: log('chunking')
    if verbose: log('reading model from ' + cascade_train_out_model)
    run_cmd(basic_cmd \
            + ' -loadModel ' + cascade_train_out_model \
            + opt_h.starter_test() \
            + opt_h.filter_flag() \
            + output_file_type \
            + ' -output ' + cascade_test_out, \
            verbose=verbose)

    cascade_iter = 1

    new_cascade_train_out_fname = get_output_fname(cascade_train_out)
    cascade_expand_last = None
    while True:

      # convert test output to trees
      cascade_test_out_fname = get_output_fname(cascade_test_out)
      cascade_expand = []
      log('building corpus record from ' + cascade_test_out)
      for s_ind, sentence in enumerate(open(cascade_test_out_fname)):
        i = 0
        sentence_str = []
        for chunk in sentence.split():
          chunk = chunk.split('_')
          chunk_str = []
          for word in chunk:
            if word.startswith('=') and len(word) > 1:
              chunk_str.append(cascade_expand_last[s_ind][i])
            else:
              chunk_str.append(word)

            i += 1

          if len(chunk) == 1:
            sentence_str.append(chunk_str[0])

          else:
            sentence_str.append('(' + (' '.join(chunk_str)) + ')')

        cascade_expand.append(sentence_str)

      cascade_test_eval_fname = cascade_dir + '/test-eval'
      eval_fh = open(cascade_test_eval_fname, 'w')
      for sent in cascade_expand:
        print >>eval_fh, '(' + (' '.join(sent)).replace(' ;', '') + ')'
      eval_fh.close()

      # evaluate test output as trees

      if opt_h.input_type() in ['WSJ','NEGRA','CTB']:
        run_cmd(opt_h.eval_cmd() \
                + opt_h.starter_test() \
                + ' -cclpOutput ' + cascade_test_eval_fname \
                + opt_h.filter_flag(), fh=results_fh, \
                verbose=opt_h.verbose())

      elif verbose:
        log(opt_h.input_type() + ' not in [WSJ,NEGRA,CTB]')

      cascade_expand_last = cascade_expand

      if verbose: log('running cascade level ' + str(cascade_iter))

      # build term frequency map from last train output
      cascade_train_out_fname = new_cascade_train_out_fname
      phrasal_terms = PhrasalTerms(cascade_train_out_fname)

      # create next-run train
      next_run_train_fname = cascade_dir + '/next-train'
      phrasal_terms.write_new_dataset(cascade_train_out_fname, \
                                      next_run_train_fname)

      # run chunker, output re-chunked train
      new_cascade_dir = '%s/cascade%02d' % (opt_h.output(), cascade_iter)
      makedirs(new_cascade_dir)
      cascade_train_out = '%s/train-out' % new_cascade_dir
      cascade_train_out_model = '%s/model.ser' % cascade_dir
      if verbose: log('chunking train set')
      if verbose: log('reading train from ' + next_run_train_fname)
      if verbose: log('writing model to ' + cascade_train_out_model)
      if verbose: log('writing chunked train to ' + cascade_train_out)
      run_cmd(basic_cmd \
              + ' -train ' + next_run_train_fname \
              + ' -trainFileType SPL ' \
              + ' -test ' + next_run_train_fname \
              + ' -writeModel ' + cascade_train_out_model \
              + ' -testFileType SPL ' \
              + output_file_type \
              + ' -output ' + cascade_train_out,
              verbose=opt_h.verbose())

      # if re-chunked train is the same as orig, break
      new_cascade_train_out_fname = get_output_fname(cascade_train_out)
      if filecmp(cascade_train_out_fname, new_cascade_train_out_fname): 
        break

      # create next-run test
      cascade_test_out = '%s/test-out' % new_cascade_dir
      next_run_test_fname = cascade_dir + '/next-test'
      phrasal_terms.write_new_dataset(cascade_test_out_fname, \
                                      next_run_test_fname)

      # run the chunker, output re-chunked test

      if verbose: log('chunking test')
      if verbose: log('reading model from ' + cascade_train_out_model)
      if verbose: log('chunking ' + next_run_test_fname)
      if verbose: log('writing output to ' + cascade_test_out)
      run_cmd(basic_cmd \
              + ' -loadModel ' + cascade_train_out_model \
              + ' -test ' + next_run_test_fname \
              + ' -testFileType SPL ' \
              + output_file_type \
              + ' -output ' + cascade_test_out, \
              verbose=verbose)

      cascade_dir = new_cascade_dir
      cascade_iter += 1

    results_fh.close()

  else:
    cmd = opt_h.basic_cmd()

    output_flag = ''
    if opt_h.stdout():
      output_flag = ' -output -'

    elif opt_h.output() is not None:
      opt_h.check_output()
      output_flag = ' -output ' + opt_h.output()

    cmd += ' -outputType ' + opt_h.output_type()
 
    cmd += output_flag
    cmd += opt_h.starter_train()
    cmd += opt_h.starter_test()
    cmd += opt_h.filter_flag()

    cmd += ' -E PRCL -e CLUMP,NPS,TREEBANKPREC'
    run_cmd(cmd, verbose=opt_h.verbose())

if __name__ == '__main__':
  main()