Sentiment analysis through google cloud Library

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

Jon Skeet
people
quotationmark

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;

people

See more on this question at Stackoverflow