public override void Translate(ITranslationSession translationSession) { using (var client = new TerminologyClient(_binding, _endpoint)) { var translationSources = new TranslationSources() { TranslationSource.UiStrings }; foreach (var item in translationSession.Items) { if (translationSession.IsCanceled) { break; } Contract.Assume(item != null); var targetCulture = item.TargetCulture.Culture ?? translationSession.NeutralResourcesLanguage; if (targetCulture.IsNeutralCulture) { targetCulture = CultureInfo.CreateSpecificCulture(targetCulture.Name); } try { var response = client.GetTranslations(item.Source, translationSession.SourceLanguage.Name, targetCulture.Name, SearchStringComparison.CaseInsensitive, SearchOperator.Contains, translationSources, false, 5, false, null); if (response != null) { translationSession.Dispatcher.BeginInvoke(() => { Contract.Requires(item != null); Contract.Requires(response != null); foreach (var match in response) { Contract.Assume(match != null); foreach (var trans in match.Translations) { item.Results.Add(new TranslationMatch(this, trans.TranslatedText, match.ConfidenceLevel / 100.0)); } } }); } } catch (Exception ex) { translationSession.AddMessage(DisplayName + ": " + ex.Message); break; } } } }
public override void Translate(ITranslationSession translationSession) { foreach (var item in translationSession.Items) { if (translationSession.IsCanceled) { break; } var translationItem = item; Contract.Assume(translationItem != null); try { Contract.Assume(Credentials.Count == 1); var targetCulture = translationItem.TargetCulture.Culture ?? translationSession.NeutralResourcesLanguage; var result = TranslateText(translationItem.Source, Credentials[0]?.Value, translationSession.SourceLanguage, targetCulture); translationSession.Dispatcher.BeginInvoke(() => { if (result.Matches != null) { foreach (var match in result.Matches) { var translation = match.Translation; if (string.IsNullOrEmpty(translation)) { continue; } translationItem.Results.Add(new TranslationMatch(this, translation, match.Match.GetValueOrDefault() * match.Quality.GetValueOrDefault() / 100.0)); } } else { var translation = result.ResponseData.TranslatedText; if (!string.IsNullOrEmpty(translation)) { translationItem.Results.Add(new TranslationMatch(this, translation, result.ResponseData.Match.GetValueOrDefault())); } } }); } catch (Exception ex) { translationSession.AddMessage(DisplayName + ": " + ex.Message); break; } } }
public override void Translate(ITranslationSession translationSession) { using (var client = new TerminologyClient(_binding, _endpoint)) { var translationSources = new TranslationSources { TranslationSource.UiStrings }; foreach (var item in translationSession.Items) { if (translationSession.IsCanceled) { break; } var targetCulture = item.TargetCulture.Culture ?? translationSession.NeutralResourcesLanguage; if (targetCulture.IsNeutralCulture) { targetCulture = CultureInfo.CreateSpecificCulture(targetCulture.Name); } try { var response = client.GetTranslations(item.Source, translationSession.SourceLanguage.Name, targetCulture.Name, SearchStringComparison.CaseInsensitive, SearchOperator.Contains, translationSources, false, 5, false, null); if (response != null) { var matches = response .SelectMany(match => match?.Translations?.Select(trans => new TranslationMatch(this, trans?.TranslatedText, match.ConfidenceLevel / 100.0))) .Where(m => m?.TranslatedText != null) .Distinct(TranslationMatch.TextComparer); translationSession.Dispatcher.BeginInvoke(() => { item.Results.AddRange(matches); }); } } catch (Exception ex) { translationSession.AddMessage(DisplayName + ": " + ex.Message); break; } } } }
public override async Task Translate(ITranslationSession translationSession) { using (var client = new TerminologyClient(_binding, _endpoint)) { var translationSources = new TranslationSources { TranslationSource.UiStrings }; foreach (var item in translationSession.Items) { if (translationSession.IsCanceled) { break; } var targetCulture = item.TargetCulture.Culture ?? translationSession.NeutralResourcesLanguage; if (targetCulture.IsNeutralCulture) { targetCulture = CultureInfo.CreateSpecificCulture(targetCulture.Name); } try { var response = await client.GetTranslationsAsync( item.Source, translationSession.SourceLanguage.Name, targetCulture.Name, SearchStringComparison.CaseInsensitive, SearchOperator.Contains, translationSources, false, 5, false, null) .ConfigureAwait(false); if (response != null) { var matches = response .SelectMany(match => match?.Translations?.Select(trans => new TranslationMatch(this, trans?.TranslatedText, match.ConfidenceLevel / 100.0))) .Where(m => m?.TranslatedText != null) .Distinct(TranslationMatch.TextComparer); #pragma warning disable CS4014 // Because this call is not awaited ... => just push out results, no need to wait. translationSession.MainThread.StartNew(() => item.Results.AddRange(matches)); } } catch (Exception ex) { translationSession.AddMessage(DisplayName + ": " + ex.Message); break; } } } }
async Task ITranslator.Translate(ITranslationSession translationSession) { try { IsActive = true; await Translate(translationSession).ConfigureAwait(false); } catch (Exception ex) { translationSession.AddMessage(DisplayName + ": " + string.Join(" => ", ex.ExceptionChain().Select(item => item.Message))); } finally { IsActive = false; } }
public void Translate([NotNull] ITranslationSession translationSession) { Contract.Requires(translationSession != null); var translatorCounter = 0; foreach (var translator in Translators) { Contract.Assume(translator != null); var local = translator; if (!local.IsEnabled) { continue; } Interlocked.Increment(ref translatorCounter); ThreadPool.QueueUserWorkItem(_ => { try { local.Translate(translationSession); } finally { // ReSharper disable once AccessToModifiedClosure if (Interlocked.Decrement(ref translatorCounter) == 0) { translationSession.IsComplete = true; } } }); } if (translatorCounter == 0) { translationSession.IsComplete = true; } }
protected override async Task Translate(ITranslationSession translationSession) { using (var client = new TerminologyClient(_binding, _endpoint)) { var translationSources = new TranslationSources { TranslationSource.UiStrings }; foreach (var item in translationSession.Items) { if (translationSession.IsCanceled) { break; } var targetCulture = item.TargetCulture.Culture ?? translationSession.NeutralResourcesLanguage; if (targetCulture.IsNeutralCulture) { targetCulture = CultureInfo.CreateSpecificCulture(targetCulture.Name); } var response = await client.GetTranslationsAsync( item.Source, translationSession.SourceLanguage.Name, targetCulture.Name, SearchStringComparison.CaseInsensitive, SearchOperator.Contains, translationSources, false, 5, false, null) .ConfigureAwait(false); if (response != null) { var matches = response .SelectMany(match => match?.Translations?.Select(trans => new TranslationMatch(this, trans?.TranslatedText, Ranking * match.ConfidenceLevel / 100.0))) .Where(m => m?.TranslatedText != null) .Distinct(TranslationMatch.TextComparer); await translationSession.MainThread.StartNew(() => item.Results.AddRange(matches)).ConfigureAwait(false); } } } }
public abstract void Translate(ITranslationSession translationSession);
void ITranslator.Translate(ITranslationSession translationSession) { Contract.Requires(translationSession != null); throw new NotImplementedException(); }
protected abstract Task Translate(ITranslationSession translationSession);
public override void Translate(ITranslationSession translationSession) { try { Contract.Assume(Credentials.Count == 2); var clientId = Credentials[0]?.Value; var clientSecret = Credentials[1]?.Value; if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(clientSecret)) { translationSession.AddMessage("Bing Translator requires client id and secret."); return; } var token = AdmAuthentication.GetAuthToken(WebProxy, clientId, clientSecret); var binding = new BasicHttpBinding(); var endpointAddress = new EndpointAddress("http://api.microsofttranslator.com/V2/soap.svc"); using (var client = new LanguageServiceClient(binding, endpointAddress)) { using (new OperationContextScope(client.InnerChannel)) { var httpRequestProperty = new HttpRequestMessageProperty(); httpRequestProperty.Headers.Add("Authorization", token); var operationContext = OperationContext.Current; Contract.Assume(operationContext != null); // because we are inside OperationContextScope operationContext.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty; foreach (var languageGroup in translationSession.Items.GroupBy(item => item.TargetCulture)) { Contract.Assume(languageGroup != null); var cultureKey = languageGroup.Key; Contract.Assume(cultureKey != null); var targetLanguage = cultureKey.Culture ?? translationSession.NeutralResourcesLanguage; using (var itemsEnumerator = languageGroup.GetEnumerator()) { while (true) { var sourceItems = itemsEnumerator.Take(10); var sourceStrings = sourceItems.Select(item => item.Source).ToArray(); if (!sourceStrings.Any()) { break; } var response = client.GetTranslationsArray("", sourceStrings, translationSession.SourceLanguage.IetfLanguageTag, targetLanguage.IetfLanguageTag, 5, new TranslateOptions() { ContentType = "text/plain", IncludeMultipleMTAlternatives = true }); translationSession.Dispatcher.BeginInvoke(() => ReturnResults(sourceItems, response)); if (translationSession.IsCanceled) { break; } } } } } } } catch (Exception ex) { translationSession.AddMessage("Bing translator reported a problem: " + ex); } }
public override void Translate(ITranslationSession translationSession) { }
public override async void Translate(ITranslationSession translationSession) { try { var authenticationKey = AuthenticationKey; if (string.IsNullOrEmpty(authenticationKey)) { translationSession.AddMessage("Azure Translator requires subscription secret."); return; } var token = await AzureAuthentication.GetBearerAccessTokenAsync(authenticationKey).ConfigureAwait(false); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", token); foreach (var languageGroup in translationSession.Items.GroupBy(item => item.TargetCulture)) { var cultureKey = languageGroup.Key; var targetLanguage = cultureKey.Culture ?? translationSession.NeutralResourcesLanguage; var uri = new Uri($"https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from={translationSession.SourceLanguage.IetfLanguageTag}&to={targetLanguage.IetfLanguageTag}"); using (var itemsEnumerator = languageGroup.GetEnumerator()) { while (true) { var sourceItems = itemsEnumerator.Take(10); var sourceStrings = sourceItems // ReSharper disable once PossibleNullReferenceException .Select(item => item.Source) .Select(RemoveKeyboardShortcutIndicators) .ToArray(); if (!sourceStrings.Any()) { break; } var response = await client.PostAsync(uri, CreateRequestContent(sourceStrings)).ConfigureAwait(false); if (response.IsSuccessStatusCode) { var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); using (var reader = new StreamReader(stream, Encoding.UTF8)) { var translations = JsonConvert.DeserializeObject <List <AzureTranslationResponse> >(reader.ReadToEnd()); if (translations != null) { #pragma warning disable CS4014 // Because this call is not awaited ... => just push out results, no need to wait. translationSession.Dispatcher.BeginInvoke(() => ReturnResults(sourceItems, translations)); } } } else { var errorMessage = await response.Content.ReadAsStringAsync().ConfigureAwait(false); translationSession.AddMessage("Azure translator reported a problem: " + errorMessage); } if (translationSession.IsCanceled) { break; } } } } } } catch (Exception ex) { translationSession.AddMessage("Azure translator reported a problem: " + ex); } }
public override async void Translate(ITranslationSession translationSession) { try { var authenticationKey = Credentials[0].Value; if (string.IsNullOrEmpty(authenticationKey)) { translationSession.AddMessage("Azure Translator requires subscription secret."); return; } var token = await AzureAuthentication.GetBearerAccessTokenAsync(authenticationKey); var binding = new BasicHttpBinding(); var endpointAddress = new EndpointAddress("http://api.microsofttranslator.com/V2/soap.svc"); using (var client = new LanguageServiceClient(binding, endpointAddress)) { var innerChannel = client.InnerChannel; // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (innerChannel == null) { // ReSharper disable once HeuristicUnreachableCode return; } using (new OperationContextScope(innerChannel)) { var httpRequestProperty = new HttpRequestMessageProperty(); httpRequestProperty.Headers.Add("Authorization", token); var operationContext = OperationContext.Current; Contract.Assume(operationContext != null); // because we are inside OperationContextScope operationContext.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty; foreach (var languageGroup in translationSession.Items.GroupBy(item => item.TargetCulture)) { Contract.Assume(languageGroup != null); var cultureKey = languageGroup.Key; Contract.Assume(cultureKey != null); var targetLanguage = cultureKey.Culture ?? translationSession.NeutralResourcesLanguage; using (var itemsEnumerator = languageGroup.GetEnumerator()) { while (true) { var sourceItems = itemsEnumerator.Take(10); var sourceStrings = sourceItems.Select(item => item.Source).ToArray(); if (!sourceStrings.Any()) { break; } var translateOptions = new TranslateOptions() { ContentType = "text/plain", IncludeMultipleMTAlternatives = true }; var response = client.GetTranslationsArray("", sourceStrings, translationSession.SourceLanguage.IetfLanguageTag, targetLanguage.IetfLanguageTag, 5, translateOptions); if (response != null) { #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed => just push out results, no need to wait. translationSession.Dispatcher.BeginInvoke(() => ReturnResults(sourceItems, response)); } if (translationSession.IsCanceled) { break; } } } } } } } catch (Exception ex) { translationSession.AddMessage("Azure translator reported a problem: " + ex); } }
public abstract Task Translate(ITranslationSession translationSession);
public override void Translate(ITranslationSession translationSession) { if (string.IsNullOrEmpty(APIKey)) { translationSession.AddMessage("Google Translator requires API Key."); return; } foreach (var languageGroup in translationSession.Items.GroupBy(item => item.TargetCulture)) { if (translationSession.IsCanceled) { break; } Contract.Assume(languageGroup != null); var targetCulture = languageGroup.Key.Culture ?? translationSession.NeutralResourcesLanguage; using (var itemsEnumerator = languageGroup.GetEnumerator()) { var loop = true; while (loop) { var sourceItems = itemsEnumerator.Take(10); if (translationSession.IsCanceled || !sourceItems.Any()) { break; } // Build out list of parameters var parameters = new List <string>(30); foreach (var item in sourceItems) { parameters.AddRange(new[] { "q", RemoveKeyboardShortcutIndicators(item.Source) }); } parameters.AddRange(new[] { "target", GoogleLangCode(targetCulture), "format", "text", "source", GoogleLangCode(translationSession.SourceLanguage), "model", "base", "key", APIKey }); // Call the Google API var responseTask = GetHttpResponse("https://translation.googleapis.com/language/translate/v2", null, parameters, JsonConverter <TranslationRootObject>); // Handle successful run responseTask.ContinueWith(t => { translationSession.Dispatcher.BeginInvoke(() => { foreach (var tuple in sourceItems.Zip(t.Result.Data.Translations, (a, b) => new Tuple <ITranslationItem, string>(a, b.TranslatedText))) { Contract.Assume(tuple != null); Contract.Assume(tuple.Item1 != null); Contract.Assume(tuple.Item2 != null); tuple.Item1.Results.Add(new TranslationMatch(this, tuple.Item2, 1.0)); } }); }, TaskContinuationOptions.OnlyOnRanToCompletion); // Handle exception in run responseTask.ContinueWith(t => { translationSession.AddMessage(DisplayName + ": " + t.Exception?.InnerException?.Message); loop = false; }, TaskContinuationOptions.OnlyOnFaulted); } } } }
protected override async Task Translate(ITranslationSession translationSession) { var authenticationKey = AuthenticationKey; if (string.IsNullOrEmpty(authenticationKey)) { translationSession.AddMessage("Azure Translator requires subscription secret."); return; } var token = await AzureAuthentication.GetBearerAccessTokenAsync(authenticationKey, translationSession.CancellationToken).ConfigureAwait(false); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", token); var throttle = new Throttle(MaxCharactersPerMinute, translationSession.CancellationToken); var itemsByLanguage = translationSession.Items.GroupBy(item => item.TargetCulture); foreach (var languageGroup in itemsByLanguage) { var cultureKey = languageGroup.Key; var targetLanguage = cultureKey.Culture ?? translationSession.NeutralResourcesLanguage; var itemsByTextType = languageGroup.GroupBy(GetTextType); foreach (var textTypeGroup in itemsByTextType) { var textType = textTypeGroup.Key; foreach (var sourceItems in SplitIntoChunks(translationSession, textTypeGroup)) { if (!sourceItems.Any()) { break; } var sourceStrings = sourceItems .Select(item => item.Source) .Select(RemoveKeyboardShortcutIndicators) .ToList(); await throttle.Tick(sourceItems); if (translationSession.IsCanceled) { return; } var uri = new Uri($"https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from={translationSession.SourceLanguage.IetfLanguageTag}&to={targetLanguage.IetfLanguageTag}&textType={textType}"); var response = await client.PostAsync(uri, CreateRequestContent(sourceStrings), translationSession.CancellationToken).ConfigureAwait(false); response.EnsureSuccessStatusCode(); var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); using (var reader = new StreamReader(stream, Encoding.UTF8)) { var translations = JsonConvert.DeserializeObject <List <AzureTranslationResponse> >(reader.ReadToEnd()); if (translations != null) { await translationSession.MainThread.StartNew(() => ReturnResults(sourceItems, translations)).ConfigureAwait(false); } } } } } } }
public override async void Translate(ITranslationSession translationSession) { if (string.IsNullOrEmpty(ApiKey)) { translationSession.AddMessage("Google Translator requires API Key."); return; } foreach (var languageGroup in translationSession.Items.GroupBy(item => item.TargetCulture)) { if (translationSession.IsCanceled) { break; } var targetCulture = languageGroup.Key.Culture ?? translationSession.NeutralResourcesLanguage; using (var itemsEnumerator = languageGroup.GetEnumerator()) { var loop = true; while (loop) { var sourceItems = itemsEnumerator.Take(10); if (translationSession.IsCanceled || !sourceItems.Any()) { break; } // Build out list of parameters var parameters = new List <string>(30); foreach (var item in sourceItems) { // ReSharper disable once PossibleNullReferenceException parameters.AddRange(new[] { "q", RemoveKeyboardShortcutIndicators(item.Source) }); } parameters.AddRange(new[] { "target", GoogleLangCode(targetCulture), "format", "text", "source", GoogleLangCode(translationSession.SourceLanguage), "model", "base", "key", ApiKey }); try { // Call the Google API // ReSharper disable once AssignNullToNotNullAttribute var response = await GetHttpResponse("https://translation.googleapis.com/language/translate/v2", null, parameters, JsonConverter <TranslationRootObject>).ConfigureAwait(false); await translationSession.Dispatcher.BeginInvoke(() => { foreach (var tuple in sourceItems.Zip(response.Data.Translations, (a, b) => new Tuple <ITranslationItem, string>(a, b.TranslatedText))) { tuple.Item1.Results.Add(new TranslationMatch(this, tuple.Item2, 1.0)); } }); } catch (Exception ex) { translationSession.AddMessage(DisplayName + ": " + ex.InnerException?.Message); loop = false; } } } } }