예제 #1
0
    def __init__(self, name, app_path, nlp=None):
        """
        Args:
            name (str): The name of the server.
            app_path (str): The path of the MindMeld application.
            nlp (NaturalLanguageProcessor): MindMeld NLP component, will try to load from app path
              if None.
        """
        self.app = Flask(name)
        if not nlp:
            self.nlp = NaturalLanguageProcessor(app_path)
            self.nlp.load()
        else:
            self.nlp = nlp
        self.conv = Conversation(nlp=self.nlp, app_path=app_path)
        self.logger = logging.getLogger(__name__)

        @self.app.route("/", methods=["POST"])
        def handle_message():  # pylint: disable=unused-variable
            incoming_msg = request.values.get('Body', '').lower()
            resp = MessagingResponse()
            msg = resp.message()
            response_text = self.conv.say(incoming_msg)[0]
            msg.body(response_text)
            return str(resp)
예제 #2
0
    def reply(message):
        try:
            request_text = message['text']
            username = message['chat']['username'].lower()
        except:
            return

        if username not in conversations:
            conversations[username] = {}
            conversations[username]['data'] = {'username': username}
            conversations[username]['conversation'] = Conversation(
                app=app, context=conversations[username]['data'])

        resps = conversations[username]['conversation'].say(request_text)

        for resp in resps:
            print(username)
            print(request_text)
            history = conversations[username]['conversation'].history
            if history:
                intent = history[0]['request']['intent']
                resp += f"\n[{intent}]"
                if history[0]['request']['entities']:
                    resp += "\nEntities"
                    for e in history[0]['request']['entities']:
                        resp += f"\n{e}"
            logger.write(":::\n".join(
                str(l)
                for l in [timestamp(), username, request_text, resp, LOGEND]))
            print(resp)
            print(LOGEND, end='')
            bot.send_message(message['chat']['id'], resp)
예제 #3
0
class WhatsappBotServer:
    """
    A sample server class for Whatsapp integration with any MindMeld application
    """
    def __init__(self, name, app_path, nlp=None):
        """
        Args:
            name (str): The name of the server.
            app_path (str): The path of the MindMeld application.
            nlp (NaturalLanguageProcessor): MindMeld NLP component, will try to load from app path
              if None.
        """
        self.app = Flask(name)
        if not nlp:
            self.nlp = NaturalLanguageProcessor(app_path)
            self.nlp.load()
        else:
            self.nlp = nlp
        self.conv = Conversation(nlp=self.nlp, app_path=app_path)
        self.logger = logging.getLogger(__name__)

        @self.app.route("/", methods=["POST"])
        def handle_message():  # pylint: disable=unused-variable
            incoming_msg = request.values.get('Body', '').lower()
            resp = MessagingResponse()
            msg = resp.message()

            # to access the individual directive, you can invoke self.conv._app_manager.parse instead
            response_text = self.conv.say(incoming_msg)[0]
            msg.body(response_text)
            return str(resp)

    def run(self, host="localhost", port=7150):
        self.app.run(host=host, port=port)
class TestIntents(unittest.TestCase):
    def setUp(self):
        self.app = app
        self.conversation = Conversation(app=app,
                                         context={'username': '******'})

    def test_hello(self):
        message = "Привітулі!"
        self.conversation.say(message)
        intent = self.conversation.history[0]['request']['intent']
        self.assertEqual(intent, "greet")

    def test_check_balance(self):
        message = "Скільки грошей у мене на рахунку?"
        self.conversation.say(message)
        intent = self.conversation.history[0]['request']['intent']
        self.assertEqual(intent, "check_balance")
예제 #5
0
    def reply(message):
        try:
            username = message['chat']['username'].lower()
        except:
            return

        conversations[username] = {}
        conversations[username]['data'] = {'username': username}
        conversations[username]['conversation'] = Conversation(
            app=app, context=conversations[username]['data'])

        print(f"{username} has new session")
        print("==========================")
        bot.send_message(message['chat']['id'], "")
