diff --git a/tsyppo_anton_lab_7/README.md b/tsyppo_anton_lab_7/README.md new file mode 100644 index 0000000..cafb2d6 --- /dev/null +++ b/tsyppo_anton_lab_7/README.md @@ -0,0 +1,96 @@ +# Лабораторная работа №7: Рекуррентная нейронная сеть и задача генерации текста +## Задание. Вариант 28 + +Выбрать художественный текст (четные варианты – русскоязычный, нечетные – англоязычный) и обучить на нем рекуррентную +нейронную сеть для решения задачи генерации. Подобрать архитектуру и параметры так, чтобы приблизиться к максимально +осмысленному результату. Далее разбиться на пары четный-нечетный вариант, обменяться разработанными сетями и проверить, +как архитектура товарища справляется с вашим текстом. В завершении подобрать компромиссную архитектуру, справляющуюся +достаточно хорошо с обоими видами текстов. + +## Описание программы + +Данная программа обучается на двух текстах русскоязычном и англоязычном (2912 слов в англоязычном тесте и 1908 в +русскоязычном). В программе по итогу была реализованна архитектура справляющаяся с обоими видами текстов. + +## Как запустить лабораторную работу + +1. Установите необходимые библиотеки: + + ```bash + pip install tensorflow + pip install keras + ``` + +2. Запустите скрипт: + + ```bash + python main.py + ``` + +## Использованные технологии + +- Python +- tensorflow +- keras + +## Что программа делает + +Программа загружает данные, считывает текста из файлов rus.txt и eng.txt. Далее для обоих текстов происходит следующее: +Происходит токенизация текста на отдельные слова. Создание последовательностей (n-грамм) для обучения модели. +Использование рекуррентной нейронной сети (RNN) с LSTM слоями. Потом происходит обучение модели на подготовленных данных. +Использование обученной модели для предсказания следующего слова на основе введенного текста. В конце программа выводит +сгенерированные текста. + +## Тесты + +Запуск программы с 20-ю эпохами: +![Графики моделей](img/work20.png) + +Вывод русскоязычного текста с 20-ю эпохами: +![Графики моделей](img/rus20.png) + +Текст: +> Начало широким надень дочка старик и откуда вдруг ледяной уж август и пошла так на выручили на дверей и тебе перед +> беседуют старику тут сосульки висели они ни обогнал в лесу присесть стукнул считать ждать на сказала да месяцы неба +> покрытая дочку и тихо опять и под между зеленые вязанкой достает + +Вывод англоязычного текста с 20-ю эпохами: +![Графики моделей](img/eng20.png) + +Текст: +> Start if i back ‘i i’m sure we ’ any worked is has aloud into dinner has three coming surprised to soon about the +> back all he said to have thing mr britnell exactly across when he saw that looked at the picture before — a very +> dark he with the + +Запуск программы с 100-й эпохами: +![Графики моделей](img/work100.png) + +Вывод русскоязычного текста с 100-й эпохами: +![Графики моделей](img/rus100.png) + +Текст: +> Начало ему свою длинную бороду старик и говорит сестра — уже домой вернулась а подснежники где за нею замерзнуть +> ворох подснежников чем корзинкой подснежников не выглянут мартом ворох подснежников какие сладких а май обогнал бы +> апрель месяцы не гаснет он за подарили где пожарче и стала греться замолчали братья месяцы тихо + +Вывод англоязычного текста с 100-й эпохами: +![Графики моделей](img/eng100.png) + +Текст: +> Start a see ’ said nisbet ‘but i must have but what i must do first i must ask garwood exactly what he saw when he +> looked at the picture last night then i must have the picture photographed before it goes any further and thirdly i +> must find out where + +Перевод англоязычных текстов с помощью Google-переводчика: +![Графики моделей](img/translation.png) + +## Вывод + +_Смотря на тесты можно заметить что текст с 20-ю эпохами является по сути несвязным набором слов, в отличие от 100 где +уже прослеживаются вполне связный ряд словосочетаний и местами текст обретает хоть какой-то смысл в случае русскоязычного +можно догадаться что основной темой являются подснежники. С англоязычным текстом разница заметна ещё лучше поскольку +англоязычный текст больше. Подводя итоги можно сделать вывод, что количество эпох, а так же объём текста на котором +обучается рекуррентная нейронная сеть влияет на конечный генерируемый текст._ + +--- + diff --git a/tsyppo_anton_lab_7/img/eng100.png b/tsyppo_anton_lab_7/img/eng100.png new file mode 100644 index 0000000..32fe2d8 Binary files /dev/null and b/tsyppo_anton_lab_7/img/eng100.png differ diff --git a/tsyppo_anton_lab_7/img/eng20.png b/tsyppo_anton_lab_7/img/eng20.png new file mode 100644 index 0000000..4c4bd47 Binary files /dev/null and b/tsyppo_anton_lab_7/img/eng20.png differ diff --git a/tsyppo_anton_lab_7/img/rus100.png b/tsyppo_anton_lab_7/img/rus100.png new file mode 100644 index 0000000..76ec07e Binary files /dev/null and b/tsyppo_anton_lab_7/img/rus100.png differ diff --git a/tsyppo_anton_lab_7/img/rus20.png b/tsyppo_anton_lab_7/img/rus20.png new file mode 100644 index 0000000..5d1f965 Binary files /dev/null and b/tsyppo_anton_lab_7/img/rus20.png differ diff --git a/tsyppo_anton_lab_7/img/translation.png b/tsyppo_anton_lab_7/img/translation.png new file mode 100644 index 0000000..f6bb1a2 Binary files /dev/null and b/tsyppo_anton_lab_7/img/translation.png differ diff --git a/tsyppo_anton_lab_7/img/work100.png b/tsyppo_anton_lab_7/img/work100.png new file mode 100644 index 0000000..7427a51 Binary files /dev/null and b/tsyppo_anton_lab_7/img/work100.png differ diff --git a/tsyppo_anton_lab_7/img/work20.png b/tsyppo_anton_lab_7/img/work20.png new file mode 100644 index 0000000..cb29959 Binary files /dev/null and b/tsyppo_anton_lab_7/img/work20.png differ diff --git a/tsyppo_anton_lab_7/main.py b/tsyppo_anton_lab_7/main.py new file mode 100644 index 0000000..2039e97 --- /dev/null +++ b/tsyppo_anton_lab_7/main.py @@ -0,0 +1,95 @@ +import numpy as np +import tensorflow as tf +from tensorflow.keras.models import Sequential +from tensorflow.keras.layers import Embedding, LSTM, Dense +from tensorflow.keras.preprocessing.text import Tokenizer +from tensorflow.keras.preprocessing.sequence import pad_sequences + +# Загрузка русского текста +with open('text/rus.txt', encoding='utf-8') as file: + text_rus = file.read() + +# Загрузка английского текста +with open('text/eng.txt', encoding='utf-8') as file: + text_eng = file.read() + +# Токенизация русского текста +tokenizer_rus = Tokenizer() +tokenizer_rus.fit_on_texts([text_rus]) +total_words_rus = len(tokenizer_rus.word_index) + 1 + +# Токенизация английского текста +tokenizer_eng = Tokenizer() +tokenizer_eng.fit_on_texts([text_eng]) +total_words_eng = len(tokenizer_eng.word_index) + 1 + +# Создание последовательностей для обучения модели русского текста +input_sequences_rus = [] +for line in text_rus.split('\n'): + token_list = tokenizer_rus.texts_to_sequences([line])[0] + for i in range(1, len(token_list)): + n_gram_sequence = token_list[:i + 1] + input_sequences_rus.append(n_gram_sequence) + +max_sequence_length_rus = max([len(x) for x in input_sequences_rus]) +input_sequences_rus = pad_sequences(input_sequences_rus, maxlen=max_sequence_length_rus, padding='pre') + +predictors_rus, labels_rus = input_sequences_rus[:, :-1], input_sequences_rus[:, -1] + +# Создание последовательностей для обучения модели английского текста +input_sequences_eng = [] +for line in text_eng.split('\n'): + token_list = tokenizer_eng.texts_to_sequences([line])[0] + for i in range(1, len(token_list)): + n_gram_sequence = token_list[:i + 1] + input_sequences_eng.append(n_gram_sequence) + +max_sequence_length_eng = max([len(x) for x in input_sequences_eng]) +input_sequences_eng = pad_sequences(input_sequences_eng, maxlen=max_sequence_length_eng, padding='pre') + +predictors_eng, labels_eng = input_sequences_eng[:, :-1], input_sequences_eng[:, -1] + +# Создание и компиляция модели для русского текста +model_rus = Sequential([ + Embedding(total_words_rus, 100, input_length=max_sequence_length_rus - 1), + LSTM(150), + Dense(total_words_rus, activation='softmax') +]) + +model_rus.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy']) + +# Тренировка модели русского текста +model_rus.fit(predictors_rus, labels_rus, epochs=100, verbose=1) + +# Создание и компиляция модели для английского текста +model_eng = Sequential([ + Embedding(total_words_eng, 100, input_length=max_sequence_length_eng - 1), + LSTM(150), + Dense(total_words_eng, activation='softmax') +]) + +model_eng.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy']) + +# Тренировка модели английского текста +model_eng.fit(predictors_eng, labels_eng, epochs=100, verbose=1) + +# Генерация текста на основе русского текста +def generate_text(seed_text, next_words, model, max_sequence_length, tokenizer): + for _ in range(next_words): + token_list = tokenizer.texts_to_sequences([seed_text])[0] + token_list = pad_sequences([token_list], maxlen=max_sequence_length - 1, padding='pre') + predicted_probs = model.predict(token_list)[0] + predicted_word_index = np.random.choice(len(predicted_probs), p=predicted_probs) + output_word = tokenizer.index_word.get(predicted_word_index, '') + seed_text += " " + output_word + return seed_text + +# Генерация текста на основе русского текста +generated_text_rus = generate_text("Начало", 50, model_rus, max_sequence_length_rus, tokenizer_rus) +print("Generated Russian Text:") +print(generated_text_rus) + +# Генерация текста на основе английского текста +generated_text_eng = generate_text("Start", 50, model_eng, max_sequence_length_eng, tokenizer_eng) +print("\nGenerated English Text:") +print(generated_text_eng) \ No newline at end of file diff --git a/tsyppo_anton_lab_7/text/eng.txt b/tsyppo_anton_lab_7/text/eng.txt new file mode 100644 index 0000000..7224ccc --- /dev/null +++ b/tsyppo_anton_lab_7/text/eng.txt @@ -0,0 +1,103 @@ +For several years Mr Williams worked for the museum at the University of Oxford, enlarging its already famous collection of drawings and pictures of English country houses and churches. It is hard to imagine anything less alarming than collecting pictures of houses and churches, but Mr Williams found that even this peaceful work had its unexpected dark corners. +He bought many pictures for the museum from the London shop of Mr J. W. Britnell. Twice a year Mr Britnell sent a list of pictures to all his regular customers, who could then choose which pictures they wanted to look at before deciding whether to buy. +In February 1895 Mr Williams received a list from Mr Britnell with the following letter: + +Dear Sir, +I think you might be interested in Picture Number 978 in our list, which I will be happy to send to you if you wish. +J. W. Britnell + +Mr Williams turned to Number 978 in the list and found the following note: + +Number 978. Artist unknown. Picture of an English country house, early nineteenth century. 25 centimetres by 40 centimetres. £20. + +It did not sound very interesting and the price seemed high. However, Mr Williams added it to the pictures that he asked Mr Britnell to send to him. +The pictures arrived at the museum one Saturday afternoon, just after Mr Williams had left. They were brought round to his rooms in college so that he could look at them over the weekend. Mr Williams found them on his table when he and his friend, Mr Binks, came in to have tea. + +Picture Number 978 showed the front of quite a large country house. It had three rows of windows with the door in the middle of the bottom row. There were trees on both sides of the house and a large lawn in front of it. The letters A. W. F. were written in the corner of the picture. Mr Williams thought that it was not very well done, probably the work of an amateur artist, and he could not understand why Mr Britnell thought it was worth twenty pounds. He turned it over and saw that there was a piece of paper on the back with part of a name on it. All he could read were the ends of two lines of Writing The first said, ‘—ngly Hall’; the second, ‘—ssex’. + +Mr Williams thought that it would be interesting to see if he could find the name of the house in one of his guidebooks before sending the picture back on Monday morning. Meanwhile, he put the picture on the table, lit the lamp because it was now getting dark, and made the tea. + +While they were having tea, his friend picked up the picture, looked at it and said, ‘Where’s this house, Williams?’ +‘That’s just what I was going to find out, ‘ said Williams, taking a book from the shelf. ‘If you look at the back, you’ll see it’s Something Hall in either Essex or Sussex. Half the name’s missing, you see. I don’t suppose you recognize the house, do you? ‘ +‘No, I don’t, ‘ said Mr Binks. ‘It’s from Britnell, ‘I suppose, isn’t it? Is it for the museum?’ +‘Well, I would buy it if the price was two pounds, ‘replied Mr Williams, ‘but for some reason he wants twenty pounds for it. I can’t think why. It’s not a very good picture and there aren’t even any figures in it to make it more interesting.’ +‘I agree it’s not worth twenty pounds,’ said Binks, ‘but I don’t think it’s too bad. The light seems rather good to me and I think there is a figure here, just at the edge, in the front.’ +‘Let me see,’ said Williams. ‘Well, it’s true the light is quite well done. Where’s the figure? Oh, yes! Just the head, in the very front of the picture.’ +And indeed there was — right on the edge of the picture — just the head of a man or a woman, who was looking towards the house. Williams had not noticed it before. +‘Still,’ he said, ‘though it’s better than I thought at first, I can’t spend twenty pounds of the museum’s money on a picture of a house I don’t even know.’ + +Mr Binks, who had some work to finish, soon left and Mr Williams spent the time before dinner trying to find the name of the house in his guidebooks. +‘If I knew the letter before the “—ngly”,’ he said to himself, ‘it would be easy enough. But there are many more names ending in “—ngly” than I thought.’ + +Dinner in Mr Williams’ college was at seven o’clock and afterwards a few of his friends came back to his rooms to play cards. During a pause in the game Mr Williams picked up the picture from the table without looking at it and passed it to a man named Garwood, who was interested in pictures. Garwood looked at it and said: +‘This is really a very fine picture, you know, Williams. The light is very well done, in my opinion, and though the figure is rather unpleasant, it is quite interesting.’ +‘Yes, isn’t it? ‘said Williams, who was too busy giving drinks to his guests to look at the picture again. + +When his visitors had gone, Williams had to finish writing a letter, so it was after midnight before he was ready to go to bed. The picture lay face upwards on the table where Garwood had left it and, as Williams was putting out the lamp, he saw it. For a moment he was too surprised to move, then he slowly picked up the picture and stared at it in horror. In the middle of the lawn, in front of the unknown house, there was a figure where there had been no figure earlier. It was crawling on hands and knees towards the house, and it was covered in a strange black garment with a white cross on the back. + +After a second or two Mr Williams took the picture by one corner and carried it to an empty room. There, he locked it, face downwards, in a cupboard, then closed and locked the door of the empty room. He went back to his own room and locked the door behind him. Before going to bed, he sat down and wrote a note describing in detail the extraordinary change in the picture since he had received it. + +He was glad to remember that Mr Garwood, who had looked at the picture earlier in the evening, had also seen a ‘rather unpleasant’ figure. He decided that in the morning he must ask someone to look carefully at the picture with him, and he must try very hard to discover the name of the house. He would ask his neighbour, Mr Nisbet, to have breakfast with him. Then he would spend the morning looking for the house in his guidebooks. + +Mr Nisbet arrived at nine o’clock and the two men sat down to breakfast. When they had finished, Mr Williams, feeling both nervous and excited, hurried to the empty room. He unlocked the cupboard, took out the picture, still face downwards, and, without looking at it, went back to his own room and put it into Nisbet’s hands. + +‘Now, Nisbet,’ he said, ‘I want you to tell me what you see in that picture. Describe it, please, in detail. I’ll tell you why afterwards.’ +‘Well,’ said Nisbet, ‘I have here a picture of an English country house by moonlight.’ +‘Moonligh? Are you sure?’ +‘Oh, yes. The moon is shown quite clearly and there are clouds in the sky.’ +‘All right. Go on. But I’m sure,’ added Williams quietly, ‘that there was no moon when I first saw it.’ +‘Well, there’s not much more I can say,’ Nisbet continued. ‘The house has three rows of windows, five in each row, except at the bottom, where there’s a door instead of the middle one and…’ +‘But what about figures? ‘said Williams with great interest. +‘Figures?’ replied Nisbet. ‘There aren’t any.’ +‘What? No figure on the grass in front?’ +‘No. Not a thing.’ +‘Are you sure?’ +‘Of course I am. But there’s one other thing.’ +‘What’s that?’ +‘One of me windows on the ground floor, on the left of the door, is open.’ +‘Is it really? Oh dear! I suppose he’s got into the house,’ said Williams, with great excitement. + +He hurried across to where Nisbet was sitting and, taking the picture from him, saw for himself. It was quite true. There was no figure on the lawn, and there was the open window. +For a moment williams was too surprised to speak, then he sat down at his desk and wrote for a few minutes. When he had finished, he brought two papers across to Nisbet. He asked him to sign the first one, which was Nisbet’s own description of the picture, then to read the other one, which was the note Williams had written the night before. + +‘What can it all mean? ‘asked Nisbet. +‘That’s what I must find out,’ said Williams. ‘Now, there are three things I must do. First, I must ask Garwood exactly what he saw when he looked at the picture last night, then I must have the picture photographed before it goes any further and, thirdly, I must find out where this house is.’ +‘I can take the photograph for you myself,’ said Nisbet. ‘But, you know, I think we are seeing something terrible happening here. The question is, has it already happened or is it going to happen? You really must find out where this house is. ‘He looked at the picture again and shook his head. ‘I think you are right, you know. He has got in. I’m sure there will be some trouble in that house.’ + +‘I’ll tell you what I’ll do,’ said Williams. ‘I’ll show the picture to old Doctor Green. He grew up in Essex and he often goes to Sussex to see his brother who lives there. He’s been going there for years. He must know both places quite well.’ +‘That’s a very good idea,’ agreed Nisbet. ‘But I think I heard Green say that he was going away this weekend.’ +‘You’re right, said Williams. ‘I remember now — he’s gone to Brighton for the weekend. I’ll leave a note asking him to see me as soon as he returns. Meanwhile, you take the picture and photograph it and I’ll see Garwood and ask him what he saw when he looked at it last night.’ He paused. ‘You know,’ he added, ‘I don’t think twenty pounds is too much to ask for this picture, after all.’ + +In a short time Williams returned to his room, bringing Mr Garwood with him. Mr Garwood said that when he had looked at the picture the figure was just starting to crawl across the lawn. He remembered that it was wearing a black garment with something white on the back — he was not sure if it was a cross. While he was writing this down, Mr Nisbet returned and said that he had photographed the picture. + +‘What are you going to do now, Williams?’ asked Mr Garwood. ‘Are you going to sit and watch the picture all day?’ +‘No, I don’t think we need to do that,’ replied Williams. +‘You see, there has been plenty of time since I looked at it last night for the creature in the picture to finish what he wants to do, but he has only gone into the house. The window is open and he must still be in there. I think he wants us to see what happens next. Anyway, I don’t think the picture will change much during the day. I suggest that we all go for a walk after lunch and come back here for tea. I’ll leave the picture on my table and lock the door. My servant has a key and can get in if he wants to, but nobody else can.’ + +The others agreed that this was a good plan. They also wanted to avoid talking to anyone about this extraordinary picture, knowing what excitement and argument it would cause. +At about five o’clock they came back to Mr Williams’ rooms for tea. When they entered the room, they were surprised to find Mr Filcher, the servant, sitting in Mr Williams’ armchair and staring in horror at the picture on the table. Mr Filcher had worked in the college for many years and had never before behaved in so unusual a way. He seemed to feel this himself, and tried to jump to his feet when the three men came in. + +‘I’m sorry, sir,’ he said. ‘I didn’t mean to sit down.’ +‘That’s all right, Robert,’ said Mr Williams. ‘I was going to ask you some time what you thought of that picture.’ +‘Well, sir,’ replied the servant, ‘of course, I don’t really understand pictures, but I wouldn’t like my little girl to see it. I’m sure it would give her bad dreams. It doesn’t seem the right kind of picture to leave lying around. It could frighten anybody — seeing that awful thing carrying off the poor baby. That’s what I think, sir. Will you need me any more today, sir? Thank you, sir.’ + +Filcher left the room and the three men went at once to look at the picture. There was the house as before, under the moon and the clouds. But the window that had been open was now shut, and the figure was once more on the lawn; but not crawling this time. Now it was walking, with long steps, towards the front of the picture. The moon was behind it and the black material of its garment nearly covered its face. The three men were deeply thankful that they could see no more of the face than a high, white forehead and a few long, thin hairs. Its legs beneath the garment were horribly thin, and its arms held something which seemed to be a child, whether dead or living it was not possible to say. + +The three friends watched the picture until it was time for dinner but it did not change at all. They hurried back to Williams’ rooms as soon as dinner was finished. The picture was where they had left it, but the figure had gone, and the house was quiet under the moon and the clouds. + +‘Well,’ said Mr Williams, ‘now we really must try to find where this house is.’ They got out the guidebooks and began to work. + +It was nearly two hours later when Williams suddenly cried, ‘Ha! This looks like it.’ +He read aloud from the Cuide to Essex that he was holding: + +‘Anningly. Interesting twelfth-century church containing the tombs of the Francis family, whose home, Anningly Hall, stands just behind the church. The family is now extinct. The last member of the family disappeared very mysteriously in 1802 while still a child. His father, Sir Arthur Francis, a well-known amateur artist, lived quite alone after that until he was found dead in his house three years later, after he had just completed a picture of the Hall.’ + +As Mr Williams finished reading, there was a knock on the door and Doctor Green came in. He had just returned from Brighton and had found Williams’ note. He agreed at once that the picture was of Anningly Hall, which was not far from where he had grown up. + +‘Have you any explanation of the figure, Green?’ asked Williams. +‘I don’t know, I’m sure, Williams,’ Doctor Green replied. +‘When I was a boy, some of the old people in Anningly still used to talk about the disappearance of the Francis child. They said that Sir Arthur had a lot of trouble with some of the local people coming onto his land to steal his fish and his birds. He decided to catch them all and have them punished, and, one by one he did, until there was only one left. This was a man called Gawdy whose family had once been rich and important in that part of Essex. In fact, some of them had their tombs in the village church too. However, the family had lost all their land and their money over the years and Gawdy felt rather bitter about it all. + +For a long time Sir Arthur could not catch him doing anything wrong until one night his men found Gawdy with some dead birds in Sir Arthur’s woods. There was a fight and one of the men was shot. This was just what Sir Arthur needed; the judge was all on his side, of course, and poor Gawdy was hanged a few days later. People thought that some friend of Gawdy’s stole Sir Arthur’s little boy in revenge, to put an end to the Francis family as well. But I should say now, that it looks more as if old Gawdy managed the job himself. Brrrr. I don’t like to think about it. Let’s have a drink, shall we?’ + +The story of the picture was told to a few people; some believed it and some did not. Mr Britnell knew nothing about it except that the picture was unusual in some way. It is now in the museum and, although it has been carefully watched, no one has ever seen it change again. \ No newline at end of file diff --git a/tsyppo_anton_lab_7/text/rus.txt b/tsyppo_anton_lab_7/text/rus.txt new file mode 100644 index 0000000..4a027f0 --- /dev/null +++ b/tsyppo_anton_lab_7/text/rus.txt @@ -0,0 +1,217 @@ +Знаешь ли ты, сколько месяцев в году? + +— Двенадцать. + +А как их зовут? + +— Январь, февраль, март, апрель, май, июнь, июль, август, сентябрь, октябрь, ноябрь, декабрь. + +Только окончится один месяц, сразу же начинается другой. И ни разу еще не бывало так, чтобы февраль пришел раньше, чем уйдет январь, а май обогнал бы апрель. Месяцы идут один за другим и никогда не встречаются. + +Но люди рассказывают, будто в горной стране Богемии была девочка, которая видела все двенадцать месяцев сразу. Как же это случилось? А вот как. + +В одной маленькой деревушке жила злая и скупая женщина с дочкой и падчерицей. Дочку она любила, а падчерица ничем ей не могла угодить. + +Что ни сделает падчерица — все не так, как ни повернется — все не в ту сторону. Дочка по целым дням на перине валялась, да пряники ела, а падчерице с утра до ночи и присесть некогда было: то воды натаскай, то хворосту из лесу привези, то белье на речке выполощи, то грядки в огороде выполи. Знала она и зимний холод, и летний зной, и весенний ветер, и осенний дождь. Потому-то, может, и довелось ей однажды увидеть все двенадцать месяцев разом. + +Была зима. Шел январь месяц. Снегу намело столько, что от дверей его приходилось отгребать лопатами, а в лесу на горе деревья стояли по пояс в сугробах и даже качаться не могли, когда на них налетал ветер. Люди сидели в домах и топили печки. В такую-то пору, под вечер, злая мачеха приоткрыла дверь, поглядела, как метет вьюга, а потом вернулась к теплой печке и сказала падчерице: + +— Сходила бы ты в лес да набрала там подснежников. Завтра сестрица твоя именинница. + +Посмотрела на мачеху девочка: шутит она или вправду посылает ее в лес? Страшно теперь в лесу! Да и какие среди зимы подснежники? Раньше марта месяца они и не появятся на свет, сколько их ни ищи. Только пропадешь в лесу, увязнешь в сугробах. + +А сестра говорит ей: + +— Если и пропадешь, так плакать о тебе никто не станет. Ступай да без цветов не возвращайся. Вот тебе корзинка. + +Заплакала девочка, закуталась в рваный платок и вышла из дверей. + +Ветер снегом ей глаза порошит, платок с нее рвет. Идет она, еле ноги из сугробов вытягивает. + +Все темнее становится кругом. Небо черное, ни одной звездочкой на землю не глядит, а земля чуть посветлее. Это от снега. + +Вот и лес. Тут уж совсем темно — рук своих не разглядишь. Села девочка на поваленное дерево и сидит. Все равно, думает, где замерзать. + +И вдруг далеко меж деревьев сверкнул огонек — будто звезда среди ветвей запуталась. Поднялась девочка и пошла на этот огонек. Тонет в сугробах, через бурелом перелезает. «Только бы, — думает, — огонек не погас!» А он не гаснет, он все ярче горит. Уж и теплым дымком запахло и слышно стало, как потрескивает в огне хворост. Девочка прибавила шагу и вышла на полянку. Да так и замерла. + +Светло на полянке, точно от солнца. Посреди полянки большой костер горит, чуть ли не до самого неба достает. А вокруг костра сидят люди — кто поближе к огню, кто подальше. Сидят и тихо беседуют. Смотрит на них девочка и думает: кто же они такие? На охотников будто не похожи, на дровосеков еще того меньше: вон они какие нарядные — кто в серебре, кто в золоте, кто в зеленом бархате. Стала она считать, насчитала двенадцать: трое старых, трое пожилых, трое молодых, а последние трое — совсем еще мальчики. + +Молодые у самого огня сидят, а старики — поодаль. + +И вдруг обернулся один старик — самый высокий, бородатый, бровастый — и поглядел в ту сторону, где стояла девочка. Испугалась она, хотела убежать, да поздно. Спрашивает ее старик громко: + +— Ты откуда пришла, чего тебе здесь нужно? + +Девочка показала ему свою пустую корзинку и говорит: + +— Да, нужно мне набрать в эту корзинку подснежников. + +Засмеялся старик: + +— Это в январе-то подснежников? Вон чего выдумала! + +— Не я выдумала, — отвечает девочка, — а прислала меня сюда за подснежниками моя мачеха и не велела мне с пустой корзинкой домой возвращаться. Тут все двенадцать поглядели на нее и стали между собой переговариваться. + +Стоит девочка, слушает, а слов не понимает — будто это не люди разговаривают, а деревья шумят. + +Поговорили они, поговорили и замолчали. + +А высокий старик опять обернулся и спрашивает: + +— Что же ты делать будешь, если не найдешь подснежников? Ведь раньше марта месяца они и не выглянут. + +— В лесу останусь, — говорит девочка. — Буду марта месяца ждать. Уж лучше мне в лесу замерзнуть, чем домой без подснежников вернуться. + +Сказала это и заплакала. И вдруг один из двенадцати, самый молодой, веселый, в шубке на одном плече, встал и подошел к старику: + +— Братец Январь, уступи мне на час свое место! + +Погладил свою длинную бороду старик и говорит: + +— Я бы уступил, да не бывать Марту прежде Февраля. + +— Ладно, уж, — проворчал другой старик, весь лохматый, с растрепанной бородой. — Уступи, я спорить не стану! Мы все хорошо ее знаем: то у проруби ее встретишь с ведрами, то в лесу с вязанкой дров. Всем месяцам она своя. Надо ей помочь. + +— Ну, будь, по-вашему, — сказал Январь. + +Он стукнул о землю своим ледяным посохом и заговорил: + +Не трещите, морозы, + +В заповедном бору, + +У сосны, у березы + +Не грызите кору! + +Полно вам воронье + +Замораживать, + +Человечье жилье + +Выхолаживать! + +Замолчал старик, и тихо стало в лесу. Перестали потрескивать от мороза деревья, а снег начал падать густо, большими, мягкими хлопьями. + +— Ну, теперь твой черед, братец, — сказал Январь и отдал посох меньшому брату, лохматому Февралю. + +Тот стукнул посохом, мотнул бородой и загудел: + +Ветры, бури, ураганы, + +Дуйте что есть мочи! + +Вихри, вьюги и бураны, + +Разыграйтесь к ночи! + +В облаках трубите громко, + +Вейтесь над землею. + +Пусть бежит в полях поземка + +Белою змеею! + +Только он это сказал, как зашумел в ветвях бурный, мокрый ветер. Закружились снежные хлопья, понеслись по земле белые вихри. + +А Февраль отдал свой ледяной посох младшему брату и сказал: + +— Теперь твой черед, братец Март. + +Взял младший брат посох и ударил о землю. Смотрит девочка, а это уже не посох. Это большая ветка, вся покрытая почками. Усмехнулся Март и запел звонко, во весь свой мальчишеский голос: + +Разбегайтесь, ручьи, + +Растекайтесь, лужи, + +Вылезайте, муравьи, + +После зимней стужи! + +Пробирается медведь + +Сквозь лесной валежник. + +Стали птицы песни петь, + +И расцвел подснежник. + +Девочка даже руками всплеснула. Куда девались высокие сугробы? Где ледяные сосульки, что висели на каждой ветке! Под ногами у нее — мягкая весенняя земля. Кругом каплет, течет, журчит. Почки на ветвях надулись, и уже выглядывают из-под темной кожуры первые зеленые листики. Глядит девочка — наглядеться не может. + +— Что же ты стоишь? — говорит ей Март. — Торопись, нам с тобой всего один часок братья мои подарили. + +Девочка очнулась и побежала в чащу подснежники искать. А их видимо-невидимо! Под кустами и под камнями, на кочках и под кочками — куда ни поглядишь. Набрала она полную корзину, полный передник — и скорее опять на полянку, где костер горел, где двенадцать братьев сидели. А там уже ни костра, ни братьев нет… Светло на поляне, да не по-прежнему. Не от огня свет, а от полного месяца, что взошел над лесом. + +Пожалела девочка, что поблагодарить ей некого, и побеждала домой. А месяц за нею поплыл. + +Не чуя под собой ног, добежала она до своих дверей — и только вошла в дом, как за окошками опять загудела зимняя вьюга, а месяц спрятался в тучи. + +— Ну, что, — спросили ее мачеха и сестра, — уже домой вернулась? А подснежники где? + +Ничего не ответила девочка, только высыпала из передника на лавку подснежники и поставила рядом корзинку. + +Мачеха и сестра так и ахнули: + +— Да где же ты их взяла? + +Рассказала им девочка все, как было. Слушают они обе и головами качают — верят и не верят. Трудно поверить, да ведь вот на лавке целый ворох подснежников, свежих, голубеньких. Так и веет от них мартом месяцем! + +Переглянулись мачеха с дочкой и спрашивают: + +— А больше тебе ничего месяцы не дали? — Да я больше ничего и не просила. + +— Вот дура, так, дура! — говорит сестра. — В кои-то веки со всеми двенадцатью месяцами встретилась, а ничего, кроме подснежников, не выпросила! Ну, будь я на твоем месте, я бы знала, чего просить. У одного — яблок да груш сладких, у другого — земляники спелой, у третьего — грибов беленьких, у четвертого — свежих огурчиков! + +— Умница, доченька! — говорит мачеха. — Зимой землянике да грушам цены нет. Продали бы мы это и сколько бы денег выручили! А эта дурочка подснежников натаскала! Одевайся, дочка, потеплее, да сходи на полянку. Уж тебя они не проведут, хоть их двенадцать, а ты одна. + +— Где им! — отвечает дочка, а сама — руки в рукава, платок на голову. + +Мать ей вслед кричит: + +— Рукавички надень, шубку застегни! + +А дочка уже за дверью. Убежала в лес! + +Идет по сестриным следам, торопится. Скорее бы, — думает, — до полянки добраться! + +Лес все гуще, все темней. Сугробы все выше, бурелом стеной стоит. + +Ох, — думает мачехина дочка, — и зачем только я в лес пошла! Лежала бы сейчас дома в теплой постели, а теперь ходи да мерзни! Еще пропадешь тут! + +И только она это подумала, как увидела вдалеке огонек — точно звездочка в ветвях запуталась. Пошла она на огонек. Шла, шла и вышла на полянку. Посреди полянки большой костер горит, а вокруг костра сидят двенадцать братьев, двенадцать месяцев. Сидят и тихо беседуют. Подошла мачехина дочка к самому костру, не поклонилась, приветливого слова не сказала, а выбрала место, где пожарче, и стала греться. Замолчали братья-месяцы. Тихо стало в лесу. И вдруг стукнул Январь-месяц посохом о землю. + +— Ты кто такая? — спрашивает. — Откуда взялась? + +— Из дому, — отвечает мачехина дочка. — Вы нынче моей сестре целую корзинку подснежников дали. Вот я и пришла по ее следам. + +— Сестру твою мы знаем, — говорит Январь-месяц, — а тебя и в глаза не видали. Ты зачем к нам пожаловала? + +— За подарками. Пусть Июнь-месяц мне земляники в корзинку насыплет, да покрупней. А Июль-месяц — огурцов свежих и грибов белых, а месяц Август — яблок да груш сладких. А Сентябрь-месяц — орехов спелых. А Октябрь… + +— Погоди, — говорит Январь-месяц. — Не бывать лету перед весной, а весне перед зимой. Далеко еще до июня-месяца. Я теперь лесу хозяин, тридцать один день здесь царствовать буду. + +— Ишь, какой сердитый! — говорит мачехина дочка. — Да я не к тебе и пришла — от тебя, кроме снега да инея, ничего не дождешься. Мне летних месяцев надо. + +Нахмурился Январь-месяц. + +— Ищи лета зимой! — говорит. + +Махнул он широким рукавом, и поднялась в лесу метель от земли до неба заволокла и деревья и полянку, на которой братья-месяцы сидели. Не видно стало за снегом и костра, а только слышно было, как свистит где-то огонь, потрескивает, полыхает. + +Испугалась мачехина дочка. — Перестань! — кричит. — Хватит! + +Да где там! + +Кружит ее метель, глаза ей слепит, дух перехватывает. Свалилась она в сугроб, и замело ее снегом. + +А мачеха ждала-ждала свою дочку, в окошко смотрела, за дверь выбегала — нет ее, да и только. Закуталась она потеплее и пошла в лес. Да разве найдешь кого-нибудь в чаще в такую метель и темень! + +Ходила она, ходила, искала-искала, пока и сама не замерзла. Так и остались они обе в лесу лета ждать. А падчерица долго на свете жила, большая выросла, замуж вышла и детей вырастила. + +И был у нее, рассказывают, около дома сад — да такой чудесный, какого и свет не видывал. Раньше, чем у всех, расцветали в этом саду цветы, поспевали ягоды, наливались яблоки и груши. В жару было там прохладно, в метель тихо. + +— У этой хозяйки все двенадцать месяцев разом гостят! — говорили люди. + +Кто знает — может, так оно и было. \ No newline at end of file