Beispiel #1
0
    def ask_watson(self):
        try:
            authenticator = IAMAuthenticator(secrets['apikey'])
            assistant = AssistantV2(version=secrets['version'],
                                    authenticator=authenticator)

            assistant.set_service_url(url)

            sess_response = assistant.create_session(
                assistant_id=secrets['assistant_id']).get_result()

            session_id = sess_response['session_id']

            response = assistant.message(assistant_id=secrets['assistant_id'],
                                         session_id=session_id,
                                         input={
                                             'message_type': 'text',
                                             'text':
                                             self.cleaned_data['comment']
                                         }).get_result()

            return (response['output']['generic'][0]['text'])

            sess_end_response = assistant.delete_session(
                assistant_id=secrets['assistant_id'],
                session_id=session_id).get_result()

        except ApiException as ex:
            return ('Method failed with status code' + str(ex.code) + ': ' +
                    ex.message)
Beispiel #2
0
def sendmessage():
    txt = request.args.get('txt')

    apikey = 'vBOIg92dGqhTTgU3fA2W1zLsjughb7R18g5z24ULcjfi'
    version1 = '2020-04-01'
    url = 'https://api.eu-gb.assistant.watson.cloud.ibm.com/instances/afd39c9f-8f90-4ff7-9047-5c86c564c732'
    assistant_id = '99418e38-b023-41a2-bf43-050acb1bab85'

    # authenticate watson
    authenticator = IAMAuthenticator(apikey)
    assistant = AssistantV2(version=version1, authenticator=authenticator)

    assistant.set_service_url(url)

    try:
        response = assistant.message_stateless(assistant_id=assistant_id,
                                               input={
                                                   'message_type': 'text',
                                                   'text': txt
                                               }).get_result()

    except ApiException as ex:
        print("Method failed with status code " + str(ex.code) + ": " +
              ex.message)

    txtResponse = "Sorry, i could not help you at this time"
    if response['output']['generic']:
        if response['output']['generic'][0]['response_type'] == 'text':
            txtResponse = response['output']['generic'][0]['text']

    return jsonify(txtResponse)
Beispiel #3
0
def watson_assistant(session, text):
    """
    Watson Assistantにリクエスト送信
    """
    # 初期設定
    authenticator = IAMAuthenticator(settings.WATSON_SETTINGS['API_KEY'])
    assistant = AssistantV2(version=settings.WATSON_SETTINGS['VERSION'],
                            authenticator=authenticator)
    assistant.set_service_url(settings.WATSON_SETTINGS['URL'])
    # Watsonのセッション取得
    response_session_id = assistant.create_session(
        assistant_id=settings.WATSON_SETTINGS['ASSISTANT_ID']).get_result()
    watson_session = response_session_id['session_id']

    # リクエスト送信
    response = assistant.message(
        assistant_id=settings.WATSON_SETTINGS['ASSISTANT_ID'],
        session_id=watson_session,
        input={
            'message_type': 'text',
            'text': text
        }).get_result()
    returned_text = response['output']['generic'][0]['text']

    return returned_text
Beispiel #4
0
def assistant(speech):
    global sessionCreated
    global session_key
    authenticator = IAMAuthenticator(
        'T44GGYi18K6A9i7f7UeZKxfPO41SKBIV6X3Mtp7tjwSj')
    assistant = AssistantV2(version='2020-01-26', authenticator=authenticator)

    assistant.set_service_url(
        'https://gateway.watsonplatform.net/assistant/api')

    if sessionCreated is False:
        session = assistant.create_session(
            assistant_id='cb4dacb9-085f-4a99-adfa-96e54d786f90').get_result()
        session_json = json.dumps(session)
        #print(session_json)
        session_key = (json.loads(session_json))
        #print(session_key["session_id"])
        sessionCreated = True

    response = assistant.message(
        assistant_id='cb4dacb9-085f-4a99-adfa-96e54d786f90',
        session_id=session_key["session_id"],
        input={
            'message_type': 'text',
            'text': speech
        }).get_result()
    # print(json.dumps(response, indent=2))
    return response
