Esempio n. 1
0
 public void AddRow(params string[] fields)
 {
     if (EnumerableValidator.IsNotEmpty(fields))
     {
         AddRow(fields.Select(TableDataCell.CreateText).ToList());
     }
 }
        public List <string> FindSentences(string words, OrderWordsInSearch orderWordsInSearch)
        {
            var             uniqueWords = new HashSet <string>(words.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries));
            List <Sentence> sentences   = _sentenceWordsQuery.FindSentencesByWords(uniqueWords.Select(e => e.Trim()).ToList(),
                                                                                   orderWordsInSearch);

            if (EnumerableValidator.IsEmpty(sentences))
            {
                NLPWrapper.ExternalObjects.Sentence sentence = _textAnalyzer.ParseSentence(words, false);
                var normalWords = new List <string>();
                foreach (Word word in sentence.Words)
                {
                    if (EnumerableValidator.IsNotEmpty(word.NormalForms))
                    {
                        normalWords.AddRange(word.NormalForms);
                    }
                    else
                    {
                        normalWords.Add(word.GetAppropriateWordText());
                    }
                }
                sentences = _sentenceWordsQuery.FindSentencesByWords(normalWords, orderWordsInSearch);
            }
            return(sentences.Select(e => e.Text).ToList());
        }
Esempio n. 3
0
 public void AddHeader(params string[] headers)
 {
     if (EnumerableValidator.IsNotEmpty(headers))
     {
         AddHeader(headers.ToList());
     }
 }
Esempio n. 4
0
        public DocumentationGenerator Download(DocumentType docType, string fileName, ComparisonForUser comparisonForUser)
        {
            string header = comparisonForUser.Title;
            DocumentationGenerator documentGenerator = DocumentationGenerator.Create(_domain, _fontPath, docType, fileName);

            documentGenerator.AddHeader(header, false);
            if (comparisonForUser.HasDescription)
            {
                documentGenerator.AddParagraph(TextFormatter.AppendCharIfNeed(comparisonForUser.Description));
            }
            foreach (ComparisonItemForUser item in comparisonForUser.Items)
            {
                string title = item.Title;
                if (item.HasTranslatedTitle)
                {
                    title += " – " + item.TitleTranslated;
                }
                documentGenerator.AddSubheader(title);
                documentGenerator.AddParagraph(item.GetRuleHeader());
                int ruleNumber = 1;
                foreach (ComparisonRuleForUser rule in item.Rules)
                {
                    string ruleDescription = TextFormatter.AppendCharIfNeed(rule.Description);
                    if (!item.IsOneRule)
                    {
                        ruleDescription = ruleNumber + ". " + ruleDescription;
                        ruleNumber++;
                    }
                    documentGenerator.AddParagraph(ruleDescription);
                    if (EnumerableValidator.IsNotEmpty(rule.Examples))
                    {
                        foreach (ComparisonRuleExampleForUser example in @rule.Examples)
                        {
                            documentGenerator.AddParagraph(example.Example.Source.Text + " – "
                                                           + example.Example.Translation.Text,
                                                           new TextFormat {
                                CountLeftPaddings = 1
                            });
                            if (!string.IsNullOrWhiteSpace(example.Description))
                            {
                                documentGenerator.AddParagraph("Пояснение к примеру: "
                                                               + TextFormatter.AppendCharIfNeed(example.Description),
                                                               new TextFormat {
                                    IsItalic = true, CountLeftPaddings = 1
                                });
                            }
                        }
                    }
                }
            }

            return(documentGenerator);
        }
