Doing Google's Natural Language ClassifyText() in ASP.NET
Bruce Axtens
Posted on October 11, 2019
I had a profoundly difficult time installing Google.Cloud.Language.V1 into our ASP.NET site yesterday and today. I used the NuGet route. It didn't work. A DLL, I think it was Grpc.Code.Api
refused to install properly.
So I wrote a wrapper DLL and installed it as a Reference. In that process all the relevant Google DLLs were copied in. I just needed to manually include grpc_csharp_ext.x64.dll
and grpc_csharp_ext.x86.dll
A JSON credentials file is provided by Google when you request the right to do Natural Language calls. I copied that to the server. Also an environment variable (GOOGLE_APPLICATION_CREDENTIALS) needs to be created on the server, its value being the path to the JSON credentials file. Google.Cloud.Language.V1 does all the authorization automagically in the background.
This is the wrapper, called Classification (now available on Github).
using Google.Cloud.Language.V1;
using Newtonsoft.Json;
using System;
namespace Classification
{
internal class JsonResponse
{
public string Error { get; set; }
public object Cargo { get; set; }
}
public class Classifier
{
public static string Classify(string html)
{
var document = new Document
{
Type = Document.Types.Type.Html,
Content = html
};
string error;
object cargo;
try
{
var client = LanguageServiceClient.Create();
ClassifyTextResponse response = client.ClassifyText(document);
cargo = response.Categories;
error = null;
}
catch (Exception e)
{
error = e.Message;
cargo = string.Empty;
}
return JsonConvert.SerializeObject(new JsonResponse()
{
Error = error,
Cargo = cargo
});
}
}
}
I hand over the HTML of the website to that, and I get back a JSON string. This is what I get back from the HTML of SIL
{"Error":null,"Cargo":[{"Name":"/Reference/Language Resources","Confidence":0.56}]}
This works for most sites, except one (so far) that seems to dislike me reading the site source with RestSharp. I'm going to have a go with BrowseSharp.
PLEASE NOTE
I haven't included the source to the ASHX handler file that uses the wrapper. That's left as an exercise for the reader.
Posted on October 11, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.