From 586693dc7299bd680c14012fcf1b5825b015df5e Mon Sep 17 00:00:00 2001 From: Nyan404 Date: Tue, 25 Aug 2026 03:43:10 +0300 Subject: [PATCH] feat(parser): prioritize explicit participant roles --- MEMORY.md | 1 + app/belki/vk_bot.py | 61 ++++++++++++++++++++++++++--------- structure_and_data.md | 1 + tests/test_vk_conversation.py | 10 ++++++ 4 files changed, 58 insertions(+), 15 deletions(-) diff --git a/MEMORY.md b/MEMORY.md index f4ce2bb..3324a45 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -38,6 +38,7 @@ - 2026-08-25: public JSON cannot choose arbitrary attachment URLs. Web attachments are accepted only after the running process issued their image-host URL through `/api/web/upload`. - 2026-08-25: VK attachment mirroring has a strict 15 MiB transfer cap, including a Content-Length precheck and bounded read. - 2026-08-25: the web service uses `BelkiHTTPServer` with 15-second socket reads and a 32-request semaphore in addition to the bounded JSON body reader. +- 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-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 e23ce57..94a6086 100644 --- a/app/belki/vk_bot.py +++ b/app/belki/vk_bot.py @@ -61,6 +61,11 @@ _DATE_RE = re.compile(r"\b(?P\d{1,2}\.\d{1,2})\b") _TIME_RE = re.compile(r"\b(?:[01]?\d|2[0-3]):[0-5]\d\b") # Натуральное имя: "Имя [ID" или "Имя ID" _NATURAL_PERSON_RE = re.compile(r"(?P[А-Яа-яЁёA-Za-z][^\d|,\n]*?)\s*\[?(?P\d{3,})\]?") +_LABELED_PERSON_RE = re.compile( + r"(?i)\b(?Pсопровождающ\w*|наставник\w*|учител\w*|ведущ\w*|" + r"кот[- ]?сопровождающ\w*|ученик\w*|кот[её]нок\w*|бельчонок\w*|подопечн\w*)" + r"\s*[:—-]?\s*(?P[А-Яа-яЁёA-Za-z][А-Яа-яЁёA-Za-z _-]*?)\s*\[?(?P\d{3,})\]?" +) class VkError(RuntimeError): @@ -78,6 +83,31 @@ def _person(value: str) -> tuple[str, int]: return match.group("name").strip(), int(match.group("id")) +def _natural_people(text: str) -> tuple[list[tuple[str, int]], list[tuple[str, int]], list[tuple[str, int]]]: + """Extract labelled roles first, then unlabeled name/ID pairs. + + Natural reports are often prose rather than a fixed sequence. Role labels + win over pair order, so the parser asks for a missing field rather than + silently exchanging a mentor and a student. + """ + escorts: list[tuple[str, int]] = [] + kittens: list[tuple[str, int]] = [] + labeled_spans: list[tuple[int, int]] = [] + for match in _LABELED_PERSON_RE.finditer(text): + person = (match.group("name").strip(" |,–-[]"), int(match.group("id"))) + role = match.group("role").casefold() + (kittens if re.match(r"^(ученик|котенок|котёнок|бельчонок|подопечн)", role) else escorts).append(person) + labeled_spans.append(match.span()) + unlabelled = list(text) + for start, end in labeled_spans: + unlabelled[start:end] = " " * (end - start) + people = [ + (match.group("name").strip(" |,–-[]"), int(match.group("id"))) + for match in _NATURAL_PERSON_RE.finditer("".join(unlabelled)) + ] + return escorts, kittens, people + + def _extra_kittens(value: str) -> tuple[tuple[str, int, str], ...]: """ Парсит дополнительных котят из строки команды. @@ -249,16 +279,16 @@ def parse_natural_bulk(text: str) -> tuple[dict[str, Any], list[str]] | None: lowered = text.lower() if re.search(r"\b(урок|тренировк)\w*\b", lowered): people_text = re.sub(r"(?i)^\s*(?:урок|тренировк\w*)\s*", "", text) - people = [(match.group("name").strip(" |,–-[]"), int(match.group("id"))) - for match in _NATURAL_PERSON_RE.finditer(people_text)] + escorts, kittens, people = _natural_people(people_text) fields: dict[str, Any] = {"mode": "training"} questions: list[str] = [] - if people: - fields["escort_name"], fields["escort_id"] = people[0] + if escorts or people: + fields["escort_name"], fields["escort_id"] = (escorts or people)[0] else: questions.append("Не вижу сопровождающего в формате Имя и ID.") - if len(people) > 1: - fields["kitten_name"], fields["kitten_id"] = people[1] + fallback_kittens = people[1:] if not escorts else people + if kittens or fallback_kittens: + fields["kitten_name"], fields["kitten_id"] = (kittens or fallback_kittens)[0] else: questions.append("Не вижу котёнка в формате Имя и ID.") return fields, questions @@ -306,9 +336,8 @@ def parse_natural_bulk(text: str) -> tuple[dict[str, Any], list[str]] | None: " ", person_source, ) - people = [(match.group("name").strip(" |,–-[]"), int(match.group("id"))) - for match in _NATURAL_PERSON_RE.finditer(person_source)] - if not date_match and len(times) < 2 and len(people) < 1: + escorts, kittens, people = _natural_people(person_source) + if not date_match and len(times) < 2 and not (escorts or kittens or people): return None skill_match = re.search(r"(?i)\b(лу|лазание|зу|зоркость)\b", text) skill = None @@ -328,12 +357,13 @@ def parse_natural_bulk(text: str) -> tuple[dict[str, Any], list[str]] | None: fields["start"], fields["end"] = times[:2] else: questions.append("Нужны время начала и время конца, например 11:00 11:20.") - if len(people) >= 1: - fields["escort_name"], fields["escort_id"] = people[0] + if escorts or people: + fields["escort_name"], fields["escort_id"] = (escorts or people)[0] else: questions.append("Не вижу сопровождающего в формате Имя и ID.") - if len(people) >= 2: - fields["kitten_name"], fields["kitten_id"] = people[1] + fallback_kittens = people[1:] if not escorts else people + if kittens or fallback_kittens: + fields["kitten_name"], fields["kitten_id"] = (kittens or fallback_kittens)[0] else: questions.append("Не вижу котёнка в формате Имя и ID.") independence_match = re.search(r"(?i)\b(самостоятельно|самостоятельный|несамостоятельно|несамостоятельный|сам|несам)\b", text) @@ -342,9 +372,10 @@ def parse_natural_bulk(text: str) -> tuple[dict[str, Any], list[str]] | None: fields["kitten_independence"] = "несамостоятельно" if value.startswith("несам") else "самостоятельно" else: questions.append("Котёнок самостоятельный или несамостоятельный?") - if len(people) > 2: + extra_kittens = (kittens or fallback_kittens)[1:] + if extra_kittens: primary = fields.get("kitten_independence", "самостоятельно") - fields["extra_kittens"] = [(name, kitten_id, primary) for name, kitten_id in people[2:]] + fields["extra_kittens"] = [(name, kitten_id, primary) for name, kitten_id in extra_kittens] if skill: _validate_independence(skill, primary, fields["extra_kittens"]) return fields, questions diff --git a/structure_and_data.md b/structure_and_data.md index ddbfcfe..76d76bc 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -65,6 +65,7 @@ - 2026-08-25: web calculations and applications now accept attachment URLs only when the same web process received them from the image-host upload endpoint. This prevents public JSON from planting arbitrary browser-fetchable URLs in the admin interface; the in-memory authorization is intentionally limited to the active upload-and-submit flow. - 2026-08-25: VK image mirroring checks the advertised byte length and reads at most 15 MiB plus a one-byte sentinel before uploading. Oversized upstream photos no longer allocate unbounded memory in the bot process. - 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-16: несколько котят Калькулятор прокачки принимает `extra_kittens` из веб-формы, API и VK-команды. Общая выплата сопровождающему не суммирует полную ставку на каждого котёнка: первый подопечный использует базовый коэффициент, второй — множитель 1,5, каждый следующий — дополнительный множитель 1,15. Сайт добавляет строки дополнительных котят динамически; VK поддерживает сегмент `доп. котята: Имя [ID], Имя2 [ID]`. diff --git a/tests/test_vk_conversation.py b/tests/test_vk_conversation.py index 05b9c90..4c2c5fd 100644 --- a/tests/test_vk_conversation.py +++ b/tests/test_vk_conversation.py @@ -137,6 +137,16 @@ class VkConversationTests(unittest.TestCase): self.assertEqual(inspected["fields"]["start"], "21:00") self.assertEqual(inspected["fields"]["end"], "22:00") + def test_natural_bulk_input_prioritizes_explicit_mentor_and_student_labels(self): + inspected = inspect_bulk_text( + "24.08 ЛУ ученик: Серопопик [1346767], сопровождающая: Дикая Вишня [1604614] 21:00-22:00 несам" + ) + self.assertEqual(inspected["fields"]["escort_name"], "Дикая Вишня") + self.assertEqual(inspected["fields"]["escort_id"], 1604614) + self.assertEqual(inspected["fields"]["kitten_name"], "Серопопик") + self.assertEqual(inspected["fields"]["kitten_id"], 1346767) + self.assertEqual(inspected["fields"]["kitten_independence"], "несамостоятельно") + def test_training_supports_stepwise_and_natural_bulk(self): dialog = BelkiDialog() self.assertIn("сопровождающ", dialog.handle(102, "/урок").lower())