Exemple #1
0
from wxpy import *
from rasa_core.agent import Agent
from rasa_core.interpreter import RasaNLUInterpreter
from rasa_core.policies.keras_policy import KerasPolicy
from rasa_core.policies.memoization import MemoizationPolicy
from rasa_core.utils import EndpointConfig

agent = Agent('w_domain.yml',
              policies=[
                  MemoizationPolicy(),
                  KerasPolicy(max_history=3, epochs=200, batch_size=50)
              ])
data = agent.load_data('./data/stories.md')
agent.train(data)
interpreter = RasaNLUInterpreter('./models/nlu/default/trainedNlu')
action_endpoint = EndpointConfig(url="http://localhost:5055/webhook")
agent = Agent.load('./models/dialogue',
                   interpreter=interpreter,
                   action_endpoint=action_endpoint)

bot = Bot(console_qr=False, cache_path=True)


@bot.register(bot.friends())
def reply_my_friend(msg):
    ans = agent.handle_message(msg.text)
    print(ans)
    return ans[0]['text']


embed()
Exemple #2
0
from rasa_core.channels import HttpInputChannel
from rasa_core.channels.facebook import FacebookInput
from rasa_core.agent import Agent
from rasa_core.interpreter import RasaNLUInterpreter

# load your trained agent
agent = Agent.load(
    "models/dialogue",
    interpreter=RasaNLUInterpreter(
        model_directory=
        "C:/Users/Administrator/Desktop/BotV3.0/models/nlu/current",
        config_file="nlu_model_config.json"))

YOUR_FB_VERIFY = "rasa-bot"
YOUR_FB_SECRET = "a9f5370c907e14a983051bd4d266c47b"
YOUR_FB_PAGE_ID = "158943344706542"
YOUR_FB_PAGE_TOKEN = "EAACZAVkjEPR8BANiwfuKaSVz8yxtLsytuOPvaUzUTlCMAmvuX9TdqGR5P4F1EepBfZCQoKhSR49zM5C9pYX9hmmv3qqiUnRCMDE0eJ1lWRjeqNYTLLA5nbXelSMw0p7neZBSyyIcNHS3e1lbbf2raWPY8IUosJZBMlDLLA7ZBJgTxZAZCvhbO84"

input_channel = FacebookInput(
    fb_verify=
    YOUR_FB_VERIFY,  # you need tell facebook this token, to confirm your URL
    fb_secret=YOUR_FB_SECRET,  # your app secret
    fb_tokens={YOUR_FB_PAGE_ID:
               YOUR_FB_PAGE_TOKEN},  # page ids + tokens you subscribed to
    debug_mode=True  # enable debug mode for underlying fb library
)

agent.handle_channel(HttpInputChannel(8080, "", input_channel))
Exemple #3
0
def run_dialogue(serve_forever=True):
    interpreter = RasaNLUInterpreter('./models/nlu/default/chat')
    action_endpoint = EndpointConfig(url="http://localhost:5055/webhook")
    agent = Agent.load('./models/dialogue', interpreter=interpreter, action_endpoint=action_endpoint)
    rasa_core.run.serve_application(agent, channel='cmdline')
    return agent
from rasa_core.interpreter import RegexInterpreter
from rasa_core.policies.keras_policy import KerasPolicy
from rasa_core.policies.memoization import MemoizationPolicy
from rasa_core.interpreter import RasaNLUInterpreter


logger = logging.getLogger(__name__)


def run_weather_online(input_channel, interpreter,
                          domain_file="domain.yml",
                          training_data_file='data/stories.md'):
    agent = Agent(domain_file,
                  policies=[MemoizationPolicy(), KerasPolicy()],
                  interpreter=interpreter)

    agent.train_online(training_data_file,
                       input_channel=input_channel,
                       max_history=2,
                       batch_size=50,
                       epochs=200,
                       max_training_samples=300)

    return agent


