{"id":724,"date":"2021-11-24T02:08:34","date_gmt":"2021-11-24T02:08:34","guid":{"rendered":"http:\/\/192.168.8.123\/?p=724"},"modified":"2022-02-18T16:44:23","modified_gmt":"2022-02-18T16:44:23","slug":"microsoft-azure-natural-language-processing-translate-text","status":"publish","type":"post","link":"https:\/\/exceedthecloud.com\/?p=724","title":{"rendered":"Microsoft Azure Natural Language Processing: Translate Text"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">The <strong>Translator<\/strong> service is a cognitive service that enables you to translate text between languages.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, suppose a travel agency wants to examine hotel reviews that have been submitted to the company&#8217;s web site, standardizing on English as the language that is used for analysis. By using the Translator service, they can determine the language each review is written in, and if it is not already English, translate it from whatever source language it was written in into English.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Prerequisites for this labs : <a rel=\"noreferrer noopener\" href=\"https:\/\/azure.microsoft.com\/en-us\/free\/\" target=\"_blank\">Azure Account<\/a> \/ <a rel=\"noreferrer noopener\" href=\"http:\/\/192.168.8.123\/index.php\/2021\/11\/20\/setting-up-windows-10-environment-for-ai-apps-with-azure-cognitive-services\/\" target=\"_blank\">Setting up Windows 10 environment for AI Apps with Azure Cognitive Services<\/a><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Clone the repository for this course<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you have already cloned <strong>AI-102-AIEngineer<\/strong> code repository to the environment where you&#8217;re working on this lab, open it in Visual Studio Code; otherwise, follow these steps to clone it now.<\/p>\n\n\n\n<ul class=\"wp-block-list\" type=\"1\"><li>Start Visual Studio Code.<\/li><li>Open the palette (SHIFT+CTRL+P) and run a <strong>Git: Clone<\/strong> command to clone the https:\/\/github.com\/MicrosoftLearning\/AI-102-AIEngineer repository to a local folder (it doesn&#8217;t matter which folder).<\/li><li>When the repository has been cloned, open the folder in Visual Studio Code.<\/li><li>Wait while additional files are installed to support the C# code projects in the repo.<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note<\/strong>: If you are prompted to add required assets to build and debug, select <strong>Not Now<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Provision a Cognitive Services resource<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you don&#8217;t already have one in your subscription, you&#8217;ll need to provision a <strong>Cognitive Services<\/strong> resource.<\/p>\n\n\n\n<ul class=\"wp-block-list\" type=\"1\"><li>Open the Azure portal at <a href=\"https:\/\/portal.azure.com\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/portal.azure.com<\/a>, and sign in using the Microsoft account associated with your Azure subscription.<\/li><li>Select the <strong>\uff0bCreate a resource<\/strong> button, search for <em>cognitive services<\/em>, and create a <strong>Cognitive Services<\/strong> resource with the following settings:<ul><li><strong>Subscription<\/strong>: <em>Your Azure subscription<\/em><\/li><li><strong>Resource group<\/strong>: <em>Choose or create a resource group (if you are using a restricted subscription, you may not have permission to create a new resource group &#8211; use the one provided)<\/em><\/li><li><strong>Region<\/strong>: <em>Choose any available region<\/em><\/li><li><strong>Name<\/strong>: <em>Enter a unique name<\/em><\/li><li><strong>Pricing tier<\/strong>: Standard S0<\/li><\/ul><\/li><li>Select the required checkboxes and create the resource.<\/li><li>Wait for deployment to complete, and then view the deployment details.<\/li><li>When the resource has been deployed, go to it and view its <strong>Keys and Endpoint<\/strong> page. You will need one of the keys and the location in which the service is provisioned from this page in the next procedure.<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Prepare to use the Translator service<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this exercise, you&#8217;ll complete a partially implemented client application that uses the Translator REST API to translate hotel reviews.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note<\/strong>: You can choose to use the API from either <strong>C#<\/strong> or <strong>Python<\/strong>. In the steps below, perform the actions appropriate for your preferred language.<\/p>\n\n\n\n<ul class=\"wp-block-list\" type=\"1\"><li>In Visual Studio Code, in the <strong>Explorer<\/strong> pane, browse to the <strong>06-translate-text<\/strong> folder and expand the <strong>C-Sharp<\/strong> or <strong>Python<\/strong> folder depending on your language preference.<\/li><li>View the contents of the <strong>text-translation<\/strong> folder, and note that it contains a file for configuration settings:<ul><li><strong>C#<\/strong>: appsettings.json<\/li><li><strong>Python<\/strong>: .env<\/li><\/ul><\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Open the configuration file and update the configuration values it contains to include an authentication <strong>key<\/strong> for your cognitive services resource, and the <strong>location<\/strong> where it is deployed (not the endpoint) &#8211; you should copy both of these from the <strong>keys and Endpoint<\/strong> page for your cognitive services resource. Save your changes.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large is-style-default\"><img decoding=\"async\" src=\"https:\/\/exceedthecloud.com\/wp-content\/uploads\/2022\/02\/img1-6-2.png\" alt=\"\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\" type=\"1\"><li>Note that the <strong>text-translation<\/strong> folder contains a code file for the client application:<ul><li><strong>C#<\/strong>: Program.cs<\/li><li><strong>Python<\/strong>: text-translation.py<\/li><\/ul><\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Open the code file and examine the code it contains.<\/p>\n\n\n\n<ul class=\"wp-block-list\" type=\"1\" start=\"2\"><li>In the <strong>Main<\/strong> function, note that code to load the cognitive services key and region from the configuration file has already been provided. The endpoint for the translation service is also specified in your code.<\/li><li>Right-click the <strong>text-translation<\/strong> folder, open an integrated terminal, and enter the following command to run the program:<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>C#<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>dotnet run<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Python<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>python text-translation.py<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\" type=\"1\" start=\"4\"><li>Observe the output as the code should run without error, displaying the contents of each review text file in the <strong>reviews<\/strong> folder. The application currently doesn&#8217;t make use of the Translator service. We&#8217;ll fix that in the next procedure.<\/li><\/ul>\n\n\n\n<figure class=\"wp-block-image size-large is-style-default\"><img decoding=\"async\" src=\"https:\/\/exceedthecloud.com\/wp-content\/uploads\/2022\/02\/img2-6.png\" alt=\"\"\/><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Detect language<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The Translator service can automatically detect the source language of text to be translated, but it also enables you to explicitly detect the language in which text is written.<\/p>\n\n\n\n<ul class=\"wp-block-list\" type=\"1\"><li>In your code file, find the <strong>GetLanguage<\/strong> function, which currently returns &#8220;en&#8221; for all text values.<\/li><li>In the <strong>GetLanguage<\/strong> function, under the comment <strong>Use the Translator detect function<\/strong>, add the following code to use the Translator&#8217;s REST API to detect the language of the specified text, being careful not to replace the code at the end of the function that returns the language:<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>C#<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Use the Translator detect function\nobject&#91;] body = new object&#91;] { new { Text = text } };\nvar requestBody = JsonConvert.SerializeObject(body);\nusing (var client = new HttpClient())\n{\n    using (var request = new HttpRequestMessage())\n    {\n        \/\/ Build the request\n        string path = \"\/detect?api-version=3.0\";\n        request.Method = HttpMethod.Post;\n        request.RequestUri = new Uri(translatorEndpoint + path);\n        request.Content = new StringContent(requestBody, Encoding.UTF8, \"application\/json\");\n        request.Headers.Add(\"Ocp-Apim-Subscription-Key\", cogSvcKey);\n        request.Headers.Add(\"Ocp-Apim-Subscription-Region\", cogSvcRegion);\n\n        \/\/ Send the request and get response\n        HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);\n        \/\/ Read response as a string\n        string responseContent = await response.Content.ReadAsStringAsync();\n\n        \/\/ Parse JSON array and get language\n        JArray jsonResponse = JArray.Parse(responseContent);\n        language = (string)jsonResponse&#91;0]&#91;\"language\"]; \n    }\n}\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Python<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Use the Translator detect function\npath = '\/detect'\nurl = translator_endpoint + path\n\n# Build the request\nparams = {\n    'api-version': '3.0'\n}\n\nheaders = {\n'Ocp-Apim-Subscription-Key': cog_key,\n'Ocp-Apim-Subscription-Region': cog_region,\n'Content-type': 'application\/json'\n}\n\nbody = &#91;{\n    'text': text\n}]\n\n# Send the request and get response\nrequest = requests.post(url, params=params, headers=headers, json=body)\nresponse = request.json()\n\n# Parse JSON array and get language\nlanguage = response&#91;0]&#91;\"language\"]\n\n<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image size-large is-style-default\"><img decoding=\"async\" src=\"https:\/\/exceedthecloud.com\/wp-content\/uploads\/2022\/02\/img3-5-1024x456.png\" alt=\"\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\" type=\"1\" start=\"3\"><li>Save your changes and return to the integrated terminal for the <strong>text-translation<\/strong> folder, and enter the following command to run the program:<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>C#<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>dotnet run<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Python<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>python text-translation.py<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\" type=\"1\" start=\"4\"><li>Observe the output, noting that this time the language for each review is identified.<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Translate text<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Now that your application can determine the language in which reviews are written, you can use the Translator service to translate any non-English reviews into English.<\/p>\n\n\n\n<ul class=\"wp-block-list\" type=\"1\"><li>In your code file, find the <strong>Translate<\/strong> function, which currently returns and empty string for all text values.<\/li><li>In the <strong>Translate<\/strong> function, under the comment <strong>Use the Translator translate function<\/strong>, add the following code to use the Translator&#8217;s REST API to translate the specified text from its source language into English, being careful not to replace the code at the end of the function that returns the translation:<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>C#<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Use the Translator translate function\nobject&#91;] body = new object&#91;] { new { Text = text } };\nvar requestBody = JsonConvert.SerializeObject(body);\nusing (var client = new HttpClient())\n{\n    using (var request = new HttpRequestMessage())\n    {\n        \/\/ Build the request\n        string path = \"\/translate?api-version=3.0&amp;from=\" + sourceLanguage + \"&amp;to=en\" ;\n        request.Method = HttpMethod.Post;\n        request.RequestUri = new Uri(translatorEndpoint + path);\n        request.Content = new StringContent(requestBody, Encoding.UTF8, \"application\/json\");\n        request.Headers.Add(\"Ocp-Apim-Subscription-Key\", cogSvcKey);\n        request.Headers.Add(\"Ocp-Apim-Subscription-Region\", cogSvcRegion);\n\n        \/\/ Send the request and get response\n        HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);\n        \/\/ Read response as a string\n        string responseContent = await response.Content.ReadAsStringAsync();\n\n        \/\/ Parse JSON array and get translation\n        JArray jsonResponse = JArray.Parse(responseContent);\n        translation = (string)jsonResponse&#91;0]&#91;\"translations\"]&#91;0]&#91;\"text\"];  \n    }\n}\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Python<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Use the Translator translate function\npath = '\/translate'\nurl = translator_endpoint + path\n\n# Build the request\nparams = {\n    'api-version': '3.0',\n    'from': source_language,\n    'to': &#91;'en']\n}\n\nheaders = {\n    'Ocp-Apim-Subscription-Key': cog_key,\n    'Ocp-Apim-Subscription-Region': cog_region,\n    'Content-type': 'application\/json'\n}\n\nbody = &#91;{\n    'text': text\n}]\n\n# Send the request and get response\nrequest = requests.post(url, params=params, headers=headers, json=body)\nresponse = request.json()\n\n# Parse JSON array and get translation\ntranslation = response&#91;0]&#91;\"translations\"]&#91;0]&#91;\"text\"]\n\n<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image size-large is-style-default\"><img decoding=\"async\" src=\"https:\/\/exceedthecloud.com\/wp-content\/uploads\/2022\/02\/img4-5.png\" alt=\"\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\" type=\"1\" start=\"3\"><li>Save your changes and return to the integrated terminal for the <strong>text-translation<\/strong> folder, and enter the following command to run the program:<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>C#<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>dotnet run<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Python<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>python text-translation.py<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\" type=\"1\" start=\"4\"><li>Observe the output, noting that non-English reviews are translated into English.<\/li><\/ul>\n\n\n\n<figure class=\"wp-block-image size-large is-style-default\"><img decoding=\"async\" src=\"https:\/\/exceedthecloud.com\/wp-content\/uploads\/2022\/02\/img5-5.png\" alt=\"\"\/><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><mark class=\"kt-highlight\"><strong>Reminder<\/strong>: Don\u2019t forget to delete or shutdown all unused Azure resources after your labs for cost saving<\/mark><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>More information<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For more information about using the <strong>Translator<\/strong> service, see the <a href=\"https:\/\/docs.microsoft.com\/azure\/cognitive-services\/translator\/\" target=\"_blank\" rel=\"noreferrer noopener\">Translator documentation<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The Translator service is a cognitive service that enables you to translate text between languages. For example, suppose a travel agency wants to examine hotel reviews that have been submitted to the company&#8217;s web site, standardizing on English as the &hellip; <a href=\"https:\/\/exceedthecloud.com\/?p=724\">Continued<\/a><\/p>\n","protected":false},"author":1,"featured_media":2473,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"kt_blocks_editor_width":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[14,15,4],"tags":[7,8,57,53,52,55,54],"class_list":["post-724","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-artificial-intelligence","category-cognitive-services","category-practical-labs-series","tag-ai","tag-azure","tag-cognitive-service","tag-git","tag-nlp","tag-python","tag-visual-studio-code"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/exceedthecloud.com\/wp-content\/uploads\/2021\/11\/istockphoto-1204589722-612x612-1.jpg","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/exceedthecloud.com\/index.php?rest_route=\/wp\/v2\/posts\/724","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/exceedthecloud.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/exceedthecloud.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/exceedthecloud.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/exceedthecloud.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=724"}],"version-history":[{"count":4,"href":"https:\/\/exceedthecloud.com\/index.php?rest_route=\/wp\/v2\/posts\/724\/revisions"}],"predecessor-version":[{"id":2331,"href":"https:\/\/exceedthecloud.com\/index.php?rest_route=\/wp\/v2\/posts\/724\/revisions\/2331"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/exceedthecloud.com\/index.php?rest_route=\/wp\/v2\/media\/2473"}],"wp:attachment":[{"href":"https:\/\/exceedthecloud.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=724"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/exceedthecloud.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=724"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/exceedthecloud.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=724"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}