Esempio n. 1
0
def sms_reply():
    # Start our TwiML response
    from_number = request.values.get('From')
    country = request.values.get('FromCountry')
    message_body = request.values.get('Body')
    print(request.values)
    print('{} has sent a message saying {} from {}'.format(
        str(from_number), str(message_body), str(country)))
    service = watson_developer_cloud.AssistantV1(
        username='******',  # replace with service username
        password=
        '******',  # replace with service password
        version='2018-02-16')
    workspace_id = '4abe462d-03d4-4fd3-9f5a-9f8ee11ad00a'
    user_input = str(message_body)
    context = {}
    while True:
        response = service.message(workspace_id=workspace_id,
                                   input={'text': user_input},
                                   context=context)

        if response['intents']:
            print('Detected intent: #' + response['intents'][0]['intent'])

        # Print the output from dialog, if any.

        if response['output']['text']:
            resp = MessagingResponse()
            resp.message(str(response['output']['text'][0]))
            return str(resp)

        # Update the stored context with the latest received from the dialog.
        context = response['context']
Esempio n. 2
0
def conversationCall(search_file):
    assistant = watson_developer_cloud.AssistantV1(
        iam_apikey=config.iam_apikey,
        version='2018-09-20',
        url='https://gateway.watsonplatform.net/assistant/api')

    response = assistant.message(workspace_id=config.workspace_id,
                                 input={
                                     'text': search_file
                                 }).get_result()

    #print(json.dumps(response, indent=2))

    #intent = response['intents'][0]['intent']

    if 'intents' in response:
        try:
            confidence = response['intents'][0]['confidence']
            print(confidence)
            intent = response['intents'][0]['intent']
            if confidence >= 0.6:
                print("certeza")
                #postar(intent)
                song = AudioSegment.from_wav("./audio" + intent + ".wav")
                print(caminho_mac + intent + ".wav")
                play(song)
                call(["python", "./SnowboyTest.py"])
        except:
            print("except")
            song = AudioSegment.from_wav("./audio" + "/anything_else.wav")
            play(song)
            #			main()
            call(["python", "./transcribe.py"])
Esempio n. 3
0
def cliente_funcion(texto):
    # Set up Assistant service.
    print("holaaaaa")
    service = watson_developer_cloud.AssistantV1(
        username=
        '******',  # replace with service username
        password='******',  # replace with service password
        version='2018-02-16')
    workspace_id = '624a1e2c-c475-4be0-8152-e68caf79f95c'  # replace with workspace ID

    # Initialize with empty value to start the conversation.
    user_input = texto
    context = {}
    current_action = ''
    # Main input/output loop

    while current_action != 'finalConversacion':

        # Send message to Assistant service.
        response = service.message(workspace_id=workspace_id,
                                   input={'text': user_input},
                                   context=context)
        # If an intent was detected, print it to the console
        if response['intents']:
            print('Detected intent: #' + response['intents'][0]['intent'])
        # Print the output from dialog, if any.
        if response['output']['text']:
            print(response['output']['text'][0])
        # Update the stored context with the latest received from the dialog.
        context = response['context']
        if 'action' in response['output']:
            current_action = response['output']['action']
        if current_action != 'finalConversacion':
            user_input = input('>> ')
Esempio n. 4
0
 def __init__(self, usr, pas, workspace):
     self.convo = watson_developer_cloud.AssistantV1(
         username=usr,
         password=pas,
         url='https://gateway.watsonplatform.net/assistant/api',
         version='2018-07-10')
     self.workspace_id = workspace
Esempio n. 5
0
def reply_text_watson(reply_token, text):
    import watson_developer_cloud

    print(text)

    assistant = watson_developer_cloud.AssistantV1(
        username='******',
        password='******',
        version='2018-02-16')

    from watson_developer_cloud import WatsonApiException
    try:
        # Invoke a Assistant method
        response = assistant.message(
            workspace_id='585d1384-6b78-42a3-8911-5958572af8a4',
            input={'text': text})
    except WatsonApiException as ex:
        print("Method failed with status code " + str(ex.code) + ": " +
              ex.message)

    print(json.dumps(response, indent=2))

    payload = {
        "replyToken": reply_token,
        "messages": [{
            "type": "text",
            "text": response["output"]["text"][0]
        }]
    }

    requests.post(REPLY_ENDPOINT, headers=HEADER, data=json.dumps(payload))
    return response["output"]["text"][0]
