diff --git a/MEMORY.md b/MEMORY.md index f0f5846..b7f4169 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -41,6 +41,7 @@ - 2026-08-25: natural bulk parsing prioritizes explicit Russian mentor/student labels, then falls back to the original pair order when labels are absent. - 2026-08-25: `project_mind_map.md` is the current source-controlled project map for Belki and deployment/security boundaries; update it when a data flow, service, or integration changes. - 2026-08-25: password-only admin login has an in-process five-attempt/15-minute per-source limit; it complements but does not replace an edge rate limit. +- 2026-08-25: free-text parsing normalizes common punctuation, spaced IDs, ID markers and close role-label typos. Do not add generic Russian NER solely for CatWar nicknames: ID and role context are the more reliable authority. # 2026-08-16 — несколько котят в прокачке `CoachingSession.extra_kittens` теперь влияет на баллы сопровождающего через количество подопечных: 1-й ×1, 2-й ×1,5, каждый последующий ×1,15 (коэффициенты перемножаются), вместо сложения полной прибыли. Базовый коэффициент самостоятельности основного котёнка сохраняется. Веб-форма отправляет список `extra_kittens`; VK принимает `доп. котята: ...` в pipe-команде. diff --git a/app/belki/vk_bot.py b/app/belki/vk_bot.py index 81a304c..a120483 100644 --- a/app/belki/vk_bot.py +++ b/app/belki/vk_bot.py @@ -7,7 +7,9 @@ import random import re import threading import time +import unicodedata from datetime import datetime +from difflib import SequenceMatcher from typing import Any, Iterator from urllib.parse import urlencode from urllib.request import Request, urlopen @@ -66,6 +68,12 @@ _LABELED_PERSON_RE = re.compile( r"кот[- ]?сопровождающ\w*|ученик\w*|кот[её]нок\w*|бельчонок\w*|подопечн\w*)" r"\s*[:—-]?\s*(?P[А-Яа-яЁёA-Za-z][А-Яа-яЁёA-Za-z _-]*?)\s*\[?(?P\d{3,})\]?" ) +_SPACED_ID_RE = re.compile(r"(? tuple[list[tuple[str, int]], list[tuple[str, i return escorts, kittens, people +def _normalise_natural_text(text: str) -> str: + """Make common free-form date/time/ID variations safe for the parser.""" + text = unicodedata.normalize("NFKC", text).replace("\u00a0", " ") + text = text.replace("—", "-").replace("–", "-").replace("−", "-") + text = re.sub(r"(?i)\b(?:id|айди|№)\s*(?=\d)", "", text) + text = _SPACED_ID_RE.sub(lambda match: match.group(1).replace(" ", ""), text) + text = re.sub(r"\b(\d{1,2})[/-](\d{1,2})\b", r"\1.\2", text) + # A bare ``15.08`` is a date, not 15:08. Preserve the first dotted pair + # as the report date and treat later dotted pairs as clock values. + date_match = re.search(r"\b(?:[12]?\d|3[01])\.(?:0?\d|1[0-2])\b", text) + + def normalise_dotted_time(match: re.Match[str]) -> str: + if date_match is not None and match.start() == date_match.start(): + return match.group(0) + return f"{match.group(1)}:{match.group(2)}" + + text = re.sub(r"\b([01]?\d|2[0-3])\s*\.\s*([0-5]\d)\b", normalise_dotted_time, text) + text = re.sub(r"\b([01]?\d|2[0-3])\s*ч\s*([0-5]\d)\b", r"\1:\2", text) + text = re.sub(r"(? str: + word = match.group(0) + candidate = max(_ROLE_TYPO_WORDS, key=lambda role: SequenceMatcher(None, word.casefold(), role).ratio()) + return candidate if SequenceMatcher(None, word.casefold(), candidate).ratio() >= 0.84 else word + + return re.sub(r"\b[А-Яа-яЁё]{5,}\b", correct_role, text) + + def _extra_kittens(value: str) -> tuple[tuple[str, int, str], ...]: """ Парсит дополнительных котят из строки команды. @@ -276,6 +312,7 @@ def parse_natural_bulk(text: str) -> tuple[dict[str, Any], list[str]] | None: Возвращает (поля, вопросы) или None, если ввод не распознан. """ + text = _normalise_natural_text(text) lowered = text.lower() if re.search(r"\b(урок|тренировк)\w*\b", lowered): people_text = re.sub(r"(?i)^\s*(?:урок|тренировк\w*)\s*", "", text) diff --git a/project_mind_map.md b/project_mind_map.md index 5057dc1..a6eac47 100644 --- a/project_mind_map.md +++ b/project_mind_map.md @@ -41,6 +41,7 @@ mindmap Step dialogs Natural one-line parser Mentor and student labels + Flexible punctuation and ID normalization Attachment mirroring Applications dialog Data diff --git a/structure_and_data.md b/structure_and_data.md index 6f3a13f..5cf19f7 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -68,6 +68,7 @@ - 2026-08-25: `BelkiHTTPServer` supersedes the unbounded standard threaded server. It rejects oversized declared JSON before reading, times out a slow client after 15 seconds, and serves at most 32 concurrent connections. - 2026-08-25: one-line VK/web recognition now gives explicit role labels priority over position. `сопровождающий`/`наставник`/`учитель` identify the escort, while `ученик`/`котёнок`/`бельчонок`/`подопечный` identify the ward; unlabeled pairs retain the original order-based fallback. - 2026-08-25: corrected Russian UX copy in the VK help and attachment flow; the web identity hint now accurately says that a manually completed pair applies only to the current calculation. +- 2026-08-25: natural input normalizes Unicode spaces, dash variants, `ID`/`№` prefixes, spaced IDs, common date/time separators, and close role-label typos before extracting structured fields. Natasha was evaluated for Russian NER through Context7 but not added: game nicknames are better anchored by user-provided IDs and local role context than a generic person model. - 2026-08-25: `/api/admin/auth` now permits five password attempts per source in a rolling 15-minute window and clears that local budget after a successful sign-in. Edge rate limiting and TLS remain required deployment controls. # Обновление 2026-08-16: несколько котят diff --git a/tests/test_vk_conversation.py b/tests/test_vk_conversation.py index 51183ad..a10864e 100644 --- a/tests/test_vk_conversation.py +++ b/tests/test_vk_conversation.py @@ -148,6 +148,15 @@ class VkConversationTests(unittest.TestCase): self.assertEqual(inspected["fields"]["kitten_id"], 1346767) self.assertEqual(inspected["fields"]["kitten_independence"], "несамостоятельно") + def test_natural_bulk_input_normalizes_flexible_punctuation_ids_and_role_typos(self): + inspected = inspect_bulk_text( + "лу; 24-08; 21.00 - 22 ч 00. ученика: Серопопик [1 346 767]; сопроваждающая Дикая Вишня id 1 604 614; несам." + ) + self.assertEqual(inspected["fields"]["date"], "24.08") + self.assertEqual((inspected["fields"]["start"], inspected["fields"]["end"]), ("21:00", "22:00")) + self.assertEqual((inspected["fields"]["escort_name"], inspected["fields"]["escort_id"]), ("Дикая Вишня", 1604614)) + self.assertEqual((inspected["fields"]["kitten_name"], inspected["fields"]["kitten_id"]), ("Серопопик", 1346767)) + def test_training_supports_stepwise_and_natural_bulk(self): dialog = BelkiDialog() self.assertIn("сопровождающ", dialog.handle(102, "/урок").lower())