Пример #1
0
import pyaudio
import wave
import json
import random
from watson_developer_cloud import ConversationV1
from watson_developer_cloud import TextToSpeechV1
from watson_developer_cloud import SpeechToTextV1
import watson_developer_cloud
from os.path import join, dirname
import sounddevice as sd
import scipy.io.wavfile as wav

conversation = ConversationV1(username='******',
                              password='******',
                              version='2017-04-21')
workspace_id = '68e5659a-6135-4a80-962b-53e924eb4a66'

text_to_speech = TextToSpeechV1(
    username='******',
    password='******',
    x_watson_learning_opt_out=True)  # Optional flag

#print(json.dumps(text_to_speech.voices(), indent=2))

speech_to_text = SpeechToTextV1(
    username='******',
    password='******',
    x_watson_learning_opt_out=False)
print(json.dumps(speech_to_text.models(), indent=2))

print(json.dumps(speech_to_text.get_model('en-US_BroadbandModel'), indent=2))
Пример #2
0
            break

        # sends the input to conversation and retrieves the json response.
        response = conversation.message(workspace_id=workspace_id,
                                        message_input={'text': input_content},
                                        context=context)

        # sends the response to our functions
        data = parse_conversation_response(response)
        context = handle_conversation_data(data)




if __name__ == '__main__':
    # BEGIN of python-dotenv section
    dotenv_path = join(dirname(__file__), '.env')
    load_dotenv(dotenv_path)
    # END of python-dotenv section

    # create an instance of the API ConversationV1 object
    conversation_apiobj = ConversationV1(
        username=os.environ.get("CONVERSATION_USERNAME"),
        password=os.environ.get("CONVERSATION_PASSWORD"),
        version='2016-09-20')

    # obtain the workspace id from dotenv
    workspace_id_env = os.environ.get("CONVERSATION_WORKSPACE_ID")

    main_loop(conversation_apiobj, workspace_id_env)
Пример #3
0
    def get_watson_online_store():
        load_dotenv(os.path.join(os.path.dirname(__file__), ".env"))

        # Use these env vars first if set
        bot_id = os.environ.get("BOT_ID")
        slack_bot_token = os.environ.get('SLACK_BOT_TOKEN')
        conversation_username = os.environ.get("CONVERSATION_USERNAME")
        conversation_password = os.environ.get("CONVERSATION_PASSWORD")
        cloudant_username = os.environ.get("CLOUDANT_USERNAME")
        cloudant_password = os.environ.get("CLOUDANT_PASSWORD")
        cloudant_url = os.environ.get("CLOUDANT_URL")
        cloudant_db_name = os.environ.get("CLOUDANT_DB_NAME")

        # TODO: It looks like we'll want to make discovery required too.
        discovery_username = os.environ.get('DISCOVERY_USERNAME')
        discovery_password = os.environ.get('DISCOVERY_PASSWORD')
        discovery_environment_id = os.environ.get('DISCOVERY_ENVIRONMENT_ID')
        discovery_collection_id = os.environ.get('DISCOVERY_COLLECTION_ID')

        if not all((conversation_username, conversation_password,
                    cloudant_username, cloudant_password, cloudant_url,
                    discovery_username, discovery_password)):
            # If some of the service env vars are not set get them from VCAP
            vcap_env = None
            vcap_services = os.environ.get("VCAP_SERVICES")
            if vcap_services:
                vcap_env = json.loads(vcap_services)
            if vcap_env:
                conversation_creds = WatsonEnv.get_vcap_credentials(
                    vcap_env, 'conversation')
                conversation_username = \
                    conversation_username or conversation_creds['username']
                conversation_password = \
                    conversation_password or conversation_creds['password']

                cloudant_creds = WatsonEnv.get_vcap_credentials(
                    vcap_env, 'cloudantNoSQLDB')
                cloudant_username = \
                    cloudant_username or cloudant_creds['username']
                cloudant_password = \
                    cloudant_password or cloudant_creds['password']
                cloudant_url = cloudant_url or cloudant_creds['url']

                discovery_creds = WatsonEnv.get_vcap_credentials(
                    vcap_env, 'discovery')
                discovery_username = \
                    discovery_username or discovery_creds['username']
                discovery_password = \
                    discovery_password or discovery_creds['password']

        # If we still don't have all the above plus a few, then no WOS.
        if not all((slack_bot_token, conversation_username,
                    conversation_password, cloudant_username,
                    cloudant_password, cloudant_url, cloudant_db_name)):
            print(MISSING_ENV_VARS)
            return None

        if 'placeholder' in slack_bot_token:
            raise Exception("SLACK_BOT_TOKEN needs to be set correctly. "
                            "It is currently set to 'placeholder'.")
        slack_client = SlackClient(slack_bot_token)
        # If BOT_ID wasn't set, we can get it using SlackClient and user ID.
        if not bot_id:
            bot_id = WatsonEnv.get_slack_user_id(slack_client)
            if not bot_id:
                print("Error: Missing BOT_ID or invalid SLACK_BOT_USER.")
                return None

        conversation_client = ConversationV1(username=conversation_username,
                                             password=conversation_password,
                                             version='2016-07-11')

        cloudant_online_store = CloudantOnlineStore(
            Cloudant(cloudant_username,
                     cloudant_password,
                     url=cloudant_url,
                     connect=True), cloudant_db_name)
        #
        # Init Watson Discovery only if all the env vars are set.
        #
        discovery_client = None
        if all((discovery_username, discovery_password,
                discovery_environment_id, discovery_collection_id)):
            discovery_client = DiscoveryV1(version='2016-11-07',
                                           username=discovery_username,
                                           password=discovery_password)
        watsononlinestore = WatsonOnlineStore(bot_id, slack_client,
                                              conversation_client,
                                              discovery_client,
                                              cloudant_online_store)
        return watsononlinestore
