public string Translate(string Text, string targetlan) { try { LanguagesListResponse ls = new LanguagesListResponse(); Google.Apis.Translate.v2.Data.LanguagesResource ss = new Google.Apis.Translate.v2.Data.LanguagesResource(); if (targetlan == "en-US") targetlan = "en"; ss.Language = targetlan; // GetLanguageCode var service = new TranslateService(new BaseClientService.Initializer() { ApiKey = googlekey }); //new TranslateService { Key = googlekey }; ICollection<string> data = new Collection<string>(); string[] srcText = new[] { Text }; TranslationsListResponse response = service.Translations.List(srcText, targetlan).Execute(); var translations = new List<string>(); // We need to change this code... // currently this code foreach (Google.Apis.Translate.v2.Data.TranslationsResource translation in response.Translations) { translations.Add(translation.TranslatedText); } string translated = translations[0]; log.InfoFormat("[GoogleTranslate] Text={0}, targetlan={1}, translation={2}.", Text, targetlan, translated); if (translated != null && translated.IndexOf("'") > 0) { translated = translated.Replace("'", "'"); } return translated; } catch (Exception ex) { log.ErrorFormat("[Translate] Exception={0}.", ex); return null; } }
public string GoogleTranslate(string Text, string targetlan) { try { LanguagesListResponse ls = new LanguagesListResponse(); Google.Apis.Translate.v2.Data.LanguagesResource ss = new Google.Apis.Translate.v2.Data.LanguagesResource(); ss.Language = targetlan; // GetLanguageCode string googlekey = "AIzaSyCILytJnsn0FjzG6L7siOPeAqXTa9cQ0A8"; var service = new TranslateService(new BaseClientService.Initializer() { ApiKey = googlekey }); //new TranslateService { Key = googlekey }; ICollection<string> data = new Collection<string>(); string[] srcText = new[] { Text }; TranslationsListResponse response = service.Translations.List(srcText, targetlan).Execute(); var translations = new List<string>(); // We need to change this code... // currently this code foreach (Google.Apis.Translate.v2.Data.TranslationsResource translation in response.Translations) { translations.Add(translation.TranslatedText); } log.InfoFormat("[GoogleTranslate] Text={0}, targetlan={1}, translation={2}.", Text, targetlan, translations[0]); return translations[0]; } catch (Exception ex) { log.ErrorFormat("[GoogleTranslate] Exception={0}.", ex); return null; } }
/// <summary> /// Asynchronously calls the Translate API to translate a string from one language to /// another. /// </summary> /// <param name="service">An instance of the translate service.</param> /// <param name="text">The string to translate.</param> /// <param name="sourceLanguage">The code for the source language.</param> /// <param name="targetLanguage">The code for the target language.</param> /// <returns>A task that represents the asynchronous operation.</returns> /// <remarks> /// For a list of supported language codes, see /// https://cloud.google.com/translate/v2/using_rest#language-params. /// </remarks> private static async Task<string> TranslateTextAsync(TranslateService service, string text, string sourceLanguage, string targetLanguage) { var request = service.Translations.List(new[] { text }, targetLanguage); request.Source = sourceLanguage; request.Format = TranslationsResource.ListRequest.FormatEnum.Text; var response = await request.ExecuteAsync(); return response.Translations[0].TranslatedText; }
private async void TranslateBtn_Click(object sender, RoutedEventArgs e) { // In this sample, we create the service each time the user clicks. In a real application, consider // creating the service only once and then reusing the same instance for every request. var service = new TranslateService(new BaseClientService.Initializer() { ApiKey = API_KEY, ApplicationName = "Translate WP API Sample", }); // Execute the first translation request. var srcText = (string)this.DefaultViewModel["OriginalText"]; var targetLanguage = (string)this.DefaultViewModel["TargetLanguage"]; var translatedText = await TranslateTextAsync(service, srcText, "en", targetLanguage); this.DefaultViewModel["TranslatedText"] = translatedText; // Translate the text back to English to verify that the translation is right. var reTranslatedText = await TranslateTextAsync(service, translatedText, targetLanguage, "en"); this.DefaultViewModel["ReTranslatedText"] = reTranslatedText; }
public async Task RedeemUses([Remainder] string key = "") { if (string.IsNullOrWhiteSpace(key)) { await ReplyAsync($"Please enter a key or purchase one at: {TranslateService.GetTranslateConfig().StoreUrl}"); return; } var profile = TranslateService.License.GetQuantifiableUser(TranslateService.TranslateType, Context.Guild.Id); var redeemResult = TranslateService.License.RedeemLicense(profile, key); if (redeemResult == LicenseService.RedemptionResult.Success) { await ReplyAsync($"You have successfully redeemed the license. Current Balance is: {profile.RemainingUses()}"); } else if (redeemResult == LicenseService.RedemptionResult.AlreadyClaimed) { await ReplyAsync("License Already Redeemed"); } else if (redeemResult == LicenseService.RedemptionResult.InvalidKey) { await ReplyAsync("Invalid Key Provided"); } }
/// <summary> /// Translates input text, returning translated text. /// Documentation https://developers.google.com/translate/v2/reference/translations/list /// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong. /// </summary> /// <param name="service">Authenticated Translate service.</param> /// <param name="q">The input text to translate. Repeat this parameter to perform translationoperations on multiple text inputs.</param> /// <param name="target">The language to use for translation of the input text, set to one of thelanguage codes listed in Language Support.</param> /// <param name="optional">Optional paramaters.</param> /// <returns>TranslationsListResponseResponse</returns> public static TranslationsListResponse List(TranslateService service, string q, string target, TranslationsListOptionalParms optional = null) { try { // Initial validation. if (service == null) { throw new ArgumentNullException("service"); } if (q == null) { throw new ArgumentNullException(q); } if (target == null) { throw new ArgumentNullException(target); } // Building the initial request. var request = service.Translations.List(q, target); // Applying optional parameters to the request. request = (TranslationsResource.ListRequest)SampleHelpers.ApplyOptionalParms(request, optional); // Requesting data. return(request.Execute()); } catch (Exception ex) { throw new Exception("Request Translations.List failed.", ex); } }
public List <string> Trans(string[] words) { List <string> _results = new List <string>(); TranslateInput input = new TranslateInput(); input.TargetLanguage = "vi"; var service = new TranslateService(new BaseClientService.Initializer() { ApiKey = "AIzaSyA5naCjbPLqFdhaY6-f24bwoTwKSTHS9m4", ApplicationName = "CafeT" }); string[] srcText = words.Distinct().ToArray(); srcText = srcText.Take(100).ToArray(); try { var response = service.Translations.List(srcText, input.TargetLanguage).Execute(); foreach (TranslationsResource translation in response.Translations) { _results.Add(translation.TranslatedText); } } catch (Exception ex) { Console.WriteLine(ex.Message); } return(_results); }
static async Task Main(string[] args) { Dictionary <string, string> keyValue = new Dictionary <string, string>(); var service = new TranslateService(new BaseClientService.Initializer() { ApiKey = ConfigurationManager.AppSettings.Get("GoogleTranslateAPIKey").ToString(), ApplicationName = ConfigurationManager.AppSettings.Get("GoogleTranslateApplicationName").ToString() }); string json = @"{""Name"":""Mahesh"",""LastName"":""B"",""Gender"":""Male"",""Sample"":""Test""}"; //Deserialize the JSON string to Disctionary, as Google translate API requires IEnumerable<string> as input keyValue = JsonConvert.DeserializeObject <Dictionary <string, string> >(json); //Call google API for Translation var response = await service.Translations.List(keyValue.Values.ToArray <string>(), "fr").ExecuteAsync(); for (int i = 0; i < response.Translations.Count; i++) { //Get specific key at element and replace the translated text keyValue[keyValue.Keys.ElementAt(i)] = response.Translations[i].TranslatedText; } //Serialize key value pair back to JSON var outputJsonResult = JsonConvert.SerializeObject(keyValue); }
private void InitSortList() { SortListProperties.Add(new CustomComboboxItem() { DisplayText = TranslateService.ProvideValue("FileName"), Value = "FileName" }); SortListProperties.Add(new CustomComboboxItem() { DisplayText = TranslateService.ProvideValue("FileExt"), Value = "FileExtension" }); SortListProperties.Add(new CustomComboboxItem() { DisplayText = TranslateService.ProvideValue("EncryptDate"), Value = "FileEncryptionDate" }); SortListProperties.Add(new CustomComboboxItem() { DisplayText = TranslateService.ProvideValue("EncryptMethod"), Value = "FileEncryptionMethod" }); SelectedSortProperty = SortListProperties.FirstOrDefault(x => x.Value == SortListProperty); }
public async Task Translate(string languageCode, [Remainder] string message) { var config = TranslateService.GetTranslateGuild(Context.Guild.Id); //Ensure whitelist isn't enforced unless the list is populated if (config.WhitelistRoles.Any()) { //Check to see if the user has a whitelisted role if (!config.WhitelistRoles.Any(x => (Context.User as IGuildUser)?.RoleIds.Contains(x) == true)) { await ReplyAsync("You do not have enough permissions to run translations."); return; } } var response = TranslateService.Translate(Context.Guild.Id, message, languageCode); if (response.ResponseResult != TranslateService.TranslateResponse.Result.Success) { return; } var embed = TranslateService.GetTranslationEmbed(response); if (embed == null) { return; } await ReplyAsync("", false, embed.Build()); }
public async Task <IActionResult> Translate([FromServices] IGoogleAuthProvider auth, [FromServices] ClientInfo clientInfo) { // Programmatic auth check. if (await auth.RequireScopesAsync(TranslateService.Scope.CloudTranslation) is IActionResult authResult) { // If the required scopes are not authorized, then a non-null IActionResult will be returned, // which must be returned from the action. return(authResult); } // The required scopes have now been authorized. var cred = await auth.GetCredentialAsync(); var service = new TranslateService(new BaseClientService.Initializer { HttpClientInitializer = cred }); var translateRequest = service.Translations.Translate(new TranslateTextRequest { Format = "text", Q = new List <string> { "The cold weather will soon be over" }, Source = "en", Target = "fr", }); var response = await translateRequest.ExecuteAsync(); return(View((object)response.Translations.Single().TranslatedText)); }
public async Task <IActionResult> Translate([FromServices] IGoogleAuthProvider auth) { // Check if the required scopes have been granted. if (await auth.RequireScopesAsync(TranslateService.Scope.CloudTranslation) is IActionResult authResult) { // If the required scopes are not granted, then a non-null IActionResult will be returned, // which must be returned from the action. This triggers incremental authorization. // Once the user has granted the scope, an automatic redirect to this action will be issued. return(authResult); } // The required scopes have now been granted. GoogleCredential cred = await auth.GetCredentialAsync(); var service = new TranslateService(new BaseClientService.Initializer { HttpClientInitializer = cred }); var translateRequest = service.Translations.Translate(new TranslateTextRequest { Format = "text", Q = new List <string> { "The cold weather will soon be over" }, Source = "en", Target = "fr", }); var response = await translateRequest.ExecuteAsync(); return(View((object)response.Translations.Single().TranslatedText)); }
public static string ToVietnamese(this string text) { var key = new GoogleServices.GoogleServices().GetGoogleApiKey(); TranslateInput input = new TranslateInput(); input.SourceText = text; input.TargetLanguage = "vi"; // Create the service. var service = new TranslateService(new BaseClientService.Initializer() { ApiKey = key, ApplicationName = "MathBot" }); string[] srcText = new[] { input.SourceText }; var response = service.Translations.List(srcText, input.TargetLanguage).Execute(); var translations = new List <string>(); foreach (TranslationsResource translation in response.Translations) { translations.Add(translation.TranslatedText); } return(translations.FirstOrDefault()); }
private async Task <List <string> > TranslateStringsUsingGoogleAsync(string language, string apiKey, string appName, List <string> strings) { string from = MultiString.GetPrimaryLanguage(MultiString.DefaultLanguage); string to = MultiString.GetPrimaryLanguage(language); List <string> newStrings = new List <string>(); int total = strings.Count(); int skip = 0; while (total > 0) { TranslateService service = new TranslateService(new BaseClientService.Initializer() { ApiKey = apiKey, ApplicationName = appName, }); TranslationsListResponse resp = await service.Translations.List(strings.Skip(skip).Take(40).ToList(), to).ExecuteAsync(); List <string> returnedStrings = (from r in resp.Translations select r.TranslatedText).ToList(); returnedStrings = (from r in returnedStrings select Utility.HtmlDecode(r)).ToList(); newStrings.AddRange(returnedStrings); skip += returnedStrings.Count(); total -= returnedStrings.Count(); } return(newStrings); }
public Translator() { var keyJsonFilepath = Path.Combine( Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"key.json"); try { var credential = GoogleCredential.FromFile(keyJsonFilepath); if (!(credential.UnderlyingCredential is ServiceAccountCredential)) { throw new Exception("key.json should define a ServiceAccountCredential"); } _projectId = ((ServiceAccountCredential)credential.UnderlyingCredential).ProjectId; if (credential.IsCreateScopedRequired) { credential = credential.CreateScoped(TranslateService.Scope.CloudTranslation); } _translateService = new TranslateService(new BaseClientService.Initializer { ApplicationName = nameof(GoogleApisTranslateWrapper), HttpClientInitializer = credential }); } catch (Exception ex) { } }
public async Task <string> Translate(string phrase) { _logger.LogInformation($"Translating phrase: {phrase}"); var apiKey = _secretProvider.GetSecret("GoogleTranslateApiKey/bce3d012310e4196a430a8d731990f9c"); using (var service = new TranslateService(new BaseClientService.Initializer { ApiKey = apiKey, ApplicationName = ApplicationName })) { try { var response = await service.Translations.List(new[] { phrase }, "en").ExecuteAsync(); if (response.Translations.Count > 0) { return(CleanTranslation(response.Translations[0].TranslatedText)); } } catch (Exception ex) { _logger.LogError(ex, $"Error occurred while attempting to call the transation service. Unable to translate phrase: {phrase}"); } return(string.Empty); } }
public override void AfterCreateEntity(TEntity t) { Type thisType = GetType(); PropertyInfo[] thisProperties = thisType.GetProperties(); TranslateService translateService = ServiceProvider.GetService <TranslateService>(); foreach (var localization in Localizations) { Type localization_Type = localization.GetType(); PropertyInfo[] localization_Properties = localization_Type.GetProperties(); foreach (PropertyInfo localization_Property in localization_Properties) { if (localization_Property.IsStringProperty()) { PropertyInfo thisProperty = thisProperties.FirstOrDefault(w => w.Name == localization_Property.Name); if (thisProperty == null) { continue; } translateService.Translate( thisProperty.GetValue(this, null)?.ToString(), localization_Property.GetValue(localization, null)?.ToString(), localization.CultureCode); } } } }
public TranslationResult TranslateText(string source, string sourceLanguage, string targetLanguage) { if (!IsValidLanguageCode(targetLanguage)) { throw new Exception("Invalid Target Language Code."); } else if (!IsValidLanguageCode(sourceLanguage)) { throw new Exception("Invalid Source Language Code."); } var response = TranslateMessageAsync(source, targetLanguage, source).Result; if (response.translatedMessage == null) { return(null); } var result = new TranslationResult(); result.DestinationLanguage = targetLanguage; result.SourceLanguage = sourceLanguage; result.SourceText = source; result.TranslatedText = TranslateService.FixTranslatedString(response.translatedMessage); return(result); }
public void Translate() { GoogleCredential credential = Helper.GetServiceCredential().CreateScoped(TranslateService.Scope.CloudTranslation); TranslateService client = new TranslateService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "IntegrationTest" }); var translateRequest = client.Translations.Translate(new TranslateTextRequest { Format = "text", Q = new List <string> { "The cold weather will soon be over" }, Source = "en", Target = "fr", }); var response = translateRequest.Execute(); Assert.Single(response.Translations); // We sometimes get: // Le temps froid sera bientôt fini // Le froid sera bientôt terminé Assert.Contains("froid sera bientôt", response.Translations[0].TranslatedText); }
public FavDialog(Accessor accessor, PowerTwitterService powerTwitterService, TranslateService translateService, TranslateDialog translateDialog) { _translateService = translateService; _accessor = accessor; _powerTwitterService = powerTwitterService; _translateDialog = translateDialog; }
public GoogleTranslator() { _translateService = new TranslateService(new BaseClientService.Initializer() { ApiKey = ConfigurationManager.AppSettings["GoogleApiKey"] }); }
public override IActionResult Delete(int id) { var entity = Service.ByID(id); if (entity == null) { return(NotFound()); } entity.Icon = entity.Icon.GetFullPath("Storage:Images"); if (!string.IsNullOrEmpty(entity.Icon)) { if (System.IO.File.Exists(entity.Icon)) { System.IO.File.Delete(entity.Icon); } } CultureViewModel model = Activator.CreateInstance <CultureViewModel>(); model.GetKeys(entity); if (Service.TryDelete(entity)) { model.AfterDeleteEntity(entity); if (!TranslateService.HasTranslationTable(model.Code)) { TranslateService.DeleteTranslationTable(model.Code); } } CultureHelper.ReLoad(); return(Ok(OperationType.Delete)); }
public async void TranslateText() { //번역 서비스 생성 TranslateService service = new TranslateService(new BaseClientService.Initializer() { ApiKey = this.textBox3.Text, ApplicationName = " " }); //string[] srcText = new[] { "Hello world!", "The Google APIs client library for .NET uses client_secrets.json files for storing the client_id, client_secret, and other OAuth 2.0 parameters." }; try { //번역 요청 TranslationsListResponse response = await service.Translations.List(textBox1.Text, "ko").ExecuteAsync(); //결과를 저장 textBox2.Text = response.Translations[0].TranslatedText; } catch (Exception ex) { //api에서 문제가 생겨도 여기서 오류가 발생한다. //오류 내용을 확인해서 로그를 남겨야 할듯 Console.WriteLine("오류 :" + ex.ToString()); } }
void listen1() { srcText = textBox1.Text; String[] target_language_shortname = new String[] { "af", "sq", "am", "ar", "hy", "az", "eu", "be", "bn", "bs", "bg", "ca", "ceb", "ny", "zh-CN", "zh-TW", "co", "hr", "cs", "da", "nl", "en", "eo", "et", "tl", "fi", "fr", "fy", "gl", "ka", "de", "el", "gu", "ht", "ha", "haw", "iw", "hi", "hmn", "hu", "is", "ig", "id", "ga", "it", "ja", "jw", "kn", "kk", "km", "ko", "ku", "ky", "lo", "la", "lv", "lt", "lb", "mk", "mg", "ms", "ml", "mt", "mi", "mr", "mn", "my", "ne", "no", "ps", "fa", "pl", "pt", "ma", "ro", "ru", "sm", "gd", "sr", "st", "sn", "sd", "si", "sk", "sl", "so", "es", "su", "sw", "sv", "tg", "ta", "te", "th", "tr", "uk", "ur", "uz", "vi", "cy", "xh", "yi", "yo", "zu" }; var service = new TranslateService(new BaseClientService.Initializer() { ApiKey = "AIzaSyAsjrVKsPasvqfcZnvrIayprnql5zEIt0M", // your API key, that you get from Google Developer Console ApplicationName = "API key 1" // your application name, that you get form Google Developer Console }); TranslationsListResponse response = service.Translations.List(srcText, "en").Execute(); foreach (TranslationsResource t in response.Translations) { detect = t.DetectedSourceLanguage; } try { text = textBox1.Text; mp3path = Environment.CurrentDirectory + @"tmp.mp3"; wavpath = Environment.CurrentDirectory + @"\me\me.wav"; urltts = new Uri("http://translate.google.com/translate_tts?client=tw-ob&tl=" + detect + "-gb&q=" + text); using (tts = new WebClient()) { tts.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 9.0; Windows;)"); tts.DownloadFile(urltts, mp3path); } using (reader = new Mp3FileReader(new FileStream(mp3path, FileMode.OpenOrCreate))) { WaveFileWriter.CreateWaveFile(wavpath, reader); } SoundPlayer simpleSound = new SoundPlayer(@"C:\Users\Abdullah\Documents\Visual Studio 2013\Projects\LanguageTranslatorProject\LanguageTranslatorProject\bin\Debug\me\me.wav"); simpleSound.Play(); //MessageBox.Show("hogya"); } catch { MessageBox.Show("Error. Clear the screen first.\nNote that some languages are not supported."); } }
public async Task ToggleDmReactions() { var config = TranslateService.GetTranslateGuild(Context.Guild.Id); config.DirectMessageTranslations = !config.DirectMessageTranslations; TranslateService.SaveTranslateGuild(config); await ReplyAsync($"DM Users Translations: {config.DirectMessageTranslations}"); }
public async Task ToggleReactions() { var config = TranslateService.GetTranslateGuild(Context.Guild.Id); config.ReactionTranslations = !config.ReactionTranslations; TranslateService.SaveTranslateGuild(config); await ReplyAsync($"Translation Reactions Enabled: {config.ReactionTranslations}"); }
public Translator() { TranService = new TranslateService(new BaseClientService.Initializer() { ApiKey = CurrentApiKey, ApplicationName = CurrentApplicationName }); }
private async void CommandHandler(object sender, ExecutedRoutedEventArgs ea) { var tweet = (TwitterStatus)ea.Parameter; var lang = CultureInfo.InstalledUICulture.TwoLetterISOLanguageName; tweet.TranslatedText = (string)Application.Current.FindResource("translate-text-working"); tweet.TranslatedText = await TranslateService.Translate(tweet.FullText, lang).ConfigureAwait(true); }
private void GoogleToolStripMenuItem_Click(object sender, EventArgs e) { YoudaoToolStripMenuItem.Checked = false; BaiduToolStripMenuItem.Checked = false; MicrosoftToolStripMenuItem.Checked = false; GoogleToolStripMenuItem.Checked = true; translateService = new GoogleTranslateService(); }
public async Task RemoveWhitelistRole(ulong roleId) { var config = TranslateService.GetTranslateGuild(Context.Guild.Id); config.WhitelistRoles.Remove(roleId); TranslateService.SaveTranslateGuild(config); await ReplyAsync("Role removed."); }
/// <inheritdoc /> public override TranslationClient Build() { Validate(); var initializer = CreateServiceInitializer(); var service = new TranslateService(initializer); return(new TranslationClientImpl(service, TranslationModel)); }
public static async Task <string> ToUserLocale(this string text, IDialogContext context) { context.UserData.TryGetValue(AppSettings.UserLanguageKey, out string userLanguageCode); text = await TranslateService.TranslateAsync(text, AppSettings.DefaultLanguage, userLanguageCode); return(text); }
public GoogleTranslate(Translation translation) { _translation = translation; _translateService = new TranslateService(new BaseClientService.Initializer { ApplicationName = _googleApplicationName, ApiKey = _googleApiKey, }); }
public void InitializerBaseUriIsUsedByGeneratedServices(string initializerUri, string expectedServiceUri) { var service = new TranslateService(new BaseClientService.Initializer { BaseUri = initializerUri }); Assert.Equal(expectedServiceUri, service.BaseUri); }
static void Main(string[] args) { // Initialize this sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("Translate Sample"); // Ask for the user input. TranslateInput input = CommandLine.CreateClassFromUserinput<TranslateInput>(); // Create the service. var service = new TranslateService { Key = GetApiKey() }; // Execute the first translation request. CommandLine.WriteAction("Translating to '"+input.TargetLanguage+"' ..."); string[] srcText = new[] { "Hello world!", input.SourceText }; TranslationsListResponse response = service.Translations.List(srcText, input.TargetLanguage).Fetch(); var translations = new List<string>(); foreach (TranslationsResource translation in response.Translations) { translations.Add(translation.TranslatedText); CommandLine.WriteResult("translation", translation.TranslatedText); } // Translate the text (back) to english. CommandLine.WriteAction("Translating to english ..."); response = service.Translations.List(translations, "en").Fetch(); foreach (TranslationsResource translation in response.Translations) { CommandLine.WriteResult("translation", translation.TranslatedText); } // ...and we are done. CommandLine.PressAnyKeyToExit(); }