bllip.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. # Natural Language Toolkit: Interface to BLLIP Parser
  2. #
  3. # Author: David McClosky <dmcc@bigasterisk.com>
  4. #
  5. # Copyright (C) 2001-2020 NLTK Project
  6. # URL: <http://nltk.org/>
  7. # For license information, see LICENSE.TXT
  8. from nltk.parse.api import ParserI
  9. from nltk.tree import Tree
  10. """
  11. Interface for parsing with BLLIP Parser. Requires the Python
  12. bllipparser module. BllipParser objects can be constructed with the
  13. ``BllipParser.from_unified_model_dir`` class method or manually using the
  14. ``BllipParser`` constructor. The former is generally easier if you have
  15. a BLLIP Parser unified model directory -- a basic model can be obtained
  16. from NLTK's downloader. More unified parsing models can be obtained with
  17. BLLIP Parser's ModelFetcher (run ``python -m bllipparser.ModelFetcher``
  18. or see docs for ``bllipparser.ModelFetcher.download_and_install_model``).
  19. Basic usage::
  20. # download and install a basic unified parsing model (Wall Street Journal)
  21. # sudo python -m nltk.downloader bllip_wsj_no_aux
  22. >>> from nltk.data import find
  23. >>> model_dir = find('models/bllip_wsj_no_aux').path
  24. >>> bllip = BllipParser.from_unified_model_dir(model_dir)
  25. # 1-best parsing
  26. >>> sentence1 = 'British left waffles on Falklands .'.split()
  27. >>> top_parse = bllip.parse_one(sentence1)
  28. >>> print(top_parse)
  29. (S1
  30. (S
  31. (NP (JJ British) (NN left))
  32. (VP (VBZ waffles) (PP (IN on) (NP (NNP Falklands))))
  33. (. .)))
  34. # n-best parsing
  35. >>> sentence2 = 'Time flies'.split()
  36. >>> all_parses = bllip.parse_all(sentence2)
  37. >>> print(len(all_parses))
  38. 50
  39. >>> print(all_parses[0])
  40. (S1 (S (NP (NNP Time)) (VP (VBZ flies))))
  41. # incorporating external tagging constraints (None means unconstrained tag)
  42. >>> constrained1 = bllip.tagged_parse([('Time', 'VB'), ('flies', 'NNS')])
  43. >>> print(next(constrained1))
  44. (S1 (NP (VB Time) (NNS flies)))
  45. >>> constrained2 = bllip.tagged_parse([('Time', 'NN'), ('flies', None)])
  46. >>> print(next(constrained2))
  47. (S1 (NP (NN Time) (VBZ flies)))
  48. References
  49. ----------
  50. - Charniak, Eugene. "A maximum-entropy-inspired parser." Proceedings of
  51. the 1st North American chapter of the Association for Computational
  52. Linguistics conference. Association for Computational Linguistics,
  53. 2000.
  54. - Charniak, Eugene, and Mark Johnson. "Coarse-to-fine n-best parsing
  55. and MaxEnt discriminative reranking." Proceedings of the 43rd Annual
  56. Meeting on Association for Computational Linguistics. Association
  57. for Computational Linguistics, 2005.
  58. Known issues
  59. ------------
  60. Note that BLLIP Parser is not currently threadsafe. Since this module
  61. uses a SWIG interface, it is potentially unsafe to create multiple
  62. ``BllipParser`` objects in the same process. BLLIP Parser currently
  63. has issues with non-ASCII text and will raise an error if given any.
  64. See http://pypi.python.org/pypi/bllipparser/ for more information
  65. on BLLIP Parser's Python interface.
  66. """
  67. __all__ = ["BllipParser"]
  68. # this block allows this module to be imported even if bllipparser isn't
  69. # available
  70. try:
  71. from bllipparser import RerankingParser
  72. from bllipparser.RerankingParser import get_unified_model_parameters
  73. def _ensure_bllip_import_or_error():
  74. pass
  75. except ImportError as ie:
  76. def _ensure_bllip_import_or_error(ie=ie):
  77. raise ImportError("Couldn't import bllipparser module: %s" % ie)
  78. def _ensure_ascii(words):
  79. try:
  80. for i, word in enumerate(words):
  81. word.decode("ascii")
  82. except UnicodeDecodeError:
  83. raise ValueError(
  84. "Token %d (%r) is non-ASCII. BLLIP Parser "
  85. "currently doesn't support non-ASCII inputs." % (i, word)
  86. )
  87. def _scored_parse_to_nltk_tree(scored_parse):
  88. return Tree.fromstring(str(scored_parse.ptb_parse))
  89. class BllipParser(ParserI):
  90. """
  91. Interface for parsing with BLLIP Parser. BllipParser objects can be
  92. constructed with the ``BllipParser.from_unified_model_dir`` class
  93. method or manually using the ``BllipParser`` constructor.
  94. """
  95. def __init__(
  96. self,
  97. parser_model=None,
  98. reranker_features=None,
  99. reranker_weights=None,
  100. parser_options=None,
  101. reranker_options=None,
  102. ):
  103. """
  104. Load a BLLIP Parser model from scratch. You'll typically want to
  105. use the ``from_unified_model_dir()`` class method to construct
  106. this object.
  107. :param parser_model: Path to parser model directory
  108. :type parser_model: str
  109. :param reranker_features: Path the reranker model's features file
  110. :type reranker_features: str
  111. :param reranker_weights: Path the reranker model's weights file
  112. :type reranker_weights: str
  113. :param parser_options: optional dictionary of parser options, see
  114. ``bllipparser.RerankingParser.RerankingParser.load_parser_options()``
  115. for more information.
  116. :type parser_options: dict(str)
  117. :param reranker_options: optional
  118. dictionary of reranker options, see
  119. ``bllipparser.RerankingParser.RerankingParser.load_reranker_model()``
  120. for more information.
  121. :type reranker_options: dict(str)
  122. """
  123. _ensure_bllip_import_or_error()
  124. parser_options = parser_options or {}
  125. reranker_options = reranker_options or {}
  126. self.rrp = RerankingParser()
  127. self.rrp.load_parser_model(parser_model, **parser_options)
  128. if reranker_features and reranker_weights:
  129. self.rrp.load_reranker_model(
  130. features_filename=reranker_features,
  131. weights_filename=reranker_weights,
  132. **reranker_options
  133. )
  134. def parse(self, sentence):
  135. """
  136. Use BLLIP Parser to parse a sentence. Takes a sentence as a list
  137. of words; it will be automatically tagged with this BLLIP Parser
  138. instance's tagger.
  139. :return: An iterator that generates parse trees for the sentence
  140. from most likely to least likely.
  141. :param sentence: The sentence to be parsed
  142. :type sentence: list(str)
  143. :rtype: iter(Tree)
  144. """
  145. _ensure_ascii(sentence)
  146. nbest_list = self.rrp.parse(sentence)
  147. for scored_parse in nbest_list:
  148. yield _scored_parse_to_nltk_tree(scored_parse)
  149. def tagged_parse(self, word_and_tag_pairs):
  150. """
  151. Use BLLIP to parse a sentence. Takes a sentence as a list of
  152. (word, tag) tuples; the sentence must have already been tokenized
  153. and tagged. BLLIP will attempt to use the tags provided but may
  154. use others if it can't come up with a complete parse subject
  155. to those constraints. You may also specify a tag as ``None``
  156. to leave a token's tag unconstrained.
  157. :return: An iterator that generates parse trees for the sentence
  158. from most likely to least likely.
  159. :param sentence: Input sentence to parse as (word, tag) pairs
  160. :type sentence: list(tuple(str, str))
  161. :rtype: iter(Tree)
  162. """
  163. words = []
  164. tag_map = {}
  165. for i, (word, tag) in enumerate(word_and_tag_pairs):
  166. words.append(word)
  167. if tag is not None:
  168. tag_map[i] = tag
  169. _ensure_ascii(words)
  170. nbest_list = self.rrp.parse_tagged(words, tag_map)
  171. for scored_parse in nbest_list:
  172. yield _scored_parse_to_nltk_tree(scored_parse)
  173. @classmethod
  174. def from_unified_model_dir(
  175. cls, model_dir, parser_options=None, reranker_options=None
  176. ):
  177. """
  178. Create a ``BllipParser`` object from a unified parsing model
  179. directory. Unified parsing model directories are a standardized
  180. way of storing BLLIP parser and reranker models together on disk.
  181. See ``bllipparser.RerankingParser.get_unified_model_parameters()``
  182. for more information about unified model directories.
  183. :return: A ``BllipParser`` object using the parser and reranker
  184. models in the model directory.
  185. :param model_dir: Path to the unified model directory.
  186. :type model_dir: str
  187. :param parser_options: optional dictionary of parser options, see
  188. ``bllipparser.RerankingParser.RerankingParser.load_parser_options()``
  189. for more information.
  190. :type parser_options: dict(str)
  191. :param reranker_options: optional dictionary of reranker options, see
  192. ``bllipparser.RerankingParser.RerankingParser.load_reranker_model()``
  193. for more information.
  194. :type reranker_options: dict(str)
  195. :rtype: BllipParser
  196. """
  197. (
  198. parser_model_dir,
  199. reranker_features_filename,
  200. reranker_weights_filename,
  201. ) = get_unified_model_parameters(model_dir)
  202. return cls(
  203. parser_model_dir,
  204. reranker_features_filename,
  205. reranker_weights_filename,
  206. parser_options,
  207. reranker_options,
  208. )
  209. def demo():
  210. """This assumes the Python module bllipparser is installed."""
  211. # download and install a basic unified parsing model (Wall Street Journal)
  212. # sudo python -m nltk.downloader bllip_wsj_no_aux
  213. from nltk.data import find
  214. model_dir = find("models/bllip_wsj_no_aux").path
  215. print("Loading BLLIP Parsing models...")
  216. # the easiest way to get started is to use a unified model
  217. bllip = BllipParser.from_unified_model_dir(model_dir)
  218. print("Done.")
  219. sentence1 = "British left waffles on Falklands .".split()
  220. sentence2 = "I saw the man with the telescope .".split()
  221. # this sentence is known to fail under the WSJ parsing model
  222. fail1 = "# ! ? : -".split()
  223. for sentence in (sentence1, sentence2, fail1):
  224. print("Sentence: %r" % " ".join(sentence))
  225. try:
  226. tree = next(bllip.parse(sentence))
  227. print(tree)
  228. except StopIteration:
  229. print("(parse failed)")
  230. # n-best parsing demo
  231. for i, parse in enumerate(bllip.parse(sentence1)):
  232. print("parse %d:\n%s" % (i, parse))
  233. # using external POS tag constraints
  234. print(
  235. "forcing 'tree' to be 'NN':",
  236. next(bllip.tagged_parse([("A", None), ("tree", "NN")])),
  237. )
  238. print(
  239. "forcing 'A' to be 'DT' and 'tree' to be 'NNP':",
  240. next(bllip.tagged_parse([("A", "DT"), ("tree", "NNP")])),
  241. )
  242. # constraints don't have to make sense... (though on more complicated
  243. # sentences, they may cause the parse to fail)
  244. print(
  245. "forcing 'A' to be 'NNP':",
  246. next(bllip.tagged_parse([("A", "NNP"), ("tree", None)])),
  247. )
  248. def setup_module(module):
  249. from nose import SkipTest
  250. try:
  251. _ensure_bllip_import_or_error()
  252. except ImportError:
  253. raise SkipTest(
  254. "doctests from nltk.parse.bllip are skipped because "
  255. "the bllipparser module is not installed"
  256. )