如何使用DialogFlow V2客户端库

时间:2018-04-30 07:32:29

标签: android dialogflow

我正在使用dialogflow-android-client但现在已经发布了dialogflowV2。所以我试图使用Dialogflow new Library来实现。

以下是Android中的代码

 private String projectId = "modroid-test-3aedd";
 private TextView textView;
 private SpeechToText toText;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = findViewById(R.id.textview);
    toText = new SpeechToText(this, textView);

    try {
        GoogleCredentials credentials = GoogleCredentials.fromStream(getResources().getAssets().open("Test-9d8a744b520a.json"))
                .createScoped(newArrayList("https://www.googleapis.com/auth/compute"));
        credentials.toBuilder().build();

    } catch (IOException e) {
        e.printStackTrace();
    }
    textView = findViewById(R.id.textview);
    new MyAsync(projectId).execute();

}

 @Override
 protected void onStart() {
    super.onStart();
    toText.start();
 }

 @Override
 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    toText.start();
}

class MyAsync extends AsyncTask {
    private String projectId;

    MyAsync(String projectId) {
        this.projectId = projectId;
    }

    @Override
    protected Object doInBackground(Object[] objects) {
        try {

            detectIntentStream(projectId, null, "7fff90e6-3879-4ed5-ad85-058531b3002a", "en-US");

        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }

    public void detectIntentStream(String projectId, String audioFilePath, String sessionId,
                                   String languageCode) throws Throwable {
        // Start bi-directional StreamingDetectIntent stream.
        final CountDownLatch notification = new CountDownLatch(1);
        final List<Throwable> responseThrowables = new ArrayList<>();
        final List<StreamingDetectIntentResponse> responses = new ArrayList<>();

        // Instantiates a client
        try (SessionsClient sessionsClient = SessionsClient.create()) { // on this line it throws exception to me
            // Set the session name using the sessionId (UUID) and projectID (my-project-id)
            SessionName session = SessionName.of(projectId, sessionId);
            System.out.println("Session Path: " + session.toString());

            // Note: hard coding audioEncoding and sampleRateHertz for simplicity.
            // Audio encoding of the audio content sent in the query request.
            AudioEncoding audioEncoding = AudioEncoding.AUDIO_ENCODING_LINEAR_16;
            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();

            ApiStreamObserver<StreamingDetectIntentResponse> responseObserver =
                    new ApiStreamObserver<StreamingDetectIntentResponse>() {
                        @Override
                        public void onNext(StreamingDetectIntentResponse response) {
                            // Do something when receive a response
                            responses.add(response);
                        }

                        @Override
                        public void onError(Throwable t) {
                            // Add error-handling
                            responseThrowables.add(t);
                        }

                        @Override
                        public void onCompleted() {
                            // Do something when complete.
                            notification.countDown();
                        }
                    };

            // Performs the streaming detect intent callable request
            ApiStreamObserver<StreamingDetectIntentRequest> requestObserver =
                    sessionsClient.streamingDetectIntentCallable().bidiStreamingCall(responseObserver);

            // Build the query with the InputAudioConfig
            QueryInput queryInput = QueryInput.newBuilder().setAudioConfig(inputAudioConfig).build();

            try (FileInputStream audioStream = new FileInputStream(audioFilePath)) {
                // The first request contains the configuration
                StreamingDetectIntentRequest request = StreamingDetectIntentRequest.newBuilder()
                        .setSession(session.toString())
                        .setQueryInput(queryInput)
                        .build();

                // Make the first request
                requestObserver.onNext(request);

                // 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) {
                    requestObserver.onNext(
                            StreamingDetectIntentRequest.newBuilder()
                                    .setInputAudio(ByteString.copyFrom(buffer, 0, bytes))
                                    .build());
                }
            } catch (RuntimeException e) {
                // Cancel stream.
                requestObserver.onError(e);
            }
            // Half-close the stream.
            requestObserver.onCompleted();
            // Wait for the final response (without explicit timeout).
            notification.await();
            // Process errors/responses.
            if (!responseThrowables.isEmpty()) {
                throw responseThrowables.get(0);
            }
            if (responses.isEmpty()) {
                throw new RuntimeException("No response from Dialogflow.");
            }

            for (StreamingDetectIntentResponse response : responses) {
                if (response.hasRecognitionResult()) {
                    System.out.format(
                            "Intermediate transcript: '%s'\n", response.getRecognitionResult().getTranscript());
                }
            }

            // Display the last query result
            QueryResult queryResult = responses.get(responses.size() - 1).getQueryResult();
            System.out.println("====================");
            System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
            System.out.format("Detected Intent: %s (confidence: %f)\n",
                    queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
            System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());

            textView.setText(queryResult.getQueryText() + queryResult.getFulfillmentText());
        }
    }
}