Esempio n. 6
0
    def __init__(self, text):
        self.config = watson_developer_cloud.AssistantV1(
            version='2018-09-20',
            username='******',
            password='******',
            url='https://gateway.watsonplatform.net/assistant/api')

        self.text = text
Esempio n. 7
0
 def __init__(self):
     self.speech = ''
     self.assistant = watson_developer_cloud.AssistantV1(username=USERNAME,
                                                         password=PASSWORD,
                                                         version=VERSION)
     self.watson_pub = rospy.Publisher('/watson_speech_output',
                                       String,
                                       queue_size=10)
     rospy.Subscriber('/speech_text_input', String, self.get_response)
     rospy.spin()
def get_watsonbot_greet():
    assistant = watson_developer_cloud.AssistantV1(
        version='2017-10-16',
        username='******',
        password='******',
        url='https://gateway.watsonplatform.net/assistant/api')
    response = assistant.message(
        workspace_id='6e65b7c7-9b60-40b1-a01e-03704ac13391').get_result()
    jsonResp = json.loads(json.dumps(response, indent=2))
    resp = ''.join(jsonResp['output']['text'])
    return resp
Esempio n. 9
0
 def __init__(self, credfile):
     with open(credfile, 'rb') as infile:
         creds = json.load(infile)
     self._assistant = watson_developer_cloud.AssistantV1(
         '2018-02-16',
         url=creds['url'],
         username=creds['username'],
         password=creds['password'])
     self._request = {
         'workspace_id': creds['workspace'],
         'input': {
             'text': ''
         }
     }
Esempio n. 10
0
def listar(config):
    assistant = watson_developer_cloud.AssistantV1(
        iam_apikey=config['iam_apikey'], version=config['version'])

    response = assistant.list_intents(
        workspace_id=config['workspace_id']).get_result()

    print(json.dumps(response, indent=2))

    tamanho = len(response['intents'])
    dic = {}

    for num in range(0, tamanho):
        dic[num] = response['intents'][num]['intent']

    print(dic)
    return dic
Esempio n. 11
0
def listar(config):

    assistant = watson_developer_cloud.AssistantV1(
        iam_apikey=config['iam_apikey'], version=config['version'])

    response = assistant.list_dialog_nodes(
        workspace_id=config['workspace_id']).get_result()

    print(response)

    tamanho = len(response['dialog_nodes'])
    dic = {}

    for num in range(0, tamanho):
        key = response['dialog_nodes'][num]['conditions']
        key = key.replace('#', '')
        dic[key] = response['dialog_nodes'][num]['output']['text']['values'][0]
        #dic[key] = response['dialog_nodes'][num]['output']['generic'][0]['values'][0]['text'] # versões novas do assistant

    return dic
Esempio n. 12
0
def listar(dic_intencao, config):

    print(config)

    assistant = watson_developer_cloud.AssistantV1(
        iam_apikey=config['iam_apikey'], version=config['version'])

    dic_exemplos = {}

    for num in range(0, len(dic_intencao)):

        response = assistant.list_examples(
            workspace_id=config['workspace_id'],
            intent=dic_intencao[num]).get_result()

        for numero in range(0, len(response['examples'])):
            dic_exemplos[(
                response['examples'][numero]['text'])] = dic_intencao[num]

    return dic_exemplos