Beispiel #5
0
def create_elmo(credential):
    # If service instance provides API key authentication
    return AssistantV2(
               version='2018-09-20',
               # url is optional, and defaults to the URL below. Use the correct URL for your region.
               url='https://gateway.watsonplatform.net/assistant/api',
               iam_apikey=credential['ASSISTANT_IAM_APIKEY'])
Beispiel #6
0
async def call_watson(message, config):
    """Call the IBM Watson api and return the response.

    Main function used to call Watson API by using the official
    watson dependency for python.  We use get_result() to get the
    response on a dict format - without this the response is of type
    'ibm_cloud_sdk_core.detailed_response.DetailedResponse' and will
    show everything from the request including headers.

    Return:
        A dict containing the API response

    """
    authenticator = IAMAuthenticator(config["token"])
    service = AssistantV2(version=WATSON_API_VERSION,
                          authenticator=authenticator)

    await get_session_id(service, config)

    response = service.message(
        assistant_id=config["assistant-id"],
        session_id=config["session-id"],
        input={
            "message_type": "text",
            "text": message.text
        },
    ).get_result()

    _LOGGER.debug(_("Watson response - %s."), response)

    return response
Beispiel #7
0
 def __init__(self):
     self.authenticator = IAMAuthenticator(settings.ASSISTANT_APIKEY)
     self.assistant_id = settings.ASSISTANT_ID
     self.assistant = AssistantV2(version='2018-07-10',
                                  authenticator=self.authenticator)
     self.assistant.set_service_url(
         "https://api.us-south.assistant.watson.cloud.ibm.com")
Beispiel #8
0
 def _connect_ibm(self):
     authenticator = IAMAuthenticator(self.api_key)
     self.assistant = AssistantV2(
         version=self.version,
         authenticator=authenticator,
     )
     self.assistant.set_service_url(self.service_url)
def callNLP():
    question = request.args.get('question')
    print(question)
    authenticator = IAMAuthenticator(
        '1gR3LB1WjGbyLDWM-cvUUg5QlFDK2LSzy5Z55b9FZwaH')
    assistant = AssistantV2(version='2020-04-01', authenticator=authenticator)

    assistant.set_service_url(
        'https://api.au-syd.assistant.watson.cloud.ibm.com/instances/45e4a82e-f647-4a5c-866b-69fae0086057'
    )  #root 의 url

    response = assistant.create_session(
        assistant_id='315b8e12-6ee1-48e4-b35c-dcc6a3172b94').get_result(
        )  #Carbon_Tax_Bot assistant ID

    session_real_id = response["session_id"]
    print(session_real_id)
    response = assistant.message(
        assistant_id='315b8e12-6ee1-48e4-b35c-dcc6a3172b94',
        session_id=session_real_id,
        input={
            'message_type': 'text',
            'text': question
        }).get_result()

    print(json.dumps(response, indent=2))
    return response
