public void Translate(TranslationRequest trans)
        {
            var baseUrl = "https://www.googleapis.com/language/translate/v2?key=" + _apiKey +
                "&source=" + trans.SourceLanguage + "&target=" + trans.TargetLanguage;

            var url = new StringBuilder(baseUrl);
            int lastTranslatedIndex = 0;
            for (int i = 0; i < trans.Translations.Count; i++)
            {
                AddTextToUrl(url, trans.Translations[i].SourceText);

                // All this craziness is here because we want to add as many segments to the URL as poassible
                // without going over the max length
                var nextUrl = new StringBuilder(url.ToString());
                if (i < trans.Translations.Count - 1)
                    AddTextToUrl(nextUrl, trans.Translations[i+1].SourceText);

                if ((i - lastTranslatedIndex) >= MaxNumSegments
                    || i == (trans.Translations.Count - 1)
                    || (nextUrl.Length > MaxUrlLength))
                {
                    var translations = trans.Translations.GetRange(lastTranslatedIndex, i - lastTranslatedIndex + 1);
                    CallGoogle(url.ToString(), translations);
                    url = new StringBuilder(baseUrl);
                    lastTranslatedIndex = i + 1;
                    AddWhitespaceBackIn(translations);
                }
            }
        }
        public ActionResult Create(TranslationRequest item)
        {
            item.Requester = Employee.TryFind (item.RequesterId);

            if (!ModelState.IsValid) {
                return PartialView ("_Create", item);
            }

            using (var scope = new TransactionScope ()) {
                item.CreateAndFlush ();
            }

            return PartialView ("_CreateSuccesful", item);
        }
Beispiel #3
0
        /// <summary>
        /// 翻译
        /// </summary>
        /// <param name="language">语言结构</param>
        public void Translate(LanguageStructure language)
        {
            SearchRequest searchRequest = new SearchRequest();

            searchRequest.AppId  = _appID;
            searchRequest.Query  = language.OriginalText;
            searchRequest.Market = "en-US";
            TranslationRequest transRequest = new TranslationRequest();

            transRequest.SourceLanguage = "En";     //English
            transRequest.TargetLanguage = "zh-CHS"; //China
            TranslationResponse response = API.Translation(searchRequest, transRequest);

            if (response.TranslationResults.Count > 0)
            {
                language.Translation = response.TranslationResults[0].TranslatedTerm;
                On_Sucess(language);
            }
            else
            {
                On_Error("Error");
            }
        }
        private List <string> GetTranslations(TranslationRequest translationRequest, TranslationEngine translationEngine, string apiKey, string formality)
        {
            var translations = new List <string>();

            Parallel.ForEach(translationRequest.Contents, (text) =>
            {
                var encodedText      = HttpUtility.UrlEncode(text);
                using var httpClient = new HttpClient();

                var content = new StringContent($"text={encodedText}" +
                                                $"&source_lang={translationEngine.EngineSourceLanguage}" +
                                                $"&target_lang={translationEngine.EngineTargetLanguage}" +
                                                $"&formality={formality.ToLower()}" +
                                                "&preserve_formatting=1" +
                                                "&tag_handling=xml" +
                                                $"&auth_key={apiKey}", Encoding.UTF8, "application/x-www-form-urlencoded");

                var response = httpClient.PostAsync("https://api.deepl.com/v2/translate", content).Result;
                if (response.IsSuccessStatusCode)
                {
                    var translationResponse = response.Content?.ReadAsStringAsync().Result;
                    var translatedObject    = JsonSerializer.Deserialize <DeeplTranslationResponse>(translationResponse, JsonSettings.Default());
                    var translatedText      = translatedObject.Translations[0].Text;

                    translations.Add(translatedText);
                }
                else
                {
                    var responseContent = response.Content?.ReadAsStringAsync().Result;

                    throw new AddonValidationException($"Request to DeepL Translate endpoint failed with status code {response.StatusCode}", new Details {
                        Code = ErrorCodes.GeneralError, Value = responseContent
                    });
                }
            });
            return(translations);
        }
