def main(): def workspace_df_to_csv(df, workspace_name): """Exports workspace dataframe to CSV""" file_name = workspace_name + '_questions.csv' script_dir = os.path.dirname(__file__) output_dir = os.path.join(script_dir, data_dir, 'workspace_training/') output_path = os.path.join(output_dir, file_name) df.to_csv(output_path, index=False, header=False) active_adoption = Credentials.active_adoption instance_creds = Credentials.ctx[active_adoption] conversation_version = Credentials.conversation_version if 'apikey' in instance_creds: logger.debug("Authenticating (apikey)") ctk = AssistantV1(iam_apikey=instance_creds['apikey'], url=instance_creds['url'], version=conversation_version) elif 'password' in instance_creds: logger.debug("Authenticating (username/password)") ctk = AssistantV1(username=instance_creds['username'], password=instance_creds['password'], url=instance_creds['url'], version=conversation_version) workspace_info = ctk.list_workspaces().get_result() logger.debug({ workspace["name"]: workspace["workspace_id"] for workspace in workspace_info["workspaces"] if workspace["workspace_id"] not in workspaces_to_ignore }) for workspace in tqdm(workspace_info["workspaces"]): workspace_id = workspace["workspace_id"] if workspace_id in workspaces_to_ignore: continue workspace_name = workspace["name"] workspace = ctk.get_workspace(workspace_id, export=True).get_result() intents = workspace['intents'] workspace_df = pd.DataFrame() for intent in intents: intent_name = intent['intent'] utterances = [example['text'] for example in intent['examples']] intent_df = pd.DataFrame(utterances) intent_df = intent_df.rename(columns={0: 'utterance'}) intent_df['Intent'] = intent_name workspace_df = workspace_df.append(intent_df) workspace_df_to_csv(workspace_df, workspace_name)
def watsonMessage(self, msg): authenticator = IAMAuthenticator(os.getenv('API_KEY')) service = AssistantV1(version='2019-02-08', authenticator=authenticator) service.set_service_url( 'https://gateway.watsonplatform.net/assistant/api') frase = msg if 'context' in globals() and context is not None: response = service.message(workspace_id=os.getenv('WORKSPACE_ID'), input={ 'text': frase }, context=context).get_result() else: response = service.message(workspace_id=os.getenv('WORKSPACE_ID'), input={ 'text': frase }).get_result() resp = response.get('output').get('text') def change_context(): global context context = response.get('context') change_context() return resp
def __init__(self, **kwargs): authenticator = IAMAuthenticator(kwargs.get("password")) self.ctk = AssistantV1( version=kwargs.get("version"), authenticator=authenticator ) self.ctk.set_service_url(kwargs.get("url"))
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 assistant if 'apikey' in configWA: # Authentication via IAM authenticator = IAMAuthenticator(configWA['apikey']) assistant = AssistantV1(authenticator=authenticator, version=configWA['version']) assistant.set_service_url(configWA['url']) else: print('Apikey for Watson Assistant in credentials.') exit
def texto2Intencao(script): """ Função recebe uma string de texto e retorna a intenção do cliente e a acertividade da intenção identificada :param script: Variável de texto contendo as falas do cliente. :return:intencao - Qual a intenção que o cliente quis transmitir confianca - Acertividade da intenção identificada script - Variável de texto contendo as falas do cliente. :author: Ellen Giacometti """ print('begin texto2Intencao') queryset = ReqBuilder.objects.filter(description='texto2Intencao').get() secret = queryset.secret url = queryset.url authenticator = IAMAuthenticator(secret) assistant = AssistantV1(version='2020-04-01', authenticator=authenticator) assistant.set_service_url(url) response = assistant.message( workspace_id='0cdbed9b-0268-43a6-968d-3030de036bf5', assistant_id='4873209d-6ce9-4bf1-8361-f4638e99b5a5', input={ 'message_type': 'text', 'text': script }).get_result() intencao = response['intents'][0]['intent'] confianca = response['intents'][0]['confidence'] print('intencao', intencao) return intencao, confianca, script
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' authenticator = IAMAuthenticator(args.iam_apikey[0]) service = AssistantV1(version=VERSION, authenticator=authenticator) service.set_service_url(args.url) #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)
def get_remote_workspace(args): authenticator = IAMAuthenticator(args.iam_apikey) conv = AssistantV1(version=WA_API_VERSION, authenticator=authenticator) conv.set_service_url(args.url) workspace = conv.get_workspace(args.workspace_id, export=True) write_output(workspace, args.output)
def __init__(self, workspace_name, api_url, key, version='2019-02-28'): self._assistant = AssistantV1( authenticator=IAMAuthenticator(key), version=version, ) self._assistant.set_service_url(api_url) self._workspace_name = workspace_name self._assistant.set_http_config({'timeout': 100})
def func(args): workspace = None if not os.path.isfile(args.input): authenticator = choose_auth(args) conv = AssistantV1(version=args.version, authenticator=authenticator) conv.set_service_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)
def authenticate_watson(self): """ Connect to WA and return an assistant instance. Takes apikey or username & password kwargs depending on auth_type. """ if self.auth_type == 'apikey': assistant = AssistantV1(iam_apikey=self.apikey, version=self.conversation_version, url=self.url) elif self.auth_type == 'password': assistant = AssistantV1(username=self.username, password=self.password, version=self.conversation_version, url=self.url) self.assistant = assistant
def wa_api_conn(): authenticator = IAMAuthenticator('o76JGGNsgDZA1b7dyvWO1EOAlyONV3jEzr48H_C9nnAQ') assistant = AssistantV1( version='2020-04-01', authenticator=authenticator ) assistant.set_service_url('https://api.eu-de.assistant.watson.cloud.ibm.com') return assistant
def __init__(self, access): self.apikey, self.url, self.version, self.workspace_id = access.apikey, access.url, access.version, access.workspace_id authenticator = IAMAuthenticator(self.apikey) self.assistant = AssistantV1(version=self.version, authenticator=authenticator) self.assistant.set_service_url(self.url) self.response = self.assistant.list_logs( workspace_id=self.workspace_id).get_result()
def list_workspaces(iam_apikey, version, url): authenticator = IAMAuthenticator(iam_apikey) if WATSON_SERVICE != 'nlc': c = AssistantV1(version=version, authenticator=authenticator) c.set_service_url(url) return c.list_workspaces() else: c = NaturalLanguageClassifierV1(authenticator) c.set_service_url(url) return c.list_classifiers()
def initialize_assistant(string): authenticator = IAMAuthenticator('IBM Service API Key') assistant = AssistantV1(version='2018-07-10', authenticator=authenticator) assistant.set_service_url( 'https://api.eu-gb.assistant.watson.cloud.ibm.com') assistant.set_http_config({'timeout': 100}) response = assistant.message(workspace_id='Assistant ID', input={ 'text': string }).get_result() return (response["output"]["text"][0])
def delete_workspaces(username, password, iam_apikey, url, version, workspace_ids): """ Delete workspaces """ c = AssistantV1(username=username, password=password, iam_apikey=iam_apikey, version=version, url=url) for workspace_id in workspace_ids: c.delete_workspace(workspace_id=workspace_id) print('Cleaned up workspaces')
def __init__(self, version, username, password, url): """ This function creates a watson assistant object that allows us to talk to watson chatbot param: version - version of watson assistant param: username - username of your watson assistant param: password - password of your watson assistant param: url - the url of your watson assistant service, to find go to https://cloud.ibm.com/resources, go to Services, click on Watson Assistant """ self.assistant = AssistantV1(version=version, username=username, password=password, url=url)
def main(): active_adoption = Credentials.active_adoption instance_creds = Credentials.ctx[active_adoption] conversation_version = Credentials.conversation_version if 'apikey' in instance_creds: logger.debug("Authenticating (apikey)") ctk = AssistantV1(iam_apikey=instance_creds['apikey'], url=instance_creds['url'], version=conversation_version) elif 'password' in instance_creds: logger.debug("Authenticating (username/password)") ctk = AssistantV1(username=instance_creds['username'], password=instance_creds['password'], url=instance_creds['url'], version=conversation_version) workspace_info = ctk.list_workspaces().get_result() for item in workspace_info['workspaces']: print(item['name'], item['workspace_id'])
def delete_workspaces(iam_apikey, url, version, workspace_ids): """ Delete workspaces """ authenticator = IAMAuthenticator(iam_apikey) for workspace_id in workspace_ids: if 'natural-language-classifier' in url: c = NaturalLanguageClassifierV1(authenticator=authenticator) c.set_service_url(url) c.delete_classifier(classifier_id=workspace_id) else: c = AssistantV1(version=version, authenticator=authenticator) c.set_service_url(url) c.delete_workspace(workspace_id=workspace_id) print('Cleaned up workspaces')
def load_service(self): """ This functon instantiate a Watson Assistant service object. Arguments: All arguments are passed in class level. Output: - Watson Assistant's service object. """ authenticator = IAMAuthenticator(self.apikey) assistant = AssistantV1(version=self.version, authenticator=authenticator) assistant.set_service_url(self.service_endpoint) self.assistant = assistant return assistant
def get_logs(assistant: AssistantV1, workspace_id: str = None, cursor: str = None, processing_result=[], iteration: int = 1, saving: bool = True, saving_destiny: str = 'processing', *args, **kwargs): if not workspace_id: workspace_id = os.environ.get('WATSON_WORKSPACE_ID', None) if not workspace_id: raise RuntimeError("Verifique o parâmetro 'workspace_id'.") print("\n\nIteração {}".format(iteration)) response = assistant.list_logs(workspace_id=workspace_id, cursor=cursor).get_result() if not 'logs' in response or not response['logs']: return processing_result print("Adicionando {} interações!".format(len(response['logs']))) processing_result.extend(response['logs']) print("Total de {} interações!".format(len(processing_result))) """ Verificando se podemos paginar os resultados: """ if 'pagination' in response and 'next_cursor' in response['pagination'] and\ response['pagination']['next_cursor'] != cursor: # Atribuindo novo valor ao cursor: cursor = response['pagination']['next_cursor'] return get_logs(assistant, workspace_id, cursor=cursor, iteration=iteration + 1) print("Finalizado!") if saving: return save_data(processing_result, 'complete_result') return processing_result
def main(dict): # WatsonAssistantの初期設定 authenticator = IAMAuthenticator('<your apikey>') assistant = AssistantV1(version='2020-04-01', authenticator=authenticator) assistant.set_service_url( 'https://gateway-tok.watsonplatform.net/assistant/api') # Firebase Realtime Databaseの初期設定 if not firebase_admin._apps: cred = credentials.Certificate('<your service account json>') firebase_admin.initialize_app(cred, { 'databaseURL': '<your databaseURL>', }) search_text = dict["text"] # WatsonAssistantからユーザー入力への応答の取得 response = assistant.message(workspace_id='<your workspace_id>', input={ 'text': search_text }).get_result() command = response["output"]["text"][0] # Firebase Realtime Databaseのgeneralからデータの取得 general_ref = db.reference('/general') commands = [] options = [] for k, v in general_ref.get()[command].items(): if v["type"] == "cmd": commands.append({ "label": k, "type": v["type"], "options": [], "description": v["description"] }) elif v["type"] == "opt": options.append({ "label": k, "type": v["type"], "description": v["description"] }) for item in commands: item["optionsList"] = options result = {"commands": commands} return result
def BankBot(): # Create session with the Watson Assistant assistant = AssistantV1( iam_apikey='PrLJLVykZG4V-FQrADLiZG91oOKcJN0UZWEUAo0HxW8Q', version='2018-09-20') # Pull the first prompt from the Dialog response = assistant.message( workspace_id='3e86c7a1-b071-4e6a-ada2-a8ac616e6aa6').get_result() # Continue prompting the user and getting their input, until they indicate # it's time to quit while True: # Get the text of the prompt prompt = response.get("output").get("text") # Display all of the text provided in the prompt for text in prompt: print(text) # Get the user's next utterance utterance = input("==> ") # Invoke Watson to assess the intent of the utterance and determine how # to respond to the user response = assistant.message( workspace_id='3e86c7a1-b071-4e6a-ada2-a8ac616e6aa6', input={'text': utterance}, context=response.get("context")).get_result() # Ensure there are intents in the response. if len(response.get("intents")) > 0: #Check whether the dialog indicates an end to the conversation if response["intents"][0]["intent"] == "General_Ending": if len(response.get("output").get("text")) > 0: # If there are any remaining messages in the response then # print them out. print(response.get("output").get("text")[0] + '\n') # And terminate the conversation. break
def delete_workspaces(iam_apikey, url, version, workspace_ids, auth_type): """ Delete workspaces """ if auth_type == 'iam': authenticator = IAMAuthenticator(iam_apikey) elif auth_type == 'bearer': authenticator = BearerTokenAuthenticator(iam_apikey) else: raise ValueError(f'Unknown auth_type "{auth_type}"') for workspace_id in workspace_ids: if 'natural-language-classifier' in url: c = NaturalLanguageClassifierV1(authenticator=authenticator) c.set_service_url(url) c.delete_classifier(classifier_id=workspace_id) else: c = AssistantV1(version=version, authenticator=authenticator) c.set_service_url(url) c.delete_workspace(workspace_id=workspace_id) print('Cleaned up workspaces')
def bot(): # ibm-watson auth authenticator = IAMAuthenticator('YOUR_API_KEY') assistant = AssistantV1(version='2018-07-10', authenticator=authenticator) # check workspace status (wait for training to complete) workspace_id = 'YOU_WORKSPACE_ID' workspace = assistant.get_workspace(workspace_id=workspace_id).get_result() print('The workspace status is: {0}'.format(workspace['status'])) if workspace['status'] == 'Available': print('Ready to chat!') else: print( 'The workspace should be available shortly. Please try again in 30s.' ) print( '(You can send messages, but not all functionality will be supported yet.)' ) # responde to inscoming calls with a simple text message # fetch the message msg = request.form.get('Body') input = {'text': msg} response = assistant.message(workspace_id=workspace_id, input=input).get_result() print(json.dumps(response, indent=2)) while True: if response['intents']: print('Detected intent: #' + response['intents'][0]['intent']) # print the output from dialog, if any. if response['output']['text']: resp = MessagingResponse() resp.message(str(response['output']['text'][0])) return str(resp)
def message(bot, update): print('Received an update') global context conversation = AssistantV1(username=assist_username, # TODO password=assist_password, # TODO version='2018-02-16') # get response from watson response = conversation.message( workspace_id=workspace_id, # TODO input={'text': update.message.text}, context=context) print(json.dumps(response, indent=2)) context = response['context'] # build response resp = '' for text in response['output']['text']: resp += text update.message.reply_text(resp)
from __future__ import print_function import json from ibm_watson import AssistantV1 # If service instance provides API key authentication assistant = AssistantV1( version='2018-07-10', ## 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='DBxOesEcwYTQK9-dvcaxTwBICWk0s3RwwEW6m-2eppDn') # assistant = AssistantV1( # username='******', # password='******', # ## url is optional, and defaults to the URL below. Use the correct URL for your region. # # url='https://gateway.watsonplatform.net/assistant/api', # version='2018-07-10') ######################### # Workspaces ######################### create_workspace_data = { "name": "test_workspace", "description": "integration tests", "language": "en", "intents": [{ "intent": "hello",
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') authenticator = (get_authenticator_from_environment('assistant') or get_authenticator_from_environment('conversation')) cloudant_account = os.environ.get("CLOUDANT_USERNAME") cloudant_iam_apikey = os.environ.get("CLOUDANT_IAM_APIKEY") cloudant_db_name = os.environ.get( "CLOUDANT_DB_NAME") or 'watson_online_store' # If the CLOUDANT_USERNAME env var was not set then use # VCAP_SERVICES like a WatsonService would. if not cloudant_iam_apikey: vcap_services = os.environ.get("VCAP_SERVICES") vcap_env = json.loads(vcap_services) if vcap_services else None if vcap_env: cloudant_creds = WatsonEnv.get_vcap_credentials( vcap_env, 'cloudantNoSQLDB') if cloudant_creds: if 'apikey' in cloudant_creds: cloudant_iam_apikey = cloudant_creds['apikey'] if 'username' in cloudant_creds: cloudant_account = cloudant_creds['username'] # Instantiate Watson Assistant client. # - only give a url if we have one (don't override the default) assistant_client = AssistantV1( version='2018-09-20', authenticator=authenticator) # Instantiate Cloudant DB. cloudant_online_store = CloudantOnlineStore( Cloudant.iam( cloudant_account, cloudant_iam_apikey, connect=True ), cloudant_db_name ) # Instantiate Watson Discovery client. # - only give a url if we have one (don't override the default) discovery_client = DiscoveryV1( version='2019-11-22', ) # Instantiate Slack chatbot. if not slack_bot_token or 'placeholder' in slack_bot_token: print("SLACK_BOT_TOKEN needs to be set correctly. " "It is currently set to '%s'." % slack_bot_token) print("Only the web UI will be available.") 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, assistant_client, discovery_client, cloudant_online_store) return watsononlinestore
def spool_data(): pd.set_option('display.max_colwidth', -1) authenticator = IAMAuthenticator( "9nJ7-MvPt9AVtK72-YotVNLRLvGARrEc3lls1oTgO1MW") service = AssistantV1(version='2019-02-28', authenticator=authenticator) service.set_service_url("https://gateway.watsonplatform.net/assistant/api") #select a workspace by specific id workspace_id = '61d70d27-a82d-495a-b6dc-d7b129a651ce' # or fetch one via the APIs # workspaces=service.list_workspaces().get_result() # workspace_id = service['workspaces'][0]['workspace_id'] #fetch the workspace workspace = service.get_workspace(workspace_id=workspace_id, export=True).get_result() # set query parameters limit_number_of_records = 40000 # example of time range query query_filter = "response_timestamp>=2021-04-23,response_timestamp<2021-04-24" #query_filter = None # Fetch the logs for the workspace df_logs = wa_adaptor.read_logs(service, workspace_id, limit_number_of_records, query_filter) skill_id = workspace_id assistant_skills = wa_assistant_skills.WA_Assistant_Skills() assistant_skills.add_skill(skill_id, workspace) #validate the number of workspace_ids print("workspace_ids in skills: " + pd.DataFrame(assistant_skills.list_skills())["skill_id"].unique()) print("workspace_ids in logs: " + df_logs.workspace_id.unique()) df_logs_canonical = transformation.to_canonical_WA_v2( df_logs, assistant_skills, skill_id_field=None, include_nodes_visited_str_types=True, include_context=False) #df_logs_canonical = transformation.to_canonical_WA_v2(df_logs, assistant_skills, skill_id_field="workspace_id", include_nodes_visited_str_types=True, include_context=False) # the rest of the notebook runs on the df_logs_to_analyze object. df_logs_to_analyze = df_logs_canonical.copy(deep=False) '''title = "All Conversations" turn_based_path_flows = analysis.aggregate_flows(df_logs_to_analyze, mode="turn-based", on_column="turn_label", max_depth=400, trim_reroutes=False) # increase the width of the Jupyter output cell display(HTML("<style>.container { width:95% !important; }</style>")) config = { 'commonRootPathName': title, # label for the first root node 'height': 800, # control the visualization height. Default 600 'nodeWidth': 250, 'maxChildrenInNode':10, # control the number of immediate children to show (and collapse rest into *others* node). Default 5 'linkWidth' : 400, # control the width between pathflow layers. Default 360 'sortByAttribute': 'flowRatio' # control the sorting of the chart. (Options: flowRatio, dropped_offRatio, flows, dropped_off, rerouted) 'sortByAttribute': 'flowRatio', 'title': title, 'mode': "turn-based" } jsondata = json.loads(turn_based_path_flows.to_json(orient='records')) visualization.draw_flowchart(config, jsondata, python_selection_var="selection") # filter the conversations that include escalation title2="Banking Card Escalated" filters = filtering.ChainFilter(df_logs_to_analyze).setDescription(title2) # node with condition on the #Banking-Card_Selection (node_1_1510880732839) and visit the node "Transfer To Live Agent" (node_25_1516679473977) filters.by_dialog_node_id('node_1_1537359291884')\ .by_dialog_node_id('node_2_1557410657039')\ .by_dialog_node_id('node_2_1557485570085')\ .by_dialog_node_id('node_1_1539687257421')\ #.by_dialog_node_id('node_4_1550388155701')\ #.by_dialog_node_id('node_4_1550388155701') #.by_dialog_node_id('node_8_1591090496445') filters.printConversationFilters() # get a reference to the dataframe. Note: you can get access to intermediate dataframes by calling getDataFrame(index) ##define the milestones and corresponding node ids for the `Schedule Appointment` task milestone_analysis = analysis.MilestoneFlowGraph(assistant_skills.get_skill_by_id(skill_id)) milestone_analysis.add_milestones(["Appointment scheduling start", "Enter purpose of appointment", "Scheduling completion", "Enter Zip Code", "Schedule time"]) milestone_analysis.add_node_to_milestone("node_1_1537359291884", "Appointment scheduling start") milestone_analysis.add_node_to_milestone("node_2_1557410657039", "Enter purpose of appointment") milestone_analysis.add_node_to_milestone("node_2_1557485570085", "Scheduling completion") milestone_analysis.add_node_to_milestone("node_4_1550388155701", "Enter Zip Code") milestone_analysis.add_node_to_milestone("node_1_1539687257421", "Schedule time") #enrich with milestone information - will add a column called 'milestone' milestone_analysis.enrich_milestones(df_logs_to_analyze) #remove all log records without a milestone df_milestones = df_logs_to_analyze[pd.isna(df_logs_to_analyze["milestone"]) == False] #optionally, remove consecutive milestones for a more simplified flow visualization representation df_milestones = analysis.simplify_flow_consecutive_milestones(df_milestones) # compute the aggregate flows of milestones computed_flows= analysis.aggregate_flows(df_milestones, mode="milestone-based", on_column="milestone", max_depth=30, trim_reroutes=False) config = { 'commonRootPathName': 'All Conversations', # label for the first root node 'height': 800, # control the visualization height. Default 600 'maxChildrenInNode': 6, # control the number of immediate children to show (and collapse the rest into *other* node). Default 5 # 'linkWidth' : 400, # control the width between pathflow layers. Default 360 ' 'sortByAttribute': 'flowRatio', # control the sorting of the chart. (Options: flowRatio, dropped_offRatio, flows, dropped_off, rerouted) 'title': "Abandoned Conversations in Appointment Schedule Flow", 'showVisitRatio' : 'fromTotal', # default: 'fromTotal'. 'fromPrevious' will compute percentages from previous step, 'mode': 'milestone-based' } jsondata = json.loads(computed_flows.to_json(orient='records')) visualization.draw_flowchart(config, jsondata, python_selection_var="milestone_selection") #the selection variable contains details about the selected node, and conversations that were abandoned at that point print("Selected Path: ", jsondata) #fetch the dropped off conversations from the selection # #dropped_off_conversations = vis_selection.to_dataframe(jsondata)["dropped_off"] realData = jsondata original = [data['dropped_off'] for data in realData] dropped_off_conversations = json.loads(json.dumps(original)) print("The selection contains {} records, with a reference back to the converstion logs".format(str(len(dropped_off_conversations)))) print("start") print(df_logs_to_analyze["request_text"]) #try: # df_logs_to_analyze=TextBlob(df_logs_to_analyze).sentiment # df_logs_to_analyze = sentiment_analysis.add_sentiment_columns(df_logs_to_analyze) #except: # df_logs_to_analyze=sentiment_analysis.add_sentiment_columns(df_logs_to_analyze) print("end") df_logs_to_analyze["request_text"]= df_logs_to_analyze["request_text"].astype(str) df_logs_to_analyze = sentiment_analysis.add_sentiment_columns(df_logs_to_analyze) #create insights, and highlights annotation for the transcript visualization NEGATIVE_SENTIMENT_THRESHOLD=-0.15 df_logs_to_analyze["insights_tags"] = df_logs_to_analyze.apply(lambda x: ["Negative Sentiment"] if x.sentiment < NEGATIVE_SENTIMENT_THRESHOLD else [], axis=1) df_logs_to_analyze["highlight"] = df_logs_to_analyze.apply(lambda x: True if x.sentiment < NEGATIVE_SENTIMENT_THRESHOLD else False, axis=1)''' newData = df_logs_to_analyze.loc[:, [ "conversation_id", "log_id", "request_text", "response_text", "intent_1" ]] result = newData.to_json(orient="table") data = json.loads(json.dumps(result, indent=4)) print(df_logs_to_analyze) return data
def bot(): # ibm-watson auth authenticator = IAMAuthenticator('2yc97zPkBEuQyq0LENgZn2x6-IpD29Dz-YFZfT2MjogI') #anterior 2018-07-10 assistant = AssistantV1(version='2020-04-01', authenticator=authenticator) # Agregar url segun la zona assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com') responseLW=assistant.list_workspaces().get_result() print(responseLW) # check workspace status (wait for training to complete) workspace_id = '350afcf8-f545-46a6-a88c-1e98a88eae0c' workspace = assistant.get_workspace(workspace_id=workspace_id).get_result() print('The workspace status is: {0}'.format(workspace['status'])) if workspace['status'] == 'Available': print('Ready to chat!') else: print('The workspace should be available shortly. Please try again in 30s.') print('(You can send messages, but not all functionality will be supported yet.)') # responde to inscoming calls with a simple text message # fetch the message msg = request.form.get('Body') input = {'text': msg} # response = assistant.message( # workspace_id=workspace_id, input=input).get_result() # responseSesId = assistant.create_session(assistant_id='2c1a74b6-3869-4b09-8e09-133a2d68fd26').get_result() # response = assistant.message( # assistant_id='2c1a74b6-3869-4b09-8e09-133a2d68fd26', # session_id= str(responseSesId), # input={ # 'message_type': 'text', # 'text': str(input) # } # ).get_result() # response = assistant.delete_session(assistant_id='2c1a74b6-3869-4b09-8e09-133a2d68fd26',session_id=str(responseSesId)).get_result() # print(json.dumps(response, indent=2)) response = assistant.message( workspace_id=workspace_id, input=input).get_result() print(json.dumps(response, indent=2)) while True: if response['intents']: print('Detected intent: #' + response['intents'][0]['intent']) # print the output from dialog, if any. if response['output']['text']: resp = MessagingResponse() resp.message(str(response['output']['text'][0])) return str(resp)
def getAssistant(iam_apikey, url, version=DEFAULT_WCS_VERSION): '''Retrieve Watson Assistant SDK object''' authenticator = IAMAuthenticator(iam_apikey) c = AssistantV1(version=version, authenticator=authenticator) c.set_service_url(url) return c