Have you ever wondered how realtime
text translation works? Google, Microsoft Machine learning
algorithm is one of the best out there.
With the popularity of Google Home, Amazon’s Echo, Cortana and Alexa I’m sure you know how those home gadgets translates your voice and questions in realtime and gives you an answer.
Same way realtime text also works. As you know, companies have geo specific sites
to attract more local users. As an example, Google has lots of domestic sites like,
- https://www.google.co.in
- https://www.google.ca
- https://www.google.com and so on.
Text on those sites translate in realtime
to specific characters. Some examples are English to Chinese
, Latin to English
and so on.
You are at right place if you have any of below questions:
- Do I have Microsoft translator api Java example?
- How to try Microsoft Translator for free
- How to get started on Translator Text API – Azure
Cognitive Services
- Machine Translation – Microsoft Translator for Business Tutorial
In this tutorial we will go over below 3 sections:
- Sign up for Microsoft Azure
- Get Translator Text API key from Azure portal
- Use that API key in Java program to perform text translation
Section-1) Sing up for Microsoft Azure
- Go to: https://azure.microsoft.com/en-us/.
- Sign in using your Microsoft / Outlook ID.
- If you don’t have outlook.com ID then sign up for one.
Azure is one of the leading industry standard cloud provider
after Amazon AWS. It provides support for number of languages and frameworks.
Section-2) Get Translator Text API key
Step-1
- Go to https://portal.azure.com.
- Click on
Create a resource
from left navigation. - Search for
Translator Text
in search bar.
Step-2
On Next screen click on Create
button.
Step-3
On next screen, provide below all fields and click on Create
button
- Name: Crunchify_Translator_Service
- Subscription: Free Trial (if you are subscribing for 1st time)
- Pricing tier: Pay as you go (preferred)
- Resource Group: Crunchify_Services
- Resource Group location: West Central US
Above step will create new Resource under Type Cognitive Services
.
Step-4
- Click on
All resources
tab from left navigation - Click on
Crunchify_Translator_Service
Step-5
On next screen Overview
tab will give you all below details
- Resource group
- Status
- Location
- Subscription
- Subscription ID
- Tags
- API Type
- Pricing Tier
- Endpoint
- Keys
Take a look at Endpoint (Base URL) which we will use in our program:
https://api.cognitive.microsofttranslator.com
Step-6
Click on Show access keys
… and you will see two API Keys: KEY1
and KEY2
. Just save those keys and we will use those in below Java program.
Section-3) Use API key in Java program to perform text translation
Step-1
- Create class CrunchifyMicrosoftBingAzureTranslatorAPI.java
- In this tutorial we are using
OkHttpClient
to makePOST call
. There are number of ways we could make POST call as you see in Java.Net.URL and java.net.URLConnection. OkHttp
performs best when you create a singleOkHttpClient
instance and reuse it for all of your HTTP calls. Logic is very simple. Each client holds its own connection pool and thread pools. Reusing connections and threads reduces latency and saves memory.- So it’s not advisable to keep creating new client each time. Just
OkHttpClient crunchifyClient = new OkHttpClient();
once and you use that through out your project.
- So it’s not advisable to keep creating new client each time. Just
- Once we create client, we will create POST request using RequestBody, MediaType, Request and Response objects.
newCall
prepares therequest
to be executed at some point in the future.- Once we get response we will just beautify response and will print on Eclipse console.
CrunchifyMicrosoftBingAzureTranslatorAPI.java
Please make sure to update Key value for microsoftBingAPIKey
.
package crunchify.com.tutorial; import java.io.IOException; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; /** * @author Crunchify.com * Version: 1.1 * Microsoft Azure Translator Text API v3.0 Java Tutorial * */ public class CrunchifyMicrosoftBingAzureTranslatorAPI { String microsoftBingAPIKey = "6380c68dff384955ae2ca406e989867a"; String crunchifyTranslatorURL = "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=de,it,ja,es,fr,hi,zh-Hans,te,ar,ta"; // Factory for calls, which can be used to send HTTP requests and read their responses. OkHttpClient crunchifyClient = new OkHttpClient(); public static void main(String[] args) { try { CrunchifyMicrosoftBingAzureTranslatorAPI crunchifyRequest = new CrunchifyMicrosoftBingAzureTranslatorAPI(); String crunchifyResponse = crunchifyRequest.CrunchifyMakePostCall(); log(crunchifyPrettyJSONUtility(crunchifyResponse)); } catch (Exception e) { System.out.println(e); } } // This function performs a simple POST call to Microsoft Translator Text Endpoint. public String CrunchifyMakePostCall() throws IOException { // An RFC 2045 Media Type, appropriate to describe the content type of an HTTP request or response body. MediaType crunchifyMT = MediaType.parse("application/json"); RequestBody crunchifyBody = RequestBody.create(crunchifyMT, "[{\n\t\"Text\": \"This is Crunchify! How are you? This is very simple Bing/Microsoft Translator Text v3.0 API tutorial.\"\n}]"); log("Input Data ======> \nThis is Crunchify! How are you? This is very simple Bing/Microsoft Translator Text v3.0 API tutorial. \n"); // An HTTP request. Instances of this class are immutable if their body is null or itself immutable. Request crunchifyRequest = new Request.Builder().url(crunchifyTranslatorURL).post(crunchifyBody) .addHeader("Ocp-Apim-Subscription-Key", microsoftBingAPIKey).addHeader("Content-type", "application/json").build(); // An HTTP response. Instances of this class are not immutable: the response body is a one-shot value that may be consumed only once and then closed. // All other properties are immutable. Response crunchifyResponse = crunchifyClient.newCall(crunchifyRequest).execute(); String crunchifyResult = crunchifyResponse.body().string(); return crunchifyResult; } // This function beautify the json response which we get from Translator API endpoint public static String crunchifyPrettyJSONUtility(String json_text) { // A parser to parse Json into a parse tree of JsonElements JsonParser crunchifyParser = new JsonParser(); // A class representing an element of Json. It could either be a JsonObject, a JsonArray, a JsonPrimitive or a JsonNull. JsonElement crunchifyJson = crunchifyParser.parse(json_text); // This is the main class for using Gson. Gson is typically used by first constructing a Gson instance and then invoking toJson(Object) or // fromJson(String, Class) methods on it. Gson instances are Thread-safe so you can reuse them freely across multiple threads. Gson crunchifyGson = new GsonBuilder().setPrettyPrinting().create(); // return simple JSON. Converts a tree of JsonElements into its equivalent JSON representation. String beautifyResponse = crunchifyGson.toJson(crunchifyJson); return "Output Data ======> \n" + beautifyResponse; } // Simple Log Utility private static void log(String crunchifyPrettyJSONUtility) { System.out.println(crunchifyPrettyJSONUtility); } }
- Here we are converting Text from English
- Germany
- Italian
- Japanese
- Spanish
- French
- Chinese
- Telugu
- Arabic
- Tamil
Step-2 Execute program and check out result
Just execute above program in Eclipse IDE as Java application and you will see below translation result.
Input Data ======> This is Crunchify! How are you? This is very simple Bing/Microsoft Translator Text v3.0 API tutorial. Output Data ======> [ { "detectedLanguage": { "language": "en", "score": 1.0 }, "translations": [ { "text": "Das ist Crunchify! Wie geht es dir? Dies ist sehr einfach Bing/Microsoft Translator Text v3.0 API-Tutorial.", "to": "de" }, { "text": "Questo è Crunchify! Come stai? Questo è molto semplice Bing/Microsoft Translator text v 3.0 API tutorial.", "to": "it" }, { "text": "これは Crunchify!お元気ですか。これは非常に簡単な Bing/マイクロソフトの翻訳テキスト v 3.0 API チュートリアルです。", "to": "ja" }, { "text": "¡ Este es Crunchify! ¿Cómo estás? Esto es muy simple Bing/Microsoft traductor texto v 3.0 API tutorial.", "to": "es" }, { "text": "C\u0027est Crunchify! Comment vas-tu? Ceci est très simple Bing/Microsoft Translator Text v 3.0 API Tutorial.", "to": "fr" }, { "text": "यह Crunchify है! तुम कैसे हो? यह बहुत सरल है बिंग/Microsoft अनुवादक पाठ v 3.0 एपीआई ट्यूटोरियल ।", "to": "hi" }, { "text": "我是克伦基菲!你好吗?这是非常简单的 bang\\ 微软翻译文本 v3.0 api 教程。", "to": "zh-Hans" }, { "text": "ఇది క్రూచిఫై! మీరు ఎలా ఉన్నారు? ఇది చాలా సరళమైన Bing/మైక్రోసాఫ్ట్ ట్రాన్స్ లేటర్ టెక్స్ట్ v 3.0 API ట్యుటోరియల్.", "to": "te" }, { "text": "هذا هو الجرش! كيف حالك؟ هذا هو بسيط جدا بينغ/مايكروسوفت مترجم النص v3.0 API البرنامج التعليمي.", "to": "ar" }, { "text": "இது Crunchify! எப்படி இருக்கிறாய்? இது மிகவும் எளிமையான Bing/Microsoft மொழிபெயர்ப்பாளர் உரை v 3.0 API பயிற்சி.", "to": "ta" } ] } ]
And you are all set.
How to test Microsoft Translator Text API using Linux CURL Command?
Just execute below cURL command and you will see result in Mac OS X terminal window.
Here is a same screenshot about below test and result.
bash-3.2$ curl -X POST "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from=en&to=de,it,ja,es,fr,hi,zh-Hans,te,ar,ta" -H "Ocp-Apim-Subscription-Key: 6380c68dff384955ae2ca406e989867a" -H "Content-Type: application/json" -d '[{"Text":"I am an Engineer by profession, Blogger by passion & Founder of Crunchify, LLC, the largest free blogging and technical resource site for beginners."}]' | json_pp % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 2634 100 2473 100 161 3304 215 --:--:-- --:--:-- --:--:-- 3301 [ { "translations" : [ { "to" : "de", "text" : "Ich bin ein Ingenieur von Beruf, Blogger von Leidenschaft & Gründer von Crunchify, LLC, die größte kostenlose Blogging und technische Ressource Website für Anfänger." }, { "to" : "it", "text" : "Sono un ingegnere di professione, blogger di passione & fondatore di Crunchify, LLC, il più grande sito di blogging gratuito e risorse tecniche per i principianti." }, { "to" : "ja", "text" : "私は初心者のための最大の無料ブログや技術リソースサイト、LLC、Crunchify の情熱 & 創設者によって専門家、ブロガーによってエンジニアです。" }, { "text" : "Soy Ingeniero de profesión, blogger por pasión y fundador de Crunchify, LLC, el mayor sitio de blogs gratuitos y recursos técnicos para principiantes.", "to" : "es" }, { "to" : "fr", "text" : "Je suis un ingénieur par profession, Blogger par la passion et le fondateur de Crunchify, LLC, le plus grand blog gratuit et le site de ressources techniques pour les débutants." }, { "to" : "hi", "text" : "मैं पेशे से एक इंजीनियर हूं, जुनून द्वारा ब्लॉगर Crunchify, LLC, सबसे बड़ा मुक्त ब्लॉगिंग और तकनीकी संसाधन के लिए शुरुआती साइट के संस्थापक ।" }, { "to" : "zh-Hans", "text" : "我是一个工程师的职业, 博客的激情 & 创始人克朗奇菲, 有限责任公司, 最大的免费博客和技术资源网站的初学者。" }, { "to" : "te", "text" : "నేను వృత్తిపరంగా ఒక ఇంజినీర్ ని, బ్లాగర్ ని అభిరుచి ద్వారా, crunchify యొక్క వ్యవస్థాపకుడు, LLC, ప్రారంభ కోసం అతిపెద్ద ఉచిత బ్లాగింగ్ మరియు సాంకేతిక వనరుల సైట్." }, { "to" : "ar", "text" : "انا مهندس من قبل المهنة ، مدون من قبل العاطفة ومؤسس الجرش ، LLC ، أكبر المدونات الحرة وموقع الموارد التقنية للمبتدئين." }, { "text" : "நான் தொழில் ஒரு பொறியாளர், & நிறுவனர் Crunchify, ஒரு பெரிய இலவச வலைப்பூ மற்றும் தொடக்க தொழில்நுட்ப வள தளம்.", "to" : "ta" } ] } ]
I hope this tutorial helps you implement Microsoft / Bing / Azure’s Translator Text API
to your Project easily. We are using v3.0 Translator
Text specification in our program. As usual let me know for any question.