def loadAndInit(confFile=None):
    # Credentials are read from a file
    with open(confFile) as confFile:
        config=json.load(confFile)
        configWA=config['credentials']
        if 'ICF_KEY' in config:
            global privcontext
            icf_key=config['ICF_KEY'].split(':')
            privcontext={"private": {"icfcreds": {"user": icf_key[0], "password": icf_key[1]}}}

    # Initialize the Watson Assistant client
    global conversation
    if 'username' in configWA:
        conversation = AssistantV1(
            username=configWA['username'],
            password=configWA['password'],
            version=configWA['version'],
            url=configWA['url']
        )
    elif 'apikey' in configWA:
        conversation = AssistantV1(
            iam_apikey=configWA['apikey'],
            version=configWA['version'],
            url=configWA['url']
        )
    else:
        print('Expected either username / password or apikey in credentials.')
        exit
    def deploy_to(self, assistant: AssistantV1, name: str):
        """
        Deploys written configuration via given assistant connector.
        If a workspace with same name exists already, it will be overwritten.
        """

        intents = []
        for intent_name, examples in self._wa_intent_definitions.items():
            intent = CreateIntent(
                intent_name, examples=[CreateExample(ex) for ex in examples])
            intents.append(intent)

        intents.extend(self._wa_intents)
        intents = self._make_unique_intents(intents)

        entities = []
        for sys_entity in self._declared_sys_entities:
            entities.append(CreateEntity(sys_entity))

        entities.extend(self._wa_entities)
        entities = self._make_unique_entities(entities)

        wa_nodes = self._create_wa_nodes()

        workspace_id = None
        for workspace in assistant.list_workspaces(
                page_limit=MAX_WS_PAGINATION).result["workspaces"]:
            if workspace["name"] == name:
                workspace_id = workspace["workspace_id"]
                break

        if workspace_id is None:
            result = assistant.create_workspace(name=name,
                                                intents=intents,
                                                entities=entities,
                                                dialog_nodes=wa_nodes)
        else:
            result = assistant.update_workspace(name=name,
                                                intents=intents,
                                                entities=entities,
                                                dialog_nodes=wa_nodes,
                                                workspace_id=workspace_id)

        unreachable_nodes = self._find_unreachable_nodes()
        print("DEPLOY STATISTICS")
        print(f"\t intents: {len(intents)}")
        print(f"\t entities: {len(entities)}")
        print(f"\t wa nodes: {len(wa_nodes)}")
        print(f"\t planning nodes: {len(self._plan_nodes)}")
        print(f"\t unreachable nodes: {len(unreachable_nodes)}")

        print()
        print(f"Status: {result.status_code}")
        print(f"WA API result: {result.result}")
Example #3
0
class IbmAssistant:

    assistant = AssistantV1(username=API_USER_NAME,
                            password=API_PASSWORD,
                            version='2018-07-10')

    workspace_id = '1ef0a9c1-f07e-4bb7-adfc-0d0f3fb6ff4a'
    mc = bmemcached.Client(
        os.environ.get('MEMCACHEDCLOUD_SERVERS').split(','),
        os.environ.get('MEMCACHEDCLOUD_USERNAME'),
        os.environ.get('MEMCACHEDCLOUD_PASSWORD'))
    mc.delete('context')

    def list_workspace(self):
        return self.assistant.list_workspaces()

    def message_request(self, message):
        context = self.mc.get('context')

        # set default timezone
        if context is None:
            context = dict()
            context['timezone'] = 'Asia/Tokyo'
            context['no_reservation'] = True

        response = self.assistant.message(
            workspace_id=self.workspace_id,
            input={'text': message},
            alternate_intents=True,
            context=context,
        )

        self.mc.set('context', response.get('context'))
        return response.get('output').get('generic')[0].get('text')
