Now a days i am implementing sentiment analysis through google cloud library,my code is
string text = "Feeling Not Well";
var client = LanguageServiceClient.Create();
var response = client.AnalyzeSentiment(new Document()
{
Content = text,
Type = Document.Types.Type.PlainText
});
var sentiment = response.DocumentSentiment;
var Score = sentiment.Score;
var magnitude = sentiment.Magnitude;
but it gives an error on
var client = LanguageServiceClient.Create();.
the error is
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.
please give me solution
You can either use
gcloud auth application-default login
from the command line (assuming you have the Cloud SDK installed), or generate and download a service account JSON file and then set the GOOGLE_APPLICATION_CREDENTIALS environment variable to point to that file.
The Create method call will first check the environment variable, and then look for application default credentials from gcloud if the environment variable isn't set.
Basically, the credential options are:
Explicitly create one from a service account file, e.g. GoogleCredential.FromStream(stream) and use that to create a Channel which you can pass into Create, as described in the FAQ
Call create without any arguments (or passing in null) in which case:
If you've set the GOOGLE_APPLICATION_CREDENTIALS environment variable, it is assumed that's where the service account JSON file is
Otherwise, if you've run gcloud auth application-default login those credentials will be used
Otherwise, if you're running on Google Cloud Platform (e.g. Compute Engine or AppEngine Flexible) you will get the default credentials for the project
Otherwise, the call will fail
Additionally, you can use the Document.FromPlainText call to simplify your code:
string text = "Feeling Not Well";
var client = LanguageServiceClient.Create();
var response = client.AnalyzeSentiment(Document.FromPlainText(text));
var sentiment = response.DocumentSentiment;
var Score = sentiment.Score;
var magnitude = sentiment.Magnitude;
Related
I am attempting to connect a local .NET Core project to a Firebase project. I am using the Google documentation at https://cloud.google.com/dotnet/docs/reference/Google.Cloud.Firestore/latest:
private async Task<Dictionary<string, object>> GetData()
{
string projectId = "My-Project";
FirestoreDb db = FirestoreDb.Create(projectId);
Dictionary<string, object> documentDictionary = new Dictionary<string, object>();
...
}
When it hits the call to create an instance of the project (FirestoreDb.Create(projectId)), I receive this error:
Error: System.InvalidOperationException: 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.
at Google.Apis.Auth.OAuth2.DefaultCredentialProvider.CreateDefaultCredentialAsync()
I have exported the service account from Firebase into a JSON file, generating a private key and saving it locally:
I have added the path of the key file to this JSON file in an environment variable:
However, I continue to get the error.
There is one way I have been able to authenticate, and that was using the example code at https://cloud.google.com/docs/authentication/production:
public object AuthExplicit(string projectId, string jsonPath) {
var credential = GoogleCredential.FromFile(jsonPath);
var storage = StorageClient.Create(credential);
var buckets = storage.ListBuckets(projectId);
foreach (var bucket in buckets)
{
Console.WriteLine(bucket.Name);
}
return null;
}
However, I don't know how (or if it's possible) to link that authentication code with Firebase in order to retrieve my data.
Is there any guidance you can provide so I can properly authenticate and pull my data?
The missing step was calling the FirebaseApp.Create() method, as described in the Firebase authentication documentation.
I modified my application to add that method before the call to FirestoreDb.Create(), and that did it. Here is the modified code:
private async Task<Dictionary<string, object>> GetData() {
string projectId = "My-Project";
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.GetApplicationDefault(),
});
FirestoreDb db = FirestoreDb.Create(projectId);
Dictionary<string, object> dd = new Dictionary<string, object>();
...
}
This link provides a reason why this error is being caused.
I – If GOOGLE_APPLICATION_CREDENTIALS is SET and it uses the service
account file path using the value associated with the above
Environment variable GOOGLE_APPLICATION_CREDENTIALS
II – If GOOGLE_APPLICATION_CREDENTIALS is not SET, then the following preferences are set:
ADC uses a service account file that is running the code.
Otherwise, if a service account also does exist, then ADC uses the default service account that Compute Engine, Google Kubernetes Engine, App Engine, and Cloud Functions provide.
Try to debug the application locally by doing the following:
If you already have a service account created, then it applies to an application instead of an individual user. You need to authenticate a service account while accessing your IAP-secured resources.
Please make sure to set Environment Variable GOOGLE_APPLICATION_CREDENTIALS with the secured key JSON file path.
Example
C#:
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "secured-service-account.json");
I am using Google.Cloud.Vision.V1, Version=2.0.0.0 and the following below code from Google Vision API specify JSON file
using Google.Apis.Auth.OAuth2;
using Google.Cloud.Vision.V1;
using Grpc.Auth;
using Grpc.Core;
var credential = GoogleCredential.FromFile("VisionProject.json");
var channel = new Grpc.Core.Channel(ImageAnnotatorClient.DefaultEndpoint.ToString(), credential.ToChannelCredentials());
var client = ImageAnnotatorClient.Create(channel);
But its shows me this error No overload for method 'ImageAnnotatorClient.Create' takes 1 arguments.
I have found similar code in documentation https://googleapis.github.io/google-cloud-dotnet/docs/Google.Cloud.Vision.V1P2Beta1/api/Google.Cloud.Vision.V1P2Beta1.ImageAnnotatorClient.html
But for some reason, it's not working( unable to see the overload)
It seems that you are using newer version of API. Docs state that now authentication is set up(when needed) via environment variable:
Otherwise, the simplest way of authenticating your API calls is to download a service account JSON file then set the GOOGLE_APPLICATION_CREDENTIALS environment variable to refer to it. The credentials will automatically be used to authenticate. See the Getting Started With Authentication guide for more details.
So you can do something like this:
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "PathTo_VisionProject.json");
var client = ImageAnnotatorClient.Create();
Or set this environment variable some other way.
While setting the environment variable is certainly a simple way of specifying which service account file to use, it's not the only one. You can use the builder to specify the path very easily:
var client = new ImageAnnotatorClientBuilder
{
CredentialsPath = "VisionProject.json"
}.Build();
Another solution if you do not have access to the JSON file directly and you want to stay close to what you previously did with the GoogleCredential and Channel creation is something like:
var credential = GoogleCredential.FromFile("VisionProject.json");
// or if you have access to the content only
// var credential = GoogleCredential.FromJson(json);
var client = await new ImageAnnotatorClientBuilder
{
Endpoint = ImageAnnotatorClient.DefaultEndpoint,
ChannelCredentials = credential.ToChannelCredentials()
}.BuildAsync();
I am creating a SAS key in my C# code, like below.
string returnValue = String.Empty;
// Create a new access policy for the account with the following properties:
SharedAccessAccountPolicy policy = new SharedAccessAccountPolicy()
{
Permissions = SharedAccessAccountPermissions.Read | SharedAccessAccountPermissions.Write | SharedAccessAccountPermissions.Create,
Services = SharedAccessAccountServices.Blob,
ResourceTypes = SharedAccessAccountResourceTypes.Container | SharedAccessAccountResourceTypes.Object,
SharedAccessExpiryTime = DateTime.UtcNow.AddHours(10),
Protocols = SharedAccessProtocol.HttpsOrHttp
};
// Create new storage credentials using the SAS token.
ExecuteWithExceptionHandling(
() =>
{
returnValue = storageAccount.GetSharedAccessSignature(policy);
});
return returnValue;
This code generates a key properly. But when I try to use this key in Azure Storage Explorer, I get an error saying Inadequate resource type access. At least service-level ('s') access is required.
When I try to use this key from javascript to create a container, I get an error saying Refused to set unsafe header "user-agent" in azure-storage-blob.min.js file (came from azure storage api by microsoft).
I have added the create permission in SharedAccessAccountPolicy, but the key generated is not working for some reason.
Edit:
Javascript code to create blobservice.
var blobService = AzureStorage.Blob.createBlobServiceWithSas(blobUri, $("#SASToken").val());
blobService.createContainerIfNotExists(folderID, function (error, result) {
if (error) {
return false;
} else {
return true;
}
});
Edit:
Below is a screenshot of the azure portal, where I tried to generate manual token. Even that token has ss=b in it instead of sr=b as per the document.
I tried the token I generated manually. And the JS code still says Refused to set unsafe header "user-agent".
Apparently it is an issue with the damn js file provided by Azure.
https://github.com/Azure/azure-storage-node/issues/463
Here is an open ticket about it.
Anyway, for now, I have added a condition to ensure header is not added. If the code still fails, I will create a different question.
I think, within 2 days, I can just take the latest update of the Azure's js and this should fix itself. Still in case, anyone needs a quick fix, here is the code change done by me.
if (e[0] != 'user-agent'){ s.setRequestHeader(e[0],e[1])}}
instead of s.setRequestHeader(e[0],e[1])}
It is only a temporary fix. Best option is still to update to version 2.10.101 or higher for azure storage js file.
I am trying to use google cloud vision api text detection.
using System;
using Google.Apis.Auth.OAuth2;
using Google.Cloud.Vision.V1;
using Google.Api.Gax.Grpc;
namespace blablabla
{
class Program
{
static void Main(string[] args)
{
string filePath = #"D:\Manisha\Pictures\1.png";
var image = Image.FromFile(filePath);
var client = ImageAnnotatorClient.Create();
var response = client.DetectText(image);
foreach (var annotation in response)
{
if (annotation.Description != null)
Console.WriteLine(annotation.Description);
}
Console.ReadLine();
}
}
}
I am getting the following error at
"var client = ImageAnnotatorClient.Create();"
"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."
I have set the GOOGLE_APPLICATION_CREDENTIALS to the json file path.
Where am i actually going wrong. Am i missing some important steps?
There are a few things you could check in this situation.
Is the value of GOOGLE_APPLICATION_CREDENTIALS correct?
Can your application access that environment variable?
Does your app/Visual Studio need to be restarted?
What is the value of credential?
One way to check the credentials that the SDK is using is the following.
var credential = GoogleCredential.GetApplicationDefault();
This appears to be a way to get an instance of the credentials, in case you wanted to test it. It's not necessary for the ImageAnnotatorClient per se.
I have set up a basic C# application to run a PageSpeed test on a website that I specify using the Google.Apis.Pagespeedonline.v2 nuget package.
The set up is simple enough and I have a variable that I can specify the url which is then past in to the Service
// Create the service.
var service = new PagespeedonlineService(new BaseClientService.Initializer
{
ApplicationName = "PageSpeed Sample",
ApiKey = "[API_KEY_HERE]"
});
var url = "URL_TO_TEST";
// Run the request.
var result = await service.Pagespeedapi.Runpagespeed(url).ExecuteAsync();
The problem being the .Runpagespeed method ONLY accepts URL. I need to be able to specify, at minimum, the 'Mobile' strategy so I can obtain scores for both Desktop and Mobile. I know this is possible in other libraries but seems to be missing in .NET. Is anybody aware of a way to do this using the .NET library? In the reference documentation it implies that the method accepts further optional parameters but it does not in the code.
Pagespeedapi: runpagespeed has an optional value called strategy
strategy string The analysis strategy to use
Acceptable values are: "desktop": Fetch and analyze the URL for
desktop browsers "mobile": Fetch and analyze the URL for mobile
devices
Example:
var request = service.Pagespeedapi.Runpagespeed(url);
request.Strategy = Google.Apis.Pagespeedonline.v2.PagespeedapiResource.RunpagespeedRequest.StrategyEnum.Mobile;
var results = request.Execute();