Skip to content

Commit 40893da

Browse files
nnegreyShabirmean
authored andcommitted
samples: Dialogflow to gcp (#1181)
* Clean copy of Dialogflow samples, need to update pom.xml to work with java-docs-samples repo * Update files to match GCP Repo's style guides * Update argument parsing * Update Inc. to LLC * Update pom.xml * Add missing region tags for sample tracker
1 parent 1449ee1 commit 40893da

32 files changed

+3310
-0
lines changed
53.8 KB
Binary file not shown.
Binary file not shown.
30.3 KB
Binary file not shown.
35.3 KB
Binary file not shown.
33.1 KB
Binary file not shown.
22.5 KB
Binary file not shown.
30.4 KB
Binary file not shown.
Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
/*
2+
* Copyright 2018 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.dialogflow;
18+
19+
// Imports the Google Cloud client library
20+
import com.google.cloud.dialogflow.v2.Context;
21+
import com.google.cloud.dialogflow.v2.ContextName;
22+
import com.google.cloud.dialogflow.v2.ContextsClient;
23+
import com.google.cloud.dialogflow.v2.SessionName;
24+
import com.google.protobuf.Value;
25+
26+
import java.util.Map.Entry;
27+
import net.sourceforge.argparse4j.ArgumentParsers;
28+
import net.sourceforge.argparse4j.inf.ArgumentParser;
29+
import net.sourceforge.argparse4j.inf.ArgumentParserException;
30+
import net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup;
31+
import net.sourceforge.argparse4j.inf.Namespace;
32+
import net.sourceforge.argparse4j.inf.Subparser;
33+
import net.sourceforge.argparse4j.inf.Subparsers;
34+
35+
36+
/**
37+
* DialogFlow API Context sample.
38+
*/
39+
public class ContextManagement {
40+
41+
// [START dialogflow_list_contexts]
42+
/**
43+
* Lists contexts
44+
* @param sessionId Identifier of the DetectIntent session.
45+
* @param projectId Project/Agent Id.
46+
*/
47+
public static void listContexts(String sessionId, String projectId) throws Exception {
48+
// Instantiates a client
49+
try (ContextsClient contextsClient = ContextsClient.create()) {
50+
// Set the session name using the sessionId (UUID) and projectId (my-project-id)
51+
SessionName session = SessionName.of(projectId, sessionId);
52+
53+
// Performs the list contexts request
54+
System.out.format("Contexts for session %s:\n", session.toString());
55+
for (Context context : contextsClient.listContexts(session).iterateAll()) {
56+
System.out.format("Context name: %s\n", context.getName());
57+
System.out.format("Lifespan Count: %d\n", context.getLifespanCount());
58+
System.out.format("Fields:\n");
59+
for (Entry<String, Value> entry : context.getParameters().getFieldsMap().entrySet()) {
60+
if (entry.getValue().hasStructValue()) {
61+
System.out.format("\t%s: %s\n", entry.getKey(), entry.getValue());
62+
}
63+
}
64+
}
65+
}
66+
}
67+
// [END dialogflow_list_contexts]
68+
69+
// [START dialogflow_create_context]
70+
/**
71+
* Create an entity type with the given display name
72+
* @param contextId The Id of the context.
73+
* @param sessionId Identifier of the DetectIntent session.
74+
* @param lifespanCount The lifespan count of the context.
75+
* @param projectId Project/Agent Id.
76+
*/
77+
public static void createContext(String contextId, String sessionId, String projectId,
78+
int lifespanCount) throws Exception {
79+
// Instantiates a client
80+
try (ContextsClient contextsClient = ContextsClient.create()) {
81+
// Set the session name using the sessionId (UUID) and projectID (my-project-id)
82+
SessionName session = SessionName.of(projectId, sessionId);
83+
84+
// Create the context name with the projectId, sessionId, and contextId
85+
ContextName contextName = ContextName.newBuilder()
86+
.setProject(projectId)
87+
.setSession(sessionId)
88+
.setContext(contextId)
89+
.build();
90+
91+
// Create the context with the context name and lifespan count
92+
Context context = Context.newBuilder()
93+
.setName(contextName.toString()) // The unique identifier of the context
94+
.setLifespanCount(lifespanCount) // Number of query requests before the context expires.
95+
.build();
96+
97+
// Performs the create context request
98+
Context response = contextsClient.createContext(session, context);
99+
System.out.format("Context created: %s\n", response);
100+
}
101+
}
102+
// [END dialogflow_create_context]
103+
104+
// [START dialogflow_delete_context]
105+
/**
106+
* Delete entity type with the given entity type name
107+
* @param contextId The Id of the context.
108+
* @param sessionId Identifier of the DetectIntent session.
109+
* @param projectId Project/Agent Id.
110+
*/
111+
public static void deleteContext(String contextId, String sessionId, String projectId)
112+
throws Exception {
113+
// Instantiates a client
114+
try (ContextsClient contextsClient = ContextsClient.create()) {
115+
// Create the context name with the projectId, sessionId, and contextId
116+
ContextName contextName = ContextName.of(projectId, sessionId, contextId);
117+
// Performs the delete context request
118+
contextsClient.deleteContext(contextName);
119+
}
120+
}
121+
// [END dialogflow_delete_context]
122+
123+
public static void main(String[] args) throws Exception {
124+
ArgumentParser parser =
125+
ArgumentParsers.newFor("ContextManagement")
126+
.build()
127+
.defaultHelp(true)
128+
.description("Create / List / Delete a context.");
129+
130+
Subparsers subparsers = parser.addSubparsers().dest("command").title("Commands");
131+
132+
Subparser listParser = subparsers.addParser("list")
133+
.help("mvn exec:java -DContextManagement -Dexec.args='list --sessionId SESSION_ID "
134+
+ "--projectId PROJECT_ID'");
135+
listParser.addArgument("--sessionId")
136+
.help("Identifier of the DetectIntent session").required(true);
137+
listParser.addArgument("--projectId").help("Project/Agent Id").required(true);
138+
139+
Subparser createParser = subparsers.addParser("create")
140+
.help("mvn exec:java -DContextManagement -Dexec.args='create --sessionId SESSION_ID "
141+
+ "--projectId PROJECT_ID --contextId CONTEXT_ID'");
142+
createParser.addArgument("--sessionId")
143+
.help("Identifier of the DetectIntent session").required(true);
144+
createParser.addArgument("--projectId").help("Project/Agent Id").required(true);
145+
createParser.addArgument("--contextId")
146+
.help("The Id of the context")
147+
.required(true);
148+
createParser.addArgument("--lifespanCount")
149+
.help("The lifespan count of the context (Default: 1)").setDefault(1);
150+
151+
Subparser deleteParser = subparsers.addParser("delete")
152+
.help("mvn exec:java -DContextManagement -Dexec.args='delete --sessionId SESSION_ID "
153+
+ "--projectId PROJECT_ID --contextId CONTEXT_ID'");
154+
deleteParser.addArgument("--sessionId")
155+
.help("Identifier of the DetectIntent session").required(true);
156+
deleteParser.addArgument("--projectId").help("Project/Agent Id").required(true);
157+
deleteParser.addArgument("--contextId")
158+
.help("The Id of the context")
159+
.required(true);
160+
161+
try {
162+
Namespace namespace = parser.parseArgs(args);
163+
164+
if (namespace.get("command").equals("list")) {
165+
listContexts(namespace.get("sessionId"), namespace.get("projectId"));
166+
} else if (namespace.get("command").equals("create")) {
167+
createContext(namespace.get("contextId"), namespace.get("sessionId"),
168+
namespace.get("projectId"), namespace.get("lifespanCount"));
169+
} else if (namespace.get("command").equals("delete")) {
170+
deleteContext(namespace.get("contextId"), namespace.get("sessionId"),
171+
namespace.get("projectId"));
172+
}
173+
} catch (ArgumentParserException e) {
174+
parser.handleError(e);
175+
}
176+
}
177+
}
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
/*
2+
* Copyright 2018 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.dialogflow;
18+
19+
// Imports the Google Cloud client library
20+
import com.google.cloud.dialogflow.v2.AudioEncoding;
21+
import com.google.cloud.dialogflow.v2.DetectIntentRequest;
22+
import com.google.cloud.dialogflow.v2.DetectIntentResponse;
23+
import com.google.cloud.dialogflow.v2.InputAudioConfig;
24+
import com.google.cloud.dialogflow.v2.QueryInput;
25+
import com.google.cloud.dialogflow.v2.QueryResult;
26+
import com.google.cloud.dialogflow.v2.SessionName;
27+
import com.google.cloud.dialogflow.v2.SessionsClient;
28+
import com.google.protobuf.ByteString;
29+
30+
import java.nio.file.Files;
31+
import java.nio.file.Paths;
32+
import java.util.UUID;
33+
import net.sourceforge.argparse4j.ArgumentParsers;
34+
import net.sourceforge.argparse4j.inf.ArgumentParser;
35+
import net.sourceforge.argparse4j.inf.ArgumentParserException;
36+
import net.sourceforge.argparse4j.inf.Namespace;
37+
38+
39+
/**
40+
* DialogFlow API Detect Intent sample with audio files.
41+
*/
42+
public class DetectIntentAudio {
43+
44+
// [START dialogflow_detect_intent_audio]
45+
/**
46+
* Returns the result of detect intent with an audio file as input.
47+
*
48+
* Using the same `session_id` between requests allows continuation of the conversation.
49+
* @param projectId Project/Agent Id.
50+
* @param audioFilePath Path to the audio file.
51+
* @param sessionId Identifier of the DetectIntent session.
52+
* @param languageCode Language code of the query.
53+
*/
54+
public static void detectIntentAudio(String projectId, String audioFilePath, String sessionId,
55+
String languageCode)
56+
throws Exception {
57+
// Instantiates a client
58+
try (SessionsClient sessionsClient = SessionsClient.create()) {
59+
// Set the session name using the sessionId (UUID) and projectID (my-project-id)
60+
SessionName session = SessionName.of(projectId, sessionId);
61+
System.out.println("Session Path: " + session.toString());
62+
63+
// Note: hard coding audioEncoding and sampleRateHertz for simplicity.
64+
// Audio encoding of the audio content sent in the query request.
65+
AudioEncoding audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16;
66+
int sampleRateHertz = 16000;
67+
68+
// 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();
74+
75+
// Build the query with the InputAudioConfig
76+
QueryInput queryInput = QueryInput.newBuilder().setAudioConfig(inputAudioConfig).build();
77+
78+
// Read the bytes from the audio file
79+
byte[] inputAudio = Files.readAllBytes(Paths.get(audioFilePath));
80+
81+
// Build the DetectIntentRequest
82+
DetectIntentRequest request = DetectIntentRequest.newBuilder()
83+
.setSession(session.toString())
84+
.setQueryInput(queryInput)
85+
.setInputAudio(ByteString.copyFrom(inputAudio))
86+
.build();
87+
88+
// Performs the detect intent request
89+
DetectIntentResponse response = sessionsClient.detectIntent(request);
90+
91+
// Display the query result
92+
QueryResult queryResult = response.getQueryResult();
93+
System.out.println("====================");
94+
System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
95+
System.out.format("Detected Intent: %s (confidence: %f)\n",
96+
queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
97+
System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());
98+
}
99+
}
100+
// [END dialogflow_detect_intent_audio]
101+
102+
public static void main(String[] args) throws Exception {
103+
ArgumentParser parser =
104+
ArgumentParsers.newFor("DetectIntentAudio")
105+
.build()
106+
.defaultHelp(true)
107+
.description("Returns the result of detect intent with an audio file as input.\n"
108+
+ "mvn exec:java -DDetectIntentAudio -Dexec.args='--projectId PROJECT_ID "
109+
+ "--audioFilePath resources/book_a_room.wav --sessionId SESSION_ID'");
110+
111+
parser.addArgument("--projectId").help("Project/Agent Id").required(true);
112+
113+
parser.addArgument("--audioFilePath")
114+
.help("Path to the audio file")
115+
.required(true);
116+
117+
parser.addArgument("--sessionId")
118+
.help("Identifier of the DetectIntent session (Default: UUID.)")
119+
.setDefault(UUID.randomUUID().toString());
120+
121+
parser.addArgument("--languageCode")
122+
.help("Language Code of the query (Default: en-US")
123+
.setDefault("en-US");
124+
125+
try {
126+
Namespace namespace = parser.parseArgs(args);
127+
128+
detectIntentAudio(namespace.get("projectId"), namespace.get("audioFilePath"),
129+
namespace.get("sessionId"), namespace.get("languageCode"));
130+
} catch (ArgumentParserException e) {
131+
parser.handleError(e);
132+
}
133+
}
134+
}

0 commit comments

Comments
 (0)