def getConvResponse():
    # Instantiate Watson Assistant client.
    # only give a url if we have one (don't override the default)
    try:
        assistant_kwargs = {
            'version': '2018-07-06',
            'username': assistantUsername,
            'password': assistantPassword,
            'iam_api_key': assistantIAMKey
        }

        assistant = AssistantV1(**assistant_kwargs)

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

        if convContext is None:
            convContext = "{}"
        print(convContext)
        jsonContext = json.loads(convContext)

        response = assistant.message(workspace_id=workspace_id,
                                     input={'text': convText},
                                     context=jsonContext)
    except Exception as e:
        print(e)

    print(response)
    reponseText = response["output"]["text"]
    responseDetails = {
        'responseText': reponseText[0],
        'context': response["context"]
    }
    return jsonify(results=responseDetails)
def get_response_from_watson_assistamt(version, username, password, url, workspace_id, input_json):

    # Initialize assistant
    assistant = AssistantV1(
        version=version,
        username=username,
        password=password,
        url=url
        )
    
    # Try to send request
    try:
        response = assistant.message(
            workspace_id=workspace_id,
            input=input_json
        ).get_result()
        # print(json.dumps(response, indent=2))

        # Returned answer string manupulation
        j = json.dumps(response, indent=2)
        out_json = json.loads(j)
        output = out_json['output']['text'][0]  # *** check here ***
        
        return output

    except WatsonApiException as ex:
        return "Method failed with status code " + str(ex.code) + ": " + ex.message
Example #6
0
def wa_get_assistant(url, version, username, password):
    assistant = AssistantV1(version=version,
                            username=username,
                            password=password,
                            url=url)

    return assistant
def main(dict):

    serviceUsername = dict['CLOUDANT_ACCOUNT']
    servicePassword = dict['CLOUDANT_PASSWORD']
    serviceURL = dict['CLOUDANT_URL']

    # Use the IBM Cloudant library to create an IBM Cloudant client.
    client = Cloudant(serviceUsername, servicePassword, url=serviceURL)

    # Connect to the server
    client.connect()

    databaseName = dict['CLOUDANT_DBNAME']

    # Create an instance of the database.
    myDatabaseDemo = client.create_database(databaseName)

    # Check that the database now exists.
    if myDatabaseDemo.exists():
        print("'{0}' successfully created.\n".format(databaseName))

    service = AssistantV1(iam_apikey=dict['IAM_APIKEY'],
                          version=dict['WDC_VERSION'],
                          url=dict['WDC_URL'])

    response = service.get_workspace(workspace_id=dict['WDC_WORKSPACEID'],
                                     export='true').get_result()

    newDocument = myDatabaseDemo.create_document(response)

    return {'status': 200, 'message': 'Backup realizado com sucesso!'}
 def __init__(self):
     self.watson_assistant = AssistantV1(
         username='******',
         password='******',
         version='2018-02-16',
     )
     self.response = None
Example #9
0
def list_workspaces(username, password, iam_apikey, url):
    c = AssistantV1(username=username,
                    password=password,
                    iam_apikey=iam_apikey,
                    version=WCS_VERSION,
                    url=url)
    return c.list_workspaces()
Example #10
0
 def init_app(self, app):
     self.app = app
     self.conversation = AssistantV1(
         username=app.config.get('WATSON_CONV_USER'),
         password=app.config.get('WATSON_CON_PASS'),
         version=app.config.get('WATSON_CON_VER'),
         url=app.config.get('WASTON_CON_URL'))
Example #11
0
def getWorkspaceJson(args):
    if args.file and args.file[0]:
        jsonFile = open(args.file[0], 'r')
        return json.load(jsonFile)
    if args.online:
        VERSION = '2018-09-20'
        service = AssistantV1(username=args.username[0],
                              password=args.password[0],
                              version=VERSION,
                              url=args.url[0])

        #Note: export=True is rate-limited, see https://cloud.ibm.com/apidocs/assistant?code=python#get-information-about-a-workspace
        response = service.get_workspace(workspace_id=args.workspace_id[0],
                                         export=True)

        #Check for v1 vs v2 syntax
        result_attr = getattr(response, "get_result", None)
        if callable(result_attr):
            response = response.get_result()

        return json.loads(json.dumps(response))

    sys.stderr.write(
        'Invalid configuration, did not specify a workspace file or an online connection\n'
    )
    sys.exit(2)