Beispiel #5
0
        public TranslationResult Adapt(TranslationRequest request, TranslationResultDto resultDto)
        {
            var translations = new List <TextTranslation>();

            for (var i = 0; i < resultDto.Translations.Count; i++)
            {
                var translationDto         = resultDto.Translations.ElementAt(i);
                var detectedSourceLanguage = TranslationLanguage.CreateByCode(translationDto.Detected_source_language);
                var textKey = request.TextParts.ElementAt(i).Key;
                var text    = translationDto.Text;

                request.IgnoreMarkup.Evaluate(
                    markup =>
                {
                    text = text.Replace(IgnoreForTranslationMarkup.DeeplIgnoreBeginTag, markup.BeginTag);
                    text = text.Replace(IgnoreForTranslationMarkup.DeeplIgnoreEndTag, markup.EndTag);
                });

                var identifiableText = new TextPart(textKey, text);
                translations.Add(new TextTranslation(detectedSourceLanguage, identifiableText));
            }

            return(new TranslationResult(translations));
        }
Beispiel #6
0
        public void AddRequestInfo(TranslationRequest request)
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.Invoke(() => AddRequestInfo(request));
                return;
            }

            var requestParagraph = new Paragraph();

            requestParagraph.Inlines.Add(new Run("From "));
            requestParagraph.Inlines.Add(new Bold(new Run($"{request.From}")));
            requestParagraph.Inlines.Add(new Run(" to "));
            requestParagraph.Inlines.Add(new Bold(new Run($"{request.To}")));

            requestParagraph.Inlines.Add(new LineBreak());

            foreach (var translationItem in request.Items)
            {
                requestParagraph.Inlines.Add(new Italic(new Run(translationItem.Text)));
            }

            TranslationAreaDocument.Blocks.Add(requestParagraph);
        }
        public async Task StartAsync(TranslationRequest request)
        {
            int version = request.Version + 1;

            var fileResult = await _fileClient.DownloadAsync(
                fileName : $"{request.CorrelationId}{Path.GetExtension(request.FileName)}",
                userId : request.UserId
                );

            string text;

            using (var fileStream = await fileResult.OpenStreamAsync())
                using (var textExtractor = TextExtractor.Open(fileStream, fileResult.ContentType))
                {
                    text = await textExtractor.ExtractAsync();
                }

            var textChunks = text.ChunkWithDelimeters(5000, '.', '!', '?', ')', '"', '}', ']');

            await _eventPublisher.PublishAsync(new TranslationStarted(
                                                   aggregateId : request.AggregateId,
                                                   version : version,
                                                   correlationId : request.CorrelationId,
                                                   causationId : request.CausationId,
                                                   characterCount : textChunks.Sum(tc => tc.Length),
                                                   userId : request.UserId
                                                   ));

            try
            {
                var result = await _speechSynthesizer.TranslateTextAsync(new GoogleSpeechRequest(
                                                                             voiceSelection : new VoiceSelectionParams
                {
                    Name = request.TranslationSubject
                },
                                                                             audioConfig : new AudioConfig
                {
                    AudioEncoding = AudioEncoding.Mp3
                },
                                                                             content : textChunks,
                                                                             callback : async length =>
                {
                    Interlocked.Increment(ref version);
                    await _semaphoreSlim.WaitAsync();

                    try
                    {
                        await _eventPublisher.PublishAsync(new TranslationCharactersProcessed(
                                                               aggregateId: request.AggregateId,
                                                               version: version,
                                                               correlationId: request.CorrelationId,
                                                               causationId: request.CausationId,
                                                               charactersProcessed: length,
                                                               userId: request.UserId
                                                               ));
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                    finally
                    {
                        _semaphoreSlim.Release();
                    }
                }
                                                                             ));


                using (var stream = await result.OpenStreamAsync())
                {
                    await _fileClient.UploadAsync($"{request.AggregateId}.mp3", request.UserId, stream);

                    await _eventPublisher.PublishAsync(new TranslationSucceded(
                                                           aggregateId : request.AggregateId,
                                                           version : ++version,
                                                           correlationId : request.CorrelationId,
                                                           causationId : request.CausationId,
                                                           userId : request.UserId
                                                           ));
                }
            }
            catch (Exception e)
            {
                await _eventPublisher.PublishAsync(new TranslationFailed(
                                                       aggregateId : request.AggregateId,
                                                       version : ++version,
                                                       correlationId : request.CorrelationId,
                                                       causationId : request.CausationId,
                                                       error : e.Message,
                                                       userId : request.UserId
                                                       ));
            }
        }
Beispiel #8
0
 public Task StartAsync(TranslationRequest request)
 {
     return(Task.CompletedTask);
 }
Beispiel #9
0
 public TranslationResponse Translate(TranslationRequest request)
 {
     return(Translate(request.SourceLanguage, request.TargetLanguage, request.Text));
 }
Beispiel #10
0
 public List <Example> GetPhrases(TranslationRequest request)
 {
     return(GetPhrases(request.SourceLanguage, request.TargetLanguage, request.Text));
 }
Beispiel #11
0
        public ActionResult Edit(int id)
        {
            var item = TranslationRequest.Find(id);

            return(PartialView("_Edit", item));
        }
Beispiel #12
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))
        public async Task StartAsync(TranslationRequest request)
        {
            int version = request.Version + 1;

            var fileResult = await _fileClient.DownloadAsync(
                fileName : $"{request.CorrelationId}{Path.GetExtension(request.FileName)}",
                userId : request.UserId
                );

            string text;

            using (var fileStream = await fileResult.OpenStreamAsync())
                using (var textExtractor = TextExtractor.Open(fileStream, fileResult.ContentType))
                {
                    text = await textExtractor.ExtractAsync();
                }

            var textChunks = text.ChunkWithDelimeters(5000, '.', '!', '?', ')', '"', '}', ']').ToArray();

            await _eventPublisher.PublishAsync(new TranslationStarted(
                                                   aggregateId : request.AggregateId,
                                                   version : version,
                                                   correlationId : request.CorrelationId,
                                                   causationId : request.CausationId,
                                                   characterCount : textChunks.Sum(tc => tc.Length),
                                                   userId : request.UserId
                                                   ));

            try
            {
                for (int i = 0; i < textChunks.Count(); i++)
                {
                    version++;
                    await _eventPublisher.PublishAsync(new TranslationCharactersProcessed(
                                                           aggregateId : request.AggregateId,
                                                           version : version,
                                                           correlationId : request.CorrelationId,
                                                           causationId : request.CausationId,
                                                           charactersProcessed : textChunks[i].Length,
                                                           userId : request.UserId
                                                           ));
                }

                using (var stream = new MemoryStream())
                    using (TextWriter tw = new StreamWriter(stream))
                    {
                        await tw.WriteAsync("test");

                        await tw.FlushAsync();

                        stream.Position = 0;
                        await _fileClient.UploadAsync($"{request.AggregateId}.mp3", request.UserId, stream);

                        await _eventPublisher.PublishAsync(new TranslationSucceded(
                                                               aggregateId : request.AggregateId,
                                                               version : ++version,
                                                               correlationId : request.CorrelationId,
                                                               causationId : request.CausationId,
                                                               userId : request.UserId
                                                               ));
                    }
            }
            catch (Exception e)
            {
                await _eventPublisher.PublishAsync(new TranslationFailed(
                                                       aggregateId : request.AggregateId,
                                                       version : ++version,
                                                       correlationId : request.CorrelationId,
                                                       causationId : request.CausationId,
                                                       error : e.Message,
                                                       userId : request.UserId
                                                       ));
            }
        }
        public ActionResult Edit(TranslationRequest item)
        {
            item.Requester = Employee.TryFind (item.RequesterId);

            if (!ModelState.IsValid) {
                return PartialView ("_Edit", item);
            }

            var entity = TranslationRequest.Find (item.Id);

            entity.Date = item.Date;
            entity.Requester = item.Requester;
            entity.Agency = item.Agency;
            entity.DocumentName = item.DocumentName;
            entity.Amount = item.Amount;
            entity.DeliveryDate = item.DeliveryDate;
            entity.Comment = item.Comment;

            using (var scope = new TransactionScope ()) {
                entity.UpdateAndFlush ();
            }

            return PartialView ("_Refresh");
        }
 public async Task <string> TranslateSingleAsync(TranslationRequest translationRequest)
 {
     return(await Task.Run(() => TranslateSingle(translationRequest)));
 }
        public async Task <IActionResult> TranslationsList(TranslationRequest request)
        {
            var translations = await _translationsService.GetTranslationsAsync(request);

            return(this.PageObject(translations, translations.Count, 0, 0));
        }
