Esempio n. 1
0
def chatbot(text_to_be_analyzed):
    os.environ[
        "GOOGLE_APPLICATION_CREDENTIALS"] = 'rai_modules/rai_voniq/private_key.json'  # หาenvironment ชื่อ Google app credentials แล้ว add new environmental variable named private_key
    #os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = 'C:\\Users\\ThanaphatJ\\Desktop\\Django\\voniq\\voice_assist\\app1\\private_key.json' # หาenvironment ชื่อ Google app credentials แล้ว add new environmental variable named private_key

    DIALOGFLOW_PROJECT_ID = 'smartlab-dbmvqk'
    DIALOGFLOW_LANGUAGE_CODE = 'en'
    SESSION_ID = 'me'

    session_client = dialogflow_v2.SessionsClient()
    session = session_client.session_path(DIALOGFLOW_PROJECT_ID, SESSION_ID)
    text_input = dialogflow_v2.types.TextInput(
        text=text_to_be_analyzed, language_code=DIALOGFLOW_LANGUAGE_CODE)
    query_input = dialogflow_v2.types.QueryInput(text=text_input)
    try:
        response = session_client.detect_intent(session=session,
                                                query_input=query_input)
    except InvalidArgument:
        raise Exception("Sorry")

    # print("Query text:", response.query_result.query_text)
    # print("Detected intent:", response.query_result.intent.display_name)
    # print("Detected intent confidence:", response.query_result.intent_detection_confidence)
    # print("Fulfillment text:", response.query_result.fulfillment_text)
    return response.query_result.fulfillment_text
Esempio n. 2
0
    def detect_intent_texts(self, texts, language_code, speak=True):
        """Returns the result of detect intent with texts as inputs.
        Using the same `session_id` between requests allows continuation
        of the conversaion."""

        session_client = dialogflow.SessionsClient()
        session = session_client.session_path(self.project_id, self.session_id)

        for text in texts:
            text_input = dialogflow.types.TextInput(
                text=text, language_code=language_code)

            query_input = dialogflow.types.QueryInput(text=text_input)

            response = session_client.detect_intent(session=session,
                                                    query_input=query_input)

            if self.debug:
                print('Detected intent: {} (confidence: {})\n'.format(
                    response.query_result.intent.display_name,
                    response.query_result.intent_detection_confidence))
                print('Fulfillment text: {}\n'.format(
                    response.query_result.fulfillment_text))
                print('Action text: {}\n'.format(response.query_result.action))
            # print(response.query_result)
            if response.query_result.fulfillment_text != "" and speak:
                self.tts.speak(response.query_result.fulfillment_text)
            if (response.query_result.action != ""):  #do_action
                self.action_func(action=response.query_result.action)
Esempio n. 3
0
    def detect_intent_and_generate_response(self, texts, session_id):
        """ Returns the result of detect intent with texts as inputs.

        Using the same `session_id` between requests allows continuation
        of the conversation. """

        ## Track conversations using user session ID
        session_client = dialogflow.SessionsClient()
        session = session_client.session_path(self.project_id, session_id)

        ## User input messages
        for text in texts:
            # Serialize text as dialogflow.types.TextInput
            text_input = dialogflow.types.TextInput(
                text=text, language_code=self.language_code)
            # Recognize the text input as a query
            query_input = dialogflow.types.QueryInput(text=text_input)
            # Send the query off to DialogFlow and wait for a response
            intents_payload = session_client.detect_intent(
                session=session, query_input=query_input)
            # Extract the chatbot text response and parameters
            chatbot_response = intents_payload.query_result.fulfillment_text
            chatbot_params = intents_payload.query_result.parameters

        # return the chatbot response and parameters
        return chatbot_response, chatbot_params
Esempio n. 4
0
def detect_intent_texts(project_id, session_id, text, language_code, phoneNumber):
     context_short_name = "doesnotmatter"

     context_name = "projects/" + PROJECT_ID + "/agent/sessions/" + SESSION_ID + "/contexts/" + \
               context_short_name.lower()

     import dialogflow_v2 as dialogflow
     parameters = dialogflow.types.struct_pb2.Struct()
     parameters['phoneNumber'] = phoneNumber
     context = dialogflow.types.context_pb2.Context(
             name=context_name,
             lifespan_count = 2,
            parameters = parameters
             )
     query_params_1 = {"contexts":[context]}

     session_client = dialogflow.SessionsClient()

     session = session_client.session_path(project_id, session_id)

     text_input = dialogflow.types.TextInput(
         text=text, language_code=language_code)

     query_input = dialogflow.types.QueryInput(text=text_input)

     response = session_client.detect_intent(
         session=session, query_input=query_input,query_params=query_params_1)
     print (response.query_result)
     return response.query_result.intent.display_name, response.query_result.fulfillment_text
