senna.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. # encoding: utf-8
  2. # Natural Language Toolkit: Senna Interface
  3. #
  4. # Copyright (C) 2001-2020 NLTK Project
  5. # Author: Rami Al-Rfou' <ralrfou@cs.stonybrook.edu>
  6. # URL: <http://nltk.org/>
  7. # For license information, see LICENSE.TXT
  8. """
  9. A general interface to the SENNA pipeline that supports any of the
  10. operations specified in SUPPORTED_OPERATIONS.
  11. Applying multiple operations at once has the speed advantage. For example,
  12. Senna will automatically determine POS tags if you are extracting named
  13. entities. Applying both of the operations will cost only the time of
  14. extracting the named entities.
  15. The SENNA pipeline has a fixed maximum size of the sentences that it can read.
  16. By default it is 1024 token/sentence. If you have larger sentences, changing
  17. the MAX_SENTENCE_SIZE value in SENNA_main.c should be considered and your
  18. system specific binary should be rebuilt. Otherwise this could introduce
  19. misalignment errors.
  20. The input is:
  21. - path to the directory that contains SENNA executables. If the path is incorrect,
  22. Senna will automatically search for executable file specified in SENNA environment variable
  23. - List of the operations needed to be performed.
  24. - (optionally) the encoding of the input data (default:utf-8)
  25. Note: Unit tests for this module can be found in test/unit/test_senna.py
  26. >>> from nltk.classify import Senna
  27. >>> pipeline = Senna('/usr/share/senna-v3.0', ['pos', 'chk', 'ner'])
  28. >>> sent = 'Dusseldorf is an international business center'.split()
  29. >>> [(token['word'], token['chk'], token['ner'], token['pos']) for token in pipeline.tag(sent)] # doctest: +SKIP
  30. [('Dusseldorf', 'B-NP', 'B-LOC', 'NNP'), ('is', 'B-VP', 'O', 'VBZ'), ('an', 'B-NP', 'O', 'DT'),
  31. ('international', 'I-NP', 'O', 'JJ'), ('business', 'I-NP', 'O', 'NN'), ('center', 'I-NP', 'O', 'NN')]
  32. """
  33. from os import path, sep, environ
  34. from subprocess import Popen, PIPE
  35. from platform import architecture, system
  36. from nltk.tag.api import TaggerI
  37. _senna_url = "http://ml.nec-labs.com/senna/"
  38. class Senna(TaggerI):
  39. SUPPORTED_OPERATIONS = ["pos", "chk", "ner"]
  40. def __init__(self, senna_path, operations, encoding="utf-8"):
  41. self._encoding = encoding
  42. self._path = path.normpath(senna_path) + sep
  43. # Verifies the existence of the executable on the self._path first
  44. # senna_binary_file_1 = self.executable(self._path)
  45. exe_file_1 = self.executable(self._path)
  46. if not path.isfile(exe_file_1):
  47. # Check for the system environment
  48. if "SENNA" in environ:
  49. # self._path = path.join(environ['SENNA'],'')
  50. self._path = path.normpath(environ["SENNA"]) + sep
  51. exe_file_2 = self.executable(self._path)
  52. if not path.isfile(exe_file_2):
  53. raise OSError(
  54. "Senna executable expected at %s or %s but not found"
  55. % (exe_file_1, exe_file_2)
  56. )
  57. self.operations = operations
  58. def executable(self, base_path):
  59. """
  60. The function that determines the system specific binary that should be
  61. used in the pipeline. In case, the system is not known the default senna binary will
  62. be used.
  63. """
  64. os_name = system()
  65. if os_name == "Linux":
  66. bits = architecture()[0]
  67. if bits == "64bit":
  68. return path.join(base_path, "senna-linux64")
  69. return path.join(base_path, "senna-linux32")
  70. if os_name == "Windows":
  71. return path.join(base_path, "senna-win32.exe")
  72. if os_name == "Darwin":
  73. return path.join(base_path, "senna-osx")
  74. return path.join(base_path, "senna")
  75. def _map(self):
  76. """
  77. A method that calculates the order of the columns that SENNA pipeline
  78. will output the tags into. This depends on the operations being ordered.
  79. """
  80. _map = {}
  81. i = 1
  82. for operation in Senna.SUPPORTED_OPERATIONS:
  83. if operation in self.operations:
  84. _map[operation] = i
  85. i += 1
  86. return _map
  87. def tag(self, tokens):
  88. """
  89. Applies the specified operation(s) on a list of tokens.
  90. """
  91. return self.tag_sents([tokens])[0]
  92. def tag_sents(self, sentences):
  93. """
  94. Applies the tag method over a list of sentences. This method will return a
  95. list of dictionaries. Every dictionary will contain a word with its
  96. calculated annotations/tags.
  97. """
  98. encoding = self._encoding
  99. if not path.isfile(self.executable(self._path)):
  100. raise OSError(
  101. "Senna executable expected at %s but not found"
  102. % self.executable(self._path)
  103. )
  104. # Build the senna command to run the tagger
  105. _senna_cmd = [
  106. self.executable(self._path),
  107. "-path",
  108. self._path,
  109. "-usrtokens",
  110. "-iobtags",
  111. ]
  112. _senna_cmd.extend(["-" + op for op in self.operations])
  113. # Serialize the actual sentences to a temporary string
  114. _input = "\n".join((" ".join(x) for x in sentences)) + "\n"
  115. if isinstance(_input, str) and encoding:
  116. _input = _input.encode(encoding)
  117. # Run the tagger and get the output
  118. p = Popen(_senna_cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
  119. (stdout, stderr) = p.communicate(input=_input)
  120. senna_output = stdout
  121. # Check the return code.
  122. if p.returncode != 0:
  123. raise RuntimeError("Senna command failed! Details: %s" % stderr)
  124. if encoding:
  125. senna_output = stdout.decode(encoding)
  126. # Output the tagged sentences
  127. map_ = self._map()
  128. tagged_sentences = [[]]
  129. sentence_index = 0
  130. token_index = 0
  131. for tagged_word in senna_output.strip().split("\n"):
  132. if not tagged_word:
  133. tagged_sentences.append([])
  134. sentence_index += 1
  135. token_index = 0
  136. continue
  137. tags = tagged_word.split("\t")
  138. result = {}
  139. for tag in map_:
  140. result[tag] = tags[map_[tag]].strip()
  141. try:
  142. result["word"] = sentences[sentence_index][token_index]
  143. except IndexError:
  144. raise IndexError(
  145. "Misalignment error occurred at sentence number %d. Possible reason"
  146. " is that the sentence size exceeded the maximum size. Check the "
  147. "documentation of Senna class for more information."
  148. % sentence_index
  149. )
  150. tagged_sentences[-1].append(result)
  151. token_index += 1
  152. return tagged_sentences
  153. # skip doctests if Senna is not installed
  154. def setup_module(module):
  155. from nose import SkipTest
  156. try:
  157. tagger = Senna("/usr/share/senna-v3.0", ["pos", "chk", "ner"])
  158. except OSError:
  159. raise SkipTest("Senna executable not found")