if __name__ == '__main__':
    logging.basicConfig(level="INFO")
    nlu_interpreter = RasaNLUInterpreter('./models/nlu/default/doctornlu')
    run_weather_online(ConsoleInputChannel(), nlu_interpreter)
Exemple #5
0
from rasa_core.channels import HttpInputChannel
from rasa_core.agent import Agent
from rasa_core.interpreter import RasaNLUInterpreter
from rasa_slack_connector import SlackInput

nlu_interpreter = RasaNLUInterpreter(
    './models/nlu/default/retailbot')  ## model path
agent = Agent.load('./models/dialogue', interpreter=nlu_interpreter)

input_channel = SlackInput(
    'xoxp-423894218069-423894219605-424790010167-542a4c4faab8353d53dfe2e1d3ae56af',  #app verification token
    'xoxb-423894218069-423901535829-mCl8rB6reWAonQpHCMXhsbB9',  # bot verification token
    'tmuWECAy59Qba6hbYzSJft11',  # slack verification token
    True)

agent.handle_channel(HttpInputChannel(5004, '/', input_channel))
Exemple #6
0
import requests 
import json
from flask import Flask 
from flask import request
from flask import Response
from rasa_core.agent import Agent
from rasa_core.interpreter import RasaNLUInterpreter
from rasa_core.utils import EndpointConfig

# load trained models
interpreter = RasaNLUInterpreter('./models/current/nlu')
agent = Agent.load('./models/current/dialogue', interpreter=interpreter,action_endpoint=EndpointConfig(url="0.0.0.0:5055/webhook"))

token = '739701752:AAEu1dcyxVeTNf8pgyN5FfMZx-2Te3PwprA'

# https://api.telegram.org/bot{token}/deleteWebhook

app = Flask(__name__)

# accept telegram messages
@app.route('/',methods=['POST','GET'])
def index():
    if(request.method == 'POST'):
        msg = request.get_json()
        print(msg)
        chat_id , message = parse_msg(msg) #message é a mensagem do usuario, chat_id do user
        
        response_messages = applyAi(message)
        send_message(chat_id,response_messages)
        return Response('ok',status=200)
    else:
from rasa_core.agent import Agent
from rasa_core.interpreter import RasaNLUInterpreter
from ga_connector import GoogleConnector
from rasa_core.utils import EndpointConfig

action_endpoint = EndpointConfig(url="http://localhost:5055/webhook")
nlu_interpreter = RasaNLUInterpreter('./models/nlu/default/chatter')



#generator = EndpointConfig(url="http://localhost:5055/nlg")

#agent = Agent.load('./models/dialogue', interpreter = nlu_interpreter, action_endpoint=action_endpoint , generator=generator)
agent = Agent.load('./models/dialogue', interpreter=nlu_interpreter, action_endpoint = action_endpoint)
input_channel = GoogleConnector()
agent.handle_channels([input_channel], 5004, serve_forever=True)


from rasa_core.channels.facebook import FacebookInput
from rasa_core.agent import Agent
from rasa_core.interpreter import RasaNLUInterpreter
from rasa_core.utils import EndpointConfig

input_channel = FacebookInput(
    fb_verify="ResBot",
    # you need tell facebook this token, to confirm your URL
    fb_secret="f12e71394b4b95e1ae348a8023b72855",  # your app secret
    fb_access_token=
    "EAAGH6Mgz3VoBAPX7ZCaOvbkNi6Y2qhKJ5ZBycstxdpYnEMr3LfOiqBksrrVNZAZA0FbxwilAyEhJa34EgczzHk9ZCPgC0KjAxroGuxd43xQjtaqv7v7kon1BH3L1S1pgV5G0zBjZCc5F75AS9aLXHpi7vEMUTQnaoHZBZAMe0JyM3eKKsykWfxhL"
    # token for the page you subscribed to
)

nlu_interpreter = RasaNLUInterpreter('./models/nlu/default/ResBot')
action_endpoint = EndpointConfig(url="http://localhost:5055/webhook")
agent = Agent.load('./models/dialogue',
                   interpreter=nlu_interpreter,
                   action_endpoint=action_endpoint)

