Skip to content

Commit

Permalink
samples: samples: refactor dialogflow for 2.1.0 (#3283)
Browse files Browse the repository at this point in the history
* samples: refactor dialogflow for 2.1.0

* formatted code

* made requested changes

* fixed compilation error

* fixed lint on tests

* lint issue
  • Loading branch information
munkhuushmgl authored and chingor13 committed Aug 3, 2020
1 parent 5e0dbda commit 62de669
Show file tree
Hide file tree
Showing 16 changed files with 198 additions and 258 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@

package com.example.dialogflow;

// Imports the Google Cloud client library
// [START dialogflow_detect_intent_audio]

import com.google.api.gax.rpc.ApiException;
import com.google.cloud.dialogflow.v2.AudioEncoding;
import com.google.cloud.dialogflow.v2.DetectIntentRequest;
import com.google.cloud.dialogflow.v2.DetectIntentResponse;
Expand All @@ -27,33 +28,16 @@
import com.google.cloud.dialogflow.v2.SessionName;
import com.google.cloud.dialogflow.v2.SessionsClient;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;


/**
* DialogFlow API Detect Intent sample with audio files.
*/
public class DetectIntentAudio {
// [START dialogflow_detect_intent_audio]

/**
* Returns the result of detect intent with an audio file as input.
*
* Using the same `session_id` between requests allows continuation of the conversation.
*
* @param projectId Project/Agent Id.
* @param audioFilePath Path to the audio file.
* @param sessionId Identifier of the DetectIntent session.
* @param languageCode Language code of the query.
* @return QueryResult for the request.
*/
// DialogFlow API Detect Intent sample with audio files.
public static QueryResult detectIntentAudio(
String projectId,
String audioFilePath,
String sessionId,
String languageCode)
throws Exception {
String projectId, String audioFilePath, String sessionId, String languageCode)
throws IOException, ApiException {
// Instantiates a client
try (SessionsClient sessionsClient = SessionsClient.create()) {
// Set the session name using the sessionId (UUID) and projectID (my-project-id)
Expand All @@ -66,11 +50,13 @@ public static QueryResult detectIntentAudio(
int sampleRateHertz = 16000;

// Instructs the speech recognizer how to process the audio content.
InputAudioConfig inputAudioConfig = InputAudioConfig.newBuilder()
.setAudioEncoding(audioEncoding) // audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16
.setLanguageCode(languageCode) // languageCode = "en-US"
.setSampleRateHertz(sampleRateHertz) // sampleRateHertz = 16000
.build();
InputAudioConfig inputAudioConfig =
InputAudioConfig.newBuilder()
.setAudioEncoding(
audioEncoding) // audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16
.setLanguageCode(languageCode) // languageCode = "en-US"
.setSampleRateHertz(sampleRateHertz) // sampleRateHertz = 16000
.build();

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

// Build the DetectIntentRequest
DetectIntentRequest request = DetectIntentRequest.newBuilder()
.setSession(session.toString())
.setQueryInput(queryInput)
.setInputAudio(ByteString.copyFrom(inputAudio))
.build();
DetectIntentRequest request =
DetectIntentRequest.newBuilder()
.setSession(session.toString())
.setQueryInput(queryInput)
.setInputAudio(ByteString.copyFrom(inputAudio))
.build();

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

return queryResult;
}
}
// [END dialogflow_detect_intent_audio]
}
// [END dialogflow_detect_intent_audio]
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@

package com.example.dialogflow;

// Imports the Google Cloud client library
// [START dialogflow_detect_intent_knowledge]

import com.google.api.gax.rpc.ApiException;
import com.google.cloud.dialogflow.v2beta1.DetectIntentRequest;
import com.google.cloud.dialogflow.v2beta1.DetectIntentResponse;
import com.google.cloud.dialogflow.v2beta1.KnowledgeAnswers;
Expand All @@ -29,33 +30,20 @@
import com.google.cloud.dialogflow.v2beta1.SessionsClient;
import com.google.cloud.dialogflow.v2beta1.TextInput;
import com.google.common.collect.Maps;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
* DialogFlow API Detect Intent sample with querying knowledge connector.
*/
public class DetectIntentKnowledge {
// [START dialogflow_detect_intent_knowledge]

/**
* Returns the result of detect intent with text as input.
*
* <p>Using the same `session_id` between requests allows continuation of the conversation.
*
* @param projectId Project/Agent Id.
* @param knowledgeBaseName Knowledge base Id.
* @param sessionId Identifier of the DetectIntent session.
* @param languageCode Language code of the query.
* @param texts The texts to be processed.
* @return The KnowledgeAnswers found for each text.
*/
// DialogFlow API Detect Intent sample with querying knowledge connector.
public static Map<String, KnowledgeAnswers> detectIntentKnowledge(
String projectId,
String knowledgeBaseName,
String sessionId,
String languageCode,
List<String> texts) throws Exception {
List<String> texts)
throws IOException, ApiException {
// Instantiates a client
Map<String, KnowledgeAnswers> allKnowledgeAnswers = Maps.newHashMap();
try (SessionsClient sessionsClient = SessionsClient.create()) {
Expand All @@ -72,9 +60,7 @@ public static Map<String, KnowledgeAnswers> detectIntentKnowledge(
QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();

QueryParameters queryParameters =
QueryParameters.newBuilder()
.addKnowledgeBaseNames(knowledgeBaseName)
.build();
QueryParameters.newBuilder().addKnowledgeBaseNames(knowledgeBaseName).build();

DetectIntentRequest detectIntentRequest =
DetectIntentRequest.newBuilder()
Expand Down Expand Up @@ -107,5 +93,5 @@ public static Map<String, KnowledgeAnswers> detectIntentKnowledge(
}
return allKnowledgeAnswers;
}
// [END dialogflow_detect_intent_knowledge]
}
// [END dialogflow_detect_intent_knowledge]
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
package com.example.dialogflow;

// [START dialogflow_detect_intent_streaming]
// Imports the Google Cloud client library

import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.BidiStream;
import com.google.cloud.dialogflow.v2.AudioEncoding;
import com.google.cloud.dialogflow.v2.InputAudioConfig;
Expand All @@ -31,12 +32,11 @@
import java.io.FileInputStream;
import java.io.IOException;

/**
* DialogFlow API Detect Intent sample with audio files processes as an audio stream.
*/
class DetectIntentStream {

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

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

// The first request must **only** contain the audio configuration:
bidiStream.send(StreamingDetectIntentRequest.newBuilder()
.setSession(session.toString())
.setQueryInput(queryInput)
.build());
bidiStream.send(
StreamingDetectIntentRequest.newBuilder()
.setSession(session.toString())
.setQueryInput(queryInput)
.build());

try (FileInputStream audioStream = new FileInputStream(audioFilePath)) {
// Subsequent requests must **only** contain the audio data.
Expand All @@ -91,13 +93,11 @@ static void detectIntentStream(String projectId, String audioFilePath, String se
System.out.println("====================");
System.out.format("Intent Display Name: %s\n", queryResult.getIntent().getDisplayName());
System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
System.out.format("Detected Intent: %s (confidence: %f)\n",
System.out.format(
"Detected Intent: %s (confidence: %f)\n",
queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());

}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,40 +16,26 @@

package com.example.dialogflow;

// Imports the Google Cloud client library
// [START dialogflow_detect_intent_text]

import com.google.api.gax.rpc.ApiException;
import com.google.cloud.dialogflow.v2.DetectIntentResponse;
import com.google.cloud.dialogflow.v2.QueryInput;
import com.google.cloud.dialogflow.v2.QueryResult;
import com.google.cloud.dialogflow.v2.SessionName;
import com.google.cloud.dialogflow.v2.SessionsClient;
import com.google.cloud.dialogflow.v2.TextInput;
import com.google.common.collect.Maps;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
* DialogFlow API Detect Intent sample with text inputs.
*/
public class DetectIntentTexts {
// [START dialogflow_detect_intent_text]

/**
* Returns the result of detect intent with texts as inputs.
*
* Using the same `session_id` between requests allows continuation of the conversation.
*
* @param projectId Project/Agent Id.
* @param texts The text intents to be detected based on what a user says.
* @param sessionId Identifier of the DetectIntent session.
* @param languageCode Language code of the query.
* @return The QueryResult for each input text.
*/
// DialogFlow API Detect Intent sample with text inputs.
public static Map<String, QueryResult> detectIntentTexts(
String projectId,
List<String> texts,
String sessionId,
String languageCode) throws Exception {
String projectId, List<String> texts, String sessionId, String languageCode)
throws IOException, ApiException {
Map<String, QueryResult> queryResults = Maps.newHashMap();
// Instantiates a client
try (SessionsClient sessionsClient = SessionsClient.create()) {
Expand All @@ -74,7 +60,8 @@ public static Map<String, QueryResult> detectIntentTexts(

System.out.println("====================");
System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
System.out.format("Detected Intent: %s (confidence: %f)\n",
System.out.format(
"Detected Intent: %s (confidence: %f)\n",
queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());

Expand All @@ -83,5 +70,5 @@ public static Map<String, QueryResult> detectIntentTexts(
}
return queryResults;
}
// [END dialogflow_detect_intent_text]
}
// [END dialogflow_detect_intent_text]
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@

package com.example.dialogflow;

// [START dialogflow_detect_intent_with_sentiment_analysis]

import com.google.api.gax.rpc.ApiException;
import com.google.cloud.dialogflow.v2.DetectIntentRequest;
import com.google.cloud.dialogflow.v2.DetectIntentResponse;
import com.google.cloud.dialogflow.v2.QueryInput;
Expand All @@ -26,28 +29,15 @@
import com.google.cloud.dialogflow.v2.SessionsClient;
import com.google.cloud.dialogflow.v2.TextInput;
import com.google.common.collect.Maps;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class DetectIntentWithSentimentAnalysis {
// [START dialogflow_detect_intent_with_sentiment_analysis]

/**
* Returns the result of detect intent with texts as inputs.
*
* <p>Using the same `session_id` between requests allows continuation of the conversation.
*
* @param projectId Project/Agent Id.
* @param texts The text intents to be detected based on what a user says.
* @param sessionId Identifier of the DetectIntent session.
* @param languageCode Language code of the query.
* @return The QueryResult for each text in query.
*/
public static Map<String, QueryResult> detectIntentSentimentAnalysis(
String projectId,
List<String> texts,
String sessionId,
String languageCode) throws Exception {
public static Map<String, QueryResult> detectIntentSentimentAnalysis(
String projectId, List<String> texts, String sessionId, String languageCode)
throws IOException, ApiException {
Map<String, QueryResult> queryResults = Maps.newHashMap();
// Instantiates a client
try (SessionsClient sessionsClient = SessionsClient.create()) {
Expand Down Expand Up @@ -100,5 +90,5 @@ public static Map<String, QueryResult> detectIntentSentimentAnalysis(
}
return queryResults;
}
// [END dialogflow_detect_intent_with_sentiment_analysis]
}
// [END dialogflow_detect_intent_with_sentiment_analysis]
Loading

0 comments on commit 62de669

Please sign in to comment.