From 6bb79a4214913db781d57d85730faed9d56c3b46 Mon Sep 17 00:00:00 2001 From: aribray <45905583+aribray@users.noreply.github.com> Date: Tue, 12 Jul 2022 07:50:28 -0500 Subject: [PATCH] docs: add DetectIntent samples (#500) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * docs:add configure webhook to set form parameter as optional or required sample and test Change-Id: I75bed489bd8abefca60263acb266501810c0e856 * docs: fix checkstyle Change-Id: I18be2a5c1d46ac9838cf4a15ab87dcf331ee26ee * fix checkstyle Change-Id: Ia85899f678ef1382718c2443a682770417340af2 * fix checkstyle Change-Id: I4dd56107a3197027f287980fa87a15e962154783 * fix multiline string Change-Id: I8dcdb0dcaad486a2fb69e0737df99bda49b28839 * fix checkstyle violations Change-Id: I5f4521b3e50660f30f9f73da3d939da213084d28 * fix checkstyle violations Change-Id: I39dedfba1b62be5cb4580a42dde270146f3b6f97 * remove unused variable Change-Id: Ic54ae0d1f091079661f3fa67097cdcd2e888dc90 * fix checkstyle violations Change-Id: Ifd303b7395844240dca0b29cde9b791112fcabe5 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * fix checkstyle violations Change-Id: I59e45da9f9e57b327a527f1405816ac1275fe1c8 * fix checkstyle violations Change-Id: I70ff4118cc8b3111a3ed55a2fae32258d3f6819c * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * remove unnecessary samples Change-Id: I395dd5abc9a48733126ab0ecdc2a974fbf9eb471 * add webhook configure session parameter sample and test Change-Id: Ia599ab7f4d432477d9952b4e12c709845f1ad97b * add webhook validate form parameter sample and test Change-Id: I8cdf93fd9e21161757d198b1338c5ab77bb3a236 * fix checkstyle violations Change-Id: I90f1f626588fd59c116d119348054c914945cd1d * fix checkstyle violations Change-Id: I5ff686ab2ffc94b358bdf87b8dfc3d00f5e45657 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * add detectintent with intent input sample and test Change-Id: I4a2bef88da7ed04d343da63544563130182e6aaf * docs: add detect intent samples and tests Change-Id: I8e6a26441a79b1ed44def4877c822040cb143e33 * add detectintent with audio input sample and test Change-Id: I741c73d3f14bfe5f9b4ff6ec55d43f2687ac51dd * fix checkstyle violations Change-Id: I216ade5c8bca9e85850b6ab84b2a70eab0d4fd53 * add detectintent with event input sample and test Change-Id: Ie0846bd780f20cd1a8406f8a1278ccf45824b646 * add detectintent with sentiment analysis sample and test Change-Id: I7d8c855bd0e1a0bc19288abd968a4602a909b3df * add detectintent with webhook disabled sample and test Change-Id: Idf6c2005b7a1970e3c8227080bb91a1d408474b0 * add detectintentstreamingpartialresponse sample and test Change-Id: Id1a0017757da3eee5e0556f0c7ba8954f9907ca3 * add detectintentsynthesizettsoutput sample and test Change-Id: I389daae0a1b5b7fb858dd8c81ceba99475ce3ca3 * fix checkstyle violations Change-Id: Ic247c4b7d50df1a6a5eb74fe0899defc63478b0e * rename detectintent with text input sample and test Change-Id: Ic9b54f74723f716cd688e780675ce878487251aa * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * change the name back Change-Id: I153f94d5c9c1c53d96365fb05c02625c2dc5f745 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * fix comments Change-Id: I02c0ce2e61ab74026d04103774de02fc2bb0ae6b * remove old webhook samples Change-Id: I6d2872aa1b3c77c0f08cd62a508d351066490f25 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * v3beta1 to v3 Change-Id: I3850ed76ea36def3cf215c7261fa1bffba274d6e * v3beta1 to v3 Change-Id: Ie0539f4a6ca8d5c9cb21ac528e09ce8f992a0486 * add flag to kokoro build script Change-Id: I5c3862c61931b28772e408b5e2d68e7cc5af72d2 * fix test assertion Change-Id: I2bffb8d973362d032265f7bd7b89aa88555de819 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * remove flag Change-Id: Ie3c449bdb635180653237745a8cc282afb088a57 * hardcode parameters Change-Id: Iac48159892b0b6a34f31b013d446dfd66e62b8a7 * move sessionID comments Change-Id: I8e3fcea6a24739cb7a1e49d7572688e22d4d0147 * add main and hardcode variables Change-Id: I29f4cb587b10f46576aa36a56cde8c8fcb6e1acb * add session path comments and path format Change-Id: I327b7e90d8562c9698bc1fc4324ec249c6326436 * checkstyle Change-Id: If9937d41cefcff2fa0480524d036aecf5a1fda40 * checkstyle Change-Id: I9980a07e9c2ca377f669f0b80bbf16a42033d634 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * fix list construction Change-Id: I5115e749e47427c50e2ed0ad494525dc6f9be66a * import ArrayList Change-Id: Ibe5abeee5b6b003fc8c77eb53eb432a340629255 Co-authored-by: Owl Bot --- java-dialogflow-cx/README.md | 7 + .../dialogflow/cx/DetectIntentAudioInput.java | 128 +++++++++++++++ .../cx/DetectIntentDisableWebhook.java | 120 ++++++++++++++ .../dialogflow/cx/DetectIntentEventInput.java | 98 +++++++++++ .../cx/DetectIntentIntentInput.java | 100 ++++++++++++ .../cx/DetectIntentSentimentAnalysis.java | 117 +++++++++++++ .../dialogflow/cx/DetectIntentStream.java | 7 +- .../DetectIntentStreamingPartialResponse.java | 154 ++++++++++++++++++ ...ectIntentSynthesizeTextToSpeechOutput.java | 131 +++++++++++++++ .../cx/DetectIntentAudioInputTest.java | 72 ++++++++ .../cx/DetectIntentDisableWebhookTest.java | 74 +++++++++ .../cx/DetectIntentEventInputTest.java | 66 ++++++++ .../java/dialogflow/cx/DetectIntentIT.java | 2 +- .../cx/DetectIntentIntentInputTest.java | 75 +++++++++ .../cx/DetectIntentSentimentAnalysisTest.java | 56 +++++++ ...ectIntentStreamingPartialResponseTest.java | 68 ++++++++ ...ntentSynthesizeTextToSpeechOutputTest.java | 72 ++++++++ 17 files changed, 1342 insertions(+), 5 deletions(-) create mode 100644 java-dialogflow-cx/samples/snippets/src/main/java/dialogflow/cx/DetectIntentAudioInput.java create mode 100644 java-dialogflow-cx/samples/snippets/src/main/java/dialogflow/cx/DetectIntentDisableWebhook.java create mode 100644 java-dialogflow-cx/samples/snippets/src/main/java/dialogflow/cx/DetectIntentEventInput.java create mode 100644 java-dialogflow-cx/samples/snippets/src/main/java/dialogflow/cx/DetectIntentIntentInput.java create mode 100644 java-dialogflow-cx/samples/snippets/src/main/java/dialogflow/cx/DetectIntentSentimentAnalysis.java create mode 100644 java-dialogflow-cx/samples/snippets/src/main/java/dialogflow/cx/DetectIntentStreamingPartialResponse.java create mode 100644 java-dialogflow-cx/samples/snippets/src/main/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutput.java create mode 100644 java-dialogflow-cx/samples/snippets/src/test/java/dialogflow/cx/DetectIntentAudioInputTest.java create mode 100644 java-dialogflow-cx/samples/snippets/src/test/java/dialogflow/cx/DetectIntentDisableWebhookTest.java create mode 100644 java-dialogflow-cx/samples/snippets/src/test/java/dialogflow/cx/DetectIntentEventInputTest.java create mode 100644 java-dialogflow-cx/samples/snippets/src/test/java/dialogflow/cx/DetectIntentIntentInputTest.java create mode 100644 java-dialogflow-cx/samples/snippets/src/test/java/dialogflow/cx/DetectIntentSentimentAnalysisTest.java create mode 100644 java-dialogflow-cx/samples/snippets/src/test/java/dialogflow/cx/DetectIntentStreamingPartialResponseTest.java create mode 100644 java-dialogflow-cx/samples/snippets/src/test/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutputTest.java diff --git a/java-dialogflow-cx/README.md b/java-dialogflow-cx/README.md index e6f44871fab0..24a1bcb7f892 100644 --- a/java-dialogflow-cx/README.md +++ b/java-dialogflow-cx/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/java-dialogflow-cx/samples/snippets/src/main/java/dialogflow/cx/DetectIntentAudioInput.java b/java-dialogflow-cx/samples/snippets/src/main/java/dialogflow/cx/DetectIntentAudioInput.java new file mode 100644 index 000000000000..e864f381a034 --- /dev/null +++ b/java-dialogflow-cx/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/java-dialogflow-cx/samples/snippets/src/main/java/dialogflow/cx/DetectIntentDisableWebhook.java b/java-dialogflow-cx/samples/snippets/src/main/java/dialogflow/cx/DetectIntentDisableWebhook.java new file mode 100644 index 000000000000..c0cf470fefa9 --- /dev/null +++ b/java-dialogflow-cx/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/java-dialogflow-cx/samples/snippets/src/main/java/dialogflow/cx/DetectIntentEventInput.java b/java-dialogflow-cx/samples/snippets/src/main/java/dialogflow/cx/DetectIntentEventInput.java new file mode 100644 index 000000000000..5f92199e9b96 --- /dev/null +++ b/java-dialogflow-cx/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/java-dialogflow-cx/samples/snippets/src/main/java/dialogflow/cx/DetectIntentIntentInput.java b/java-dialogflow-cx/samples/snippets/src/main/java/dialogflow/cx/DetectIntentIntentInput.java new file mode 100644 index 000000000000..45af3c56795f --- /dev/null +++ b/java-dialogflow-cx/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/java-dialogflow-cx/samples/snippets/src/main/java/dialogflow/cx/DetectIntentSentimentAnalysis.java b/java-dialogflow-cx/samples/snippets/src/main/java/dialogflow/cx/DetectIntentSentimentAnalysis.java new file mode 100644 index 000000000000..318242c4fb5d --- /dev/null +++ b/java-dialogflow-cx/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/java-dialogflow-cx/samples/snippets/src/main/java/dialogflow/cx/DetectIntentStream.java b/java-dialogflow-cx/samples/snippets/src/main/java/dialogflow/cx/DetectIntentStream.java index b09609aea458..96b1799a5bd4 100644 --- a/java-dialogflow-cx/samples/snippets/src/main/java/dialogflow/cx/DetectIntentStream.java +++ b/java-dialogflow-cx/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/java-dialogflow-cx/samples/snippets/src/main/java/dialogflow/cx/DetectIntentStreamingPartialResponse.java b/java-dialogflow-cx/samples/snippets/src/main/java/dialogflow/cx/DetectIntentStreamingPartialResponse.java new file mode 100644 index 000000000000..81cb534e2856 --- /dev/null +++ b/java-dialogflow-cx/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/java-dialogflow-cx/samples/snippets/src/main/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutput.java b/java-dialogflow-cx/samples/snippets/src/main/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutput.java new file mode 100644 index 000000000000..d26437eefff0 --- /dev/null +++ b/java-dialogflow-cx/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/java-dialogflow-cx/samples/snippets/src/test/java/dialogflow/cx/DetectIntentAudioInputTest.java b/java-dialogflow-cx/samples/snippets/src/test/java/dialogflow/cx/DetectIntentAudioInputTest.java new file mode 100644 index 000000000000..ffe3619149dc --- /dev/null +++ b/java-dialogflow-cx/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/java-dialogflow-cx/samples/snippets/src/test/java/dialogflow/cx/DetectIntentDisableWebhookTest.java b/java-dialogflow-cx/samples/snippets/src/test/java/dialogflow/cx/DetectIntentDisableWebhookTest.java new file mode 100644 index 000000000000..3564ed1cc2fc --- /dev/null +++ b/java-dialogflow-cx/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/java-dialogflow-cx/samples/snippets/src/test/java/dialogflow/cx/DetectIntentEventInputTest.java b/java-dialogflow-cx/samples/snippets/src/test/java/dialogflow/cx/DetectIntentEventInputTest.java new file mode 100644 index 000000000000..f6362519411e --- /dev/null +++ b/java-dialogflow-cx/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/java-dialogflow-cx/samples/snippets/src/test/java/dialogflow/cx/DetectIntentIT.java b/java-dialogflow-cx/samples/snippets/src/test/java/dialogflow/cx/DetectIntentIT.java index 2d85f6dc9733..66d356a9b2df 100644 --- a/java-dialogflow-cx/samples/snippets/src/test/java/dialogflow/cx/DetectIntentIT.java +++ b/java-dialogflow-cx/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/java-dialogflow-cx/samples/snippets/src/test/java/dialogflow/cx/DetectIntentIntentInputTest.java b/java-dialogflow-cx/samples/snippets/src/test/java/dialogflow/cx/DetectIntentIntentInputTest.java new file mode 100644 index 000000000000..51dc3a560f8b --- /dev/null +++ b/java-dialogflow-cx/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/java-dialogflow-cx/samples/snippets/src/test/java/dialogflow/cx/DetectIntentSentimentAnalysisTest.java b/java-dialogflow-cx/samples/snippets/src/test/java/dialogflow/cx/DetectIntentSentimentAnalysisTest.java new file mode 100644 index 000000000000..2194a9e70b81 --- /dev/null +++ b/java-dialogflow-cx/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/java-dialogflow-cx/samples/snippets/src/test/java/dialogflow/cx/DetectIntentStreamingPartialResponseTest.java b/java-dialogflow-cx/samples/snippets/src/test/java/dialogflow/cx/DetectIntentStreamingPartialResponseTest.java new file mode 100644 index 000000000000..7f6f24a2ee43 --- /dev/null +++ b/java-dialogflow-cx/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/java-dialogflow-cx/samples/snippets/src/test/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutputTest.java b/java-dialogflow-cx/samples/snippets/src/test/java/dialogflow/cx/DetectIntentSynthesizeTextToSpeechOutputTest.java new file mode 100644 index 000000000000..20d84e37a1eb --- /dev/null +++ b/java-dialogflow-cx/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"); + } +}