SystemyDialogowe/NaturalLanguageUnderstanding.py

31 lines
993 B
Python
Raw Normal View History

2021-04-25 23:17:14 +02:00
from UserActType import UserActType
from UserAct import UserAct
2021-05-16 16:56:37 +02:00
import jsgf
2021-04-25 23:17:14 +02:00
class NLU:
def __init__(self):
2021-05-16 16:56:37 +02:00
self.book_grammar = jsgf.parse_grammar_file('book.jsgf')
def get_dialog_act(self, rule):
slots = []
self.get_slots(rule.expansion, slots)
2021-05-16 18:07:23 +02:00
return UserAct(UserActType[rule.name.upper()], slots)
2021-05-16 16:56:37 +02:00
def get_slots(self, expansion, slots):
if expansion.tag != '':
slots.append((expansion.tag, expansion.current_match))
return
for child in expansion.children:
self.get_slots(child, slots)
if not expansion.children and isinstance(expansion, jsgf.NamedRuleRef):
self.get_slots(expansion.referenced_rule.expansion, slots)
2021-04-25 23:17:14 +02:00
2021-05-16 16:56:37 +02:00
def parse_user_input(self, text: str) -> UserAct:
matched_rules = self.book_grammar.find_matching_rules(text)
if matched_rules:
return self.get_dialog_act(matched_rules[0])
2021-05-16 23:11:55 +02:00
return UserAct(UserActType.INVALID, [])