当我运行我的代码时,我得到了以下异常

 omputeEngineCredentials: Failed to detect whether we are running on Google Compute Engine.
                       java.io.IOException: unexpected end of stream on com.android.okhttp.Address@8ab7d8c3
                           at com.android.okhttp.internal.http.Http1xStream.readResponse(Http1xStream.java:201)
                           at com.android.okhttp.internal.http.Http1xStream.readResponseHeaders(Http1xStream.java:127)
                           at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:737)
                           at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:609)
                           at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:471)
                           at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:407)
                           at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:538)
                           at com.google.api.client.http.javanet.NetHttpResponse.<init>(NetHttpResponse.java:37)
                           at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:105)
                           at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:981)
                           at com.google.auth.oauth2.ComputeEngineCredentials.runningOnComputeEngine(ComputeEngineCredentials.java:191)
                           at com.google.auth.oauth2.DefaultCredentialsProvider.tryGetComputeCredentials(DefaultCredentialsProvider.java:270)
                           at com.google.auth.oauth2.DefaultCredentialsProvider.getDefaultCredentialsUnsynchronized(DefaultCredentialsProvider.java:194)
                           at com.google.auth.oauth2.DefaultCredentialsProvider.getDefaultCredentials(DefaultCredentialsProvider.java:112)
                           at com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:127)
                           at com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:100)
                           at com.google.api.gax.core.GoogleCredentialsProvider.getCredentials(GoogleCredentialsProvider.java:53)
                           at com.google.api.gax.rpc.ClientContext.create(ClientContext.java:134)
                           at com.google.cloud.dialogflow.v2.stub.GrpcSessionsStub.create(GrpcSessionsStub.java:75)
                           at com.google.cloud.dialogflow.v2.stub.SessionsStubSettings.createStub(SessionsStubSettings.java:100)
                           at com.google.cloud.dialogflow.v2.SessionsClient.<init>(SessionsClient.java:132)
                           at com.google.cloud.dialogflow.v2.SessionsClient.create(SessionsClient.java:114)
                           at com.google.cloud.dialogflow.v2.SessionsClient.create(SessionsClient.java:106)
                           at com.example.lpt_0096.dialogflowv2.MainActivity$MyAsync.detectIntentStream(MainActivity.java:99)
                           at com.example.lpt_0096.dialogflowv2.MainActivity$MyAsync.doInBackground(MainActivity.java:83)
                           at android.os.AsyncTask$2.call(AsyncTask.java:333)
                           at java.util.concurrent.FutureTask.run(FutureTask.java:266)
                           at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
                           at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
                           at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
                           at java.lang.Thread.run(Thread.java:764)
                        Caused by: java.io.EOFException: \n not found: size=0 content=...
                           at com.android.okhttp.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:200)
                           at com.android.okhttp.internal.http.Http1xStream.readResponse(Http1xStream.java:186)
                           at com.android.okhttp.internal.http.Http1xStream.readResponseHeaders(Http1xStream.java:127) 
                           at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:737) 
                           at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:609) 
                           at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:471) 
                           at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:407) 
                           at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:538) 
                           at com.google.api.client.http.javanet.NetHttpResponse.<init>(NetHttpResponse.java:37) 
                           at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:105) 
                           at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:981) 
                           at com.google.auth.oauth2.ComputeEngineCredentials.runningOnComputeEngine(ComputeEngineCredentials.java:191) 
                           at com.google.auth.oauth2.DefaultCredentialsProvider.tryGetComputeCredentials(DefaultCredentialsProvider.java:270) 
                           at com.google.auth.oauth2.DefaultCredentialsProvider.getDefaultCredentialsUnsynchronized(DefaultCredentialsProvider.java:194) 
                           at com.google.auth.oauth2.DefaultCredentialsProvider.getDefaultCredentials(DefaultCredentialsProvider.java:112) 
                           at com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:127) 
                           at com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:100) 
                           at com.google.api.gax.core.GoogleCredentialsProvider.getCredentials(GoogleCredentialsProvider.java:53) 
                           at com.google.api.gax.rpc.ClientContext.create(ClientContext.java:134) 
                           at com.google.cloud.dialogflow.v2.stub.GrpcSessionsStub.create(GrpcSessionsStub.java:75) 
                           at com.google.cloud.dialogflow.v2.stub.SessionsStubSettings.createStub(SessionsStubSettings.java:100) 
                           at com.google.cloud.dialogflow.v2.SessionsClient.<init>(SessionsClient.java:132) 
                           at com.google.cloud.dialogflow.v2.SessionsClient.create(SessionsClient.java:114) 
                           at com.google.cloud.dialogflow.v2.SessionsClient.create(SessionsClient.java:106) 
                           at com.example.lpt_0096.dialogflowv2.MainActivity$MyAsync.detectIntentStream(MainActivity.java:99) 
                           at com.example.lpt_0096.dialogflowv2.MainActivity$MyAsync.doInBackground(MainActivity.java:83) 
                           at android.os.AsyncTask$2.call(AsyncTask.java:333) 
                           at java.util.concurrent.FutureTask.run(FutureTask.java:266) 
                           at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) 
                           at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162) 
                           at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636) 
                           at java.lang.Thread.run(Thread.java:764) 

