how to Use google Translation with Google Glossary in C# .net

93 Views Asked by At

I have an application where i am using google Tranlastion api. Now for the customization of some keywords I have created google glossary which is setup successfully. Now i am planning to use it in my application which has below code :-

            string apikey = ConfigurationManager.AppSettings["GoogleTranslateApiKey"].ToString();
            try
            {
                var client = TranslationClient.CreateFromApiKey(apikey);
                var result = client.TranslateText(Text, TranslateTo, LanguageCodes.English);
                List<string> lstData = new List<string>();
                foreach (var item in result)
                {
                    lstData.Add(item.TranslatedText);
                }
                response.KEY = "SUCCESS";
                response.MESSAGE = JsonConvert.SerializeObject(lstData);
            }

Now the issue is like where i have to involve my glossary configurations? below is my postman request details :-

Request URL:- https://translation.googleapis.com/v3/projects/mywebapp-translate/locations/us-central1:translateText

Request:-

{
  "sourceLanguageCode": "en",
  "targetLanguageCode": "hi",
  "contents": "my language is hindi",
  "glossaryConfig": {
    "glossary": "projects/661824000002/locations/us-central1/glossaries/my-glossary",
    "ignoreCase": "true"
  }
}

Do I need to change my whole code or just including above configuration somewhere in my code will work? Can someone help

1

There are 1 best solutions below

1
 Lesig On

The glossary configuration is not directly supported in the TranslateText method. Instead, you need to use the TranslateText method with a TranslateTextRequest object, which allows you to specify the glossary configuration.

Here's a modified version of your code:

string apikey = ConfigurationManager.AppSettings["GoogleTranslateApiKey"].ToString();

try
{
    var client = TranslationClient.CreateFromApiKey(apikey);

    var request = new TranslateTextRequest
    {
        Contents = { Text },
        TargetLanguageCode = TranslateTo,
        SourceLanguageCode = LanguageCodes.English,
        GlossaryConfig = new TranslateTextGlossaryConfig
        {
            Glossary = "projects/661824000002/locations/us-central1/glossaries/my-glossary",
            IgnoreCase = true
        }
    };

    var response = client.TranslateText(request);

    List<string> lstData = new List<string>();
    foreach (var item in response.Translations)
    {
        lstData.Add(item.TranslatedText);
    }

    // Your further processing logic here

    response.KEY = "SUCCESS";
    response.MESSAGE = JsonConvert.SerializeObject(lstData);
}
catch (Exception ex)
{
    // Handle exception
}

This modification uses the TranslateTextRequest object to set the glossary configuration. Make sure to adjust the error handling and further processing logic based on your application's requirements.