Example #1
0
def webhook_attachment_location_processing(recipient_id, params):

    if redis_client.hget(recipient_id, "hazard_chat_status") is None:
        return
    elif redis_client.hget(recipient_id, "hazard_chat_status") == "end":
        return

    # 判断是否发送的是位置附件app
    elif 'attachments' in params["entry"][0]["messaging"][0]['message'].keys():

        info = location_processing(
            recipient_id,
            params["entry"][0]["messaging"][0]['message']['attachments'][0])
        if info is not None:

            if type(info) == "string":
                webhook_response_message(recipient_id, info)
                return

            add_value_location(recipient_id, info["title"])

            response = "Got the location : " + info["title"] +\
                       "\nAddress: "+info['address_detail']

            webhook_response_message(recipient_id, response)

            # 检查一下时间
            check_element_date(recipient_id)

            return
Example #2
0
def webhook_msg_entry(recipient_id, text):

    question_seq = redis_client.hget(recipient_id, "question_seq")

    if question_seq is None:
        return

    #
    if question_seq == "1":

        all_text = []
        all_text.append(text)

        res = searching_req_ask(recipient_id, all_text)

        webhook_response_message(recipient_id, res)

        # 第一个问题回答完成
        redis_client.hset(recipient_id, "question_seq", "2")
    elif question_seq == "2" and \
        redis_client.hget(recipient_id, "date") is not None and\
        redis_client.hget(recipient_id, "location") is not None:

        res = searching_resp_time_location(recipient_id)
        if res is not None:
            if len(res) != 0:
                for resp in res:
                    webhook_response_message(recipient_id, resp)
                # 意味着hazard对话已经结束
                redis_client.hset(recipient_id, "hazard_chat_status", "end")

                # 结束问题
                redis_client.hset(recipient_id, "question_seq", "0")
Example #3
0
def add_value_location(recipient_id,location):
    if not redis_client.hexists(recipient_id, "location"):

        # 如果已经已经有的话更新,没有就创建
        redis_client.hset(recipient_id, "location", json.dumps({"title": location}))
    else:
        info = redis_client.hget(recipient_id, "location")

        dict = json.loads(info)

        # 直接更新data
        dict['title'] = location

        redis_client.hset(recipient_id, "location", json.dumps(dict))
Example #4
0
def webhook_nlp_location_processing(recipient_id, params):

    nlp = params["entry"][0]["messaging"][0]['message']['nlp']

    if 'entities' not in nlp.keys():
        return

    if redis_client.hget(recipient_id, "hazard_chat_status") is None:
        return
    elif redis_client.hget(recipient_id, "hazard_chat_status") == "end":
        return

    if 'location' not in nlp["entities"].keys() and \
        redis_client.hget(recipient_id,"hazard_chat_status") == "start":
        check_element_location(recipient_id)
        return
        # 只要开始了对话就必须先提供时间日期

    # 不止一个地区结果
    # 目前默认为1个地区结果
    if len(nlp["entities"]['location']) != 1:
        response = "This system is not support multi-location."
        webhook_response_message(recipient_id, response)
        return

    response = ""
    if 'resolved' not in nlp["entities"]['location'][0]:

        # 可以拿到准确的位置信息
        if 'suggested' in nlp["entities"]['location'][0].keys():

            if nlp["entities"]['location'][0]['suggested']:

                location = nlp["entities"]['location'][0]['value']

                add_value_location(recipient_id, location)

                response = "Got the location : " + location

    elif len(nlp["entities"]['location'][0]['resolved']['values']) != 1:

        # 详细信息可以用下面的进一步取
        all_prob_location = ""

        for val in nlp["entities"]['location'][0]['resolved']['values']:
            if 'external' in val.keys():
                if 'wikipedia' in val['external'].keys():
                    all_prob_location = all_prob_location + "\n\t" + val[
                        'external']['wikipedia']
                else:
                    all_prob_location = all_prob_location + "\n\t" + val['name']

        location = nlp["entities"]['location'][0]["value"]
        add_value_location(recipient_id, location)
        response = "Got the location : " + location
        webhook_response_message(recipient_id, response)
        response = "\nAll relative location bask on your mentioned " + nlp[
            "entities"]['location'][0][
                'value'] + " you can input the full name next time." + all_prob_location

    webhook_response_message(recipient_id, response)