Example #12
0
def main():
    print(
        "---\nThis is a demo bot for making Watson Assistant API calls\n---\n")

    cred = get_credential_data()

    try:
        assistant = AssistantV1(version=cred['version'],
                                iam_apikey=cred['apiKey'],
                                url=cred['url'])

        input_message = raw_input(
            "Ask the chatbot (e.g. I want to order pizza): ")

        workspace = cred['workspace_id']

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

        print(json.dumps(response, indent=2))
        print("Bot response: ", response['output']['text'][0])

    except WatsonException as wex:
        print wex
        sys.exit(0)
    except KeyError as missingKey:
        print "% key is missing in credentials" % missingKey
        sys.exit(1)
Example #13
0
File: chatbot.py Project: mp5k/work
 def __init__(self, version, username, password, workspace_id, debug=False):
     self.watson_assistant = AssistantV1(version=version,
                                         username=username,
                                         password=password)
     self.workspace_id = workspace_id
     self.context_val = {}
     self.debug = debug
Example #14
0
	def default_handler(self,event,context):
	
		assistant = AssistantV1(
         version='2018-11-26',
         iam_apikey='o861MgDaxNdBUeAbUuU_EolNeHjjPrtCZbRHsmo7gOwB',
         url='https://gateway-wdc.watsonplatform.net/assistant/api'
		)
      
		n=event['content']
		n.rstrip()
		
		response = assistant.message(
         workspace_id='4aa742b3-5451-4692-9ac6-e241f4ff7f8f',
         input={
            'text': n
         }
		).get_result()
      
		user_data =  UserData(self, self.get_user_data())
		context = user_data.get_state()
      
      
		if context == 'IDLE': #직전 λŒ€ν™”μ—μ„œ ν•™μŠ΅κ³Όμ •μ΄ μ—†λŠ” 경우
			if response['intents'] == [] or response['intents'][0]['confidence'] <= 0.4: #μΈμ‹ν•˜λŠ” μΈν…νŠΈκ°€ μ‘΄μž¬ν•˜μ§€ μ•Šμ„ 경우 or μΈμ‹λœ μΈν…νŠΈμ˜ 정확도가 0.4 μ΄ν•˜μΌ 경우
				user_data.set_data(n)
				user_data.set_state('BUSY')
				self.EWord_to_KWord(response,n) #μž…λ ₯ 값에 μˆœν™”λŒ€μƒμ–΄κ°€ μžˆλŠ”μ§€ 확인 & μžˆμ„ 경우 μˆœν™”μ–΄ μ •λ³΄μΆœλ ₯
				self.send_message("μ„Έμ’…λŒ€μ™•λ΄‡: 잘 λͺ» μ•Œμ•„λ“£κ² μ–΄μš”. 뭐라고 λŒ€λ‹΅ν•˜λ©΄ 쒋을지 μ›ν•˜μ‹œλŠ” λŒ€λ‹΅μ„ μž…λ ₯ν•΄μ„œ ν•™μŠ΅μ‹œμΌœμ£Όμ„Έμš”.\n")   
				if response['intents'] == []:
					print('μž…λ ₯κ°’ μ˜λ„ : {}\n'.format(response['intents']))
				else:
					if response['intents'][0]['confidence'] <= 0.4:
						print('인식λ₯  : {}\n'.format(response['intents'][0]['confidence']))
				self.User_makes_intent(n,assistant,response)
          
			else: #μΈμ‹ν•˜λŠ” μΈν…νŠΈμ˜ confidenceκ°€ 0.7이상일 경우 
				if response['intents'][0]['confidence'] >= 0.7:
          
					self.EWord_to_KWord(response,n)
            
					if response['output']['text']==[]:
				
						self.send_message("μ„Έμ’…λŒ€μ™•λ΄‡: μ£„μ†‘ν•΄μš”. μ§€κΈˆμ€ λŒ€λ‹΅ν•˜κ³  싢지 μ•Šμ•„μš”.\n")
               
					else:
						self.send_message('μ„Έμ’…λŒ€μ™•λ΄‡: {}\n'.format(response['output']['text'][0]))
						print('인식λ₯ :{}'.format(response['intents'][0]['confidence']))
						print('μž…λ ₯κ°’ μ˜λ„:{}\n'.format(response['intents'][0]['intent']))

				elif response['intents'][0]['confidence'] < 0.7: #μΈμ‹ν•˜λŠ” μΈν…νŠΈμ˜ confidenceκ°€ 0.7 미만일 경우
					self.EWord_to_KWord(response,n)
					self.send_message("μ„Έμ’…λŒ€μ™•λ΄‡: λ‹€μ‹œ ν•œλ²ˆ λ§μ”€ν•΄μ£Όμ„Έμš”. μ΄ν•΄ν•˜μ§€ λͺ»ν–ˆμ–΄μš”.\n")
					print('인식λ₯ :{}'.format(response['intents'][0]['confidence']))
					print('μž…λ ₯κ°’ μ˜λ„:{}\n'.format(response['intents'][0]['intent']))
					
		elif context == 'BUSY': #직전 λŒ€ν™”μ—μ„œ ν•™μŠ΅κ³Όμ •μ΄ μžˆλŠ” 경우
				
			user_data.set_state('IDLE')
			w = user_data.get_data()
			self.User_makes_dialog(assistant,w,n,response)