Beispiel #17
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                ShowSyntax();
                return;
            }
            var textToTranslate = string.Join(" ", args);


            // Output all supported languages
            var supportedLanguages = _translationService.SupportedLanguages;

            WriteAndResetStopwatch($"Supported Languages:\n{string.Join(", ", supportedLanguages.Values.Select(l => l.Code))}");


            // Detect a different language (Norwegian)
            var norwegianAnthem   = "Ja vi elsker dette landet som det stiger frem. Furet værbitt over vannet med de tusen hjem. Elsker, elsker det og tenker på vår far og mor.";
            var detectedNorwegian = _translationService.DetectLanguage(norwegianAnthem);

            WriteAndResetStopwatch($"Detected language to be '{detectedNorwegian.Code}'");


            // Break up the sentences and return their character counts
            var result = _translationService.BreakSentences(detectedNorwegian, norwegianAnthem);

            WriteAndResetStopwatch("Sentences broken:");
            int index = 1;

            foreach (var sentence in result)
            {
                Console.WriteLine($"Sentence {index} contains {sentence} characters");
            }


            // Detect the language of the text to translate from
            var detectedLanguage = _translationService.DetectLanguage(textToTranslate);

            WriteAndResetStopwatch($"Detected language to be '{detectedLanguage.Code}'");


            // Get text to translate from Project Debug arguments.
            // The text is obtained from Samuel L. Ipsum generator
            WriteAndResetStopwatch(textToTranslate);


            // Translate into norwegian
            var norwegian          = supportedLanguages["no"];
            var translationRequest = new TranslationRequest
            {
                From = detectedLanguage,
                To   = norwegian,
                Text = textToTranslate
            };
            var translatedResult = _translationService.TranslateSingle(translationRequest);

            WriteAndResetStopwatch(translatedResult);


            // End of program
            Console.WriteLine("Done. Press any key to finish");
            Console.ReadKey();
        }
        /// <summary>
        /// Attempt to translated the provided untranslated text. Will be used in a "coroutine",
        /// so it can be implemented in an asynchronous fashion.
        /// </summary>
        public IEnumerator Translate(ITranslationContext context)
        {
            EnsureInitialized();

            while (_initializing && !_failed)
            {
                var instruction = Features.GetWaitForSecondsRealtime(0.2f);
                if (instruction != null)
                {
                    yield return(instruction);
                }
                else
                {
                    yield return(null);
                }
            }

            if (_failed)
            {
                context.Fail("External process failed.");
            }

            var totalDelay    = (float)(Rng.Next((int)((MaxDelay - MinDelay) * 1000)) + (MinDelay * 1000)) / 1000;
            var timeSinceLast = TimeSupport.Time.realtimeSinceStartup - _lastRequestTimestamp;

            if (timeSinceLast < totalDelay)
            {
                var remainingDelay = totalDelay - timeSinceLast;

                var instruction = Features.GetWaitForSecondsRealtime(remainingDelay);
                if (instruction != null)
                {
                    yield return(instruction);
                }
                else
                {
                    float start = TimeSupport.Time.realtimeSinceStartup;
                    var   end   = start + remainingDelay;
                    while (TimeSupport.Time.realtimeSinceStartup < end)
                    {
                        yield return(null);
                    }
                }
            }
            _lastRequestTimestamp = TimeSupport.Time.realtimeSinceStartup;

            var result = new ProtocolTransactionHandle();
            var id     = Guid.NewGuid();

            lock ( _sync )
            {
                _transactionHandles[id] = result;
            }

            try
            {
                var request = new TranslationRequest
                {
                    Id                    = id,
                    SourceLanguage        = context.SourceLanguage,
                    DestinationLanguage   = context.DestinationLanguage,
                    UntranslatedTextInfos = context.UntranslatedTextInfos.Select(x => x.ToTransmittable()).ToArray()
                };
                var payload = ExtProtocolConvert.Encode(request);

                _process.StandardInput.WriteLine(payload);
            }
            catch (Exception e)
            {
                result.SetCompleted(null, e.Message, StatusCode.Unknown);
            }

            // yield-wait for completion
            var iterator = result.GetSupportedEnumerator();

            while (iterator.MoveNext())
            {
                yield return(iterator.Current);
            }

            if (!result.Succeeded)
            {
                context.Fail("Error occurred while retrieving translation. " + result.Error);
            }

            context.Complete(result.Results);
        }