# set serve_forever=True if you want to keep the server running
s = agent.handle_channels([input_channel], 5004, serve_forever=True)
 def __init__(self):
     interpreter = RasaNLUInterpreter(
         './models/nlu/default/helloweather_model')
     self.run_online_trainer(interpreter)
Exemple #10
0
# Messenger Platform
from controllers.messenger_send_api import verify_webhook, respond
# Image
from controllers.image import predict_herb_image
# Utilities
import random
import os

# Initialize the Flask application
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = os.path.join(os.getcwd(), "api_images")

# NLU
rasa_nlu_interpreter_path = os.path.join(os.getcwd(), "models", "nlu",
                                         "default", "current")
interpreter = RasaNLUInterpreter(rasa_nlu_interpreter_path)
rasa_nlu_dialogue_path = os.path.join(os.getcwd(), "models", "dialogue")
agent = Agent.load(rasa_nlu_dialogue_path, interpreter=interpreter)


@app.route('/')
def index():
    return '<h1>Hello World<h1/>'


def get_message():
    sample_responses = [
        "อู้หยังนิ", "บ่ฮู้เรื่อง", "อู้ไปเรื่อย", "สวัสดีเจ้า", "ต่อนยอน"
    ]
    # return selected item to the user
    return random.choice(sample_responses)
Exemple #11
0
def load_interpreter():
    print("loading in interpreter")
    interpreter = RasaNLUInterpreter(INTEPRETER_PATH)
    return interpreter
Exemple #12
0
#!/usr/bin/env python

#SENIVERSE_KEY=hjne3bys5ilki7yw python ./webchat.py

import os
import pypher
import json
import warnings
import ruamel.yaml as yaml
from pypher.builder import Param, Pypher
from neo4j.v1 import GraphDatabase
from rasa_core.interpreter import RasaNLUInterpreter
import sys 
import argparse

interpret = RasaNLUInterpreter('./models/nlu/longbi')
extracted_intents = None
extracted_values = None # entities values
prediction = None

a_list=['过度依赖父母怎么办','总咬指甲怎么办','爱说谎怎么办','过度胆小怎么办','害怕分离怎么办','孩子经常夹腿怎么办','5岁了还尿床怎么办','多动不专心怎么办','不自主的挤眉弄眼怎么办','走路说话晚怎么办','不看人不理人怎么办','孩子易冲动、爱攻击别人怎么办','家长如何帮助孩子对应压力','家长如何帮助孩子理解和表达自己的感受']

for a in a_list:

	extracted_entities = None
	extracted_intents = None

	prediction = interpret.parse(a)
	print(a,':',prediction['intent'])
	if len(prediction.get("entities")) > 0:
	    # extracted_entities = None
Exemple #13
0
except ImportError:
    import md5
    md5_constructor = md5.new
    md5_hmac = md5
    import sha
    sha_constructor = sha.new
    sha_hmac = sha

from rasa_core.agent import Agent
from rasa_core.interpreter import RasaNLUInterpreter

sys.path.append('../MITIE/mitielib')
# from momo.helper import get_momo_answer  # 导入获取机器人回答获取函数

nlu_model_path = '../models/default/model_20171117-181635'
agent = Agent.load("../models/policy/mom", interpreter=RasaNLUInterpreter(nlu_model_path))

# momo_chat = ChatBot(
#     'Momo',
#     storage_adapter='chatterbot.storage.MongoDatabaseAdapter',
#     logic_adapters=[
#         "chatterbot.logic.BestMatch",
#         "chatterbot.logic.MathematicalEvaluation",
#         "chatterbot.logic.TimeLogicAdapter",
#     ],
#     input_adapter='chatterbot.input.VariableInputTypeAdapter',
#     output_adapter='chatterbot.output.OutputAdapter',
#     database='chatterbot',
#     read_only=True
# )
Exemple #14
0
from rasa_core.interpreter import RegexInterpreter
from rasa_core.policies.keras_policy import KerasPolicy
from rasa_core.policies.memoization import MemoizationPolicy
from rasa_core.interpreter import RasaNLUInterpreter

