Azure Translation Service
Picture from Alex Knight @ https://www.pexels.com/
As of today, there are no clients for Azure Translation Service, hence requests have to be made through HTTP calls. I am referencing this tutorial however, I need to make changes to the path of the URL.
1. Initialize Setup
First and foremost, I need to do the following
- Create a resource group
- Create Azure Cognitive Translation Services in this resource group.
- Copy the key, endpoint, and location values as shown below.
For simplicity, I have values as environment parameters, AZURE_TRANSLATOR_KEY, AZURE_TRANSLATOR_ENDPOINT, and AZURE_TRANSLATOR_LOC.
2. Code
FYI, I am using MacOSX and Typescript.
import axios from "axios"; import { v4 } from "uuid"; import * as process from "process"; const AZURE_TRANSLATOR_KEY = process.env["AZURE_TRANSLATOR_KEY"]; const AZURE_TRANSLATOR_ENDPOINT = process.env["AZURE_TRANSLATOR_ENDPOINT"]; const AZURE_TRANSLATOR_LOC = process.env["AZURE_TRANSLATOR_LOC"]; const translate = async (text: string, lang: string): Promise<any> => { const headers = { "Ocp-Apim-Subscription-Key": AZURE_TRANSLATOR_KEY, "Ocp-Apim-Subscription-Region": AZURE_TRANSLATOR_LOC, "Content-type": "application/json", "X-ClientTraceId": v4(), }; return new Promise((resolve, reject) => { axios(`${AZURE_TRANSLATOR_ENDPOINT}translator/text/v3.0/translate`, { method: "POST", params: { to: lang, }, headers, data: JSON.stringify([{ Text: text }]), }).then((res) => { if (res.status === 200) { resolve(res.data[0]); } else { reject(res.data); } }); }); }; (async () => { console.log(await translate("hello", "ja")); })();
output
{ detectedLanguage: { language: 'en', score: 1 }, translations: [ { text: 'こんにちは', to: 'ja' } ] }
I also tested with
console.log(await translate("The weather is good and air is fresh.", "zh"));
and got
{
detectedLanguage: { language: 'en', score: 1 },
translations: [ { text: '天气好,空气清新。', to: 'zh-Hans' } ]
}
3. Conclusion
All and all, easy to code in Typescript or any other programming language to make HTTPS calls. I will test with longer statements (or paragraphs) in other languages.
Comments
Post a Comment