diff --git a/README.md b/README.md index e6f44871f..24a1bcb7f 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,14 @@ Samples are in the [`samples/`](https://github.com/googleapis/java-dialogflow-cx | Create Simple Page | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/CreateSimplePage.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/CreateSimplePage.java) | | Delete Page | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/DeletePage.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/DeletePage.java) | | Detect Intent | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/DetectIntent.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/DetectIntent.java) | +| Detect Intent Audio Input | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/DetectIntentAudioInput.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/DetectIntentAudioInput.java) | +| Detect Intent Disable Webhook | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/DetectIntentDisableWebhook.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/DetectIntentDisableWebhook.java) | +| Detect Intent Event Input | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/DetectIntentEventInput.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/DetectIntentEventInput.java) | +| Detect Intent Intent Input | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/DetectIntentIntentInput.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/DetectIntentIntentInput.java) | +| Detect Intent Sentiment Analysis | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/DetectIntentSentimentAnalysis.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/DetectIntentSentimentAnalysis.java) | | Detect Intent Stream | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/DetectIntentStream.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/DetectIntentStream.java) | +| Detect Intent Streaming Partial Response | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/DetectIntentStreamingPartialResponse.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/DetectIntentStreamingPartialResponse.java) | +| Detect Intent Synthesize Text To Speech Output | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutput.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutput.java) | | Export Agent | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/ExportAgent.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/ExportAgent.java) | | List Pages | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/ListPages.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/ListPages.java) | | List Test Case Results | [source code](https://github.com/googleapis/java-dialogflow-cx/blob/main/samples/snippets/src/main/java/dialogflow/cx/ListTestCaseResults.java) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/java-dialogflow-cx&page=editor&open_in_editor=samples/snippets/src/main/java/dialogflow/cx/ListTestCaseResults.java) | diff --git a/samples/snippets/src/main/java/dialogflow/cx/DetectIntentAudioInput.java b/samples/snippets/src/main/java/dialogflow/cx/DetectIntentAudioInput.java new file mode 100644 index 000000000..e864f381a --- /dev/null +++ b/samples/snippets/src/main/java/dialogflow/cx/DetectIntentAudioInput.java @@ -0,0 +1,128 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_v3_detect_intent_audio_input] + +import com.google.api.gax.rpc.ApiException; +import com.google.cloud.dialogflow.cx.v3.AudioEncoding; +import com.google.cloud.dialogflow.cx.v3.AudioInput; +import com.google.cloud.dialogflow.cx.v3.DetectIntentRequest; +import com.google.cloud.dialogflow.cx.v3.DetectIntentResponse; +import com.google.cloud.dialogflow.cx.v3.InputAudioConfig; +import com.google.cloud.dialogflow.cx.v3.QueryInput; +import com.google.cloud.dialogflow.cx.v3.QueryResult; +import com.google.cloud.dialogflow.cx.v3.SessionName; +import com.google.cloud.dialogflow.cx.v3.SessionsClient; +import com.google.cloud.dialogflow.cx.v3.SessionsSettings; +import com.google.protobuf.ByteString; +import java.io.FileInputStream; +import java.io.IOException; + +public class DetectIntentAudioInput { + + // DialogFlow API Detect Intent sample with Audio input. + public static void main(String[] args) throws IOException, ApiException { + /** TODO (developer): replace these values with your own values */ + String projectId = "my-project-id"; + String locationId = "global"; + String agentId = "my-agent-id"; + String audioFileName = "resources/book_a_room.wav"; + int sampleRateHertz = 16000; + /* + * A session ID is a string of at most 36 bytes in size. + * Your system is responsible for generating unique session IDs. + * They can be random numbers, hashed end-user identifiers, + * or any other values that are convenient for you to generate. + */ + String sessionId = "my-UUID"; + String languageCode = "en"; + + detectIntent( + projectId, locationId, agentId, audioFileName, sampleRateHertz, sessionId, languageCode); + } + + public static void detectIntent( + String projectId, + String locationId, + String agentId, + String audioFileName, + int sampleRateHertz, + String sessionId, + String languageCode) + throws IOException, ApiException { + + SessionsSettings.Builder sessionsSettingsBuilder = SessionsSettings.newBuilder(); + if (locationId.equals("global")) { + sessionsSettingsBuilder.setEndpoint("dialogflow.googleapis.com:443"); + } else { + sessionsSettingsBuilder.setEndpoint(locationId + "-dialogflow.googleapis.com:443"); + } + SessionsSettings sessionsSettings = sessionsSettingsBuilder.build(); + + // Instantiates a client by setting the session name. + // Format:`projects//locations//agents//sessions/` + try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) { + SessionName session = + SessionName.ofProjectLocationAgentSessionName(projectId, locationId, agentId, sessionId); + + // TODO : Uncomment if you want to print session path + // System.out.println("Session Path: " + session.toString()); + InputAudioConfig inputAudioConfig = + InputAudioConfig.newBuilder() + .setAudioEncoding(AudioEncoding.AUDIO_ENCODING_LINEAR_16) + .setSampleRateHertz(sampleRateHertz) + .build(); + + try (FileInputStream audioStream = new FileInputStream(audioFileName)) { + // 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 = audioStream.read(buffer); + AudioInput audioInput = + AudioInput.newBuilder() + .setAudio(ByteString.copyFrom(buffer, 0, bytes)) + .setConfig(inputAudioConfig) + .build(); + QueryInput queryInput = + QueryInput.newBuilder() + .setAudio(audioInput) + .setLanguageCode("en-US") // languageCode = "en-US" + .build(); + + DetectIntentRequest request = + DetectIntentRequest.newBuilder() + .setSession(session.toString()) + .setQueryInput(queryInput) + .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( + "Detected Intent: %s (confidence: %f)\n", + queryResult.getTranscript(), queryResult.getIntentDetectionConfidence()); + } + } + } +} +// [END dialogflow_cx_v3_detect_intent_audio_input] diff --git a/samples/snippets/src/main/java/dialogflow/cx/DetectIntentDisableWebhook.java b/samples/snippets/src/main/java/dialogflow/cx/DetectIntentDisableWebhook.java new file mode 100644 index 000000000..c0cf470fe --- /dev/null +++ b/samples/snippets/src/main/java/dialogflow/cx/DetectIntentDisableWebhook.java @@ -0,0 +1,120 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_v3_detect_intent_disable_webhook] + +import com.google.api.gax.rpc.ApiException; +import com.google.cloud.dialogflow.cx.v3.DetectIntentRequest; +import com.google.cloud.dialogflow.cx.v3.DetectIntentResponse; +import com.google.cloud.dialogflow.cx.v3.QueryInput; +import com.google.cloud.dialogflow.cx.v3.QueryParameters; +import com.google.cloud.dialogflow.cx.v3.QueryResult; +import com.google.cloud.dialogflow.cx.v3.SessionName; +import com.google.cloud.dialogflow.cx.v3.SessionsClient; +import com.google.cloud.dialogflow.cx.v3.SessionsSettings; +import com.google.cloud.dialogflow.cx.v3.TextInput; +import com.google.common.collect.Maps; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class DetectIntentDisableWebhook { + + public static void main(String[] args) throws IOException, ApiException { + String projectId = "my-project-id"; + String locationId = "global"; + String agentId = "my-agent-id"; + String sessionId = "my-UUID"; + List texts = new ArrayList<>(List.of("my-list", "of-texts")); + String languageCode = "en"; + + detectIntent(projectId, locationId, agentId, sessionId, texts, languageCode); + } + + // DialogFlow API Detect Intent sample with webhook disabled. + public static Map detectIntent( + String projectId, + String locationId, + String agentId, + String sessionId, + List texts, + String languageCode) + throws IOException, ApiException { + SessionsSettings.Builder sessionsSettingsBuilder = SessionsSettings.newBuilder(); + if (locationId.equals("global")) { + sessionsSettingsBuilder.setEndpoint("dialogflow.googleapis.com:443"); + } else { + sessionsSettingsBuilder.setEndpoint(locationId + "-dialogflow.googleapis.com:443"); + } + SessionsSettings sessionsSettings = sessionsSettingsBuilder.build(); + + Map queryResults = Maps.newHashMap(); + + // Instantiates a client by setting the session name. + // Format:`projects//locations//agents//sessions/` + try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) { + SessionName session = + SessionName.ofProjectLocationAgentSessionName(projectId, locationId, agentId, sessionId); + + // TODO : Uncomment if you want to print session path + // System.out.println("Session Path: " + session.toString()); + + // Detect intents for each text input. + for (String text : texts) { + // Set the text (hello) for the query. + TextInput.Builder textInput = TextInput.newBuilder().setText(text); + + // Build the query with the TextInput and language code (en-US). + QueryInput queryInput = + QueryInput.newBuilder().setText(textInput).setLanguageCode(languageCode).build(); + + // Build the query parameters and setDisableWebhook to true. + QueryParameters queryParameters = + QueryParameters.newBuilder().setDisableWebhook(true).build(); + + // Build the DetectIntentRequest with the SessionName, QueryInput, and QueryParameters. + DetectIntentRequest request = + DetectIntentRequest.newBuilder() + .setSession(session.toString()) + .setQueryInput(queryInput) + .setQueryParams(queryParameters) + .build(); + System.out.println(request.toString()); + + // Performs the detect intent request. + DetectIntentResponse response = sessionsClient.detectIntent(request); + + // Display the query result. + QueryResult queryResult = response.getQueryResult(); + + // TODO : Uncomment if you want to print queryResult + // System.out.println("===================="); + // System.out.format("Query Text: '%s'\n", queryResult.getText()); + // System.out.format( + // "Detected Intent: %s (confidence: %f)\n", + // queryResult.getIntent().getDisplayName(), + // queryResult.getIntentDetectionConfidence()); + + queryResults.put(text, queryResult); + } + } + return queryResults; + } +} +// [END dialogflow_cx_v3_detect_intent_disable_webhook] diff --git a/samples/snippets/src/main/java/dialogflow/cx/DetectIntentEventInput.java b/samples/snippets/src/main/java/dialogflow/cx/DetectIntentEventInput.java new file mode 100644 index 000000000..5f92199e9 --- /dev/null +++ b/samples/snippets/src/main/java/dialogflow/cx/DetectIntentEventInput.java @@ -0,0 +1,98 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_v3_detect_intent_event_input] + +import com.google.api.gax.rpc.ApiException; +import com.google.cloud.dialogflow.cx.v3.DetectIntentRequest; +import com.google.cloud.dialogflow.cx.v3.DetectIntentResponse; +import com.google.cloud.dialogflow.cx.v3.EventInput; +import com.google.cloud.dialogflow.cx.v3.QueryInput; +import com.google.cloud.dialogflow.cx.v3.QueryResult; +import com.google.cloud.dialogflow.cx.v3.SessionName; +import com.google.cloud.dialogflow.cx.v3.SessionsClient; +import com.google.cloud.dialogflow.cx.v3.SessionsSettings; +import java.io.IOException; + +public class DetectIntentEventInput { + + // DialogFlow API Detect Intent sample with Event input. + public static void main(String[] args) throws IOException, ApiException { + String projectId = "my-project-id"; + String locationId = "global"; + String agentId = "my-agent-id"; + String sessionId = "my-UUID"; + String event = "my-event-id"; + String languageCode = "en"; + + detectIntent(projectId, locationId, agentId, sessionId, event, languageCode); + } + + public static void detectIntent( + String projectId, + String locationId, + String agentId, + String sessionId, + String event, + String languageCode) + throws IOException, ApiException { + + SessionsSettings.Builder sessionsSettingsBuilder = SessionsSettings.newBuilder(); + if (locationId.equals("global")) { + sessionsSettingsBuilder.setEndpoint("dialogflow.googleapis.com:443"); + } else { + sessionsSettingsBuilder.setEndpoint(locationId + "-dialogflow.googleapis.com:443"); + } + SessionsSettings sessionsSettings = sessionsSettingsBuilder.build(); + + // Instantiates a client by setting the session name. + // Format:`projects//locations//agents//sessions/` + try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) { + SessionName session = + SessionName.ofProjectLocationAgentSessionName(projectId, locationId, agentId, sessionId); + + // TODO : Uncomment if you want to print session path + // System.out.println("Session Path: " + session.toString()); + + EventInput.Builder eventInput = EventInput.newBuilder().setEvent(event); + + // Build the query with the EventInput and language code (en-US). + QueryInput queryInput = + QueryInput.newBuilder().setEvent(eventInput).setLanguageCode(languageCode).build(); + + // Build the DetectIntentRequest with the SessionName and QueryInput. + DetectIntentRequest request = + DetectIntentRequest.newBuilder() + .setSession(session.toString()) + .setQueryInput(queryInput) + .build(); + + // Performs the detect intent request. + DetectIntentResponse response = sessionsClient.detectIntent(request); + + // Display the query result. + QueryResult queryResult = response.getQueryResult(); + + // TODO : Uncomment if you want to print queryResult + System.out.println("===================="); + System.out.format("Triggering Event: %s \n", queryResult.getTriggerEvent()); + } + } +} + +// [END dialogflow_cx_v3_detect_intent_event_input] diff --git a/samples/snippets/src/main/java/dialogflow/cx/DetectIntentIntentInput.java b/samples/snippets/src/main/java/dialogflow/cx/DetectIntentIntentInput.java new file mode 100644 index 000000000..45af3c567 --- /dev/null +++ b/samples/snippets/src/main/java/dialogflow/cx/DetectIntentIntentInput.java @@ -0,0 +1,100 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_v3_detect_intent_intent_input] + +import com.google.api.gax.rpc.ApiException; +import com.google.cloud.dialogflow.cx.v3.DetectIntentRequest; +import com.google.cloud.dialogflow.cx.v3.DetectIntentResponse; +import com.google.cloud.dialogflow.cx.v3.IntentInput; +import com.google.cloud.dialogflow.cx.v3.QueryInput; +import com.google.cloud.dialogflow.cx.v3.QueryResult; +import com.google.cloud.dialogflow.cx.v3.SessionName; +import com.google.cloud.dialogflow.cx.v3.SessionsClient; +import com.google.cloud.dialogflow.cx.v3.SessionsSettings; +import java.io.IOException; + +public class DetectIntentIntentInput { + + // DialogFlow API Detect Intent sample with Intent input. + public static void main(String[] args) throws IOException, ApiException { + String projectId = "my-project-id"; + String locationId = "global"; + String agentId = "my-agent-id"; + String sessionId = "my-UUID"; + String intent = "my-intent-id"; + String languageCode = "en"; + + detectIntent(projectId, locationId, agentId, sessionId, intent, languageCode); + } + + public static void detectIntent( + String projectId, + String locationId, + String agentId, + String sessionId, + String intent, + String languageCode) + throws IOException, ApiException { + + SessionsSettings.Builder sessionsSettingsBuilder = SessionsSettings.newBuilder(); + if (locationId.equals("global")) { + sessionsSettingsBuilder.setEndpoint("dialogflow.googleapis.com:443"); + } else { + sessionsSettingsBuilder.setEndpoint(locationId + "-dialogflow.googleapis.com:443"); + } + SessionsSettings sessionsSettings = sessionsSettingsBuilder.build(); + + // Instantiates a client by setting the session name. + // Format:`projects//locations//agents//sessions/` + try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) { + SessionName session = + SessionName.ofProjectLocationAgentSessionName(projectId, locationId, agentId, sessionId); + + // TODO : Uncomment if you want to print session path + // System.out.println("Session Path: " + session.toString()); + + IntentInput.Builder intentInput = IntentInput.newBuilder().setIntent(intent); + + // Build the query with the IntentInput and language code (en-US). + QueryInput queryInput = + QueryInput.newBuilder().setIntent(intentInput).setLanguageCode(languageCode).build(); + + // Build the DetectIntentRequest with the SessionName and QueryInput. + DetectIntentRequest request = + DetectIntentRequest.newBuilder() + .setSession(session.toString()) + .setQueryInput(queryInput) + .build(); + + // Performs the detect intent request. + DetectIntentResponse response = sessionsClient.detectIntent(request); + + // Display the query result. + QueryResult queryResult = response.getQueryResult(); + + // TODO : Uncomment if you want to print queryResult + System.out.println("===================="); + System.out.format( + "Detected Intent: %s (confidence: %f)\n", + queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence()); + } + } +} + +// [END dialogflow_cx_v3_detect_intent_intent_input] diff --git a/samples/snippets/src/main/java/dialogflow/cx/DetectIntentSentimentAnalysis.java b/samples/snippets/src/main/java/dialogflow/cx/DetectIntentSentimentAnalysis.java new file mode 100644 index 000000000..318242c4f --- /dev/null +++ b/samples/snippets/src/main/java/dialogflow/cx/DetectIntentSentimentAnalysis.java @@ -0,0 +1,117 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_v3_detect_intent_sentiment_analysis] + +import com.google.api.gax.rpc.ApiException; +import com.google.cloud.dialogflow.cx.v3.DetectIntentRequest; +import com.google.cloud.dialogflow.cx.v3.DetectIntentResponse; +import com.google.cloud.dialogflow.cx.v3.QueryInput; +import com.google.cloud.dialogflow.cx.v3.QueryParameters; +import com.google.cloud.dialogflow.cx.v3.QueryResult; +import com.google.cloud.dialogflow.cx.v3.SessionName; +import com.google.cloud.dialogflow.cx.v3.SessionsClient; +import com.google.cloud.dialogflow.cx.v3.SessionsSettings; +import com.google.cloud.dialogflow.cx.v3.TextInput; +import com.google.common.collect.Maps; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class DetectIntentSentimentAnalysis { + + public static void main(String[] args) throws IOException, ApiException { + String projectId = "my-project-id"; + String locationId = "global"; + String agentId = "my-agent-id"; + String sessionId = "my-UUID"; + List texts = new ArrayList<>(List.of("my-list", "of-texts")); + String languageCode = "en"; + + detectIntent(projectId, locationId, agentId, sessionId, texts, languageCode); + } + + // DialogFlow API Detect Intent sample with sentiment analysis. + public static Map detectIntent( + String projectId, + String locationId, + String agentId, + String sessionId, + List texts, + String languageCode) + throws IOException, ApiException { + SessionsSettings.Builder sessionsSettingsBuilder = SessionsSettings.newBuilder(); + if (locationId.equals("global")) { + sessionsSettingsBuilder.setEndpoint("dialogflow.googleapis.com:443"); + } else { + sessionsSettingsBuilder.setEndpoint(locationId + "-dialogflow.googleapis.com:443"); + } + SessionsSettings sessionsSettings = sessionsSettingsBuilder.build(); + + Map queryResults = Maps.newHashMap(); + + // Instantiates a client by setting the session name. + // Format:`projects//locations//agents//sessions/` + try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) { + SessionName session = + SessionName.ofProjectLocationAgentSessionName(projectId, locationId, agentId, sessionId); + + // TODO : Uncomment if you want to print session path + // System.out.println("Session Path: " + session.toString()); + + // Detect intents for each text input. + for (String text : texts) { + // Set the text (hello) for the query. + TextInput.Builder textInput = TextInput.newBuilder().setText(text); + + // Build the query with the TextInput and language code (en-US). + QueryInput queryInput = + QueryInput.newBuilder().setText(textInput).setLanguageCode(languageCode).build(); + + // Build the query parameters to analyze the sentiment of the query. + QueryParameters queryParameters = + QueryParameters.newBuilder().setAnalyzeQueryTextSentiment(true).build(); + + // Build the DetectIntentRequest with the SessionName, QueryInput, and QueryParameters. + DetectIntentRequest request = + DetectIntentRequest.newBuilder() + .setSession(session.toString()) + .setQueryInput(queryInput) + .setQueryParams(queryParameters) + .build(); + + // Performs the detect intent request. + DetectIntentResponse response = sessionsClient.detectIntent(request); + + // Display the query result. + QueryResult queryResult = response.getQueryResult(); + + // TODO : Uncomment if you want to print queryResult + // System.out.println("===================="); + // SentimentAnalysisResult sentimentAnalysisResult = + // queryResult.getSentimentAnalysisResult(); + // Float score = sentimentAnalysisResult.getScore(); + + queryResults.put(text, queryResult); + } + } + return queryResults; + } +} +// [END dialogflow_cx_v3_detect_intent_sentiment_analysis] diff --git a/samples/snippets/src/main/java/dialogflow/cx/DetectIntentStream.java b/samples/snippets/src/main/java/dialogflow/cx/DetectIntentStream.java index b09609aea..96b1799a5 100644 --- a/samples/snippets/src/main/java/dialogflow/cx/DetectIntentStream.java +++ b/samples/snippets/src/main/java/dialogflow/cx/DetectIntentStream.java @@ -53,11 +53,10 @@ public static void detectIntentStream( } SessionsSettings sessionsSettings = sessionsSettingsBuilder.build(); - // Instantiates a client + // Instantiates a client by setting the session name. + // Format: `projects//locations//agents//sessions/` + // Using the same `sessionId` between requests allows continuation of the conversation. try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) { - // Set the session name using the projectID (my-project-id), locationID (global), agentID - // (UUID), and sessionId (UUID). - // Using the same `sessionId` between requests allows continuation of the conversation. SessionName session = SessionName.of(projectId, locationId, agentId, sessionId); // Instructs the speech recognizer how to process the audio content. diff --git a/samples/snippets/src/main/java/dialogflow/cx/DetectIntentStreamingPartialResponse.java b/samples/snippets/src/main/java/dialogflow/cx/DetectIntentStreamingPartialResponse.java new file mode 100644 index 000000000..81cb534e2 --- /dev/null +++ b/samples/snippets/src/main/java/dialogflow/cx/DetectIntentStreamingPartialResponse.java @@ -0,0 +1,154 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_v3_detect_intent_streaming_partial_response] + +import com.google.api.gax.rpc.ApiException; +import com.google.api.gax.rpc.BidiStream; +import com.google.cloud.dialogflow.cx.v3.AudioEncoding; +import com.google.cloud.dialogflow.cx.v3.AudioInput; +import com.google.cloud.dialogflow.cx.v3.InputAudioConfig; +import com.google.cloud.dialogflow.cx.v3.OutputAudioConfig; +import com.google.cloud.dialogflow.cx.v3.OutputAudioEncoding; +import com.google.cloud.dialogflow.cx.v3.QueryInput; +import com.google.cloud.dialogflow.cx.v3.SessionName; +import com.google.cloud.dialogflow.cx.v3.SessionsClient; +import com.google.cloud.dialogflow.cx.v3.SessionsSettings; +import com.google.cloud.dialogflow.cx.v3.SsmlVoiceGender; +import com.google.cloud.dialogflow.cx.v3.StreamingDetectIntentRequest; +import com.google.cloud.dialogflow.cx.v3.StreamingDetectIntentResponse; +import com.google.cloud.dialogflow.cx.v3.SynthesizeSpeechConfig; +import com.google.cloud.dialogflow.cx.v3.VoiceSelectionParams; +import com.google.protobuf.ByteString; +import java.io.FileInputStream; +import java.io.IOException; + +public class DetectIntentStreamingPartialResponse { + + // DialogFlow API Detect Intent sample with audio files + // that processes as an audio stream. + public static void detectIntentStreamingPartialResponse( + String projectId, String locationId, String agentId, String sessionId, String audioFilePath) + throws ApiException, IOException { + SessionsSettings.Builder sessionsSettingsBuilder = SessionsSettings.newBuilder(); + if (locationId.equals("global")) { + sessionsSettingsBuilder.setEndpoint("dialogflow.googleapis.com:443"); + } else { + sessionsSettingsBuilder.setEndpoint(locationId + "-dialogflow.googleapis.com:443"); + } + SessionsSettings sessionsSettings = sessionsSettingsBuilder.build(); + + // Instantiates a client by setting the session name. + // Format:`projects//locations//agents//sessions/` + // Using the same `sessionId` between requests allows continuation of the conversation. + try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) { + SessionName session = SessionName.of(projectId, locationId, agentId, 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) + .setSampleRateHertz(16000) // sampleRateHertz = 16000 + .build(); + + // Build the AudioInput with the InputAudioConfig. + AudioInput audioInput = AudioInput.newBuilder().setConfig(inputAudioConfig).build(); + + // Build the query with the InputAudioConfig. + QueryInput queryInput = + QueryInput.newBuilder() + .setAudio(audioInput) + .setLanguageCode("en-US") // languageCode = "en-US" + .build(); + + // Create the Bidirectional stream + BidiStream bidiStream = + sessionsClient.streamingDetectIntentCallable().call(); + + // Specify sssml name and gender + VoiceSelectionParams voiceSelection = + // Voices that are available https://cloud.google.com/text-to-speech/docs/voices + VoiceSelectionParams.newBuilder() + .setName("en-GB-Standard-A") + .setSsmlGender(SsmlVoiceGender.SSML_VOICE_GENDER_FEMALE) + .build(); + + SynthesizeSpeechConfig speechConfig = + SynthesizeSpeechConfig.newBuilder().setVoice(voiceSelection).build(); + + // Setup audio config + OutputAudioConfig audioConfig = + // Output encoding explanation + // https://cloud.google.com/dialogflow/cx/docs/reference/rpc/google.cloud.dialogflow.cx.v3#outputaudioencoding + OutputAudioConfig.newBuilder() + .setAudioEncoding(OutputAudioEncoding.OUTPUT_AUDIO_ENCODING_UNSPECIFIED) + .setAudioEncodingValue(1) + .setSynthesizeSpeechConfig(speechConfig) + .build(); + + StreamingDetectIntentRequest streamingDetectIntentRequest = + StreamingDetectIntentRequest.newBuilder() + .setSession(session.toString()) + .setQueryInput(queryInput) + .setEnablePartialResponse(true) + .setOutputAudioConfig(audioConfig) + .build(); + System.out.println(streamingDetectIntentRequest.toString()); + + // The first request must **only** contain the audio configuration: + bidiStream.send(streamingDetectIntentRequest); + + 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) { + AudioInput subAudioInput = + AudioInput.newBuilder().setAudio(ByteString.copyFrom(buffer, 0, bytes)).build(); + QueryInput subQueryInput = + QueryInput.newBuilder() + .setAudio(subAudioInput) + .setLanguageCode("en-US") // languageCode = "en-US" + .build(); + bidiStream.send( + StreamingDetectIntentRequest.newBuilder().setQueryInput(subQueryInput).build()); + } + } + + // Tell the service you are done sending data. + bidiStream.closeSend(); + + // TODO: Uncomment to print detectIntentResponse. + + // for (StreamingDetectIntentResponse response : bidiStream) { + // QueryResult queryResult = response.getDetectIntentResponse().getQueryResult(); + // System.out.println("===================="); + // System.out.format("Query Text: '%s'\n", queryResult.getTranscript()); + // System.out.format( + // "Detected Intent: %s (confidence: %f)\n", + // queryResult.getIntent() + // .getDisplayName(), queryResult.getIntentDetectionConfidence()); + // } + } + } +} +// [END dialogflow_cx_v3_detect_intent_streaming_partial_response] diff --git a/samples/snippets/src/main/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutput.java b/samples/snippets/src/main/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutput.java new file mode 100644 index 000000000..d26437eef --- /dev/null +++ b/samples/snippets/src/main/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutput.java @@ -0,0 +1,131 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +// [START dialogflow_cx_v3_detect_intent_synthesize_tts_output] + +import com.google.api.gax.rpc.ApiException; +import com.google.cloud.dialogflow.cx.v3.AudioEncoding; +import com.google.cloud.dialogflow.cx.v3.AudioInput; +import com.google.cloud.dialogflow.cx.v3.DetectIntentRequest; +import com.google.cloud.dialogflow.cx.v3.DetectIntentResponse; +import com.google.cloud.dialogflow.cx.v3.InputAudioConfig; +import com.google.cloud.dialogflow.cx.v3.OutputAudioConfig; +import com.google.cloud.dialogflow.cx.v3.OutputAudioEncoding; +import com.google.cloud.dialogflow.cx.v3.QueryInput; +import com.google.cloud.dialogflow.cx.v3.SessionName; +import com.google.cloud.dialogflow.cx.v3.SessionsClient; +import com.google.cloud.dialogflow.cx.v3.SessionsSettings; +import com.google.cloud.dialogflow.cx.v3.SynthesizeSpeechConfig; +import com.google.protobuf.ByteString; +import java.io.FileInputStream; +import java.io.IOException; + +public class DetectIntentSynthesizeTextToSpeechOutput { + + // DialogFlow API Detect Intent sample with synthesize TTS output. + public static void main(String[] args) throws IOException, ApiException { + String projectId = "my-project-id"; + String locationId = "my-location-id"; + String agentId = "my-agent-id"; + String audioFileName = "my-audio-file-name"; + int sampleRateHertz = 16000; + String sessionId = "my-session-id"; + String languageCode = "my-language-code"; + + detectIntent( + projectId, locationId, agentId, audioFileName, sampleRateHertz, sessionId, languageCode); + } + + public static void detectIntent( + String projectId, + String locationId, + String agentId, + String audioFileName, + int sampleRateHertz, + String sessionId, + String languageCode) + throws IOException, ApiException { + + SessionsSettings.Builder sessionsSettingsBuilder = SessionsSettings.newBuilder(); + if (locationId.equals("global")) { + sessionsSettingsBuilder.setEndpoint("dialogflow.googleapis.com:443"); + } else { + sessionsSettingsBuilder.setEndpoint(locationId + "-dialogflow.googleapis.com:443"); + } + SessionsSettings sessionsSettings = sessionsSettingsBuilder.build(); + + // Instantiates a client by setting the session name. + // Format:`projects//locations//agents//sessions/` + try (SessionsClient sessionsClient = SessionsClient.create(sessionsSettings)) { + SessionName session = + SessionName.ofProjectLocationAgentSessionName(projectId, locationId, agentId, sessionId); + + // TODO : Uncomment if you want to print session path + // System.out.println("Session Path: " + session.toString()); + InputAudioConfig inputAudioConfig = + InputAudioConfig.newBuilder() + .setAudioEncoding(AudioEncoding.AUDIO_ENCODING_LINEAR_16) + .setSampleRateHertz(sampleRateHertz) + .build(); + + try (FileInputStream audioStream = new FileInputStream(audioFileName)) { + // 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 = audioStream.read(buffer); + AudioInput audioInput = + AudioInput.newBuilder() + .setAudio(ByteString.copyFrom(buffer, 0, bytes)) + .setConfig(inputAudioConfig) + .build(); + QueryInput queryInput = + QueryInput.newBuilder() + .setAudio(audioInput) + .setLanguageCode("en-US") // languageCode = "en-US" + .build(); + + SynthesizeSpeechConfig speechConfig = + SynthesizeSpeechConfig.newBuilder().setSpeakingRate(1.25).setPitch(10.0).build(); + + OutputAudioConfig outputAudioConfig = + OutputAudioConfig.newBuilder() + .setAudioEncoding(OutputAudioEncoding.OUTPUT_AUDIO_ENCODING_LINEAR_16) + .setSynthesizeSpeechConfig(speechConfig) + .build(); + + DetectIntentRequest request = + DetectIntentRequest.newBuilder() + .setSession(session.toString()) + .setQueryInput(queryInput) + .setOutputAudioConfig(outputAudioConfig) + .build(); + + // Performs the detect intent request. + DetectIntentResponse response = sessionsClient.detectIntent(request); + + // Display the output audio config retrieved from the response. + OutputAudioConfig audioConfigFromResponse = response.getOutputAudioConfig(); + + System.out.println("===================="); + System.out.format("Output Audio Config: %s \n", audioConfigFromResponse.toString()); + } + } + } +} +// [END dialogflow_cx_v3_detect_intent_synthesize_tts_output] diff --git a/samples/snippets/src/test/java/dialogflow/cx/DetectIntentAudioInputTest.java b/samples/snippets/src/test/java/dialogflow/cx/DetectIntentAudioInputTest.java new file mode 100644 index 000000000..ffe361914 --- /dev/null +++ b/samples/snippets/src/test/java/dialogflow/cx/DetectIntentAudioInputTest.java @@ -0,0 +1,72 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** Unit test for {@link DetectIntentIntentAudioInput}. */ +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectIntentAudioInputTest { + + private static String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static String LOCATION = "global"; + private static String AGENT_ID = + System.getenv() + .getOrDefault("DIALOGFLOW_CX_AGENT_ID_GLOBAL", "b8d0e85d-0741-4e6d-a66a-3671184b7b93"); + private static String AUDIO_FILE_NAME = "resources/book_a_room.wav"; + private static int SAMPLE_RATE_HERTZ = 16000; + private static String SESSION_ID = UUID.randomUUID().toString(); + private static String LANGUAGE_CODE = "en"; + + private ByteArrayOutputStream stdOut; + + @Before + public void setUp() throws IOException { + + stdOut = new ByteArrayOutputStream(); + System.setOut(new PrintStream(stdOut)); + } + + @After + public void tearDown() throws IOException { + stdOut = null; + System.setOut(null); + } + + @Test + public void testDetectIntentAudioInput() throws Exception { + + DetectIntentAudioInput.detectIntent( + PROJECT_ID, + LOCATION, + AGENT_ID, + AUDIO_FILE_NAME, + SAMPLE_RATE_HERTZ, + SESSION_ID, + LANGUAGE_CODE); + System.out.println(stdOut.toString()); + assertThat(stdOut.toString()).contains("Detected Intent:"); + } +} diff --git a/samples/snippets/src/test/java/dialogflow/cx/DetectIntentDisableWebhookTest.java b/samples/snippets/src/test/java/dialogflow/cx/DetectIntentDisableWebhookTest.java new file mode 100644 index 000000000..3564ed1cc --- /dev/null +++ b/samples/snippets/src/test/java/dialogflow/cx/DetectIntentDisableWebhookTest.java @@ -0,0 +1,74 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static com.google.common.truth.Truth.assertThat; + +import com.google.cloud.dialogflow.cx.v3.QueryResult; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** Unit test for {@link DetectIntentDisableWebhook}. */ +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectIntentDisableWebhookTest { + + private static String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static String LOCATION = "global"; + private static String AGENT_ID = + System.getenv() + .getOrDefault("DIALOGFLOW_CX_AGENT_ID_GLOBAL", "b8d0e85d-0741-4e6d-a66a-3671184b7b93"); + private static String SESSION_ID = UUID.randomUUID().toString(); + private static String LANGUAGE_CODE = "en-US"; + private static List TEXTS = Arrays.asList("hello", "unhappy"); + + private ByteArrayOutputStream stdOut; + + @Before + public void setUp() throws IOException { + + stdOut = new ByteArrayOutputStream(); + System.setOut(new PrintStream(stdOut)); + } + + @After + public void tearDown() throws IOException { + stdOut = null; + System.setOut(null); + } + + @Test + public void testDetectIntentDisableWebhook() throws Exception { + Map queryResults = + DetectIntentDisableWebhook.detectIntent( + PROJECT_ID, LOCATION, AGENT_ID, SESSION_ID, TEXTS, LANGUAGE_CODE); + + for (int i = 0; i < TEXTS.size(); i++) { + String text = TEXTS.get(i); + float score = queryResults.get(text).getSentimentAnalysisResult().getScore(); + System.out.println(stdOut.toString()); + assertThat(stdOut.toString()).contains("disable_webhook"); + } + } +} diff --git a/samples/snippets/src/test/java/dialogflow/cx/DetectIntentEventInputTest.java b/samples/snippets/src/test/java/dialogflow/cx/DetectIntentEventInputTest.java new file mode 100644 index 000000000..f63625194 --- /dev/null +++ b/samples/snippets/src/test/java/dialogflow/cx/DetectIntentEventInputTest.java @@ -0,0 +1,66 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** Unit test for {@link DetectIntentEventInput}. */ +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectIntentEventInputTest { + + private static String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static String LOCATION = "global"; + private static String AGENT_ID = + System.getenv() + .getOrDefault("DIALOGFLOW_CX_AGENT_ID_GLOBAL", "b8d0e85d-0741-4e6d-a66a-3671184b7b93"); + private static String EVENT = "sys.no-match-default"; + private static String SESSION_ID = UUID.randomUUID().toString(); + private static String LANGUAGE_CODE = "en-US"; + + private ByteArrayOutputStream stdOut; + + @Before + public void setUp() throws IOException { + + stdOut = new ByteArrayOutputStream(); + System.setOut(new PrintStream(stdOut)); + } + + @After + public void tearDown() throws IOException { + stdOut = null; + System.setOut(null); + } + + @Test + public void testDetectIntentEventInput() throws Exception { + String triggeringEvent = "sys.no-match-default"; + + DetectIntentEventInput.detectIntent( + PROJECT_ID, LOCATION, AGENT_ID, SESSION_ID, EVENT, LANGUAGE_CODE); + System.out.println(stdOut.toString()); + assertThat(stdOut.toString()).contains(triggeringEvent); + } +} diff --git a/samples/snippets/src/test/java/dialogflow/cx/DetectIntentIT.java b/samples/snippets/src/test/java/dialogflow/cx/DetectIntentIT.java index 2d85f6dc9..66d356a9b 100644 --- a/samples/snippets/src/test/java/dialogflow/cx/DetectIntentIT.java +++ b/samples/snippets/src/test/java/dialogflow/cx/DetectIntentIT.java @@ -28,7 +28,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** Integration (system) tests for {@link DetectIntent}. */ +/** Integration (system) tests for {@link DetectIntentText}. */ @RunWith(JUnit4.class) @SuppressWarnings("checkstyle:abbreviationaswordinname") public class DetectIntentIT { diff --git a/samples/snippets/src/test/java/dialogflow/cx/DetectIntentIntentInputTest.java b/samples/snippets/src/test/java/dialogflow/cx/DetectIntentIntentInputTest.java new file mode 100644 index 000000000..51dc3a560 --- /dev/null +++ b/samples/snippets/src/test/java/dialogflow/cx/DetectIntentIntentInputTest.java @@ -0,0 +1,75 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** Unit test for {@link DetectIntentIntentInput}. */ +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectIntentIntentInputTest { + + private static String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static String LOCATION = "global"; + private static String AGENT_ID = + System.getenv() + .getOrDefault("DIALOGFLOW_CX_AGENT_ID_GLOBAL", "b8d0e85d-0741-4e6d-a66a-3671184b7b93"); + private static String INTENT_ID = "00000000-0000-0000-0000-000000000000"; + private static String SESSION_ID = UUID.randomUUID().toString(); + private static String LANGUAGE_CODE = "en-US"; + private static String INTENT = + "projects/" + + PROJECT_ID + + "/locations/" + + LOCATION + + "/agents/" + + AGENT_ID + + "/intents/" + + INTENT_ID; + + private ByteArrayOutputStream stdOut; + + @Before + public void setUp() throws IOException { + + stdOut = new ByteArrayOutputStream(); + System.setOut(new PrintStream(stdOut)); + } + + @After + public void tearDown() throws IOException { + stdOut = null; + System.setOut(null); + } + + @Test + public void testDetectIntentIntentInput() throws Exception { + String intentName = "Default Welcome Intent"; + + DetectIntentIntentInput.detectIntent( + PROJECT_ID, LOCATION, AGENT_ID, SESSION_ID, INTENT, LANGUAGE_CODE); + System.out.println(stdOut.toString()); + assertThat(stdOut.toString()).contains(intentName); + } +} diff --git a/samples/snippets/src/test/java/dialogflow/cx/DetectIntentSentimentAnalysisTest.java b/samples/snippets/src/test/java/dialogflow/cx/DetectIntentSentimentAnalysisTest.java new file mode 100644 index 000000000..2194a9e70 --- /dev/null +++ b/samples/snippets/src/test/java/dialogflow/cx/DetectIntentSentimentAnalysisTest.java @@ -0,0 +1,56 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static org.junit.Assert.assertTrue; + +import com.google.cloud.dialogflow.cx.v3.QueryResult; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.Test; + +/** Unit test for {@link DetectIntentSentimentAnalysis}. */ +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectIntentSentimentAnalysisTest { + + private static String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static String LOCATION = "global"; + private static String AGENT_ID = + System.getenv() + .getOrDefault("DIALOGFLOW_CX_AGENT_ID_GLOBAL", "b8d0e85d-0741-4e6d-a66a-3671184b7b93"); + private static String SESSION_ID = UUID.randomUUID().toString(); + private static String LANGUAGE_CODE = "en-US"; + private static List TEXTS = Arrays.asList("hello", "unhappy"); + + @Test + public void testDetectIntentSentimentAnalysis() throws Exception { + int min = -1; + int max = 1; + + Map queryResults = + DetectIntentSentimentAnalysis.detectIntent( + PROJECT_ID, LOCATION, AGENT_ID, SESSION_ID, TEXTS, LANGUAGE_CODE); + + for (int i = 0; i < TEXTS.size(); i++) { + String text = TEXTS.get(i); + float score = queryResults.get(text).getSentimentAnalysisResult().getScore(); + assertTrue(min <= score && score <= max); + } + } +} diff --git a/samples/snippets/src/test/java/dialogflow/cx/DetectIntentStreamingPartialResponseTest.java b/samples/snippets/src/test/java/dialogflow/cx/DetectIntentStreamingPartialResponseTest.java new file mode 100644 index 000000000..7f6f24a2e --- /dev/null +++ b/samples/snippets/src/test/java/dialogflow/cx/DetectIntentStreamingPartialResponseTest.java @@ -0,0 +1,68 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Integration (system) tests for {@link DetectIntentStream}. */ +@RunWith(JUnit4.class) +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectIntentStreamingPartialResponseTest { + + private static String AUDIO_FILE_PATH = "resources/book_a_room.wav"; + private static String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static String LOCATION = "global"; + private static String AGENT_ID = + System.getenv() + .getOrDefault("DIALOGFLOW_CX_AGENT_ID_GLOBAL", "b8d0e85d-0741-4e6d-a66a-3671184b7b93"); + private static String SESSION_ID = UUID.randomUUID().toString(); + private ByteArrayOutputStream bout; + private PrintStream original; + + @Before + public void setUp() { + original = System.out; + bout = new ByteArrayOutputStream(); + System.setOut(new PrintStream(bout)); + } + + @After + public void tearDown() { + System.setOut(original); + bout.reset(); + } + + @Test + public void testDetectIntentStreamingPartialResponse() throws IOException { + DetectIntentStreamingPartialResponse.detectIntentStreamingPartialResponse( + PROJECT_ID, LOCATION, AGENT_ID, SESSION_ID, AUDIO_FILE_PATH); + + String output = bout.toString(); + + assertThat(output).contains("enable_partial_response"); + } +} diff --git a/samples/snippets/src/test/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutputTest.java b/samples/snippets/src/test/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutputTest.java new file mode 100644 index 000000000..20d84e37a --- /dev/null +++ b/samples/snippets/src/test/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutputTest.java @@ -0,0 +1,72 @@ +/* + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dialogflow.cx; + +import static com.google.common.truth.Truth.assertThat; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** Unit test for {@link DetectIntentSynthesizeTtSOutput}. */ +@SuppressWarnings("checkstyle:abbreviationaswordinname") +public class DetectIntentSynthesizeTextToSpeechOutputTest { + + private static String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); + private static String LOCATION = "global"; + private static String AGENT_ID = + System.getenv() + .getOrDefault("DIALOGFLOW_CX_AGENT_ID_GLOBAL", "b8d0e85d-0741-4e6d-a66a-3671184b7b93"); + private static String AUDIO_FILE_NAME = "resources/book_a_room.wav"; + private static int SAMPLE_RATE_HERTZ = 16000; + private static String SESSION_ID = UUID.randomUUID().toString(); + private static String LANGUAGE_CODE = "en"; + + private ByteArrayOutputStream stdOut; + + @Before + public void setUp() throws IOException { + + stdOut = new ByteArrayOutputStream(); + System.setOut(new PrintStream(stdOut)); + } + + @After + public void tearDown() throws IOException { + stdOut = null; + System.setOut(null); + } + + @Test + public void testDetectIntentSynthesizeTextToSpeechOutput() throws Exception { + + DetectIntentSynthesizeTextToSpeechOutput.detectIntent( + PROJECT_ID, + LOCATION, + AGENT_ID, + AUDIO_FILE_NAME, + SAMPLE_RATE_HERTZ, + SESSION_ID, + LANGUAGE_CODE); + System.out.println(stdOut.toString()); + assertThat(stdOut.toString()).contains("speaking_rate"); + } +}