Friday, January 24, 2025

Azure AI services - Translator - Translate Text with Azure AI Translator

 Azure AI services - Translator - Translate Text with Azure AI Translator:

C-Sharp C# Code:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text;
 
public class Program
{
    public static string translatorEndpoint = "https://api.cognitive.microsofttranslator.com";
    public static string cogSvcKey = "Aq3OMPInYriPClIMJJuKzpN1JGOJZZRqM3FXJ3w3AAAbACOGxJeX";
    public static string cogSvcRegion = "eastus";
 
    public static async Task Main(string[] args)
    {
        try
        {
            // Get config settings from AppSettings
            // IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
            // IConfigurationRoot configuration = builder.Build();
            // cogSvcKey = configuration["CognitiveServiceKey"];
            // cogSvcRegion = configuration["CognitiveServiceRegion"];
 
            // Set console encoding to unicode
            Console.InputEncoding = Encoding.Unicode;
            Console.OutputEncoding = Encoding.Unicode;
 
            // Analyze each text file in the reviews folder
            var folderPath = Path.GetFullPath("./reviews");
            DirectoryInfo folder = new DirectoryInfo(folderPath);
            foreach (var file in folder.GetFiles("*.txt"))
            {
                // Read the file contents
                Console.WriteLine("\n-------------\n" + file.Name);
                StreamReader sr = file.OpenText();
                var text = sr.ReadToEnd();
                sr.Close();
                Console.WriteLine("\n" + text);
 
                // Detect the language
                string language = await GetLanguage(text);
                Console.WriteLine("Language: " + language);
 
                // Translate if not already English
                if (language != "en")
                {
                    string translatedText = await Translate(text, language);
                    Console.WriteLine("\nTranslation:\n" + translatedText);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        Console.ReadKey();
    }
 
    private static async Task<string> GetLanguage(string text)
    {
        // Default language is English
        string language = "en";
 
        // Use the Translator detect function
        // Use the Azure AI Translator detect function
        object[] body = new object[] { new { Text = text } };
        var requestBody = JsonConvert.SerializeObject(body);
        using (var client = new HttpClient())
        {
            using (var request = new HttpRequestMessage())
            {
                // Build the request
                string path = "/detect?api-version=3.0";
                request.Method = HttpMethod.Post;
                request.RequestUri = new Uri(translatorEndpoint + path);
                request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
                request.Headers.Add("Ocp-Apim-Subscription-Key", cogSvcKey);
                request.Headers.Add("Ocp-Apim-Subscription-Region", cogSvcRegion);
 
                // Send the request and get response
                HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
                // Read response as a string
                string responseContent = await response.Content.ReadAsStringAsync();
 
                // Parse JSON array and get language
                JArray jsonResponse = JArray.Parse(responseContent);
                language = (string)jsonResponse[0]["language"];
            }
        }
 
        // return the language
        return language;
    }
 
    private static async Task<string> Translate(string text, string sourceLanguage)
    {
        string translation = "";
 
        // Use the Translator translate function
        // Use the Azure AI Translator translate function
        object[] body = new object[] { new { Text = text } };
        var requestBody = JsonConvert.SerializeObject(body);
        using (var client = new HttpClient())
        {
            using (var request = new HttpRequestMessage())
            {
                // Build the request
                string path = "/translate?api-version=3.0&from=" + sourceLanguage + "&to=en";
                request.Method = HttpMethod.Post;
                request.RequestUri = new Uri(translatorEndpoint + path);
                request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
                request.Headers.Add("Ocp-Apim-Subscription-Key", cogSvcKey);
                request.Headers.Add("Ocp-Apim-Subscription-Region", cogSvcRegion);
 
                // Send the request and get response
                HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
                // Read response as a string
                string responseContent = await response.Content.ReadAsStringAsync();
 
                // Parse JSON array and get translation
                JArray jsonResponse = JArray.Parse(responseContent);
                translation = (string)jsonResponse[0]["translations"][0]["text"];
            }
        }
 
        // Return the translation
        return translation;
    }
}
 
 Output:

Python:
from dotenv import load_dotenv
import os
import requests, json
 
def main():
    global translator_endpoint
    global cog_key
    global cog_region
 
    try:
        # Get Configuration Settings
        load_dotenv()
        # cog_key = os.getenv('COG_SERVICE_KEY')
        # cog_region = os.getenv('COG_SERVICE_REGION')
        cog_key = 'Aq3OMPInYriPClIMJJuKzpNMBAACYeBjFXJ3w3AAAbACOGxJeX'
        cog_region = 'eastus'
        translator_endpoint = 'https://api.cognitive.microsofttranslator.com'
 
        # Analyze each text file in the reviews folder
        reviews_folder = 'reviews'
        for file_name in os.listdir(reviews_folder):
            # Read the file contents
            print('\n-------------\n' + file_name)
            text = open(os.path.join(reviews_folder, file_name), encoding = 'utf8').read()
            print('\n' + text)
 
            # Detect the language
            language = GetLanguage(text)
            print('Language:', language)
 
            # Translate if not already English
            if language != 'en':
                translation = Translate(text, language)
                print("\nTranslation:\n{}".format(translation))
 
 
    except Exception as ex:
        print(ex)
 
def GetLanguage(text):
    # Default language is English
    language = 'en'
 
    # Use the Translator detect function
# Use the Azure AI Translator detect function
    path = '/detect'
    url = translator_endpoint + path
 
    # Build the request
    params = {
    'api-version': '3.0'
    }
headers = {
    'Ocp-Apim-Subscription-Key': cog_key,
        'Ocp-Apim-Subscription-Region': cog_region,
        'Content-type': 'application/json'
    }
body = [{
    'text': text
    }]
 
    # Send the request and get response
    request = requests.post(url, params=params, headers = headers, json = body)
    response = request.json()
 
    # Parse JSON array and get language
    language = response[0]["language"]
 
    # Return the language
    return language
 
def Translate(text, source_language):
    translation = ''
 
    # Use the Translator translate function
# Use the Azure AI Translator translate function
    path = '/translate'
    url = translator_endpoint + path
 
    # Build the request
    params = {
    'api-version': '3.0',
        'from': source_language,
        'to': ['en']
    }
headers = {
    'Ocp-Apim-Subscription-Key': cog_key,
        'Ocp-Apim-Subscription-Region': cog_region,
        'Content-type': 'application/json'
    }
body = [{
    'text': text
    }]
 
    # Send the request and get response
    request = requests.post(url, params=params, headers = headers, json = body)
    response = request.json()
 
    # Parse JSON array and get translation
    translation = response[0]["translations"][0]["text"]
 
    # Return the translation
    return translation
 
if __name__ == "__main__":
    main()

Output:

Source:
git clone https://github.com/MicrosoftLearning/AI-102-AIEngineer azure-ai-eng

5 comments:

  1. 2482E05636
    Many online resources are available for those interested in digital art and design. One useful platform to explore is https://dtfhub.com, which offers a wide range of tutorials and tools. Whether you're a beginner or an experienced artist, this site provides valuable content to enhance your skills. For more information, visit https://dtfhub.com.

    ReplyDelete

  2. Somewhere beyond the usual digital experiences, dignotech delivered a refreshing example of how effective presentation enhances valuable information. The website creates lasting appreciation through its balanced and carefully planned design.

    ReplyDelete
  3. Some digital platforms fade from memory, but FindRemind remains distinctive because of its organized flow and carefully structured content. Every section contributes to an enjoyable and worthwhile browsing experience.

    ReplyDelete
  4. An ordinary online session turned surprisingly productive after carmannews showcased a polished structure filled with engaging material. The website combines convenience and quality in a way that deserves sincere recognition.

    ReplyDelete

Featured Post

Microsoft Entra ID — A Practical Introduction for M365 Admins

Microsoft Entra ID — A Practical Introduction for M365 Admins Meta Description: New to Microsoft Entra ID? This practical guide covers the...

Popular posts