Example #5
0
def check_element_location(recipient_id):
    if redis_client.hget(recipient_id, "location") is None:
        response = "Could you tell me the location ?"
        webhook_response_message(recipient_id, response)
    return
Example #6
0
def check_element_date(recipient_id):
    if redis_client.hget(recipient_id, "date") is None:
        response = "Could you tell me about the date or period of date ?"
        webhook_response_message(recipient_id, response)
    return
Example #7
0
def webhook_nlp_datetime_processing(recipient_id, nlp):

    if 'entities' not in nlp.keys():
        return

    if redis_client.hget(recipient_id, "hazard_chat_status") is None:
        return
    elif redis_client.hget(recipient_id, "hazard_chat_status") == "end":
        return

    # 只要开始了对话就必须先提供时间日期
    if 'datetime' not in nlp["entities"].keys() and \
        redis_client.hget(recipient_id,"hazard_chat_status") == "start":
        check_element_date(recipient_id)
        return

    # 目前只支持一个datetime
    # if len(nlp["entities"]["datetime"]) > 1:
    #     response = "How only suport one datatime in one message."
    #     webhook_response_message(recipient_id, response)
    #     return

    # 判断类型
    if 'type' in nlp["entities"]["datetime"][0]:

        response = ""

        # 指定日期以及 今天明天昨天关键词
        if nlp["entities"]["datetime"][0]["type"] == "value":

            if 'value' in nlp["entities"]["datetime"][0]:

                date = nlp["entities"]["datetime"][0]['value'].split('T')[0]

                if not redis_client.hexists(recipient_id, "date"):

                    # 如果已经已经有的话更新,没有就创建
                    redis_client.hset(
                        recipient_id, "date",
                        json.dumps({
                            "value": date,
                            "type": "value"
                        }))
                else:
                    info = redis_client.hget(recipient_id, "date")

                    dict = json.loads(info)

                    # 直接更新data
                    dict['value'] = date
                    dict['type'] = "value"

                    redis_client.hset(recipient_id, "date", json.dumps(dict))

                    response = "Got the date : " + date

        # 一段时间 目前只支持输入 from 。。。  to ...
        if nlp["entities"]["datetime"][0]["type"] == "interval":

            if 'from' in nlp["entities"]["datetime"][0] and 'to' in nlp[
                    "entities"]["datetime"][0]:

                # 当前只取date
                date_from = nlp["entities"]["datetime"][0]["from"][
                    "value"].split('T')[0]

                date_to = nlp["entities"]["datetime"][0]["to"]["value"].split(
                    'T')[0]

                if not redis_client.hexists(recipient_id, "date"):

                    # 如果已经已经有的话更新,没有就创建
                    redis_client.hset(
                        recipient_id, "date",
                        json.dumps({
                            "from": date_from,
                            "to": date_to,
                            "type": "interval"
                        }))
                else:
                    info = redis_client.hget(recipient_id, "date")

                    dict = json.loads(info)

                    # 直接更新data
                    dict['from'] = date_from
                    dict['to'] = date_to
                    dict['type'] = "interval"

                    redis_client.hset(recipient_id, "date", json.dumps(dict))

                    response = "Got the period of date : from " + date_from + " to " + date_to

        webhook_response_message(recipient_id, response)