def tts(question):
    authenticator = IAMAuthenticator(assistant_api_key)
    assistant = AssistantV2(version='2020-04-01', authenticator=authenticator)
    message_input = question
    message_input.encode('utf-8')
    assistant.set_service_url(assistant_url)
    session_id = assistant.create_session(
        assistant_id=assisstant_id).get_result()
    session_idj = json.dumps(session_id['session_id'])[1:-1]
    response = assistant.message(assistant_id=assisstant_id,
                                 session_id=session_idj,
                                 input={
                                     'message_type': 'text',
                                     'text': message_input
                                 }).get_result()
    response_of_assistant = json.loads(
        json.dumps(response['output']['generic'][0]['text']))
    print(response_of_assistant)
    authenticator = IAMAuthenticator(tts_api_key)
    text_to_speech = TextToSpeechV1(authenticator=authenticator)

    text_to_speech.set_service_url(tts_url)

    with open('response.wav', 'wb') as audio_file:
        audio_file.write(
            text_to_speech.synthesize(response_of_assistant,
                                      voice='ar-AR_OmarVoice',
                                      accept='audio/wav').get_result().content)

    class AudioFile:
        chunk = 1024

        def __init__(self, file):
            """ Init audio stream """
            self.wf = wave.open(file, 'rb')
            self.p = pyaudio.PyAudio()
            self.stream = self.p.open(format=self.p.get_format_from_width(
                self.wf.getsampwidth()),
                                      channels=self.wf.getnchannels(),
                                      rate=self.wf.getframerate(),
                                      output=True)

        def play(self):
            """ Play entire file """
            data = self.wf.readframes(self.chunk)
            while data != '':
                self.stream.write(data)
                data = self.wf.readframes(self.chunk)

        def close(self):
            """ Graceful shutdown """
            self.stream.close()
            self.p.terminate()

    # Usage example for pyaudio
    a = AudioFile("response.wav")
    a.play()
    a.close()
Beispiel #11
0
 def __init__(self, api_key, assistant_id=None):
     self.authenticator = IAMAuthenticator(api_key)
     if assistant_id:
         self.service = AssistantV2(version='2019-02-28',
                                    authenticator=self.authenticator)
         self.service.set_service_url(
             'https://gateway.watsonplatform.net/assistant/api')
         self.assistant_id = assistant_id
         self.session = self.create_session()
Beispiel #12
0
def authentication_function():

    global TTS_AUTH
    global TTS_SERVICE
    global WATSON_KEY
    global WATSON_AUTH
    global WATSON_ASSISTANT
    global HEADERS
    global USERPASS
    global URL
    global TONE_AUTHENTICATOR
    global TONE_SERVICE

    # TTS
    TTS_AUTH = IAMAuthenticator('4CUYHU_68pReHO4xyfisGiuH7fQmXanfbgf4OR94gp2l')
    TTS_SERVICE = TextToSpeechV1(authenticator=TTS_AUTH)
    TTS_SERVICE.set_service_url(
        'https://api.us-south.text-to-speech.watson.cloud.ibm.com/instances/806b8f05-e01e-4b2b-8d83-194205e7733b'
    )
    # END TTS

    # STT
    HEADERS = {}
    USERPASS = "******".join(get_auth())
    HEADERS["Authorization"] = "Basic " + base64.b64encode(
        USERPASS.encode()).decode()
    URL = get_url()
    # END STT

    # WATSON
    # put the general watson api key here
    WATSON_AUTH = IAMAuthenticator(
        'AGesgrUJa4L4OVBHpbJgTKfOeCU6kVeVxo2qhIVFqIYS')
    WATSON_ASSISTANT = AssistantV2(version='2018-09-20',
                                   authenticator=WATSON_AUTH)
    WATSON_ASSISTANT.set_service_url(
        'https://api.us-south.assistant.watson.cloud.ibm.com/instances/28f6a127-f399-482b-9b66-5502ad5af6f5'
    )
    # WATSON_ASSISTANT.set_service_url(
    #    'https://api.us-south.assistant.watson.cloud.ibm.com/instances/28f6a127-f399-482b-9b66-5502ad5af6f5')
    # session = WATSON_ASSISTANT.create_session(
    #    "82b5e8f6-5a1d-44a5-930e-a388332db998").get_result()  # put the specific assistant api key
    session = WATSON_ASSISTANT.create_session(
        "9bf7bf36-235e-4089-bf1d-113791da5b43").get_result(
        )  # put the specific assistant api key
    WATSON_KEY = session.get("session_id", "")
    # END WATSON

    # TONE ANALYZER
    TONE_AUTHENTICATOR = IAMAuthenticator(
        'b0DmzKxaFck7YymuFStEYpJPMmt_bbYLPu8fPO9aEend')
    TONE_SERVICE = ToneAnalyzerV3(version='2017-09-21',
                                  authenticator=TONE_AUTHENTICATOR)
    TONE_SERVICE.set_service_url(
        'https://api.us-south.tone-analyzer.watson.cloud.ibm.com/instances/4a4d15eb-5212-447b-8da9-dcad6434130a'
    )
    def _create_session(self):
        authenticator = IAMAuthenticator("REPLACE")  # Replace with API key
        self._service = AssistantV2(version="2020-04-01",
                                    authenticator=authenticator)
        self.service.set_service_url("REPLACE")  # Replace with service URL

        self._session_id = self.service.create_session(
            assistant_id=self.assistant_id).get_result()["session_id"]
        self._is_active = True
        self.connected.emit()