Esempio n. 5
0
    def detect_intent_texts(self, project_id, session_id, texts,
                            language_code):
        import dialogflow_v2 as dialogflow
        session_client = dialogflow.SessionsClient()

        session = session_client.session_path(project_id, session_id)
        print('Session path: {}\n'.format(session))
        text_input = dialogflow.types.TextInput(text=texts,
                                                language_code=language_code)

        query_input = dialogflow.types.QueryInput(text=text_input)

        response = session_client.detect_intent(session=session,
                                                query_input=query_input)

        print('=' * 20)
        print('Query text: {}'.format(response.query_result.query_text))
        print('Detected intent: {} (confidence: {})\n'.format(
            response.query_result.intent.display_name,
            response.query_result.intent_detection_confidence))
        print('Fulfillment text: {}\n'.format(
            response.query_result.fulfillment_text))
        ChatFns.LoadOtherEntry(
            self.ChatLog,
            format(response.query_result.fulfillment_text) + "\n")
        ChatFns.playsound('notif.wav')
        if self.top.focus_get() == None:
            ChatFns.FlashMyWindow("Machine Learning Chatbot")
Esempio n. 6
0
def get_intent_from_text(project_id, session_id, text, language_code):
    # create a session
    global intent_config
    session_client = dialogflow.SessionsClient(credentials=creds)
    session = session_client.session_path(project_id, session_id)

    # Convert text to the way dialogflow needs it
    text_input = dialogflow.types.TextInput(text=text,
                                            language_code=language_code)
    query_input = dialogflow.types.QueryInput(text=text_input)

    # Get the response from dialogflow api
    response = session_client.detect_intent(session=session,
                                            query_input=query_input)

    #print('=' * 20)
    # print the querry text as parsed by dialogflow
    print('Query text: %s' % (response.query_result.query_text))

    # get the parameters we need
    detected_intent = response.query_result.intent.display_name
    detected_intent_confidence = response.query_result.intent_detection_confidence
    bots_response = str(response.query_result.fulfillment_text)
    parameters = MessageToJson(response.query_result.parameters)

    # Return these parameters
    return detected_intent, parameters, bots_response
Esempio n. 7
0
    def test_streaming_detect_intent(self):
        # Setup Expected Response
        response_id = 'responseId1847552473'
        output_audio = b'24'
        expected_response = {
            'response_id': response_id,
            'output_audio': output_audio
        }
        expected_response = session_pb2.StreamingDetectIntentResponse(
            **expected_response)

        # Mock the API response
        channel = ChannelStub(responses=[iter([expected_response])])
        patch = mock.patch('google.api_core.grpc_helpers.create_channel')
        with patch as create_channel:
            create_channel.return_value = channel
            client = dialogflow_v2.SessionsClient()

        # Setup Request
        session = 'session1984987798'
        query_input = {}
        request = {'session': session, 'query_input': query_input}
        request = session_pb2.StreamingDetectIntentRequest(**request)
        requests = [request]

        response = client.streaming_detect_intent(requests)
        resources = list(response)
        assert len(resources) == 1
        assert expected_response == resources[0]

        assert len(channel.requests) == 1
        actual_requests = channel.requests[0][1]
        assert len(actual_requests) == 1
        actual_request = list(actual_requests)[0]
        assert request == actual_request
Esempio n. 8
0
 def apiaiCon(self):
     """
     Instantiate Dialogflow Client
     """
     self.session_client = dialogflow.SessionsClient()
     self.session = self.session_client.session_path(
         DIALOGFLOW_PROJECT_ID, str(uuid.uuid4()))
