googlecloudplatform / dotnet-docs-samples Goto Github PK
View Code? Open in Web Editor NEW.NET code samples used on https://cloud.google.com
Home Page: https://cloud.google.com/dotnet
License: Apache License 2.0
.NET code samples used on https://cloud.google.com
Home Page: https://cloud.google.com/dotnet
License: Apache License 2.0
I wrote the seed in
https://github.com/GoogleCloudPlatform/dotnet-docs-samples/tree/streamingPull
but it still needs tests, comments, etc.
I am using this slightly modified version of the code from this repository:
public async Task<string> TranscribeSpeech(string filenameAndPath, int WAVSampleRate = 8000)
{
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", Utils.GetHomeFolder() + @"\Google Speech API Key.json"); //for authentication
var language = WebConfigurationManager.AppSettings["GoogleSpeechFromLocale"];
var speech = SpeechClient.Create();
var response = await speech.RecognizeAsync(new RecognitionConfig()
{
Encoding = RecognitionConfig.Types.AudioEncoding.Linear16,
SampleRateHertz = WAVSampleRate,
LanguageCode = language,
}, RecognitionAudio.FromFile(filenameAndPath));
return response.Results.First().Alternatives.First().Transcript;
}
The .Recognize() or .RecognizeAsync() methods never return anything and throw an exception after 10 minutes saying Status(StatusCode=DeadlineExceeded,Detail="Deadline Exceeded")!
.
Is there an issue with the code or with the API settings?
I am working on Google Speech by c # . I want to use the microphone . My code is there But My code uses only audio files. Please help me . Thank you
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Cloud.Speech.V1Beta1;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var speech = SpeechClient.Create();
var response = speech.SyncRecognize(new RecognitionConfig()
{
LanguageCode = "tr-TR",
Encoding = RecognitionConfig.Types.AudioEncoding.Linear16,
SampleRate = 16000,
}, RecognitionAudio.FromFile("audio.wav"));
foreach (var result in response.Results)
{
foreach (var alternative in result.Alternatives)
{
Console.WriteLine(alternative.Transcript);
} }
Console.ReadLine();
}}}
Hi guys,
Google Vision, any sample for Windows 8, metro apps?
Thank you.
Hi,
I'm using the vision api (via ImageAnnotatorClient) and upon instantiating I get the following error:
"Error reading credential file from location [PATH]: Error deserializing JSON credential data.\nPlease check the value of the Environment Variable GOOGLE_APPLICATION_CREDENTIALS"
Problem is, I cloned the vision api sample in this repo and that runs just fine so I know that the environment variable is set correctly and that the info inside my credential file is in the right format. Both where I want to use this in my own code (not working) and in the test code (working) have the same code:
// Instantiates a client
var client = ImageAnnotatorClient.Create();
// Load the image file into memory
Image image = Image.FetchFromUri(url);
//Performs label detection on the image file
var response = client.DetectLabels(image);
and have the same version of Newtonsoft.Json (10.0.2) and target the same framework (.net 4.5). My failure is coming from the first line.
Note: Maybe its worth mentioning that the error producing code is contained within a Class Library project that is used by a Console Application project and the working code is directly in the Console Application.
There isn't really a difference between "sync/asynch" queries. I'm working to remove this distinction from the docs.
Please update all query samples to look more like this one, where they poll for results:
Even if the "synchronous" request times out, the job is still running. Most people will want to wait for the results.
Hi,
do you plan to create sample project for .net showing text to speech api usage?
I checked it, but I didn't understand how to use it.
Petr
I'm using below method to convert speech to text using microphone, and the sample rate is 16000. I have tested it on Windows 10 machine initially and it worked fine and later when I tested the same script on Windows 7 machine it is not working properly and I'm getting the below error message.
audio data is being streamed too slow. please stream audio data approximately at real time
How to decide which sample rate to beused on which machine? What could be the problem with my Windows 7 machine?
// [START speech_streaming_mic_recognize]
static async Task StreamingMicRecognizeAsync(int seconds)
{
// code here....
StreamingConfig = new StreamingRecognitionConfig()
{
Config = new RecognitionConfig()
{
Encoding =
RecognitionConfig.Types.AudioEncoding.Linear16,
SampleRate = 16000,
},
InterimResults = false,
}
// code here........
}
Please help me in fixing this issue.
https://cloud.google.com/pubsub/docs/reference/libraries
The method FormatTopicName
does not exist in PublisherClient
.
I am using this version:-
<package id="Google.Cloud.PubSub.V1" version="1.0.0-beta07" targetFramework="net461" />
The Endpoints example project fails to load in Visual Studio Community 2017.
The issue was that the global.json file is using an incompatible version of the ASP.NET Core SDK.
The Fix:
{
"projects": [ "src", "test" ],
"sdk": {
"version": "2.0.0",
"runtime": "coreclr"
}
}
Would really appreciate an example of how to make API calls to the Cloud ML platform using Google.Apis.CloudMachineLearningEngine.v1
Ideally the example would show how make a predict call (https://cloud.google.com/ml-engine/reference/rest/v1/projects/predict), which is something I think you would do frequently.
It is vital to have a global.json that points to the right SDK to ensure that right tools are being used. This is also very important for those older samples that still use project.json, as the newer versions of the .NET Core SDK do not support it anymore.
I am using .flac format file for google speech api SyncRecognize method but it always returns results and Etag as null. I am using Naudio to record my .wav file and i am converting it to .flac ,and after sending this .flac file to syncRecognize it gives null result always.Its Urgent.
Please Help to resolve this.
How can we set proxy in speech sdk.we need to use proxy while consuming speech to text services and I have noticed that even setting proxy in web.config, sdk ignores it and hits google API directly ignoring proxy configuration.can u pls guide us on proxy configuration
Hello,
Any one has solution to convert Json string to AnnotateTextResponse object? see below code for more details
private static void AnalyzeSyntax(string text, string encoding = "UTF16")
{
var client = LanguageServiceClient.Create();
var response = client.AnnotateText(new Document()
{
Content = text,
Type = Document.Types.Type.PlainText
},
new Features() { ExtractSyntax = true });
string jsonString = response.ToString();
// HERE I HAVE ADDED CODE TO DO REVERSE PROCESS (JSON STRING TO ANOTATETEXTRESPONSE)
var stringFromDatabase = jsonString;
AnnotateTextResponse anotateTextResponseObj = ??????(jsonString); // I need some code here that can convert Json string to AnnotateTextResponse object
}
Thanks,
Ashish
Hi Guys,
This is not an issue but more of a request for help. Does anyone know how I can return the progress or status of the long running operation. Below is my current code but have no clue how to return the progress as I couldn't find it in the documentation. I am using Google.Cloud.Speech.V1.
`dynamic audiofile = "gs://mybucket/test2.wav";
dynamic speech = SpeechClient.Create();
dynamic longOperation = await speech.LongRunningRecognizeAsync(new RecognitionConfig {
Encoding = RecognitionConfig.Types.AudioEncoding.Linear16,
SampleRateHertz = 8000,
LanguageCode = LanguageCodes.English.UnitedKingdom
}, RecognitionAudio.FromStorageUri(audiofile));
longOperation = await longOperation.PollUntilCompletedAsync();
dynamic response = longOperation.Result;
foreach (object result in response.Results) {
foreach (object alternative in result.Alternatives) {
txtReturn.Text = txtReturn.Text + alternative.Transcript;
MyObservable.Add(new TranscriptionResult {
Transcript = alternative.Transcript,
Confidence = alternative.Confidence
});
}
}`
I appreciate your assistance with this.
The auth AuthExplicitComputeEngine sample comment here is incorrect: https://github.com/GoogleCloudPlatform/dotnet-docs-samples/blob/master/auth/Program.cs#L133
It's not using a service account credential in this sample.
I don't think Lookup
guarantees that the order of the result is the same as the given keys. Please close if it does, but please fix this otherwise.
The check for a command line argument looks for 2 args, so it exits if a single arg (for the project id) is supplied.
When building the Spanner project. Far from fatal, but we should be using https://www.nuget.org/packages/TransientFaultHandling.Core/
The repo has samples, and a buildAndRunTests.ps
file, but the README.md
doesn't explain how to actually do that.
I tried the Recognize sample. It takes about 2 seconds to start the recognition since inputting "listen". Is there any way to make it faster?
But only when running automated tests. I suspect that this is happening because two tests are running simultaneously. But two applications should be able to run simultaneously.
I will turn off running tests in parallel to see if it fixes it. If it fixes it, then it's a bug in the libs.
Test method AuthTest.Test.TestListBucketContents threw exception:
System.AggregateException: One or more errors occurred. ---> System.InvalidOperationException: Error reading credential file from location C:\users\root\Documents\silver-python2-b6dac6d6b9a8.json: The process cannot access the file 'C:\users\root\Documents\silver-python2-b6dac6d6b9a8.json' because it is being used by another process.
Please check the value of the Environment Variable GOOGLE_APPLICATION_CREDENTIALS
Google.Apis.Auth.OAuth2.DefaultCredentialProvider.<CreateDefaultCredentialAsync>d__0.MoveNext() in c:\ApiaryDotnet\default\Src\GoogleApis.Auth.DotNet4\OAuth2\DefaultCredentialProvider.cs: line 95
System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
System.Threading.Tasks.Task`1.get_Result()
GoogleCloudSamples.AuthSample.CreateAuthorizedClient() in C:\users\root\workspace\dotnet-docs-samples\auth\Program.cs: line 38
AuthTest.Test.TestListBucketContents() in C:\users\root\workspace\dotnet-docs-samples\auth\test\Test.cs: line 46
I'm using Node implementation of Google Speech to Text API, but the lag time is too much --- 3-4 seconds in response time. Is this normal? Is there a way to get it to less than 2 seconds?
The samples for netcore on app engine flex all show running the apps in visual studio on a local windows machine. When the apps are deployed they are run on a debian8 linux container.
Although it is improving, the current state of cross platform support in netcore is not 100%. I've run into many issues moving code from windows to linux and had to implement workarounds. It would be helpful to show a sample of doing local development on a windows pc using the same linux containers that the app will be deployed under in the flex app engine.
This is relatively easy now with Docker for Windows and Docker tools for VS. If desired I can update a repo and submit a pull request.
dotnet-docs-samples/endpoints/getting-started/src/IO.Swagger/app.yaml
it should use the new aspnetcore runtime
Hi Google cloud team,
On textDetection sample don't work on Thai Language.
Can't translate on the message.
Question:
Thanks you
https://github.com/GoogleCloudPlatform/dotnet-docs-samples/tree/master/vision/api
I try to use this api and i got this error.
Status(StatusCode=Unauthenticated, Detail="Exception occured in metadata credentials plugin.")
ps. I have create credentials JSON file and set environment already.
I am testing google api streamimg speech recognition.
I opened this project https://github.com/GoogleCloudPlatform/dotnet-docs-samples/tree/master/speech/api/Recognize
and ran StreamingMicRecognizeAsync method from main. It was working fine.
But after 60 seconds or so it stopped recognizing audio from mic. I tried increasing the time in "ListenOptions.Seconds". It did not help.
did anyone face the same issue and find some workaround ?
Thanks.
It appears all of the samples provided for the flexible App Engine environment were created using "dotnet new" and as a result include a web.config
and .UseIISIntegration()
for Kestrel in the Program.cs
.
From what I can tell based on the docker images the App Engine sets the PORT environmental variable in the container which is then exposed via docker and then Kestrel is set to use this port using the ASPNETCORE_URLS environmental variable via ASPNETCORE_URLS=http://*:${PORT}
.
If this is the case and the web.config
and IIS integration are not needed, I suggest removing them as being in the samples may suggest some IIS dependency.
From the test log:
Test Settings: Default Test Settings
storage\api\test\test.csproj
Microsoft (R) Test Execution Command Line Tool Version 14.0.23107.0
Copyright (c) Microsoft Corporation. All rights reserved.
Loading bin\debug\test.dll...
Starting execution...
No tests to execute.
StreamingMicRecognizeAsync is not recognizing the live streaming audio spoken using microphone with laptop. Any setup needed for this?
hi, I followed each and every steps given in both readme docs. I set GOOGLE_APPLICATION_CREDENTIALS in to the environment variable of windows from System Properties\Advance system settings with path of it's json file location in my computer. I got the credential from console.cloud.google.com according to structured format. And finally, I built the project before start running. But once I run the project and set startup project as QuickStart Project, I got an Exeption at var speech = SpeechClient.Create(); in QuickStart.cs file. What I am doing wrong, I don't get it till now. Here is the details of exception:
"An unhandled exception of type 'System.InvalidOperationException' occurred in Google.Api.Gax.dll
Additional information: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information."
StackTrace: at Google.Api.Gax.TaskExtensions.WaitWithUnwrappedExceptions(Task task)
at Google.Api.Gax.TaskExtensions.ResultWithUnwrappedExceptions[T](Task`1 task)
at Google.Api.Gax.Grpc.ChannelPool.GetChannel(ServiceEndpoint endpoint)
at Google.Cloud.Speech.V1Beta1.SpeechClient.Create(ServiceEndpoint endpoint, SpeechSettings settings)
at GoogleCloudSamples.QuickStart.Main(String[] args) in D:\Drive-F\Study\Google Cloud Speech Recognition\dotnet-docs-samples-master\dotnet-docs-samples-master\speech\api\QuickStart\QuickStart.cs:line 30
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Hi.
I use Speech API.
I want to use RecognitionConfig.SpeechContext, but is required set SpeechContext type.
I search sample, but no sample found.
Now, SpeechContext.Phrases is gettable, but no settable.
is this have not been provided yet?
If not, please tell me a usage example.
Using the RecognitionConfig object for speech recognition, we have not found a way to set the properties in a SpeechContext object in C#. The Intellisense blocks us from setting any Phrases (or any other object) by only offering Read-Only properties (GETs). We have seen no way to write to these properties (SETs).
Here is the example from one of our attempts:
In this attempt, we were going to assign test to the SpeechContext as shown below:
Thank you!
As we know, google speech to text is in beta.
is it safe to use it in production? any suggestions?
There has been a long streak of failed pubsub tests. We need to make them handle eventual consistency. For example, this code:
CreateTopicMessage(topicId, _publisher);
//Pull the Message to confirm it is valid
PullResponse response = PullTopicMessage(subscriptionId, _subscriber);
Assert.False(IsEmptyResponse(response));
There is no guarantee that the message will be immediately available in the subscription. We need Eventually()
wrappers around this and similar code.
When I use Speech API in a hosted environment (Azure), I don't know the path to the credentials file in advance. I know that we can create a GoogleCredential instance from a file. But how do I use it when I create a SpeechClient instance? Would be great if you could provide a code example for this.
https://github.com/GoogleCloudPlatform/dotnet-docs-samples/blob/master/kms/api/Program.cs
Let's wrap them less than 80 characters so users don't have to horizontally scroll when looking an the snippet in the docs.
sln
and load itPackage 'NAudio 1.8.4' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.0'. This package may not be fully compatible with your project.
Please see this issue on NAudio as follows. Please see here.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.