Beispiel #14
0
    def __init__(self):
        self.api = os.environ["WATSON_API"]
        self.url = os.environ["WATSON_URL"]
        self.assistant_id = os.environ["WATSON_ID"]

        self.authenticator = IAMAuthenticator(self.api)
        self.assistant = AssistantV2(
            version="2020-04-01", authenticator=self.authenticator
        )
        self.assistant.set_service_url(self.url)
Beispiel #15
0
def login():
    try:
        assistant = AssistantV2(version="2019-08-20",
                                url=ASSISTANT_URL,
                                iam_apikey=ASSISTANT_APIKEY)

        session = assistant.create_session(ASSISTANT_ID).get_result()
        return (session, assistant)
    except Exception as e:
        print(e)
        exit(-1)
def chat(tema):
    global id, sesion, service
    if request.method == 'POST':
        return redirect(url_for('index'))
    pagina = wikipedia.page(tema).url
    authenticator = IAMAuthenticator('Proporcionado_por_Watson')
    service = AssistantV2(version='2019-02-28', authenticator=authenticator)
    service.set_service_url('https://gateway.watsonplatform.net/assistant/api')
    response = service.create_session(assistant_id=id).get_result()
    sesion = response['session_id']
    return render_template('chat.html', pagina=pagina, tema=tema)
Beispiel #17
0
def sendToAssistant(textInput):

    assistant_apiKey = os.getenv("assistant_apiKey")
    assistant_url = os.getenv("assistant_url")
    assistant_id = os.getenv("assistant_id")

    authenticator = IAMAuthenticator(assistant_apiKey)
    assistant = AssistantV2(version='2020-02-05', authenticator=authenticator)
    assistant.set_service_url(assistant_url)
    assistant.set_disable_ssl_verification(True)

    if '|' in textInput:
        #'|' is use on GET query to divide between usr message and session_id
        params = textInput.split('|')
        textInput = params[0]

        if params[1] == '':
            #No session_id was previously established
            #session_id is created
            session_id = assistant.create_session(
                assistant_id=assistant_id).get_result()['session_id']

        else:
            #Obtains existing session_id
            session_id = params[1]

        #Calls for Watsons message interpretation
        response = assistant.message(assistant_id=assistant_id,
                                     session_id=session_id,
                                     input={
                                         'message_type': 'text',
                                         'text': textInput,
                                         'options': {
                                             'return_context': True
                                         }
                                     }).get_result()
        #Returns both Watsons response and current session_id
        return response, session_id

    #session_id is created
    session_id = assistant.create_session(
        assistant_id=assistant_id).get_result()['session_id']

    #Calls for Watsons message interpretation
    response = assistant.message(assistant_id=assistant_id,
                                 session_id=session_id,
                                 input={
                                     'message_type': 'text',
                                     'text': textInput
                                 }).get_result()

    #Returns Watsons response, and invalid session_id
    return response, 0