Beispiel #19
0
        public ActionResult Delete(int id)
        {
            var item = TranslationRequest.Find(id);

            return(PartialView("_Delete", item));
        }
Beispiel #20
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 #21
0
        public async Task StartAsync(TranslationRequest request)
        {
            int version = request.Version + 1;

            var fileResult = await _fileClient.DownloadAsync(
                fileName : $"{request.CorrelationId.ToString()}{Path.GetExtension(request.FileName)}",
                userId : request.UserId
                );

            string text;

            using (var fileStream = await fileResult.OpenStreamAsync())
                using (var textExtractor = TextExtractor.Open(fileStream, fileResult.ContentType))
                {
                    text = await textExtractor.ExtractAsync();
                }

            var textChunks = text.ChunkWithDelimeters(100000, '.', '!', '?', ')', '"', '}', ']');

            await _eventPublisher.PublishAsync(new TranslationStarted(
                                                   aggregateId : request.AggregateId,
                                                   version : version,
                                                   correlationId : request.CorrelationId,
                                                   causationId : request.CausationId,
                                                   characterCount : text.Length,
                                                   userId : request.UserId
                                                   ));

            try
            {
                var result = await _speechSynthesizer.TranslateTextAsync(new AWSSpeechRequest {
                    OutputFormat = "",
                    Content      = textChunks,
                    VoiceId      = request.TranslationSubject,
                    CallBack     = async length =>
                    {
                        Interlocked.Increment(ref version);
                        await _semaphoreSlim.WaitAsync();

                        try
                        {
                            await _eventPublisher.PublishAsync(new TranslationCharactersProcessed(
                                                                   aggregateId: request.AggregateId,
                                                                   version: version,
                                                                   correlationId: request.CorrelationId,
                                                                   causationId: request.CausationId,
                                                                   charactersProcessed: length,
                                                                   userId: request.UserId
                                                                   ));
                        }
                        catch (Exception)
                        {
                            throw;
                        }
                        finally
                        {
                            _semaphoreSlim.Release();
                        }
                    }
                });;


                using (var stream = await result.OpenStreamAsync())
                {
                    await _fileClient.UploadAsync($"{request.AggregateId}.mp3", request.UserId, stream);

                    await _eventPublisher.PublishAsync(new TranslationSucceded(
                                                           aggregateId : request.AggregateId,
                                                           version : version + 1,
                                                           correlationId : request.CorrelationId,
                                                           causationId : request.CausationId,
                                                           userId : request.UserId
                                                           ));
                }
            }
            catch (Exception e)
            {
                await _eventPublisher.PublishAsync(new TranslationFailed(
                                                       aggregateId : request.AggregateId,
                                                       version : version + 1,
                                                       correlationId : request.CorrelationId,
                                                       causationId : request.CausationId,
                                                       error : e.Message,
                                                       userId : request.UserId
                                                       ));
            }
        }
 public void Translate(TranslationRequest req)
 {
     Task.Run(() => internalTranslate(req.Destination, req.Type.Value, req.Text, req.Consumer));
 }