Esempio n. 5
0
        public void ConvertGroupWords()
        {
            string path = string.Format(@"C:\Projects\StudyLanguages\Источники для групп\Word\{0}\", _languageTo);

            string[] files = Directory.GetFiles(Path.Combine(path, "Xml"), "*.xml");

            var xmlTranslationReader = new XmlTranslationReader();

            foreach (string file in files)
            {
                string name = Path.GetFileNameWithoutExtension(file);

                Console.WriteLine("Обрабатываем группу слов \"{0}\"", name);

                List <XmlTranslationReader.Item> items = xmlTranslationReader.Read(file);

                string destinationFile = Path.Combine(path, name + ".csv");
                using (var csvWriter = new CsvWriter(destinationFile)) {
                    csvWriter.WriteLine(name);
                    foreach (XmlTranslationReader.Item item in items)
                    {
                        var    fields = new List <string>();
                        string source;
                        if (EnumerableValidator.IsNotEmpty(item.Best))
                        {
                            source = item.Best[0].Trim();
                        }
                        else
                        {
                            source = "<UNKNOWN> - " + string.Join("|", item.Other);
                        }

                        fields.Add(source);
                        fields.Add(item.Source);

                        /* string imageFileName =
                         *  string.Format(
                         *      @"C:\Projects\StudyLanguages\Источники для групп\Источники картинок\{0}\{1}.jpg",
                         *      name, item.Translation);
                         * if (File.Exists(imageFileName)) {
                         *  fields.Add(item.Translation);
                         * }*/

                        csvWriter.WriteLine(fields.ToArray());
                    }
                }
            }

            Console.WriteLine("Все группы слов обработаны!");
        }
Esempio n. 6
0
        private WordsByPattern GetKeyboardLayoutResult(UserLanguages userLanguages, string query, WordsQuery wordsQuery)
        {
            var           keyboardLayoutConverter = new KeyboardLayoutConverter();
            List <string> convertedQueries        = keyboardLayoutConverter.Convert(query);

            foreach (string convertedQuery in convertedQueries)
            {
                WordsByPattern result = wordsQuery.GetLikeWords(userLanguages, convertedQuery, WordType);
                if (EnumerableValidator.IsNotEmpty(result.Words))
                {
                    result.NewPattern = convertedQuery;
                    return(result);
                }
            }
            return(new WordsByPattern());
        }
Esempio n. 7
0
        /// <summary>
        /// Переводит на язык to, тексты которые указаны в textsByFromLanguages
        /// </summary>
        /// <param name="to">язык на который нужно перевести</param>
        /// <param name="textsWithLanguages">список текстов на разных, которые означают одно и то же и значение перевод у которых будет одно и тоже</param>
        /// <returns>наилучшии общие переводы для текстов на разных языках; пустой список если не удалось определить наилучшие переводы</returns>
        public List <string> Translate(LanguageShortName to,
                                       IEnumerable <Tuple <LanguageShortName, string> > textsWithLanguages)
        {
            _bestTranslations.Clear();
            _otherTranslations.Clear();
            _initialsByNormalized.Clear();

            Translate(_translators, to, textsWithLanguages);
            if (EnumerableValidator.IsEmpty(_bestTranslations) && EnumerableValidator.IsNotEmpty(_extraTranslators))
            {
                //наилучшие переводы не найдены - перевести с помощью дополнительных переводчиков
                Console.WriteLine("Воспользуемся дополнительными переводчиками!!!");
                CountExtraCalls++;
                Translate(_extraTranslators, to, textsWithLanguages);
            }

            return(GetBestTranslations());
        }
Esempio n. 8
0
        private void SaveConvertedWords(string fileName,
                                        IEnumerable <SourceWithTranslation> words)
        {
            var translationSaver = new TranslationSaver(fileName);

            foreach (SourceWithTranslation sourceWithTranslation in words)
            {
                PronunciationForUser source      = sourceWithTranslation.Source;
                PronunciationForUser translation = sourceWithTranslation.Translation;

                var textsWithLanguages = new List <Tuple <LanguageShortName, string> > {
                    new Tuple <LanguageShortName, string>(_languageShortNames[source.LanguageId],
                                                          source.Text),
                    new Tuple <LanguageShortName, string>(_languageShortNames[translation.LanguageId],
                                                          translation.Text),
                };

                string sourceWords = string.Join(", ", textsWithLanguages.Select(e => e.Item2));

                List <string> bestTranslations  = _translator.Translate(_languageTo, textsWithLanguages);
                List <string> otherTranslations = _translator.GetOtherTranslations();
                translationSaver.Write(sourceWithTranslation, bestTranslations, otherTranslations);

                if (EnumerableValidator.IsNotEmpty(bestTranslations))
                {
                    Console.WriteLine("Лучшие переводы для {0} это {1}", sourceWords,
                                      string.Join(", ", bestTranslations));
                    //TODO: сохранять в БД, предварительно изменив регистр в соответствии с английским словом
                    continue;
                }

                if (EnumerableValidator.IsEmpty(otherTranslations))
                {
                    //не нашли вообще переводов - сообщить
                    Console.WriteLine("ERROR: Для {0} не нашли вообще переводов. Пропустить", sourceWords);
                }

                Console.WriteLine(
                    "WARNING: Для слова {0} нашли переводы {1}, но среди них нет лучшего. Пропустить", sourceWords,
                    string.Join(", ", otherTranslations));
            }

            translationSaver.Save();
        }
Esempio n. 9
0
        public List <TVSeriesWatch> GetSeriesWatches(string urlPart)
        {
            return(Adapter.ReadByContext(c => {
                TVSeries parentTVSeries =
                    c.TVSeries.FirstOrDefault(e => e.LanguageId == _languageId && e.UrlPart == urlPart);
                if (parentTVSeries == null)
                {
                    return new List <TVSeriesWatch>(0);
                }

                List <TVSeriesWatch> result = GetSeriesWatches(parentTVSeries.Id, IdValidator.INVALID_ID);
                if (EnumerableValidator.IsNotEmpty(result))
                {
                    var coverInfo = JsonConvert.DeserializeObject <TVSeriesInfo>(parentTVSeries.Info);
                    result[0].SetSeriesInfo(coverInfo);
                }
                return result;
            }));
        }
Esempio n. 10
0
        private void Translate(ITranslator[] translators,
                               LanguageShortName to,
                               IEnumerable <Tuple <LanguageShortName, string> > textsWithLanguages)
        {
            foreach (var textWithLanguage in textsWithLanguages)
            {
                LanguageShortName from = textWithLanguage.Item1;
                string            text = textWithLanguage.Item2;

                //перевести текст с языка на другой язык
                Translate(translators, from, to, text);
                if (EnumerableValidator.IsNotEmpty(_bestTranslations))
                {
                    //найдены лучшие переводы - вернуть
                    return;
                }

                //лучшие переводы не найдены - попробовать перевести это же слово, но уже с другого языка
            }
        }
Esempio n. 11
0
        public void ConvertMinileks(string fileName)
        {
            var xmlTranslationReader = new XmlTranslationReader();

            string name = Path.GetFileNameWithoutExtension(fileName);

            Console.WriteLine("Обрабатываем минилекс \"{0}\"", name);

            List <XmlTranslationReader.Item> items = xmlTranslationReader.Read(fileName);

            string path            = Path.GetDirectoryName(fileName);
            string destinationFile = Path.Combine(path, name + ".csv");

            using (var csvWriter = new CsvWriter(destinationFile)) {
                csvWriter.WriteLine("Минилекс Гуннемарка");
                foreach (XmlTranslationReader.Item item in items)
                {
                    var    fields = new List <string>();
                    string source;
                    if (EnumerableValidator.IsNotEmpty(item.Best))
                    {
                        source = item.Best[0].Trim();
                    }
                    else
                    {
                        source = "<UNKNOWN> - " + string.Join("|", item.Other);
                    }

                    fields.Add(source);
                    fields.Add(item.Source);

                    csvWriter.WriteLine(fields.ToArray());
                }
            }

            Console.WriteLine("Минилекс обработан!");
        }
Esempio n. 12
0
        public SentenceWithWords GetWordsBySentenceId(long sentenceId)
        {
            SentenceWithWords result = null;

            Adapter.ActionByContext(c => {
                var sentences = from s in c.Sentence
                                join sw in c.SentenceWord on s.Id equals sw.SentenceId
                                join w in c.Word on sw.WordId equals w.Id into ssw
                                from e in ssw.DefaultIfEmpty()
                                where s.Id == sentenceId && s.LanguageId == _languageId
                                orderby sw.OrderInSentence
                                select new { s, sw, ssw };
                var sentencesWithWords = sentences.ToList();
                foreach (var sentenceWithWord in sentencesWithWords)
                {
                    if (result == null)
                    {
                        var sentence = new PronunciationForUser(sentenceWithWord.s);
                        result       = new SentenceWithWords(sentence);
                    }

                    List <Word> words = sentenceWithWord.ssw.ToList();
                    if (EnumerableValidator.IsNotEmpty(words))
                    {
                        var word = new PronunciationForUser(words[0]);
                        result.AddWord(word);
                    }
                    else
                    {
                        result.AddWord(sentenceWithWord.sw.OriginalText);
                    }
                }
            });

            return(result);
        }
Esempio n. 13
0
 internal bool IsValid()
 {
     return(!string.IsNullOrWhiteSpace(Description) && EnumerableValidator.IsNotEmpty(Examples) &&
            Examples.All(e => e.IsValid()));
 }
Esempio n. 14
0
 public bool IsValid()
 {
     return(!string.IsNullOrWhiteSpace(Title) && !string.IsNullOrWhiteSpace(Description) &&
            EnumerableValidator.IsNotEmpty(Items) && Items.All(e => e.IsValid()));
 }
Esempio n. 15
0
        public List <Subtitle> Analyze(string timeShiftFile)
        {
            const int MIN_ROWS     = 3;
            string    rowSeparator = Environment.NewLine;

            Dictionary <int, TimeSpan> timeShifts = GetTimeshift(timeShiftFile);

            var result = new List <Subtitle>();

            string allContent = File.ReadAllText(_fileName, _encoding);

            string[] blocks = allContent.Split(new[] {
                rowSeparator + rowSeparator
            }, StringSplitOptions.RemoveEmptyEntries);

            var currentTimeShift = new TimeSpan();
            int i = 1;

            foreach (string block in blocks)
            {
                string[] rows = block.Split(new[] { rowSeparator }, MIN_ROWS, StringSplitOptions.RemoveEmptyEntries);
                if (rows.Length < MIN_ROWS)
                {
                    Console.WriteLine("Блок {0} содержит менее {1} строк", i, MIN_ROWS);
                    continue;
                }

                string dirtyNumber = rows[0];
                if (dirtyNumber == "9999")
                {
                    continue;
                }
                int number = int.Parse(dirtyNumber);

                string dirtyTime    = rows[1];
                var    videoEpisode = new Subtitle {
                    Text = rows[2],
                };

                string[] timeParts = dirtyTime.Split(new[] { " --> " }, StringSplitOptions.RemoveEmptyEntries);
                if (timeParts.Length != 2)
                {
                    Console.WriteLine("Время в блоке {0} некорректно!", i);
                    continue;
                }

                TimeSpan from = DateTimeFormatter.ToTimeSpan(timeParts[0]);
                TimeSpan to   = DateTimeFormatter.ToTimeSpan(timeParts[1]);

                TimeSpan time;
                if (timeShifts.TryGetValue(number, out time))
                {
                    currentTimeShift = time - from;
                }

                from += currentTimeShift;
                to   += currentTimeShift;

                videoEpisode.TimeFrom = from.TotalSeconds;
                videoEpisode.TimeTo   = to.TotalSeconds;

                if (EnumerableValidator.IsNotEmpty(result) && videoEpisode.TimeFrom <= result[result.Count - 1].TimeTo)
                {
                    var prevSubtitle = result[result.Count - 1];
                    prevSubtitle.TimeTo = videoEpisode.TimeFrom - 0.1; //на 100мс сдвигаем время
                    if (prevSubtitle.TimeFrom >= prevSubtitle.TimeTo)
                    {
                        Console.WriteLine("Что-то не то с временем для {0} !!! Время от {1} до {2}", prevSubtitle.Text, prevSubtitle.TimeFrom, prevSubtitle.TimeTo);
                    }
                }

                i++;

                result.Add(videoEpisode);
            }

            return(result);
        }
Esempio n. 16
0
        public ComparisonForUser GetOrCreate(ComparisonForUser comparisonForUser)
        {
            if (!comparisonForUser.IsValid())
            {
                return(null);
            }

            bool isSuccess           = true;
            ComparisonForUser result = null;

            Adapter.ActionByContext(c => {
                GroupComparison groupComparison = GetOrCreateGroupComparison(comparisonForUser, c);
                if (IdValidator.IsInvalid(groupComparison.Id))
                {
                    LoggerWrapper.LogTo(LoggerName.Errors).ErrorFormat(
                        "ComparisonsQuery.GetOrCreate не удалось создать! Название: {0}, описание: {1}",
                        comparisonForUser.Title,
                        comparisonForUser.Description);
                    isSuccess = false;
                    return;
                }
                result = new ComparisonForUser(groupComparison);

                int orderItem = 1;
                foreach (ComparisonItemForUser comparisonItemForUser in comparisonForUser.Items)
                {
                    ComparisonItem comparisonItem = GetOrCreateComparisonItem(comparisonItemForUser, groupComparison.Id,
                                                                              orderItem++, c);
                    if (IdValidator.IsInvalid(comparisonItem.Id))
                    {
                        LoggerWrapper.LogTo(LoggerName.Errors).ErrorFormat(
                            "ComparisonsQuery.GetOrCreate не удалось создать пункт для сравнения! " +
                            "Id сравнения: {0}, название {1}, перевод названия {2}, описание {3}",
                            groupComparison.Id, comparisonItemForUser.Title, comparisonItemForUser.TitleTranslated,
                            comparisonItemForUser.Description);
                        isSuccess = false;
                        continue;
                    }

                    var newComparisonItemForUser = new ComparisonItemForUser(comparisonItem);
                    result.AddItem(newComparisonItemForUser);

                    int orderRule = 1;
                    foreach (ComparisonRuleForUser comparisonRuleForUser in comparisonItemForUser.Rules)
                    {
                        ComparisonRule comparisonRule = GetOrCreateComparisonRule(comparisonRuleForUser,
                                                                                  comparisonItem.Id, orderRule++, c);
                        long ruleId = comparisonRule.Id;
                        if (IdValidator.IsInvalid(ruleId))
                        {
                            LoggerWrapper.LogTo(LoggerName.Errors).ErrorFormat(
                                "ComparisonsQuery.GetOrCreate не удалось создать правило для сравнения! " +
                                "Id пункта сравнения: {0}, описание {1}",
                                comparisonItem.Id, comparisonRule.Description);
                            isSuccess = false;
                            continue;
                        }

                        var newComparisonRuleForUser = new ComparisonRuleForUser(comparisonRule);
                        newComparisonItemForUser.AddRule(newComparisonRuleForUser);

                        isSuccess = EnumerableValidator.IsNotEmpty(comparisonRuleForUser.Examples) &&
                                    CreateExamples(comparisonRuleForUser.Examples, newComparisonRuleForUser, c);
                    }
                }

                if (isSuccess)
                {
                    //удалить пункты, правила, примеры, которые не были переданы в этот раз
                    DeleteOldInfos(c, result);
                }
            });
            return(isSuccess && result != null && result.IsValid() ? result : null);
        }
Esempio n. 17
0
 internal bool IsValid()
 {
     return(!string.IsNullOrWhiteSpace(Title) && !string.IsNullOrWhiteSpace(TitleTranslated) &&
            EnumerableValidator.IsNotEmpty(Rules) && Rules.All(e => e.IsValid()));
 }
Esempio n. 18
0
        public void ConvertVisualDictionaries()
        {
            string path = string.Format(@"C:\Projects\StudyLanguages\Источники визуального словаря\{0}\", _languageTo);

            string[] files = Directory.GetFiles(Path.Combine(path, "Xml"), "*.xml");

            var xmlTranslationReader = new XmlTranslationReader();

            const string PATTERN_VISUAL_DICTIONARY = @"C:\Projects\StudyLanguages\Источники визуального словаря\{0}.csv";
            const string PATTERN_KEY = "{0}_{1}";

            foreach (string file in files)
            {
                string name = Path.GetFileNameWithoutExtension(file);

                Console.WriteLine("Обрабатываем визуальный словарь \"{0}\"", name);

                List <XmlTranslationReader.Item> items = xmlTranslationReader.Read(file);

                string destinationFile = Path.Combine(path, name + ".csv");
                using (var csvWriter = new CsvWriter(destinationFile)) {
                    var      csvReader = new CsvReader(string.Format(PATTERN_VISUAL_DICTIONARY, name));
                    string[] header    = csvReader.ReadLine();
                    csvWriter.WriteLine(header);

                    Dictionary <string, string[]> lines = ConvertFieldsToDictionary(csvReader, PATTERN_KEY);
                    foreach (XmlTranslationReader.Item item in items)
                    {
                        string key = string.Format(PATTERN_KEY, item.Translation, item.Source).ToLowerInvariant();
                        if (!lines.ContainsKey(key))
                        {
                            Console.WriteLine(
                                "В файле {0} не найдены слова {1} - {2}. Слова не будут добавлены в файл! Нажмите ввод...",
                                name, item.Translation, item.Source);
                            Console.ReadLine();
                            continue;
                        }

                        var    fields = new List <string>();
                        string source;
                        if (EnumerableValidator.IsNotEmpty(item.Best))
                        {
                            source = item.Best[0].Trim();
                        }
                        else
                        {
                            source = "<UNKNOWN> - " + string.Join("|", item.Other);
                        }

                        fields.Add(source);
                        fields.Add(item.Source);
                        fields.AddRange(lines[key]);

                        csvWriter.WriteLine(fields.ToArray());
                    }

                    csvReader.Dispose();
                }
            }

            Console.WriteLine("Все визуальные словари обработаны!");
        }