Esempio n. 9
0
def detect_intent_texts(project_id, session_id, text, language_code):
    """Returns the result of detect intent with texts as inputs.

    Using the same `session_id` between requests allows continuation
    of the conversation."""
    session_client = df.SessionsClient()

    session = session_client.session_path(project_id, session_id)
    print('Session path: {}\n'.format(session))
    a = ""

    text_input = df.types.TextInput(text=text, language_code=language_code)

    query_input = df.types.QueryInput(text=text_input)

    response = session_client.detect_intent(session=session,
                                            query_input=query_input)

    parameter_dict = {}
    for key in response.query_result.parameters:
        value = '{}'.format(response.query_result.parameters[key.encode()])
        if value != '':
            parameter_dict['{}'.format(key)] = value

    dic = {}
    dic['parameters'] = parameter_dict
    dic['query_text'] = '{}'.format(response.query_result.query_text)
    dic['display_name'] = '{}'.format(
        response.query_result.intent.display_name)
    dic['confidence'] = float('{}'.format(
        response.query_result.intent_detection_confidence))
    dic['fulfillment_text'] = '{}'.format(
        response.query_result.fulfillment_text)
    return dic
Esempio n. 10
0
def ask_the_wizard(text, session_id='123456', language_code='en-US'):

    session_client = dialogflow.SessionsClient()
    session = session_client.session_path(PROJECT_ID, session_id)
    text_input = dialogflow.types.TextInput(
    	text=text,
    	language_code=language_code
    )

    query_input = dialogflow.types.QueryInput(text=text_input)

    response = session_client.detect_intent(
    	session=session,
    	query_input=query_input
    )
    #print(response.query_result)
    intent = response.query_result.intent.display_name
    intent_value = ""
    if len(response.query_result.parameters) > 0:
    	tmp = list(response.query_result.parameters.keys())[0]
    	intent_value = response.query_result.parameters.__getitem__(tmp)

    # print('User text       : {}'.format(text))
    # print('Fulfillment text: {}\n'.format(response.query_result.fulfillment_text))

    return {
    	'intent': intent,
		'intent_value': intent_value,
		'response': response.query_result.fulfillment_text
	}
Esempio n. 11
0
def detect_intent_audio(project_id, session_id, audio_file_path,
                        language_code):
    """
    Returns response to audio file
    """

    session_client = dialogflow.SessionsClient()

    audio_encoding = dialogflow.enums.AudioEncoding.AUDIO_ENCODING_LINEAR_16
    sample_rate_hertz = 44100

    session = session_client.session_path(project_id, session_id)

    with open(audio_file_path, 'rb') as audio_file:
        input_audio = audio_file.read()

    audio_config = dialogflow.types.InputAudioConfig(
        audio_encoding=audio_encoding,
        language_code=language_code,
        sample_rate_hertz=sample_rate_hertz)
    query_input = dialogflow.types.QueryInput(audio_config=audio_config)

    response = session_client.detect_intent(session=session,
                                            query_input=query_input,
                                            input_audio=input_audio)

    return response.query_result.fulfillment_text
Esempio n. 12
0
def detect_intent_texts(project_id, session_id, texts, language_code):

    import dialogflow_v2 as dialogflow
    session_client = dialogflow.SessionsClient()

    session = session_client.session_path(project_id, session_id)
    print('Session path: {}\n'.format(session))

    for text in texts:
        text_input = dialogflow.types.TextInput(text=text,
                                                language_code=language_code)

        query_input = dialogflow.types.QueryInput(text=text_input)

        response = session_client.detect_intent(session=session,
                                                query_input=query_input)

        print('=' * 20)
        print('Query text: {}'.format(response.query_result.query_text))
        print('Detected intent: {} (confidence: {})\n'.format(
            response.query_result.intent.display_name,
            response.query_result.intent_detection_confidence))
        print('Fulfillment text: {}\n'.format(
            response.query_result.fulfillment_text))
        return response.query_result.fulfillment_text
Esempio n. 13
0
    async def construct( # type: ignore
        self,
        _global_config: GlobalConfig,
        time_zone: str,
        project: str = "nlutestframework",
        agent: str = "NLUTestFramework"
    ) -> None:
        """
        Args:
            _global_config: Global configuration for the whole test framework.
            time_zone: The time zone, e.g. Europe/Berlin. See https://www.iana.org/time-zones for
                the list of possible values.
            project: The name of the Dialogflow project. Defaults to "nlutestframework".
            agent: The name of the Dialogflow agent. Defaults to "NLUTestFramework".
        """

        self.__time_zone = time_zone
        self.__project   = project
        self.__agent     = agent

        # Create the various clients to interact with the Dialogflow API
        clients_config: Dict[str, Any] = {}

        self.__agents_client   = dialogflow_v2.AgentsClient(**clients_config)
        self.__intents_client  = dialogflow_v2.IntentsClient(**clients_config)
        self.__sessions_client = dialogflow_v2.SessionsClient(**clients_config)

        await self.__removeIntents()
