diff --git a/MEMORY.md b/MEMORY.md index 9a894bc..1ee49c2 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -41,6 +41,7 @@ - 2026-08-25: after the byte cap, VK attachment mirroring accepts only PNG/JPEG/WebP signatures and does not trust the external response Content-Type. - 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-25: when several labelled wards appear in one natural line, an adjacent `сам`/`несам` marker is assigned to that specific ward before any global status fallback. - 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: in-process admin sessions are opaque tokens with a 12-hour server and cookie lifetime, capped at 100 active sessions; a restart still invalidates them by design. diff --git a/app/belki/vk_bot.py b/app/belki/vk_bot.py index 9d2c2c9..2aad881 100644 --- a/app/belki/vk_bot.py +++ b/app/belki/vk_bot.py @@ -146,6 +146,30 @@ def _natural_people(text: str) -> tuple[list[tuple[str, int]], list[tuple[str, i return escorts, kittens, people +def _labelled_kitten_statuses(text: str) -> dict[int, str]: + """Read a status written beside an explicitly labelled ward. + + A final standalone ``сам``/``несам`` still applies to the whole entry, but + a status inside the same comma/semicolon-delimited phrase as ``ученик`` or + ``котёнок`` is stronger evidence for that particular participant. + """ + statuses: dict[int, str] = {} + matches = list(_LABELED_PERSON_RE.finditer(text)) + for index, match in enumerate(matches): + role = match.group("role").casefold() + if not re.match(r"^(ученик|котенок|котёнок|бельчонок|подопечн)", role): + continue + next_start = matches[index + 1].start() if index + 1 < len(matches) else len(text) + fragment = text[match.end():next_start] + fragment = re.split(r"[,;\n]", fragment, maxsplit=1)[0] + status = re.search(r"(?i)\b(самостоятельно|самостоятельный|несамостоятельно|несамостоятельный|сам|несам)\b", fragment) + if status: + statuses[int(match.group("id"))] = ( + "несамостоятельно" if status.group(1).casefold().startswith("несам") else "самостоятельно" + ) + return statuses + + 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", " ") @@ -467,16 +491,24 @@ def parse_natural_bulk(text: str) -> tuple[dict[str, Any], list[str]] | None: fields["kitten_name"], fields["kitten_id"] = (kittens or fallback_kittens)[0] else: questions.append("Не вижу котёнка в формате Имя и ID.") + participants = kittens or fallback_kittens + labelled_statuses = _labelled_kitten_statuses(text) independence_match = re.search(r"(?i)\b(самостоятельно|самостоятельный|несамостоятельно|несамостоятельный|сам|несам)\b", text) - if independence_match: + primary_status = labelled_statuses.get(participants[0][1]) if participants else None + if primary_status is None and independence_match: value = independence_match.group(1).lower() - fields["kitten_independence"] = "несамостоятельно" if value.startswith("несам") else "самостоятельно" + primary_status = "несамостоятельно" if value.startswith("несам") else "самостоятельно" + if primary_status: + fields["kitten_independence"] = primary_status else: questions.append("Котёнок самостоятельный или несамостоятельный?") - extra_kittens = (kittens or fallback_kittens)[1:] + extra_kittens = participants[1:] if extra_kittens: primary = fields.get("kitten_independence", "самостоятельно") - fields["extra_kittens"] = [(name, kitten_id, primary) for name, kitten_id in extra_kittens] + fields["extra_kittens"] = [ + (name, kitten_id, labelled_statuses.get(kitten_id, primary)) + for name, kitten_id in extra_kittens + ] if skill: try: _validate_independence(skill, fields.get("kitten_independence", "самостоятельно"), fields.get("extra_kittens", ())) diff --git a/project_mind_map.md b/project_mind_map.md index 7b9732b..ecd9d57 100644 --- a/project_mind_map.md +++ b/project_mind_map.md @@ -47,6 +47,7 @@ mindmap Step dialogs Natural one-line parser Mentor and student labels + Per-ward self-sufficiency labels Flexible punctuation and ID normalization Written Russian dates Attachment mirroring diff --git a/structure_and_data.md b/structure_and_data.md index 0a88f9e..26efe7d 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -74,6 +74,7 @@ - 2026-08-25: admin history sorting now tolerates legacy records whose IDs were stored as strings, preserving numeric order for valid IDs instead of failing the complete history view. - 2026-08-25: coaching sessions now validate a real calendar date in `ДД.ММ` form before any calculation or persistence; free-form dates remain accepted after parser normalization. - 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: a self-sufficiency marker directly beside a labelled ward now belongs to that ward, so one natural line can describe different statuses for several kittens. - 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: impossible status combinations discovered in free text (for example, non-self-sufficient ЗУ) now remain a repairable clarification in the dialogue instead of raising out of the VK handler. diff --git a/tests/test_vk_conversation.py b/tests/test_vk_conversation.py index 26f8a1a..e169cd8 100644 --- a/tests/test_vk_conversation.py +++ b/tests/test_vk_conversation.py @@ -157,6 +157,15 @@ class VkConversationTests(unittest.TestCase): self.assertEqual(inspected["fields"]["kitten_id"], 1346767) self.assertEqual(inspected["fields"]["kitten_independence"], "несамостоятельно") + def test_natural_bulk_input_assigns_statuses_to_labelled_individual_kittens(self): + inspected = inspect_bulk_text( + "24.08 ЛУ 21:00-22:00 сопровождающая Дикая Вишня [1604614]; " + "ученик Серопопик [1346767] — несам; бельчонок Тучка [1604615] — сам" + ) + self.assertEqual(inspected["status"], "complete") + self.assertEqual(inspected["fields"]["kitten_independence"], "несамостоятельно") + self.assertEqual(inspected["fields"]["extra_kittens"], [("Тучка", 1604615, "самостоятельно")]) + 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; несам."