Beispiel #18
0
def watson_instance(iam_apikey: str,
                    url: str,
                    version: str = "2019-02-28") -> AssistantV2:
    try:
        authenticator = IAMAuthenticator(iam_apikey)
        assistant = AssistantV2(authenticator=authenticator, version=version)
        assistant.set_service_url(url)
    except ApiException as error:
        _logger.error("%s - %s", error.code, error.message)
        return jsonify({'error': str(error.message)}), error.code

    return assistant
class Assistant:
    authenticator = IAMAuthenticator('n0wn_OrjN7yR0PPbTP-C8x2tgczMZwGSruI-tfMvM6r-')
    assistant = AssistantV2(version='2020-04-01', authenticator=authenticator)
    assistant.set_service_url(
        'https://api.us-south.assistant.watson.cloud.ibm.com/instances/ddab0742-ca44-444e-b4b3-420a1868a372')

    ASSISTANT_ID = '0d6f7d80-c769-42d2-bccf-183d7700bc6b'

    def __init__(self):
        self.session_id = ''
        self.create_session()
        print(self.session_id)

    def create_session(self):
        session = self.assistant.create_session(self.ASSISTANT_ID).get_result()
        self.session_id = session.get('session_id')

    def ask_assistant(self, message):
        """Gets the response from Watson assistant.
            At this point the message should only be a yes/no type answer for asking age
                or querying for movie genre
            Random input may get a 'I didn't understand' response
        Parameters
        ----------
        message: str,
            user input message to get response for
        Returns
        -------
        str
            The string of what assistant response
            possible values for now: 'yes', 'no', '[Genres]' 'I didn't understand.'
        """
        if self.session_id == '':
            self.create_session()
        response = self.assistant.message(assistant_id=self.ASSISTANT_ID, session_id=self.session_id,
                                          input={'text': message}).get_result()
        return response.get('output').get('generic')[0].get('text')


    def get_intent(self,message):
        if self.session_id == '':
            self.create_session()
        response = self.assistant.message(assistant_id=self.ASSISTANT_ID, session_id=self.session_id,
                                          input={'text': message}).get_result()
        intents = response.get('output').get('intents',[])
        if len(intents) > 0:
            return [intents[0].get('intent')]
        else:
            return []

    def end_session(self):
        self.assistant.delete_session(self.ASSISTANT_ID, self.session_id).get_result()
        self.session_id = ''
    def __init__(self, chatId):
        self.chat_id = chatId

        authenticator = IAMAuthenticator(ConfigManager.get_ibm_token())
        self.assistant_id = ConfigManager.get_ibm_assistent_id()

        self.assistant = AssistantV2(version='2020-02-05',
                                     authenticator=authenticator)

        self.assistant.set_service_url(ConfigManager.get_ibm_assistent_url())

        self.validate_session()
Beispiel #21
0
def bot():
    # ibm-watson autenticacion
    authenticator = IAMAuthenticator(
        '2yc97zPkBEuQyq0LENgZn2x6-IpD29Dz-YFZfT2MjogI')

    # anterior 2018-07-10
    assistant = AssistantV2(version='2020-04-01', authenticator=authenticator)

    # Agregar url segun la zona
    assistant.set_service_url(
        'https://api.us-south.assistant.watson.cloud.ibm.com')

    # obtener mensaje enviado desde la llamada al servicio
    msg = request.form.get('Body')

    # validar que se envien los parametros
    if request.form.get('Body') is not None:
        msg = request.form.get('Body')
    elif request.form is not None:
        msg = request.form
    else:
        msg = ''

    # enviar el mensaje a Watson
    response = assistant.message_stateless(
        assistant_id='2c1a74b6-3869-4b09-8e09-133a2d68fd26',
        input={
            'message_type': 'text',
            'text': str(msg)
        }).get_result()

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

        # print the output from dialog, if any.
        if response['output']['generic']:
            resp = MessagingResponse()

            for res in response['output']['generic']:
                tipoResultado = res['response_type']

                if tipoResultado == 'text':
                    resp.message(str(res['text']))
                elif tipoResultado == 'image':
                    urlImagen = res['source']
                    tituloImagen = res['title']
                    resp.message(str(tituloImagen)).media(urlImagen)

            return str(resp)
        else:
            sda = ''
