示例#1
0
def test_credentials_transport_error():
    # It is an error to provide credentials and a transport instance.
    transport = transports.SessionsGrpcTransport(
        credentials=credentials.AnonymousCredentials(), )
    with pytest.raises(ValueError):
        client = SessionsClient(
            credentials=credentials.AnonymousCredentials(),
            transport=transport,
        )

    # It is an error to provide a credentials file and a transport instance.
    transport = transports.SessionsGrpcTransport(
        credentials=credentials.AnonymousCredentials(), )
    with pytest.raises(ValueError):
        client = SessionsClient(
            client_options={"credentials_file": "credentials.json"},
            transport=transport,
        )

    # It is an error to provide scopes and a transport instance.
    transport = transports.SessionsGrpcTransport(
        credentials=credentials.AnonymousCredentials(), )
    with pytest.raises(ValueError):
        client = SessionsClient(
            client_options={"scopes": ["1", "2"]},
            transport=transport,
        )
示例#2
0
def detect_intent_texts(agent, 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_path = f"{agent}/sessions/{session_id}"
    print(f"Session path: {session_path}\n")
    client_options = None
    agent_components = AgentsClient.parse_agent_path(agent)
    location_id = agent_components["location"]
    if location_id != "global":
        api_endpoint = f"{location_id}-dialogflow.googleapis.com:443"
        print(f"API Endpoint: {api_endpoint}\n")
        client_options = {"api_endpoint": api_endpoint}
    session_client = SessionsClient(client_options=client_options)
    text_input = session.TextInput(text=text)
    query_input = session.QueryInput(text=text_input,
                                     language_code=language_code)
    request = session.DetectIntentRequest(session=session_path,
                                          query_input=query_input)
    response = session_client.detect_intent(request=request)

    print("=" * 20)
    print(f"Query text: {response.query_result.text}")
    response_messages = [
        " ".join(msg.text.text)
        for msg in response.query_result.response_messages
    ]
    print(f"Response text: {' '.join(response_messages)}\n")
    return response
示例#3
0
def test_fulfill_intent_field_headers():
    client = SessionsClient(credentials=credentials.AnonymousCredentials(), )

    # Any value that is part of the HTTP/1.1 URI should be sent as
    # a field header. Set these to a non-empty value.
    request = session.FulfillIntentRequest()
    request.match_intent_request.session = "match_intent_request.session/value"

    # Mock the actual call within the gRPC stub, and fake the request.
    with mock.patch.object(type(client._transport.fulfill_intent),
                           "__call__") as call:
        call.return_value = session.FulfillIntentResponse()

        client.fulfill_intent(request)

        # Establish that the underlying gRPC stub method was called.
        assert len(call.mock_calls) == 1
        _, args, _ = call.mock_calls[0]
        assert args[0] == request

    # Establish that the field header was sent.
    _, _, kw = call.mock_calls[0]
    assert (
        "x-goog-request-params",
        "match_intent_request.session=match_intent_request.session/value",
    ) in kw["metadata"]
示例#4
0
def discord_response(user, message_contents):
    """Returns the result of detect intent with texts as inputs.

    Using the same `session_id` between requests allows continuation
    of the conversation."""
    session_path = f"{agent}/sessions/{session_id}"
    #print(f"Session path: {session_path}\n")
    client_options = None
    agent_components = AgentsClient.parse_agent_path(agent)
    location_id = agent_components["location"]
    if location_id != "global":
        api_endpoint = f"{location_id}-dialogflow.googleapis.com:443"
        print(f"API Endpoint: {api_endpoint}\n")
        client_options = {"api_endpoint": api_endpoint}
    session_client = SessionsClient(client_options=client_options)

    input_string  = message_contents
    image_float   = analyze_sentiment(user, input_string)
    text_input    = session.TextInput(text=input_string)
    query_input   = session.QueryInput(text=text_input, language_code=language_code)
    request = session.DetectIntentRequest(
          session=session_path, query_input=query_input
		)
    response = session_client.detect_intent(request=request)

    #print("=" * 20)
    #print(f"Query text: {response.query_result.text}")
    response_messages = [
      " ".join(msg.text.text) for msg in response.query_result.response_messages
    ]
    return ((os.getcwd() + find_emotion_gif(image_float)), f"{' '.join(response_messages)}\n")
示例#5
0
def detect_intent_audio(agent, session_id, audio_file_path, language_code):
    """Returns the result of detect intent with an audio file as input.

    Using the same `session_id` between requests allows continuation
    of the conversation."""
    session_client = SessionsClient()
    session_path = f"{agent}/sessions/{session_id}"
    print(f"Session path: {session_path}\n")

    input_audio_config = audio_config.InputAudioConfig(
        audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16,
        sample_rate_hertz=24000,
    )

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

    audio_input = session.AudioInput(config=input_audio_config,
                                     audio=input_audio)
    query_input = session.QueryInput(audio=audio_input,
                                     language_code=language_code)
    request = session.DetectIntentRequest(session=session_path,
                                          query_input=query_input)
    response = session_client.detect_intent(request=request)

    print("=" * 20)
    print(f"Query text: {response.query_result.transcript}")
    response_messages = [
        " ".join(msg.text.text)
        for msg in response.query_result.response_messages
    ]
    print(f"Response text: {' '.join(response_messages)}\n")
示例#6
0
def test_fulfill_intent(transport: str = "grpc",
                        request_type=session.FulfillIntentRequest):
    client = SessionsClient(
        credentials=credentials.AnonymousCredentials(),
        transport=transport,
    )

    # Everything is optional in proto3 as far as the runtime is concerned,
    # and we are mocking out the actual API, so just send an empty request.
    request = request_type()

    # Mock the actual call within the gRPC stub, and fake the request.
    with mock.patch.object(type(client._transport.fulfill_intent),
                           "__call__") as call:
        # Designate an appropriate return value for the call.
        call.return_value = session.FulfillIntentResponse(
            response_id="response_id_value",
            output_audio=b"output_audio_blob",
        )

        response = client.fulfill_intent(request)

        # Establish that the underlying gRPC stub method was called.
        assert len(call.mock_calls) == 1
        _, args, _ = call.mock_calls[0]

        assert args[0] == session.FulfillIntentRequest()

    # Establish that the response is the type that we expect.
    assert isinstance(response, session.FulfillIntentResponse)

    assert response.response_id == "response_id_value"

    assert response.output_audio == b"output_audio_blob"
示例#7
0
def test_streaming_detect_intent(
        transport: str = "grpc",
        request_type=session.StreamingDetectIntentRequest):
    client = SessionsClient(
        credentials=credentials.AnonymousCredentials(),
        transport=transport,
    )

    # Everything is optional in proto3 as far as the runtime is concerned,
    # and we are mocking out the actual API, so just send an empty request.
    request = request_type()

    requests = [request]

    # Mock the actual call within the gRPC stub, and fake the request.
    with mock.patch.object(type(client._transport.streaming_detect_intent),
                           "__call__") as call:
        # Designate an appropriate return value for the call.
        call.return_value = iter([session.StreamingDetectIntentResponse()])

        response = client.streaming_detect_intent(iter(requests))

        # Establish that the underlying gRPC stub method was called.
        assert len(call.mock_calls) == 1
        _, args, _ = call.mock_calls[0]

        assert next(args[0]) == request

    # Establish that the response is the type that we expect.
    for message in response:
        assert isinstance(message, session.StreamingDetectIntentResponse)
示例#8
0
def detect_intent_stream(agent, session_id, audio_file_path, language_code):
    """Returns the result of detect intent with streaming audio as input.

    Using the same `session_id` between requests allows continuation
    of the conversation."""
    session_client = SessionsClient()
    session_path = f"{agent}/sessions/{session_id}"
    print(f"Session path: {session_path}\n")

    input_audio_config = audio_config.InputAudioConfig(
        audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16,
        sample_rate_hertz=24000,
    )

    def request_generator():
        audio_input = session.AudioInput(config=input_audio_config)
        query_input = session.QueryInput(audio=audio_input,
                                         language_code=language_code)

        # The first request contains the configuration.
        yield session.StreamingDetectIntentRequest(session=session_path,
                                                   query_input=query_input)

        # Here we are reading small chunks of audio data from a local
        # audio file.  In practice these chunks should come from
        # an audio input device.
        with open(audio_file_path, "rb") as audio_file:
            while True:
                chunk = audio_file.read(4096)
                if not chunk:
                    break
                # The later requests contains audio data.
                audio_input = session.AudioInput(audio=chunk)
                query_input = session.QueryInput(audio=audio_input)
                yield session.StreamingDetectIntentRequest(
                    query_input=query_input)

    responses = session_client.streaming_detect_intent(
        requests=request_generator())

    print("=" * 20)
    for response in responses:
        print(
            f'Intermediate transcript: "{response.recognition_result.transcript}".'
        )

    # Note: The result from the last response is the final transcript along
    # with the detected content.
    response = response.detect_intent_response
    print(f"Query text: {response.query_result.transcript}")
    response_messages = [
        " ".join(msg.text.text)
        for msg in response.query_result.response_messages
    ]
    print(f"Response text: {' '.join(response_messages)}\n")
示例#9
0
def test_parse_intent_path():
    expected = {
        "project": "oyster",
        "location": "nudibranch",
        "agent": "cuttlefish",
        "intent": "mussel",
    }
    path = SessionsClient.intent_path(**expected)

    # Check that the path construction is reversible.
    actual = SessionsClient.parse_intent_path(path)
    assert expected == actual
示例#10
0
def test_parse_session_entity_type_path():
    expected = {
        "project": "nudibranch",
        "location": "cuttlefish",
        "agent": "mussel",
        "session": "winkle",
        "entity_type": "nautilus",
    }
    path = SessionsClient.session_entity_type_path(**expected)

    # Check that the path construction is reversible.
    actual = SessionsClient.parse_session_entity_type_path(path)
    assert expected == actual
示例#11
0
def detect_intent(user): #, agent, session_id, 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_path = f"{agent}/sessions/{session_id}"
    print(f"Session path: {session_path}\n")
    client_options = None
    agent_components = AgentsClient.parse_agent_path(agent)
    location_id = agent_components["location"]
    if location_id != "global":
        api_endpoint = f"{location_id}-dialogflow.googleapis.com:443"
        print(f"API Endpoint: {api_endpoint}\n")
        client_options = {"api_endpoint": api_endpoint}
    session_client = SessionsClient(client_options=client_options)

    input_string = input("Enter your prompt for bitberg")
    while(input_string != 'close'):
      image_float = analyze_sentiment(user, input_string)
      text_input = session.TextInput(text=input_string)
      query_input = session.QueryInput(text=text_input, language_code=language_code)
      request = session.DetectIntentRequest(
           session=session_path, query_input=query_input
			)
      response = session_client.detect_intent(request=request)
			#display image somehow
      #
      #
      ### display_gif(find_emotion_gif(image_float))
      #
      #
      if  -1.0 < image_float < -0.5:
          __display_gif('angry')
				#display angry
      elif image_float < 0.0:
          __display_gif('sad')
				#display sad
      elif image_float < 0.5:
          __display_gif('bored')
				#display bored
      else:
          __display_gif('happy')
				  #display happy
      print("=" * 20)
      print(f"Query text: {response.query_result.text}")
      response_messages = [
      " ".join(msg.text.text) for msg in response.query_result.response_messages
      ]
      print(f"Response text: {' '.join(response_messages)}\n")

      input_string = input()
示例#12
0
def test_sessions_host_with_port():
    client = SessionsClient(
        credentials=credentials.AnonymousCredentials(),
        client_options=client_options.ClientOptions(
            api_endpoint="dialogflow.googleapis.com:8000"),
    )
    assert client._transport._host == "dialogflow.googleapis.com:8000"
示例#13
0
def test_transport_grpc_default():
    # A client should use the gRPC transport by default.
    client = SessionsClient(credentials=credentials.AnonymousCredentials(), )
    assert isinstance(
        client._transport,
        transports.SessionsGrpcTransport,
    )
示例#14
0
def test_client_withDEFAULT_CLIENT_INFO():
    client_info = gapic_v1.client_info.ClientInfo()

    with mock.patch.object(transports.SessionsTransport,
                           "_prep_wrapped_messages") as prep:
        client = SessionsClient(
            credentials=credentials.AnonymousCredentials(),
            client_info=client_info,
        )
        prep.assert_called_once_with(client_info)

    with mock.patch.object(transports.SessionsTransport,
                           "_prep_wrapped_messages") as prep:
        transport_class = SessionsClient.get_transport_class()
        transport = transport_class(
            credentials=credentials.AnonymousCredentials(),
            client_info=client_info,
        )
        prep.assert_called_once_with(client_info)
示例#15
0
def test_sessions_auth_adc():
    # If no credentials are provided, we should use ADC credentials.
    with mock.patch.object(auth, "default") as adc:
        adc.return_value = (credentials.AnonymousCredentials(), None)
        SessionsClient()
        adc.assert_called_once_with(
            scopes=(
                "https://www.googleapis.com/auth/cloud-platform",
                "https://www.googleapis.com/auth/dialogflow",
            ),
            quota_project_id=None,
        )
示例#16
0
def detect_intent_audio(agent, session_id, audio_file_path, language_code):
    """Returns the result of detect intent with an audio file as input.

    Using the same `session_id` between requests allows continuation
    of the conversation."""
    session_path = f"{agent}/sessions/{session_id}"
    print(f"Session path: {session_path}\n")
    client_options = None
    agent_components = AgentsClient.parse_agent_path(agent)
    location_id = agent_components["location"]
    if location_id != "global":
        api_endpoint = f"{location_id}-dialogflow.googleapis.com:443"
        print(f"API Endpoint: {api_endpoint}\n")
        client_options = {"api_endpoint": api_endpoint}
    session_client = SessionsClient(client_options=client_options)

    input_audio_config = audio_config.InputAudioConfig(
        audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16,
        sample_rate_hertz=24000,
    )

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

    audio_input = session.AudioInput(config=input_audio_config,
                                     audio=input_audio)
    query_input = session.QueryInput(audio=audio_input,
                                     language_code=language_code)
    request = session.DetectIntentRequest(session=session_path,
                                          query_input=query_input)
    response = session_client.detect_intent(request=request)

    print("=" * 20)
    print(f"Query text: {response.query_result.transcript}")
    response_messages = [
        " ".join(msg.text.text)
        for msg in response.query_result.response_messages
    ]
    print(f"Response text: {' '.join(response_messages)}\n")
示例#17
0
def detect_intent_text(agent, 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_path = f"{agent}/sessions/{session_id}"
    client_options = None
    agent_components = AgentsClient.parse_agent_path(agent)
    location_id = agent_components["location"]
    if location_id != "global":
        api_endpoint = f"{location_id}-dialogflow.googleapis.com:443"
        client_options = {"api_endpoint": api_endpoint}
    session_client = SessionsClient(client_options=client_options)

    text_input = session.TextInput(text=text)
    query_input = session.QueryInput(text=text_input, language_code=language_code)
    my_request = session.DetectIntentRequest(
        session=session_path, query_input=query_input
    )
    response = session_client.detect_intent(request=my_request)
    serializable_messages = [proto.Message.to_dict(message) for message in \
      response.query_result.response_messages]
    return json.dumps({'messages':serializable_messages})
示例#18
0
def test_intent_path():
    project = "squid"
    location = "clam"
    agent = "whelk"
    intent = "octopus"

    expected = "projects/{project}/locations/{location}/agents/{agent}/intents/{intent}".format(
        project=project,
        location=location,
        agent=agent,
        intent=intent,
    )
    actual = SessionsClient.intent_path(project, location, agent, intent)
    assert expected == actual
def detect_intent_texts(agent, 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."""
    session_client = SessionsClient()
    session_path = f"{agent}/sessions/{session_id}"
    print(f"Session path: {session_path}\n")

    for text in texts:
        text_input = session.TextInput(text=text)
        query_input = session.QueryInput(text=text_input,
                                         language_code=language_code)
        request = session.DetectIntentRequest(session=session_path,
                                              query_input=query_input)
        response = session_client.detect_intent(request=request)

        print("=" * 20)
        print(f"Query text: {response.query_result.text}")
        response_messages = [
            " ".join(msg.text.text)
            for msg in response.query_result.response_messages
        ]
        print(f"Response text: {' '.join(response_messages)}\n")
示例#20
0
def test_sessions_client_client_options_from_dict():
    with mock.patch(
            "google.cloud.dialogflowcx_v3beta1.services.sessions.transports.SessionsGrpcTransport.__init__"
    ) as grpc_transport:
        grpc_transport.return_value = None
        client = SessionsClient(
            client_options={"api_endpoint": "squid.clam.whelk"})
        grpc_transport.assert_called_once_with(
            credentials=None,
            credentials_file=None,
            host="squid.clam.whelk",
            scopes=None,
            api_mtls_endpoint="squid.clam.whelk",
            client_cert_source=None,
            quota_project_id=None,
            client_info=transports.base.DEFAULT_CLIENT_INFO,
        )
示例#21
0
def test_session_entity_type_path():
    project = "squid"
    location = "clam"
    agent = "whelk"
    session = "octopus"
    entity_type = "oyster"

    expected = "projects/{project}/locations/{location}/agents/{agent}/sessions/{session}/entityTypes/{entity_type}".format(
        project=project,
        location=location,
        agent=agent,
        session=session,
        entity_type=entity_type,
    )
    actual = SessionsClient.session_entity_type_path(project, location, agent,
                                                     session, entity_type)
    assert expected == actual
示例#22
0
def test__get_default_mtls_endpoint():
    api_endpoint = "example.googleapis.com"
    api_mtls_endpoint = "example.mtls.googleapis.com"
    sandbox_endpoint = "example.sandbox.googleapis.com"
    sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com"
    non_googleapi = "api.example.com"

    assert SessionsClient._get_default_mtls_endpoint(None) is None
    assert SessionsClient._get_default_mtls_endpoint(
        api_endpoint) == api_mtls_endpoint
    assert (SessionsClient._get_default_mtls_endpoint(api_mtls_endpoint) ==
            api_mtls_endpoint)
    assert (SessionsClient._get_default_mtls_endpoint(sandbox_endpoint) ==
            sandbox_mtls_endpoint)
    assert (SessionsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) ==
            sandbox_mtls_endpoint)
    assert SessionsClient._get_default_mtls_endpoint(
        non_googleapi) == non_googleapi
示例#23
0
def test_transport_instance():
    # A client may be instantiated with a custom transport instance.
    transport = transports.SessionsGrpcTransport(
        credentials=credentials.AnonymousCredentials(), )
    client = SessionsClient(transport=transport)
    assert client._transport is transport
def detect_intent_stream(agent, session_id, audio_file_path, language_code):
    """Returns the result of detect intent with streaming audio as input.

    Using the same `session_id` between requests allows continuation
    of the conversation."""
    session_path = f"{agent}/sessions/{session_id}"
    print(f"Session path: {session_path}\n")
    client_options = None
    agent_components = AgentsClient.parse_agent_path(agent)
    location_id = agent_components["location"]
    if location_id != "global":
        api_endpoint = f"{location_id}-dialogflow.googleapis.com:443"
        print(f"API Endpoint: {api_endpoint}\n")
        client_options = {"api_endpoint": api_endpoint}
    session_client = SessionsClient(client_options=client_options)

    input_audio_config = audio_config.InputAudioConfig(
        audio_encoding=audio_config.AudioEncoding.AUDIO_ENCODING_LINEAR_16,
        sample_rate_hertz=24000,
    )

    def request_generator():
        audio_input = session.AudioInput(config=input_audio_config)
        query_input = session.QueryInput(audio=audio_input,
                                         language_code=language_code)
        voice_selection = audio_config.VoiceSelectionParams()
        synthesize_speech_config = audio_config.SynthesizeSpeechConfig()
        output_audio_config = audio_config.OutputAudioConfig()

        # Sets the voice name and gender
        voice_selection.name = "en-GB-Standard-A"
        voice_selection.ssml_gender = (
            audio_config.SsmlVoiceGender.SSML_VOICE_GENDER_FEMALE)

        synthesize_speech_config.voice = voice_selection

        # Sets the audio encoding
        output_audio_config.audio_encoding = (
            audio_config.OutputAudioEncoding.OUTPUT_AUDIO_ENCODING_UNSPECIFIED)
        output_audio_config.synthesize_speech_config = synthesize_speech_config

        # The first request contains the configuration.
        yield session.StreamingDetectIntentRequest(
            session=session_path,
            query_input=query_input,
            output_audio_config=output_audio_config,
        )

        # Here we are reading small chunks of audio data from a local
        # audio file.  In practice these chunks should come from
        # an audio input device.
        with open(audio_file_path, "rb") as audio_file:
            while True:
                chunk = audio_file.read(4096)
                if not chunk:
                    break
                # The later requests contains audio data.
                audio_input = session.AudioInput(audio=chunk)
                query_input = session.QueryInput(audio=audio_input)
                yield session.StreamingDetectIntentRequest(
                    query_input=query_input)

    responses = session_client.streaming_detect_intent(
        requests=request_generator())

    print("=" * 20)
    for response in responses:
        print(
            f'Intermediate transcript: "{response.recognition_result.transcript}".'
        )

    # Note: The result from the last response is the final transcript along
    # with the detected content.
    response = response.detect_intent_response
    print(f"Query text: {response.query_result.transcript}")
    response_messages = [
        " ".join(msg.text.text)
        for msg in response.query_result.response_messages
    ]
    print(f"Response text: {' '.join(response_messages)}\n")
示例#25
0
def test_sessions_client_get_transport_class():
    transport = SessionsClient.get_transport_class()
    assert transport == transports.SessionsGrpcTransport

    transport = SessionsClient.get_transport_class("grpc")
    assert transport == transports.SessionsGrpcTransport