Esempio n. 13
0
    def initialize_from_dict(self, config):
        print config
        self.WORKSPACE_ID = config['WORKSPACE_ID']
        self.WORKSPACE_URL = config['WORKSPACE_URL']
        self.WATSON_API_KEY = config['WATSON_API_KEY']
        self.WATSON_CRED_NAME = config['WATSON_CRED_NAME']
        self.WATSON_URL = config['WATSON_URL']

        print self.WATSON_CRED_NAME

        #self.assistant = watson_developer_cloud.AssistantV1(
        #    username=self.WATSON_CRED_NAME,
        #    password=self.WATSON_API_KEY,
        #    version='2018-09-20'
        #)

        self.assistant = watson_developer_cloud.AssistantV1(
            url=self.WATSON_URL,
            iam_apikey=self.WATSON_API_KEY,
            version='2018-07-10')
Esempio n. 14
0
def watsonConnection(message, context, categoria):
    user = '******'
    pw = 'TPKMPYH21L3Q'
    wk = ''
    if (categoria == 'st'):
        wk = '85a2b90e-4d6c-42ef-9787-e269d38f2aad'
    else:
        wk = 'fc9f117a-f372-4f93-b932-bade81508504'
    assistant = watson_developer_cloud.AssistantV1(username=user,
                                                   password=pw,
                                                   version='2018-09-25')
    print(context)
    response = assistant.message(workspace_id=wk,
                                 encoding='utf-8',
                                 input={
                                     'text': message
                                 },
                                 context=eval(context)).get_result()

    return response
Esempio n. 15
0
def init():
    global assistant
    assistant = watson_developer_cloud.AssistantV1(
        username='******',
        password='******',
        version='2018-09-20')
Face = ""
show_acom = False
run_program = True
entertainment_value = False
Tickle = False
start = []
end = []
end_location = ""

#--------> Initialize qi framework <-------------
connection_url = "tcp://" + ip + ":" + str(port)
app = qi.Application(["ReactToTouch", "--qi-url=" + connection_url])

# ----------> Connect to Watson Assistant <-------------
assistant = watson_developer_cloud.AssistantV1(
    username='******',
    password='******',
    version='2018-07-10')

# ----------> Connect to Watson Speech to Text <-------------
speech_to_text = SpeechToTextV1(
    username='******',
    password='******',
    url='https://stream.watsonplatform.net/speech-to-text/api')

# ----------> Connect to robot <----------
tts = ALProxy("ALTextToSpeech", ip, port)
mic = ALProxy("ALAudioDevice", ip, port)
record = ALProxy("ALAudioRecorder", ip, port)
aup = ALProxy("ALAudioPlayer", ip, port)
tts = ALProxy("ALTextToSpeech", ip, port)
animated_speech = ALProxy("ALAnimatedSpeech", ip, port)
Esempio n. 17
0
run_program = True
entertainment_value = False
Tickle = False
start = []
end = []
end_location = ""
New_question_input = ""

#--------> Initialize qi framework <-------------
connection_url = "tcp://" + ip + ":" + str(port)
app = qi.Application(["ReactToTouch", "--qi-url=" + connection_url])

# ----------> Connect to Watson Assistant <-------------
assistant = watson_developer_cloud.AssistantV1(
    username='******',
    password='******',
    version='2018-07-10'
)

# ----------> Connect to Watson Speech to Text <-------------
speech_to_text = SpeechToTextV1(
    username='******',
    password='******',
    url='https://stream.watsonplatform.net/speech-to-text/api')


# ----------> Connect to robot <----------
tts = ALProxy("ALTextToSpeech", ip, port)
mic = ALProxy("ALAudioDevice", ip, port)
record = ALProxy("ALAudioRecorder", ip, port)
aup = ALProxy("ALAudioPlayer", ip, port)
Esempio n. 18
0
import os
import watson_developer_cloud

from dotenv import load_dotenv, find_dotenv

load_dotenv(find_dotenv())

service = watson_developer_cloud.AssistantV1(
	username=os.getenv("WATSON_USERNAME"),
	password=os.getenv("WATSON_PASSWORD"),
	version=os.getenv("WATSON_VERSION")
)

workspace_id = os.getenv("WATSON_WORKSPACEID")

