Example #1
0
	def replace_colon(self, txt):
		txt = txt.replace('y_pred:\t','')
		spl = list(map(lambda x : x.strip(), txt.split(':')))
		if len(spl) != 2 : return txt # if it has more than 2 colons, just return it as-is
		if spl[0] in spl[1]: txt = '' # if second part contains the key word, remove the key word
		else: txt = '{}(은)는 '.format(spl[0])
		txt += '{}'.format(spl[1])
		txt = pyjosa.replace_josa(txt)
		return txt
Example #2
0
def recordDiary():

    global j
    global word
    global user_id, user_response
    global ending, ask, emotions, noEmotions, final
    global val, session

    ### GET USER INFORMATION
    content = request.get_json()
    user_id = content['userRequest']['user']['id']
    print("Logged in: ", user_id)
    val = j
    session['user_id'] = val

    if j == 1:
        content = request.get_json()
        user_response = content['userRequest']['utterance']
        if len(user_response.split(" ")) > 100:  #100단어 이상 입력
            text = pyjosa.replace_josa(random.choice(ending))  # 일기 종료
            dataSend = {
                "version": "2.0",
                "template": {
                    "outputs": [{
                        "simpleText": {
                            "text": text
                        }
                    }]
                }
            }
            print("stage done=", j)
            j = 1
            val = 0
            time.sleep(0.8)  # sleep for 0.8 sec
            return jsonify(dataSend)
        else:
            text = random.choice(ask)  # 추가 답변 요청
            dataSend = {
                "version": "2.0",
                "template": {
                    "outputs": [{
                        "simpleText": {
                            "text": text
                        }
                    }]
                }
            }
            j = 1
            time.sleep(0.8)  # sleep for 0.8 sec
            return jsonify(dataSend)
