parse-to-conll.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. # Copyright 2017 Google Inc. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. r"""Runs a both a segmentation and parsing model on a CoNLL dataset.
  16. """
  17. import re
  18. import time
  19. import tensorflow as tf
  20. from google.protobuf import text_format
  21. from tensorflow.python.client import timeline
  22. from tensorflow.python.platform import gfile
  23. from dragnn.protos import spec_pb2
  24. from dragnn.python import graph_builder
  25. from dragnn.python import sentence_io
  26. from dragnn.python import spec_builder
  27. from syntaxnet import sentence_pb2
  28. from syntaxnet.ops import gen_parser_ops
  29. from syntaxnet.util import check
  30. import dragnn.python.load_dragnn_cc_impl
  31. import syntaxnet.load_parser_ops
  32. flags = tf.app.flags
  33. FLAGS = flags.FLAGS
  34. flags.DEFINE_string('parser_master_spec', '',
  35. 'Path to text file containing a DRAGNN master spec to run.')
  36. flags.DEFINE_string('parser_checkpoint_file', '',
  37. 'Path to trained model checkpoint.')
  38. flags.DEFINE_string('parser_resource_dir', '',
  39. 'Optional base directory for resources in the master spec.')
  40. flags.DEFINE_string('segmenter_master_spec', '',
  41. 'Path to text file containing a DRAGNN master spec to run.')
  42. flags.DEFINE_string('segmenter_checkpoint_file', '',
  43. 'Path to trained model checkpoint.')
  44. flags.DEFINE_string('segmenter_resource_dir', '',
  45. 'Optional base directory for resources in the master spec.')
  46. flags.DEFINE_bool('complete_master_spec', True, 'Whether the master_specs '
  47. 'needs the lexicon and other resources added to them.')
  48. flags.DEFINE_string('input_file', '',
  49. 'File of CoNLL-formatted sentences to read from.')
  50. flags.DEFINE_string('output_file', '',
  51. 'File path to write annotated sentences to.')
  52. flags.DEFINE_integer('max_batch_size', 2048, 'Maximum batch size to support.')
  53. flags.DEFINE_string('inference_beam_size', '', 'Comma separated list of '
  54. 'component_name=beam_size pairs.')
  55. flags.DEFINE_string('locally_normalize', '', 'Comma separated list of '
  56. 'component names to do local normalization on.')
  57. flags.DEFINE_integer('threads', 10, 'Number of threads used for intra- and '
  58. 'inter-op parallelism.')
  59. flags.DEFINE_string('timeline_output_file', '', 'Path to save timeline to. '
  60. 'If specified, the final iteration of the evaluation loop '
  61. 'will capture and save a TensorFlow timeline.')
  62. flags.DEFINE_bool('use_gold_segmentation', False,
  63. 'Whether or not to use gold segmentation.')
  64. def main(unused_argv):
  65. # Parse the flags containint lists, using regular expressions.
  66. # This matches and extracts key=value pairs.
  67. component_beam_sizes = re.findall(r'([^=,]+)=(\d+)',
  68. FLAGS.inference_beam_size)
  69. # This matches strings separated by a comma. Does not return any empty
  70. # strings.
  71. components_to_locally_normalize = re.findall(r'[^,]+',
  72. FLAGS.locally_normalize)
  73. ## SEGMENTATION ##
  74. if not FLAGS.use_gold_segmentation:
  75. # Reads master spec.
  76. master_spec = spec_pb2.MasterSpec()
  77. with gfile.FastGFile(FLAGS.segmenter_master_spec) as fin:
  78. text_format.Parse(fin.read(), master_spec)
  79. if FLAGS.complete_master_spec:
  80. spec_builder.complete_master_spec(
  81. master_spec, None, FLAGS.segmenter_resource_dir)
  82. # Graph building.
  83. tf.logging.info('Building the graph')
  84. g = tf.Graph()
  85. with g.as_default(), tf.device('/device:CPU:0'):
  86. hyperparam_config = spec_pb2.GridPoint()
  87. hyperparam_config.use_moving_average = True
  88. builder = graph_builder.MasterBuilder(master_spec, hyperparam_config)
  89. annotator = builder.add_annotation()
  90. builder.add_saver()
  91. tf.logging.info('Reading documents...')
  92. input_corpus = sentence_io.ConllSentenceReader(FLAGS.input_file).corpus()
  93. with tf.Session(graph=tf.Graph()) as tmp_session:
  94. char_input = gen_parser_ops.char_token_generator(input_corpus)
  95. char_corpus = tmp_session.run(char_input)
  96. check.Eq(len(input_corpus), len(char_corpus))
  97. session_config = tf.ConfigProto(
  98. log_device_placement=False,
  99. intra_op_parallelism_threads=FLAGS.threads,
  100. inter_op_parallelism_threads=FLAGS.threads)
  101. with tf.Session(graph=g, config=session_config) as sess:
  102. tf.logging.info('Initializing variables...')
  103. sess.run(tf.global_variables_initializer())
  104. tf.logging.info('Loading from checkpoint...')
  105. sess.run('save/restore_all',
  106. {'save/Const:0': FLAGS.segmenter_checkpoint_file})
  107. tf.logging.info('Processing sentences...')
  108. processed = []
  109. start_time = time.time()
  110. run_metadata = tf.RunMetadata()
  111. for start in range(0, len(char_corpus), FLAGS.max_batch_size):
  112. end = min(start + FLAGS.max_batch_size, len(char_corpus))
  113. feed_dict = {annotator['input_batch']: char_corpus[start:end]}
  114. if FLAGS.timeline_output_file and end == len(char_corpus):
  115. serialized_annotations = sess.run(
  116. annotator['annotations'], feed_dict=feed_dict,
  117. options=tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE),
  118. run_metadata=run_metadata)
  119. trace = timeline.Timeline(step_stats=run_metadata.step_stats)
  120. with open(FLAGS.timeline_output_file, 'w') as trace_file:
  121. trace_file.write(trace.generate_chrome_trace_format())
  122. else:
  123. serialized_annotations = sess.run(
  124. annotator['annotations'], feed_dict=feed_dict)
  125. processed.extend(serialized_annotations)
  126. tf.logging.info('Processed %d documents in %.2f seconds.',
  127. len(char_corpus), time.time() - start_time)
  128. input_corpus = processed
  129. else:
  130. input_corpus = sentence_io.ConllSentenceReader(FLAGS.input_file).corpus()
  131. ## PARSING
  132. # Reads master spec.
  133. master_spec = spec_pb2.MasterSpec()
  134. with gfile.FastGFile(FLAGS.parser_master_spec) as fin:
  135. text_format.Parse(fin.read(), master_spec)
  136. if FLAGS.complete_master_spec:
  137. spec_builder.complete_master_spec(
  138. master_spec, None, FLAGS.parser_resource_dir)
  139. # Graph building.
  140. tf.logging.info('Building the graph')
  141. g = tf.Graph()
  142. with g.as_default(), tf.device('/device:CPU:0'):
  143. hyperparam_config = spec_pb2.GridPoint()
  144. hyperparam_config.use_moving_average = True
  145. builder = graph_builder.MasterBuilder(master_spec, hyperparam_config)
  146. annotator = builder.add_annotation()
  147. builder.add_saver()
  148. tf.logging.info('Reading documents...')
  149. session_config = tf.ConfigProto(
  150. log_device_placement=False,
  151. intra_op_parallelism_threads=FLAGS.threads,
  152. inter_op_parallelism_threads=FLAGS.threads)
  153. with tf.Session(graph=g, config=session_config) as sess:
  154. tf.logging.info('Initializing variables...')
  155. sess.run(tf.global_variables_initializer())
  156. tf.logging.info('Loading from checkpoint...')
  157. sess.run('save/restore_all', {'save/Const:0': FLAGS.parser_checkpoint_file})
  158. tf.logging.info('Processing sentences...')
  159. processed = []
  160. start_time = time.time()
  161. run_metadata = tf.RunMetadata()
  162. for start in range(0, len(input_corpus), FLAGS.max_batch_size):
  163. end = min(start + FLAGS.max_batch_size, len(input_corpus))
  164. feed_dict = {annotator['input_batch']: input_corpus[start:end]}
  165. for comp, beam_size in component_beam_sizes:
  166. feed_dict['%s/InferenceBeamSize:0' % comp] = beam_size
  167. for comp in components_to_locally_normalize:
  168. feed_dict['%s/LocallyNormalize:0' % comp] = True
  169. if FLAGS.timeline_output_file and end == len(input_corpus):
  170. serialized_annotations = sess.run(
  171. annotator['annotations'], feed_dict=feed_dict,
  172. options=tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE),
  173. run_metadata=run_metadata)
  174. trace = timeline.Timeline(step_stats=run_metadata.step_stats)
  175. with open(FLAGS.timeline_output_file, 'w') as trace_file:
  176. trace_file.write(trace.generate_chrome_trace_format())
  177. else:
  178. serialized_annotations = sess.run(
  179. annotator['annotations'], feed_dict=feed_dict)
  180. processed.extend(serialized_annotations)
  181. tf.logging.info('Processed %d documents in %.2f seconds.',
  182. len(input_corpus), time.time() - start_time)
  183. if FLAGS.output_file:
  184. with gfile.GFile(FLAGS.output_file, 'w') as f:
  185. for serialized_sentence in processed:
  186. sentence = sentence_pb2.Sentence()
  187. sentence.ParseFromString(serialized_sentence)
  188. f.write('#' + sentence.text.encode('utf-8') + '\n')
  189. for i, token in enumerate(sentence.token):
  190. head = token.head + 1
  191. f.write('%s\t%s\t_\t_\t_\t_\t%d\t%s\t_\t_\n'%(
  192. i + 1,
  193. token.word.encode('utf-8'), head,
  194. token.label.encode('utf-8')))
  195. f.write('\n\n')
  196. if __name__ == '__main__':
  197. tf.app.run()