Beispiel #22
0
    def _create_session(self):
        """Realiza autenticação e cria sessão com o Watson.
        """

        authenticator = IAMAuthenticator(apikey=config.apikey)

        self._service = AssistantV2(version=config.version,
                                    authenticator=authenticator)

        session = self._service.create_session(
            assistant_id=config.assistant_id)
        self._session_id = session.get_result()['session_id']
Beispiel #23
0
def authentication_function():
    global TTS_AUTH
    global TTS_SERVICE
    global WATSON_KEY
    global WATSON_AUTH
    global WATSON_ASSISTANT
    global HEADERS
    global USERPASS
    global URL
    global TONE_SERVICE

    # TTS
    TTS_AUTH = IAMAuthenticator('msoasmplOnX24TCnYif7vaJK_bb9h2MuJG0yjp6kpPOR')
    TTS_SERVICE = TextToSpeechV1(authenticator=TTS_AUTH)
    TTS_SERVICE.set_service_url(
        'https://api.us-south.text-to-speech.watson.cloud.ibm.com/instances/74be1af9-eb16-43eb-ae58-3b3f5849e112'
    )
    # END TTS

    # STT
    HEADERS = {}
    USERPASS = "******".join(get_auth())
    HEADERS["Authorization"] = "Basic " + base64.b64encode(
        USERPASS.encode()).decode()
    URL = get_url()
    # END STT

    # WATSON
    WATSON_AUTH = IAMAuthenticator(
        'AGesgrUJa4L4OVBHpbJgTKfOeCU6kVeVxo2qhIVFqIYS'
    )  # put the general watson api key here
    WATSON_ASSISTANT = AssistantV2(version='2018-09-20',
                                   authenticator=WATSON_AUTH)
    WATSON_ASSISTANT.set_service_url(
        'https://api.us-south.assistant.watson.cloud.ibm.com/instances/28f6a127-f399-482b-9b66-5502ad5af6f5'
    )
    session = WATSON_ASSISTANT.create_session(
        "9bf7bf36-235e-4089-bf1d-113791da5b43").get_result(
        )  # put the specific assistant api key
    WATSON_KEY = session.get("session_id", "")
    # END WATSON

    # TONE ANALYZER
    TONE_AUTHENTICATOR = IAMAuthenticator(
        'b0DmzKxaFck7YymuFStEYpJPMmt_bbYLPu8fPO9aEend')
    TONE_SERVICE = ToneAnalyzerV3(version='2017-09-21',
                                  authenticator=TONE_AUTHENTICATOR)
    TONE_SERVICE.set_service_url(
        'https://api.us-south.tone-analyzer.watson.cloud.ibm.com/instances/4a4d15eb-5212-447b-8da9-dcad6434130a'
    )
    def __init__(self):
        print("watson.py", "__init__")

        # fetch env variables
        self.ASSISTANT_ID = os.environ['ASSISTANT_ID']
        self.ASSISTANT_URL = os.environ['ASSISTANT_URL']

        # Initialize assistant
        self.assistant = AssistantV2(version='2020-04-01')
        self.assistant.set_service_url(self.ASSISTANT_URL)

        # Create session to work with
        self.SESSION_ID = self.assistant.create_session(
            self.ASSISTANT_ID).get_result()['session_id']
Beispiel #25
0
    def __init__(self):
        # read Watson Assistant data from config file
        self.config = configparser.ConfigParser()
        self.config.read('watson_config.ini')

        self.authenticator = IAMAuthenticator(
            str(self.config['watson']['apikey']))
        self.assistant = AssistantV2(version=str(
            self.config['watson']['version']),
                                     authenticator=self.authenticator)
        self.assistant.set_service_url(
            'https://api.us-south.assistant.watson.cloud.ibm.com/')
        self.assistant_id = str(self.config['watson']['assistant_id'])
        self.session_id = self.assistant.create_session(
            assistant_id=self.assistant_id).get_result()['session_id']