Пример #4
0
from sttClient import *

# speech-to-text object credentials
credentials = ['67d89d3e-94d7-4232-8c87-0b588f60cc49', 'ibvlcVN5HH3x']
model = 'en-US_BroadbandModel'
fileInput = './recordings.txt'
dirOutput = './output'
contentType = 'audio/wav'
threads = '1'
optOut = True
tokenauth = True

# New conversation object - add to the library on
# https://www.ibmwatsonconversation.com
conversation = ConversationV1(username='******',
                              password='******',
                              version='2016-09-20')
# Text to speech module
text_to_speech = TextToSpeechV1(
    username='******',
    password='******',
    x_watson_learning_opt_out=True)  # Optional flag

# Replace with the context obtained from the initial request
context = {}

# Create a new workspace for useful conversations
workspace_id = '6846ffc4-07eb-45d9-a517-abe54e9f2dae'

# generate filename for audio output
unique_filename = uuid.uuid4()
Пример #5
0
@author: tatianarominahartinger
"""

#%%
import json
#import watson_developer_cloud
from watson_developer_cloud import ConversationV1

#para obtener las credenciales, dentro de un workspace ir a deploy->credentials

user = '******'
pass_ = 'Lw8yNivJxfCF'
ver = '2018-02-01'
wks_id = 'c8a68520-766f-4be9-a771-278502091801'

conversation = ConversationV1(username=user, password=pass_, version=ver)
#%%
from py2neo import Graph
from py2neo import Node, Relationship
from py2neo import cypher

# graph_1 = Graph()
# graph_2 = Graph(host="localhost")
graph = Graph(password='******')
#%%
#Creamos los nodos:


def que(nombre):
    query = "match(p:Pregunta),(x:" + categoria + ") where p.pregunta='" + categoria.lower(
    ) + "' merge (p)-[:ES]->(x)"
Пример #6
0
import os, requests
from watson_developer_cloud import ConversationV1, LanguageTranslatorV2
from flask import Flask, jsonify, json, request, render_template
import infermedica_api


infermedica_api.configure(app_id='8eab6cb8', app_key='ff87a9caf26433944a6236f19e70173f')

conversation = ConversationV1(
username= '******',
password= '******',
version= '2017-05-26'
)
workspace_id = '957755fd-3d4c-4b76-854e-92154d6887d0'

language_translator = LanguageTranslatorV2(
  url= "https://gateway.watsonplatform.net/language-translator/api",
  username= "******",
  password= "******"
)

app = Flask(__name__)

global context
context = {}

@app.route('/')
def Welcome():
    return app.send_static_file('webpage.html')

@app.route('/conversation', methods=['GET', 'POST'])
Пример #7
0
    def execute_dialog(self, inbound_message, outbound_message,context_chamada):
        if self.API_KEY:
            conversation = ConversationV1(
                version=self.VERSION_API,
                iam_apikey=self.API_KEY,
                url=self.API_URL
            )
        else:
            conversation = ConversationV1(
                version=self.VERSION_API,
                username=self.API_USER,
                password=self.API_PASS,
                url=self.API_URL
            )

        # Obtem o response
        try:
            self.logger.debug('[%s]INPUT - Workspace: [%s]', inbound_message.session_verbio, self.API_WORKSPACE)            
            self.logger.debug('[%s]INPUT - Text: [%s]', inbound_message.session_verbio, inbound_message.user_message)        
            # valida os objetos dict dentro do dicionário context
            inicio = datetime.datetime.now()
            response = conversation.message(
                            workspace_id=self.API_WORKSPACE,
                            input = {
                                "text": inbound_message.user_message
                            },
                            context = eval(context_chamada.context_watson)
                        )

            # Verificando tempo de resposta do watson
            fim = datetime.datetime.now()
            diff = fim-inicio
            #response = response.result            
            # LOG FUNCIONAL
            funcional_logger = logging.getLogger('funcional')
            funcional_logger.info(" ")
            funcional_logger.info("[%s] PROCESSADO PELO WATSON:", inbound_message.session_verbio)
            funcional_logger.info("[%s] Tempo de processo do Watson: %f:", inbound_message.session_verbio, diff.total_seconds()) 
            
            self.logger.debug("[%s]OUTPUT - Secs: [%f]", inbound_message.session_verbio, diff.total_seconds())
            self.logger.debug("[%s]OUTPUT - Watson Response: [%s]", inbound_message.session_verbio, response) 

            # Verificando se o watson retornou alguma frase para a sequência            
            if len(response["output"]["text"]) <= 0:
                funcional_logger.info("[%s] Erro Watson: Nenhum texto retornado", inbound_message.session_verbio)
                # Caso o watson não responda nada, solicita que o cliente repita. Representa uma falha no watson                                
                #Obtem uma resposta aleatoria de nao entendimento.
                misunderstood = get_list_on_redis('nao-entendimento')
                misunderstood = misunderstood.get(str(randint(1, len(misunderstood))),'Não entendi, você pode repetir')
                response = self.__change_answer_and_context__(response, misunderstood)

                self.logger.critical("[%s]OUTPUT - Empty text from Watson", inbound_message.session_verbio)
                self.logger.debug("[%s]OUTPUT - Code Response: [%s]", inbound_message.session_verbio, response)
            else:
                text_response = response["output"]["text"]
                funcional_logger.info("[%s] Resposta do Watson: %s", inbound_message.session_verbio, text_response)
            
            etapa_anterior = context_chamada.etapa            
            if len(response["intents"]) <= 0:                                                       
                funcional_logger.info("[%s] Erro Watson: Intent não identificada", inbound_message.session_verbio)
            else:
                intent = response["intents"][0]["intent"] if "intent" in response["intents"][0] else ""               	
                confidence = response["intents"][0]["confidence"] if "confidence" in response["intents"][0] else "" 
                funcional_logger.info("[%s] Intenção identificada: %s", inbound_message.session_verbio, intent)
                funcional_logger.info("[%s] Confiança: %f", inbound_message.session_verbio, confidence)
           
            # Valida confiaça retornada da intent dentro dos thresholds configurados
            # e muda a resposta se for necessário
            #response = self.__check_intent_confidence__(response, context_chamada,etapa_anterior)

            # Constrói o outbound_message e atualiza o contexto
            outbound_message = self.__create_outbound_message__(outbound_message,response)            
            outbound_message = self.set_registrar_chamada(outbound_message, inbound_message, context_chamada)
            outbound_message = self.set_flag_anatel(outbound_message, inbound_message)                        
            # TODO: Verificar se tem status no retorno da mensagem: if response.status != 200:  

        except HTTPError as err:
            # TODO: lançar exception correta
            raise err
        except BaseException as err:
            raise err

        return outbound_message
Пример #8
0
# Get Conversation Credentials
if 'VCAP_SERVICES' in os.environ:
    import json
    vcap_services = json.loads(os.environ['VCAP_SERVICES'])
    conversation_creds = vcap_services['conversation'][0]['credentials']
    USERNAME = conversation_creds['username']
    PASSWORD = conversation_creds['password']
else:
    from dotenv import load_dotenv, find_dotenv
    load_dotenv(find_dotenv())
    USERNAME = os.environ.get("CONVERSATION_USERNAME")
    PASSWORD = os.environ.get("CONVERSATION_PASSWORD")

# Set conversation service
conversation = ConversationV1(username=USERNAME,
                              password=PASSWORD,
                              version='2017-02-03')


def workspaces():
    return conversation.list_workspaces()['workspaces']


def workspace_info(workspace_id):
    ws = cache.get(workspace_id)
    if ws is None:
        ws = update_workspace(workspace_id)
    else:
        min_ws = conversation.get_workspace(workspace_id)
        if min_ws['updated'] != ws['updated']:
            ws = update_workspace(workspace_id)
    for row in readCSV:
        temp = []
        temp.append(row[1])
        temp.append(row[2])
        movies.append(temp)

emotion = "p"
y_value = 75
y1 = 75
text1 = "Start conversation with greeting!"

EMOTION_TONE_LABEL = 'emotion_tone'
THRESHOLD = 0.5

conversation = ConversationV1(username="******",
                              password="******",
                              version="2017-04-25")
tone_analyser = ToneAnalyzerV3(
    username="******",
    password="******",
    url="https://gateway.watsonplatform.net/tone-analyzer/api",
    version="2017-04-25")

workspace_id = "b3f9b097-f794-4dd9-8575-8fdb7180e1db"

payload = {'workspace_id': workspace_id, 'input': {'text': ""}}

root = Tk()
root.title("Mood-Based Activity Recommendation System")
frame = Frame(root, width=900, height=1000, bg='white')
frame.grid(row=0, column=0)
Пример #10
0
import json
from watson_developer_cloud import ConversationV1
from ay_news_api import *
import pickle
from flask import Flask, render_template, request
from mySportsFeedAPI import *
app = Flask(__name__)

with open('credentials.json') as js:
    credentials = json.load(js)

conversation = ConversationV1(username=str(credentials['username']),
                              password=str(credentials['password']),
                              version='2017-04-21')

workspace_id = '73a74624-91c6-447c-86df-b0a8a3eb6724'


class Team:
    def __init__(self, city, nfl, mlb, nba, nhl):
        self.leagues = {}
        self.leagues['NFL'] = nfl
        self.leagues['MLB'] = mlb
        self.leagues['NBA'] = nba
        self.leagues['NHL'] = nhl


teams = {}
teams['Boston'] = Team("Boston", [], ["Red Sox"], ["Celtics"], ["Bruins"])
teams['New England'] = Team("New England", ["Patriots"], [], [], [])
teams['Chicago'] = Team("Chicago", ["Bears"], ["White Sox", "Cubs"], ["Bulls"],
Пример #11
0
from watson_developer_cloud import ConversationV1
import json

conversation = ConversationV1(username='******',
                              password='******',
                              version='2017-05-26')

#response = conversation.list_workspaces()
workspaceID = 'c76dde4b-deb6-4e10-87df-08778b85ce53'

response = conversation.message(workspace_id=workspaceID, input={'text': 'S'})

print(json.dumps(response, indent=2))
Пример #12
0
    def get_watson_online_store():
        load_dotenv(os.path.join(os.path.dirname(__file__), ".env"))

        # Use these env vars first if set
        bot_id = os.environ.get("BOT_ID")
        slack_bot_token = os.environ.get('SLACK_BOT_TOKEN')
        conversation_username = os.environ.get("CONVERSATION_USERNAME")
        conversation_password = os.environ.get("CONVERSATION_PASSWORD")
        cloudant_username = os.environ.get("CLOUDANT_USERNAME")
        cloudant_password = os.environ.get("CLOUDANT_PASSWORD")
        cloudant_url = os.environ.get("CLOUDANT_URL")
        cloudant_db_name = os.environ.get("CLOUDANT_DB_NAME")
        discovery_username = os.environ.get('DISCOVERY_USERNAME')
        discovery_password = os.environ.get('DISCOVERY_PASSWORD')

        if not all((conversation_username, conversation_password,
                    cloudant_username, cloudant_password, cloudant_url,
                    discovery_username, discovery_password)):
            # If some of the service env vars are not set get them from VCAP
            vcap_env = None
            vcap_services = os.environ.get("VCAP_SERVICES")
            if vcap_services:
                vcap_env = json.loads(vcap_services)
            if vcap_env:
                conversation_creds = WatsonEnv.get_vcap_credentials(
                    vcap_env, 'conversation')
                conversation_username = \
                    conversation_username or conversation_creds['username']
                conversation_password = \
                    conversation_password or conversation_creds['password']

                cloudant_creds = WatsonEnv.get_vcap_credentials(
                    vcap_env, 'cloudantNoSQLDB')
                cloudant_username = \
                    cloudant_username or cloudant_creds['username']
                cloudant_password = \
                    cloudant_password or cloudant_creds['password']
                cloudant_url = cloudant_url or cloudant_creds['url']

                discovery_creds = WatsonEnv.get_vcap_credentials(
                    vcap_env, 'discovery')
                discovery_username = \
                    discovery_username or discovery_creds['username']
                discovery_password = \
                    discovery_password or discovery_creds['password']

        # If we still don't have all the above plus a few, then no WOS.
        if not all(
            (slack_bot_token, conversation_username, conversation_password,
             cloudant_username, cloudant_password, cloudant_url,
             cloudant_db_name, discovery_username, discovery_password)):
            print(MISSING_ENV_VARS)
            return None

        # Instantiate Watson Conversation client.
        conversation_client = ConversationV1(username=conversation_username,
                                             password=conversation_password,
                                             version='2017-05-26')

        # Instantiate Cloudant DB.
        cloudant_online_store = CloudantOnlineStore(
            Cloudant(cloudant_username,
                     cloudant_password,
                     url=cloudant_url,
                     connect=True), cloudant_db_name)

        # Instantiate Watson Discovery client.
        discovery_client = DiscoveryV1(version='2017-09-01',
                                       username=discovery_username,
                                       password=discovery_password)

        # Instantiate Slack chatbot.
        if 'placeholder' in slack_bot_token:
            print("SLACK_BOT_TOKEN needs to be set correctly. "
                  "It is currently set to 'placeholder'.")
            slack_client = None
        else:
            slack_client = SlackClient(slack_bot_token)
            # If BOT_ID wasn't set, we can get it using SLACK_BOT_USER.
            if not bot_id:
                bot_id = WatsonEnv.get_slack_user_id(slack_client)
                if not bot_id:
                    print("Error: Missing BOT_ID or invalid SLACK_BOT_USER.")
                    return None

        # Start Watson Online Store app.
        watsononlinestore = WatsonOnlineStore(bot_id, slack_client,
                                              conversation_client,
                                              discovery_client,
                                              cloudant_online_store)
        return watsononlinestore
Пример #13
0
import numpy as np
from flask import session
from flask import render_template
from flask import request, url_for, make_response,redirect
from watson_developer_cloud import ConversationV1
from os.path import join, dirname
from flask import Flask
import csv
from random import shuffle

#import pysolr
#from watson_developer_cloud import RetrieveAndRankV1

	
conversation = ConversationV1(
    username='******',
    password='******',
    version='2017-02-03')


	
print("inside global application")

#conv_workspace_id = '72e3ba4d-5ca3-4fa4-b696-4b790d55cf5d'
# conv_workspace_id = '5c2446b9-28a3-40f9-906e-b46350f494b3'
conv_workspace_id = '5e685fd6-a971-47f1-af9b-ab409f4c5a36'

app = Flask(__name__, static_url_path='/static')
app.secret_key = os.urandom(24)

@app.route("/")
def get():
Пример #14
0
import json
import rospy
from std_msgs.msg import String

from watson_developer_cloud import ConversationV1
answer = "a"

conversation = ConversationV1(username='******',
                              password='******',
                              version='2017-05-26')


def callback(data):
    pub = rospy.Publisher('Robot_response', String, queue_size=10)

    #rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)
    context = {}

    workspace_id = 'b862e7b6-82f8-4e50-9ebd-e3be4c07d9a9'

    response = conversation.message(workspace_id=workspace_id,
                                    message_input={'text': data.data},
                                    context=context)
    #print(json.dumps(response, indent=2))
    answer = response[u'output'][u'text'][0]

    pub.publish(String(answer))

    print answer

Пример #15
0
# input in Python 2.7 evals(), so lets not use it.
try: input = raw_input
except NameError: pass

### Conversation variables ###
# ctx you copy and paste straight from the conversation service credentials (if using new layout)
ctx = {
  "url": "https://gateway.watsonplatform.net/conversation/api",
  "password": "******",
  "username": "******"
}

# workspace id can be gotten by "view details" in the drop down menu of the conversation tile.
workspaceId = '24541008-3420-4a39-ba7d-b2ebf4337e2b'
##############################

conv = ConversationV1(version='2016-09-20', username=ctx.get('username'),password=ctx.get('password'))

context = {} 
i = ''

while i != '...':
    i = input()
    message = { 'text': i }
    if i != '...': 
        response = conv.message(workspace_id = workspaceId, message_input = message, context = context)
        context = response['context']
        print(json.dumps(response))
        #print(json.dumps(response['output']['text']))

Пример #16
0
def message(bot, update):
   # print(places)
    print('Received an update')
    global context

   # conversation = ConversationV1(username='******',  # TODO
    #                              password='******',  # TODO
	#			  version='2018-02-16')
    conversation = ConversationV1(version='2018-07-10',
                        iam_api_key='ypiFBBkjolaveQQBhjg6yIFnLZAZzxO7KY7dJ29Mc41F',
                        url='https://gateway-wdc.watsonplatform.net/assistant/api')

    
    print('Message' + update.message.text)
    msg=update.message.text

    # get response from watson
    response = conversation.message(
        workspace_id='62b52706-21b5-428d-9bba-780ccd785b6e',  # TODO
        input={'text': update.message.text},
        context=context)
    #print('hello123')
    s=0
   
       
   #update.message.reply(img=urllib2.urlopen('index.jpeg').read())
    context = response['context']
    print(context)
    if "places" in context.keys() and "category" in context.keys():
        pl=context["places"]
        ct=context["category"]
        print(ct)
        str=""
        print(context["places"])
        conn=sqlite3.connect('mydatabase.db')
        c=conn.cursor()
        print("Entered SQL")
        try:
           c.execute("SELECT place FROM cat WHERE state=? and category=?",(pl,ct))
           rows=c.fetchall()
           update.message.reply_text("You can visit these places")
           for row in rows:
                update.message.reply_text(str.join(row))
                #update.message.reply_text(row)
           c.execute("SELECT name FROM images WHERE st=? and category=?",(pl,ct))
           rows=c.fetchall()

           for row in rows:
            #update.message.reply_text(str.join(row))
               print(row)
               print(stt+stt.join(row))
               bot.sendPhoto(chat_id=599070941,photo=open(stt+stt.join(row), 'rb'))

           conn.commit()
           conn.close()
        except:
           print("Fail")
        #del context["places"]
        del context["category"]

#insert the details of booking
    id1=" "
    name=""
    if "person" in context.keys() and "number" in context.keys() and "date" in context.keys():
        person=context["person"]
        number=context["number"]
        date=context["date"]
        conn=sqlite3.connect('mydatabase.db')
        c=conn.cursor()
        print("Enter sql")
       # c.execute("SELECT person from booking")
        #print("hat man")
        #rows=c.fetchall()
        #print("am ")
        #print(rows)
        #for row in rows:
         #  if person==name.join(row):
          #    update.message.reply_text("This name already exists..Try with different one!") 
        c.execute("INSERT INTO booking(person,number,date) values(?,?,?) ",(person,number,date))
        print("hhhhhhiiiiiii")
        conn.commit()
        conn.close()
        conn=sqlite3.connect('mydatabase.db')
        c=conn.cursor()
        print("kk")
        c.execute("SELECT rowid FROM booking WHERE person=? and number=? and date=?",(person,number,date))
        rows=c.fetchall()
        print("gggg")
        #update.message.text("Thank you for booking" )
        for row in rows:
            print(row)
            update.message.reply_text(row)
            #update.message.reply_text(row)
            print(id1)
        del context["person"]
        del context["number"]
        del context["date"]
        
        conn.commit()
        conn.close()
#cancellation
    if "cancel" in context.keys() and "person" in context.keys() and "ask" in context.keys():
        cancel=""
        person=context["person"]
        conn=sqlite3.connect('mydatabase.db')
        c=conn.cursor()
        print("Enter sql for delete")
       # c.execute("SELECT rowid from booking where person=?",(person,))
        #rows=c.fetchall()
        #for row in rows:
         #   update.message.reply_text(cancel.join(row))
        ask=context["ask"]
        if ask=="Yes":
            c.execute("DELETE FROM booking where person=? ",(person,))
            update.message.reply_text("Thank you")
        conn.commit()
        conn.close()
      
    # sql(pl)
    # build response
    resp = ''
    for text in response['output']['text']:
       print("Execute1")
       resp += text
    print('Resp',resp)
    update.message.reply_text(resp)
    if resp=="Please enter the state you want to visit..":
       flag=1
       print("after flag=",flag)
    
    print("Bad")
    print(ref)
 
    if (ref==20):
        sql()
    if ((flag==1) and (ref==10)):
        ref=20
        print('ref=',ref)
        return
   
    print("after2 flag=",flag)
Пример #17
0
workspace_id = '55981191-57ee-4cdb-8402-e586a126f174'

print('Environment Variable VCAP_SERVICES')
vcap_services = os.getenv('VCAP_SERVICES')
print(json.dumps(vcap_services, indent=2))

vcap = json.loads(os.getenv("VCAP_SERVICES"))['conversation']
print('VCAP Services vcap %s'  %vcap )
cl_username = vcap[0]['credentials']['username']
print('VCAP Services cl_username %s'  %cl_username )
cl_password = vcap[0]['credentials']['password']
print('VCAP Services cl_password %s'  %cl_password )

# Call Conversation Service
conversation = ConversationV1(
    username = cl_username,
    password = cl_password,
    version='2016-09-20')

logging.debug('Checked Conversation Service is working')
response = conversation.message(workspace_id=workspace_id, message_input={'text': 'Hello.'})
print(json.dumps(response, indent=2))
            
ask = Ask(app, "/")

@ask.launch

def new_game():

    welcome_msg = render_template('welcome')

    return question(welcome_msg)
from souschef.graph_recipe_store import GraphRecipeStore
from souschef.recipe import RecipeClient
from souschef.sns_client import SNSClient
from souschef.souschef import SousChef

if __name__ == "__main__":
    try:
        # load environment variables
        load_dotenv(os.path.join(os.path.dirname(__file__), ".env"))
        slack_bot_id = os.environ.get("SLACK_BOT_ID")
        slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))
        conversation_workspace_id = os.environ.get("CONVERSATION_WORKSPACE_ID")
        conversation_client = ConversationV1(
            username=os.environ.get("CONVERSATION_USERNAME"),
            password=os.environ.get("CONVERSATION_PASSWORD"),
            version='2016-07-11'
        )
        recipe_client = RecipeClient(os.environ.get("SPOONACULAR_KEY"))
        recipe_store = GraphRecipeStore(
            IBMGraphClient(
                os.environ.get("GRAPH_API_URL"),
                os.environ.get("GRAPH_USERNAME"),
                os.environ.get("GRAPH_PASSWORD")
            ),
            os.environ.get("GRAPH_ID")
        )
        sns_client = SNSClient(
            os.environ.get("SNS_API_URL"),
            os.environ.get("SNS_API_KEY")
        )
Пример #19
0
from dotenv import load_dotenv, find_dotenv

from watson_developer_cloud import ConversationV1
from watson_developer_cloud import ToneAnalyzerV3

# import tone detection
import tone_detection

# load the .env file containing your environment variables for the required
# services (conversation and tone)
load_dotenv(find_dotenv())

# replace with your own conversation credentials or put them in a .env file
conversation = ConversationV1(username=os.environ.get('CONVERSATION_USERNAME')
                              or 'YOUR SERVICE NAME',
                              password=os.environ.get('CONVERSATION_PASSWORD')
                              or 'YOUR PASSWORD',
                              version='2016-09-20')

# replace with your own tone analyzer credentials
tone_analyzer = ToneAnalyzerV3(
    username=os.environ.get('TONE_ANALYZER_USERNAME') or 'YOUR SERVICE NAME',
    password=os.environ.get('TONE_ANALYZER_PASSWORD') or 'YOUR SERVICE NAME',
    version='2016-02-11')

# replace with your own workspace_id
workspace_id = os.environ.get('WORKSPACE_ID') or 'YOUR WORKSPACE ID'

# This example stores tone for each user utterance in conversation context.
# Change this to false, if you do not want to maintain history
maintainToneHistoryInContext = True
Пример #20
0
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = '******'
app.config['MAIL_PASSWORD'] = '******'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True

mail = Mail(app)

# SocketIO
socketio = SocketIO(app, async_mode='eventlet')
thread = None

# Watson Conversation
conversation = ConversationV1(
  username="******",
  password="******",
  version='2017-05-26'
)

workspace_id = '87e1fc89-276d-4acb-a691-74e6469b38db'

context = {}
last_response = ""

# DashDB
#Enter the values for you database connection
dsn_driver = "IBM DB2 ODBC DRIVER"
dsn_database = "BLUDB"
dsn_hostname = "dashdb-txn-flex-yp-lon02-71.services.eu-gb.bluemix.net"
dsn_port = "50000"
dsn_protocol = "TCPIP"
Пример #21
0
def message(bot, update):
    print('Received an update')
    global context
    conversation = ConversationV1(
        username='******',  # TODO
        password='******',  # TODO
        version='2018-02-16')
    response = conversation.message(workspace_id='workspace_ID',
                                    input={'text': update.message.text},
                                    context=context)
    print(json.dumps(response, indent=2))
    context = response['context']
    if not response['intents']:
        pass
    else:
        global y
        try:
            if response['intents'][-1]['intent'] == 'greetings' and response[
                    'entities'][-1]['entity'] == 'yes':
                global skey
                global akey
                skey = response['context']['secret_key']
                akey = response['context']['access_key']
                global client
                client = boto3.client(
                    'ec2',
                    aws_access_key_id=akey,
                    aws_secret_access_key=skey,
                    region_name='ap-south-1',
                )
                global abcdef
                abcdef = update.message.chat.id
            try:
                if response['context']['no_of_instances'] is not None:
                    y = response['context']['no_of_instances']
            except KeyError:
                pass
            try:
                if response['intents'][-1]['intent'] == 'start_instance':
                    global tree
                    tree = response['context']['ec2']
            except KeyError:
                pass
            try:
                if response['context']['os'] is not None:
                    version = response['context']['os']
                    print('OS version : ', version)
                    if version == 'windows':
                        imageid = 'ami-ae1627c1'
                    else:
                        imageid = 'ami-d783a9b8'
            except KeyError:
                pass
            try:
                if response['intents'][-1]['intent'] == "terminate":
                    global unicorn
                    unicorn = response['context']['instance']
            except KeyError:
                pass
            try:
                if response['intents'][-1]['intent'] == "stop_instance":
                    global unicorn1
                    unicorn1 = response['context']['ec2id']
            except KeyError:
                pass
        except IndexError:
            pass
        except NameError:
            pass

        x = str(response['intents'][-1]['intent'])
        try:
            if x == 'create_ec2':
                try:
                    if y:
                        b.create(ima=imageid, abcd=y)
                except NameError:
                    print(NameError)
                    pass
            elif x == 'start_instance':
                b.describe()
                showa(bot, update)
                b.start(tree)
            elif x == 'stop_instance':
                b.describe()
                showa(bot, update)
                b.stop(unicorn1)
            elif x == 'terminate':
                b.describe()
                showa(bot, update)
                b.terminate(unicorn)
            elif x == 'describe_instance':
                b.describe()
                showa(bot, update)
        except NameError:
            print(NameError)
    resp = ''
    for text in response['output']['text']:
        resp += text
    update.message.reply_text(resp)
Пример #22
0
def message(bot, update):
    print('Received an update')
    global context

    conversation = ConversationV1(username='******',  # TODO
                                  password='******',  # TODO
                                  version='2018-02-16')

    print(conversation)
    print(type(context))
    print(context)

    print('hello' + update.message.text)

    # get response from watson
    response = conversation.message(
        workspace_id='d3c60545-4cd6-48d6-a853-ad2de1682988',  # TODO
        input={'text': update.message.text},
        context=context)
    # print('hello thw response is ::::::::::::::::;', response)
    s = 0

    num_intents = len(response['intents'])
    num_entities = len(response['entities'])

    if num_intents != 0  and response['intents'][0]['intent'] == 'get_menu':
        s = 1
        conn = sqlite3.connect('test1.db')
        c = conn.cursor()
        c.execute("SELECT * FROM menu")
        rows = c.fetchall()

        for row in rows:
            update.message.reply_text("Item: " + row[0] + "\t Price:" + str(row[1]))
        update.message.reply_text("select from above list only")
        conn.commit()
        conn.close()

    #if len(response['entities']) > 0 and response['entities'][0]['entity'] == 'sys-number':
        #if num_entities > 0:
            #user_contact_num = response['entities'][0]['value']
	     


    #if len(response['entities']) != 0  and response['entities'][0]['entity'] == 'sys-number':
     #   update.message.reply_text("Thank you")
    #print(json.dumps(response, indent=2))
    context = response['context']

    # c.execute("INSERT INTO address(address,pincode) VALUES(?,?)")
    # c.execute("SELECT * FROM address")
    # rows=c.fetchall()
    # for row in rows:
    # update.message.reply_text("Address: " + row[0] + "\t Pincode:" + str(row[1])

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

    # build response
    resp = ''
    for text in response['output']['text']:
        resp += text
    if s != 1:
        update.message.reply_text(resp)
Пример #23
0
from nltk.tokenize import word_tokenize
import random
import tensorflow as tf
import json
import tflearn
import pickle
import pyttsx3
import numpy as np
from watson_developer_cloud import ConversationV1

lemmatizer = WordNetLemmatizer()

with open('./cred.txt', 'r') as f:
    cred = json.loads(f.read())
conversation = ConversationV1(username=cred['username'],
                              password=cred['password'],
                              version='2018-06-10')
context = {}


def initVoice():
    engine = pyttsx3.init()
    rate = engine.getProperty('rate')
    engine.setProperty('rate', rate - 20)
    voices = engine.getProperty('voices')
    engine.setProperty('voice', voices[2].id)
    return engine


def setVoice(engine, voice=1):
    voices = engine.getProperty('voices')
Пример #24
0
    "apiKey": "AIzaSyAS-xxxxxxxxxxxxxxxxxx",
    "authDomain": "xxxxxxxxxxxxxxx.firebaseapp.com",
    "databaseURL": "https://xxxxxxxxxx.firebaseio.com",
    "storageBucket": "xxxxxxxxxxx.appspot.com",
}
firebase = pyrebase.initialize_app(config)
db = firebase.database()

app = Flask(__name__)
app.config.from_object('config.ProductionConfig')

socketio = SocketIO(app, async_mode='eventlet')
thread = None

conversation = ConversationV1(username='******',
                              password='******',
                              version='2016-07-11')
workspace_id = 'xxxxxxxxxxxxxxxxxx'
context = {}
last_response = ""

response = conversation.message(workspace_id=workspace_id)
context = response["context"]


@app.route('/')
def index():
    user_ip = request.remote_addr
    user_agent = request.headers.get('User-Agent')
    session['unique_conversation_id'] = str(user_ip) + "__" + str(user_agent)
    context["conversation_id"] = str(
Пример #25
0
from ws4py.client.threadedclient import WebSocketClient
from watson_developer_cloud import ConversationV1
import sys, signal, snowboydecoder, re, base64, json, ssl, subprocess, threading, time

# Initialising TTS global variables
speech_received = False  # has speech been returned by Watson?
transcript = "silence"  # default value for speech if nothing returned

# Initialise snowboy global variables
model = "./K9.pmdl"
interrupted = False

# Initialise conversation global variables
conversation = ConversationV1(username='******',
                              password='******',
                              version='actual conversation version here')
workspace_id = 'your conversation workspace id here'


def signal_handler(signal, frame):
    global interrupted
    interrupted = True


def interrupt_callback():
    global interrupted
    return interrupted


signal.signal(signal.SIGINT, signal_handler)
Пример #26
0
from watson_developer_cloud import ConversationV1
import json
import re

conversation = ConversationV1(
    username = '******',
    password = '******',
    version = '2018-02-16'
)

workspace_name = 'Chatbot'
workspace_id = '0053d8c4-64cc-4f83-b0b3-39be8c6e5a0f'

def sendInitialMessage():
    inputMessage = {'text': ''}
    response = conversation.message(workspace_id = workspace_id, input = inputMessage)
    #context = response['context']
    #print(response)
    return response

def sendMessage(message, context):
    message = re.sub('[\r\t\n]', '', message)
    inputMessage = {'text': message}
    response = conversation.message(workspace_id = workspace_id, input = inputMessage, context = context)
    #print(response)
    return response

'''
context = sendInitialMessage()
while(True):
    message = input("")
Пример #27
0
from flask import Flask, render_template
import os
from watson_developer_cloud import ConversationV1
import random
from random import randint

app = Flask(__name__)
conversation = ConversationV1(username='******',
                              password='******',
                              version='2017-05-26')
context_val = {}


@app.route('/')
@app.route('/index')
def chat():
    return render_template('chat.html')


@app.route('/send_message/<message>')
def send_mesage(message):
    global context_val
    response = conversation.message(
        workspace_id='913aef7a-8ec6-4dfd-a3d4-9f92ea7a9b54',
        input={'text': str(message)},
        context=context_val)

    print(context_val.keys())
    context_val = response['context']
    if ('nearest_pizza_restaurant' not in context_val.keys()):
        context_val['nearest_pizza_restaurant'] = find_nearest_restaurants()
Пример #28
0
# except psycopg2.DatabaseError:
#     if con:
#         con.rollback()

#     print('Error')

# finally:

#     if con:
#         con.close()

app = Flask(__name__)

CONVERSATION_WORKSPACE_ID = "229647e2-25a3-446c-9050-09eeda995c2d"
conversation = ConversationV1(username='******',
                              password='******',
                              version='2017-04-21')

# Statuses for each action
STATUS_ERROR = 400
STATUS_SUCCESS = 200

api = Api(app)
CORS(app, resources={r"/*": {"origins": "*"}})


class Hello(Resource):
    def get(self, text):

        if os.getenv("conversation_workspace_id") is not None:
            workspace_id = os.getenv("conversation_workspace_id")
Пример #29
0
import json
from watson_developer_cloud import ConversationV1

#########################
# message
#########################

conversation = ConversationV1(
    username='******',
    password='******',
    version='2016-09-20')

# replace with your own workspace_id
workspace_id = '0a0c06c1-8e31-4655-9067-58fcac5134fc'

response = conversation.message(workspace_id=workspace_id, message_input={
    'text': 'What\'s the weather like?'})
print(json.dumps(response, indent=2))

# When you send multiple requests for the same conversation, include the
# context object from the previous response.
# response = conversation.message(workspace_id=workspace_id, message_input={
# 'text': 'turn the wipers on'},
#                                context=response['context'])
# print(json.dumps(response, indent=2))

#########################
# workspaces
#########################

response = conversation.create_workspace(name='test_workspace',
Пример #30
0
key = 'key-0335ffc6179bb9f65d104cf06eb11aae'
sandbox = 'sandbox102ac7d1115646e1a481e5ef5dce6f0b.mailgun.org'

request_url = 'https://api.mailgun.net/v2/{0}/messages'.format(sandbox)

#Opening Files
with open('config.json') as data_file:
    config = json.load(data_file)

with open('users.json') as data_file:
    users = json.load(data_file)

# Setting up Watson API's
conversation = ConversationV1(username=config['conversation']['username'],
                              password=config['conversation']['password'],
                              version='2017-02-03')

tone_analyzer = ToneAnalyzerV3(username=config['watson']['username'],
                               password=config['watson']['password'],
                               version='2016-05-19')

# Variables
global context
context = {}
workspace_id = 'fba7b3e5-6881-416c-9cf1-578fce2a9fee'


def analyseTone(chatMessage):
    toneData = tone_analyzer.tone(
        text=chatMessage)['document_tone']['tone_categories']