GOATS/NaturalLanguageAnalyzer.py

36 lines
1.1 KiB
Python
Raw Normal View History

2024-04-23 13:04:36 +02:00
import jsgf
class NaturalLanguageAnalyzer:
2024-04-23 13:04:36 +02:00
# def process(self, text):
# user_act = None
# if ("imie" in text or "imię" in text) and "?" in text:
# user_act = "request(firstname)"
# return user_act
def process(self, text):
2024-04-30 00:10:20 +02:00
with open('grammar_1.jsgf', 'r', encoding='utf-8') as f:
2024-04-23 13:04:36 +02:00
content = f.read()
book_grammar = jsgf.parse_grammar_string(content)
matched = book_grammar.find_matching_rules(text)
if matched:
return self.get_dialog_act(matched[0])
else:
return {'act': 'null', '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)
def get_dialog_act(self, rule):
slots = []
self.get_slots(rule.expansion, slots)
return {'act': rule.grammar.name, 'slots': slots}