Skip to content

Commit

Permalink
Adds Dialogflow detect intent streams sample
Browse files Browse the repository at this point in the history
This PR adds the following code sample region tags:
dialogflow_detect_intent_streaming

The canonical (Java) is found here:
https://github.com/GoogleCloudPlatform/java-docs-samples/blob/master/dialogflow/cloud-client/src/main/java/com/example/dialogflow/DetectIntentStream.java

Individual commits:
* feat: adds detect intent stream sample to Dialogflow C# samples
* feat: adds test for detect intent stream
* fix: changes timeout period to 500 on DF tests
  • Loading branch information
telpirion authored Feb 24, 2020
1 parent ebc5918 commit 9a4197d
Show file tree
Hide file tree
Showing 5 changed files with 167 additions and 4 deletions.
121 changes: 121 additions & 0 deletions dialogflow/api/DialogflowSamples/DetectIntentStream.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
// Copyright(c) 2020 Google Inc.
//
// 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.

using CommandLine;
using Google.Cloud.Dialogflow.V2;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace GoogleCloudSamples
{
public class DetectIntentStream
{
public static void RegisterCommands(VerbMap<object> verbMap)
{
verbMap
.Add((DetectIntentFromStreamOptions opts) =>
DetectIntentFromStreamAsync(opts.ProjectId, opts.SessionId, opts.FilePath).Result);
}

[Verb("detect-intent:streams", HelpText = "Detect intent from stream")]
public class DetectIntentFromStreamOptions : OptionsWithProjectIdAndSessionId
{
[Value(0, MetaName = "file", HelpText = "Path to the audio file", Required = true)]
public string FilePath { get; set; }
}

// [START dialogflow_detect_intent_streaming]
public static async Task<object> DetectIntentFromStreamAsync(
string projectId,
string sessionId,
string filePath)
{
var sessionsClient = SessionsClient.Create();
var sessionName = SessionName.Format(projectId, sessionId);

// Initialize streaming call, retrieving the stream object
var streamingDetectIntent = sessionsClient.StreamingDetectIntent();

// Define a task to process results from the API
var responseHandlerTask = Task.Run(async () =>
{
var responseStream = streamingDetectIntent.ResponseStream;
while (await responseStream.MoveNext())
{
var response = responseStream.Current;
var queryResult = response.QueryResult;

if (queryResult != null)
{
Console.WriteLine($"Query text: {queryResult.QueryText}");
if (queryResult.Intent != null)
{
Console.Write("Intent detected:");
Console.WriteLine(queryResult.Intent.DisplayName);
}
}
}
});

// Instructs the speech recognizer how to process the audio content.
// Note: hard coding audioEncoding, sampleRateHertz for simplicity.
var queryInput = new QueryInput
{
AudioConfig = new InputAudioConfig
{
AudioEncoding = AudioEncoding.Linear16,
LanguageCode = "en-US",
SampleRateHertz = 16000
}
};

// The first request must **only** contain the audio configuration:
await streamingDetectIntent.WriteAsync(new StreamingDetectIntentRequest
{
QueryInput = queryInput,
Session = sessionName
});

using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
// 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.
var buffer = new byte[32 * 1024];
int bytesRead;
while ((bytesRead = await fileStream.ReadAsync(
buffer, 0, buffer.Length)) > 0)
{
await streamingDetectIntent.WriteAsync(new StreamingDetectIntentRequest
{
Session = sessionName,
InputAudio = Google.Protobuf.ByteString.CopyFrom(buffer, 0, bytesRead)
});
};
}

// Tell the service you are done sending data
await streamingDetectIntent.WriteCompleteAsync();

// This will complete once all server responses have been processed.
await responseHandlerTask;

return 0;
}
// [END dialogflow_detect_intent_streaming]
}
}
1 change: 1 addition & 0 deletions dialogflow/api/DialogflowSamples/DialogflowSamples.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public static int Main(string[] args)
var verbMap = new VerbMap<object>();

DetectIntentTexts.RegisterCommands(verbMap);
DetectIntentStream.RegisterCommands(verbMap);
ContextManagement.RegisterCommands(verbMap);
IntentManagement.RegisterCommands(verbMap);
EntityManagement.RegisterCommands(verbMap);
Expand Down
35 changes: 35 additions & 0 deletions dialogflow/api/Test/DetectIntentStreamTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Copyright(c) 2020 Google Inc.
//
// 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.

using System;
using System.IO;
using Xunit;

namespace GoogleCloudSamples
{
public class DetectIntentStreamsTest : DialogflowTest
{
[Fact(Skip = "https://github.com/GoogleCloudPlatform/dotnet-docs-samples/issues/947")]
void TestDetectIntentFromStream()
{
var _audioWavPath = Path.Combine("resources", "book_a_room.wav");

RunWithSessionId("detect-intent:streams", _audioWavPath);
Assert.Equal(0, ExitCode);

Assert.Contains("book", Stdout);
Assert.Contains("Intent detected:", Stdout);
}
}
}
12 changes: 9 additions & 3 deletions dialogflow/api/Test/DialogflowSampleTests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
<PackageReference Include="Google.Cloud.Dialogflow.V2" Version="1.2.0" />
<PackageReference Include="JUnitTestLogger" Version="0.6.0" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.9.0" />
</ItemGroup>
Expand All @@ -21,4 +21,10 @@
<ItemGroup>
<Compile Remove="BaseTest.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="..\resources\book_a_room.wav">
<Link>resources\book_a_room.wav</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>
2 changes: 1 addition & 1 deletion dialogflow/api/Test/runTests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

import-module -DisableNameChecking ..\..\..\BuildTools.psm1

Set-TestTimeout 1800
Set-TestTimeout 5000

dotnet restore
dotnet build
Expand Down

0 comments on commit 9a4197d

Please sign in to comment.