예제 #6
0
    def __init__(self, name, app_path, nlp=None):
        """
        Args:
            name (str): The name of the server.
            app_path (str): The path of the MindMeld application.
            nlp (NaturalLanguageProcessor): MindMeld NLP component, will try to load from app path
              if None.
        """
        self.firebase = firebaseHelper()
        self.app = Flask(name)
        if not nlp:
            self.nlp = NaturalLanguageProcessor(app_path)
            self.nlp.load()
        else:
            self.nlp = nlp
        self.conv = Conversation(nlp=self.nlp, app_path=app_path)
        self.logger = logging.getLogger(__name__)
        self.url = None

        @self.app.route("/", methods=["POST"])
        def handle_message():  # pylint: disable=unused-variable
            # print(request.values)
            # Getting number from which message came
            id = request.values.get('From', '')
            id = id.split('+')[1]
            # print(request.values) #uncomment this to dif deeper
            exist = self.firebase.existID(id)
            if not exist:
                result = self.firebase.createID(id)

            incoming_msg = request.values.get('Body', '').lower()
            location = {
                'Latitude': request.values.get('Latitude', ''),
                'Longitude': request.values.get('Longitude', '')
            }
            if request.values.get('Latitude', '') and request.values.get('Longitude', ''):
                intent = l_t.getIntent()
                print(intent)
                result = self.firebase.setCurrLocation(location, id)
                resp = MessagingResponse()
                msg = resp.message()
                params = dict(dynamic_resource=dict(id=id))
                if intent == 'loc_for_source':
                    incoming_msg = "source for location"
                elif intent == 'loc_for_hotel':
                    incoming_msg = "location for hotel"
                elif intent == 'loc_for_food':
                    incoming_msg = "location for food"
                else:
                    incoming_msg = "general location"
                try:
                    response_text = self.conv.say(incoming_msg, params=params)[0]
                    messages = response_text.split("~")
                    for msg in messages:
                        if msg:
                            sendMessage(msg, id)
                except IndexError:
                    msg.body("Didn't understand. sorry")
                
            else:
                resp = MessagingResponse()
                msg = resp.message()
                # Used to send dynamic id of the user making query
                params = None
                if nth.getTarget() == None :
                    params = dict(dynamic_resource =dict(id=id)) #Used to send dynamic id of the user making query
                else:
                    params = dict(dynamic_resource =dict(id=id),target_dialogue_state=nth.getTarget())
                try:
                    response_text = self.conv.say(incoming_msg, params=params)[0]
                    messages = response_text.split("~")
                    for msg in messages:
                        if msg:
                            sendMessage(msg, id)
                except IndexError:
                    msg.body("Didn't understand. sorry")
            return str(resp)

        def sendMessage(msg, number):
            # Change the from whatsapp number with your twilio account number
            valid=validators.url(msg)
            if valid :
                self.url = msg
            else:
                if self.url:
                    client.messages.create(body=msg, from_="whatsapp:+14155238886", to="whatsapp:+"+str(number), media_url=[self.url])
                    self.url = None
                else:
                    client.messages.create(body=msg, from_="whatsapp:+14155238886", to="whatsapp:+"+str(number))
예제 #7
0
from collections import Counter, defaultdict

from provider_bot.__init__ import app
from mindmeld.components.dialogue import Conversation

with open('./ intents.json') as intents_file:
    intents = json.loads(intents_file.read())

actual_intents_count = Counter(intents.values())
intents_count = defaultdict(lambda: 0)

true_positive = defaultdict(lambda: 0)
false_positive = defaultdict(lambda: 0)
false_negative = defaultdict(lambda: 0)
for prompt, actual_intent in intents.items():
    conversation = Conversation(app=app, context={'username': '******'})
    conversation.say(prompt)
    intent = conversation.history[0]['request']['intent']
    if intent == actual_intent:
        true_positive[intent] += 1
    else:
        false_positive[intent] += 1
        false_negative[actual_intent] += 1

