diff --git a/app/belki/reports.py b/app/belki/reports.py index 7995523..a1a0378 100644 --- a/app/belki/reports.py +++ b/app/belki/reports.py @@ -80,13 +80,16 @@ def render_coaching(session: CoachingSession, result: CoachingResult) -> str: Баллы бельчонка: Y. """ hashtag = "#лазание" if session.skill == "ЛУ" else "#зоркость" - kitten_text = f"{session.kitten_name} [{session.kitten_id}]" - if session.extra_kittens: - kitten_text += ", " + ", ".join(f"{name} [{kitten_id}]" for name, kitten_id, _ in session.extra_kittens) + kittens = [f"{session.kitten_name} [{session.kitten_id}]"] + [ + f"{name} [{kitten_id}]" for name, kitten_id, _ in session.extra_kittens + ] + if len(kittens) == 1: + activity = f"помог(-ла) {kittens[0]} прокачать {session.skill}." + else: + activity = f"помог(-ла) котятам прокачать {session.skill}: {', '.join(kittens)}." lines = [ hashtag, - f"{session.escort_name} [{session.escort_id}], помог(-ла) {kitten_text} " - f"прокачать {session.skill}.", + f"{session.escort_name} [{session.escort_id}], {activity}", f"Время: {format_clock(parse_clock(session.start))} – " f"{format_clock(parse_clock(session.end))} [{result.minutes} минут].", f"Баллы белки: {_points_phrase(result.escort_points)}.", @@ -101,12 +104,12 @@ def render_training(session: TrainingSession, result: TrainingResult | None = No Формат: #урок - Имя [ID], провел(-ла) урок Котёнок [ID]. + Имя [ID], провёл(-ла) урок Котёнок [ID]. """ result = result or TrainingResult() return ( "#урок\n" - f"{session.escort_name} [{session.escort_id}], провел(-ла) урок " + f"{session.escort_name} [{session.escort_id}], провёл(-ла) урок " f"{session.kitten_name} [{session.kitten_id}]." ) @@ -121,7 +124,7 @@ def render_inspection(report: InspectionReport, result: InspectionResult | None +N ресурс. (для каждого ресурса) Баллы осмотра: X. - Если ресурсов нет — выводит "0" вместо списка. + Если ресурсов нет — сообщает об этом отдельной строкой. """ result = result or calculate_inspection(report) lines = [ @@ -135,6 +138,6 @@ def render_inspection(report: InspectionReport, result: InspectionResult | None if amount ) else: - lines.append("0") + lines.append("Ресурсов не найдено.") lines.append(f"Баллы осмотра: {_points_phrase(result.points)}.") return "\n".join(lines) diff --git a/app/belki/vk_bot.py b/app/belki/vk_bot.py index fc74459..4e1ef2c 100644 --- a/app/belki/vk_bot.py +++ b/app/belki/vk_bot.py @@ -75,6 +75,17 @@ _ROLE_TYPO_WORDS = ( "учитель", "учительница", "ведущий", "ведущая", "ученик", "ученица", "котёнок", "бельчонок", "подопечный", "подопечная", ) +_INSPECTION_COUNT_RE = re.compile( + r"(?i)(?\d{1,6})\s*(?:раз(?:а|ов)?|осмотр(?:а|ов)?)\b" +) +_INSPECTION_PLACE_COUNT_RE = re.compile( + r"(?i)\b(?:дупло|расщелин\w*)\b\s*[:,\-]?\s*(?P\d{1,6})\b" +) +_INSPECTION_PERSON_RE = re.compile( + r"(?i)\b(?:персонаж|кот|белка)\s*[:\-]?\s*" + r"(?P[А-Яа-яЁёA-Za-z][А-Яа-яЁёA-Za-z _-]*?)\s*\[?(?P\d{3,})\]?" +) +_INSPECTION_RESOURCE_NAME_RE = re.compile(r"^[А-Яа-яЁёA-Za-z][А-Яа-яЁёA-Za-z _-]*$") class VkError(RuntimeError): @@ -145,6 +156,25 @@ def _normalise_natural_text(text: str) -> str: return re.sub(r"\b[А-Яа-яЁё]{5,}\b", correct_role, text) +def _natural_inspection_resources(text: str) -> list[list[str | int]]: + """Extract found resources without treating dates, IDs, or counts as loot. + + The signed format used by the dialog is deliberately preferred: ``+2 паук`` + is unambiguous even in prose. ``паутина=2`` and ``паутина: 2`` remain + accepted for compatibility with the older command format. + """ + if re.search(r"(?i)\b(?:без|нет)\s+ресурс", text): + return [] + resources: list[list[str | int]] = [] + for match in re.finditer(r"\+\s*(?P\d+)\s+(?P[А-Яа-яЁёA-Za-z][А-Яа-яЁёA-Za-z _-]*?)(?=\s*(?:[+,;]|$))", text): + resources.append([match.group("name").strip(), int(match.group("amount"))]) + for item in re.split(r"[,;]", text): + match = re.fullmatch(r"\s*(?P[А-Яа-яЁёA-Za-z][А-Яа-яЁёA-Za-z _-]*?)\s*[=:]\s*(?P\d+)\s*", item) + if match and _INSPECTION_RESOURCE_NAME_RE.fullmatch(match.group("name").strip()): + resources.append([match.group("name").strip(), int(match.group("amount"))]) + return resources + + def _extra_kittens(value: str) -> tuple[tuple[str, int, str], ...]: """ Парсит дополнительных котят из строки команды. @@ -342,14 +372,19 @@ def parse_natural_bulk(text: str) -> tuple[dict[str, Any], list[str]] | None: fields["place"] = "дупло" if place_match.group(1) == "дупло" else "расщелина" else: questions.append("Укажите место: дупло или расщелина.") - count_match = re.search(r"\b(\d+)\s*(?:раз(?:а|ов)?|осмотр(?:а|ов)?)?\b", lowered) + # Never use the first number in the line: it can be a date fragment or + # a character ID. Prefer an explicitly labelled count, then the number + # immediately following the inspected place. + count_match = _INSPECTION_COUNT_RE.search(text) or _INSPECTION_PLACE_COUNT_RE.search(text) if count_match: - fields["inspections"] = int(count_match.group(1)) + fields["inspections"] = int(count_match.group("count")) else: questions.append("Сколько было осмотров?") - people_text = text[count_match.end():] if count_match else text - people = [(match.group("name").strip(" |,–-"), int(match.group("id"))) - for match in _NATURAL_PERSON_RE.finditer(people_text)] + people_text = text + explicit_person = _INSPECTION_PERSON_RE.search(people_text) + escorts, kittens, people = _natural_people(people_text) + people = ([(explicit_person.group("name").strip(), int(explicit_person.group("id")))] + if explicit_person else escorts + kittens + people) if people: fields["character_name"], fields["character_id"] = people[0] else: @@ -364,10 +399,7 @@ def parse_natural_bulk(text: str) -> tuple[dict[str, Any], list[str]] | None: questions.append("Для этого имени не хватает ID персонажа (или его связки в справочнике).") else: questions.append("Укажите имя или ID персонажа.") - resources = [] - for match in re.finditer(r"([А-Яа-яЁёA-Za-z][А-Яа-яЁёA-Za-z _-]*)\s*[=;:]\s*(-?\d+)", text): - resources.append([match.group(1).strip(), int(match.group(2))]) - fields["resources"] = resources + fields["resources"] = _natural_inspection_resources(text) return fields, questions date_match = _DATE_RE.search(text) times = _TIME_RE.findall(text) diff --git a/structure_and_data.md b/structure_and_data.md index 6a1d4c0..1133833 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -71,6 +71,8 @@ - 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. - 2026-08-25: shared domain limits now bound public calculation fan-out: at most 50 coaching kittens, 100 inspection resource rows, 100000 inspections, and 100000 units of one resource. API and VK reject oversized kitten lists before calculation. +- 2026-08-25: report copy now uses a plural construction for several kittens, normative `провёл(-ла)` for lessons, and a readable empty-resource line instead of a standalone `0`. +- 2026-08-25: free-form inspection parsing now distinguishes a labelled count (or a count immediately after the place) from date fragments and character IDs; it also understands explicit character labels and both `+N ресурс` and legacy `ресурс=N` loot notation. - 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_belki.py b/tests/test_belki.py index add851c..47f03a5 100644 --- a/tests/test_belki.py +++ b/tests/test_belki.py @@ -185,10 +185,17 @@ class ReportTests(unittest.TestCase): self.assertNotIn("Скриншот", text) self.assertNotIn("истории", text) + def test_coaching_report_uses_plural_for_multiple_kittens(self): + session = CoachingSession( + "15.08", "ЛУ", "11:00", "11:20", "Белка", 1, "Первый", 2, + extra_kittens=(("Второй", 3, "самостоятельно"),), + ) + self.assertIn("помог(-ла) котятам прокачать ЛУ: Первый [2], Второй [3].", render_coaching(session, calculate_coaching(session))) + def test_training_report_is_separate(self): text = render_training(TrainingSession("Белка", 1, "Котёнок", 2)) self.assertIn("#урок", text) - self.assertIn("провел(-ла) урок", text) + self.assertIn("провёл(-ла) урок", text) def test_inspection_report_lists_zero_and_resources(self): text = render_inspection( @@ -207,6 +214,9 @@ class ReportTests(unittest.TestCase): self.assertNotIn("Скриншот", text) self.assertIn("Баллы осмотра: 15 баллов.", text) + def test_inspection_report_explains_an_empty_resource_list(self): + self.assertIn("Ресурсов не найдено.", render_inspection(InspectionReport("Белка", 1, "дупло", 1))) + def test_spider_and_web_have_different_values(self): report = InspectionReport( character_name="Дикая Вишня", character_id=1604614, place="дупло", inspections=4, diff --git a/tests/test_vk_conversation.py b/tests/test_vk_conversation.py index 45d3fb6..96b8a0f 100644 --- a/tests/test_vk_conversation.py +++ b/tests/test_vk_conversation.py @@ -254,6 +254,18 @@ class VkConversationTests(unittest.TestCase): self.assertEqual(inspected["fields"]["character_id"], 1617140) self.assertIn("имени", " ".join(inspected["questions"]).lower()) + def test_natural_inspection_does_not_confuse_date_or_id_with_count(self): + inspected = inspect_bulk_text( + "24.08 осмотр расщелина: 6 раз; персонаж Серолап id 1 617 140; +2 паутина, +1 паук" + ) + self.assertEqual(inspected["fields"]["inspections"], 6) + self.assertEqual((inspected["fields"]["character_name"], inspected["fields"]["character_id"]), ("Серолап", 1617140)) + self.assertEqual(inspected["fields"]["resources"], [["паутина", 2], ["паук", 1]]) + + def test_natural_inspection_accepts_legacy_resource_assignments_without_count_noise(self): + inspected = inspect_bulk_text("осмотр дупло 6 раз Серолап [1617140]; паутина=2, паук: 1") + self.assertEqual(inspected["fields"]["resources"], [["паутина", 2], ["паук", 1]]) + def test_identity_directory_persists_pairs_in_sqlite(self): with TemporaryDirectory() as directory: path = f"{directory}/identities.sqlite3"