예제 #1
0
 def __init__(self):
     #You need to change this for it to match your account
     self.conv = ConversationV1(
         username=“00000000000000000000000000”,
         password=“0000000000000”,
         version='2016-09-20')
     self.workspace_id=‘000000000000000000’
예제 #2
0
def getConvResponse():
    conversation = ConversationV1(username=conversationUser,
                                  password=conversationPassword,
                                  version='2017-04-21')

    convText = request.form.get('convText')
    convContext = request.form.get('context')

    if convContext is None:
        convContext = "{}"

    jsonContext = json.loads(convContext)
    response = conversation.message(workspace_id=workspace_id,
                                    input={
                                        'text': convText,
                                    },
                                    context=jsonContext)

    reponseText = response["output"]["text"]
    responseDetails = {
        'responseText': reponseText[0],
        'context': response["context"]
    }

    return jsonify(results=responseDetails)
예제 #3
0
def conversation(request):

    # get 요청의 경우
    if request.method == 'GET':

        # api 신임 정보 입력
        conversation = ConversationV1(
            username='******',
            password='******',
            version='2016-09-20')

        # 문맥 불러오기
        context = json.loads(request.GET.get('context', '{}'))

        # 저장소 지정
        workspace_id = '95e19486-e402-4c2b-9007-b0b36be7b066'

        # api 호출
        response = conversation.message(
            workspace_id=workspace_id,
            message_input={'text': request.GET['message']},
            context=context)

        # 클라이언트로 응답 반환
        data = {
            'answer': response['output']['text'],
            'context': response['context']
        }
        json_data = json.dumps(data)
        return HttpResponse(json_data, content_type='application/json')

    # api 응답에 실패한 경우 fail 반환
    data = {'answer': 'fail'}
    json_data = json.dumps(data)
    return HttpResponse(json_data, content_type='application/json')
예제 #4
0
 def __init__(self):
     self._conversation = ConversationV1(
         username=self.USERNAME,
         password=self.PASSWORD,
         version=self.VERSION
     )
     self._context = {}
예제 #5
0
    def __init__(self, username, password, version, workspace_id):
        self.conversation = ConversationV1(username=username,
                                           password=password,
                                           version=version)

        self.workspace_id = workspace_id
        self.context = None
예제 #6
0
    def __init__(self, user_store, dialog_store, conversation_username,
                 conversation_password, conversation_workspace_id,
                 foursquare_client_id, foursquare_client_secret,
                 profile_analysis):
        """
        Creates a new instance of HealthBot.
        Parameters
        ----------
        user_store - Instance of CloudantUserStore used to store and retrieve users from Cloudant
        dialog_store - Instance of CloudantDialogStore used to store conversation history
        conversation_username - The Watson Conversation username
        conversation_password - The Watson Converation password
        conversation_workspace_id - The Watson Conversation workspace ID
        foursquare_client_id - The Foursquare Client ID
        foursquare_client_secret - The Foursquare Client Secret
        """
        self.user_store = user_store
        self.dialog_store = dialog_store
        self.conversation_client = ConversationV1(
            username=conversation_username,
            password=conversation_password,
            version='2016-07-11')
        self.conversation_workspace_id = conversation_workspace_id

        # self.profileAnalysis = "introvert"
        self.profileAnalysis = profile_analysis

        if foursquare_client_id is not None and foursquare_client_secret is not None:
            self.foursquare_client_id = foursquare_client_id
            self.foursquare_client_secret = foursquare_client_secret
        else:
            self.foursquare_client_id = None
            self.foursquare_client_secret = None
예제 #7
0
    def converse(self, text):

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

        workspace_id = '769ec18f-f67b-4d40-9611-8ce3487545da'

        response = conversation.message(workspace_id=workspace_id,
                                        message_input={'text': text})

        print json.dumps(response)

        intent = response["intents"][0]["intent"]

        if intent == "TipOfTheDay" or intent == "NewWord":
            entity_type = "None"
            entity_value = "None"
        else:
            entity_type = response["entities"][0]["entity"]
            entity_value = response["entities"][0]["value"]

        data_json = {
            "intent": intent,
            "entity_type": entity_type,
            "entity_value": entity_value
        }

        return json.dumps(data_json)
