8000 samples: refactor dialogflow for 2.1.0 (#3283) · ssmall/java-docs-samples@90d35c3 · GitHub
[go: up one dir, main page]

Skip to content

Commit 90d35c3

Browse files
authored
samples: refactor dialogflow for 2.1.0 (GoogleCloudPlatform#3283)
* samples: refactor dialogflow for 2.1.0 * formatted code * made requested changes * fixed compilation error * fixed lint on tests * lint issue
1 parent 5c64a7a commit 90d35c3

17 files changed

+199
-259
lines changed

dialogflow/cloud-client/pom.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
<dependency>
4040
<groupId>com.google.cloud</groupId>
4141
<artifactId>google-cloud-dialogflow</artifactId>
42-
<version>1.0.0</version>
42+
<version>2.1.0</version>
4343
</dependency>
4444

4545
<!-- Test dependencies -->

dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentAudio.java

Lines changed: 22 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,9 @@
1616

1717
package com.example.dialogflow;
1818

19-
// Imports the Google Cloud client library
19+
// [START dialogflow_detect_intent_audio]
2020

21+
import com.google.api.gax.rpc.ApiException;
2122
import com.google.cloud.dialogflow.v2.AudioEncoding;
2223
import com.google.cloud.dialogflow.v2.DetectIntentRequest;
2324
import com.google.cloud.dialogflow.v2.DetectIntentResponse;
@@ -27,33 +28,16 @@
2728
import com.google.cloud.dialogflow.v2.SessionName;
2829
import com.google.cloud.dialogflow.v2.SessionsClient;
2930
import com.google.protobuf.ByteString;
31+
import java.io.IOException;
3032
import java.nio.file.Files;
3133
import java.nio.file.Paths;
3234

33-
34-
/**
35-
* DialogFlow API Detect Intent sample with audio files.
36-
*/
3735
public class DetectIntentAudio {
38-
// [START dialogflow_detect_intent_audio]
3936

40-
/**
41-
* Returns the result of detect intent with an audio file as input.
42-
*
43-
* Using the same `session_id` between requests allows continuation of the conversation.
44-
*
45-
* @param projectId Project/Agent Id.
46-
* @param audioFilePath Path to the audio file.
47-
* @param sessionId Identifier of the DetectIntent session.
48-
* @param languageCode Language code of the query.
49-
* @return QueryResult for the request.
50-
*/
37+
// DialogFlow API Detect Intent sample with audio files.
5138
public static QueryResult detectIntentAudio(
52-
String projectId,
53-
String audioFilePath,
54-
String sessionId,
55-
String languageCode)
56-
throws Exception {
39+
String projectId, String audioFilePath, String sessionId, String languageCode)
40+
throws IOException, ApiException {
5741
// Instantiates a client
5842
try (SessionsClient sessionsClient = SessionsClient.create()) {
5943
// Set the session name using the sessionId (UUID) and projectID (my-project-id)
@@ -66,11 +50,13 @@ public static QueryResult detectIntentAudio(
6650
int sampleRateHertz = 16000;
6751

6852
// Instructs the speech recognizer how to process the audio content.
69-
InputAudioConfig inputAudioConfig = InputAudioConfig.newBuilder()
70-
.setAudioEncoding(audioEncoding) // audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16
71-
.setLanguageCode(languageCode) // languageCode = "en-US"
72-
.setSampleRateHertz(sampleRateHertz) // sampleRateHertz = 16000
73-
.build();
53+
InputAudioConfig inputAudioConfig =
54+
InputAudioConfig.newBuilder()
55+
.setAudioEncoding(
56+
audioEncoding) // audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16
57+
.setLanguageCode(languageCode) // languageCode = "en-US"
58+
.setSampleRateHertz(sampleRateHertz) // sampleRateHertz = 16000
59+
.build();
7460

7561
// Build the query with the InputAudioConfig
7662
QueryInput queryInput = QueryInput.newBuilder().setAudioConfig(inputAudioConfig).build();
@@ -79,11 +65,12 @@ public static QueryResult detectIntentAudio(
7965
byte[] inputAudio = Files.readAllBytes(Paths.get(audioFilePath));
8066

8167
// Build the DetectIntentRequest
82-
DetectIntentRequest request = DetectIntentRequest.newBuilder()
83-
.setSession(session.toString())
84-
.setQueryInput(queryInput)
85-
.setInputAudio(ByteString.copyFrom(inputAudio))
86-
.build();
68+
DetectIntentRequest request =
69+
DetectIntentRequest.newBuilder()
70+
.setSession(session.toString())
71+
.setQueryInput(queryInput)
72+
.setInputAudio(ByteString.copyFrom(inputAudio))
73+
.build();
8774

8875
// Performs the detect intent request
8976
DetectIntentResponse response = sessionsClient.detectIntent(request);
@@ -92,12 +79,13 @@ public static QueryResult detectIntentAudio(
9279
QueryResult queryResult = response.getQueryResult();
9380
System.out.println("====================");
9481
System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
95-
System.out.format("Detected Intent: %s (confidence: %f)\n",
82+
System.out.format(
83+
"Detected Intent: %s (confidence: %f)\n",
9684
queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
9785
System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());
9886

9987
return queryResult;
10088
}
10189
}
102-
// [END dialogflow_detect_intent_audio]
10390
}
91+
// [END dialogflow_detect_intent_audio]

dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentKnowledge.java

Lines changed: 8 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,9 @@
1616

1717
package com.example.dialogflow;
1818

19-
// Imports the Google Cloud client library
19+
// [START dialogflow_detect_intent_knowledge]
2020

21+
import com.google.api.gax.rpc.ApiException;
2122
import com.google.cloud.dialogflow.v2beta1.DetectIntentRequest;
2223
import com.google.cloud.dialogflow.v2beta1.DetectIntentResponse;
2324
import com.google.cloud.dialogflow.v2beta1.KnowledgeAnswers;
@@ -29,33 +30,20 @@
2930
import com.google.cloud.dialogflow.v2beta1.SessionsClient;
3031
import com.google.cloud.dialogflow.v2beta1.TextInput;
3132
import com.google.common.collect.Maps;
33+
import java.io.IOException;
3234
import java.util.List;
3335
import java.util.Map;
3436

35-
/**
36-
* DialogFlow API Detect Intent sample with querying knowledge connector.
37-
*/
3837
public class DetectIntentKnowledge {
39-
// [START dialogflow_detect_intent_knowledge]
4038

41-
/**
42-
* Returns the result of detect intent with text as input.
43-
*
44-
* <p>Using the same `session_id` between requests allows continuation of the conversation.
45-
*
46-
* @param projectId Project/Agent Id.
47-
* @param knowledgeBaseName Knowledge base Id.
48-
* @param sessionId Identifier of the DetectIntent session.
49-
* @param languageCode Language code of the query.
50-
* @param texts The texts to be processed.
51-
* @return The KnowledgeAnswers found for each text.
52-
*/
39+
// DialogFlow API Detect Intent sample with querying knowledge connector.
5340
public static Map<String, KnowledgeAnswers> detectIntentKnowledge(
5441
String projectId,
5542
String knowledgeBaseName,
5643
String sessionId,
5744
String languageCode,
58-
List<String> texts) throws Exception {
45+
List<String> texts)
46+
throws IOException, ApiException {
5947
// Instantiates a client
6048
Map<String, KnowledgeAnswers> allKnowledgeAnswers = Maps.newHashMap();
6149
try (SessionsClient sessionsClient = SessionsClient.create()) {
@@ -72,9 +60,7 @@ public static Map<String, KnowledgeAnswers> detectIntentKnowledge(
7260
QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();
7361

7462
QueryParameters queryParameters =
75-
QueryParameters.newBuilder()
76-
.addKnowledgeBaseNames(knowledgeBaseName)
77-
.build();
63+
QueryParameters.newBuilder().addKnowledgeBaseNames(knowledgeBaseName).build();
7864

7965
DetectIntentRequest detectIntentRequest =
8066
DetectIntentRequest.newBuilder()
@@ -107,5 +93,5 @@ public static Map<String, KnowledgeAnswers> detectIntentKnowledge(
10793
}
10894
return allKnowledgeAnswers;
10995
}
110-
// [END dialogflow_detect_intent_knowledge]
11196
}
97+
// [END dialogflow_detect_intent_knowledge]

dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentStream.java

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@
1717
package com.example.dialogflow;
1818

1919
// [START dialogflow_detect_intent_streaming]
20-
// Imports the Google Cloud client library
20+
21+
import com.google.api.gax.rpc.ApiException;
2122
import com.google.api.gax.rpc.BidiStream;
2223
import com.google.cloud.dialogflow.v2.AudioEncoding;
2324
import com.google.cloud.dialogflow.v2.InputAudioConfig;
@@ -31,12 +32,11 @@
3132
import java.io.FileInputStream;
3233
import java.io.IOException;
3334

34-
/**
35-
* DialogFlow API Detect Intent sample with audio files processes as an audio stream.
36-
*/
3735
class DetectIntentStream {
3836

39-
static void detectIntentStream(String projectId, String audioFilePath, String sessionId) {
37+
// DialogFlow API Detect Intent sample with audio files processes as an audio stream.
38+
static void detectIntentStream(String projectId, String audioFilePath, String sessionId)
39+
throws IOException, ApiException {
4040
// String projectId = "YOUR_PROJECT_ID";
4141
// String audioFilePath = "path_to_your_audio_file";
4242
// Using the same `sessionId` between requests allows continuation of the conversation.
@@ -50,11 +50,12 @@ static void detectIntentStream(String projectId, String audioFilePath, String se
5050
// Instructs the speech recognizer how to process the audio content.
5151
// Note: hard coding audioEncoding and sampleRateHertz for simplicity.
5252
// Audio encoding of the audio content sent in the query request.
53-
InputAudioConfig inputAudioConfig = InputAudioConfig.newBuilder()
54-
.setAudioEncoding(AudioEncoding.AUDIO_ENCODING_LINEAR_16)
55-
.setLanguageCode("en-US") // languageCode = "en-US"
56-
.setSampleRateHertz(16000) // sampleRateHertz = 16000
57-
.build();
53+
InputAudioConfig inputAudioConfig =
54+
InputAudioConfig.newBuilder()
55+
.setAudioEncoding(AudioEncoding.AUDIO_ENCODING_LINEAR_16)
56+
.setLanguageCode("en-US") // languageCode = "en-US"
57+
.setSampleRateHertz(16000) // sampleRateHertz = 16000
58+
.build();
5859

5960
// Build the query with the InputAudioConfig
6061
QueryInput queryInput = QueryInput.newBuilder().setAudioConfig(inputAudioConfig).build();
@@ -64,10 +65,11 @@ static void detectIntentStream(String projectId, String audioFilePath, String se
6465
sessionsClient.streamingDetectIntentCallable().call();
6566

6667
// The first request must **only** contain the audio configuration:
67-
bidiStream.send(StreamingDetectIntentRequest.newBuilder()
68-
.setSession(session.toString())
69-
.setQueryInput(queryInput)
70-
.build());
68+
bidiStream.send(
69+
StreamingDetectIntentRequest.newBuilder()
70+
.setSession(session.toString())
71+
.setQueryInput(queryInput)
72+
.build());
7173

7274
try (FileInputStream audioStream = new FileInputStream(audioFilePath)) {
7375
// Subsequent requests must **only** contain the audio data.
@@ -91,13 +93,11 @@ static void detectIntentStream(String projectId, String audioFilePath, String se
9193
System.out.println("====================");
9294
System.out.format("Intent Display Name: %s\n", queryResult.getIntent().getDisplayName());
9395
System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
94-
System.out.format("Detected Intent: %s (confidence: %f)\n",
96+
System.out.format(
97+
"Detected Intent: %s (confidence: %f)\n",
9598
queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
9699
System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());
97-
98100
}
99-
} catch (IOException e) {
100-
e.printStackTrace();
101101
}
102102
}
103103
}

dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentTexts.java

Lines changed: 9 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -16,40 +16,26 @@
1616

1717
package com.example.dialogflow;
1818

19-
// Imports the Google Cloud client library
19+
// [START dialogflow_detect_intent_text]
2020

21+
import com.google.api.gax.rpc.ApiException;
2122
import com.google.cloud.dialogflow.v2.DetectIntentResponse;
2223
import com.google.cloud.dialogflow.v2.QueryInput;
2324
import com.google.cloud.dialogflow.v2.QueryResult;
2425
import com.google.cloud.dialogflow.v2.SessionName;
2526
import com.google.cloud.dialogflow.v2.SessionsClient;
2627
import com.google.cloud.dialogflow.v2.TextInput;
2728
import com.google.common.collect.Maps;
29+
import java.io.IOException;
2830
import java.util.List;
2931
import java.util.Map;
3032

31-
/**
32-
* DialogFlow API Detect Intent sample with text inputs.
33-
*/
3433
public class DetectIntentTexts {
35-
// [START dialogflow_detect_intent_text]
3634

37-
/**
38-
* Returns the result of detect intent with texts as inputs.
39-
*
40-
* Using the same `session_id` between requests allows continuation of the conversation.
41-
*
42-
* @param projectId Project/Agent Id.
43-
* @param texts The text intents to be detected based on what a user says.
44-
* @param sessionId Identifier of the DetectIntent session.
45-
* @param languageCode Language code of the query.
46-
* @return The QueryResult for each input text.
47-
*/
35+
// DialogFlow API Detect Intent sample with text inputs.
4836
public static Map<String, QueryResult> detectIntentTexts(
49-
String projectId,
50-
List<String> texts,
51-
String sessionId,
52-
String languageCode) throws Exception {
37+
String projectId, List<String> texts, String sessionId, String languageCode)
38+
throws IOException, ApiException {
5339
Map<String, QueryResult> queryResults = Maps.newHashMap();
5440
// Instantiates a client
5541
try (SessionsClient sessionsClient = SessionsClient.create()) {
@@ -74,7 +60,8 @@ public static Map<String, QueryResult> detectIntentTexts(
7460

7561
System.out.println("====================");
7662
System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
77-
System.out.format("Detected Intent: %s (confidence: %f)\n",
63+
System.out.format(
64+
"Detected Intent: %s (confidence: %f)\n",
7865
queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
7966
System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());
8067

@@ -83,5 +70,5 @@ public static Map<String, QueryResult> detectIntentTexts(
8370
}
8471
return queryResults;
8572
}
86-
// [END dialogflow_detect_intent_text]
8773
}
74+
// [END dialogflow_detect_intent_text]

dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentWithSentimentAnalysis.java

Lines changed: 8 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@
1616

1717
package com.example.dialogflow;
1818

19+
// [START dialogflow_detect_intent_with_sentiment_analysis]
20+
21+
import com.google.api.gax.rpc.ApiException;
1922
import com.google.cloud.dialogflow.v2.DetectIntentRequest;
2023
import com.google.cloud.dialogflow.v2.DetectIntentResponse;
2124
import com.google.cloud.dialogflow.v2.QueryInput;
@@ -26,28 +29,15 @@
2629
import com.google.cloud.dialogflow.v2.SessionsClient;
2730
import com.google.cloud.dialogflow.v2.TextInput;
2831
import com.google.common.collect.Maps;
32+
import java.io.IOException;
2933
import java.util.List;
3034
import java.util.Map;
3135

3236
public class DetectIntentWithSentimentAnalysis {
33-
// [START dialogflow_detect_intent_with_sentiment_analysis]
3437

35-
/**
36-
* Returns the result of detect intent with texts as inputs.
37-
*
38-
* <p>Using the same `session_id` between requests allows continuation of the conversation.
39-
*
40-
* @param projectId Project/Agent Id.
41-
* @param texts The text intents to be detected based on what a user says.
42-
* @param sessionId Identifier of the DetectIntent session.
43-
* @param languageCode Language code of the query.
44-
* @return The QueryResult for each text in query.
45-
*/
46-
public static Map<String, QueryResult> detectIntentSentimentAnalysis(
47-
String projectId,
48-
List<String> texts,
49-
String sessionId,
50-
String languageCode) throws Exception {
38+
public static Map<String, QueryResult> detectIntentSentimentAnalysis(
39+
String projectId, List<String> texts, String sessionId, String languageCode)
40+
throws IOException, ApiException {
5141
Map<String, QueryResult> queryResults = Maps.newHashMap();
5242
// Instantiates a client
5343
try (SessionsClient sessionsClient = SessionsClient.create()) {
@@ -100,5 +90,5 @@ public static Map<String, QueryResult> detectIntentSentimentAnalysis(
10090
}
10191
return queryResults;
10292
}
103-
// [END dialogflow_detect_intent_with_sentiment_analysis]
10493
}
94+
// [END dialogflow_detect_intent_with_sentiment_analysis]

0 commit comments

Comments
 (0)
0