{"id":24627874,"url":"https://github.com/stanleystanmarsh/phrases-generator","last_synced_at":"2025-07-23T16:34:49.394Z","repository":{"id":267691659,"uuid":"900953894","full_name":"StanleyStanMarsh/phrases-generator","owner":"StanleyStanMarsh","description":"The program for text parsing and text continuation generation based on N-grams.","archived":false,"fork":false,"pushed_at":"2025-01-24T01:23:05.000Z","size":82,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-20T02:33:44.777Z","etag":null,"topics":["haskell","n-grams","parser"],"latest_commit_sha":null,"homepage":"","language":"Haskell","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/StanleyStanMarsh.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-12-09T19:18:29.000Z","updated_at":"2025-01-24T01:23:09.000Z","dependencies_parsed_at":null,"dependency_job_id":"662e3185-5f1d-493f-8bb6-5ba2851418ff","html_url":"https://github.com/StanleyStanMarsh/phrases-generator","commit_stats":null,"previous_names":["stanleystanmarsh/phrases-generator"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/StanleyStanMarsh/phrases-generator","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/StanleyStanMarsh%2Fphrases-generator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/StanleyStanMarsh%2Fphrases-generator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/StanleyStanMarsh%2Fphrases-generator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/StanleyStanMarsh%2Fphrases-generator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/StanleyStanMarsh","download_url":"https://codeload.github.com/StanleyStanMarsh/phrases-generator/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/StanleyStanMarsh%2Fphrases-generator/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":266714491,"owners_count":23973130,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-07-23T02:00:09.312Z","response_time":66,"last_error":null,"robots_txt_status":null,"robots_txt_updated_at":null,"robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["haskell","n-grams","parser"],"created_at":"2025-01-25T05:13:32.205Z","updated_at":"2025-07-23T16:34:49.349Z","avatar_url":"https://github.com/StanleyStanMarsh.png","language":"Haskell","funding_links":[],"categories":[],"sub_categories":[],"readme":"# EN - Phrase and Dialogue Generator\n\nA program for parsing text and generating text continuation based on N-grams.\n\n## Description\n\n### Finite State Automaton for Sentence Parsing\n\n![State Diagram of the Finite Automaton](automata_sentences_parser.png)\n\nM = (Q, Σ, δ, q₀, F), where:\n\n- Q = {S₀, S₁, S₂, S₃, S₄, S₅} - set of states\n- Σ = {L, P, W, EOF} - input alphabet, where:\n  * L - letters and apostrophes (isLetter c || c == '\\'')\n  * P - punctuation marks (. ! ? ; : ( ))\n  * W - whitespace and other characters\n  * EOF - end of input\n- q₀ = S₀ - initial state\n- F = {S₄, S₅} - set of final states\n- δ: Q × Σ → Q - transition functions:\n\n|   State   | L | P | W | EOF |\n|-----------|---|---|---|-----|\n| S₀        | S₁| Sₑ| S₀| S₅ |\n| S₁        | S₁| S₃| S₂| S₅ |\n| S₂        | S₁| S₃| S₂| S₅ |\n| S₃        | S₁| S₃| S₀| S₄ |\n| S₄        | S₄| S₄| S₄| S₄ |\n| S₅        | S₅| S₅| S₅| S₅ |\n\nWhere:\n- S₀: Initial state\n- S₁: Reading a word\n- S₂: Skipping whitespace/garbage\n- S₃: Reading punctuation marks\n- S₄: Final state (success)\n- Sₑ: Error state\n\n### Mathematical Model for Text Generation\n\n#### N-grams and Markov Chains\n\n![Bigram and Trigram Model](markov_chain.png)\n\nText generation is based on a combined bigram and trigram model using Markov chains:\n\n1. **Bigram Model** (top part of the diagram):\n   - States: individual words \\( wᵢ \\)\n   - Transitions: \\( P(wᵢ|wᵢ₋₁) \\) - the probability \\( p \\) of transitioning from word \\( wᵢ₋₁ \\) to word \\( wᵢ \\)\n   - Each subsequent word depends only on the previous one.\n\n2. **Combined Bigram-Trigram Model** (middle part of the diagram):\n   - States:\n     * Individual words \\( wᵢ₋₁ \\)\n     * Pairs of words \\( (wᵢ, wᵢ₊₁) \\)\n   - Transitions:\n     * From a single word to a pair of words with probability \\( p \\)\n   - Captures longer dependencies.\n\n3. **Trigram Model** (bottom part of the diagram):\n   - States:\n     * Pairs of words \\( (wᵢ₋₂, wᵢ₋₁) \\)\n     * Individual words \\( wᵢ \\)\n   - Transitions: \\( P(wᵢ|wᵢ₋₂, wᵢ₋₁) \\) - the probability \\( p \\) of transitioning from a pair of words to the next word.\n   - Each subsequent word depends on the two previous ones.\n\nIn this implementation, the transition probability \\( p \\) for a specific word among the possible continuations is uniform random — each continuation is selected with equal probability using a random number generator.\n\n### Overview of the Program\n\nThe program performs the following tasks:\n\n1. **Text Parsing**:\n   - Reads text from a file.\n   - Splits text into sentences (based on .!?;:).\n   - Processes words, preserving apostrophes (e.g., \"don't\" as a single word).\n   - Removes punctuation and digits.\n\n2. **N-gram Model Creation**:\n   - Builds bigrams (pairs of words).\n   - Builds trigrams (triplets of words).\n   - Creates a dictionary where keys are:\n     * Single words.\n     * Word pairs.\n   - Values in the dictionary are lists of possible continuations.\n\n3. **Phrase Generation**:\n   - The user inputs a starting word.\n   - The program generates a phrase of random length (from 2 to 15 words).\n   - If the word is not found in the dictionary, an error message is displayed.\n\n4. **Model Dialogue**:\n   - Uses two different texts to create two models.\n   - Generates a dialogue of specified depth \\( M \\).\n   - Responses are based on the last word of the opponent’s phrase.\n   - If the word is missing in the dictionary, the program falls back to the penultimate word, and so on.\n\n## Usage\n\n1. Prepare two text files:\n   - `input.txt` - text for the first model.\n   - `input2.txt` - text for the second model.\n\n2. Run the program:\n   ```bash\n   stack build\n   stack exec phrases-generator-exe\n   ```\n\n3. Follow the instructions:\n   - Input the starting word for the dialogue.\n   - Specify the desired number of exchanges.\n\n## Technical Details\n\n- Language: Haskell\n- Libraries:\n  * text - for text processing.\n  * random - for random number generation.\n- Parsing is implemented using parser combinators.\n\n## Project Structure\n\n- `src/Lib.hs` - core logic of the program.\n- `app/Main.hs` - entry point and user interaction.\n\n## License\n\n[![License](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)](https://opensource.org/licenses/BSD-3-Clause)\n\nThis project is licensed under the BSD 3-Clause License. Details can be found in the [LICENSE](LICENSE) file.\n\n## Additional Information\n\nProject uses:\n- GHC (Glasgow Haskell Compiler)\n- Stack (tool for Haskell project development)\n- Cabal (building system)\nДля сообщений об ошибках и предложений используйте раздел Issues на GitHub.\n\n# RU - Генератор фраз и диалогов\n\nПрограмма для синтаксического анализа текста и генерации продолжения текста на основе N-грамм.\n\n## Описание\n\n### Конечный автомат для разбора предложений\n\n![Диаграмма состояний конечного автомата](automata_sentences_parser.png)\n\nФормальное определение автомата M = (Q, Σ, δ, q₀, F), где:\n\n- Q = {S₀, S₁, S₂, S₃, S₄, S₅} - множество состояний\n- Σ = {L, P, W, EOF} - входной алфавит, где:\n  * L - буквы и апостроф (isLetter c || c == '\\'')\n  * P - знаки пунктуации (. ! ? ; : ( ))\n  * W - пробельные и прочие символы\n  * EOF - конец входной строки\n- q₀ = S₀ - начальное состояние\n- F = {S₄, S₅} - множество конечных состояний\n- δ: Q × Σ → Q - функция переходов:\n\n| Состояние | L | P | W | EOF |\n|-----------|---|---|---|-----|\n| S₀        | S₁| Sₑ| S₀| S₅ |\n| S₁        | S₁| S₃| S₂| S₅ |\n| S₂        | S₁| S₃| S₂| S₅ |\n| S₃        | S₁| S₃| S₀| S₄ |\n| S₄        | S₄| S₄| S₄| S₄ |\n| S₅        | S₅| S₅| S₅| S₅ |\n\nГде:\n- S₀: Начальное состояние\n- S₁: Чтение слова\n- S₂: Пропуск пробелов/мусора\n- S₃: Чтение знаков пунктуации\n- S₄: Конечное состояние (успех)\n- Sₑ: Состояние ошибки\n\n### Математическая модель генерации текста\n\n#### N-граммы и цепи Маркова\n\n![Модель биграмм и триграмм](markov_chain.png)\n\nГенерация текста основана на комбинированной модели биграмм и триграмм с использованием марковских цепей:\n\n1. Биграммная модель (верхняя часть диаграммы):\n- Состояния: отдельные слова wᵢ\n- Переходы: P(wᵢ|wᵢ₋₁) - вероятность p перехода от слова wᵢ₋₁ к слову wᵢ\n- Каждое следующее слово зависит только от предыдущего\n\n2. Комбинированная биграммно-триграммная модель (средняя часть диаграммы):\n- Состояния: \n  * Одиночные слова wᵢ₋₁\n  * Пары слов (wᵢ, wᵢ₊₁)\n- Переходы: \n  * От одиночного слова к паре слов с вероятностью p\n  * Позволяет учитывать более длинные зависимости\n\n3. Триграммная модель (нижняя часть диаграммы):\n- Состояния: \n  * Пары слов (wᵢ₋₂, wᵢ₋₁)\n  * Одиночные слова wᵢ\n- Переходы: P(wᵢ|wᵢ₋₂,wᵢ₋₁) - вероятность p перехода от пары слов к следующему слову\n- Каждое следующее слово зависит от двух предыдущих\n\nВ данной реализации вероятность p перехода к конкретному слову из множества возможных следующих слов является равномерно случайной - каждое слово из возможных продолжений выбирается с одинаковой вероятностью с помощью генератора случайных чисел.\n\n### Общее описание программы\nПрограмма выполняет следующие задачи:\n\n1. Синтаксический анализ текста:\n   - Чтение текста из файла\n   - Разбиение на предложения (по знакам .!?;:)\n   - Обработка слов с учетом апострофов (например, \"don't\" как одно слово)\n   - Удаление пунктуации и цифр\n\n2. Создание модели N-грамм:\n   - Построение биграмм (пары слов)\n   - Построение триграмм (тройки слов)\n   - Формирование словаря, где ключами являются:\n     * одиночные слова\n     * пары слов\n   - Значениями в словаре являются списки возможных продолжений\n\n3. Генерация фраз:\n   - Пользователь вводит начальное слово\n   - Программа генерирует фразу случайной длины (от 2 до 15 слов)\n   - Если слово отсутствует в словаре, выводится сообщение об ошибке\n\n4. Диалог моделей:\n   - Использование двух разных текстов для создания двух моделей\n   - Генерация диалога заданной глубины M\n   - Ответы основываются на последнем слове из фразы оппонента\n   - При отсутствии слова в словаре используется предпоследнее слово и т.д.\n\n## Использование\n\n1. Подготовьте два текстовых файла:\n   - `input.txt` - текст для первой модели\n   - `input2.txt` - текст для второй модели\n\n2. Запустите программу:\n   ```bash\n   stack build\n   stack exec phrases-generator-exe\n   ```\n\n3. Следуйте инструкциям:\n   - Введите начальное слово для диалога\n   - Укажите желаемое количество обменов репликами\n\n## Технические детали\n\n- Язык программирования: Haskell\n- Используемые библиотеки:\n  * text - для работы с текстом\n  * random - для генерации случайных чисел\n- Парсинг реализован с использованием комбинаторов парсеров\n\n## Структура проекта\n\n- `src/Lib.hs` - основная логика программы\n- `app/Main.hs` - точка входа и взаимодействие с пользователем\n\n## Лицензия\n\n[![License](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)](https://opensource.org/licenses/BSD-3-Clause)\n\nДанный проект распространяется под лицензией BSD 3-Clause. Подробности в файле [LICENSE](LICENSE).\n\n## Дополнительно\n\nПроект создан с использованием:\n- GHC (Glasgow Haskell Compiler)\n- Stack (инструмент для разработки Haskell проектов)\n- Cabal (система сборки)\n\nДля сообщений об ошибках и предложений используйте раздел Issues на GitHub.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstanleystanmarsh%2Fphrases-generator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fstanleystanmarsh%2Fphrases-generator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstanleystanmarsh%2Fphrases-generator/lists"}