예제 #8
0
    def send_message(self, first, con_id=None):
        conversation = ConversationV1(
            username='******', password='******',
            version='2017-05-26')  # Latest version of Watson Conversation

        # replace with your own workspace_id
        workspace_id = '<workspaceid>'

        if first:
            response = conversation.message(
                workspace_id=workspace_id,
                message_input={'text': self.message})
        else:
            response = conversation.message(
                workspace_id=workspace_id,
                message_input={'text': self.message},
                context=con_id)
        output = response["output"]["text"][0]
        if output == "":
            output = response["output"]["text"][1]
        conversation_id = response["context"]
        # print(output)
        # print(type(output))
        print(json.dumps(response))

        return output, conversation_id
예제 #9
0
def message(bot, update):
    print('Received an update')
    global context

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

    # get response from watson
    response = conversation.message(
        workspace_id='00433057-81db-4e1e-ac1e-ae6076790f6e',
        input={'text': update.message.text},
        context=context)
    print(json.dumps(response, indent=2))
    
    context = response['context']
    try:
	if ((context['Temperature']=='yes' and context['Fatigue']=='yes' and context['Chill']=='yes') or (context['Temperature']=='yes')) :
    		update.message.reply_text('You may have fever.')
		m="You can take "+db.get_med('Fever')
		update.message.reply_text(m)
		del context['Temperature']
		del context['Fatigue']
		del context['Chill']
		
    except Exception, e:
	print('Exception',e)
예제 #10
0
파일: api.py 프로젝트: ustc-mcc/iStrong
def chat(input):
	conversation = ConversationV1(
	    username='******',
	    password='******',
	    version='2017-04-21')
	
	# replace with your own workspace_id
	workspace_id = '9bdc4eda-e512-4e27-9994-1bc2343ce8d1'
	
	response = conversation.message(workspace_id=workspace_id, message_input={
	    'text': input})
	output = json.dumps(response, indent=7)
	#print output# = json.dumps(response, indent=7)
	output = json.loads(output)
	if len(output['intents']) < 1:
		intent = 'not recognized'
	else:		
		intent = output['intents'][0]['intent']
	reply = output['output']['text'][0]
	print 'intent:', intent
	if intent == 'wake' or intent == 'start' or intent == 'bye':
		sign = intent
	else:
		sign = 'talk'
	return reply, sign
예제 #11
0
    def __init__(self):
        if not os.environ.get('SLACK_BOT_TOKEN'):
            sys.exit("No environment variable \"SLACK_BOT_TOKEN\" found.")
        self.slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))
        if not self.slack_client:
            sys.exit("Could not instantiate slack client. Wrong Token?")

        self.BOT_ID = self._get_bot_id()
        self.AT_BOT = "<@" + self.BOT_ID + ">"

        if not os.environ.get('GOOGLE_MAPS_API_TOKEN'):
            sys.exit("No environment variable \"GOOGLE_MAPS_API_TOKEN\" found.")
        self.gmaps = GoogleWrapper(os.environ.get('GOOGLE_MAPS_API_TOKEN'))
        if not self.gmaps:
            sys.exit("Could not instantiate Google Maps client. Wrong Token?")

        if not os.getenv('VCAP_SERVICES'):
            self.logger.warning("No VCAP_SERVICES found. Running without Bluemix Services.")
            self.USES_WATSON = False
            self.logger.warning("USES_WATSON is {}".format(self.USES_WATSON))
        else:
            vcap_services = json.loads(os.getenv('VCAP_SERVICES'))
            self.WATSON_USER = vcap_services['conversation'][0]['credentials']['username']
            self.WATSON_PASSWORD = vcap_services['conversation'][0]['credentials']['password']
            self.WATSON_WORKSPACE_ID = os.environ.get('WATSON_WORKSPACE_ID')
            self.conversation = ConversationV1(
                username=self.WATSON_USER,
                password=self.WATSON_PASSWORD,
                version= self.WATSON_CONVERSATION_VERSION
            )

        self.users = {}
        self.messages = self._load_config(self.MESSAGES_CONFIG_FILE)
        self.intents = self._load_config(self.INTENTS_CONFIG_FILE)
