private static SentenceTranslation GetSentenceTranslation(StudyLanguageContext context, PronunciationForUser sourceSentence, PronunciationForUser translationSentence) { IQueryable <SentenceTranslation> sentencesWithTranslationsQuery = from s1 in context.Sentence join st in context.SentenceTranslation on s1.Id equals st.SentenceId1 join s2 in context.Sentence on st.SentenceId2 equals s2.Id where ((s1.LanguageId == sourceSentence.LanguageId && s1.Text == sourceSentence.Text && s2.LanguageId == translationSentence.LanguageId && s2.Text == translationSentence.Text) || (s1.LanguageId == translationSentence.LanguageId && s1.Text == translationSentence.Text && s2.LanguageId == sourceSentence.LanguageId && s2.Text == sourceSentence.Text)) select st; SentenceTranslation sentenceTranslation = sentencesWithTranslationsQuery.FirstOrDefault(); return(sentenceTranslation); }
private SourceWithTranslation CreateSentencencesWithTranslation(SentenceType type, PronunciationForUser source, PronunciationForUser translation, byte[] image = null, int?rating = null) { SourceWithTranslation result = null; Adapter.ActionByContext(context => { Sentence sourceSentence = GetOrAddSentenceToContext(source.LanguageId, source.Text, context); Sentence translationSentence = GetOrAddSentenceToContext(translation.LanguageId, translation.Text, context); context.SaveChanges(); if (IdValidator.IsInvalid(sourceSentence.Id) || IdValidator.IsInvalid(translationSentence.Id)) { return; } var sentenceTranslation = new SentenceTranslation { SentenceId1 = sourceSentence.Id, SentenceId2 = translationSentence.Id }; SetSentenceTranslation(sentenceTranslation, type, image, rating); context.SentenceTranslation.Add(sentenceTranslation); context.SaveChanges(); if (IdValidator.IsInvalid(sentenceTranslation.Id)) { return; } result = ConverterEntities.ConvertToSourceWithTranslation(sentenceTranslation.Id, sentenceTranslation.Image, source.LanguageId, sourceSentence, translationSentence); }); return(result); }
public SourceWithTranslation GetOrCreate(SentenceType type, PronunciationForUser source, PronunciationForUser translation, byte[] image, int?rating = null) { //TODO: проверять корректность параметров SourceWithTranslation result = null; Adapter.ActionByContext(context => { SentenceTranslation sentenceTranslation = GetSentenceTranslation(context, source, translation); if (sentenceTranslation != null) { //обновить возможно изменившиеся поля SetSentenceTranslation(sentenceTranslation, type, image, rating); context.SaveChanges(); if (IdValidator.IsValid(sentenceTranslation.Id)) { result = new SourceWithTranslation(); result.Set(sentenceTranslation.Id, source, translation); } } else { result = CreateSentencencesWithTranslation(type, source, translation, image, rating); } }); return(result); }
public static string GetSpeakerHtml(PronunciationForUser pronunciationForUser, SpeakerDataType type) { string sourceText = String.Format("{0}{1}", pronunciationForUser.HasPronunciation ? String.Format(SPEAKER_PATTERN_HTML, pronunciationForUser.Id, (int)type) : String.Empty, pronunciationForUser.Text); return(sourceText); }
public static SourceWithTranslation ConvertToSourceWithTranslation(long id, byte[] image, PronunciationForUser pronunciation1, PronunciationForUser pronunciation2) { var result = new SourceWithTranslation(); result.Set(id, pronunciation1, pronunciation2); result.HasImage = image != null && image.Length > 0; return(result); }
/// <summary> /// Создает слова для группы /// </summary> /// <param name="groupForUser">группа, к которой нужно добавить слово</param> /// <param name="source">слово</param> /// <param name="translation">перевод</param> /// <param name="image">изображение для слова</param> /// <param name="rating">рейтинг</param> /// <returns>созданные слова для группы, или ничего</returns> public SourceWithTranslation GetOrCreate(GroupForUser groupForUser, PronunciationForUser source, PronunciationForUser translation, byte[] image, int?rating) { var sentencesQuery = new SentencesQuery(); SourceWithTranslation sentenceWithTranslation = sentencesQuery.GetOrCreate(SentenceType.FromGroup, source, translation, image, null); if (sentenceWithTranslation == null || IdValidator.IsInvalid(sentenceWithTranslation.Id)) { LoggerWrapper.LogTo(LoggerName.Errors).ErrorFormat( "GroupSentencesQuery.GetOrCreate can't add sentence {0} with translation {1}, image {2}, rating {3}", source.Text, translation.Text, image != null ? image.Length.ToString(CultureInfo.InvariantCulture) : "<NULL>", rating); return(null); } SourceWithTranslation result = Adapter.ReadByContext(c => { var wordsWithTranslationsQuery = (from s1 in c.Sentence join st in c.SentenceTranslation on s1.Id equals st.SentenceId1 join gs in c.GroupSentence on st.Id equals gs.SentenceTranslationId join s2 in c.Sentence on st.SentenceId2 equals s2.Id where gs.GroupId == groupForUser.Id && st.Id == sentenceWithTranslation.Id select new { gs, st, s1, s2 }); var firstRecord = wordsWithTranslationsQuery.AsEnumerable().FirstOrDefault(); if (firstRecord == null) { return(null); } //сохранить возможно изменившийся рейтинг GroupSentence groupSentence = firstRecord.gs; groupSentence.Rating = rating; c.SaveChanges(); SourceWithTranslation innerResult = ConvertToGroupSentenceWithTranslation(firstRecord.st.Id, firstRecord.st.Image, sentenceWithTranslation .Source.LanguageId, firstRecord.s1, firstRecord.s2); return(innerResult); }); if (result == null) { result = Create(groupForUser, sentenceWithTranslation, rating); } return(result); }
/*public JsonResult GetExamples(UserLanguages userLanguages, * GroupForUser group) { * if (userLanguages == null || group == null || UserLanguages.IsInvalid(userLanguages)) { * return JsonResultHelper.Error(); * } * GroupModel model = GetModel(userLanguages, group); * if (model.IsInvalid()) { * return JsonResultHelper.Error(); * } * * var resultExamples = new List<Tuple<long, List<string>>>(); * var searchEngineFactory = new SentencesSearchEngineFactory(); * ISentencesSearchEngine fromSentencesSearchEngine = searchEngineFactory.Create(userLanguages.From.Id); * ISentencesSearchEngine toSentencesSearchEngine = searchEngineFactory.Create(userLanguages.To.Id); * * foreach (SourceWithTranslation elem in model.ElemsWithTranslations) { * model.SetCurrent(elem); * * AddExample(fromSentencesSearchEngine, elem.Source, resultExamples); * AddExample(toSentencesSearchEngine, elem.Translation, resultExamples); * } * return JsonResultHelper.GetUnlimitedJsonResult(resultExamples); * }*/ /*protected JsonResult GetKnowledgeInfo(long userId, UserLanguages userLanguages, GroupForUser group) { * if (IdValidator.IsInvalid(userId) || group == null) { * return JsonResultHelper.Error(); * } * GroupModel model = GetModel(userLanguages, group, GetPatternsForAll(group)); * if (model.IsInvalid()) { * return JsonResultHelper.Error(); * } * var knowledgeQuery = IoCModule.Create<UserKnowledgeQuery>(); * var statuses = //knowledgeQuery.GetStatusesByDataIds(model.ElemsWithTranslations.Select(e => e.Id).ToList()); * return GetUnlimitedJsonResult(statuses); * }*/ public void AddExample(ISentencesSearchEngine sentencesSearcher, PronunciationForUser entity, List <Tuple <long, List <string> > > result) { List <string> examples = sentencesSearcher.FindSentences(entity.Text, OrderWordsInSearch.ExactWordForWord); if (EnumerableValidator.IsEmpty(examples)) { return; } result.Add(new Tuple <long, List <string> >(entity.Id, examples)); }
/// <summary> /// Создает слова для группы /// </summary> /// <param name="groupForUser">группа, к которой нужно добавить слово</param> /// <param name="source">слово</param> /// <param name="translation">перевод</param> /// <param name="image">изображение для слова</param> /// <param name="rating">рейтинг</param> /// <returns>созданные слова для группы, или ничего</returns> public SourceWithTranslation GetOrCreate(GroupForUser groupForUser, PronunciationForUser source, PronunciationForUser translation, byte[] image, int?rating) { var wordsQuery = new WordsQuery(); WordWithTranslation wordWithTranslation = wordsQuery.GetOrCreate(source, translation, image, WordType.Default, null); if (wordWithTranslation == null) { return(null); } SourceWithTranslation result = Adapter.ReadByContext(c => { var wordsWithTranslationsQuery = (from w1 in c.Word join wt in c.WordTranslation on w1.Id equals wt.WordId1 join gw in c.GroupWord on wt.Id equals gw.WordTranslationId join w2 in c.Word on wt.WordId2 equals w2.Id where gw.GroupId == groupForUser.Id && wt.Id == wordWithTranslation.Id select new { gw, wt, w1, w2 }); var firstRecord = wordsWithTranslationsQuery.AsEnumerable().FirstOrDefault(); if (firstRecord == null) { return(null); } //сохранить возможно изменившийся рейтинг GroupWord groupWord = firstRecord.gw; groupWord.Rating = rating; c.SaveChanges(); SourceWithTranslation innerResult = ConverterEntities.ConvertToSourceWithTranslation(firstRecord.wt.Id, firstRecord.wt. Image, wordWithTranslation .Source. LanguageId, firstRecord.w1, firstRecord.w2); return(innerResult); }); if (result == null) { result = Create(groupForUser, wordWithTranslation, rating); } return(result); }
private Word GetOrAddWord(PronunciationForUser wordForUser, WordType wordType, IEnumerable <Word> words, StudyLanguageContext context) { Word word = words.FirstOrDefault(); if (word == null) { word = AddWord(context, wordForUser.LanguageId, wordForUser.Text, wordType); } else { word.Type |= (int)wordType; } return(word); }
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(); }
/// <summary> /// Создает слова по типу популярности /// </summary> /// <param name="source">слово</param> /// <param name="translation">перевод</param> /// <param name="type">тип популярности</param> /// <returns>созданные слова для группы, или ничего</returns> public SourceWithTranslation GetOrCreate(PronunciationForUser source, PronunciationForUser translation, PopularWordType type) { var wordsQuery = new WordsQuery(); WordWithTranslation wordWithTranslation = wordsQuery.GetOrCreate(source, translation, null, WordType.Default, null); if (wordWithTranslation == null) { return(null); } var parsedType = (int)type; SourceWithTranslation result = Adapter.ReadByContext(c => { var wordsWithTranslationsQuery = (from w1 in c.Word join wt in c.WordTranslation on w1.Id equals wt.WordId1 join pw in c.PopularWord on wt.Id equals pw.WordTranslationId join w2 in c.Word on wt.WordId2 equals w2.Id where pw.Type == parsedType && wt.Id == wordWithTranslation.Id select new { wt, w1, w2 }); var firstRecord = wordsWithTranslationsQuery.AsEnumerable().FirstOrDefault(); if (firstRecord == null) { return(null); } SourceWithTranslation innerResult = ConverterEntities.ConvertToSourceWithTranslation(firstRecord.wt.Id, firstRecord.wt. Image, wordWithTranslation .Source. LanguageId, firstRecord.w1, firstRecord.w2); return(innerResult); }); if (result == null) { result = Create(wordWithTranslation, parsedType); } return(result); }
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); }
private static bool IsSentencesEquals(long searchId, PronunciationForUser sentence) { return(searchId == sentence.Id); }
public bool IsInvalid(PronunciationForUser wordForUser) { return(wordForUser == null || string.IsNullOrEmpty(wordForUser.Text) || IdValidator.IsInvalid(wordForUser.LanguageId)); }
public WordWithTranslation GetOrCreate(PronunciationForUser source, PronunciationForUser translation, byte[] image, WordType wordType = WordType.Default, int?rating = null) { //TODO: проверять корректность параметров WordWithTranslation result = null; Adapter.ActionByContext(context => { IEnumerable <Word> sourceWords = FindWords(context, new List <PronunciationForUser> { source }); IEnumerable <Word> translateWords = FindWords(context, new List <PronunciationForUser> { translation }); Word sourceWord = GetOrAddWord(source, wordType, sourceWords, context); Word translationWord = GetOrAddWord(translation, wordType, translateWords, context); context.SaveChanges(); if (sourceWord == null || IdValidator.IsInvalid(sourceWord.Id) || translationWord == null || IdValidator.IsInvalid(translationWord.Id)) { //все слова добавлены - если нужно, добавить связь между новым словом и переводом для него LoggerWrapper.LogTo(LoggerName.Errors).ErrorFormat( "WordsQuery.GetOrCreate can't add text {0} with translation {1}, image {2}, wordType {3}, rating {4}", source.Text, translation.Text, image != null ? image.Length.ToString(CultureInfo.InvariantCulture) : "<NULL>", wordType, rating); result = null; return; } WordTranslation wordTranslation = GetWordTranslation(context, sourceWord, translationWord); if (wordTranslation != null) { //обновить возможно изменившийся рейтинг и изображение wordTranslation.Image = image; wordTranslation.Rating = rating; context.SaveChanges(); } else { wordTranslation = Create(image, rating, context, sourceWord, translationWord); } if (IdValidator.IsValid(wordTranslation.Id)) { result = new WordWithTranslation(sourceWord) { Id = wordTranslation.Id }; result.AddTranslation(translationWord); } else { LoggerWrapper.LogTo(LoggerName.Errors).ErrorFormat( "WordsQuery.GetOrCreate can't add/get wordTranslation for text {0} with translation {1}, image {2}, wordType {3}, rating {4}", source.Text, translation.Text, image != null ? image.Length.ToString(CultureInfo.InvariantCulture) : "<NULL>", wordType, rating); } }); return(result); }
public long GetIdByWordsForUser(PronunciationForUser source, PronunciationForUser translation) { WordWithTranslation wrd = GetOrCreate(source, translation, null); return(wrd != null ? wrd.Id : IdValidator.INVALID_ID); }
public void Create(string fileName, string pathToImagePattern) { var csvReader = new CsvReader(fileName); var languages = new LanguagesQuery(LanguageShortName.Unknown, LanguageShortName.Unknown); Language from = languages.GetByShortName(_from); Language to = languages.GetByShortName(LanguageShortName.Ru); var representationsQuery = new RepresentationsQuery(from.Id); string[] line = csvReader.ReadLine(); if (line.Length < 1 || string.IsNullOrEmpty(line[0])) { Console.WriteLine("Некорректная первая строка в файле {0}!", fileName); return; } int imageIndex = 0; if (line.Length >= 2 && !string.IsNullOrEmpty(line[1])) { imageIndex = 1; } string imageFileName = string.Format(pathToImagePattern, line[imageIndex].Trim()); Image image = Image.FromFile(imageFileName); var memoryStream = new MemoryStream(); image.Save(memoryStream, ImageFormat.Jpeg); byte[] imageBytes = memoryStream.ToArray(); string visualDictionaryName = line[0]; byte?widthPercent = null; if (line.Length > 2) { byte w; if (byte.TryParse(line[2], out w) && w > 0 && w <= 100) { widthPercent = w; } } visualDictionaryName = char.ToUpper(visualDictionaryName[0]) + visualDictionaryName.Substring(1); var representationForUser = new RepresentationForUser(IdValidator.INVALID_ID, visualDictionaryName, imageBytes, new Size(image.Size.Width, image.Size.Height), widthPercent); bool hasErrors = false; do { line = csvReader.ReadLine(); if (line != null) { if (line.Length < 6) { hasErrors = true; break; } PronunciationForUser englishWord = CreateWordForUser(line[0], from); PronunciationForUser russianWord = CreateWordForUser(line[1], to); Point leftTopPoint = CreatePoint(line[2], line[3]); Point rightBottomPoint = CreatePoint(line[4], line[5]); if (englishWord == null || russianWord == null || leftTopPoint == null || rightBottomPoint == null) { hasErrors = true; break; } var representationArea = new RepresentationAreaForUser(IdValidator.INVALID_ID, leftTopPoint, rightBottomPoint) { Source = russianWord, Translation = englishWord }; representationForUser.AddArea(representationArea); } } while (line != null); if (hasErrors) { Console.WriteLine("В файле {0} возникли ошибки! Файл не будет сохранен", fileName); return; } RepresentationForUser savedRepresentation = representationsQuery.GetOrCreate(representationForUser); Console.WriteLine("Визуальный словарь {0} {1}", representationForUser.Title, savedRepresentation != null ? "сохранен" : "НЕ сохранен!"); }
public static string GetText(PronunciationForUser pronunciationForUser) { return(pronunciationForUser.Text); }
public WordWithTranslation(PronunciationEntity word) { Source = new PronunciationForUser(word); Translations = new List <PronunciationForUser>(); }
private static bool IsWordsEquals(string searchWord, PronunciationForUser word) { return(searchWord.Equals(word.Text, StringComparison.InvariantCultureIgnoreCase)); }