telegram-bot-systemy-dialogowe/Modules.py
2021-05-29 10:43:39 +02:00

113 lines
3.1 KiB
Python

import os
import jsgf
#Natural Language Understanding
class NLU:
def __init__(self):
self.grammars = [jsgf.parse_grammar_file(f'JSGFs/{file_name}') for file_name in os.listdir('JSGFs')]
def get_dialog_act(self, rule):
slots = []
self.get_slots(rule.expansion, slots)
return {'act': rule.grammar.name, 'slots': 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 match(self, utterance):
list_of_illegal_character = [',', '.', "'", '?', '!', ':', '-', '/']
for illegal_character in list_of_illegal_character[:-2]:
utterance = utterance.replace(f'{illegal_character}','')
for illegal_character in list_of_illegal_character[-2:]:
utterance = utterance.replace(f'{illegal_character}',' ')
for grammar in self.grammars:
matched = grammar.find_matching_rules(utterance)
if matched:
return self.get_dialog_act(matched[0])
return {'act': 'null', 'slots': []}
#Dialogue policy
class DP:
#Module decide what act takes next
def __init__(self, acts, arguments):
self.acts = acts
self.arguments = arguments
def tacticChoice(self, frame_list):
actVector = [0, 0]
return actVector
#Dialogue State Tracker
class DST:
#Contain informations about state of the dialogue and data taken from user
def __init__(self, acts, arguments):
self.acts = acts
self.arguments = arguments
self.frameList= []
#store new act into frame
def store(self, frame):
self.frameList.append(frame)
def transfer(self):
return self.frameList
#Natural Language Generator
class NLG:
def __init__(self, acts, arguments):
self.acts = acts
self.arguments = arguments
def vectorToText(self, actVector):
if(actVector == [0, 0]):
return "Witaj, nazywam się Mateusz."
else:
return "Przykro mi, nie zrozumiałem Cię"
class Run:
def __init__(self):
self.acts={
0: "hello",
1: "request",
}
self.arguments={
0: "name"
}
self.nlu = NLU()
self.dp = DP(self.acts, self.arguments)
self.nlg = NLG(self.acts, self.arguments)
self.dst = DST(self.acts, self.arguments)
def inputProcessing(self, command):
act = self.nlu.analyze(command)
self.dst.store(act)
basic_act = self.dp.tacticChoice(self.dst.transfer())
return self.nlg.vectorToText(basic_act)
# run = Run()
# while(1):
# message = input("Napisz coś: ")
# print(run.inputProcessing(message))