예제 #12
0
def run_cross_validation(folds, data):
    """
    Creates a workspace from each fold's training data, and
    computes accuracy based on the fold's testing data

    Args:
        folds (list): An iterator over a list of folds
        data (ndarray): A numpy 2d array of the intents and examples

    Returns:
        list: A list of the accuracies from each of the created workspaces
    """

    # array to hold accuracy for each fold
    accuracies = []

    # create a conversation service instance with your credentials
    conversation = ConversationV1(username=os.environ['CONVERSATION_USERNAME'],
                                  password=os.environ['CONVERSATION_PASSWORD'],
                                  version='2017-05-26')

    # clean up from previous runs
    # existing_workspaces = conversation.list_workspaces()['workspaces']
    # for workspace in existing_workspaces:
    #     conversation.delete_workspace(workspace_id=workspace['workspace_id'])

    # loop through the k folds
    for train_indices, test_indices in folds:
        train_data = data[train_indices]
        test_data = data[test_indices]
        train_map = {
            label: map(CreateExample, [example[0] for example in examples])
            for label, examples in groupby(train_data, itemgetter(1))
        }
        create_intent_objs = [
            CreateIntent(label, examples=examples)
            for label, examples in train_map.items()
        ]

        res = conversation.create_workspace(name='k-fold-test',
                                            intents=create_intent_objs)
        wid = res['workspace_id']

        # wait until training is done
        while conversation.get_workspace(wid)['status'] != 'Available':
            pass

        y_true = []
        y_pred = []
        # test the workspace with the corresponding validation data
        test_size = len(test_indices)
        correct = 0
        for example, label in test_data:
            res = conversation.message(workspace_id=wid,
                                       input={'text': example})
            top_label = res['intents'][0]['intent']
            y_true.append(top_label)
            y_pred.append(label)

    return classification_report(y_true, y_pred)
예제 #13
0
 def __init__(self, user_store, dialog_store, conversation_username,
              conversation_password, conversation_workspace_id, weather_id,
              weather_password):
     """
     Creates a new instance of UndergroundBot.
     Parameters
     ----------
     user_store - Instance of CloudantUserStore used to store and retrieve users from Cloudant
     dialog_store - Instance of CloudantDialogStore used to store conversation history
     conversation_username - The Watson Conversation username
     conversation_password - The Watson Converation password
     conversation_workspace_id - The Watson Conversation workspace ID
     weather_id - the Watson Weather ID
     weather_password - the Watson Weather Password
     """
     self.user_store = user_store
     self.dialog_store = dialog_store
     self.dialog_queue = {}
     self.conversation_client = ConversationV1(
         username=conversation_username,
         password=conversation_password,
         version='2016-07-11')
     self.conversation_workspace_id = conversation_workspace_id
     self.weather_id = weather_id
     self.weather_password = weather_password
예제 #14
0
def text_reply(msg):
    global response
    request_text = msg['Text'].encode('UTF-8')
    conversation = ConversationV1(
        username='******',
        password='******',
        version='2017-04-21')

    # replace with your own workspace_id
    workspace_id = 'd3e50587-f36a-4bdf-bf3e-38c382e8d63a'

    print "request ==>", request_text

    try:
        type(eval(response))
    except:
        print "first call"
        response = conversation.message(workspace_id=workspace_id,
                                        message_input={'text': request_text},
                                        context=response['context'])
    else:
        print "continue call"
        response = conversation.message(workspace_id=workspace_id,
                                        message_input={'text': request_text},
                                        context=response['context'])

    if len(response['output']['text']) > 0:
        response_text = response['output']['text'][0]
    else:
        response_text = "No message"

    itchat.send(response_text, msg['FromUserName'])
