/// <summary>Snippet for DetectLanguageAsync</summary>
        public async Task DetectLanguageAsync()
        {
            // Snippet: DetectLanguageAsync(string,string,string,IDictionary<string, string>,CallSettings)
            // Additional: DetectLanguageAsync(string,string,string,IDictionary<string, string>,CancellationToken)
            // Create client
            TranslationServiceClient translationServiceClient = await TranslationServiceClient.CreateAsync();

            // Initialize request argument(s)
            string formattedParent = new LocationName("[PROJECT]", "[LOCATION]").ToString();
            string model           = "";
            string mimeType        = "";
            IDictionary <string, string> labels = new Dictionary <string, string>();
            // Make the request
            DetectLanguageResponse response = await translationServiceClient.DetectLanguageAsync(formattedParent, model, mimeType, labels);

            // End snippet
        }
        /// <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
            {
                Parent = new LocationName("[PROJECT]", "[LOCATION]").ToString(),
            };
            // 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
        }
        /// <summary>Snippet for GetGlossaryAsync</summary>
        public async Task GetGlossaryAsync_RequestObject()
        {
            // Snippet: GetGlossaryAsync(GetGlossaryRequest,CallSettings)
            // Additional: GetGlossaryAsync(GetGlossaryRequest,CancellationToken)
            // Create client
            TranslationServiceClient translationServiceClient = await TranslationServiceClient.CreateAsync();

            // Initialize request argument(s)
            GetGlossaryRequest request = new GetGlossaryRequest
            {
                Name = new GlossaryName("[PROJECT]", "[LOCATION]", "[GLOSSARY]").ToString(),
            };
            // Make the request
            Glossary response = await translationServiceClient.GetGlossaryAsync(request);

            // End snippet
        }
        /// <summary>Snippet for GetSupportedLanguagesAsync</summary>
        public async Task GetSupportedLanguagesAsync_RequestObject()
        {
            // Snippet: GetSupportedLanguagesAsync(GetSupportedLanguagesRequest,CallSettings)
            // Additional: GetSupportedLanguagesAsync(GetSupportedLanguagesRequest,CancellationToken)
            // Create client
            TranslationServiceClient translationServiceClient = await TranslationServiceClient.CreateAsync();

            // Initialize request argument(s)
            GetSupportedLanguagesRequest request = new GetSupportedLanguagesRequest
            {
                Parent = new LocationName("[PROJECT]", "[LOCATION]").ToString(),
            };
            // Make the request
            SupportedLanguages response = await translationServiceClient.GetSupportedLanguagesAsync(request);

            // End snippet
        }
