This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

346 行
12 KiB

  1. """This module implements a CYK parser."""
  2. # Author: https://github.com/ehudt (2018)
  3. #
  4. # Adapted by Erez
  5. from collections import defaultdict
  6. import itertools
  7. from ..exceptions import ParseError
  8. from ..lexer import Token
  9. from ..tree import Tree
  10. from ..grammar import Terminal as T, NonTerminal as NT, Symbol
  11. try:
  12. xrange
  13. except NameError:
  14. xrange = range
  15. def match(t, s):
  16. assert isinstance(t, T)
  17. return t.name == s.type
  18. class Rule(object):
  19. """Context-free grammar rule."""
  20. def __init__(self, lhs, rhs, weight, alias):
  21. super(Rule, self).__init__()
  22. assert isinstance(lhs, NT), lhs
  23. assert all(isinstance(x, NT) or isinstance(x, T) for x in rhs), rhs
  24. self.lhs = lhs
  25. self.rhs = rhs
  26. self.weight = weight
  27. self.alias = alias
  28. def __str__(self):
  29. return '%s -> %s' % (str(self.lhs), ' '.join(str(x) for x in self.rhs))
  30. def __repr__(self):
  31. return str(self)
  32. def __hash__(self):
  33. return hash((self.lhs, tuple(self.rhs)))
  34. def __eq__(self, other):
  35. return self.lhs == other.lhs and self.rhs == other.rhs
  36. def __ne__(self, other):
  37. return not (self == other)
  38. class Grammar(object):
  39. """Context-free grammar."""
  40. def __init__(self, rules):
  41. self.rules = frozenset(rules)
  42. def __eq__(self, other):
  43. return self.rules == other.rules
  44. def __str__(self):
  45. return '\n' + '\n'.join(sorted(repr(x) for x in self.rules)) + '\n'
  46. def __repr__(self):
  47. return str(self)
  48. # Parse tree data structures
  49. class RuleNode(object):
  50. """A node in the parse tree, which also contains the full rhs rule."""
  51. def __init__(self, rule, children, weight=0):
  52. self.rule = rule
  53. self.children = children
  54. self.weight = weight
  55. def __repr__(self):
  56. return 'RuleNode(%s, [%s])' % (repr(self.rule.lhs), ', '.join(str(x) for x in self.children))
  57. class Parser(object):
  58. """Parser wrapper."""
  59. def __init__(self, rules):
  60. super(Parser, self).__init__()
  61. self.orig_rules = {rule: rule for rule in rules}
  62. rules = [self._to_rule(rule) for rule in rules]
  63. self.grammar = to_cnf(Grammar(rules))
  64. def _to_rule(self, lark_rule):
  65. """Converts a lark rule, (lhs, rhs, callback, options), to a Rule."""
  66. assert isinstance(lark_rule.origin, NT)
  67. assert all(isinstance(x, Symbol) for x in lark_rule.expansion)
  68. return Rule(
  69. lark_rule.origin, lark_rule.expansion,
  70. weight=lark_rule.options.priority if lark_rule.options.priority else 0,
  71. alias=lark_rule)
  72. def parse(self, tokenized, start): # pylint: disable=invalid-name
  73. """Parses input, which is a list of tokens."""
  74. assert start
  75. start = NT(start)
  76. table, trees = _parse(tokenized, self.grammar)
  77. # Check if the parse succeeded.
  78. if all(r.lhs != start for r in table[(0, len(tokenized) - 1)]):
  79. raise ParseError('Parsing failed.')
  80. parse = trees[(0, len(tokenized) - 1)][start]
  81. return self._to_tree(revert_cnf(parse))
  82. def _to_tree(self, rule_node):
  83. """Converts a RuleNode parse tree to a lark Tree."""
  84. orig_rule = self.orig_rules[rule_node.rule.alias]
  85. children = []
  86. for child in rule_node.children:
  87. if isinstance(child, RuleNode):
  88. children.append(self._to_tree(child))
  89. else:
  90. assert isinstance(child.name, Token)
  91. children.append(child.name)
  92. t = Tree(orig_rule.origin, children)
  93. t.rule=orig_rule
  94. return t
  95. def print_parse(node, indent=0):
  96. if isinstance(node, RuleNode):
  97. print(' ' * (indent * 2) + str(node.rule.lhs))
  98. for child in node.children:
  99. print_parse(child, indent + 1)
  100. else:
  101. print(' ' * (indent * 2) + str(node.s))
  102. def _parse(s, g):
  103. """Parses sentence 's' using CNF grammar 'g'."""
  104. # The CYK table. Indexed with a 2-tuple: (start pos, end pos)
  105. table = defaultdict(set)
  106. # Top-level structure is similar to the CYK table. Each cell is a dict from
  107. # rule name to the best (lightest) tree for that rule.
  108. trees = defaultdict(dict)
  109. # Populate base case with existing terminal production rules
  110. for i, w in enumerate(s):
  111. for terminal, rules in g.terminal_rules.items():
  112. if match(terminal, w):
  113. for rule in rules:
  114. table[(i, i)].add(rule)
  115. if (rule.lhs not in trees[(i, i)] or
  116. rule.weight < trees[(i, i)][rule.lhs].weight):
  117. trees[(i, i)][rule.lhs] = RuleNode(rule, [T(w)], weight=rule.weight)
  118. # Iterate over lengths of sub-sentences
  119. for l in xrange(2, len(s) + 1):
  120. # Iterate over sub-sentences with the given length
  121. for i in xrange(len(s) - l + 1):
  122. # Choose partition of the sub-sentence in [1, l)
  123. for p in xrange(i + 1, i + l):
  124. span1 = (i, p - 1)
  125. span2 = (p, i + l - 1)
  126. for r1, r2 in itertools.product(table[span1], table[span2]):
  127. for rule in g.nonterminal_rules.get((r1.lhs, r2.lhs), []):
  128. table[(i, i + l - 1)].add(rule)
  129. r1_tree = trees[span1][r1.lhs]
  130. r2_tree = trees[span2][r2.lhs]
  131. rule_total_weight = rule.weight + r1_tree.weight + r2_tree.weight
  132. if (rule.lhs not in trees[(i, i + l - 1)]
  133. or rule_total_weight < trees[(i, i + l - 1)][rule.lhs].weight):
  134. trees[(i, i + l - 1)][rule.lhs] = RuleNode(rule, [r1_tree, r2_tree], weight=rule_total_weight)
  135. return table, trees
  136. # This section implements context-free grammar converter to Chomsky normal form.
  137. # It also implements a conversion of parse trees from its CNF to the original
  138. # grammar.
  139. # Overview:
  140. # Applies the following operations in this order:
  141. # * TERM: Eliminates non-solitary terminals from all rules
  142. # * BIN: Eliminates rules with more than 2 symbols on their right-hand-side.
  143. # * UNIT: Eliminates non-terminal unit rules
  144. #
  145. # The following grammar characteristics aren't featured:
  146. # * Start symbol appears on RHS
  147. # * Empty rules (epsilon rules)
  148. class CnfWrapper(object):
  149. """CNF wrapper for grammar.
  150. Validates that the input grammar is CNF and provides helper data structures.
  151. """
  152. def __init__(self, grammar):
  153. super(CnfWrapper, self).__init__()
  154. self.grammar = grammar
  155. self.rules = grammar.rules
  156. self.terminal_rules = defaultdict(list)
  157. self.nonterminal_rules = defaultdict(list)
  158. for r in self.rules:
  159. # Validate that the grammar is CNF and populate auxiliary data structures.
  160. assert isinstance(r.lhs, NT), r
  161. if len(r.rhs) not in [1, 2]:
  162. raise ParseError("CYK doesn't support empty rules")
  163. if len(r.rhs) == 1 and isinstance(r.rhs[0], T):
  164. self.terminal_rules[r.rhs[0]].append(r)
  165. elif len(r.rhs) == 2 and all(isinstance(x, NT) for x in r.rhs):
  166. self.nonterminal_rules[tuple(r.rhs)].append(r)
  167. else:
  168. assert False, r
  169. def __eq__(self, other):
  170. return self.grammar == other.grammar
  171. def __repr__(self):
  172. return repr(self.grammar)
  173. class UnitSkipRule(Rule):
  174. """A rule that records NTs that were skipped during transformation."""
  175. def __init__(self, lhs, rhs, skipped_rules, weight, alias):
  176. super(UnitSkipRule, self).__init__(lhs, rhs, weight, alias)
  177. self.skipped_rules = skipped_rules
  178. def __eq__(self, other):
  179. return isinstance(other, type(self)) and self.skipped_rules == other.skipped_rules
  180. __hash__ = Rule.__hash__
  181. def build_unit_skiprule(unit_rule, target_rule):
  182. skipped_rules = []
  183. if isinstance(unit_rule, UnitSkipRule):
  184. skipped_rules += unit_rule.skipped_rules
  185. skipped_rules.append(target_rule)
  186. if isinstance(target_rule, UnitSkipRule):
  187. skipped_rules += target_rule.skipped_rules
  188. return UnitSkipRule(unit_rule.lhs, target_rule.rhs, skipped_rules,
  189. weight=unit_rule.weight + target_rule.weight, alias=unit_rule.alias)
  190. def get_any_nt_unit_rule(g):
  191. """Returns a non-terminal unit rule from 'g', or None if there is none."""
  192. for rule in g.rules:
  193. if len(rule.rhs) == 1 and isinstance(rule.rhs[0], NT):
  194. return rule
  195. return None
  196. def _remove_unit_rule(g, rule):
  197. """Removes 'rule' from 'g' without changing the langugage produced by 'g'."""
  198. new_rules = [x for x in g.rules if x != rule]
  199. refs = [x for x in g.rules if x.lhs == rule.rhs[0]]
  200. new_rules += [build_unit_skiprule(rule, ref) for ref in refs]
  201. return Grammar(new_rules)
  202. def _split(rule):
  203. """Splits a rule whose len(rhs) > 2 into shorter rules."""
  204. rule_str = str(rule.lhs) + '__' + '_'.join(str(x) for x in rule.rhs)
  205. rule_name = '__SP_%s' % (rule_str) + '_%d'
  206. yield Rule(rule.lhs, [rule.rhs[0], NT(rule_name % 1)], weight=rule.weight, alias=rule.alias)
  207. for i in xrange(1, len(rule.rhs) - 2):
  208. yield Rule(NT(rule_name % i), [rule.rhs[i], NT(rule_name % (i + 1))], weight=0, alias='Split')
  209. yield Rule(NT(rule_name % (len(rule.rhs) - 2)), rule.rhs[-2:], weight=0, alias='Split')
  210. def _term(g):
  211. """Applies the TERM rule on 'g' (see top comment)."""
  212. all_t = {x for rule in g.rules for x in rule.rhs if isinstance(x, T)}
  213. t_rules = {t: Rule(NT('__T_%s' % str(t)), [t], weight=0, alias='Term') for t in all_t}
  214. new_rules = []
  215. for rule in g.rules:
  216. if len(rule.rhs) > 1 and any(isinstance(x, T) for x in rule.rhs):
  217. new_rhs = [t_rules[x].lhs if isinstance(x, T) else x for x in rule.rhs]
  218. new_rules.append(Rule(rule.lhs, new_rhs, weight=rule.weight, alias=rule.alias))
  219. new_rules.extend(v for k, v in t_rules.items() if k in rule.rhs)
  220. else:
  221. new_rules.append(rule)
  222. return Grammar(new_rules)
  223. def _bin(g):
  224. """Applies the BIN rule to 'g' (see top comment)."""
  225. new_rules = []
  226. for rule in g.rules:
  227. if len(rule.rhs) > 2:
  228. new_rules += _split(rule)
  229. else:
  230. new_rules.append(rule)
  231. return Grammar(new_rules)
  232. def _unit(g):
  233. """Applies the UNIT rule to 'g' (see top comment)."""
  234. nt_unit_rule = get_any_nt_unit_rule(g)
  235. while nt_unit_rule:
  236. g = _remove_unit_rule(g, nt_unit_rule)
  237. nt_unit_rule = get_any_nt_unit_rule(g)
  238. return g
  239. def to_cnf(g):
  240. """Creates a CNF grammar from a general context-free grammar 'g'."""
  241. g = _unit(_bin(_term(g)))
  242. return CnfWrapper(g)
  243. def unroll_unit_skiprule(lhs, orig_rhs, skipped_rules, children, weight, alias):
  244. if not skipped_rules:
  245. return RuleNode(Rule(lhs, orig_rhs, weight=weight, alias=alias), children, weight=weight)
  246. else:
  247. weight = weight - skipped_rules[0].weight
  248. return RuleNode(
  249. Rule(lhs, [skipped_rules[0].lhs], weight=weight, alias=alias), [
  250. unroll_unit_skiprule(skipped_rules[0].lhs, orig_rhs,
  251. skipped_rules[1:], children,
  252. skipped_rules[0].weight, skipped_rules[0].alias)
  253. ], weight=weight)
  254. def revert_cnf(node):
  255. """Reverts a parse tree (RuleNode) to its original non-CNF form (Node)."""
  256. if isinstance(node, T):
  257. return node
  258. # Reverts TERM rule.
  259. if node.rule.lhs.name.startswith('__T_'):
  260. return node.children[0]
  261. else:
  262. children = []
  263. for child in map(revert_cnf, node.children):
  264. # Reverts BIN rule.
  265. if isinstance(child, RuleNode) and child.rule.lhs.name.startswith('__SP_'):
  266. children += child.children
  267. else:
  268. children.append(child)
  269. # Reverts UNIT rule.
  270. if isinstance(node.rule, UnitSkipRule):
  271. return unroll_unit_skiprule(node.rule.lhs, node.rule.rhs,
  272. node.rule.skipped_rules, children,
  273. node.rule.weight, node.rule.alias)
  274. else:
  275. return RuleNode(node.rule, children)