Ejemplo n.º 1
0
        public GoogleV3Connecter(IMtTranslationOptions options)
        {
            _options           = options;
            SupportedLanguages = new List <GoogleV3LanguageModel>();

            //We put by default NMT model if the nmt model is not supported for the language pair
            //Google knows to use basic model
            var model = "general/nmt";

            if (!string.IsNullOrEmpty(_options.GoogleEngineModel))
            {
                model = _options.GoogleEngineModel;
            }

            _modelPath = $"projects/{_options.ProjectName}/locations/{_options.ProjectLocation}/models/{model}";
            if (!string.IsNullOrEmpty(_options.GlossaryPath))
            {
                GlossaryId = Path.GetFileNameWithoutExtension(_options.GlossaryPath).Replace(" ", string.Empty);                //Google doesn't allow spaces in glossary id
                _glossaryResourceLocation = $"projects/{_options.ProjectName}/locations/{_options.ProjectLocation}/glossaries/{GlossaryId}";
            }

            try
            {
                Environment.SetEnvironmentVariable(PluginResources.GoogleApiEnvironmentVariableName, _options.JsonFilePath);
                _translationServiceClient = TranslationServiceClient.Create();
            }
            catch (Exception e)
            {
                _logger.Error($"{MethodBase.GetCurrentMethod().Name}: {e}");
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Translates a given text to a target language using glossary.
        /// </summary>
        /// <param name="text">The content to translate.</param>
        /// <param name="sourceLanguage">Optional. Source language code.</param>
        /// <param name="targetLanguage">Required. Target language code.</param>
        /// <param name="glossaryId">Translation Glossary ID.</param>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        public static void TranslateTextWithGlossarySample(
            string text           = "[TEXT_TO_TRANSLATE]",
            string sourceLanguage = "en_US",
            string targetLanguage = "ch",
            string projectId      = "[Google Cloud Project ID]",
            string glossaryId     = "[YOUR_GLOSSARY_ID]")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();

            string glossaryPath          = $"projects/{projectId}/locations/{"us-central1"}/glossaries/{glossaryId}";
            TranslateTextRequest request = new TranslateTextRequest
            {
                Contents =
                {
                    // The content to translate.
                    text,
                },
                TargetLanguageCode   = targetLanguage,
                ParentAsLocationName = new LocationName(projectId, "us-central1"),
                SourceLanguageCode   = sourceLanguage,
                GlossaryConfig       = new TranslateTextGlossaryConfig
                {
                    // Translation Glossary Path.
                    Glossary = glossaryPath,
                },
                MimeType = "text/plain",
            };
            TranslateTextResponse response = translationServiceClient.TranslateText(request);

            // Display the translation for given content.
            foreach (Translation translation in response.GlossaryTranslations)
            {
                Console.WriteLine($"Translated text: {translation.TranslatedText}");
            }
        }