Beispiel #23
0
 public List <InflectedForm> GetInflectedForm(TranslationRequest request)
 {
     return(GetInflectedForm(request.SourceLanguage, request.TargetLanguage, request.Text));
 }
Beispiel #24
0
        public async Task <IReadOnlyList <TranslationResponse> > GetTranslationsAsync(TranslationRequest request)
        {
            // get translations lsit
            var translationWorksList = await _bookContext.TranslationWorkPersons
                                       .Where(c => c.PersonId == request.PersonId)
                                       .Select(c => c.TranslationWorkId)
                                       .ToListAsync();

            // get all translators
            var translationPersons = (from twp in _bookContext.TranslationWorkPersons
                                      join p in _bookContext.Persons on twp.PersonId equals p.Id
                                      where translationWorksList.Contains(twp.TranslationWorkId)
                                      select new
            {
                Id = twp.TranslationWorkId,
                PersonId = p.Id,
                Name = p.Name,
                NameSort = p.NameSort
            }).ToList();


            // get translation names
            var translationsNames = (from a in _bookContext.EditionTranslations
                                     where translationWorksList.Contains(a.TranslationWorkId)
                                     group a by new { a.TranslationWorkId, a.Name } into g
                                     select new
            {
                Id = g.Key.TranslationWorkId,
                Name = g.Key.Name,
                Count = g.Count()
            }).ToList();

            // get translator works
            var query = from tw in _bookContext.TranslationWorks
                        join w in _bookContext.Works on tw.WorkId equals w.Id
                        join wt in _bookContext.WorkTypes on w.WorkTypeId equals wt.Id
                        where translationWorksList.Contains(tw.Id)
                        select new TranslationResponse
            {
                TranslationWorkId  = tw.Id,
                WorkId             = w.Id,
                WorkName           = w.Name,
                WorkYear           = w.Year,
                TranslationYear    = tw.Year,
                WorkTypeName       = wt.Name,
                WorkTypeNameSingle = wt.NameSingle,
                WorkTypeLevel      = wt.Level,
                LanguageId         = tw.LanguageId
            };

            var response = await query.ToListAsync();

            // get all persons
            // TODO: EF7 doesn't generate where clause
            var translationWorks   = response.Select(w => w.WorkId).ToList();
            var translationAuthors = (from pw in _bookContext.PersonWorks
                                      join p in _bookContext.Persons on pw.PersonId equals p.Id
                                      where translationWorks.Contains(pw.WorkId)
                                      select new
            {
                WorkId = pw.WorkId,
                PersonId = p.Id,
                Name = p.Name,
                NameSort = p.NameSort
            }).ToList();

            foreach (var item in response)
            {
                // adding all possible names to translation
                item.Names = translationsNames
                             .Where(c => c.Id == item.TranslationWorkId)
                             .OrderByDescending(c => c.Count)
                             .Select(c => c.Name)
                             .ToList();

                // adding all translators, except main
                // TODO: exclude main translator
                item.Translators = translationPersons
                                   .Where(c => c.Id == item.TranslationWorkId && c.PersonId != request.PersonId)
                                   .Select(c => new PersonResponse
                {
                    PersonId = c.PersonId,
                    Name     = c.Name,
                    NameSort = c.NameSort
                })
                                   .ToList();

                // get all authors
                item.Authors = translationAuthors
                               .Where(c => c.WorkId == item.WorkId)
                               .Select(c => new PersonResponse
                {
                    PersonId = c.PersonId,
                    Name     = c.Name,
                    NameSort = c.NameSort
                })
                               .ToList();
            }

            switch (request.Sort)
            {
            case TranslatorSort.Author:
                response = response
                           .OrderBy(c => string.Join(", ", c.Authors.Select(d => d.NameSort)))
                           .ThenBy(c => c.WorkTypeLevel)
                           .ToList();
                break;

            case TranslatorSort.Type:
                response = response
                           .OrderBy(c => c.WorkTypeLevel)
                           .ThenBy(c => string.Join(", ", c.Authors.Select(d => d.NameSort)))
                           .ToList();
                break;

            case TranslatorSort.Year:
                response = response
                           .OrderBy(c => c.TranslationYear)
                           .ThenBy(c => c.WorkTypeLevel)
                           .ThenBy(c => string.Join(", ", c.Authors.Select(d => d.NameSort)))
                           .ToList();
                break;
            }

            return(response);
        }