Example #3
0
def processDiary():

    global i
    global res, word
    global user_id, user_response
    global ending, requests, emotions, noEmotions, final
    global val, session

    ### GET USER INFORMATION
    content = request.get_json()
    user_id = content['userRequest']['user']['id']
    print("Logged in: ", user_id)
    val = i
    session['user_id'] = val

    ### CONVERSATION
    if 0 < i < 6:
        # loop through cycle for 0 < i < 6
        if i == 1:  # emotional awareness stage
            ### GET EMOTIONS
            content = request.get_json()
            user_response = content['userRequest']['utterance']
            if len(user_response.split(" ")) > 100:  # 100단어 이상 입력할것
                res = json.dumps(sentAnalyze(user_response),
                                 ensure_ascii=False)
                print(res)
                if res is not 'null':  # sentAnalyze에서 리턴하는 것이 string
                    res = res.strip('\"')
                    emotions = [
                        f"오늘의 일기에서 '{res}'(와)과 같은 감정을 찾았어요. 이런 감정은 지금 나의 몸과 마음에 어떤 영향을 주고 있나요?",
                        f"오늘 기록한 내용에서 '{res}'(와)과 같은 감정을 찾을 수 있었어요. 이 감정은 나에게 어떤 변화를 주나요?",
                        f"오늘의 일기에는 '{res}' - 이러한 감정이 있었네요. 이런 감정을 느낄 때 나의 몸과 마음에 주는 영향을 적어 보세요.",
                        f"오늘의 기록에서 '{res}'(와)과 같은 감정을 발견했어요. 이런 감정을 느낄 때 나는 어떤가요?",
                        f"오늘 일기에는 '{res}'(와)과 같은 감정이 있네요. 이 감정을 느낄 때 나의 몸상태와 마음의 반응을 기록해 주세요."
                    ]
                    text = pyjosa.replace_josa(
                        random.choice(emotions))  #감정 돌아보기
                    dataSend = {
                        "version": "2.0",
                        "template": {
                            "outputs": [{
                                "simpleText": {
                                    "text": text
                                }
                            }]
                        }
                    }
                    print("stage done=", i)
                    i += 1
                    time.sleep(0.8)  # sleep for 0.8 sec
                    return jsonify(dataSend)
                else:
                    text = pyjosa.replace_josa(
                        random.choice(noEmotions))  #감정이 없을 때
                    dataSend = {
                        "version": "2.0",
                        "template": {
                            "outputs": [{
                                "simpleText": {
                                    "text": text
                                }
                            }]
                        }
                    }
                    print("stage done=", i)
                    i += 1
                    time.sleep(0.8)  # sleep for 0.8 sec
                    return jsonify(dataSend)

            else:
                text = random.choice(ask)  # 짧으면 추가 답변 요청
                dataSend = {
                    "version": "2.0",
                    "template": {
                        "outputs": [{
                            "simpleText": {
                                "text": text
                            }
                        }]
                    }
                }
                i = 1
                time.sleep(0.8)  # sleep for 0.8 sec
                return jsonify(dataSend)

        elif i == 2:  # first naikan stage
            ### GET KEYWORD
            word = json.dumps(topic(user_response), ensure_ascii=False)
            print(type(word))

            if word is None or word == 'null':  # topic에서 리턴
                first_alt = [
                    "자, 그럼 이제 이 상황에서 내가 할 수 있었던 것을 생각해서 적어 볼게요.",
                    "감정을 들여다보았다면, 이제 이 상황에서 내가 할 수 있었던 것을 적어 볼게요.",
                    "이제 그럼 오늘의 일기를 잠시 성찰해볼게요. 이 상황에서 내가 할 수 있었던 것은 무엇이었을까요?",
                    "자, 오늘 이야기한 것을 토대로 한번 생각해 볼게요. 나는 무엇을 할 수 있었을까요?",
                    "내 감정을 들여다보았다면, 이제 내가 이 상황에서 무엇을 할 수 있었는지 생각해볼게요."
                ]
                text = pyjosa.replace_josa(random.choice(first_alt))
            else:
                print(word)
                word = word.strip('\"')
                first = [
                    f"감정을 들여다보았다면, 이제 오늘의 일기에 등장한 '{word}'에 대해서 좀더 생각해 보았으면 해요. 여태까지 {word}(와)과의 관계에서 내가 받은 것은 무엇일까요?",
                    f"나의 감정을 들여다보았다면, 이제 일기에 등장한 '{word}'에 대해 잠시 성찰해 볼게요. 그동안 {word}(와)과의 관계에서 내가 받은 것은 무엇이 있는지 생각해 보고 적어 주세요.",
                    f"나의 감정을 한번 살펴보았네요. 이제 일기에서 찾은 '{word}'에 대해 좀더 이야기했으면 좋겠어요. 이제까지 {word}(와)과 나의 관계에서 나는 무엇을 받았나요?",
                    f"자, 이제는 일기에 쓴 내용을 토대로 잠시 '{word}'에 대해 생각해 볼게요. 이제껏 내가 {word}(와)과의 관계에서 내가 받은 것이 있다면 무엇일까요?",
                    f"그럼 이제 오늘의 이야기를 바탕으로 '{word}'에 대해 생각해 볼게요. 이제껏 {word}(와)과 지내오면서 이 관계에서 내가 받은 것은 무엇이 있나요?"
                ]
                text = pyjosa.replace_josa(random.choice(first))  # 첫번째 나이칸 실행

            dataSend = {
                "version": "2.0",
                "template": {
                    "outputs": [{
                        "simpleText": {
                            "text": text
                        }
                    }]
                }
            }
            print("stage done=", i)
            i += 1
            time.sleep(0.8)  # sleep for 0.8 sec
            return jsonify(dataSend)

        elif i == 3:  # second naikan stage
            if word is None or word == 'null':
                second_alt = [
                    "그렇다면 이제 내가 할 수 없었던 것을 적어 볼게요.",
                    "음, 그러면 내가 할 수 없었던 것은 무엇일까요?",
                    "그렇다면 내가 할 수 없었던 것은 무엇이었을까요?",
                    "그럼 나의 통제 밖이었던, 내가 할 수 없었던 것은 무엇이었나요?",
                    "그럼 이제 내가 할 수 없었던 일을 적어볼게요."
                ]
                text = pyjosa.replace_josa(random.choice(second_alt))
            else:
                print(word)
                second = [
                    f"그럼 이제 내가 '{word}'에게 사소한 것이라도 주었거나 베푼 것은 무엇인지 적어 볼게요.",
                    f"그렇다면 '{word}'(와)과의 관계에서 내가 준 것은 무엇인가요? 잠시 생각해 보고 적어 주세요.",
                    f"이젠 '{word}'(와)과의 관계에서 내가 노력한 것을 생각해 볼게요. 내가 베풀었던 것은 무엇인지 적어 보세요.",
                    f"그렇다면 나는 '{word}’(와)과의 관계를 위해 무엇을 노력했나요? 사소한 것이라도 괜찮습니다.",
                    f"그럼 '{word}'(와)과의 관계를 위해 내가 헌신하거나 베푼 것은 무엇인가요? 무엇이든 상관없이 적어 주세요."
                ]
                text = pyjosa.replace_josa(random.choice(second))  #두번째 나이칸 실행

            dataSend = {
                "version": "2.0",
                "template": {
                    "outputs": [{
                        "simpleText": {
                            "text": text
                        }
                    }]
                }
            }
            print("stage done=", i)
            i += 1
            time.sleep(0.8)  # sleep for 0.8 sec
            return jsonify(dataSend)

        elif i == 4:  # third naikan stage
            if word is None or word == 'null':
                third_alt = [
                    "그렇다면 이 상황에서 나는 어떻게 대처하는것이 좋았을까요?",
                    "그럼 나는 어떻게 대처하는 것이 가장 현명했을까요?",
                    "다음으로, 나는 어떻게 행동하는 것이 가장 현명했을까요?",
                    "그러면 나는 어떻게 대처하는 것이 가장 현명할까요?",
                    "그렇다면 나는 어떻게 행동하는 것이 가장 현명할까요?"
                ]
                text = pyjosa.replace_josa(random.choice(third_alt))
            else:
                print(word)
                third = [
                    f"그럼 다음 질문을 해 볼게요. 나는 그동안 '{word}'(와)과 지내면서 어떤 크고작은 걱정이나 근심, 또는 곤란함이나 어려움을 주었나요? 천천히 생각해 보세요.",
                    f"그럼 이제 내가 그동안 어떤 것이라도 '{word}'에게 걱정을 끼쳤거나, 힘들게 했거나, 사소한 것이라도 어려움을 주었던 적이  있는지 생각해 볼게요.",
                    f"그렇다면 다른 질문을 해 볼게요. 나는 이제껏 '{word}'에게 어떠한 곤란함이나 걱정, 또는 힘듦을 주었을까요?  사소한 것이라도 좋습니다.",
                    f"그러면 내가 이제껏 지내면서 '{word}'에게 끼친 걱정이나 어려움, 혹은 괴로움이 조금이라도 있었는지 생각해 보고, 무엇이었는지 적어 주세요.",
                    f"자, 그럼 이제 질문을 조금 바꿔 볼게요. 그동안 나는  '{word}'에게 어떤 걱정이나 어려움, 곤란함을 주었을까요? 사소한 것이라도 괜찮으니 생각해 보고 적어 주세요."
                ]
                text = pyjosa.replace_josa(random.choice(third))  # 세번째 나이칸 실행

            dataSend = {
                "version": "2.0",
                "template": {
                    "outputs": [{
                        "simpleText": {
                            "text": text
                        }
                    }]
                }
            }
            print("stage done=", i)
            i += 1
            time.sleep(0.8)  # sleep for 0.8 sec
            return jsonify(dataSend)

        elif i == 5:  # finish
            text = random.choice(final)  # 마지막 한마디 입력
            dataSend = {
                "version": "2.0",
                "template": {
                    "outputs": [{
                        "simpleText": {
                            "text": text
                        }
                    }]
                }
            }
            print("stage done=", i)
            i += 1
            time.sleep(0.8)  # sleep for 0.8 sec
            return jsonify(dataSend)

    else:  # end
        text = random.choice(ending)  # 종료
        dataSend = {
            "version": "2.0",
            "template": {
                "outputs": [{
                    "simpleText": {
                        "text": text
                    }
                }]
            }
        }
        print("stage done=", i)
        i = 1
        val = 0
        time.sleep(0.8)  # sleep for 0.8 sec
        return jsonify(dataSend)