logger = logging.getLogger(__name__)


def run_weather_online(input_channel,
                       interpreter,
                       domain_file="domain.yml",
                       training_data_file='data/stories.md'):
    agent = Agent(domain_file,
                  policies=[MemoizationPolicy(max_history=2),
                            KerasPolicy()],
                  interpreter=interpreter)

    agent.train_online(training_data_file,
                       input_channel=input_channel,
                       batch_size=50,
                       epochs=200,
                       max_training_samples=300)

    return agent


if __name__ == '__main__':
    logging.basicConfig(level="INFO")
    nlu_interpreter = RasaNLUInterpreter('./models/nlu/default/supportnlu')
    run_weather_online(ConsoleInputChannel(), nlu_interpreter)
Exemple #15
0
def collect_story_predictions(resource_name, policy_model_path, nlu_model_path,
                              max_stories):
    """Test the stories from a file, running them through the stored model."""

    if nlu_model_path is not None:
        interpreter = RasaNLUInterpreter(model_directory=nlu_model_path)
    else:
        interpreter = RegexInterpreter()

    agent = Agent.load(policy_model_path, interpreter=interpreter)
    story_graph = training.extract_story_graph(resource_name, agent.domain,
                                               interpreter)
    preds = []
    actual = []

    g = TrainingDataGenerator(story_graph,
                              agent.domain,
                              use_story_concatenation=False,
                              tracker_limit=max_stories)
    completed_trackers = g.generate()

    failed_stories = []

    logger.info("Evaluating {} stories\nProgress:"
                "".format(len(completed_trackers)))

    for tracker in tqdm(completed_trackers):
        sender_id = "default-" + uuid.uuid4().hex
        story = {"predicted": [], "actual": []}
        events = list(tracker.events)
        actions_between_utterances = []
        last_prediction = []

        for i, event in enumerate(events[1:]):
            if isinstance(event, UserUttered):
                p, a = align_lists(last_prediction, actions_between_utterances)
                story["predicted"].extend(p)
                story["actual"].extend(a)
                actions_between_utterances = []
                agent.handle_message(event.text, sender_id=sender_id)
                tracker = agent.tracker_store.retrieve(sender_id)
                last_prediction = actions_since_last_utterance(tracker)

            elif isinstance(event, ActionExecuted):
                actions_between_utterances.append(event.action_name)

        if last_prediction:

            preds.extend(last_prediction)
            preds_padding = (len(actions_between_utterances) -
                             len(last_prediction))

            story["predicted"].extend(["None"] * preds_padding)
            preds.extend(story["predicted"])

            actual.extend(actions_between_utterances)
            actual_padding = (len(last_prediction) -
                              len(actions_between_utterances))

            story["actual"].extend(["None"] * actual_padding)
            actual.extend(story["actual"])

        if story["predicted"] != story["actual"]:
            failed_stories.append(story)

    return actual, preds, failed_stories
Exemple #16
0
from rasa_core.train import online
from rasa_core.utils import EndpointConfig

logger = logging.getLogger(__name__)


def run_weather_online(interpreter,
                       domain_file="malu_domain.yml",
                       training_data_file='data/stories.md'):
    action_endpoint = EndpointConfig(url="http://localhost:5055/webhook")
    fallback = FallbackPolicy(fallback_action_name="action_default_fallback",
                              core_threshold=0.01,
                              nlu_threshold=0.01)
    agent = Agent(
        domain_file,
        policies=[MemoizationPolicy(max_history=2),
                  KerasPolicy(), fallback],
        interpreter=interpreter,
        action_endpoint=action_endpoint)

    data = agent.load_data(training_data_file)
    agent.train(data, batch_size=50, epochs=200, max_training_samples=300)
    online.run_online_learning(agent)
    return agent