# Start conversation with an empty message
response = service.message(
	workspace_id=workspace_id,
	input={
		'text': ''
	}
).get_result()

print(f"USER: {response['input']['text']}")
print(f"WATSON: {response['output']['text'][0]}")
apikeyAssistant = 'xxx'
workspaceid = 'xxx'
apikeyNLC = 'xxx'

# Appel de l'instance NLU
naturalLanguageUnderstanding = NaturalLanguageUnderstandingV1(
    version='2018-11-16',
    iam_apikey=apikeyNLU,
    url=
    'https://gateway-fra.watsonplatform.net/natural-language-understanding/api'
)

#Appel de l'instance Chatbot (Assistant)

assistant = watson_developer_cloud.AssistantV1(
    iam_apikey=apikeyAssistant,
    version='2018-09-20',
    url='https://gateway-fra.watsonplatform.net/assistant/api')

#Importation modules NLC
from watson_developer_cloud import NaturalLanguageClassifierV1

# Appel de l'instance NLC
natural_language_classifier = NaturalLanguageClassifierV1(
    iam_apikey=apikeyNLC,
    url='https://gateway-fra.watsonplatform.net/natural-language-classifier/api'
)


def main(params):

    text = params['text'].replace("\n", "")
Esempio n. 20
0
###################################################################
######## Slack configuration   ##########################
###################################################################

SLACK_BOT_TOKEN = 'xoxb-xxxxxxxxxxxx-xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxx'
SLACK_VERIFICATION_TOKEN = 'xxxxxxxxxxxxxxxxxxxxxxxx'

# instantiate Slack client
slack_client = SlackClient(SLACK_BOT_TOKEN)  # do not change this parameter

###################################################################
######## Watson service configuration   ##########################
###################################################################

service = watson_developer_cloud.AssistantV1(
    iam_api_key=
    'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',  # replace with Password
    version='2018-09-20')

workspace_id = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'  # replace with Assistant ID

###################################################################
######## Log files configuration   ##########################
###################################################################

log_commands_path = location + "logs/log_commands.py"  # do not change this parameter
follow_up_path = location + "logs/followup_email.py"  # do not change this parameter

###################################################################
######## Temp files configuration   ##########################
###################################################################
Esempio n. 21
0
import watson_developer_cloud
from slackclient import SlackClient
location = "/Users/madhuri/Documents/MS/Fall-2020/IS/Movie-Recommendation-Chatbot/"

# Slack configuration: Slack bot token and verification token is fetched

SLACK_BOT_TOKEN = 'xoxb-1537693727958-1551909119252-uGdlSMXQKQHRIoU17qeONWfK'
SLACK_VERIFICATION_TOKEN = 'xDzOxKYl6jHqHLFwBCiXt5TL'

# instantiate slack client
slack_client = SlackClient(SLACK_BOT_TOKEN)

#watson configuration : api key and workspace id is fetched
service = watson_developer_cloud.AssistantV1(
    iam_apikey='5Xb0ruZusvZRX3-Rpyl3RZ2gEoMttuhrclh_axWS_LGz',
    version='2018-09-20')

workspace_id = 'c3fbbdf0-5e17-4531-9dae-b72bd8f92631'

onetime_path = location + "nlp/nlp_solutions/onetime.txt.py"
onetime_file = location + "nlp/nlp_solutions/onetime.txt"
import json
import watson_developer_cloud
import winsound

creds = {
    "url": "https://gateway.watsonplatform.net/assistant/api",
    "username": "******",
    "password": "******"
}

assistant = watson_developer_cloud.AssistantV1(**creds, version='2018-07-10')


def send_message(txt):
    response = assistant.message(
        workspace_id='cbb8cec2-2155-4adb-ad3f-f29dd664eac1',
        input={"text": txt})
    return response['output']['text']


