fix(parser): clarify free-form inspection input

This commit is contained in:
nyan404 committed 2026-08-25 03:54:35 +03:00
1 parent c0a6f6286e
commit 32bb5ae3d0
5 files changed
+78 -19

No files matched your search

+12 -9
View File
@@ -80,13 +80,16 @@ def render_coaching(session: CoachingSession, result: CoachingResult) -> str:
Баллы бельчонка: Y. Баллы бельчонка: Y.
""" """
hashtag = "#лазание" if session.skill == "ЛУ" else "#зоркость" hashtag = "#лазание" if session.skill == "ЛУ" else "#зоркость"
kitten_text = f"{session.kitten_name} [{session.kitten_id}]" kittens = [f"{session.kitten_name} [{session.kitten_id}]"] + [
if session.extra_kittens: f"{name} [{kitten_id}]" for name, kitten_id, _ in session.extra_kittens
kitten_text += ", " + ", ".join(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 = [ lines = [
hashtag, hashtag,
f"{session.escort_name} [{session.escort_id}], помог(-ла) {kitten_text} " f"{session.escort_name} [{session.escort_id}], {activity}",
f"прокачать {session.skill}.",
f"Время: {format_clock(parse_clock(session.start))} – " f"Время: {format_clock(parse_clock(session.start))} – "
f"{format_clock(parse_clock(session.end))} [{result.minutes} минут].", f"{format_clock(parse_clock(session.end))} [{result.minutes} минут].",
f"Баллы белки: {_points_phrase(result.escort_points)}.", 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() result = result or TrainingResult()
return ( return (
"#урок\n" "#урок\n"
f"{session.escort_name} [{session.escort_id}], провел(-ла) урок " f"{session.escort_name} [{session.escort_id}], провёл(-ла) урок "
f"{session.kitten_name} [{session.kitten_id}]." f"{session.kitten_name} [{session.kitten_id}]."
) )
@@ -121,7 +124,7 @@ def render_inspection(report: InspectionReport, result: InspectionResult | None
+N ресурс. (для каждого ресурса) +N ресурс. (для каждого ресурса)
Баллы осмотра: X. Баллы осмотра: X.
Если ресурсов нет — выводит "0" вместо списка. Если ресурсов нет — сообщает об этом отдельной строкой.
""" """
result = result or calculate_inspection(report) result = result or calculate_inspection(report)
lines = [ lines = [
@@ -135,6 +138,6 @@ def render_inspection(report: InspectionReport, result: InspectionResult | None
if amount if amount
) )
else: else:
lines.append("0") lines.append("Ресурсов не найдено.")
lines.append(f"Баллы осмотра: {_points_phrase(result.points)}.") lines.append(f"Баллы осмотра: {_points_phrase(result.points)}.")
return "\n".join(lines) return "\n".join(lines)
+41 -9
View File
@@ -75,6 +75,17 @@ _ROLE_TYPO_WORDS = (
"учитель", "учительница", "ведущий", "ведущая", "ученик", "ученица", "учитель", "учительница", "ведущий", "ведущая", "ученик", "ученица",
"котёнок", "бельчонок", "подопечный", "подопечная", "котёнок", "бельчонок", "подопечный", "подопечная",
) )
_INSPECTION_COUNT_RE = re.compile(
r"(?i)(?<![\d.])(?P<count>\d{1,6})\s*(?:раз(?:а|ов)?|осмотр(?:а|ов)?)\b"
)
_INSPECTION_PLACE_COUNT_RE = re.compile(
r"(?i)\b(?:дупло|расщелин\w*)\b\s*[:,\-]?\s*(?P<count>\d{1,6})\b"
)
_INSPECTION_PERSON_RE = re.compile(
r"(?i)\b(?:персонаж|кот|белка)\s*[:\-]?\s*"
r"(?P<name>[А-Яа-яЁёA-Za-z][А-Яа-яЁёA-Za-z _-]*?)\s*\[?(?P<id>\d{3,})\]?"
)
_INSPECTION_RESOURCE_NAME_RE = re.compile(r"^[А-Яа-яЁёA-Za-z][А-Яа-яЁёA-Za-z _-]*$")
class VkError(RuntimeError): class VkError(RuntimeError):
@@ -145,6 +156,25 @@ def _normalise_natural_text(text: str) -> str:
return re.sub(r"\b[А-Яа-яЁё]{5,}\b", correct_role, text) 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<amount>\d+)\s+(?P<name>[А-Яа-яЁё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<name>[А-Яа-яЁёA-Za-z][А-Яа-яЁёA-Za-z _-]*?)\s*[=:]\s*(?P<amount>\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], ...]: 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 "расщелина" fields["place"] = "дупло" if place_match.group(1) == "дупло" else "расщелина"
else: else:
questions.append("Укажите место: дупло или расщелина.") 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: if count_match:
fields["inspections"] = int(count_match.group(1)) fields["inspections"] = int(count_match.group("count"))
else: else:
questions.append("Сколько было осмотров?") questions.append("Сколько было осмотров?")
people_text = text[count_match.end():] if count_match else text people_text = text
people = [(match.group("name").strip(" |,–-"), int(match.group("id"))) explicit_person = _INSPECTION_PERSON_RE.search(people_text)
for match in _NATURAL_PERSON_RE.finditer(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: if people:
fields["character_name"], fields["character_id"] = people[0] fields["character_name"], fields["character_id"] = people[0]
else: else:
@@ -364,10 +399,7 @@ def parse_natural_bulk(text: str) -> tuple[dict[str, Any], list[str]] | None:
questions.append("Для этого имени не хватает ID персонажа (или его связки в справочнике).") questions.append("Для этого имени не хватает ID персонажа (или его связки в справочнике).")
else: else:
questions.append("Укажите имя или ID персонажа.") questions.append("Укажите имя или ID персонажа.")
resources = [] fields["resources"] = _natural_inspection_resources(text)
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
return fields, questions return fields, questions
date_match = _DATE_RE.search(text) date_match = _DATE_RE.search(text)
times = _TIME_RE.findall(text) times = _TIME_RE.findall(text)
+2
View File
@@ -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: 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: 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: 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-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: несколько котят # Обновление 2026-08-16: несколько котят
+11 -1
View File
@@ -185,10 +185,17 @@ class ReportTests(unittest.TestCase):
self.assertNotIn("Скриншот", text) self.assertNotIn("Скриншот", text)
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): def test_training_report_is_separate(self):
text = render_training(TrainingSession("Белка", 1, "Котёнок", 2)) text = render_training(TrainingSession("Белка", 1, "Котёнок", 2))
self.assertIn("#урок", text) self.assertIn("#урок", text)
self.assertIn("провел(-ла) урок", text) self.assertIn("провёл(-ла) урок", text)
def test_inspection_report_lists_zero_and_resources(self): def test_inspection_report_lists_zero_and_resources(self):
text = render_inspection( text = render_inspection(
@@ -207,6 +214,9 @@ class ReportTests(unittest.TestCase):
self.assertNotIn("Скриншот", text) self.assertNotIn("Скриншот", text)
self.assertIn("Баллы осмотра: 15 баллов.", 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): def test_spider_and_web_have_different_values(self):
report = InspectionReport( report = InspectionReport(
character_name="Дикая Вишня", character_id=1604614, place="дупло", inspections=4, character_name="Дикая Вишня", character_id=1604614, place="дупло", inspections=4,
+12
View File
@@ -254,6 +254,18 @@ class VkConversationTests(unittest.TestCase):
self.assertEqual(inspected["fields"]["character_id"], 1617140) self.assertEqual(inspected["fields"]["character_id"], 1617140)
self.assertIn("имени", " ".join(inspected["questions"]).lower()) 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): def test_identity_directory_persists_pairs_in_sqlite(self):
with TemporaryDirectory() as directory: with TemporaryDirectory() as directory:
path = f"{directory}/identities.sqlite3" path = f"{directory}/identities.sqlite3"