Esempio n. 14
0
def detect_intent_audio(project_id, session_id, audio_file_path,
                        language_code):
    start = time.time()
    session_client = dialogflow.SessionsClient()
    audio_encoding = dialogflow.enums.AudioEncoding.AUDIO_ENCODING_FLAC
    sample_rate_hertz = 44100
    session = session_client.session_path(project_id, session_id)

    with open(audio_file_path, 'rb') as audio_file:
        input_audio = audio_file.read()

    audio_config = dialogflow.types.InputAudioConfig(
        audio_encoding=audio_encoding,
        language_code=language_code,
        sample_rate_hertz=sample_rate_hertz)
    query_input = dialogflow.types.QueryInput(audio_config=audio_config)

    response = session_client.detect_intent(session=session,
                                            query_input=query_input,
                                            input_audio=input_audio)

    return {
        "query": response.query_result.query_text,
        "intent": response.query_result.intent.display_name,
        "confidence": response.query_result.intent_detection_confidence,
        "response_time": time.time() - start,
    }
def detect_intent_texts(project_id, session_id, text, language_code,
                        pseudo_gen):
    """Returns the result of detect intent with texts as inputs.
    Using the same `session_id` between requests allows continuation
    of the conversation."""
    import dialogflow_v2 as dialogflow
    session_client = dialogflow.SessionsClient(credentials=credentials)

    session = session_client.session_path(project_id, session_id)

    text_input = dialogflow.types.TextInput(text=text,
                                            language_code=language_code)

    query_input = dialogflow.types.QueryInput(text=text_input)

    response = session_client.detect_intent(session=session,
                                            query_input=query_input)

    query_text = response.query_result.query_text
    fulfillment = response.query_result.fulfillment_text

    print('=' * 40)

    if fulfillment == 'unknown':
        print("Default fallback")
        fulfillment = find_similar_intent(str(query_text))
        response.query_result.intent.display_name = fulfillment[0]
        print('Fulfillment text (by SE): {} (similarity: {})\n'.format(
            fulfillment[0], fulfillment[1]))
        if pseudo_gen.idnt_map[fulfillment[0]] == 'N' or pseudo_gen.idnt_map[
                fulfillment[0]] == 'DF':
            response.query_result.fulfillment_text = fulfillment[0]

    pseudo_code = generate_pseudo_code(response, pseudo_gen)
    return pseudo_code
Esempio n. 16
0
def detect_intent_texts(texts):
    """Связывается с dialogflow, возращает ответы на вопросы через dialogflow"""
    try:
        logger.debug('Старт detect_intent_texts')
        session_client = dialogflow.SessionsClient()
        path_json_config = os.getenv('GOOGLE_APPLICATION_CREDENTIALS')
        with open(path_json_config, 'r') as f:
            config_json = json.load(f)
        project_id = config_json['project_id']
        session_id = config_json['client_id']
        session = session_client.session_path(project_id, session_id)
        logger.debug('Session path: {}\n'.format(session))
        text_input = dialogflow.types.TextInput(text=texts,
                                                language_code='ru-RU')
        query_input = dialogflow.types.QueryInput(text=text_input)
        response = session_client.detect_intent(session=session,
                                                query_input=query_input)
        logger.debug('=' * 20)
        logger.debug('Query text: {}'.format(response.query_result.query_text))
        logger.debug('Detected intent: {} (confidence: {})\n'.format(
            response.query_result.intent.display_name,
            response.query_result.intent_detection_confidence))
        logger.debug('Fulfillment text: {}\n'.format(
            response.query_result.fulfillment_text))
        return response.query_result.fulfillment_text
    except:
        logger.exception('Mistake func detect_intent_texts')