#print(json.dumps(response, indent=2))
Esempio n. 23
0
# coding=utf-8
from __future__ import unicode_literals
import requests
import os
from heroku import bot, USERNAME, PASSWORD, WORKSPACE_ID, WEB_DOMAIN, INFO_WEB, INFO_NOMBRE_BOT, INFO_TLFNO_CONTACTO, INFO_EMAIL_CONTACTO
from telebot import util
import urllib, json
import watson_developer_cloud
from model import chat

assistant = watson_developer_cloud.AssistantV1(username=USERNAME,
                                               password=PASSWORD,
                                               version='2018-02-16')


def send_log(log_information):
    url = "https://" + WEB_DOMAIN + "/panel/webservice/consultabot.php?case=log&men=" + log_information
    urllib.urlopen(url)

    return


@bot.message_handler(commands=['start'])
def start(message):
    response = assistant.message(workspace_id=WORKSPACE_ID)

    response['context']['info_web'] = INFO_WEB
    response['context']['info_nombre_bot'] = INFO_NOMBRE_BOT
    response['context']['info_tlfno_contacto'] = INFO_TLFNO_CONTACTO
    response['context']['info_email_contacto'] = INFO_EMAIL_CONTACTO
Esempio n. 24
0
import random
import requests
import watson_developer_cloud
from flask import Flask, request
from googletrans import Translator
from pymessenger.bot import Bot
import bank_api


app = Flask(__name__)
ACCESS_TOKEN = 'EAAD6V6iE3WgBABDSCRcoGaF30IjKQwuzVZCzKV2WEstEedORTq28af8Xn1G3Fj7qLTm3ZAaWMUcMmX814nxDhILB83tbU8QUx16dKt4yyhpCJvh83Rd9TvMs6ZAfySSRWnraOSZCP0uubFGriRZBdMmqnrmEWRXCwgVCfSXvm2AZDZD'
VERIFY_TOKEN = 'BANKBOTTESTINGTOKEN'
bot = Bot(ACCESS_TOKEN)
assistant = watson_developer_cloud.AssistantV1(
    username='******',
    password='******',
    version='2018-02-16'
)
translator = Translator()
account = {'balance': 120000,
           'beneficiaries': ["Ayanda Mhlongo", "Busi Dlamini"],
           'transactions': ["R200 to Jonas Mthembu", "R140 to Menzi Ndlovu"],
           'orders': ["Planet Fitness: R400", "Telkom: R700"]}


