Spread the love
In this tutorial we are going to see how to use the Translator Text API to detect Language from Text.
Prerequisites
- To run the sample code you must have an edition of Visual Studio installed.
- You will need the Json.NET NuGet package.
- You will need the .NET SDK installed in your machine
- You will need an Azure Cognitive Services account with a Translator Text resource. If you don’t have an account, you can use the free trial to get a subscription key.
Create your Project
To create an application to translate your text follow the steps below:
- Create a .NET Core Console Application in Visual Studio 2017
- Add the JSON.net nuget package
- Install-Package Newtonsoft.Json
- Add the following code under Program
- static void Identify()
- {
- string host = "https://api.cognitive.microsofttranslator.com";
- string route = "/detect?api-version=3.0";
- string subscriptionKey = "enter your subscription key";
- System.Object[] body = new System.Object[] { new { Text = @"Ola, tudo bem?" } };
- var requestBody = JsonConvert.SerializeObject(body);
- using (var client = new HttpClient())
- using (var request = new HttpRequestMessage())
- {
- request.Method = HttpMethod.Post;
- request.RequestUri = new Uri(host + route);
- request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
- request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
- var response = client.SendAsync(request).Result;
- var jsonResponse = response.Content.ReadAsStringAsync().Result;
- Console.WriteLine(jsonResponse);
- Console.WriteLine("Press any key to continue.");
- }
- }
- static void Main(string[] args)
- {
- Identify();
- Console.ReadLine();
- }
- }
- Replace your subscription key here: string subscriptionKey = “enter your subscription key”;
- Add here the text you want to be translated System.Object[] body = new System.Object[] { new { Text = @”Ola, tudo bem?” } }; Document size must be under 5,000 characters per document, and you can have up to 1,000 items (IDs) per collection.
- Run the Program
Get Results
The result is in the following format. That’s it, we have identified the correct Language (Portuguese)! A positive score of 1.0 expresses the highest possible confidence level of the analysis
- {
- "documents": [
- {
- "id": "1",
- "detectedLanguages": [
- {
- "name": "Portuguese",
- "iso6391Name": "pt",
- "score": 1
- }
- ]
- }
- }
You can find the complete source code in my Github in this repository in the LanguageIdentify Project.