예제 #15
0
def message(bot, update):
    print('Received an update')
    global context

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

    # get response from watson
    response = conversation.message(
        workspace_id='36b6b197-2da6-4e71-9f23-a13d85110f84',  # TODO
        input={'text': update.message.text},
        context=context)
    print(json.dumps(response, indent=2))

    context = response['context']
    print(context)

    # build response
    resp = ''
    ret = ''
    esp = ''
    es = ''
    source = ''

    for text in response['intents']:
        es += text['intent']
    if es != 'Bot_Control_Approve_Response' and es != 'final':
        for text in response['output']['text']:
            resp += text
        update.message.reply_text(resp)
    elif es != 'final':
        #update.message.reply_text("http://127.0.0.1:5000/")
        for text in response['output']['text']:
            resp += text
        count = response['context']['count']

        category = response['context']['category']
        n = requests.get('https://newsapi.org/v2/top-headlines?country=' +
                         count + '&category=' + category +
                         '&apiKey=9ef6f45b13b94839b709d56d1b728ab6')
        obj = n.json()
        for i in range(0, 19):
            ret += str(i + 1) + ':  ' + str(
                obj['articles'][i]['title']) + '\n' + '\n'
        update.message.reply_text(resp + '\n' + '\n' + ret)
    else:
        num = response['context']['number']
        count = response['context']['count']

        category = response['context']['category']
        n = requests.get('https://newsapi.org/v2/top-headlines?country=' +
                         count + '&category=' + category +
                         '&apiKey=9ef6f45b13b94839b709d56d1b728ab6')
        obj = n.json()
        source = 'we have got this news from ' + str(
            obj['articles'][num - 1]['source']['name']) + '\n' + '\n'
        ret += str(obj['articles'][num - 1]['url'])
        update.message.reply_text(source + ret)
예제 #16
0
def home(request):
	conversation = ConversationV1(
   	username = settings.USERNAME,
	password = settings.PASSWORD,
    version='2018-02-16'
	)

	response={}
	if request.method == 'POST':
		form = ChatForm(request.POST)
		if form.is_valid():
			response = conversation.message(
				workspace_id = settings.WORKSPACE_ID,
				input = {
					'text':	form.cleaned_data['message']
				}
				)
			
		response['message'] = json.dumps(response['output']['text'], indent=2)
		return JsonResponse(response)

	else:
		form = ChatForm()



	response = conversation.get_dialog_node(
	    workspace_id = 'db92f9fa-5fcc-493c-ba9e-3ded910924da',
	    dialog_node = 'Welcome'
	)

	print(json.dumps(response, indent=2 ,))
	return render(request,'home.html',{'form': form})
	# return render(request,'home.html',{})
예제 #17
0
    def __init__(self, **kwargs):

        self.username = ''
        self.password = ''
        self.workspaceId = ''
        self.version = '2017-05-26'
        self.url = auth.url

        try : self.username = kwargs['username']
        except KeyError as e : self.username = ''

        try : self.password = kwargs['password']
        except KeyError as e : self.password = ''

        try : self.workspace_id = kwargs['workspace_id']
        except KeyError as e : self.workspace_id=''



        self.conversatin = ConversationV1(
          username=self.username,
          password=self.password,
          version='2017-05-26',
          url = auth.url
        )

        self.context = {}
예제 #18
0
파일: chatbot.py 프로젝트: Chris10M/VINAI
 def __init__(self):
     self.conversation = ConversationV1(
         username='******',
         password='******',
         version='2018-02-16'
     )
     self.workspace_id = '87f0e85e-af1c-4ea4-a5e9-9311aab29642'
예제 #19
0
    def watson_api(self, usr_name, passwd):
        '''
		Load Watson NLP API.
		'''
        self.watson_nlp = ConversationV1(username=usr_name,
                                         password=passwd,
                                         version='2017-04-21')
예제 #20
0
파일: runechona.py 프로젝트: diiogotk/open
def processar(chat, message, platform):

    conversation = ConversationV1(
        username="******",
        password="******",
        url='https://gateway-wdc.watsonplatform.net/assistant/api',
    version='2018-07-10')



    workspace_id = '0742b813-a704-4d1e-a38e-9f72517b1469'

    message = (u' '+message).encode('utf-8').strip()

    response = conversation.message(workspace_id=workspace_id, message_input={'text': message.decode()})
    
   
    
    if(len(response['output']['text'])>0):
        for valx in response['output']['text']:
            retorno = valx
            if(platform=='whastapp'):
                print("send_message_whastapp")
                send_message_whastapp(retorno, chat)
            else:
                print("send_message")
                send_message(retorno, chat)
    else:
         abcd =  response['output']['generic'][0]['source']
         abcnome = response['output']['generic'][0]['source']
         print('OIIIIII', abcd)
         send_message_whastapp_i(abcd, abcnome, chat)
예제 #21
0
 def __init__(self):
     self.speak = sp.Speak()
     self.txtSp = txtSp.TextToSpeak()
     self.conversation = ConversationV1(
         username='******',
         password='******',
         version='2016-09-20')
     # replace with your own workspace_id
     self.workspace_id = '114f8365-2e75-4fee-8b98-0df2527972bf'