Example #8
0
def facebook_webhook_post():

    params = request.json

    print(params)

    locker.acquire()
    # 目前演示的都为取第0个  日后可能有问题
    if "entry" in params.keys():

        if "messaging" in params["entry"][0].keys():

            if 'read' in params["entry"][0]["messaging"][0].keys():

                if 'seq' in params["entry"][0]["messaging"][0]['read'].keys():

                    # 目前认为序列号为0的时候回执消息
                    if params["entry"][0]["messaging"][0]['read']['seq'] == 0:
                        return "EVENT_RECEIVED", 200

            if 'message' in params["entry"][0]["messaging"][0].keys():

                if 'is_echo' not in params["entry"][0]["messaging"][0]['message'].keys():

                    recipient_id = params["entry"][0]["messaging"][0]["sender"]["id"]

                    if "text" in params["entry"][0]["messaging"][0]["message"].keys():


                        # 分析nlp的结果
                        if 'nlp' not in params["entry"][0]["messaging"][0]['message'].keys():
                            logger.error("Can not solved the message because without nlp element.")

                            return "EVENT_RECEIVED", 200

                        # 获得文本
                        text = params["entry"][0]["messaging"][0]["message"]["text"]

                        redis_client.hset(recipient_id, "user_input_text",text)

                        # 首先判断是不是询问hazard并且是疑问句
                        tag = webhook_nlp_question_processing(recipient_id,params["entry"][0]["messaging"][0]['message']['nlp'])

                        if redis_client.hget(recipient_id,"hazard_chat_status") is None:
                            if tag is None or tag != 1:
                                if 'entities' in params["entry"][0]["messaging"][0]['message']['nlp'].keys():
                                    # 强制是判断时间或者位置的消息
                                    if 'datetime' not in params["entry"][0]["messaging"][0]['message']['nlp']['entities'].keys() \
                                            and 'location' not in params["entry"][0]["messaging"][0]['message']['nlp']['entities'].keys():
                                        if 'greetings' in params["entry"][0]["messaging"][0]['message']['nlp']['entities'].keys():
                                            if len(params["entry"][0]["messaging"][0]['message']['nlp']['entities']['greetings']) >0:
                                                if 'confidence' in params["entry"][0]["messaging"][0]['message']['nlp']['entities']['greetings'][0]:
                                                    # 目前定0.989 以上为一定是打招呼 , 目前小于0.989 证明输入错误
                                                    if params["entry"][0]["messaging"][0]['message']['nlp']['entities']['greetings'][0]['confidence'] < 0.989:
                                                        response = "I can not understand this now, sorry !"
                                                        webhook_response_message(recipient_id, response)
                                        response = "I can answer question in Landslip domain, and you can ask me some questions like:"
                                        response += "\n\t 1. I saw leanning pole, what kinds of hazard will happen ?"
                                        response += "\n\t 2. The leanning pole happened in London, which hazards will happen ?"
                                        response += "\n\t 3. The New York was happend telephone leaning pole from 03/03/2010 to 21/03/2010, which hazards will happen ?"
                                        webhook_response_message(recipient_id, response)
                            locker.release()
                            return "EVENT_RECEIVED",200

                        # ontology 检索
                        webhook_msg_entry(recipient_id, text)

                        # 取时间
                        webhook_nlp_datetime_processing(recipient_id,params["entry"][0]["messaging"][0]['message']['nlp'])

                        # 取地理位置信息
                        webhook_nlp_location_processing(recipient_id,params)

                        webhook_msg_entry(recipient_id, text)

                    if 'attachments' in params["entry"][0]["messaging"][0]['message'].keys() and \
                        redis_client.hget(recipient_id,"hazard_chat_status") == "start":
                        # 取地理位置信息
                        webhook_attachment_location_processing(recipient_id, params)
                        webhook_msg_entry(recipient_id, redis_client.hget(recipient_id, "user_input_text"))

                    if redis_client.hget(recipient_id, "hazard_chat_status") is not None:
                        if redis_client.hget(recipient_id, "hazard_chat_status") == "end":
                            redis_client.hdel(recipient_id, "hazard_chat_status")
                            redis_client.hdel(recipient_id, "question_seq")
                            redis_client.hdel(recipient_id, "date")
                            redis_client.hdel(recipient_id, "location")
                            redis_client.hdel(recipient_id, "ontology_result_hazards")

    locker.release()
    return "EVENT_RECEIVED",200