示例#1
0
class Bot:
    def __init__(self, cfg_path):
        # constance.
        self.cfg_path = cfg_path
        self.init_sentence = "开场白:1"
        self.retrieve_sentence = "挽回:1"
        self.invite_sentence = "邀约:1"
        self.end_sentence = "结束:1"
        self.latest_response = ""
        self.global_events_cfg_path = os.path.join(self.cfg_path, 'global_events')

        self.conversations = []

        # class instance.
        self.graph = Graph(self.cfg_path, self.init_sentence)
        self.global_events = self._init_global_events()
        self.analyst = Analyst(self.cfg_path)

    def reset(self):
        return copy.deepcopy(self)

    def start(self):
        return self.answer(init=True)

    def answer(self, sentence=None, init=False):
        if not sentence and init:
            """初始化"""
            self.latest_response = self.graph.say(self.init_sentence)
            self.conversations.append([self.latest_response])
            return self.latest_response
        else:
            """global event"""
            event = self.global_events.answer(sentence)
            if event:
                response = self.global_events_action(event)
                self.conversations.append([sentence, response])
                return response
            else:
                """按照流程走"""
                self.latest_response = self.graph.answer(sentence)
                self.conversations.append([sentence, self.latest_response])
                return self.latest_response

    def _init_global_events(self):
        return GlobalEvent(os.path.join(self.global_events_cfg_path, 'global.json'))

    def global_events_action(self, event):
        if event == "不清楚":
            return self.latest_response
        if event == "拒绝":
            return self.graph.say(self.retrieve_sentence)
        if event == "邀约":
            return self.graph.say(self.invite_sentence)
        if event == "结束":
            return self.graph.say(self.end_sentence)

    def get_label(self):
        return self.analyst.analyze(self.conversations)