Search in sources :

Example 11 with Intent

use of com.google.cloud.dialogflow.v2.Intent in project java-dialogflow by googleapis.

the class IntentManagementIT method testCreateIntent.

@Test
public void testCreateIntent() throws Exception {
    // Create the intent
    Intent intent = IntentManagement.createIntent(INTENT_DISPLAY_NAME, PROJECT_ID, TRAINING_PHRASE_PARTS, MESSAGE_TEXTS);
    assertNotNull(intent);
    List<String> intentIds = IntentManagement.getIntentIds(intent.getDisplayName(), PROJECT_ID);
    assertThat(intentIds.size()).isEqualTo(1);
    List<Intent> intents = IntentManagement.listIntents(PROJECT_ID);
    assertTrue(intents.size() > 0);
    assertThat(intents).contains(intent);
    for (String messageText : MESSAGE_TEXTS) {
        assertTrue(intent.getMessagesList().stream().anyMatch(message -> message.getText().toString().contains(messageText)));
    }
    for (String intentId : intentIds) {
        IntentManagement.deleteIntent(intentId, PROJECT_ID);
    }
    int numIntents = intents.size();
    intents = IntentManagement.listIntents(PROJECT_ID);
    assertEquals(numIntents - 1, intents.size());
}
Also used : PrintStream(java.io.PrintStream) Arrays(java.util.Arrays) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Assert.assertNotNull(org.junit.Assert.assertNotNull) RunWith(org.junit.runner.RunWith) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) UUID(java.util.UUID) JUnit4(org.junit.runners.JUnit4) Truth.assertThat(com.google.common.truth.Truth.assertThat) List(java.util.List) Intent(com.google.cloud.dialogflow.v2.Intent) After(org.junit.After) AgentName(com.google.cloud.dialogflow.v2.AgentName) Assert.assertEquals(org.junit.Assert.assertEquals) IntentsClient(com.google.cloud.dialogflow.v2.IntentsClient) Before(org.junit.Before) Intent(com.google.cloud.dialogflow.v2.Intent) Test(org.junit.Test)

Example 12 with Intent

use of com.google.cloud.dialogflow.v2.Intent in project java-dialogflow by googleapis.

the class UpdateIntentIT method setUp.

@Before
public void setUp() throws IOException {
    stdOut = new ByteArrayOutputStream();
    System.setOut(new PrintStream(stdOut));
    try (IntentsClient intentsClient = IntentsClient.create()) {
        com.google.cloud.dialogflow.v2.Intent.Builder intent = Intent.newBuilder();
        intent.setDisplayName("temp_intent_" + UUID.randomUUID().toString());
        UpdateIntentIT.intentPath = intentsClient.createIntent(parent, intent.build()).getName();
        UpdateIntentIT.intentID = UpdateIntentIT.intentPath.split("/")[6];
    }
}
Also used : PrintStream(java.io.PrintStream) IntentsClient(com.google.cloud.dialogflow.v2.IntentsClient) Intent(com.google.cloud.dialogflow.v2.Intent) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Before(org.junit.Before)

Example 13 with Intent

use of com.google.cloud.dialogflow.v2.Intent in project java-dialogflow by googleapis.

the class DetectIntentAudio method detectIntentAudio.