예제 #22
0
    def __init__(self):

        self.conversation = ConversationV1(
            username=constants.WATSON['username'],
            password=constants.WATSON['password'],
            version=constants.WATSON['version'],
        )

        self.context = None
예제 #23
0
파일: api.py 프로젝트: andy-ta/chatstock
def start():
    conversation.append(
        ConversationV1(username='******',
                       password='******',
                       version='2017-01-27'))
    context.append(None)

    session['id'] = len(conversation) - 1

    return str(session['id'])
예제 #24
0
 def __init__(self):
     self.workspace_id = config.workspace_id
     self.conversation = ConversationV1(username=config.watson_username,
                                        password=config.watson_password,
                                        version='2017-02-03')
     self.our_context = dict()
     self.place = ""
     self.transport = ""
     self.accomodation = ""
     self.activities = ""
예제 #25
0
def searchOnWatson(message):
    conversation = ConversationV1(
        username="******",
        password="******",
        version="2018-07-10")
    workspace_id = "7473ff72-cda0-489f-84b7-ec06509f3fc5"
    response = conversation.message(workspace_id=workspace_id,
                                    input={"text": message})

    return response.get_result()
예제 #26
0
    def __init__(self, url, username, password, version, workspace_id):

        self.conversation = ConversationV1(
            url=url,
            version=version,
            username=username,
            password=password,
            use_vcap_services= False
        )

        self.workspace_id = workspace_id
예제 #27
0
    def __init__(self, username, password):
        self.username = username
        self.password = password

        self.conversation = ConversationV1(
            username=username,
            password=password,
            url='https://gateway.aibril-watson.kr/conversation/api',
            version=self.CONVERSATION_VERSION
        )  #, x_watson_learning_opt_out=True)
        self.conversation.x_watson_learning_opt_out = True
예제 #28
0
    def __init__(self, usr, pas, workspace):
        """Create conversation object.

        usr -- username for watson conversation service
        pas -- password for watson conversation service
        workspace -- workspace ID for the workspace in the conversation service.
        """
        self.convo = ConversationV1(username=usr,
                                    password=pas,
                                    version='2017-05-26')
        self.workspace_id = workspace
예제 #29
0
파일: watson.py 프로젝트: NMCT/nmct-box
 def __init__(self, workspace_id=None, credentials=None):
     if not workspace_id:
         try:
             with open(SECRETS_FILE) as f:
                 workspace_id = json.load(f)["watson"].get("workspace_id", '')
         except IOError:
             workspace_id = ''
     self.workspace_id = workspace_id
     auth = ServiceCredential("conversation", data=credentials)
     self.client = ConversationV1(version="2017-05-26", **auth.data)
     self.context = {}
     self._finished = False
예제 #30
0
def text_reply(msg):
    global conversation_server, request_text, response, response_text
    request_text = msg['Text'].encode('UTF-8')

    if request_text == '#IBM':
        conversation_server = '#IBM'
        response = {'context': {}}
        itchat.send('Greetings from IBM Waston', msg['FromUserName'])

    if request_text == '#':
        conversation_server = '#TURING'

    # IBM Waston Conversation
    if conversation_server == '#IBM':
        conversation = ConversationV1(
            username='******',
            password='******',
            version='2017-04-21')

        workspace_id = 'd3e50587-f36a-4bdf-bf3e-38c382e8d63a'

        response = conversation.message(workspace_id=workspace_id,
                                        message_input={'text': request_text},
                                        context=response['context'])

        if len(response['output']['text']) > 0:
            response_text = response['output']['text'][0]
        else:
            response_text = "No message"

        itchat.send(response_text, msg['FromUserName'])

    # Turling Robot
    if conversation_server == '#TURING':
        url = 'http://www.tuling123.com/openapi/api'
        request = urllib.urlencode({
            u"key": "d83cddc3894946338cccd9bb752b497e",
            "info": request_text,
            u"loc": r"北京市中关村",
            "userid": ""
        })

        url2 = urllib2.Request(url, request)
        response = urllib2.urlopen(url2)
        apicontent = response.read()
        s = json.loads(apicontent, encoding='utf-8')

        if s['code'] == 100000:
            response_text = s['text']
        else:
            response_text = r'问住我了?你太牛啦!'

        itchat.send(response_text, msg['FromUserName'])