Ejemplo n.º 5
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 ListGlossariesAsync</summary>
        public async Task ListGlossariesAsync()
        {
            // Snippet: ListGlossariesAsync(LocationName,string,string,int?,CallSettings)
            // Create client
            TranslationServiceClient translationServiceClient = await TranslationServiceClient.CreateAsync();

            // Initialize request argument(s)
            LocationName parent = new LocationName("[PROJECT]", "[LOCATION]");
            string       filter = "";
            // Make the request
            PagedAsyncEnumerable <ListGlossariesResponse, Glossary> response =
                translationServiceClient.ListGlossariesAsync(parent, filter);

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

            // Or iterate over pages (of server-defined size), performing one RPC per page
            await response.AsRawResponses().ForEachAsync((ListGlossariesResponse page) =>
            {
                // 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 = await response.ReadPageAsync(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
        }
        public async static Task <String> googleTranslateApiV3(String textToTranslate, String targetLanguage, String projectName, ILogger logger, IOptions <GoogleTranslateApiCredentials> googleTranslateApiCredentials)
        {
            if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT").Equals("Development"))
            {
                //var credential = GoogleCredential.GetApplicationDefaultAsync();
                //Hostirano lokalno
                TranslationServiceClientBuilder translationServiceClientBuilder = new TranslationServiceClientBuilder();
                translationServiceClientBuilder.JsonCredentials = JsonConvert.SerializeObject(googleTranslateApiCredentials.Value);
                TranslationServiceClient translationServiceClient = await translationServiceClientBuilder.BuildAsync();

                TranslateTextRequest request = new TranslateTextRequest
                {
                    Contents =
                    {
                        // The content to translate.
                        textToTranslate,
                    },
                    TargetLanguageCode   = targetLanguage,
                    ParentAsLocationName = new LocationName(projectName, "global"),
                };
                TranslateTextResponse response = await translationServiceClient.TranslateTextAsync(request);

                return(response.Translations[0].TranslatedText);
            }
            if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT").Equals("Production"))
            {
                TranslationServiceClient translationServiceClient = await TranslationServiceClient.CreateAsync();

                TranslateTextRequest request = new TranslateTextRequest
                {
                    Contents =
                    {
                        // The content to translate.
                        textToTranslate,
                    },
                    TargetLanguageCode   = targetLanguage,
                    ParentAsLocationName = new LocationName(projectName, "global"),
                };
                TranslateTextResponse response = await translationServiceClient.TranslateTextAsync(request);

                return(response.Translations[0].TranslatedText);
            }

            return(null);
        }
        /// <summary>
        /// Listing supported languages with target language code.
        /// </summary>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        /// <param name="languageCode">Target Language Code.</param>
        public static void GetSupportedLanguagesForTargetSample(string languageCode = "en",
                                                                string projectId    = "[Google Cloud Project ID]")
        {
            TranslationServiceClient     translationServiceClient = TranslationServiceClient.Create();
            GetSupportedLanguagesRequest request = new GetSupportedLanguagesRequest
            {
                ParentAsLocationName = new LocationName(projectId, "global"),
                DisplayLanguageCode  = languageCode,
            };
            SupportedLanguages response = translationServiceClient.GetSupportedLanguages(request);

            // List language codes of supported languages
            foreach (SupportedLanguage language in response.Languages)
            {
                Console.WriteLine($"Language Code: {language.LanguageCode}");
                Console.WriteLine($"Display Name: {language.DisplayName}");
            }
        }
        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);
        }
        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));
        }
        /// <summary>Snippet for TranslateTextAsync</summary>
        public async Task TranslateTextAsync_RequestObject()
        {
            // Snippet: TranslateTextAsync(TranslateTextRequest,CallSettings)
            // Additional: TranslateTextAsync(TranslateTextRequest,CancellationToken)
            // Create client
            TranslationServiceClient translationServiceClient = await TranslationServiceClient.CreateAsync();

            // Initialize request argument(s)
            TranslateTextRequest request = new TranslateTextRequest
            {
                Contents             = { },
                TargetLanguageCode   = "",
                ParentAsLocationName = new LocationName("[PROJECT]", "[LOCATION]"),
            };
            // Make the request
            TranslateTextResponse response = await translationServiceClient.TranslateTextAsync(request);

            // End snippet
        }
        /// <summary>
        /// Translates a batch of texts on GCS and stores the result in a GCS location.
        /// </summary>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        /// <param name="location">Region.</param>
        /// <param name="inputUri">The GCS path where input configuration is stored.</param>
        /// <param name="outputUri">The GCS path for translation output.</param>
        /// <param name="sourceLanguage">Source language code.</param>
        /// <param name="targetLanguage">Target language code.</param>
        public static void BatchTranslateTextSample(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 sourceLanguage = "en",
                                                    string targetLanguage = "ja")
        {
            TranslationServiceClient  translationServiceClient = TranslationServiceClient.Create();
            BatchTranslateTextRequest request = new BatchTranslateTextRequest
            {
                ParentAsLocationName = new LocationName(projectId, location),
                SourceLanguageCode   = sourceLanguage,
                TargetLanguageCodes  =
                {
                    targetLanguage,
                },
                InputConfigs =
                {
                    new InputConfig
                    {
                        GcsSource = new GcsSource
                        {
                            InputUri = inputUri,
                        },
                        MimeType = "text/plain",
                    },
                },
                OutputConfig = new OutputConfig
                {
                    GcsDestination = new GcsDestination
                    {
                        OutputUriPrefix = outputUri,
                    },
                },
            };
            // 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 BatchTranslateTextAsync</summary>
        public async Task BatchTranslateTextAsync_RequestObject()
        {
            // Snippet: BatchTranslateTextAsync(BatchTranslateTextRequest,CallSettings)
            // Create client
            TranslationServiceClient translationServiceClient = await TranslationServiceClient.CreateAsync();

            // 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 =
                await translationServiceClient.BatchTranslateTextAsync(request);

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

            // 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 =
                await translationServiceClient.PollOnceBatchTranslateTextAsync(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
        }
Ejemplo n.º 14
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.º 15
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}");
            }
        }
