Ejemplo n.º 1
0
class ChatBot:

    def __init__(self, voc_path, train_dir):
        self.dialog = Dialog()
        self.dialog.load_vocab(voc_path)

        self.model = Seq2Seq(self.dialog.vocab_size)

        self.sess = tf.Session()
        ckpt = tf.train.get_checkpoint_state(train_dir)
        self.model.saver.restore(self.sess, ckpt.model_checkpoint_path)

    def run(self):
        sys.stdout.write("> ")
        sys.stdout.flush()
        line = sys.stdin.readline()

        while line:
            print(self._get_replay(line.strip()))

            sys.stdout.write("\n> ")
            sys.stdout.flush()

            line = sys.stdin.readline()

    def _decode(self, enc_input, dec_input):
        if type(dec_input) is np.ndarray:
            dec_input = dec_input.tolist()

        # TODO: 구글처럼 시퀀스 사이즈에 따라 적당한 버킷을 사용하도록 만들어서 사용하도록
        input_len = int(math.ceil((len(enc_input) + 1) * 1.5))

        enc_input, dec_input, _ = self.dialog.transform(enc_input, dec_input,
                                                        input_len,
                                                        FLAGS.max_decode_len)

        return self.model.predict(self.sess, [enc_input], [dec_input])

    def _get_replay(self, msg):
        enc_input = self.dialog.tokenizer(msg)
        enc_input = self.dialog.tokens_to_ids(enc_input)
        dec_input = []

        # TODO: 구글처럼 Seq2Seq2 모델 안의 RNN 셀을 생성하는 부분에 넣을것
        #       입력값에 따라 디코더셀의 상태를 순차적으로 구성하도록 함
        #       여기서는 최종 출력값을 사용하여 점진적으로 시퀀스를 만드는 방식을 사용
        #       다만 상황에 따라서는 이런 방식이 더 유연할 수도 있을 듯
        curr_seq = 0
        for i in range(FLAGS.max_decode_len):
            outputs = self._decode(enc_input, dec_input)
            if self.dialog.is_eos(outputs[0][curr_seq]):
                break
            elif self.dialog.is_defined(outputs[0][curr_seq]) is not True:
                dec_input.append(outputs[0][curr_seq])
                curr_seq += 1

        reply = self.dialog.decode([dec_input], True)

        return reply
Ejemplo n.º 2
0
class ChatBot:
    def __init__(self, voc_path, train_dir):
        self.dialog = Dialog()
        self.dialog.load_vocab(voc_path)

        self.model = Seq2Seq(self.dialog.vocab_size, output_keep_prob=0.9)
        config = tf.ConfigProto(device_count={'GPU': 1})
        self.sess = tf.Session(config=config)
        #self.sess = tf.Session()
        #pdb.set_trace()
        ckpt = tf.train.get_checkpoint_state(train_dir)
        print(ckpt.model_checkpoint_path)
        self.model.saver.restore(self.sess, ckpt.model_checkpoint_path)

    def run(self):
        sys.stdout.write("> ")
        sys.stdout.flush()
        line = sys.stdin.readline()

        while line:
            print(self._get_replay(line.strip()))

            sys.stdout.write("\n> ")
            sys.stdout.flush()

            line = sys.stdin.readline()

    def _decode(self, enc_input, dec_input):
        if type(dec_input) is np.ndarray:
            dec_input = dec_input.tolist()

        input_len = 20  #int(math.ceil((len(enc_input) + 1) * 1.5))

        enc_forward_input, enc_reverse_input, dec_input, _ = self.dialog.transform(
            enc_input, dec_input, input_len, FLAGS.max_decode_len)

        return self.model.predict(self.sess, [enc_forward_input],
                                  [enc_reverse_input], [dec_input])

###########################################################################################

    def _get_replay(self, msg):  # 실제 Reply(응답) 구성하는 부분
        enc_input = self.dialog.tokenizer(msg)
        enc_input = self.dialog.tokens_to_ids(enc_input)
        dec_input = []

        curr_seq = 0
        for i in range(FLAGS.max_decode_len):
            outputs = self._decode(enc_input, dec_input)
            if self.dialog.is_eos(outputs[0][curr_seq]):
                break
            elif self.dialog.is_defined(outputs[0][curr_seq]) is not True:
                dec_input.append(outputs[0][curr_seq])
                curr_seq += 1

        reply = self.dialog.decode([dec_input], True)

        return reply