Esempio n. 17
0
def detect_intent_texts(project_id, session_id, texts, language_code):
    """Returns the result of detect intent with texts as inputs.
    Using the same `session_id` between requests allows continuation
    of the conversaion."""
    session_client = dialogflow_v2.SessionsClient()

    session = session_client.session_path(project_id, session_id)
    print('Session path: {}\n'.format(session))


    text_input = dialogflow_v2.types.TextInput(
        text=texts, language_code=language_code)

    query_input = dialogflow_v2.types.QueryInput(text=text_input)

    response = session_client.detect_intent(
        session=session, query_input=query_input)

        #print('=' * 20)
        #print('Query text: {}'.format(response.query_result.query_text))
        #print('Detected intent: {} (confidence: {})\n'.format(
        #    response.query_result.intent.display_name,
        #    response.query_result.intent_detection_confidence))
        #print('Fulfillment text: {}\n'.format(
        #    response.query_result.fulfillment_text))
    #print(response.query_result.parameters["fields"][0])
    response_json=MessageToJson(response.query_result)
    response_json=json.loads(response_json)
    print(response_json["parameters"]["any"])
    return str(response_json)
Esempio n. 18
0
def detect_intent(question):
    
    session_client = dialogflow.SessionsClient()
    session = session_client.session_path(project_id, session_id)
    
    text_input = dialogflow.types.TextInput(text=question, language_code=language_code)
    
    query_input = dialogflow.types.QueryInput(text=text_input)
    response = session_client.detect_intent(
          session=session, query_input=query_input)

    res=MessageToJson(response)
    res=json.loads(res)
    
    try:
        intent=res['queryResult']['intent']['displayName']
        os_norm=res['queryResult']['parameters']['os_norm']
        os_norm_str=''.join(os_norm)
        print("%s - %s"%(intent,os_norm_str))
        
        if intent =="contrast" and len(os_norm)>1:
            os_norm_str2=os_norm[1]+os_norm[0] 
        else:
            os_norm_str2=""
        
    except KeyError:
        print("error in ",question)
        os_norm_str=question
        os_norm_str2=""
        
    return intent,os_norm_str,os_norm_str2
Esempio n. 19
0
def do_dialogflow_analysis(enquiry):
    os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = './SystemCode/project_key.json'

    # This field need to be changed to your actual dialogFlow project ID
    DIALOGFLOW_PROJECT_ID = 'oscres-wcbhwc'

    DIALOGFLOW_LANGUAGE_CODE = 'en'
    SESSION_ID = 'me'


    session_client = dialogflow.SessionsClient()
    session = session_client.session_path(DIALOGFLOW_PROJECT_ID, SESSION_ID)

    print('Session path: {}\n'.format(session))
    text_input = dialogflow.types.TextInput(text=enquiry, language_code=DIALOGFLOW_LANGUAGE_CODE)
    query_input = dialogflow.types.QueryInput(text=text_input)
    try:
        response = session_client.detect_intent(session=session, query_input=query_input)
        print(response)

    except InvalidArgument:
        raise
    except:
        raise Exception('Sorry I am not able to connect to the internet at the moment. Please try again later. Or use our recommendation system to help you.')
    return response
Esempio n. 20
0
def detect_intent_texts(text):
    """Returns the result of detect intent with texts as inputsprint.

    Using the same `session_id` between requests allows continuation
    of the conversation."""
    # os.system('export GOOGLE_APPLICATION__CREDENTIALS="`pwd`/google_auth.json"')
    print(load_dotenv())
    print("[OS ENVIRON]", os.environ.get("GOOGLE_APPLICATION_CREDENTIALS"))
    project_id = os.environ["PROJECT_ID"]
    session_client = dialogflow.SessionsClient()
    language_code = "en"
    session = session_client.session_path(project_id, session_id)
    print('Session path: {}\n'.format(session))

    text_input = dialogflow.types.TextInput(text=text,
                                            language_code=language_code)

    query_input = dialogflow.types.QueryInput(text=text_input)

    response = session_client.detect_intent(session=session,
                                            query_input=query_input)

    print('=' * 20)
    print('Query text: {}'.format(response.query_result.query_text))
    print('Detected intent: {} (confidence: {})\n'.format(
        response.query_result.intent.display_name,
        response.query_result.intent_detection_confidence))
    print('Fulfillment text: {}\n'.format(
        response.query_result.fulfillment_text))
    return response.query_result.fulfillment_text