Ejemplo n.º 16
0
        public static async Task <TranslationServiceClient> GetTranslationServiceClientAsync()
        {
            var path = Properties.Settings.Default.CredentialsPath;

            if (!TranslationServiceClientCache.TryGetTarget(out var tuple) ||
                tuple.CredentialsPath != path)
            {
                var client = string.IsNullOrWhiteSpace(path)
                    ? await TranslationServiceClient.CreateAsync()
                    : await new TranslationServiceClientBuilder
                {
                    CredentialsPath = path
                }

                .BuildAsync();
                tuple = new TranslationServiceClientTuple {
                    Client = client, CredentialsPath = path
                };
                TranslationServiceClientCache.SetTarget(tuple);
            }
            return(tuple.Client);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Translates a given text to a target language with glossary and custom model.
        /// </summary>
        /// <param name="modelId">Translation Model ID.</param>
        /// <param name="glossaryId">Translation Glossary ID.</param>
        /// <param name="text">The content to translate in string format</param>
        /// <param name="targetLanguage">Required. Target language code.</param>
        /// <param name="sourceLanguage">Optional. Source language code.</param>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        /// <param name="location"> Region.</param>
        public static void TranslateTextWithGlossaryAndModelSample(
            string modelId        = "[YOUR_MODEL_ID]",
            string glossaryId     = "[YOUR_GLOSSARY_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}";
            string glossaryPath = $"projects/{projectId}/locations/{location}/glossaries/{glossaryId}";

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

            // Display the translation from given content using glossary and custom model.
            foreach (Translation translation in response.GlossaryTranslations)
            {
                Console.WriteLine($"Translated text: {translation.TranslatedText}");
            }
        }
Ejemplo n.º 18
0
        public async Task <ActionResult <IList <SupportedLanguage> > > GetGoogleTranslateLanguages()
        {
            TranslationServiceClient service = await translateServiceAccessor.InitializeServiceAsync();

            string[] displayLanguageCodeList = { "en" };

            #region Accept Header
            if (Request.Headers.TryGetValue("Accept-Language", out StringValues value))
            {
                string[] accept_language_values = value.ToString().Split(',');
            }
            #endregion

            int i = 0;             // iterate over display language code list
            IList <SupportedLanguage> response = null;
            while (response == null)
            {
                string displayLanguageCode = (i < displayLanguageCodeList.Length) ? displayLanguageCodeList[i] : null;

                if (displayLanguageCode == null)
                {
                    break;
                }

                try {
                    SupportedLanguages temp = await service.GetSupportedLanguagesAsync(new GetSupportedLanguagesRequest {
                        Parent = GoogleCloudTranslateServiceAccessor.PARENT,
                        DisplayLanguageCode = displayLanguageCode,
                    });

                    response = temp.Languages;
                } catch (Grpc.Core.RpcException) {
                    i++;
                }
            }

            return(new ActionResult <IList <SupportedLanguage> >(response));
        }
        /// <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}");
            }
        }
        /// <summary>Snippet for CreateGlossaryAsync</summary>
        public async Task CreateGlossaryAsync_RequestObject()
        {
            // Snippet: CreateGlossaryAsync(CreateGlossaryRequest,CallSettings)
            // Create client
            TranslationServiceClient translationServiceClient = await TranslationServiceClient.CreateAsync();

            // Initialize request argument(s)
            CreateGlossaryRequest request = new CreateGlossaryRequest
            {
                ParentAsLocationName = new LocationName("[PROJECT]", "[LOCATION]"),
                Glossary             = new Glossary(),
            };
            // Make the request
            Operation <Glossary, CreateGlossaryMetadata> response =
                await translationServiceClient.CreateGlossaryAsync(request);

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

            // 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 =
                await translationServiceClient.PollOnceCreateGlossaryAsync(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
        }
Ejemplo n.º 21
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.º 22
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);
        }
