def test_get_word_restrictions(self): normal_noun = utg_words.WordForm(utg_words.Word.create_test_word(type=utg_relations.WORD_TYPE.NOUN, prefix='w-1-', only_required=True)) singular_noun = utg_words.WordForm(utg_words.Word.create_test_word(type=utg_relations.WORD_TYPE.NOUN, prefix='w-1-', only_required=True, properties=utg_words.Properties(utg_relations.NUMBER.SINGULAR))) plural_noun = utg_words.WordForm(utg_words.Word.create_test_word(type=utg_relations.WORD_TYPE.NOUN, prefix='w-1-', only_required=True, properties=utg_words.Properties(utg_relations.NUMBER.PLURAL))) self.assertEqual(logic.get_word_restrictions('x', normal_noun), (('x', storage.restrictions_storage.get_restriction(relations.TEMPLATE_RESTRICTION_GROUP.PLURAL_FORM, relations.WORD_HAS_PLURAL_FORM.HAS.value).id),)) self.assertEqual(logic.get_word_restrictions('x', singular_noun), (('x', storage.restrictions_storage.get_restriction(relations.TEMPLATE_RESTRICTION_GROUP.PLURAL_FORM, relations.WORD_HAS_PLURAL_FORM.HAS_NO.value).id),)) self.assertEqual(logic.get_word_restrictions('x', plural_noun), (('x', storage.restrictions_storage.get_restriction(relations.TEMPLATE_RESTRICTION_GROUP.PLURAL_FORM, relations.WORD_HAS_PLURAL_FORM.HAS.value).id),))
def test_form(self): form = words.WordForm( word=self.word, properties=words.Properties(r.NUMBER.PLURAL), form_properties=words.Properties(r.NUMBER.PLURAL, r.CASE.DATIVE), ) self.assertEqual(form.form, 'w-нс,мн,дт')
def test_add_word_restrictions_into_variable_restrictions(self): key = keys.LEXICON_KEY.HERO_COMMON_JOURNAL_LEVEL_UP TEXT = '[hero|загл] [level] [дубль|hero|дт]' template = utg_templates.Template() template.parse(TEXT, externals=['hero', 'level']) prototypes.TemplatePrototype.create(key=key, raw_template=TEXT, utg_template=template, verificators=[], author=None) # update template errors_status and state to enshure, that it will be loaded in game lexicon prototypes.TemplatePrototype._db_all().update(errors_status=relations.TEMPLATE_ERRORS_STATUS.NO_ERRORS, state=relations.TEMPLATE_STATE.IN_GAME) storage.game_lexicon.refresh() normal_noun = utg_words.WordForm(utg_words.Word.create_test_word(type=utg_relations.WORD_TYPE.NOUN, prefix='w-1-', only_required=True)) singular_noun = utg_words.WordForm(utg_words.Word.create_test_word(type=utg_relations.WORD_TYPE.NOUN, prefix='w-1-', only_required=True, properties=utg_words.Properties(utg_relations.NUMBER.SINGULAR))) plural_noun = utg_words.WordForm(utg_words.Word.create_test_word(type=utg_relations.WORD_TYPE.NOUN, prefix='w-1-', only_required=True, properties=utg_words.Properties(utg_relations.NUMBER.PLURAL))) hero_mock = mock.Mock(utg_name_form=normal_noun, linguistics_restrictions=lambda: []) lexicon_key, externals, restrictions = logic.prepair_get_text(key.name, args={'hero': hero_mock, 'level': 1}) self.assertIn(('hero', storage.restrictions_storage.get_restriction(relations.TEMPLATE_RESTRICTION_GROUP.PLURAL_FORM, relations.WORD_HAS_PLURAL_FORM.HAS.value).id), restrictions) self.assertNotIn(('hero', storage.restrictions_storage.get_restriction(relations.TEMPLATE_RESTRICTION_GROUP.PLURAL_FORM, relations.WORD_HAS_PLURAL_FORM.HAS_NO.value).id), restrictions) hero_mock = mock.Mock(utg_name_form=singular_noun, linguistics_restrictions=lambda: []) lexicon_key, externals, restrictions = logic.prepair_get_text(key.name, args={'hero': hero_mock, 'level': 1}) self.assertNotIn(('hero', storage.restrictions_storage.get_restriction(relations.TEMPLATE_RESTRICTION_GROUP.PLURAL_FORM, relations.WORD_HAS_PLURAL_FORM.HAS.value).id), restrictions) self.assertIn(('hero', storage.restrictions_storage.get_restriction(relations.TEMPLATE_RESTRICTION_GROUP.PLURAL_FORM, relations.WORD_HAS_PLURAL_FORM.HAS_NO.value).id), restrictions) hero_mock = mock.Mock(utg_name_form=plural_noun, linguistics_restrictions=lambda: []) lexicon_key, externals, restrictions = logic.prepair_get_text(key.name, args={'hero': hero_mock, 'level': 1}) self.assertIn(('hero', storage.restrictions_storage.get_restriction(relations.TEMPLATE_RESTRICTION_GROUP.PLURAL_FORM, relations.WORD_HAS_PLURAL_FORM.HAS.value).id), restrictions) self.assertNotIn(('hero', storage.restrictions_storage.get_restriction(relations.TEMPLATE_RESTRICTION_GROUP.PLURAL_FORM, relations.WORD_HAS_PLURAL_FORM.HAS_NO.value).id), restrictions)
def test_starts_with_consonant_cluster(self): word = words.Word(type=r.WORD_TYPE.NOUN, forms=[ 'сон', 'сна', 'сну', 'сон', 'сном', 'сне', 'сны', 'снов', 'снам', 'сны', 'снами', 'снах', 'сны', 'снов', 'снам', 'сны', 'снами', 'снах' ], properties=words.Properties(r.GENDER.MASCULINE, r.ANIMALITY.INANIMATE)) form = words.WordForm(word=word, properties=words.Properties( r.CASE.NOMINATIVE)) # сон self.assertFalse(form.starts_with_consonant_cluster) form = words.WordForm(word=word, properties=words.Properties( r.CASE.DATIVE)) # сну self.assertTrue(form.starts_with_consonant_cluster)
def preprocessed_externals(self): externals = {} for k, (word_form, additional_properties) in self.externals.items(): if isinstance(word_form, int): word_form = utg_constructors.construct_integer(word_form) else: word_form = lexicon_dictionary.DICTIONARY.get_word(word_form) if additional_properties: properties = utg_words.Properties(word_form.properties, *[VERBOSE_TO_PROPERTIES[prop.strip()] for prop in additional_properties.split(',') if prop]) word_form = utg_words.WordForm(word=word_form.word, properties=properties) externals[k] = word_form return externals
def _construct_integer(number): form = str(number) number = abs(number) if number in (1000000, 1000000000): properties = INTEGER_PROPERTIES.IS_KKK.properties elif number == 1: properties = INTEGER_PROPERTIES.IS_1.properties elif number in (2, 3, 4): properties = INTEGER_PROPERTIES.IS_234.properties elif 10 <= number % 100 <= 19: properties = INTEGER_PROPERTIES.IS_10_19.properties elif number % 10 == 1: properties = INTEGER_PROPERTIES.IS_END_BY_1.properties elif 2 <= number % 10 <= 4: properties = INTEGER_PROPERTIES.IS_MOD_234.properties else: properties = INTEGER_PROPERTIES.IS_OTHER.properties return words.WordForm( words.Word(type=r.WORD_TYPE.INTEGER, forms=[form], properties=properties))
def utg_name_form(self): return utg_words.WordForm( utg_words.Word(type=WORD_TYPE.TEXT, forms=(self.date.verbose_full(), )))
('TEXT', 5, u'любой текст', WORD_TYPE.TEXT, s([u'любой текст'], [u'текст текст текст'], [u'какой-то текст'])), ('MODIFIER', 6, u'модификатор города', WORD_TYPE.NOUN, s([u'форт', u'захолустье', u'святыня', (u'мемориал', u'мн')], [u'замок', u'пристанище', u'земля', (u'колония', u'мн')])), ('RACE', 7, u'раса', WORD_TYPE.NOUN, s([u'человек', u'эльф', u'орк', u'гоблин', u'дварф'], [u'человек', u'эльф', u'орк', u'гоблин', u'дварф'], [u'человек', u'эльф', u'орк', u'гоблин', u'дварф']))) _construct_utg_name_form = lambda v: (v.utg_name_form, v.linguistics_restrictions()) _construct_number = lambda v: (utg_constructors.construct_integer(int(v)), []) _construct_text = lambda v: (utg_words.WordForm( utg_words.Word(type=WORD_TYPE.TEXT, forms=(v, ))), []) class VARIABLE_TYPE(DjangoEnum): verificator = Column(unique=False, no_index=True) constructor = Column(unique=False, no_index=True) restrictions = Column(unique=False, no_index=True) records = (('HERO', 0, u'герой', VARIABLE_VERIFICATOR.PERSON, _construct_utg_name_form, (relations.TEMPLATE_RESTRICTION_GROUP.GENDER, relations.TEMPLATE_RESTRICTION_GROUP.RACE, relations.TEMPLATE_RESTRICTION_GROUP.HABIT_HONOR, relations.TEMPLATE_RESTRICTION_GROUP.HABIT_PEACEFULNESS, relations.TEMPLATE_RESTRICTION_GROUP.ARCHETYPE, relations.TEMPLATE_RESTRICTION_GROUP.TERRAIN,
def utg_name_form(self): from utg import words as utg_words return utg_words.WordForm(self.word)
def test_preposition_consonants(self): pre_1 = self._create_preposition(['под', 'подо', 'подо']) pre_2 = self._create_preposition(['за', 'за', 'за']) pre_3 = self._create_preposition(['в', 'во', 'во']) pre_4 = self._create_preposition(['с', 'со', 'со']) master_word_1 = words.Word( type=r.WORD_TYPE.NOUN, forms=[ 'сон', 'сна', 'сну', 'сон', 'сном', 'сне', 'сны', 'снов', 'снам', 'сны', 'снами', 'снах', 'сны', 'снов', 'снам', 'сны', 'снами', 'снах' ], properties=words.Properties(r.GENDER.MASCULINE, r.ANIMALITY.INANIMATE)) master_word_2 = words.Word( type=r.WORD_TYPE.NOUN, forms=[ 'сновидение', 'сновидения', 'сновидению', 'сновидение', 'сновидением', 'сновидении', 'сновидения', 'сновидений', 'сновидениям', 'сновидения', 'сновидениями', 'сновидениях', 'сновидения', 'сновидений', 'сновидениям', 'сновидения', 'сновидениями', 'сновидениях' ], properties=words.Properties(r.GENDER.NEUTER, r.ANIMALITY.INANIMATE)) master_word_3 = words.Word( type=r.WORD_TYPE.NOUN, forms=[ 'власть', 'власти', 'власти', 'власть', 'властью', 'власти', '', '', '', '', '', '', '', '', '', '', '', '' ], properties=words.Properties(r.GENDER.MASCULINE, r.ANIMALITY.INANIMATE, r.NUMBER.SINGULAR)) slave_properties = words.Properties( random.choice(r.PREPOSITION_FORM.records)) master_form_1 = words.WordForm(word=master_word_1, properties=words.Properties( r.CASE.NOMINATIVE)) # сон master_form_2 = words.WordForm(word=master_word_1, properties=words.Properties( r.CASE.DATIVE)) # сну master_form_3 = words.WordForm(word=master_word_2) # сновидение master_form_4 = words.WordForm(word=master_word_3) # власть tests = { (pre_1, master_form_1): slave_properties, # под сон (pre_1, master_form_2): words.Properties(r.PREPOSITION_FORM.ALTERNATIVE), # подо сну (pre_1, master_form_3): slave_properties, # под сновидение (pre_1, master_form_4): slave_properties, # под власть (pre_2, master_form_1): slave_properties, # за сон (pre_2, master_form_2): slave_properties, # за сну (pre_2, master_form_3): slave_properties, # за сновидение (pre_2, master_form_4): slave_properties, # за власть (pre_3, master_form_1): slave_properties, # в сон (pre_3, master_form_2): words.Properties(r.PREPOSITION_FORM.ALTERNATIVE), # во сну (pre_3, master_form_3): slave_properties, # в сновидение (pre_3, master_form_4): words.Properties(r.PREPOSITION_FORM.ALTERNATIVE), # во власть (pre_4, master_form_1): slave_properties, # с сон (pre_4, master_form_2): words.Properties(r.PREPOSITION_FORM.ALTERNATIVE), # со сну (pre_4, master_form_3): words.Properties(r.PREPOSITION_FORM.ALTERNATIVE), # со сновидение (pre_4, master_form_4): slave_properties } # с власть for (pre, master_form), result_properties in tests.items(): self.assertEqual( transformators._preposition_any(properties=slave_properties, slave_word=pre, master_form=master_form), result_properties)
def test_init__simple(self): form = words.WordForm(word=self.word, properties=words.Properties(r.NUMBER.PLURAL)) self.assertEqual(form.properties, words.Properties(r.NUMBER.PLURAL)) self.assertEqual(form.form_properties, words.Properties(r.NUMBER.PLURAL))
def _construct_text(value): return (utg_words.WordForm( utg_words.Word(type=WORD_TYPE.TEXT, forms=(value, ))), [])
(len(data.WORDS_CACHES[r.WORD_TYPE.VERB]) - 5), properties=words.Properties(r.ASPECT.PERFECTIVE, r.VOICE.DIRECT)) action_word.autofill_missed_forms() test_dictionary = dictionary.Dictionary(words=[games_word, action_word]) template = templates.Template() template.parse(u'[Npc] [дал|npc] [hero|дт] [games] [игра|games|вн].', externals=('hero', 'npc', 'games')) hero = words.WordForm( words.Word(type=r.WORD_TYPE.NOUN, forms=[ u'герой', u'героя', u'герою', u'героя', u'героем', u'герое', u'герои', u'героев', u'героям', u'героев', u'героями', u'героях', u'герои', u'героев', u'героям', u'героев', u'героями', u'героях' ], properties=words.Properties(r.ANIMALITY.ANIMATE, r.GENDER.MASCULINE))) npc = words.WordForm( words.Word(type=r.WORD_TYPE.NOUN, forms=[ u'кошка', u'кошки', u'кошке', u'кошку', u'кошкой', u'кошке', u'кошки', u'кошек', u'кошкам', u'кошек', u'кошками', u'кошках', u'кошки', u'кошек', u'кошкам', u'кошек', u'кошками', u'кошках' ], properties=words.Properties(r.ANIMALITY.ANIMATE, r.GENDER.FEMININE)))
def test_preposition_vovels(self): pre_1 = self._create_preposition(['о', 'об', 'обо']) pre_2 = self._create_preposition(['у', 'у', 'у']) master_word_1 = words.Word( type=r.WORD_TYPE.NOUN, forms=[ 'ужин', 'ужина', 'ужину', 'ужин', 'ужином', 'ужине', 'ужины', 'ужинов', 'ужинам', 'ужины', 'ужинами', 'ужинах', 'ужины', 'ужинов', 'ужинам', 'ужины', 'ужинами', 'ужинах' ], properties=words.Properties(r.GENDER.MASCULINE, r.ANIMALITY.INANIMATE)) master_word_2 = words.Word( type=r.WORD_TYPE.NOUN, forms=[ 'юрист', 'юриста', 'юристу', 'юриста', 'юристом', 'юристе', 'юристы', 'юристов', 'юристам', 'юристов', 'юристами', 'юристах', 'юристы', 'юристов', 'юристам', 'юристов', 'юристами', 'юристах' ], properties=words.Properties(r.GENDER.NEUTER, r.ANIMALITY.INANIMATE)) master_word_3 = words.Word( type=r.WORD_TYPE.PRONOUN, forms=[ 'я', 'я', 'я', 'меня', 'меня', 'меня', 'мне', 'мне', 'мне', 'меня', 'меня', 'меня', 'мной', 'мной', 'мной', 'мне', 'мне', 'мне', 'мы', 'нас', 'нам', 'нас', 'нами', 'нас', 'я', 'я', 'я', 'меня', 'меня', 'меня', 'мне', 'мне', 'мне', 'меня', 'меня', 'меня', 'мной', 'мной', 'мной', 'мне', 'мне', 'мне', 'мы', 'нас', 'нам', 'нас', 'нами', 'нас' ], properties=words.Properties(r.PRONOUN_CATEGORY.PERSONAL)) slave_properties = words.Properties( random.choice(r.PREPOSITION_FORM.records)) master_form_1 = words.WordForm(word=master_word_1, properties=words.Properties( r.CASE.NOMINATIVE)) # ужин master_form_2 = words.WordForm(word=master_word_1, properties=words.Properties( r.CASE.DATIVE)) # ужину master_form_3 = words.WordForm(word=master_word_2) # юрист master_form_4 = words.WordForm(word=master_word_3) # я master_form_5 = words.WordForm(word=master_word_3, properties=words.Properties( r.CASE.DATIVE)) # мне self.assertEqual(master_form_5.form, 'мне') tests = { (pre_1, master_form_1): words.Properties(r.PREPOSITION_FORM.ALTERNATIVE), # об ужин (pre_1, master_form_2): words.Properties(r.PREPOSITION_FORM.ALTERNATIVE), # об ужину (pre_1, master_form_3): slave_properties, # о юрист (pre_1, master_form_4): slave_properties, # о я (pre_1, master_form_5): words.Properties(r.PREPOSITION_FORM.SPECIAL), # обо мне (pre_2, master_form_1): words.Properties(r.PREPOSITION_FORM.ALTERNATIVE), # у ужин (pre_2, master_form_2): words.Properties(r.PREPOSITION_FORM.ALTERNATIVE), # у ужину (pre_2, master_form_3): slave_properties, # у юрист (pre_2, master_form_4): slave_properties, # у я (pre_2, master_form_5): slave_properties, # у мне } for (pre, master_form), result_properties in tests.items(): self.assertEqual( transformators._preposition_any(properties=slave_properties, slave_word=pre, master_form=master_form), result_properties)
# описываем только нужны нам формы слова (порядок важен и определён в utg.data.WORDS_CACHES[r.WORD_TYPE.VERB]) forms=[u'подарить', u'подарил', u'подарило', u'подарила', u'подарили'] + [u''] * (len(data.WORDS_CACHES[r.WORD_TYPE.VERB]) - 5), properties=words.Properties(r.ASPECT.PERFECTIVE, r.VOICE.DIRECT)) action_word.autofill_missed_forms( ) # заполняем пропущенные формы на основе введённых (выбираются наиболее близкие) # создаём словарь для использования в шаблонах test_dictionary = dictionary.Dictionary(words=[coins_word, action_word]) # описываем внешние переменные hero = words.WordForm( words.Word(type=r.WORD_TYPE.NOUN, forms=[ u'герой', u'героя', u'герою', u'героя', u'героем', u'герое', u'герои', u'героев', u'героям', u'героев', u'героями', u'героях', u'герои', u'героев', u'героям', u'героев', u'героями', u'героях' ], properties=words.Properties(r.ANIMALITY.ANIMATE, r.GENDER.MASCULINE))) npc = words.WordForm( words.Word(type=r.WORD_TYPE.NOUN, forms=[ u'русалка', u'русалки', u'русалке', u'русалку', u'русалкой', u'русалке', u'русалки', u'русалок', u'русалкам', u'русалок', u'русалками', u'русалках', u'русалки', u'русалок', u'русалкам', u'русалок', u'русалками', u'русалках' ], properties=words.Properties(r.ANIMALITY.ANIMATE, r.GENDER.FEMININE)))
def utg_name_form(self): return utg_words.WordForm(self.utg_name)
def test_full_usage(self): # описываем существительное для словаря coins_word = words.Word( type=r.WORD_TYPE.NOUN, forms=[ 'монета', 'монеты', 'монете', 'монету', 'монетой', 'монете', # единственнео число 'монеты', 'монет', 'монетам', 'монеты', 'монетами', 'монетах', # множественное число 'монеты', 'монет', 'монетам', 'монеты', 'монетами', 'монетах' ], # счётное число (заполнено для пример, может быть заполнено методом autofill_missed_forms) properties=words.Properties( r.ANIMALITY.INANIMATE, r.GENDER.FEMININE)) # свойства: неодушевлённое, женский род # описываем глагол для словаря action_word = words.Word( type=r.WORD_TYPE.VERB, # описываем только нужны нам формы слова (порядок важен и определён в utg.data.WORDS_CACHES[r.WORD_TYPE.VERB]) forms=['подарить', 'подарил', 'подарило', 'подарила', 'подарили'] + [''] * (len(data.WORDS_CACHES[r.WORD_TYPE.VERB]) - 5), properties=words.Properties(r.ASPECT.PERFECTIVE, r.VOICE.DIRECT)) action_word.autofill_missed_forms( ) # заполняем пропущенные формы на основе введённых (выбираются наиболее близкие) # создаём словарь для использования в шаблонах test_dictionary = dictionary.Dictionary( words=[coins_word, action_word]) # создаём шаблон template = templates.Template() # externals — внешние переменные, не обязаны быть в словаре template.parse( '[Npc] [подарил|npc] [hero|дт] [coins] [монета|coins|вн].', externals=('hero', 'npc', 'coins')) # описываем внешние переменные hero = words.WordForm( words.Word(type=r.WORD_TYPE.NOUN, forms=[ 'герой', 'героя', 'герою', 'героя', 'героем', 'герое', 'герои', 'героев', 'героям', 'героев', 'героями', 'героях', 'герои', 'героев', 'героям', 'героев', 'героями', 'героях' ], properties=words.Properties(r.ANIMALITY.ANIMATE, r.GENDER.MASCULINE))) npc = words.WordForm( words.Word(type=r.WORD_TYPE.NOUN, forms=[ 'русалка', 'русалки', 'русалке', 'русалку', 'русалкой', 'русалке', 'русалки', 'русалок', 'русалкам', 'русалок', 'русалками', 'русалках', 'русалки', 'русалок', 'русалкам', 'русалок', 'русалками', 'русалках' ], properties=words.Properties(r.ANIMALITY.ANIMATE, r.GENDER.FEMININE))) # осуществляем подстановку result = template.substitute(externals={ 'hero': hero, 'npc': npc, 'coins': constructors.construct_integer(125) }, dictionary=test_dictionary) self.assertEqual(result, 'Русалка подарила герою 125 монет.')