2023-05-03 21:42:35 +02:00
|
|
|
import jsgf
|
2023-05-03 21:59:32 +02:00
|
|
|
from pathlib import Path
|
|
|
|
import os
|
2023-05-03 21:42:35 +02:00
|
|
|
|
2023-05-03 21:59:32 +02:00
|
|
|
__location__ = Path().resolve()
|
|
|
|
|
2023-05-04 12:58:32 +02:00
|
|
|
book_grammar = jsgf.parse_grammar_file(os.path.join(__location__, "grammar3.jsgf"))
|
2023-05-03 21:42:35 +02:00
|
|
|
book_grammar
|
|
|
|
|
|
|
|
|
|
|
|
def get_dialog_act(rule):
|
|
|
|
slots = []
|
|
|
|
get_slots(rule.expansion, slots)
|
|
|
|
return {'act': rule.grammar.name, 'slots': slots}
|
|
|
|
|
|
|
|
def get_slots(expansion, slots):
|
|
|
|
if expansion.tag != '':
|
|
|
|
slots.append((expansion.tag, expansion.current_match))
|
|
|
|
return
|
|
|
|
|
|
|
|
for child in expansion.children:
|
|
|
|
get_slots(child, slots)
|
|
|
|
|
|
|
|
if not expansion.children and isinstance(expansion, jsgf.NamedRuleRef):
|
|
|
|
get_slots(expansion.referenced_rule.expansion, slots)
|
|
|
|
|
|
|
|
def nlu(utterance):
|
|
|
|
matched = book_grammar.find_matching_rules(utterance)
|
|
|
|
|
|
|
|
if matched:
|
|
|
|
return get_dialog_act(matched[0])
|
|
|
|
else:
|
|
|
|
return {'act': 'null', 'slots': []}
|
|
|
|
|
|
|
|
|
2023-05-04 17:30:47 +02:00
|
|
|
def predict(utterance):
|
|
|
|
utterance = utterance.lower()
|
|
|
|
punctuation = '''!;:/?,.'''
|
2023-05-03 21:42:35 +02:00
|
|
|
|
2023-05-04 17:30:47 +02:00
|
|
|
for i in utterance:
|
|
|
|
if i in punctuation:
|
|
|
|
utterance = utterance.replace(i, "")
|
2023-05-04 16:31:38 +02:00
|
|
|
|
2023-05-04 16:41:47 +02:00
|
|
|
|
2023-05-04 17:30:47 +02:00
|
|
|
matched = book_grammar.find_matching_rules(utterance)
|
|
|
|
nlu(utterance)
|
2023-05-04 15:28:41 +02:00
|
|
|
|
2023-05-04 17:30:47 +02:00
|
|
|
try:
|
|
|
|
print(get_dialog_act(matched[0]))
|
|
|
|
except:
|
|
|
|
pass
|
2023-05-03 21:42:35 +02:00
|
|
|
|
2023-05-04 17:30:47 +02:00
|
|
|
return matched
|