Ejemplo n.º 23
0
        public async Task <IReadOnlyList <TranslationResult> > TranslateAsync(IEnumerable <string> texts, string targetLanguage, string sourceLanguage = null, CancellationToken ct = default)
        {
            var results = new List <TranslationResult>();

            if (string.IsNullOrWhiteSpace(options.ProjectId))
            {
                for (var i = 0; i < texts.Count(); i++)
                {
                    results.Add(TranslationResult.NotConfigured);
                }

                return(results);
            }

            if (!texts.Any())
            {
                return(results);
            }

            if (service == null)
            {
                service = new TranslationServiceClientBuilder().Build();
            }

            var request = new TranslateTextRequest
            {
                Parent = $"projects/{options.ProjectId}"
            };

            foreach (var text in texts)
            {
                request.Contents.Add(text);
            }

            request.TargetLanguageCode = GetLanguageCode(targetLanguage);

            if (sourceLanguage != null)
            {
                request.SourceLanguageCode = GetLanguageCode(sourceLanguage);
            }

            request.MimeType = "text/plain";

            try
            {
                var response = await service.TranslateTextAsync(request, ct);

                foreach (var translation in response.Translations)
                {
                    var language = GetSourceLanguage(translation.DetectedLanguageCode, sourceLanguage);

                    results.Add(new TranslationResult(translation.TranslatedText, language));
                }
            }
            catch (RpcException ex)
            {
                var result = GetResult(ex.Status);

                for (var i = 0; i < texts.Count(); i++)
                {
                    results.Add(result);
                }
            }

            return(results);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Translates a batch of texts on GCS and stores the result in a GCS location.
        /// Glossary is applied for translation.
        /// A model is used for translation. Can be AutoML or General (built-in) Model.
        /// </summary>
        /// <param name="targetLanguage">Target language code.</param>
        /// <param name="sourceLanguage">Source language code.</param>
        /// <param name="modelId">Translation model ID.</param>
        /// <param name="glossaryId">Translation Glossary ID.</param>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        /// <param name="location"> Region.</param>
        /// <param name="inputUri">The GCS path where input configuration is stored.</param>
        /// <param name="outputUri">The GCS path for translation output.</param>
        public static void BatchTranslateTextWithGlossaryAndModelSample(
            string inputUri       = "gs://cloud-samples-data/translation/text_with_custom_model_and_glossary.txt",
            string outputUri      = "gs://YOUR_BUCKET_ID/path_to_store_results/",
            string projectId      = "[Google Cloud Project ID]",
            string location       = "us-central1",
            string targetLanguage = "ja",
            string sourceLanguage = "en",
            string modelId        = "[YOUR-MODEL-ID]",
            string glossaryId     = "[YOUR_GLOSSARY_ID]")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();

            string modelPath    = $"projects/{projectId}/locations/{location}/models/{modelId}";
            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,
                    },
                },
                Models =
                {
                    // A model is used for Translation.
                    { targetLanguage, modelPath },
                },
                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}");
        }