Beispiel #25
0
        // ========== Translate ==========
        public Dictionary <string, string> Translate(string country, string[] untranslated)
        {
            Dictionary <string, string> translated = new Dictionary <string, string>();

            Program.LogAlert("Translator", "Checking for language translations...");
            WebClient web = new WebClient();

            web.Encoding = Encoding.UTF8;
            try
            {
                // Clean Untranslated:
                List <string> cleanedUntranslated = new List <string> ();
                foreach (string untranslatedEntry in untranslated)
                {
                    if (untranslatedEntry == "")
                    {
                        continue;
                    }
                    if (cleanedUntranslated.Contains(untranslatedEntry))
                    {
                        continue;
                    }
                    cleanedUntranslated.Add(untranslatedEntry);
                }
                untranslated = cleanedUntranslated.ToArray();
                Program.Log("Translator", "Translating " + untranslated.Length + " entries...");

                // Create Request:
                TranslationRequest translationRequest = new TranslationRequest();
                translationRequest.key     = this.Config.Key;
                translationRequest.country = country;
                translationRequest.data    = untranslated;

                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string untranslatedJSON         = serializer.Serialize(translationRequest);
                web.Headers[HttpRequestHeader.ContentType] = "application/json";
                web.Headers.Add("Accept-Charset", "utf-8");
                string   translatedJSON = web.UploadString(new Uri(this.Config.URL), "POST", untranslatedJSON);
                string[] translatedData = serializer.Deserialize <string[]> (translatedJSON);

                // Check Translations:
                if (translatedData.Length != untranslated.Length)
                {
                    Program.LogWarning("Translator", "Received an inconsistent number of translations, expected " + untranslated.Length + " but received " + translatedData.Length + ".");
                }

                // Manage Translations:
                bool changes = false;
                for (int i = 0; i < translatedData.Length; i++)
                {
                    translated.Add(untranslated[i], translatedData[i]);
                    if (untranslated[i] != translatedData[i])
                    {
                        changes = true;
                    }
                }

                // Log Result:
                if (changes)
                {
                    Program.Log("Translator", "This order has been translated.");
                }
                else
                {
                    Program.Log("Translator", "This order does not need to be translated or no translations are available.");
                }
            }
            catch (Exception e)
            {
                Program.LogWarning("Translator", "There was a problem translating this order via: " + this.Config.URL);
                Program.LogException(e);
            }

            return(translated);
        }