我不知道我做错了什么。我如何在Android中使用此库。在Google Dialogflow library示例中给出了java,我们必须在环境变量中设置 Google_Application_credential 。因此,我在Android中实现我使用下面的代码。

GoogleCredentials credentials = GoogleCredentials.fromStream(getResources().getAssets().open("Modroid-Test-9d8a744b520a.json"))
            .createScoped(newArrayList("https://www.googleapis.com/auth/compute"));
    credentials.toBuilder().build();

但它并没有起作用,并且在

上给了我一个例外
 try (SessionsClient sessionsClient = SessionsClient.create()) 

2 个答案:

答案 0 :(得分:1)

result = pd.merge(df1, df2, left_on='name', right_on='account', how='left', sort=False)

答案 1 :(得分:0)

texts.add("Hi");
String sessionId="3f46dfa4-5204-84f3-1488-5556f3d6b8a1";
String languageCode="en-US";
GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream("E:\\GoogleDialogFlow\\ChatBox\\Json.json"))
.createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));

SessionsSettings.Builder settingsBuilder = SessionsSettings.newBuilder();
SessionsSettings sessionsSettings = settingsBuilder.setCredentialsProvider(FixedCredentialsProvider.create(credentials)).build();
SessionsClient sessionsClient = SessionsClient.create(sessionsSettings);
SessionName session = SessionName.of(projectId, sessionId);
com.google.cloud.dialogflow.v2.TextInput.Builder textInput = TextInput.newBuilder().setText("Hi").setLanguageCode(languageCode);
QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();
DetectIntentResponse response = sessionsClient.detectIntent(session, queryInput);
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",
queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());    
credentials.toBuilder().build();```


This source code is working on my window but when I am publishing it getting error on Linux server.So time they are saying update your guava-23.6 jar file but problem is still there. 
I am trying read my .json file from one path. I am not setting the environment variable on Linux , even my local machine.