Beispiel #1
0
        public void UpdateLanguageMappingModel(LanguageMappingModel languageMappingModel)
        {
            var translationModels = LanguageMappingsService.GetTranslationModels(
                languageMappingModel.SelectedSource, languageMappingModel.SelectedTarget, languageMappingModel.SourceTradosCode,
                languageMappingModel.TargetTradosCode);

            if (translationModels.Any())
            {
                // assign the selected model
                var selectedModel =
                    translationModels.FirstOrDefault(a => string.Compare(a.DisplayName,
                                                                         languageMappingModel.SelectedModel?.DisplayName,
                                                                         StringComparison.InvariantCultureIgnoreCase) == 0)
                    ?? translationModels.FirstOrDefault(a =>
                                                        string.Compare(a.Model, "generic", StringComparison.InvariantCultureIgnoreCase) == 0)
                    ?? translationModels[0];

                languageMappingModel.Models        = translationModels;
                languageMappingModel.SelectedModel = selectedModel;
            }

            var dictionaries =
                LanguageMappingsService.GetDictionaries(languageMappingModel.SelectedSource,
                                                        languageMappingModel.SelectedTarget);

            // assign the selected dictionary
            var selectedDictionary =
                dictionaries.FirstOrDefault(a => a.Name.Equals(languageMappingModel.SelectedDictionary?.Name))
                ?? dictionaries[0];

            languageMappingModel.Dictionaries       = dictionaries;
            languageMappingModel.SelectedDictionary = selectedDictionary;
        }
Beispiel #2
0
        private LanguageMappingModel GetLanguageMappingModel(InternalLanguageMapping mapping)
        {
            // assign the selected model
            var selectedModel = mapping.EngineModels.FirstOrDefault(a => a.DisplayName.Equals(mapping.SavedLanguageMappingModel?.SelectedModel?.DisplayName, StringComparison.InvariantCultureIgnoreCase))
                                ?? mapping.EngineModels.FirstOrDefault(a => a.Model.Equals("generic", StringComparison.InvariantCultureIgnoreCase))
                                ?? mapping.EngineModels[0];

            var dictionaries = LanguageMappingsService.GetDictionaries(mapping.SelectedSourceLanguageMapping, mapping.SelectedTargetLanguageMapping);

            // assign the selected dictionary
            var selectedDictionary =
                dictionaries.FirstOrDefault(a => a.Name.Equals(mapping.SavedLanguageMappingModel?.SelectedDictionary?.Name))
                ?? dictionaries[0];

            var languageMappingModel = new LanguageMappingModel
            {
                Name               = mapping.Name,
                SourceLanguages    = mapping.SourceLanguageMappings,
                TargetLanguages    = mapping.TargetLanguageMappings,
                SelectedSource     = mapping.SelectedSourceLanguageMapping,
                SelectedTarget     = mapping.SelectedTargetLanguageMapping,
                SourceTradosCode   = mapping.SourceLanguageCode.TradosCode,
                TargetTradosCode   = mapping.TargetLanguageCode.TradosCode,
                Models             = mapping.EngineModels,
                SelectedModel      = selectedModel,
                Dictionaries       = dictionaries,
                SelectedDictionary = selectedDictionary
            };

            return(languageMappingModel);
        }