def get_remote_workspace(args):
    conv = AssistantV1(
        WA_API_VERSION,
        username=args.user,
        password=args.password
    )
    workspace = conv.get_workspace(args.workspace_id, export=True)
    write_output(workspace, args.output)
Example #16
0
 def __init__(self, username, password, workspace_id=None):
     self.assistant = AssistantV1(username=username,
                                  password=password,
                                  version='2017-04-21')
     self.workspace_name = None
     self.workspace_id = None
     if workspace_id:
         self.set_workspace_by_id(workspace_id)
Example #17
0
 def get(self):
     if WatsonAssistantConnection.__instance is None:
         WatsonAssistantConnection.__instance = AssistantV1(
             version='2018-09-20',
             url='https://gateway.watsonplatform.net/assistant/api',
             username='******',
             password='******')
     return WatsonAssistantConnection.__instance
Example #18
0
def delete_workspaces(username, password, workspace_ids):
    """ Delete workspaces
    """
    c = AssistantV1(username=username, password=password,
                    version=WCS_VERSION, url=BASE_URL)
    for workspace_id in workspace_ids:
        c.delete_workspace(workspace_id=workspace_id)
    print('Cleaned up workspaces')
Example #19
0
 def __init__(self):
     self.vcap_services = json.loads(os.environ['VCAP_SERVICES'])
     self.assistant = AssistantV1(
         url=self.vcap_services['conversation'][0]['credentials']['url'],
         iam_api_key=self.vcap_services['conversation'][0]['credentials']
         ['apikey'],
         version='2018-07-10')
     self.contexthandler = ContextHandler()
     self.database = DatabaseAccess()
Example #20
0
 def initAssistant(self):
     try:
         self.watson_assistant = AssistantV1(version=self.version,
                                             username=self.username,
                                             password=self.password,
                                             url=self.url)
     except WatsonApiException as ex:
         print("Method failed with status code " + str(ex.code) + ": " +
               ex.message)