Esempio n. 21
0
    def test_detect_intent(self):
        # Setup Expected Response
        response_id = 'responseId1847552473'
        output_audio = b'24'
        expected_response = {
            'response_id': response_id,
            'output_audio': output_audio
        }
        expected_response = session_pb2.DetectIntentResponse(
            **expected_response)

        # Mock the API response
        channel = ChannelStub(responses=[expected_response])
        patch = mock.patch('google.api_core.grpc_helpers.create_channel')
        with patch as create_channel:
            create_channel.return_value = channel
            client = dialogflow_v2.SessionsClient()

        # Setup Request
        session = client.session_path('[PROJECT]', '[SESSION]')
        query_input = {}

        response = client.detect_intent(session, query_input)
        assert expected_response == response

        assert len(channel.requests) == 1
        expected_request = session_pb2.DetectIntentRequest(
            session=session, query_input=query_input)
        actual_request = channel.requests[0][1]
        assert expected_request == actual_request
Esempio n. 22
0
def personal_assistant_bot(text_to_be_analyzed):
    os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = personalAssistant[
        "filename"]
    session_client = dialogflow.SessionsClient()
    session = session_client.session_path(personalAssistant["project"],
                                          "assistant")
    text_input = dialogflow.types.TextInput(text=text_to_be_analyzed,
                                            language_code="en")
    query_input = dialogflow.types.QueryInput(text=text_input)

    try:
        response = session_client.detect_intent(session=session,
                                                query_input=query_input)
    except:
        raise

    values = {
        k: v.string_value
        for k, v in response.query_result.parameters.fields.items()
    }

    return {
        "from": "PERSONAL_ASSISTANT",
        "text": response.query_result.query_text,
        "intent": response.query_result.intent.display_name,
        "intentConfidence": response.query_result.intent_detection_confidence,
        "fulfillment": response.query_result.fulfillment_text,
        "items": values
    }
Esempio n. 23
0
def detect_intent_texts(project_id, session_id, texts, language_code):
    """Returns the result of detect intent with texts as inputs.

    Using the same `session_id` between requests allows continuation
    of the conversation."""

    # Sets the client
    session_client = dialogflow.SessionsClient()

    # Session
    session = session_client.session_path(project_id, session_id)

    # Processes all text strings from the input array
    for text in texts:
        # Configures text input settings
        text_input = dialogflow.types.TextInput(
            text=text, language_code=language_code)

        # Sends text to dialogflow for procesing
        query_input = dialogflow.types.QueryInput(text=text_input)

        # Response from dialogflow
        response = session_client.detect_intent(
            session=session, query_input=query_input)

        return response.query_result.fulfillment_text
def detect_intent_with_parameters(project_id, session_id, query_params,
                                  language_code, user_input):
    session_client = dialogflow_v2.SessionsClient()

    session = session_client.session_path(project_id, session_id)
    print('Session path: {}\n'.format(session))

    text = user_input

    text_input = dialogflow_v2.types.TextInput(text=text,
                                               language_code=language_code)

    query_input = dialogflow_v2.types.QueryInput(text=text_input)

    response = session_client.detect_intent(session=session,
                                            query_input=query_input,
                                            query_params=query_params)

    print('=' * 20)
    print('Query text: {}'.format(response.query_result.query_text))
    print('Detected intent: {} (confidence: {})\n'.format(
        response.query_result.intent.display_name,
        response.query_result.intent_detection_confidence))
    print('Fulfillment text: {}\n'.format(
        response.query_result.fulfillment_text))

    return response
def testApp(form):

    text_to_be_analyzed = form.phrase_text.data

    session_client = dialogflow.SessionsClient()
    session = session_client.session_path(DIALOGFLOW_PROJECT_ID, SESSION_ID)
    text_input = dialogflow.types.TextInput(
        text=text_to_be_analyzed, language_code=DIALOGFLOW_LANGUAGE_CODE)
    query_input = dialogflow.types.QueryInput(text=text_input)
    try:
        response = session_client.detect_intent(session=session,
                                                query_input=query_input)
    except InvalidArgument:
        raise
    intent = response.query_result.intent.display_name

    flash('Detected Intent: ' + str(intent), 'success')
    c = [i for i in response.query_result.parameters.fields.keys()]
    en = c
    # en = en.join(c)
    flash('Entities Required: ' + str(en), 'success')
    x = []
    for i in response.query_result.parameters.fields.keys():
        x.append(response.query_result.parameters.fields[i].string_value)
    y = x
    # y = y.join(x)
    flash('Detected Entities in Text: ' + str(y), 'success')
    flash(
        'Fulfillment text: {}\n'.format(
            response.query_result.fulfillment_text), 'success')
