SystemyDialogowe/NaturalLanguageUnderstanding.py

32 lines
1.0 KiB
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)
print(rule.grammar.name)
return UserAct(UserActType.valueOf(rule.grammar.name.upper()), slots)
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-04-25 23:17:14 +02:00
return UserAct(UserActType.INVALID)