if __name__ == '__main__':
    logging.basicConfig(level="INFO")
    nlu_interpreter = RasaNLUInterpreter('./models/nlu/default/malu')
    run_weather_online(nlu_interpreter)
Exemple #17
0
from rasa_core.channels import HttpInputChannel
from rasa_core.agent import Agent
from rasa_core.interpreter import RasaNLUInterpreter
from rasa_slack_connector import SlackInput

nlu_interpreter = RasaNLUInterpreter('./models/nlu/default/AIchatbotnlu')
agent = Agent.load('./models/dialogue', interpreter=nlu_interpreter)

input_channel = SlackInput(
    'xoxp-xxxx',  #app verification token
    'xoxb-yyyy',  # bot verification token
    'zzzz',  # slack verification token
    True)

agent.handle_channel(HttpInputChannel(5004, '/', input_channel))
Exemple #18
0
from __future__ import unicode_literals

import argparse
import logging
import warnings

from rasa_core.actions import Action
from rasa_core.agent import Agent
from rasa_core.channels.console import ConsoleInputChannel
from rasa_core.events import SlotSet
from rasa_core.interpreter import RasaNLUInterpreter
from rasa_core.policies.keras_policy import KerasPolicy
from rasa_core.policies.memoization import MemoizationPolicy

from rasa_core.events import AllSlotsReset, Restarted
interpret1 = RasaNLUInterpreter('../fine_grained/models/nlu/longbi')

import search

import warnings
warnings.filterwarnings("ignore")

logger = logging.getLogger(__name__)

#from cocoNLP.extractor import extractor


class Performance(Action):
    def name(self):

        return 'action_query_Performance'
from rasa_core.interpreter import RegexInterpreter
from rasa_core.policies.keras_policy import KerasPolicy
from rasa_core.policies.memoization import MemoizationPolicy
from rasa_core.interpreter import RasaNLUInterpreter

logger = logging.getLogger(__name__)


def run_faq_online(input_channel,
                   interpreter,
                   domain_file="faq_domain.yml",
                   training_data_file='data/stories.md'):
    agent = Agent(domain_file,
                  policies=[MemoizationPolicy(),
                            KerasPolicy()],
                  interpreter=interpreter)

    agent.train_online(training_data_file,
                       input_channel=input_channel,
                       max_history=2,
                       batch_size=50,
                       epochs=200,
                       max_training_samples=300)

    return agent


if __name__ == '__main__':
    logging.basicConfig(level="INFO")
    nlu_interpreter = RasaNLUInterpreter('./models/nlu/default/faq_bot')
    run_faq_online(ConsoleInputChannel(), nlu_interpreter)
Exemple #20
0
from rasa_core.channels.console import ConsoleInputChannel
from rasa_core.interpreter import RegexInterpreter
from rasa_core.policies.keras_policy import KerasPolicy
from rasa_core.policies.memoization import MemoizationPolicy
from rasa_core.interpreter import RasaNLUInterpreter

logger = logging.getLogger(__name__)


def run_foodie_online(input_channel, interpreter,
                          domain_file="foodie_domain.yml",
                          training_data_file='data/stories.md'):
    agent = Agent(domain_file,
                  policies=[MemoizationPolicy(), KerasPolicy()],
                  interpreter=interpreter)

    agent.train_online(training_data_file,
                       input_channel=input_channel,
                       max_history=2,
                       batch_size=50,
                       epochs=200,
                       max_training_samples=300)

    return agent


if __name__ == '__main__':
    logging.basicConfig(level="INFO")
    nlu_interpreter = RasaNLUInterpreter('./models/nlu/default/foodienlu')
    run_foodie_online(ConsoleInputChannel(), nlu_interpreter)
Exemple #21
0
from rasa_core.agent import Agent
from rasa_core.channels.console import ConsoleInputChannel
from rasa_core.interpreter import RegexInterpreter
from rasa_core.policies.keras_policy import KerasPolicy
from rasa_core.policies.memoization import MemoizationPolicy
from rasa_core.interpreter import RasaNLUInterpreter