Ejemplo n.º 3
0
        public string Translate(string languageFrom, string languageTo, string text)
        {
            try
            {
                Environment.SetEnvironmentVariable(GoogleCredentialsVariable, JsonPath);
                var translationServiceClient = TranslationServiceClient.Create();
                var request = new TranslateTextRequest
                {
                    Contents             = { text },
                    TargetLanguageCode   = languageTo,
                    ParentAsLocationName = new LocationName(ProjectId, "global")
                };
                var response = translationServiceClient.TranslateText(request);

                var translated = new StringBuilder();
                foreach (var translation in response.Translations)
                {
                    translated.Append(HttpUtility.HtmlDecode(translation.TranslatedText));
                }
                return(translated.ToString().Trim());
            }
            catch (Exception ex)
            {
                throw new Exception("Request error.", ex);
            }
        }
        /// <summary>
        /// Translates a given text to a target language with custom model.
        /// </summary>
        /// <param name="modelId">Translation Model ID.</param>
        /// <param name="text">The content to translate.t</param>
        /// <param name="targetLanguage">Required. Target language code.</param>
        /// <param name="sourceLanguage">Optional. Source language code.</param>
        /// <param name="projectId"> Google Project ID.</param>
        /// <param name="location"> Region.</param>
        public static void TranslateTextWithModelSample(
            string modelId        = "[YOUR_MODEL_ID]",
            string text           = "[TEXT_TO_TRANSLATE]",
            string targetLanguage = "ja",
            string sourceLanguage = "en",
            string projectId      = "[Google Cloud Project ID]",
            string location       = "us-central1")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            string modelPath = $"projects/{projectId}/locations/{location}/models/{modelId}";

            TranslateTextRequest request = new TranslateTextRequest
            {
                Contents =
                {
                    // The content to translate.
                    text,
                },
                TargetLanguageCode   = targetLanguage,
                ParentAsLocationName = new LocationName(projectId, location),
                Model = modelPath,
                SourceLanguageCode = sourceLanguage,
                MimeType           = "text/plain",
            };
            TranslateTextResponse response = translationServiceClient.TranslateText(request);

            // Display the translation for each input text provided
            foreach (Translation translation in response.Translations)
            {
                Console.WriteLine($"Translated text: {translation.TranslatedText}");
            }
        }
        /// <summary>Snippet for DeleteGlossary</summary>
        public void DeleteGlossary_RequestObject()
        {
            // Snippet: DeleteGlossary(DeleteGlossaryRequest,CallSettings)
            // Create client
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            // Initialize request argument(s)
            DeleteGlossaryRequest request = new DeleteGlossaryRequest
            {
                GlossaryName = new GlossaryName("[PROJECT]", "[LOCATION]", "[GLOSSARY]"),
            };
            // Make the request
            Operation <DeleteGlossaryResponse, DeleteGlossaryMetadata> response =
                translationServiceClient.DeleteGlossary(request);

            // Poll until the returned long-running operation is complete
            Operation <DeleteGlossaryResponse, DeleteGlossaryMetadata> completedResponse =
                response.PollUntilCompleted();
            // Retrieve the operation result
            DeleteGlossaryResponse result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            Operation <DeleteGlossaryResponse, DeleteGlossaryMetadata> retrievedResponse =
                translationServiceClient.PollOnceDeleteGlossary(operationName);

            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                DeleteGlossaryResponse retrievedResult = retrievedResponse.Result;
            }
            // End snippet
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Translates a given text to a target language.
 /// </summary>
 /// <param name="text">The content to translate.</param>
 /// <param name="sourceLanguage">Required. Source language code.</param>
 /// <param name="targetLanguage">Required. Target language code.</param>
 /// <param name="projectId">Your Google Cloud Project ID.</param>
 public static void TranslateTextSample(string text,
                                        string projectId,
                                        string sourceLanguage = "en_US",
                                        string targetLanguage = "zh-CN")
 {
     try
     {
         TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
         TranslateTextRequest     request = new TranslateTextRequest
         {
             Contents =
             {
                 // The content to translate.
                 text,
             },
             SourceLanguageCode   = sourceLanguage,
             TargetLanguageCode   = targetLanguage,
             ParentAsLocationName = new LocationName(projectId, "global"),
         };
         TranslateTextResponse response = translationServiceClient.TranslateText(request);
         // Display the translation for each input text provided
         foreach (Translation translation in response.Translations)
         {
             Console.WriteLine($"Translated text: {translation.TranslatedText}");
             SavaTranslateText(text, sourceLanguage, targetLanguage, translation.TranslatedText);
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine($"Error text: {ex.Message}");
     }
 }
        /// <summary>Snippet for CreateGlossary</summary>
        public void CreateGlossary()
        {
            // Snippet: CreateGlossary(LocationName,Glossary,CallSettings)
            // Create client
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            // Initialize request argument(s)
            LocationName parent   = new LocationName("[PROJECT]", "[LOCATION]");
            Glossary     glossary = new Glossary();
            // Make the request
            Operation <Glossary, CreateGlossaryMetadata> response =
                translationServiceClient.CreateGlossary(parent, glossary);

            // Poll until the returned long-running operation is complete
            Operation <Glossary, CreateGlossaryMetadata> completedResponse =
                response.PollUntilCompleted();
            // Retrieve the operation result
            Glossary result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            Operation <Glossary, CreateGlossaryMetadata> retrievedResponse =
                translationServiceClient.PollOnceCreateGlossary(operationName);

            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Glossary retrievedResult = retrievedResponse.Result;
            }
            // End snippet
        }
        /// <summary>
        /// Translates a batch of texts on GCS and stores the result in a GCS location.
        /// Glossary is applied for translation.
        /// </summary>
        /// <param name="inputUri">The GCS path where input configuration is stored.</param>
        /// <param name="outputUri">The GCS path for translation output.</param>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        /// <param name="location">Region.</param>
        /// <param name="glossaryId">Required. Translation Glossary ID.</param>
        /// <param name="targetLanguage">Target language code.</param>
        /// <param name="sourceLanguage">Source language code.</param>
        public static void BatchTranslateTextWithGlossarySample(
            string inputUri       = "gs://cloud-samples-data/text.txt",
            string outputUri      = "gs://YOUR_BUCKET_ID/path_to_store_results/",
            string projectId      = "[Google Cloud Project ID]",
            string location       = "us-central1",
            string glossaryId     = "[YOUR_GLOSSARY_ID]",
            string targetLanguage = "en",
            string sourceLanguage = "ja")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();

            string glossaryPath = $"projects/{projectId}/locations/{location}/glossaries/{glossaryId}";
            BatchTranslateTextRequest request = new BatchTranslateTextRequest
            {
                ParentAsLocationName = new LocationName(projectId, location),
                SourceLanguageCode   = sourceLanguage,
                TargetLanguageCodes  =
                {
                    // Target language code.
                    targetLanguage,
                },
                InputConfigs =
                {
                    new InputConfig
                    {
                        GcsSource = new GcsSource
                        {
                            InputUri = inputUri,
                        },
                        MimeType = "text/plain",
                    },
                },
                OutputConfig = new OutputConfig
                {
                    GcsDestination = new GcsDestination
                    {
                        OutputUriPrefix = outputUri,
                    },
                },
                Glossaries =
                {
                    {
                        targetLanguage, new TranslateTextGlossaryConfig
                        {
                            Glossary = glossaryPath,
                        }
                    },
                },
            };
            // Poll until the returned long-running operation is completed.
            BatchTranslateResponse response = translationServiceClient.BatchTranslateText(request).PollUntilCompleted().Result;

            Console.WriteLine($"Total Characters: {response.TotalCharacters}");
            Console.WriteLine($"Translated Characters: {response.TranslatedCharacters}");
        }
 /// <summary>Snippet for GetGlossary</summary>
 public void GetGlossary()
 {
     // Snippet: GetGlossary(GlossaryName,CallSettings)
     // Create client
     TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
     // Initialize request argument(s)
     GlossaryName name = new GlossaryName("[PROJECT]", "[LOCATION]", "[GLOSSARY]");
     // Make the request
     Glossary response = translationServiceClient.GetGlossary(name);
     // End snippet
 }
 /// <summary>Snippet for GetSupportedLanguages</summary>
 public void GetSupportedLanguages()
 {
     // Snippet: GetSupportedLanguages(LocationName,string,string,CallSettings)
     // Create client
     TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
     // Initialize request argument(s)
     LocationName parent = new LocationName("[PROJECT]", "[LOCATION]");
     string       displayLanguageCode = "";
     string       model = "";
     // Make the request
     SupportedLanguages response = translationServiceClient.GetSupportedLanguages(parent, displayLanguageCode, model);
     // End snippet
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Deletes a Glossary.
        /// </summary>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        /// <param name="glossaryId">Glossary ID.</param>
        public static void DeleteGlossarySample(string projectId  = "[Google Cloud Project ID]",
                                                string glossaryId = "[YOUR_GLOSSARY_ID]")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            DeleteGlossaryRequest    request = new DeleteGlossaryRequest
            {
                GlossaryName = new GlossaryName(projectId, "us-central1", glossaryId),
            };
            // Poll until the returned long-running operation is complete
            DeleteGlossaryResponse response = translationServiceClient.DeleteGlossary(request).PollUntilCompleted().Result;

            Console.WriteLine("Deleted Glossary.");
        }
 /// <summary>Snippet for GetSupportedLanguages</summary>
 public void GetSupportedLanguages_RequestObject()
 {
     // Snippet: GetSupportedLanguages(GetSupportedLanguagesRequest,CallSettings)
     // Create client
     TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
     // Initialize request argument(s)
     GetSupportedLanguagesRequest request = new GetSupportedLanguagesRequest
     {
         ParentAsLocationName = new LocationName("[PROJECT]", "[LOCATION]"),
     };
     // Make the request
     SupportedLanguages response = translationServiceClient.GetSupportedLanguages(request);
     // End snippet
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Retrieves a glossary.
        /// </summary>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        /// <param name="glossaryId">Glossary ID.</param>
        public static void GetGlossarySample(string projectId  = "[Google Cloud Project ID]",
                                             string glossaryId = "[YOUR_GLOSSARY_ID]")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            GetGlossaryRequest       request = new GetGlossaryRequest
            {
                GlossaryName = new GlossaryName(projectId, "us-central1", glossaryId),
            };
            Glossary response = translationServiceClient.GetGlossary(request);

            Console.WriteLine($"Glossary name: {response.Name}");
            Console.WriteLine($"Entry count: {response.EntryCount}");
            Console.WriteLine($"Input URI: {response.InputConfig.GcsSource.InputUri}");
        }
 /// <summary>Snippet for DetectLanguage</summary>
 public void DetectLanguage()
 {
     // Snippet: DetectLanguage(LocationName,string,string,IDictionary<string, string>,CallSettings)
     // Create client
     TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
     // Initialize request argument(s)
     LocationName parent   = new LocationName("[PROJECT]", "[LOCATION]");
     string       model    = "";
     string       mimeType = "";
     IDictionary <string, string> labels = new Dictionary <string, string>();
     // Make the request
     DetectLanguageResponse response = translationServiceClient.DetectLanguage(parent, model, mimeType, labels);
     // End snippet
 }
 /// <summary>Snippet for DetectLanguage</summary>
 public void DetectLanguage_RequestObject()
 {
     // Snippet: DetectLanguage(DetectLanguageRequest,CallSettings)
     // Create client
     TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
     // Initialize request argument(s)
     DetectLanguageRequest request = new DetectLanguageRequest
     {
         ParentAsLocationName = new LocationName("[PROJECT]", "[LOCATION]"),
     };
     // Make the request
     DetectLanguageResponse response = translationServiceClient.DetectLanguage(request);
     // End snippet
 }
 /// <summary>Snippet for GetGlossary</summary>
 public void GetGlossary_RequestObject()
 {
     // Snippet: GetGlossary(GetGlossaryRequest,CallSettings)
     // Create client
     TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
     // Initialize request argument(s)
     GetGlossaryRequest request = new GetGlossaryRequest
     {
         Name = new GlossaryName("[PROJECT]", "[LOCATION]", "[GLOSSARY]").ToString(),
     };
     // Make the request
     Glossary response = translationServiceClient.GetGlossary(request);
     // End snippet
 }