# We will receive messages that Facebook sends our bot at this endpoint
@app.route("/", methods=['GET', 'POST'])
def receive_message():
    client_message = ""
    if request.method == 'GET':
        """Before allowing people to message your bot, Facebook has implemented a verify token
Esempio n. 25
0
###################################################################
######## Slack configuration   ##########################
###################################################################

SLACK_BOT_TOKEN='xoxb-762458134353-768410665828-TWM301hVVlAx1EGRTgmui17j'
SLACK_VERIFICATION_TOKEN='Uz8X6gSSDBBEMYM80Iy8bFNn' 

# instantiate Slack client
slack_client = SlackClient(SLACK_BOT_TOKEN) # do not change this parameter

###################################################################
######## Watson service configuration   ##########################
###################################################################

service = watson_developer_cloud.AssistantV1(
    iam_apikey = 'CmjJ_DTgfwWkqt-d1Sf603Q4FlquJmSBgMMAh7H0klrg', # replace with Password
    version = '2018-09-20'
)

workspace_id = 'd11f6e06-8f21-4095-88aa-d00e2da770ad' # replace with Assistant ID

###################################################################
######## Log files configuration   ##########################
###################################################################

log_commands_path = location + "logs/log_commands.py" # do not change this parameter
follow_up_path = location + "logs/followup_email.py" # do not change this parameter

###################################################################
######## Temp files configuration   ##########################
###################################################################
import json
import pymysql
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
import watson_developer_cloud
from watson_developer_cloud import LanguageTranslatorV3
from watson_developer_cloud import NaturalLanguageUnderstandingV1
from watson_developer_cloud.natural_language_understanding_v1 \
  import Features, EntitiesOptions, KeywordsOptions, SentimentOptions
#----------------------------------Início das Declarações-----------------------------------------#
#-------------Your Assistant API --------------#
assistant = watson_developer_cloud.AssistantV1(
    username='******',  #------>Your Assistant service username here
    password='******',  #------>Your Assistant service password here
    version='2018-02-16')

#-------------Your NLU API --------------#
natural_language_understanding = NaturalLanguageUnderstandingV1(
    username='******',  #------>Your NLU service username here
    password='******',  #------>Your NLU service password here
    version='2018-03-16')

#-------------Your Translate API --------------#
language_translator = LanguageTranslator(
    username='******',  #------>Your Translate service username here
    password='******')  #------>Your Translate service password here

df = pd.read_excel(
    '/MyFile.xlsx',
    sheet_name='Plan1')  #------> Aqui você coloca o caminho do seu arquivo
import json
import watson_developer_cloud

assistant = watson_developer_cloud.AssistantV1(
    iam_apikey='c5aJ8E_FAgdrFWnCIrAvWdX4hB4QG722UuQyiRx2sUJt',
    version='2018-09-20',
    url='https://gateway.watsonplatform.net/assistant/api')


def mandar_msg_watson(mensagem):
    response = assistant.message(
        workspace_id='ce840347-0030-41f1-8f43-ac3d812ef0db',
        input={
            'text': mensagem
        }).get_result()
    return response


'''json.dumps(response, indent=2)'''
Esempio n. 28
0
#!/bin/env python

from configBot import *

import time, json, bson
import watson_developer_cloud

assistant = assistant = watson_developer_cloud.AssistantV1(
    username=watson_uid, password=watson_passwd, version="2018-02-16")


def WatsonCreateBot(botname):
    watsonBotId = assistant.create_workspace(botname,
                                             description=botname,
                                             language="en")["workspace_id"]
    print("WatsonBotId:", watsonBotId)
    return watsonBotId


def WatsonFindIntent(watsonBotId, utterance):
    response = assistant.message(workspace_id=watsonBotId,
                                 input={"text": utterance},
                                 alternate_intents=False)
    if len(response["intents"]) > 0:
        #return response["intents"][0]
        return response["intents"]
    else:
        return [{"intent": "None", "confidence": -1}]


def WatsonCleanIntent(intent):
Esempio n. 29
0
    translation = language_translator.translate(
        text=text,
        model_id=model_id)
    # print(json.dumps(translation, indent=2, ensure_ascii=False))
    return translation['translations'][0]['translation']


######################################## WATSON ASSISTANT ####################################
### NOT USED ###

import json
import watson_developer_cloud

assistant = watson_developer_cloud.AssistantV1(
    username='******',
    password='******',
    version='2018-07-10'
)

def WATSON_Assistant(text) :
    response = assistant.message(
        workspace_id='fba62a20-bfea-45df-83b2-9aa4f4acbc2e',
        input={
            'text': text
        }
    )

    # print(json.dumps(response, indent=2))
    # print (response['output']['text'][0])
    return response['output']['text'][0]
Esempio n. 30
0
import json
import watson_developer_cloud
from watson_developer_cloud import ToneAnalyzerV3
import numpy as np
import pandas as pd
import seaborn as sns
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly.graph_objs as go
import matplotlib.pyplot as plt

# watson assistant auto response
service = watson_developer_cloud.AssistantV1(
    iam_apikey=
    '6y2WMureuqOLcCVK6vifyE0lFeq_Z2UXyeqHlr3PMWxq',  # replace with API key
    version='2018-09-20',
    url='https://gateway-wdc.watsonplatform.net/assistant/api')
workspace_id = 'f3155ca1-68d7-48f5-874d-fb7ecb03ff80'  # replace with workspace ID


def auto_response(text):
    response = service.message(workspace_id=workspace_id, input={'text': text})
    if response.result['output']['generic'] and response.result['output'][
            'generic'][0]['text']:
        # print(response.result['output'])
        return response.result['output']['generic'][0]['text']
    else:
        return None


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