// DialogFlow API Detect Intent sample with audio files.
public static QueryResult detectIntentAudio(String projectId, String audioFilePath, String sessionId, String languageCode) throws IOException, ApiException {
    // Instantiates a client
    try (SessionsClient sessionsClient = SessionsClient.create()) {
        // Set the session name using the sessionId (UUID) and projectID (my-project-id)
        SessionName session = SessionName.of(projectId, sessionId);
        System.out.println("Session Path: " + session.toString());
        // Note: hard coding audioEncoding and sampleRateHertz for simplicity.
        // Audio encoding of the audio content sent in the query request.
        AudioEncoding audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16;
        int sampleRateHertz = 16000;
        // Instructs the speech recognizer how to process the audio content.
        InputAudioConfig inputAudioConfig = InputAudioConfig.newBuilder().setAudioEncoding(// audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16
        audioEncoding).setLanguageCode(// languageCode = "en-US"
        languageCode).setSampleRateHertz(// sampleRateHertz = 16000
        sampleRateHertz).build();
        // Build the query with the InputAudioConfig
        QueryInput queryInput = QueryInput.newBuilder().setAudioConfig(inputAudioConfig).build();
        // Read the bytes from the audio file
        byte[] inputAudio = Files.readAllBytes(Paths.get(audioFilePath));
        // Build the DetectIntentRequest
        DetectIntentRequest request = DetectIntentRequest.newBuilder().setSession(session.toString()).setQueryInput(queryInput).setInputAudio(ByteString.copyFrom(inputAudio)).build();
        // Performs the detect intent request
        DetectIntentResponse response = sessionsClient.detectIntent(request);
        // Display the query result
        QueryResult queryResult = response.getQueryResult();
        System.out.println("====================");
        System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
        System.out.format("Detected Intent: %s (confidence: %f)\n", queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
        System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentMessagesCount() > 0 ? queryResult.getFulfillmentMessages(0).getText() : "Triggered Default Fallback Intent");
        return queryResult;
    }
}
Also used : DetectIntentResponse(com.google.cloud.dialogflow.v2.DetectIntentResponse) QueryInput(com.google.cloud.dialogflow.v2.QueryInput) DetectIntentRequest(com.google.cloud.dialogflow.v2.DetectIntentRequest) QueryResult(com.google.cloud.dialogflow.v2.QueryResult) InputAudioConfig(com.google.cloud.dialogflow.v2.InputAudioConfig) AudioEncoding(com.google.cloud.dialogflow.v2.AudioEncoding) SessionsClient(com.google.cloud.dialogflow.v2.SessionsClient) SessionName(com.google.cloud.dialogflow.v2.SessionName)

Example 14 with Intent

use of com.google.cloud.dialogflow.v2.Intent in project java-dialogflow by googleapis.

the class DetectIntentStream method detectIntentStream.

// DialogFlow API Detect Intent sample with audio files processes as an audio stream.
static void detectIntentStream(String projectId, String audioFilePath, String sessionId) throws IOException, ApiException {
    // Instantiates a client
    try (SessionsClient sessionsClient = SessionsClient.create()) {
        // Set the session name using the sessionId (UUID) and projectID (my-project-id)
        SessionName session = SessionName.of(projectId, sessionId);
        // Instructs the speech recognizer how to process the audio content.
        // Note: hard coding audioEncoding and sampleRateHertz for simplicity.
        // Audio encoding of the audio content sent in the query request.
        InputAudioConfig inputAudioConfig = InputAudioConfig.newBuilder().setAudioEncoding(AudioEncoding.AUDIO_ENCODING_LINEAR_16).setLanguageCode(// languageCode = "en-US"
        "en-US").setSampleRateHertz(// sampleRateHertz = 16000
        16000).build();
        // Build the query with the InputAudioConfig
        QueryInput queryInput = QueryInput.newBuilder().setAudioConfig(inputAudioConfig).build();
        // Create the Bidirectional stream
        BidiStream<StreamingDetectIntentRequest, StreamingDetectIntentResponse> bidiStream = sessionsClient.streamingDetectIntentCallable().call();
        // The first request must **only** contain the audio configuration:
        bidiStream.send(StreamingDetectIntentRequest.newBuilder().setSession(session.toString()).setQueryInput(queryInput).build());
        try (FileInputStream audioStream = new FileInputStream(audioFilePath)) {
            // Subsequent requests must **only** contain the audio data.
            // Following messages: audio chunks. We just read the file in fixed-size chunks. In reality
            // you would split the user input by time.
            byte[] buffer = new byte[4096];
            int bytes;
            while ((bytes = audioStream.read(buffer)) != -1) {
                bidiStream.send(StreamingDetectIntentRequest.newBuilder().setInputAudio(ByteString.copyFrom(buffer, 0, bytes)).build());
            }
        }
        // Tell the service you are done sending data
        bidiStream.closeSend();
        for (StreamingDetectIntentResponse response : bidiStream) {
            QueryResult queryResult = response.getQueryResult();
            System.out.println("====================");
            System.out.format("Intent Display Name: %s\n", queryResult.getIntent().getDisplayName());
            System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
            System.out.format("Detected Intent: %s (confidence: %f)\n", queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
            System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentMessagesCount() > 0 ? queryResult.getFulfillmentMessages(0).getText() : "Triggered Default Fallback Intent");
        }
    }
}
Also used : StreamingDetectIntentRequest(com.google.cloud.dialogflow.v2.StreamingDetectIntentRequest) QueryInput(com.google.cloud.dialogflow.v2.QueryInput) QueryResult(com.google.cloud.dialogflow.v2.QueryResult) InputAudioConfig(com.google.cloud.dialogflow.v2.InputAudioConfig) StreamingDetectIntentResponse(com.google.cloud.dialogflow.v2.StreamingDetectIntentResponse) SessionsClient(com.google.cloud.dialogflow.v2.SessionsClient) SessionName(com.google.cloud.dialogflow.v2.SessionName) FileInputStream(java.io.FileInputStream)