Ejemplo n.º 17
0
        /// <summary>
        /// Getting a list of supported language codes
        /// </summary>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        public static void GetSupportedLanguagesSample(string projectId = "[Google Cloud Project ID]")
        {
            TranslationServiceClient     translationServiceClient = TranslationServiceClient.Create();
            GetSupportedLanguagesRequest request = new GetSupportedLanguagesRequest
            {
                ParentAsLocationName = new LocationName(projectId, "global"),
            };
            SupportedLanguages response = translationServiceClient.GetSupportedLanguages(request);

            // List language codes of supported languages
            foreach (SupportedLanguage language in response.Languages)
            {
                Console.WriteLine($"Language Code: {language.LanguageCode}");
            }
        }
 /// <summary>Snippet for TranslateText</summary>
 public void TranslateText_RequestObject()
 {
     // Snippet: TranslateText(TranslateTextRequest,CallSettings)
     // Create client
     TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
     // Initialize request argument(s)
     TranslateTextRequest request = new TranslateTextRequest
     {
         Contents             = { },
         TargetLanguageCode   = "",
         ParentAsLocationName = new LocationName("[PROJECT]", "[LOCATION]"),
     };
     // Make the request
     TranslateTextResponse response = translationServiceClient.TranslateText(request);
     // End snippet
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Lists all the glossaries for a given project.
        /// </summary>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        public static void ListGlossariesSample(string projectId = "[Google Cloud Project ID]")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            ListGlossariesRequest    request = new ListGlossariesRequest
            {
                ParentAsLocationName = new LocationName(projectId, "us-central1"),
            };
            PagedEnumerable <ListGlossariesResponse, Glossary> response = translationServiceClient.ListGlossaries(request);

            // Iterate over glossaries and display each glossary's details.
            foreach (Glossary item in response)
            {
                Console.WriteLine($"Glossary name: {item.Name}");
                Console.WriteLine($"Entry count: {item.EntryCount}");
                Console.WriteLine($"Input URI: {item.InputConfig.GcsSource.InputUri}");
            }
        }
        /// <summary>Snippet for ListGlossaries</summary>
        public void ListGlossaries_RequestObject()
        {
            // Snippet: ListGlossaries(ListGlossariesRequest,CallSettings)
            // Create client
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            // Initialize request argument(s)
            ListGlossariesRequest request = new ListGlossariesRequest
            {
                ParentAsLocationName = new LocationName("[PROJECT]", "[LOCATION]"),
            };
            // Make the request
            PagedEnumerable <ListGlossariesResponse, Glossary> response =
                translationServiceClient.ListGlossaries(request);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (Glossary item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListGlossariesResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (Glossary item in page)
                {
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int             pageSize   = 10;
            Page <Glossary> singlePage = response.ReadPage(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (Glossary item in singlePage)
            {
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }
Ejemplo n.º 21
0
        static List <Translations> TranslateV3(RestClient restClient, List <string> text)
        {
            TranslationServiceClient client  = TranslationServiceClient.Create();
            TranslateTextRequest     request = new TranslateTextRequest();

            request.TargetLanguageCode = "es-ES";
            request.Parent             = new ProjectName("desiringgod").ToString();
            request.Contents.AddRange(text);

            TranslateTextResponse response = client.TranslateText(request);

            return(response.Translations.Select(s => new Translations
            {
                translatedText = s.TranslatedText,
                detectedSourceLanguage = s.DetectedLanguageCode
            }).ToList());
        }
        public static IEnumerable <string> GetTranslate(string projectID, string locationID, Language sourceLanguage, Language targetLanguage, string text, string modelID = "general/nmt")
        {
            TranslationServiceClient client = TranslationServiceClient.Create();

            LocationName         locationName = new LocationName(projectId: projectID, locationId: locationID);
            TranslateTextRequest request      = new TranslateTextRequest()
            {
                Parent             = locationName.ToString(),
                MimeType           = "text/plain",
                SourceLanguageCode = LanguageDic[sourceLanguage],
                TargetLanguageCode = LanguageDic[targetLanguage],
                Model    = modelID,
                Contents = { text },
            };

            TranslateTextResponse response = client.TranslateText(request);

            return(response.Translations.Select(result => result.TranslatedText));
        }
Ejemplo n.º 23
0
        public static string Translate(string text, string targetLanguage, string sourceLanguage)
        {
            var credentialsPath = Path.Combine(Directory.GetCurrentDirectory(), "service-account.json");

            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", credentialsPath);
            var projectId = JObject.Parse(File.ReadAllText(credentialsPath)).SelectToken("project_id").ToString();

            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            TranslateTextRequest     request = new TranslateTextRequest
            {
                Contents             = { text },
                TargetLanguageCode   = targetLanguage,
                SourceLanguageCode   = sourceLanguage,
                ParentAsLocationName = new LocationName(projectId, "global")
            };
            TranslateTextResponse response = translationServiceClient.TranslateText(request);

            return(response.Translations.FirstOrDefault()?.TranslatedText);
        }
Ejemplo n.º 24
0
        private static string TranslateTo(string language, string source)
        {
            if (source == String.Empty || source == " ")
            {
                return(source);
            }

            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS",
                                               Environment.CurrentDirectory + "/../../../fresh-rampart-310520-4eafed6542f9.json");
            TranslationServiceClient client  = TranslationServiceClient.Create();
            TranslateTextRequest     request = new TranslateTextRequest
            {
                SourceLanguageCode = "en",
                Contents           = { IgnoreList.ReplaceIgnoreWords(source) },
                TargetLanguageCode = language,
                Parent             = "projects/fresh-rampart-310520",
                MimeType           = "text/plain"
            };
            string xlation = "";

            try
            {
                xlation = client.TranslateText(request).Translations[0].TranslatedText;
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
                Environment.Exit(-1);
            }
            // total hack. Google translate is removing trailing spaces
            // c# API is very poorly documented, so this hack will have to do
            // for now. Same with the HtmlDecode happening in the next line.
            // Apparently you can tell the translator to use text instead of
            // html, but again, not obvious where/how it the C# APIs.
            if (source.EndsWith(" "))
            {
                xlation += " ";
            }
            return(HttpUtility.HtmlDecode(IgnoreList.ReAaddIgnoreWords(xlation)));
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Detects the language of a given text.
        /// </summary>
        /// <param name="text">The text string for performing language detection</param>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        public static void DetectLanguageSample(string text      = "[TEXT_STRING_FOR_DETECTION]",
                                                string projectId = "[Google Cloud Project ID]")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            DetectLanguageRequest    request = new DetectLanguageRequest
            {
                ParentAsLocationName = new LocationName(projectId, "global"),
                Content  = text,
                MimeType = "text/plain",
            };
            DetectLanguageResponse response = translationServiceClient.DetectLanguage(request);

            // Display list of detected languages sorted by detection confidence.
            // The most probable language is first.
            foreach (DetectedLanguage language in response.Languages)
            {
                // The language detected
                Console.WriteLine($"Language code: {language.LanguageCode}");
                // Confidence of detection result for this language
                Console.WriteLine($"Confidence: {language.Confidence}");
            }
        }
        /// <summary>Snippet for BatchTranslateText</summary>
        public void BatchTranslateText_RequestObject()
        {
            // Snippet: BatchTranslateText(BatchTranslateTextRequest,CallSettings)
            // Create client
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            // Initialize request argument(s)
            BatchTranslateTextRequest request = new BatchTranslateTextRequest
            {
                ParentAsLocationName = new LocationName("[PROJECT]", "[LOCATION]"),
                SourceLanguageCode   = "",
                TargetLanguageCodes  = { },
                InputConfigs         = { },
                OutputConfig         = new OutputConfig(),
            };
            // Make the request
            Operation <BatchTranslateResponse, BatchTranslateMetadata> response =
                translationServiceClient.BatchTranslateText(request);

            // Poll until the returned long-running operation is complete
            Operation <BatchTranslateResponse, BatchTranslateMetadata> completedResponse =
                response.PollUntilCompleted();
            // Retrieve the operation result
            BatchTranslateResponse result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            Operation <BatchTranslateResponse, BatchTranslateMetadata> retrievedResponse =
                translationServiceClient.PollOnceBatchTranslateText(operationName);

            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                BatchTranslateResponse retrievedResult = retrievedResponse.Result;
            }
            // End snippet
        }
        /// <summary>
        /// Translates a given text to a target language.
        /// </summary>
        /// <param name="text">The content to translate.</param>
        /// <param name="targetLanguage">Required. Target language code.</param>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        public static void TranslateTextSample(string text           = "[TEXT_TO_TRANSLATE]",
                                               string targetLanguage = "ja",
                                               string projectId      = "[Google Cloud Project ID]")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            TranslateTextRequest     request = new TranslateTextRequest
            {
                Contents =
                {
                    // The content to translate.
                    text,
                },
                TargetLanguageCode   = targetLanguage,
                ParentAsLocationName = new LocationName(projectId, "global"),
            };
            TranslateTextResponse response = translationServiceClient.TranslateText(request);

            // Display the translation for each input text provided
            foreach (Translation translation in response.Translations)
            {
                Console.WriteLine($"Translated text: {translation.TranslatedText}");
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Create Glossary.
        /// </summary>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        /// <param name="glossaryId">Glossary ID.</param>
        /// <param name="inputUri">Google Cloud Storage URI where glossary is stored in csv format.</param>
        public static void CreateGlossarySample(string projectId  = "[Google Cloud Project ID]",
                                                string glossaryId = "[YOUR_GLOSSARY_ID]",
                                                string inputUri   = "gs://cloud-samples-data/translation/glossary_ja.csv")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            CreateGlossaryRequest    request = new CreateGlossaryRequest
            {
                ParentAsLocationName = new LocationName(projectId, "us-central1"),
                Parent   = new LocationName(projectId, "us-central1").ToString(),
                Glossary = new Glossary
                {
                    Name             = new GlossaryName(projectId, "us-central1", glossaryId).ToString(),
                    LanguageCodesSet = new Glossary.Types.LanguageCodesSet
                    {
                        LanguageCodes =
                        {
                            "en", // source lang
                            "ja", // target lang
                        },
                    },
                    InputConfig = new GlossaryInputConfig
                    {
                        GcsSource = new GcsSource
                        {
                            InputUri = inputUri,
                        },
                    },
                },
            };
            // Poll until the returned long-running operation is complete
            Glossary response = translationServiceClient.CreateGlossary(request).PollUntilCompleted().Result;

            Console.WriteLine("Created Glossary.");
            Console.WriteLine($"Glossary name: {response.Name}");
            Console.WriteLine($"Entry count: {response.EntryCount}");
            Console.WriteLine($"Input URI: {response.InputConfig.GcsSource.InputUri}");
        }
Ejemplo n.º 29
0
        public void GettingStarted()
        {
            string projectId = TestEnvironment.GetTestProjectId();

            // Sample: GettingStarted
            TranslationServiceClient client  = TranslationServiceClient.Create();
            TranslateTextRequest     request = new TranslateTextRequest
            {
                Contents           = { "It is raining." },
                TargetLanguageCode = "fr-FR",
                Parent             = new ProjectName(projectId).ToString()
            };
            TranslateTextResponse response = client.TranslateText(request);
            // response.Translations will have one entry, because request.Contents has one entry.
            Translation translation = response.Translations[0];

            Console.WriteLine($"Detected language: {translation.DetectedLanguageCode}");
            Console.WriteLine($"Translated text: {translation.TranslatedText}");
            // End sample

            Assert.Equal(1, response.Translations.Count);
            Assert.Equal("en", translation.DetectedLanguageCode);
            Assert.Equal("Il pleut.", translation.TranslatedText);
        }