Typed interface to call the Google Cloud Natural Language gRPC API to analyze sentiment, entities and content of text.
Google Cloud Natural Language extracts insights from text, including sentiment, entities and content categories. The gRPC API is exposed through the google.cloud.language.v1.LanguageService service, reached at language.googleapis.com:443 over TLS, with the main methods AnalyzeSentiment, AnalyzeEntities and ClassifyText.
Requests are built with typed classes such as TsgcGRPCLanguageAnalyzeSentimentRequest and TsgcGRPCLanguageAnalyzeEntitiesRequest, each carrying a Document whose DocType is set to PLAIN_TEXT together with the text content to analyze.
The example below authenticates with a service-account JWT, wires a TsgcGRPCClient over a TsgcHTTP2Client to the Natural Language host, sets the authorization Bearer metadata and calls AnalyzeSentiment on a plain-text sentence:
oHTTP2 := TsgcHTTP2Client.Create(nil);
oHTTP2.Host := 'language.googleapis.com';
oHTTP2.Port := 443;
oHTTP2.TLS := True;
oGRPC := TsgcGRPCClient.Create(nil);
oGRPC.Client := oHTTP2;
// service-account JWT authentication
oGRPC.GoogleCloudOptions.JWT.KeyFile := 'service-account.json';
oGRPC.GoogleCloudOptions.JWT.API_Endpoint := 'https://language.googleapis.com/';
oGRPC.DefaultMetadata.AddValue('authorization', 'Bearer ' + oGRPC.GoogleCloudOptions.JWT.Token);
// build the typed request and call the method
oRequest := TsgcGRPCLanguageAnalyzeSentimentRequest.Create;
try
oRequest.Document.DocType := 'PLAIN_TEXT';
oRequest.Document.Content := 'I really love this product, it works great!';
oResponse := oGRPC.Call('google.cloud.language.v1.LanguageService', 'AnalyzeSentiment', oRequest.ToBytes);
ShowMessage(oResponse.DataString);
finally
oRequest.Free;
end;
| Name | Description |
|---|---|
| AnalyzeSentiment | Analyzes the overall sentiment of a document, returning a score and magnitude. |
| AnalyzeEntities | Detects named entities (people, places, organizations) in a document. |
| ClassifyText | Classifies a document into content categories. |
A working sample is available in the demo folder Demos/21.GRPC/14.Natural_Language, which shows how to authenticate and analyze the sentiment of a text with the AnalyzeSentiment method.