Beispiel #26
0
def IBM_CHAT_BOT():
        
    authenticator = IAMAuthenticator('key')
    assistant = AssistantV2(
        version='2020-04-01',
        authenticator = authenticator
    )
    
    assistant.set_service_url('assistence url')
    
    response = assistant.create_session(
        assistant_id='assistence id'
    ).get_result()

    session_idd=response['session_id']
    return session_idd,assistant
Beispiel #27
0
    def conexionIbm(self, apiKey, url, assitantId):
        try:
            authenticator = IAMAuthenticator(apiKey)
            self.assistant = AssistantV2(
                version='2018-09-20',
                authenticator=authenticator,
            )
            # assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com')

            self.assistant.set_disable_ssl_verification(False)
            self.assistant.set_service_url(url)
            session = self.assistant.create_session(assitantId).get_result()
            sessionId = session["session_id"]
        except ApiException as ex:
            print("Metodo fallo " + str(ex.code) + ": " + ex.message)
        return sessionId
Beispiel #28
0
    def __init__(self):
        authenticator = IAMAuthenticator(self.API_KEY)
        self.assistant = AssistantV2(version=self.VERSION,
                                     authenticator=authenticator)
        self.assistant.set_service_url(self.URL)

        try:
            response = self.assistant.create_session(
                assistant_id=self.ASSISTANT_ID).get_result()

            self.session_id = response["session_id"]
        except ApiException as ex:
            if ex.code == "404":
                print(ex.message)
                raise Exception
            else:
                raise Exception
Beispiel #29
0
def test():

    keyword = request.form["question"]

    authenticator = IAMAuthenticator(iAMvalue)
    assistant = AssistantV2(version='2020-04-01', authenticator=authenticator)
    assistant.set_service_url(aservice_url)

    # noinspection PyTypeChecker
    response = assistant.message_stateless(assistant_id=assistant_id,
                                           input={
                                               'message_type': 'text',
                                               'text': keyword
                                           }).get_result()

    answer = json.dumps(response["output"]["generic"][0]["text"]).strip('"')

    try:
        definition = response["output"]["intents"][0]["intent"].strip('"')
    except IndexError as e:
        definition = e

    # if the intent is a definition, create a mongo entry.
    if definition == "Definition":
        dbquery = collection.find_one({"Question": keyword})
        if dbquery is not None:
            top_answer = collection.find({
                "Question": keyword
            }).sort('Vote', -1).limit(1)
            for x in top_answer:
                dbanswer = x["Answer"]
                response["output"]["generic"][0][
                    "text"] = dbanswer  # replace initial response in json with another string
        else:

            try:
                # collection.create_index([("Question", pymongo.TEXT)], unique=True)  # make question unique
                mongopost = {"Question": keyword, "Answer": answer, "Vote": 1}
                collection.insert_one(mongopost)
            except:  # pass to escape exception and do nothing
                pass  # if it already exists.. maybe post/update(mongodb) the new answer here

    return jsonify(response)
def loadAndInit(confFile=None):
    # Credentials are read from a file
    with open(confFile) as confFile:
        config = json.load(confFile)
        configWA = config['credentials']

    global assistantService
    # Initialize the Watson Assistant client, use API V2
    if 'apikey' in configWA:
        # Authentication via IAM
        authenticator = IAMAuthenticator(configWA['apikey'])
 
        assistantService = AssistantV2(
            authenticator=authenticator,
            version=configWA['versionV2'])
        assistantService.set_service_url(configWA['url'])
    else:
        print('Expected apikey in credentials.')
        exit