Example #4
0
def racoon_message(request):
    count = 0
    if request.channel == 'CLWDPD2KY':
        if random.randrange(1, 50) > 45 and request.user != 'UECK50ENB' and user_dict[request.user] < 0:
            request.reply(f'고문 해버린다구,@{simple_slack_bot.helper_user_id_to_user_name(request.user)}')

    if request.message:
        recv_msg = request.message
        if recv_msg.find("너굴맨") != -1:

            request_cnt = manage_request_cnt(request.user)
            if simple_slack_bot.helper_user_id_to_user_name(request.user) == 'seha':
                if request_cnt >= 5:
                    request.write(f'아무리 바빠도 주인님의 명령을 무시할수는 없다구')
                threading.Thread(target=manage_cnt_after_time, args=(request.user, 60))
            elif request_cnt > 10:
                threading.Thread(target=manage_cnt_after_time, args=(request.user, 600))
                return
            elif request_cnt == 10:
                threading.Thread(target=manage_cnt_after_time, args=(request.user, 300))
                return request.write(f'@{simple_slack_bot.helper_user_id_to_user_name(request.user)} 괴롭힌다 너굴맨! 너굴맨 무시한다 당신!')
            elif request_cnt >= 5:
                threading.Thread(target=manage_cnt_after_time, args=(request.user, 120))
                return request.write(f'바쁜데 계속 말걸지말라구 @{simple_slack_bot.helper_user_id_to_user_name(request.user)}')
            else:
                threading.Thread(target=manage_cnt_after_time, args=(request.user, 60))

            if recv_msg.find("잘못") != -1 or recv_msg.find("미안") != -1:
                if random.choice([True, False]):
                    return request.write(plus_like_percent(request.user))
                else:
                    return request.write(minus_like_percent(request.user, 1))

            if (recv_msg.find("호감도") != -1 or recv_msg.find("친밀도") != -1) and recv_msg.find("보여") != -1:
                return request.write(get_like_percent(request.user))

            if user_dict.get(request.user) is not None:
                if user_dict[request.user] >= -14:
                    pass
                else:
                    if random.choice([True, False]):
                        return request.write('흥이라구')
                    else:
                        return request.write('싹싹빌라구')

            if recv_msg.find("어디") != -1:
                count += 1
                return request.write(
                    f'너굴맨은 #{simple_slack_bot.helper_channel_id_to_channel_name(request.channel)}에 있다구')

            if recv_msg.find("난") != -1 and recv_msg.find("누구") != -1:
                count += 1
                return request.write(f'@{simple_slack_bot.helper_user_id_to_user_name(request.user)} 라구')

            if recv_msg.find("될까") != -1 \
                    or recv_msg.find("할까") != -1 \
                    or recv_msg.find("있을까") != -1 \
                    or recv_msg.find("갈까") != -1 \
                    or recv_msg.find("살까") != -1:
                if random.choice([True, False]):
                    rst = '응이라구'
                else:
                    rst = "아니라구"

                count += 1
                return request.write(rst)

            if recv_msg.find("미세먼지") != -1:
                count += 1
                return request.write(mise_switch())

            if (recv_msg.find("뭐") != -1 and recv_msg.find("먹을까") != -1) \
                    or recv_msg.find("점심추천") != -1 \
                    or recv_msg.find("뭐먹지") != -1 \
                    or recv_msg.find("배고파") != -1:
                lunch_list = ['와규', '설렁탕', '쌈밥', '김치찌개', '예윤', '이자까야', '플레이티드', '등갈비 찜', '쌀국수', '부대찌개']
                count += 1
                return request.write(random.choice(lunch_list) + ' 어떠냐구')

            if recv_msg.find("처치") != -1:
                count += 1
                if recv_msg.find("사악한") != -1:
                    p = re.compile('사악한 [\u3131-\u3163\uac00-\ud7a3A-Za-z0-9]+ 처치')
                    if len(p.findall(recv_msg)) > 0:
                        re_result = p.findall(recv_msg)[0] \
                            .replace('처치', '') \
                            .replace('사악한', '') \
                            .replace('을', '') \
                            .replace('를', '')
                        if re_result.find('너굴맨') != -1:
                            return request.write(f'너굴맨은 처치할수없다구 널 처치할거라구')
                        elif re_result.find('세하') != -1:
                            return request.write(f'주인님을 처치할수 없다구')
                        else:
                            msg = u'사악한' + re_result + '(은)는 이 너굴맨이 처치했으니 안심하라구!'
                            return request.write(pyjosa.replace_josa(msg))
                    else:
                        return request.write(f'처치해버린다구, @{simple_slack_bot.helper_user_id_to_user_name(request.user)}')
                else:
                    if random.choice([True, False]):
                        return request.write("이 너굴맨이 처치했으니 안심하라구!:racoon_man:")
                    else:
                        return request.write("너굴맨 휴무라구 알아서 하라구")

            if recv_msg.find("도와줘요") != -1:
                count += 1
                msg = '`너굴맨 점심추천해줘, 너굴맨 처치해줘, 너굴맨 미세먼지, 너굴맨 날씨` 를 도와줄수 있다구!'
                return request.write(msg)

            if recv_msg.find("안녕") != -1 and request.user is not None:
                if user_dict[request.user] > 5:
                    user_dict[request.user] += 1
                    return request.write(
                        f"반갑다구 @{simple_slack_bot.helper_user_id_to_user_name(request.user)}:racoon_man:")

                else:
                    user_dict[request.user] += 1
                    return request.write("너-하 라구!")

            if recv_msg.find("안될까") != -1:
                msg = '싫다구'
                count += 1
                return request.write(msg)

            if (recv_msg.find("오늘") != -1
                or recv_msg.find("현재") != -1
                or recv_msg.find("지금") != -1) \
                    and recv_msg.find("날씨") != -1:
                count += 1
                soup = weather_init_soup()
                request.write(get_thermal(soup))
                return request.write(get_weather(soup))

            if recv_msg.find("게임추천") != -1 or recv_msg.find("궨트") != -1:
                count += 1
                if random.choice([True, False]):
                    return request.write('궨트 츄라이해보라구 갓겜이라구:racoon_man:')
                else:
                    return request.write("엥 그거 갓겜아니냐구 갓겜을 쌈에싸서 드셔보시라구:racoon_man:")

            if recv_msg.find("히오스") != -1:
                count += 1
                return request.write('시공의폭풍이라구')

            if recv_msg.find("돌겜") != -1 or recv_msg.find("하스스톤") != -1 \
                    or recv_msg.find("하스") != -1:
                count += 1
                return request.write('돌겜은 너나 하라구')

            if recv_msg.find("지금") != -1 and recv_msg.find("비와") != -1:
                count += 1
                if get_weather(weather_init_soup()).find('비') != -1:
                    return request.write('비가온다구!!')
                else:
                    return request.write('안온다구')

            if recv_msg.find("졸려") != -1 or recv_msg.find("졸립다") != -1:
                count += 1
                if random.choice([True, False]):
                    return request.write('너굴맨도 졸립다구')
                else:
                    return request.write('너굴맨 집가고 싶다구')

            if recv_msg.find("댓글") != -1:
                count += 1
                msg = recv_msg.replace("댓글", "").replace("너굴맨", "")
                return request.reply(msg)

            if recv_msg.find("칭찬해") != -1:
                count += 1
                user_dict[request.user] += 1
                return request.write('잘했다구')

            if count > 1:
                request.write(minus_like_percent(request.user, count))