Ejemplo n.º 3
0
class ChatBot:
    def __init__(self, voc_path, train_dir):
        self.dialog = Dialog()
        self.dialog.load_vocab(voc_path)

        self.model = Seq2Seq(self.dialog.vocab_size)

        self.sess = tf.Session()
        ckpt = tf.train.get_checkpoint_state(train_dir)
        self.model.saver.restore(self.sess, ckpt.model_checkpoint_path)

    def run(self):
        sys.stdout.write('> ')
        sys.stdout.flush()
        line = sys.stdin.readline()

        while line:
            print(self.get_reply(line.strip()))

            sys.stdout.write('\n> ')
            sys.stdout.fluch()

            line = sys.stdin.readline()

    def decode(self, enc_input, dec_input):
        if type(dec_input) is np.ndarray:
            dec_input = dec_input.tolist()

        input_len = int(math.ceil((len(enc_input) + 1) * 1.5))

        enc_input, dec_input, _ = self.dialog.transform(
            enc_input, dec_input, input_len, FLAGS.max_decode_len)

        return self.model.predict(self.sess, [enc_input], [dec_input])

    def get_reply(self, msg):
        _enc_input = self.dialog.tokenizer(msg)
        enc_input = self.dialog.tokens_to_ids(_enc_input)
        dec_input = []

        curr_seq = 0
        for i in range(FLAGS.max_decode_len):
            outputs = self.decode(enc_input, dec_input)

            if self.dialog.is_eos(outputs[0][curr_seq]):
                break

            elif self.dialog.is_defined(outputs[0][curr_seq]) is not True:
                dec_input.append(outputs[0][curr_seq])
                curr_seq += 1

        reply = self.dialog.decode([dec_input], True)

        return reply
class ChatBot:
    def __init__(self, voc_path, train_dir):
        self.dialog = Dialog()
        self.dialog.load_vocab(voc_path)

        self.model = Seq2Seq(self.dialog.vocab_size)

        self.sess = tf.Session()
        ckpt = tf.train.get_checkpoint_state(train_dir)
        self.model.saver.restore(self.sess, ckpt.model_checkpoint_path)

    def run(self):
        sys.stdout.write("> ")
        sys.stdout.flush()
        line = sys.stdin.readline()

        while line:
            print(self._get_replay(line.strip()))

            sys.stdout.write("\n> ")
            sys.stdout.flush()

            line = sys.stdin.readline()

    def _decode(self, enc_input, dec_input):
        if type(dec_input) is np.ndarray:
            dec_input = dec_input.tolist()

        # TODO: 구글처럼 시퀀스 사이즈에 따라 적당한 버킷을 사용하도록 만들어서 사용하도록
        input_len = int(math.ceil((len(enc_input) + 1) * 1.5))

        enc_input, dec_input, _ = self.dialog.transform(
            enc_input, dec_input, input_len, FLAGS.max_decode_len)

        return self.model.predict(self.sess, [enc_input], [dec_input])

    #메세지 입력 받음
    def _get_replay(self, msg):

        #태깅 함수 호출
        kkma = Kkma()

        # TODO: tokenizer기능 + tagging 기능 까지!
        #       tokenizer 함수 이해.
        #       tokenizer 함수는 여러군데에 적용되기 때문에, new_tokenizer_and_tagging 함수 만들기
        #       new_tokenizer_and_tagging

        # 태깅 이전
        #enc_input = self.dialog.tokenizer(msg)
        #print("입력 값(normal): ", enc_input)

        # 태깅 된 문장 출력
        enc_input = kkma.pos(msg, 22, True)

        n_enc_input = []

        str_enc_input = " ".join(enc_input)

        str_enc_input = re.sub('\w*?/E\w*', '', str_enc_input, 0, re.I | re.S)
        str_enc_input = re.sub('\w*?/J\w*', '', str_enc_input, 0, re.I | re.S)
        str_enc_input = re.sub('\w*?/IC', '', str_enc_input, 0, re.I | re.S)

        n_enc_input = str_enc_input.split()

        print("입력 값(konlpy): ", n_enc_input)

        n_enc_input = self.dialog.tokens_to_ids(
            n_enc_input)  #쪼개진 단어를 인자로 하여 아이디 매기기
        dec_input = []

        # TODO: 구글처럼 Seq2Seq2 모델 안의 RNN 셀을 생성하는 부분에 넣을것
        #       입력값에 따라 디코더셀의 상태를 순차적으로 구성하도록 함
        #       여기서는 최종 출력값을 사용하여 점진적으로 시퀀스를 만드는 방식을 사용
        #       다만 상황에 따라서는 이런 방식이 더 유연할 수도 있을 듯

        curr_seq = 0
        for i in range(FLAGS.max_decode_len):
            outputs = self._decode(n_enc_input, dec_input)
            if self.dialog.is_eos(outputs[0][curr_seq]):
                break
            elif self.dialog.is_defined(outputs[0][curr_seq]) is not True:
                dec_input.append(outputs[0][curr_seq])
                curr_seq += 1

        reply = self.dialog.decode([dec_input], True)

        return reply