logger = logging.getLogger(__name__)


def run_restaurant_online(input_channel, interpreter,
                          domain_file="restaurant_domain.yml",
                          training_data_file='data/stories.md'):
    agent = Agent(domain_file,
                  policies=[MemoizationPolicy(), KerasPolicy()],
                  interpreter=interpreter)

    agent.train_online(training_data_file,
                       input_channel=input_channel,
                       max_history=2,
                       batch_size=50,
                       epochs=200,
                       max_training_samples=300)

    return agent


if __name__ == '__main__':
    logging.basicConfig(level="INFO")
    nlu_interpreter = RasaNLUInterpreter('./models/nlu/default/restaurantnlu')
    run_restaurant_online(ConsoleInputChannel(), nlu_interpreter)
Exemple #22
0
from rasa_core.agent import Agent
from rasa_core.interpreter import RasaNLUInterpreter
from ga_connector import GoogleConnector
from rasa_core.utils import EndpointConfig

action_endpoint = EndpointConfig(url="http://localhost:5055/webhook")
nlu_interpreter = RasaNLUInterpreter(
    'C:\\Users\\HP\\Desktop\\starter-pack-rasa-stack-master\\models\\current\\nlu_model'
)
agent = Agent.load('./models/current/dialogue',
                   interpreter=nlu_interpreter,
                   action_endpoint=action_endpoint)

input_channel = GoogleConnector()
agent.handle_channels([input_channel], 5004, serve_forever=True)
Exemple #23
0
from rasa_core.channels import HttpInputChannel
from rasa_core.agent import Agent
from rasa_core.interpreter import RasaNLUInterpreter
from rasa_slack_connector import SlackInput

nlu_interpreter = RasaNLUInterpreter('./models/nlu/default/Homer_nlu')
agent = Agent.load('./models/dialogue', interpreter=nlu_interpreter)

input_channel = SlackInput()

agent.handle_channel(HttpInputChannel(5005, '/', input_channel))
Exemple #24
0
from rasa_core.channels.console import ConsoleInputChannel
from rasa_core.interpreter import RegexInterpreter
from rasa_core.policies.keras_policy import KerasPolicy
from rasa_core.policies.memoization import MemoizationPolicy
from rasa_core.interpreter import RasaNLUInterpreter

logger = logging.getLogger(__name__)


def run_online(input_channel, interpreter,
                          domain_file="domain.yml",
                          training_data_file='data/stories.md'):

    agent = Agent(domain_file,
                  policies=[MemoizationPolicy(max_history=5), KerasPolicy()],
                  interpreter=interpreter)

    training_data = agent.load_data(training_data_file)
    agent.train_online(training_data,
                       input_channel=input_channel,
                       batch_size=50,
                       epochs=200,
                       max_training_samples=300)

    return agent


if __name__ == '__main__':
    logging.basicConfig(level="INFO")
    nlu_interpreter = RasaNLUInterpreter('./models/nlu/default/current')
    run_online(ConsoleInputChannel(), nlu_interpreter)
Exemple #25
0
from rasa_nlu.model import Metadata, Interpreter
from rasa_nlu import config
from rasa_nlu.model import Trainer
from rasa_core.agent import Agent
from rasa_core.interpreter import RasaNLUInterpreter

##run durectly
'''
python -m rasa_core.run -d nlu_dialogue/models/restaurant -u nlu_model/restaurant/default/model_20180620-224333
'''

model_directory = 'nlu_model/jarvis_nlu/default/current'
# interpreter = Interpreter.load(model_directory)
agent = Agent.load('nlu_dialogue/models/jarvis_nlu',
                   interpreter=RasaNLUInterpreter(model_directory))
# Create your views here.


def home(requests):
    return render(requests, 'jarvis/home.html', {})


def task(requests):
    req = requests.GET['query']
    context = {}

    ### using NLU intent prediction
    # intent = interpreter.parse(req)
    # print(intent)
    # context['message'] = intent