Beispiel #3
0
        public async Task <Segment[]> TranslateText(string text, LanguageMappingModel model, FileAndSegmentIds fileAndSegments)
        {
            if (string.IsNullOrEmpty(model?.SelectedModel?.Model))
            {
                throw new Exception(PluginResources.Message_No_model_selected);
            }

            CheckConnection();

            var uri     = new Uri($"{Constants.MTCloudTranslateAPIUri}/v4/mt/translations/async");
            var request = GetRequestMessage(HttpMethod.Post, uri);

            var engineModel             = model.SelectedModel.Model;
            var translationRequestModel = new TranslationRequest
            {
                Input             = new[] { text },
                SourceLanguageId  = model.SelectedSource.CodeName,
                TargetLanguageId  = model.SelectedTarget.CodeName,
                Model             = engineModel,
                InputFormat       = "xliff",
                QualityEstimation = engineModel.ToLower().Contains("qe") ? 1 : 0
            };

            if (!model.SelectedDictionary.Name.Equals(PluginResources.Message_No_dictionary_available) &&
                !model.SelectedDictionary.Name.Equals(PluginResources.Message_No_dictionary))
            {
                translationRequestModel.Dictionaries = new[] { model.SelectedDictionary?.DictionaryId };
            }

            var content = JsonConvert.SerializeObject(translationRequestModel);

            request.Content = new StringContent(content, new UTF8Encoding(), "application/json");

            var response = await _httpClient.SendRequest(request);

            var translationResponse = await _httpClient.GetResult <TranslationResponse>(response);

            if (response is null)
            {
                return(null);
            }

            var responseMessage = await CheckTranslationStatus(translationResponse?.RequestId);

            var translations = await _httpClient.GetResult <TranslationResponse>(responseMessage);

            var translation = translations?.Translation?.FirstOrDefault();

            if (translation == null)
            {
                return(null);
            }

            var translatedXliff = Converter.ParseXliffString(translation);

            if (translatedXliff == null)
            {
                return(null);
            }

            var targetSegments = translatedXliff.GetTargetSegments();
            var segmentIds     = fileAndSegments.Segments.Keys.ToList();

            OnTranslationReceived(new TranslationData
            {
                TargetSegments =
                    segmentIds.Select((segmentId, index) => (segmentId, target: targetSegments[index].Segment.ToString())).ToDictionary(
                        x => x.segmentId,
                        x => x.target),
                TranslationOriginData = new TranslationOriginData
                {
                    Model = translations.Model,
                    QualityEstimations = segmentIds.Select((segmentId, index) => (segmentId, targetSegments[index].QualityEstimation))
Beispiel #4
0
        public async Task <Segment[]> TranslateText(string text, LanguageMappingModel model)
        {
            if (string.IsNullOrEmpty(model?.SelectedModel?.Model))
            {
                throw new Exception(PluginResources.Message_No_model_selected);
            }

            if (ConnectionService.Credential.ValidTo < DateTime.UtcNow)
            {
                // attempt one connection
                var success = ConnectionService.Connect(ConnectionService.Credential);
                if (!success.Item1)
                {
                    _logger.Error($"{System.Reflection.MethodBase.GetCurrentMethod().Name} " + $"{PluginResources.Message_Connection_token_has_expired}\n {ConnectionService.Credential.Token}");
                    throw new Exception(PluginResources.Message_Connection_token_has_expired);
                }
            }

            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + ConnectionService.Credential.Token);

                var uri     = new Uri($"{Constants.MTCloudTranslateAPIUri}/v4" + "/mt/translations/async");
                var request = new HttpRequestMessage(HttpMethod.Post, uri);
                ConnectionService.AddTraceHeader(request);

                var translationRequestModel = new TranslationRequest
                {
                    Input            = new[] { text },
                    SourceLanguageId = model.SelectedSource.CodeName,
                    TargetLanguageId = model.SelectedTarget.CodeName,
                    Model            = model.SelectedModel.Model,
                    InputFormat      = "xliff"
                };

                if (!model.SelectedDictionary.Name.Equals(PluginResources.Message_No_dictionary_available) &&
                    !model.SelectedDictionary.Name.Equals(PluginResources.Message_No_dictionary))
                {
                    translationRequestModel.Dictionaries = new[] { model.SelectedDictionary?.DictionaryId };
                }

                var content = JsonConvert.SerializeObject(translationRequestModel);
                request.Content = new StringContent(content, new UTF8Encoding(), "application/json");


                var responseMessage = await httpClient.SendAsync(request);

                var response = await responseMessage.Content.ReadAsStringAsync();

                if (!responseMessage.IsSuccessStatusCode)
                {
                    return(null);
                }

                if (JsonConvert.DeserializeObject <TranslationResponse>(response) is TranslationResponse translationResponse)
                {
                    var dataResponse = await GetTranslations(httpClient, translationResponse.RequestId);

                    if (JsonConvert.DeserializeObject <TranslationResponse>(dataResponse) is TranslationResponse translations)
                    {
                        var translation = translations.Translation.FirstOrDefault();
                        if (translation == null)
                        {
                            return(null);
                        }
                        //feedback.TargetMtText = translation;
                        //TranslationReceived?.Invoke(feedback);
                        var translatedXliff = Converter.ParseXliffString(translation);
                        if (translatedXliff != null)
                        {
                            var segments = translatedXliff.GetTargetSegments();
                            return(segments);
                        }
                    }
                }
            }

            return(null);
        }
Beispiel #5
0
        public LanguageMappingModel GetLanguageMappingModel(LanguagePair languageDirection, List <MappedLanguage> mappedLanguages)
        {
            var sourceLanguageCode = mappedLanguages?.FirstOrDefault(s => s.TradosCode.Equals(languageDirection.SourceCulture?.Name));

            if (sourceLanguageCode == null)
            {
                return(null);
            }

            var sourceLanguageMappings        = LanguageMappingsService.GetMTCloudLanguages(sourceLanguageCode, languageDirection.SourceCulture);
            var sourceLanguageMappingSelected = sourceLanguageMappings.FirstOrDefault(a => a.IsLocale) ?? sourceLanguageMappings[0];

            var targetLanguageCode = mappedLanguages.FirstOrDefault(s => s.TradosCode.Equals(languageDirection.TargetCulture?.Name));

            if (targetLanguageCode == null)
            {
                return(null);
            }

            var name = $"{languageDirection.SourceCulture?.DisplayName} - {languageDirection.TargetCulture?.DisplayName}";
            var savedLanguageMappingModel = Options.LanguageMappings.FirstOrDefault(a => a.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase));

            var targetLanguageMappings        = LanguageMappingsService.GetMTCloudLanguages(targetLanguageCode, languageDirection.TargetCulture);
            var targetLanguageMappingSelected = targetLanguageMappings.FirstOrDefault(a => a.IsLocale) ?? targetLanguageMappings[0];

            // assign the selected target langauge
            targetLanguageMappingSelected = targetLanguageMappings.FirstOrDefault(a =>
                                                                                  a.CodeName.Equals(savedLanguageMappingModel?.SelectedTarget?.CodeName))
                                            ?? targetLanguageMappingSelected;

            var engineModels = LanguageMappingsService.GetTranslationModels(sourceLanguageMappingSelected, targetLanguageMappingSelected,
                                                                            sourceLanguageCode.TradosCode, targetLanguageCode.TradosCode);

            // attempt to recover the language model from the secondary language code if it exists!
            if (engineModels.Count == 1 && engineModels[0].DisplayName == PluginResources.Message_No_model_available && targetLanguageMappings.Count > 1 &&
                savedLanguageMappingModel?.SelectedModel.DisplayName != PluginResources.Message_No_model_available)
            {
                var secondaryLanguageCode = targetLanguageMappings.FirstOrDefault(a => a.CodeName != targetLanguageMappingSelected.CodeName);

                var secondaryEngineModels = LanguageMappingsService.GetTranslationModels(
                    sourceLanguageMappingSelected, secondaryLanguageCode, sourceLanguageCode.TradosCode, targetLanguageCode.TradosCode);

                if (secondaryEngineModels.Any())
                {
                    engineModels = secondaryEngineModels;
                    targetLanguageMappingSelected = secondaryLanguageCode;
                }
            }

            if (engineModels.Any())
            {
                // assign the selected model
                var selectedModel =
                    engineModels.FirstOrDefault(a => a.DisplayName.Equals(savedLanguageMappingModel?.SelectedModel?.DisplayName, StringComparison.InvariantCultureIgnoreCase))
                    ?? engineModels.FirstOrDefault(a => a.Model.Equals("generic", StringComparison.InvariantCultureIgnoreCase))
                    ?? engineModels[0];

                var dictionaries = LanguageMappingsService.GetDictionaries(sourceLanguageMappingSelected, targetLanguageMappingSelected);

                // assign the selected dictionary
                var selectedDictionary =
                    dictionaries.FirstOrDefault(a => a.Name.Equals(savedLanguageMappingModel?.SelectedDictionary?.Name))
                    ?? dictionaries[0];

                var languageMappingModel = new LanguageMappingModel
                {
                    Name               = name,
                    SourceLanguages    = sourceLanguageMappings,
                    TargetLanguages    = targetLanguageMappings,
                    SelectedSource     = sourceLanguageMappingSelected,
                    SelectedTarget     = targetLanguageMappingSelected,
                    SourceTradosCode   = sourceLanguageCode.TradosCode,
                    TargetTradosCode   = targetLanguageCode.TradosCode,
                    Models             = engineModels,
                    SelectedModel      = selectedModel,
                    Dictionaries       = dictionaries,
                    SelectedDictionary = selectedDictionary
                };

                return(languageMappingModel);
            }

            return(null);
        }