lexicon_builder_test.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. # coding=utf-8
  2. # Copyright 2016 Google Inc. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # ==============================================================================
  16. """Tests for lexicon_builder."""
  17. # disable=no-name-in-module,unused-import,g-bad-import-order,maybe-no-member
  18. import os.path
  19. import tensorflow as tf
  20. import syntaxnet.load_parser_ops
  21. from tensorflow.python.framework import test_util
  22. from tensorflow.python.platform import googletest
  23. from tensorflow.python.platform import tf_logging as logging
  24. from syntaxnet import sentence_pb2
  25. from syntaxnet import task_spec_pb2
  26. from syntaxnet.ops import gen_parser_ops
  27. FLAGS = tf.app.flags.FLAGS
  28. CONLL_DOC1 = u'''1 बात _ n NN _ _ _ _ _
  29. 2 गलत _ adj JJ _ _ _ _ _
  30. 3 हो _ v VM _ _ _ _ _
  31. 4 तो _ avy CC _ _ _ _ _
  32. 5 गुस्सा _ n NN _ _ _ _ _
  33. 6 सेलेब्रिटिज _ n NN _ _ _ _ _
  34. 7 को _ psp PSP _ _ _ _ _
  35. 8 भी _ avy RP _ _ _ _ _
  36. 9 आना _ v VM _ _ _ _ _
  37. 10 लाजमी _ adj JJ _ _ _ _ _
  38. 11 है _ v VM _ _ _ _ _
  39. 12 । _ punc SYM _ _ _ _ _'''
  40. CONLL_DOC2 = u'''1 लेकिन _ avy CC _ _ _ _ _
  41. 2 अभिनेत्री _ n NN _ _ _ _ _
  42. 3 के _ psp PSP _ _ _ _ _
  43. 4 इस _ pn DEM _ _ _ _ _
  44. 5 कदम _ n NN _ _ _ _ _
  45. 6 से _ psp PSP _ _ _ _ _
  46. 7 वहां _ pn PRP _ _ _ _ _
  47. 8 रंग _ n NN _ _ _ _ _
  48. 9 में _ psp PSP _ _ _ _ _
  49. 10 भंग _ adj JJ _ _ _ _ _
  50. 11 पड़ _ v VM _ _ _ _ _
  51. 12 गया _ v VAUX _ _ _ _ _
  52. 13 । _ punc SYM _ _ _ _ _'''
  53. TAGS = ['NN', 'JJ', 'VM', 'CC', 'PSP', 'RP', 'JJ', 'SYM', 'DEM', 'PRP', 'VAUX']
  54. CATEGORIES = ['n', 'adj', 'v', 'avy', 'n', 'psp', 'punc', 'pn']
  55. TOKENIZED_DOCS = u'''बात गलत हो तो गुस्सा सेलेब्रिटिज को भी आना लाजमी है ।
  56. लेकिन अभिनेत्री के इस कदम से वहां रंग में भंग पड़ गया ।
  57. '''
  58. CHARS = u'''अ इ आ क ग ज ट त द न प भ ब य म र ल व ह स ि ा ु ी े ै ो ् ड़ । ं'''
  59. COMMENTS = u'# Line with fake comments.'
  60. class LexiconBuilderTest(test_util.TensorFlowTestCase):
  61. def setUp(self):
  62. if not hasattr(FLAGS, 'test_srcdir'):
  63. FLAGS.test_srcdir = ''
  64. if not hasattr(FLAGS, 'test_tmpdir'):
  65. FLAGS.test_tmpdir = tf.test.get_temp_dir()
  66. self.corpus_file = os.path.join(FLAGS.test_tmpdir, 'documents.conll')
  67. self.context_file = os.path.join(FLAGS.test_tmpdir, 'context.pbtxt')
  68. def AddInput(self, name, file_pattern, record_format, context):
  69. inp = context.input.add()
  70. inp.name = name
  71. inp.record_format.append(record_format)
  72. inp.part.add().file_pattern = file_pattern
  73. def WriteContext(self, corpus_format):
  74. context = task_spec_pb2.TaskSpec()
  75. self.AddInput('documents', self.corpus_file, corpus_format, context)
  76. for name in ('word-map', 'lcword-map', 'tag-map',
  77. 'category-map', 'label-map', 'prefix-table',
  78. 'suffix-table', 'tag-to-category', 'char-map'):
  79. self.AddInput(name, os.path.join(FLAGS.test_tmpdir, name), '', context)
  80. logging.info('Writing context to: %s', self.context_file)
  81. with open(self.context_file, 'w') as f:
  82. f.write(str(context))
  83. def ReadNextDocument(self, sess, doc_source):
  84. doc_str, last = sess.run(doc_source)
  85. if doc_str:
  86. doc = sentence_pb2.Sentence()
  87. doc.ParseFromString(doc_str[0])
  88. else:
  89. doc = None
  90. return doc, last
  91. def ValidateDocuments(self):
  92. doc_source = gen_parser_ops.document_source(self.context_file, batch_size=1)
  93. with self.test_session() as sess:
  94. logging.info('Reading document1')
  95. doc, last = self.ReadNextDocument(sess, doc_source)
  96. self.assertEqual(len(doc.token), 12)
  97. self.assertEqual(u'लाजमी', doc.token[9].word)
  98. self.assertFalse(last)
  99. logging.info('Reading document2')
  100. doc, last = self.ReadNextDocument(sess, doc_source)
  101. self.assertEqual(len(doc.token), 13)
  102. self.assertEqual(u'भंग', doc.token[9].word)
  103. self.assertFalse(last)
  104. logging.info('Hitting end of the dataset')
  105. doc, last = self.ReadNextDocument(sess, doc_source)
  106. self.assertTrue(doc is None)
  107. self.assertTrue(last)
  108. def ValidateTagToCategoryMap(self):
  109. with file(os.path.join(FLAGS.test_tmpdir, 'tag-to-category'), 'r') as f:
  110. entries = [line.strip().split('\t') for line in f.readlines()]
  111. for tag, category in entries:
  112. self.assertIn(tag, TAGS)
  113. self.assertIn(category, CATEGORIES)
  114. def LoadMap(self, map_name):
  115. loaded_map = {}
  116. with file(os.path.join(FLAGS.test_tmpdir, map_name), 'r') as f:
  117. for line in f:
  118. entries = line.strip().split(' ')
  119. if len(entries) == 2:
  120. loaded_map[entries[0]] = entries[1]
  121. return loaded_map
  122. def ValidateCharMap(self):
  123. char_map = self.LoadMap('char-map')
  124. self.assertEqual(len(char_map), len(CHARS.split(' ')))
  125. for char in CHARS.split(' '):
  126. self.assertIn(char.encode('utf-8'), char_map)
  127. def ValidateWordMap(self):
  128. word_map = self.LoadMap('word-map')
  129. for word in filter(None, TOKENIZED_DOCS.replace('\n', ' ').split(' ')):
  130. self.assertIn(word.encode('utf-8'), word_map)
  131. def BuildLexicon(self):
  132. with self.test_session():
  133. gen_parser_ops.lexicon_builder(task_context=self.context_file).run()
  134. def testCoNLLFormat(self):
  135. self.WriteContext('conll-sentence')
  136. logging.info('Writing conll file to: %s', self.corpus_file)
  137. with open(self.corpus_file, 'w') as f:
  138. f.write((CONLL_DOC1 + u'\n\n' + CONLL_DOC2 + u'\n')
  139. .replace(' ', '\t').encode('utf-8'))
  140. self.ValidateDocuments()
  141. self.BuildLexicon()
  142. self.ValidateTagToCategoryMap()
  143. self.ValidateCharMap()
  144. self.ValidateWordMap()
  145. def testCoNLLFormatExtraNewlinesAndComments(self):
  146. self.WriteContext('conll-sentence')
  147. with open(self.corpus_file, 'w') as f:
  148. f.write((u'\n\n\n' + CONLL_DOC1 + u'\n\n\n' + COMMENTS +
  149. u'\n\n' + CONLL_DOC2).replace(' ', '\t').encode('utf-8'))
  150. self.ValidateDocuments()
  151. self.BuildLexicon()
  152. self.ValidateTagToCategoryMap()
  153. def testTokenizedTextFormat(self):
  154. self.WriteContext('tokenized-text')
  155. with open(self.corpus_file, 'w') as f:
  156. f.write(TOKENIZED_DOCS.encode('utf-8'))
  157. self.ValidateDocuments()
  158. self.BuildLexicon()
  159. def testTokenizedTextFormatExtraNewlines(self):
  160. self.WriteContext('tokenized-text')
  161. with open(self.corpus_file, 'w') as f:
  162. f.write((u'\n\n\n' + TOKENIZED_DOCS + u'\n\n\n').encode('utf-8'))
  163. self.ValidateDocuments()
  164. self.BuildLexicon()
  165. if __name__ == '__main__':
  166. googletest.main()