Example #21
0
 def __init__(self):
     f = open("key.txt", "r")
     f1 = f.read().splitlines()
     f.close()
     self.entity = AssistantV1(version=f1[0],
                               username=f1[1],
                               password=f1[2],
                               url=f1[3])
     self.workspace_id = f1[4]
     self.context = {}
Example #22
0
def get_assistant():
    username = sys.argv[1]
    password = sys.argv[2]

    assistant = AssistantV1(version=api_version,
                            username=username,
                            password=password,
                            url=WA_URL)

    return assistant
Example #23
0
 def __init__(self,top,msgList):
     self.assistant = AssistantV1(
         version='2018-07-10',
         username='******',
         password='******',
         url='https://gateway.watsonplatform.net/assistant/api'
     )
     self.assistant.set_detailed_response(False)
     self.tops=top
     self.resposta = ResponseTreatment(top,msgList)
def validate_with_fold(fold, data):
    """
    Creates a workspace from the fold's training data, and
    computes classification metrics based on the fold's testing data.

    Args:
        fold (tuple): A tuple of train and test indices. 
        data (ndarray): A numpy 2d array of the intents and examples.

    Returns:
        str: A classification report string from the created workspace.
    """

    # create an assistant service instance with your credentials
    assistant = AssistantV1(username=os.environ['ASSISTANT_USERNAME'],
                            password=os.environ['ASSISTANT_PASSWORD'],
                            version='2017-05-26')

    train_indices, test_indices = fold
    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 = assistant.create_workspace(name='k-fold-test',
                                     intents=create_intent_objs)
    wid = res['workspace_id']

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

    # validate the workspace with the corresponding test data
    y_true, y_pred = [], []
    for example, label in test_data:
        res = assistant.message(workspace_id=wid, input={'text': example})
        # ignore counter examples
        if len(res['intents']) < 1:
            continue
        top_label = res['intents'][0]['intent']
        y_true.append(label)
        y_pred.append(top_label)

    # delete the created workspace
    assistant.delete_workspace(workspace_id=wid)

    # return the classification report string
    return classification_report(y_true, y_pred)
Example #25
0
def func(args):
    workspace = None
    if not os.path.isfile(args.input):
        conv = AssistantV1(username=args.username, password=args.password, iam_apikey=args.iam_apikey,
                           version=WCS_VERSION, url=args.url)
        raw_workspace = conv.get_workspace(workspace_id=args.input, export=True)
        try:
           #V2 API syntax
           workspace = raw_workspace.get_result()
        except:
           #V1 API syntax
           workspace = raw_workspace
    else:
        with open(args.input) as f:
            workspace = json.load(f)

    intent_train_file = os.path.join(args.outdir, TRAIN_INTENT_FILENAME)
    entity_train_file = os.path.join(args.outdir, TRAIN_ENTITY_FILENAME)
    workspace_file = os.path.join(args.outdir, WORKSPACE_BASE_FILENAME)

    intent_exports = workspace['intents']
    entity_exports = workspace['entities']
    if len(intent_exports) == 0:
        raise ValueError("No intent is found in workspace")

    # Save workspace json
    with open(workspace_file, 'w+', encoding=UTF_8) as file:
        json.dump(workspace, file)

    # Parse intents to file
    with open(intent_train_file, 'w+', encoding=UTF_8) as csvfile:
        intent_writer = csv.writer(csvfile, quoting=csv.QUOTE_ALL)
        for intent_export in workspace['intents']:
            intent = intent_export['intent']
            if len(intent_export['examples']) != 0:
                for example in intent_export['examples']:
                    intent_writer.writerow([example['text'], intent])

    if len(entity_exports) != 0:
        # Parse entities to file
        with open(entity_train_file, 'w+', encoding=UTF_8) as csvfile:
            entity_writer = csv.writer(csvfile, quoting=csv.QUOTE_ALL)
            for entity_export in workspace['entities']:
                entity = entity_export['entity']
                for value_export in entity_export['values']:
                    row = [entity, value_export['value']]
                    if 'synonyms' in value_export:
                        row += value_export['synonyms']
                    elif 'patterns' in value_export:
                        row += ['/{}/'.format(pattern)
                                for pattern in value_export['patterns']
                                ]
                    entity_writer.writerow(row)