Example 15 with Intent

use of com.google.cloud.dialogflow.v2.Intent in project java-dialogflow by googleapis.

the class DetectIntentTexts method detectIntentTexts.

// DialogFlow API Detect Intent sample with text inputs.
public static Map<String, QueryResult> detectIntentTexts(String projectId, List<String> texts, String sessionId, String languageCode) throws IOException, ApiException {
    Map<String, QueryResult> queryResults = Maps.newHashMap();
    // Instantiates a client
    try (SessionsClient sessionsClient = SessionsClient.create()) {
        // Set the session name using the sessionId (UUID) and projectID (my-project-id)
        SessionName session = SessionName.of(projectId, sessionId);
        System.out.println("Session Path: " + session.toString());
        // Detect intents for each text input
        for (String text : texts) {
            // Set the text (hello) and language code (en-US) for the query
            TextInput.Builder textInput = TextInput.newBuilder().setText(text).setLanguageCode(languageCode);
            // Build the query with the TextInput
            QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();
            // Performs the detect intent request
            DetectIntentResponse response = sessionsClient.detectIntent(session, queryInput);
            // Display the query result
            QueryResult queryResult = response.getQueryResult();
            System.out.println("====================");
            System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
            System.out.format("Detected Intent: %s (confidence: %f)\n", queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
            System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentMessagesCount() > 0 ? queryResult.getFulfillmentMessages(0).getText() : "Triggered Default Fallback Intent");
            queryResults.put(text, queryResult);
        }
    }
    return queryResults;
}
Also used : DetectIntentResponse(com.google.cloud.dialogflow.v2.DetectIntentResponse) QueryInput(com.google.cloud.dialogflow.v2.QueryInput) QueryResult(com.google.cloud.dialogflow.v2.QueryResult) SessionsClient(com.google.cloud.dialogflow.v2.SessionsClient) TextInput(com.google.cloud.dialogflow.v2.TextInput) SessionName(com.google.cloud.dialogflow.v2.SessionName)

Aggregations

Test (org.junit.Test)12 Intent (com.google.cloud.dialogflow.v2.Intent)10 IntentsClient (com.google.cloud.dialogflow.v2.IntentsClient)8 Intent (com.google.cloud.dialogflow.cx.v3beta1.Intent)7 QueryInput (com.google.cloud.dialogflow.v2.QueryInput)5 QueryResult (com.google.cloud.dialogflow.v2.QueryResult)5 SessionName (com.google.cloud.dialogflow.v2.SessionName)5 SessionsClient (com.google.cloud.dialogflow.v2.SessionsClient)5 AgentName (com.google.cloud.dialogflow.v2.AgentName)4 DetectIntentResponse (com.google.cloud.dialogflow.v2.DetectIntentResponse)4 ListIntentsPagedResponse (com.google.cloud.dialogflow.v2.IntentsClient.ListIntentsPagedResponse)4 AbstractMessage (com.google.protobuf.AbstractMessage)4 Intent (com.google.cloud.dialogflow.cx.v3.Intent)3 IntentsClient (com.google.cloud.dialogflow.cx.v3.IntentsClient)3 TrainingPhrase (com.google.cloud.dialogflow.cx.v3beta1.Intent.TrainingPhrase)3 DetectIntentRequest (com.google.cloud.dialogflow.v2.DetectIntentRequest)3 TextInput (com.google.cloud.dialogflow.v2.TextInput)3 FieldMask (com.google.protobuf.FieldMask)3 ArrayList (java.util.ArrayList)3 IntentsClient (com.google.cloud.dialogflow.cx.v3beta1.IntentsClient)2