Esempio n. 26
0
def request(text):
    try:
        session_client = dialogflow.SessionsClient()
        session = session_client.session_path(PROJECT_ID, SESSION_ID)

        text_input = dialogflow.types.TextInput(text=text,
                                                language_code=LANGUAGE_CODE)

        query_input = dialogflow.types.QueryInput(text=text_input)

        response = session_client.detect_intent(session=session,
                                                query_input=query_input)

        response = MessageToDict(response.query_result)

        if response['parameters']:
            data = data_processing(response['parameters'])
            return data

        return
    except Exception:
        print(
            "Error with Dialogflow, service probably down, please wait a few minutes and retry. If still returning error, please contact me at [email protected]"
        )
        sys.exit()
    def detect_intent(self, session_id, texts, language_code):
        if self.service_account_json:
            session_client = dialogflow.SessionsClient.from_service_account_json(self.service_account_json)

        else:
            session_client = dialogflow.SessionsClient()

        session = session_client.session_path(self.project_id, session_id)

        for text in texts:
            text_input = dialogflow.types.TextInput(
                text=text,
                language_code=language_code
            )

            query_input = dialogflow.types.QueryInput(
                text=text_input
            )

            response = session_client.detect_intent(
                session=session,
                query_input=query_input
            )

            return response
Esempio n. 28
0
    def run(self):

        os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.path.join(
            sys.path[0], 'GLaD-OS-99f13c598280.json')

        DIALOGFLOW_PROJECT_ID = 'glad-os-vuaplf'
        DIALOGFLOW_LANGUAGE_CODE = 'en-US'
        GOOGLE_APPLICATION_CREDENTIALS = os.path.join(
            sys.path[0], 'GLaD-OS-99f13c598280.json')
        SESSION_ID = 'current-user-id'

        session_client = dialogflow_v2.SessionsClient()
        session = session_client.session_path(DIALOGFLOW_PROJECT_ID,
                                              SESSION_ID)

        text_input = dialogflow_v2.types.TextInput(
            text=self.text_to_be_analyzed,
            language_code=DIALOGFLOW_LANGUAGE_CODE)
        query_input = dialogflow_v2.types.QueryInput(text=text_input)
        try:
            response = session_client.detect_intent(session=session,
                                                    query_input=query_input)
        except InvalidArgument:
            raise

        self.response = response.query_result.fulfillment_text


# obj = DialogFlow("ashvdhvasjhdva")
# print(obj.response)
Esempio n. 29
0
def detect_intent_texts(project_id, session_id, texts, language_code):
    """Returns the result of detect intent with texts as inputs.
    Using the same `session_id` between requests allows continuation
    of the conversation."""
    import dialogflow_v2 as dialogflow
    session_client = dialogflow.SessionsClient()

    session = session_client.session_path(project_id, session_id)
    print('Session path: {}\n'.format(session))

    for text in texts:
        text_input = dialogflow.types.TextInput(text=text,
                                                language_code=language_code)

        query_input = dialogflow.types.QueryInput(text=text_input)

        response = session_client.detect_intent(session=session,
                                                query_input=query_input)

        print('=' * 20)
        print('Query text: {}'.format(response.query_result.query_text))
        print('Detected intent: {} (confidence: {})\n'.format(
            response.query_result.intent.display_name,
            response.query_result.intent_detection_confidence))
        print('Fulfillment text: {}\n'.format(
            response.query_result.fulfillment_text))
def detect_intent_texts(project_id, session_id, text, language_code):
    """Returns the result of detect intent with texts as inputs.
    Using the same `session_id` between requests allows continuation
    of the conversation."""
    import dialogflow_v2 as dialogflow
    session_client = dialogflow.SessionsClient(credentials=credentials)

    session = session_client.session_path(project_id, session_id)

    text_input = dialogflow.types.TextInput(text=text,
                                            language_code=language_code)

    query_input = dialogflow.types.QueryInput(text=text_input)

    response = session_client.detect_intent(session=session,
                                            query_input=query_input)

    query_text = response.query_result.query_text
    intent = response.query_result.intent.display_name
    # confidence = response.query_result.intent_detection_confidence
    # fulfillment = response.query_result.fulfillment_text
    # parameters = response.query_result.parameters

    print('=' * 80)
    print('Query text: {}'.format(query_text))
    # print('Detected intent: {} (confidence: {})\n'.format(intent, confidence))
    # print('Fulfillment text: {}\n'.format(fulfillment))
    # print('Parameter Entity : {}'.format(parameters))

    return intent