Example #26
0
    def __init__(self, username, password, workspace_id):
        self.username = username
        self.password = password
        self.workspace_id = workspace_id
        self.lastResponse = None

        self.assistant = AssistantV1(
            username=username,
            password=password,
            version='2017-04-21')

        self.assistant.set_http_config({'timeout': 100})
Example #27
0
    def __init__(self):
        self.assistant = AssistantV1(username=param_username,
                                     password=param_password,
                                     version='2017-04-21')

        self.workspace_id = param_workspace_id
        # read question text
        name = 'input\science.csv'
        with open(name, 'r') as f:
            reader = csv.reader(f)
            data = [r for r in reader if r]
        self.qname = {x[0]: x[1] for x in data}
Example #28
0
 def __init__(self,
              classes,
              max_api_calls=200,
              verbose=False,
              workspace_id=None):
     super().__init__(classes, max_api_calls, verbose)
     secrets = SecretsManager()
     self.workspace_id = workspace_id or secrets.get_secret(
         'watson/workspace_id')
     self.assistant = AssistantV1(
         version='2018-09-20',
         iam_apikey=secrets.get_secret('watson/iam_apikey'),
         url='https://gateway-syd.watsonplatform.net/assistant/api')
def func(args):
    conv = AssistantV1(username=args.username,
                       password=args.password,
                       version=WCS_VERSION,
                       url=BASE_URL)
    workspace = conv.get_workspace(workspace_id=args.workspace_id, export=True)
    intent_train_file = os.path.join(args.outdir, TRAIN_INTENT_FILENAME)
    entity_train_file = os.path.join(args.outdir, TRAIN_ENTITY_FILENAME)
    workspace_file = os.path.join(args.outdir, WORKSPACE_BASE_FILENAME)

    intent_exports = workspace['intents']
    entity_exports = workspace['entities']
    if len(intent_exports) == 0:
        raise ValueError("No intent is found in workspace")

    # Save workspace json
    with open(workspace_file, 'w+') as file:
        json.dump(workspace, file)

    # Parse intents to file
    with open(intent_train_file, 'w+') as csvfile:
        intent_writer = csv.writer(csvfile, quoting=csv.QUOTE_ALL)
        for intent_export in workspace['intents']:
            intent = intent_export['intent']
            if len(intent_export['examples']) == 0:
                intent_writer.writerow(['', intent])
            else:
                for example in intent_export['examples']:
                    intent_writer.writerow([example['text'], intent])

    if len(entity_exports) != 0:
        # Parse entities to file
        with open(entity_train_file, 'w+') as csvfile:
            entity_writer = csv.writer(csvfile, quoting=csv.QUOTE_ALL)
            for entity_export in workspace['entities']:
                entity = entity_export['entity']
                for value_export in entity_export['values']:
                    row = [entity, value_export['value']]
                    if 'synonyms' in value_export:
                        row += value_export['synonyms']
                    elif 'patterns' in value_export:
                        row += [
                            '/{}/'.format(pattern)
                            for pattern in value_export['patterns']
                        ]
                    entity_writer.writerow(row)
Example #30
0
 def __init__(self, debug_mode=False):
     self.debug_mode = debug_mode
     self.user_input = ''
     self.context1 = {}
     self.current_action = ''
     f = open("key.txt", "r")
     f1 = f.read().splitlines()
     f.close()
     self.assistant = AssistantV1(version=f1[0],
                                  username=f1[1],
                                  password=f1[2],
                                  url=f1[3])
     self.workspace_id = f1[4]
     response = self.assistant.message(workspace_id=self.workspace_id,
                                       input={'text': self.user_input},
                                       context=self.context1)
     print(response['output']['text'][0])