Example #5
0
def menu():
    # (POST된) JSON 파일 저장
    req = request.get_json()
    # 필요한 키 추출. 키가 없으면 0 리턴 (try..except 대신 get 함수 사용)
    rest_name = req.get("action", {}).get("detailParams",
                                          {}).get("restaurant_name",
                                                  {}).get("value", 0)
    sys_date = req.get("action", {}).get("detailParams",
                                         {}).get("sys_date",
                                                 {}).get("origin", 0)
    sys_timep = req.get("action", {}).get("detailParams",
                                          {}).get("meal_time",
                                                  {}).get("value", 0)

    date_string = "오늘"
    time_string = ""
    notice = ""
    breakfast = {}
    lunch = {}
    dinner = {}

    # 만약 오늘/내일 등이 날짜가 지정되면
    if sys_date != 0:
        if sys_date == "오늘":
            date_string = "오늘"
            breakfast, lunch, dinner = get_menu()
            notice = ""
        elif sys_date == "내일":
            date_string = "내일"
            breakfast, lunch, dinner = get_menu(1)
            notice = ""
        else:
            date_string = "오늘"
            breakfast, lunch, dinner = get_menu()
            notice = "오늘과 내일의 메뉴만 제공합니다.\n"

    # 날짜가 지정되지 않으면
    else:
        date_string = "오늘"
        breakfast, lunch, dinner = get_menu()

    breakfast_menu = breakfast.get(rest_name, 0)
    lunch_menu = lunch.get(rest_name, 0)
    dinner_menu = dinner.get(rest_name, 0)

    menu = ""
    # sys_timep가 0이 아닌 경우, 즉, 아침, 점심, 저녁 등의 키워드가 제공된 경우
    # 해당 시간대의 메뉴를 제공
    if sys_timep != 0:
        if sys_timep in ["아침", "오전", "모닝", "조식"]:
            time_string = "아침"
            if breakfast_menu != 0:
                menu += "\n\n== 아침 ==\n{}".format(breakfast_menu)
        if sys_timep in ["점심", "오후", "중식"]:
            time_string = "점심"
            if lunch_menu != 0:
                menu += "\n\n== 점심 ==\n{}".format(lunch_menu)
        if sys_timep in ["저녁", "밤", "석식"]:
            time_string = "저녁"
            if dinner_menu != 0:
                menu += "\n\n== 저녁 ==\n{}".format(dinner_menu)

        if menu == "":
            answer = pyjosa.replace_josa("{}(은)는 {} {}시간에 쉽니다.".format(
                rest_name, date_string, time_string))
            answer = notice + answer
        else:
            answer = "{} {}의 {}메뉴는 다음과 같습니다.{}".format(date_string, rest_name,
                                                       time_string, menu)
            answer = notice + answer

    # sys_timep가 0인 경우, 즉 아침, 점심, 저녁이 제공되지 않으면
    # 하루 전체 메뉴를 제공.
    else:
        if breakfast_menu != 0:
            menu += "\n\n== 아침 ==\n{}".format(breakfast_menu)
        if lunch_menu != 0:
            menu += "\n\n== 점심 ==\n{}".format(lunch_menu)
        if dinner_menu != 0:
            menu += "\n\n== 저녁 ==\n{}".format(dinner_menu)

        if menu == "":
            answer = pyjosa.replace_josa("{} {}(은)는 쉽니다.".format(
                date_string, rest_name))
            answer = notice + answer
        else:
            answer = "{}의 {} 메뉴는 다음과 같습니다.{}".format(rest_name, date_string,
                                                     menu)
            answer = notice + answer

    # 답변을 위한 JSON
    res = {
        "version": "2.0",
        "template": {
            "outputs": [{
                "simpleText": {
                    "text": answer
                }
            }]
        }
    }
    return jsonify(res)
Example #6
0
        text = self.post_process(text)
        return text

    def xlsx2script(self, xlsx):
        load_wb = load_workbook(xlsx, data_only=True)
        load_ws = load_wb.active

        if load_ws.title + '_notex' in load_wb.sheetnames:
            save_ws = load_wb[load_ws.title + '_notex']
        else:
            save_ws = load_wb.create_sheet(load_ws.title + '_notex')
        for row_id, row in enumerate(load_ws.rows):
            for collumn_id, collumn in enumerate(row):
                raw_text = collumn.value
                if raw_text is not None: 
                    save_ws.cell(row_id+1, collumn_id+1, self.text2script(raw_text))

        load_wb.save(xlsx)
        print('저장완료...')

                
if __name__ == '__main__':
    
    tcs = open('test_cases.txt','rt',encoding='utf8') 

    for idx,tc in enumerate(tcs):
        sample = Eq2Script().text2script(tc)
        sample = pyjosa.replace_josa(sample)
        print('({}){}'.format(idx+1,sample))