Exemple #26
0
from rasa_core.agent import Agent
from rasa_core.utils import EndpointConfig
from rasa_core.interpreter import RasaNLUInterpreter

agent = Agent.load(
    'models/dialogue',
    interpreter=RasaNLUInterpreter('./models/nlu/default/restaurantbot/'),
    action_endpoint=EndpointConfig(url="http://127.0.0.1:5055/webhook"))
print("Bot is ready to talk! Start conversation with 'hi'")
while True:
    st = input()
    if st == 'stop':
        break
    responses = agent.handle_text(st)
    for response in responses:
        print(response["text"])
Exemple #27
0
from rasa_core.channels.console import ConsoleInputChannel
from rasa_core.interpreter import RegexInterpreter
from rasa_core.policies.keras_policy import KerasPolicy
from rasa_core.policies.memoization import MemoizationPolicy
from rasa_core.interpreter import RasaNLUInterpreter

logger = logging.getLogger(__name__)


def run_weather_online(input_channel,
                       interpreter,
                       domain_file="weather_domain.yml",
                       training_data_file='data/stories.md'):
    agent = Agent(domain_file,
                  policies=[MemoizationPolicy(max_history=2),
                            KerasPolicy()],
                  interpreter=interpreter)

    agent.train_online(training_data_file,
                       input_channel=input_channel,
                       batch_size=50,
                       epochs=200,
                       max_training_samples=300)

    return agent


if __name__ == '__main__':
    logging.basicConfig(level="INFO")
    nlu_interpreter = RasaNLUInterpreter('./models/nlu/default/weathernlu')
    run_weather_online(ConsoleInputChannel(), nlu_interpreter)
Exemple #28
0
import os

from rasa_core.channels.rasa_chat import RasaChatInput
from rasa_core.channels.channel import CollectingOutputChannel, UserMessage
from rasa_core.agent import Agent
from rasa_core.interpreter import RasaNLUInterpreter
from rasa_core.utils import EndpointConfig
from rasa_core import utils

from flask import render_template, Blueprint, jsonify, request

# load your trained agent
interpreter = RasaNLUInterpreter("models/nlu/default/horoscopebot/")
MODEL_PATH = "models/dialogue"
action_endpoint = EndpointConfig(
    url="https://horoscopebot1212-actions.herokuapp.com/webhook")

agent = Agent.load(MODEL_PATH,
                   interpreter=interpreter,
                   action_endpoint=action_endpoint)


class MyNewInput(RasaChatInput):
    @classmethod
    def name(cls):
        return "rasa"

    def _check_token(self, token):
        if token == 'secret':
            return {'username': 1234}
        else:
Exemple #29
0
def run_online_dialogue(serve_forever=True):
    interpreter = RasaNLUInterpreter('./models/nlu/default/chat')
    action_endpoint = EndpointConfig(url="http://localhost:5055/webhook")
    agent = Agent.load('./models/dialogue', interpreter=interpreter, action_endpoint=action_endpoint)
    interactive.run_interactive_learning(agent)#, channel='cmdline')
    return agent
Exemple #30
0
from rasa_core.agent import Agent
from rasa_core.interpreter import RasaNLUInterpreter
import time

interpreter = RasaNLUInterpreter(
    '/app/project/model/default/model_20190204-222950')
messages = [
    "Hi! you can chat in this window. Type 'stop' to end the conversation."
]
agent = Agent.load('/app/project/model/dialogue', interpreter=interpreter)


def chatlogs_html(messages):
    messages_html = "".join(["<p>{}</p>".format(m) for m in messages])
    chatbot_html = """<div class="chat-window" {}</div>""".format(
        messages_html)
    return chatbot_html


while True:
    print(chatlogs_html(messages))
    time.sleep(0.3)
    a = input()
    messages.append(a)
    if a == 'stop':
        break
    responses = agent.handle_message(a)
    for r in responses:
        messages.append(r.get("text"))