public async Task <string> TranslateAsync(string inSentence, TranslationEngine translationEngine, TranslatorLanguague fromLang, TranslatorLanguague toLang) { string result = String.Empty; await Task.Run(() => { result = Translate(inSentence, translationEngine, fromLang, toLang); }); return(result); }
public string Translate(string inSentence, TranslationEngine translationEngine, TranslatorLanguague fromLang, TranslatorLanguague toLang) { if (fromLang.SystemName == "Auto") { if (translationEngine.EngineName != TranslationEngineName.GoogleTranslate) { var dLang = _LanguageDetector.TryDetectLanguague(inSentence); if (dLang.Length > 1) { var nLang = translationEngine.SupportedLanguages.FirstOrDefault(x => x.SystemName == dLang); if (nLang != null) { fromLang = nLang; } } } } if (fromLang.SystemName == toLang.SystemName) { return(inSentence); } if (inSentence.All(x => !char.IsLetter(x))) { return(inSentence); } switch (toLang.SystemName) { case "Korean": if (_LanguageDetector.HasKorean(inSentence)) { return(inSentence); } break; case "Japanese": if (_LanguageDetector.HasJapanese(inSentence)) { return(inSentence); } break; } TranslationRequest translationRequest = new TranslationRequest(inSentence, translationEngine.EngineName, fromLang.LanguageCode, toLang.LanguageCode); var cachedResult = transaltionCache.FirstOrDefault(x => x.Key == translationRequest); if (!cachedResult.Equals(defaultCachedResult)) { return(cachedResult.Value); } string result = String.Empty; inSentence = PreprocessSentence(inSentence); var fromLangCode = fromLang.LanguageCode; var toLangCode = toLang.LanguageCode; switch (translationEngine.EngineName) { case TranslationEngineName.GoogleTranslate: { result = GoogleTranslate(inSentence, fromLangCode, toLangCode); break; } case TranslationEngineName.DeepL: { result = DeeplTranslate(inSentence, fromLangCode, toLangCode); break; } case TranslationEngineName.Yandex: { result = YandexTranslate(inSentence, fromLangCode, toLangCode); break; } case TranslationEngineName.Papago: { result = PapagoTranslate(inSentence, fromLangCode, toLangCode); break; } case TranslationEngineName.Baidu: { result = BaiduTranslate(inSentence, fromLangCode, toLangCode); break; } default: { result = String.Empty; break; } } if (result.Length > 1) { cachedResult = transaltionCache.FirstOrDefault(x => x.Key == translationRequest); if (cachedResult.Equals(defaultCachedResult)) { transaltionCache.Add(new KeyValuePair <TranslationRequest, string>(translationRequest, result)); } if (transaltionCache.Count > GlobalTranslationSettings.TranslationCacheSize - 10) { transaltionCache.RemoveRange(0, GlobalTranslationSettings.TranslationCacheSize / 2); } } return(result); }