Ejemplo n.º 5
0
class ChatBot:
    def __init__(self, voc_path, train_dir):
        self.ciSock = socket(AF_INET, SOCK_STREAM)
        self.ciSock.connect(('127.0.0.1', 5001))
        self.drqaSock = socket(AF_INET, SOCK_STREAM)
        self.drqaSock.connect(('127.0.0.1', 5002))
        print('연결 수립')
        self.dialog = Dialog()
        self.dialog.load_vocab(voc_path)

        self.model = Seq2Seq(self.dialog.vocab_size)

        # self.sess = tf.Session()
        # ckpt = tf.train.get_checkpoint_state(train_dir)
        # self.model.saver.restore(self.sess, ckpt.model_checkpoint_path)

    def predict_intent(self, msg):
        self.ciSock.send(msg.encode('utf-8'))
        res = self.ciSock.recv(1024)
        res = res.decode('utf-8')
        return res

    def predict_drqa(self, msg):
        self.drqaSock.send(msg.encode('utf-8'))
        res = self.drqaSock.recv(1024)
        res = res.decode('utf-8')
        return res

    def run(self):
        sys.stdout.write("> ")
        sys.stdout.flush()
        line = sys.stdin.readline()

        while line:
            print(self._get_replay(line.strip()))

            sys.stdout.write("\n> ")
            sys.stdout.flush()

            line = sys.stdin.readline()

    def run_server(self):
        app = Flask(__name__)

        @app.route('/')
        def home():
            message = request.args.get('message')
            res = self._get_replay(message)
            return res

        app.run()

    def _decode(self, enc_input, dec_input):
        if type(dec_input) is np.ndarray:
            dec_input = dec_input.tolist()

        # TODO: 구글처럼 시퀀스 사이즈에 따라 적당한 버킷을 사용하도록 만들어서 사용하도록
        input_len = int(math.ceil((len(enc_input) + 1) * 1.5))

        enc_input, dec_input, _ = self.dialog.transform(
            enc_input, dec_input, input_len, FLAGS.max_decode_len)

        return self.model.predict(self.sess, [enc_input], [dec_input])

    def _get_replay(self, msg):
        lang = detect(msg)
        translator = Translator()
        if lang != "ko":
            res = translator.translate(msg, dest='ko')
            msg = res.text
        chitclass = self.predict_intent(msg)
        if chitclass == 'what':
            res = translator.translate(msg, dest='en')
            msg = res.text
            reply = self.predict_drqa(msg)
            res = translator.translate(reply, dest=lang)
            reply = res.text
        else:
            enc_input = self.dialog.tokenizer(msg)
            enc_input = self.dialog.tokens_to_ids(enc_input)
            dec_input = []

            # TODO: 구글처럼 Seq2Seq2 모델 안의 RNN 셀을 생성하는 부분에 넣을것
            #       입력값에 따라 디코더셀의 상태를 순차적으로 구성하도록 함
            #       여기서는 최종 출력값을 사용하여 점진적으로 시퀀스를 만드는 방식을 사용
            #       다만 상황에 따라서는 이런 방식이 더 유연할 수도 있을 듯
            curr_seq = 0
            for i in range(FLAGS.max_decode_len):
                outputs = self._decode(enc_input, dec_input)
                if self.dialog.is_eos(outputs[0][curr_seq]):
                    break
                elif self.dialog.is_defined(outputs[0][curr_seq]) is not True:
                    dec_input.append(outputs[0][curr_seq])
                    curr_seq += 1

            reply = self.dialog.decode([dec_input], True)

        if lang != 'ko':
            res = translator.translate(reply, dest=lang)
            reply = res.text

        return reply