for intent in actual_intents_count:
    if intent not in true_positive:
        print(f'{intent} is absent!')
    else:
        print(
            f'{intent}: p:{true_positive[intent] / (true_positive[intent] + false_positive[intent])}'
            +
# -*- coding: utf-8 -*-

import os
from flask import Flask
from mindmeld.components import NaturalLanguageProcessor
from mindmeld.components.dialogue import Conversation
from mindmeld.bot import WebexBotServer
from mindmeld import configure_logs

if __name__ == '__main__':

    app = Flask(__name__)

    # Create web hook here: https://developer.webex.com/docs/api/v1/webhooks/create-a-webhook
    WEBHOOK_ID = os.environ.get('WEBHOOK_ID')

    # Create bot access token here: https://developer.webex.com/my-apps/new
    ACCESS_TOKEN = os.environ.get('BOT_ACCESS_TOKEN')

    configure_logs()
    nlp = NaturalLanguageProcessor('.')
    nlp.build()
    conv = Conversation(nlp=nlp, app_path='.')

    server = WebexBotServer(app, WEBHOOK_ID, ACCESS_TOKEN, conv)

    port_number = 8080
    print('Running server on port {}...'.format(port_number))

    server.run(host='localhost', port=port_number)
 def setUp(self):
     self.app = app
     self.conversation = Conversation(app=app,
                                      context={'username': '******'})
예제 #10
0
def send():
    request_body = request.get_json()
    session_id = request_body['session_id']

    if not request_body['session_id'] in conversations:
        user_data = {
            'username': session_id,  # TODO: Need get real name
            'language': 'uk',
            'detected_languages': deque(maxlen=LANGUAGE_CHAIN_LENGTH),
            'language_confirmed': False,
            'message_without_response': None,
            'suggest_change_language': False,
            'aggressive_met': False
        }
        conversation = Conversation(app=app, context=user_data)
        conversations[session_id] = {
            'conversation': conversation,
            'data': user_data
        }

    conversation, data = conversations[session_id][
        'conversation'], conversations[session_id]['data']
    message = request_body['message']

    detected_languages = data['detected_languages']
    lang = detect(message)
    detected_languages.append(lang)

    if data.get('suggest_change_language'):
        change_lang = is_user_confirm(message)
        if change_lang:
            data['language'] = detected_languages[0]
        data['language_confirmed'] = True
        message = data['message_without_response']
        data['message_without_response'] = None
        data['suggest_change_language'] = False
    elif not data['language_confirmed'] and\
            len(detected_languages) == LANGUAGE_CHAIN_LENGTH and detected_languages[0] != data['language'] and \
            all(e == detected_languages[0] for e in detected_languages):
        data['message_without_response'] = message
        data['suggest_change_language'] = True

        conversations[session_id] = {
            'conversation': conversation,
            'data': data
        }
        return jsonify({
            'session_id':
            session_id,
            'response':
            "Змінити мову з {} на {}?".format(data['language'],
                                              detected_languages[0]),
            'from_core':
            True
        })

    if is_aggressive(message):
        if data['aggressive_met']:
            switch_to = conversation.frame.get('current_topic') or 'general'
            conversations[session_id] = {
                'conversation': conversation,
                'data': data
            }
            return jsonify({
                'session_id': session_id,
                'response': "Заспокойтесь, ми з'єднаємо вас з оператором!",
                'from_core': True,
                'switch_to': switch_to
            })
        else:
            data['aggressive_met'] = True
            conversations[session_id] = {
                'conversation': conversation,
                'data': data
            }
            return jsonify({
                'session_id': session_id,
                'response':
                "Заспокойтеся, будь ласка, ми вирішимо вашу проблему.",
                'from_core': True
            })

    conversation.context = data
    response = conversation.say(message)
    data = conversation.context

    intent = conversation.history[0]['request']['intent']
    entities = conversation.history[0]['request']['entities']

    # TODO: Exit on goodbye?
    # if intent == 'goodbye':
    #     del conversations[session_id]

    conversations[session_id] = {'conversation': conversation, 'data': data}
    return jsonify({
        'session_id': session_id,
        'response': response,
        'intent': intent,
        'entities': entities,
        'from_core': False,
        'lang': data['language']
    })
예제 #11
0
from flask import Flask, request, jsonify
from provider_bot.__init__ import app
from mindmeld.components.dialogue import Conversation
from provider_bot.bot_db import create_database

api = Flask(__name__)
conversation = Conversation(app=app, context={'username': '******'})


def simplify_entity(e):
    if e is None:
        return None
    if e['type'] == 'sys_time':
        if e['role'] == 'day':
            return str(e['value'][0]['value'])[:10]
        if e['role'] == 'hour':
            return str(e['value'][0]['value'])[11:16]
        else:
            raise NotImplementedError('Unknown sys_time role')
    if e['type'] == 'service_plan':
        return e['value'][0]['cname']
    if e['type'] == 'sys_number':
        return e['value'][0]['value']
    else:
        raise NotImplementedError('Unknown entity type')


@api.route('/api', methods=['POST'])
def endpoint():
    message = request.json['message']
    conversation.say(message)