feat(parser): prioritize explicit participant roles
This commit is contained in:
1 parent
a105be4822
commit
586693dc72
4 files changed
+58
-15
No files matched your search
@@ -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: 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: 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: 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 — несколько котят в прокачке
|
# 2026-08-16 — несколько котят в прокачке
|
||||||
|
|
||||||
`CoachingSession.extra_kittens` теперь влияет на баллы сопровождающего через количество подопечных: 1-й ×1, 2-й ×1,5, каждый последующий ×1,15 (коэффициенты перемножаются), вместо сложения полной прибыли. Базовый коэффициент самостоятельности основного котёнка сохраняется. Веб-форма отправляет список `extra_kittens`; VK принимает `доп. котята: ...` в pipe-команде.
|
`CoachingSession.extra_kittens` теперь влияет на баллы сопровождающего через количество подопечных: 1-й ×1, 2-й ×1,5, каждый последующий ×1,15 (коэффициенты перемножаются), вместо сложения полной прибыли. Базовый коэффициент самостоятельности основного котёнка сохраняется. Веб-форма отправляет список `extra_kittens`; VK принимает `доп. котята: ...` в pipe-команде.
|
||||||
+46
-15
@@ -61,6 +61,11 @@ _DATE_RE = re.compile(r"\b(?P<date>\d{1,2}\.\d{1,2})\b")
|
|||||||
_TIME_RE = re.compile(r"\b(?:[01]?\d|2[0-3]):[0-5]\d\b")
|
_TIME_RE = re.compile(r"\b(?:[01]?\d|2[0-3]):[0-5]\d\b")
|
||||||
# Натуральное имя: "Имя [ID" или "Имя ID"
|
# Натуральное имя: "Имя [ID" или "Имя ID"
|
||||||
_NATURAL_PERSON_RE = re.compile(r"(?P<name>[А-Яа-яЁёA-Za-z][^\d|,\n]*?)\s*\[?(?P<id>\d{3,})\]?")
|
_NATURAL_PERSON_RE = re.compile(r"(?P<name>[А-Яа-яЁёA-Za-z][^\d|,\n]*?)\s*\[?(?P<id>\d{3,})\]?")
|
||||||
|
_LABELED_PERSON_RE = re.compile(
|
||||||
|
r"(?i)\b(?P<role>сопровождающ\w*|наставник\w*|учител\w*|ведущ\w*|"
|
||||||
|
r"кот[- ]?сопровождающ\w*|ученик\w*|кот[её]нок\w*|бельчонок\w*|подопечн\w*)"
|
||||||
|
r"\s*[:—-]?\s*(?P<name>[А-Яа-яЁёA-Za-z][А-Яа-яЁёA-Za-z _-]*?)\s*\[?(?P<id>\d{3,})\]?"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class VkError(RuntimeError):
|
class VkError(RuntimeError):
|
||||||
@@ -78,6 +83,31 @@ def _person(value: str) -> tuple[str, int]:
|
|||||||
return match.group("name").strip(), int(match.group("id"))
|
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], ...]:
|
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()
|
lowered = text.lower()
|
||||||
if re.search(r"\b(урок|тренировк)\w*\b", lowered):
|
if re.search(r"\b(урок|тренировк)\w*\b", lowered):
|
||||||
people_text = re.sub(r"(?i)^\s*(?:урок|тренировк\w*)\s*", "", text)
|
people_text = re.sub(r"(?i)^\s*(?:урок|тренировк\w*)\s*", "", text)
|
||||||
people = [(match.group("name").strip(" |,–-[]"), int(match.group("id")))
|
escorts, kittens, people = _natural_people(people_text)
|
||||||
for match in _NATURAL_PERSON_RE.finditer(people_text)]
|
|
||||||
fields: dict[str, Any] = {"mode": "training"}
|
fields: dict[str, Any] = {"mode": "training"}
|
||||||
questions: list[str] = []
|
questions: list[str] = []
|
||||||
if people:
|
if escorts or people:
|
||||||
fields["escort_name"], fields["escort_id"] = people[0]
|
fields["escort_name"], fields["escort_id"] = (escorts or people)[0]
|
||||||
else:
|
else:
|
||||||
questions.append("Не вижу сопровождающего в формате Имя и ID.")
|
questions.append("Не вижу сопровождающего в формате Имя и ID.")
|
||||||
if len(people) > 1:
|
fallback_kittens = people[1:] if not escorts else people
|
||||||
fields["kitten_name"], fields["kitten_id"] = people[1]
|
if kittens or fallback_kittens:
|
||||||
|
fields["kitten_name"], fields["kitten_id"] = (kittens or fallback_kittens)[0]
|
||||||
else:
|
else:
|
||||||
questions.append("Не вижу котёнка в формате Имя и ID.")
|
questions.append("Не вижу котёнка в формате Имя и ID.")
|
||||||
return fields, questions
|
return fields, questions
|
||||||
@@ -306,9 +336,8 @@ def parse_natural_bulk(text: str) -> tuple[dict[str, Any], list[str]] | None:
|
|||||||
" ",
|
" ",
|
||||||
person_source,
|
person_source,
|
||||||
)
|
)
|
||||||
people = [(match.group("name").strip(" |,–-[]"), int(match.group("id")))
|
escorts, kittens, people = _natural_people(person_source)
|
||||||
for match in _NATURAL_PERSON_RE.finditer(person_source)]
|
if not date_match and len(times) < 2 and not (escorts or kittens or people):
|
||||||
if not date_match and len(times) < 2 and len(people) < 1:
|
|
||||||
return None
|
return None
|
||||||
skill_match = re.search(r"(?i)\b(лу|лазание|зу|зоркость)\b", text)
|
skill_match = re.search(r"(?i)\b(лу|лазание|зу|зоркость)\b", text)
|
||||||
skill = None
|
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]
|
fields["start"], fields["end"] = times[:2]
|
||||||
else:
|
else:
|
||||||
questions.append("Нужны время начала и время конца, например 11:00 11:20.")
|
questions.append("Нужны время начала и время конца, например 11:00 11:20.")
|
||||||
if len(people) >= 1:
|
if escorts or people:
|
||||||
fields["escort_name"], fields["escort_id"] = people[0]
|
fields["escort_name"], fields["escort_id"] = (escorts or people)[0]
|
||||||
else:
|
else:
|
||||||
questions.append("Не вижу сопровождающего в формате Имя и ID.")
|
questions.append("Не вижу сопровождающего в формате Имя и ID.")
|
||||||
if len(people) >= 2:
|
fallback_kittens = people[1:] if not escorts else people
|
||||||
fields["kitten_name"], fields["kitten_id"] = people[1]
|
if kittens or fallback_kittens:
|
||||||
|
fields["kitten_name"], fields["kitten_id"] = (kittens or fallback_kittens)[0]
|
||||||
else:
|
else:
|
||||||
questions.append("Не вижу котёнка в формате Имя и ID.")
|
questions.append("Не вижу котёнка в формате Имя и ID.")
|
||||||
independence_match = re.search(r"(?i)\b(самостоятельно|самостоятельный|несамостоятельно|несамостоятельный|сам|несам)\b", text)
|
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 "самостоятельно"
|
fields["kitten_independence"] = "несамостоятельно" if value.startswith("несам") else "самостоятельно"
|
||||||
else:
|
else:
|
||||||
questions.append("Котёнок самостоятельный или несамостоятельный?")
|
questions.append("Котёнок самостоятельный или несамостоятельный?")
|
||||||
if len(people) > 2:
|
extra_kittens = (kittens or fallback_kittens)[1:]
|
||||||
|
if extra_kittens:
|
||||||
primary = fields.get("kitten_independence", "самостоятельно")
|
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:
|
if skill:
|
||||||
_validate_independence(skill, primary, fields["extra_kittens"])
|
_validate_independence(skill, primary, fields["extra_kittens"])
|
||||||
return fields, questions
|
return fields, questions
|
||||||
|
|||||||
@@ -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: 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: 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: `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: несколько котят
|
# Обновление 2026-08-16: несколько котят
|
||||||
|
|
||||||
Калькулятор прокачки принимает `extra_kittens` из веб-формы, API и VK-команды. Общая выплата сопровождающему не суммирует полную ставку на каждого котёнка: первый подопечный использует базовый коэффициент, второй — множитель 1,5, каждый следующий — дополнительный множитель 1,15. Сайт добавляет строки дополнительных котят динамически; VK поддерживает сегмент `доп. котята: Имя [ID], Имя2 [ID]`.
|
Калькулятор прокачки принимает `extra_kittens` из веб-формы, API и VK-команды. Общая выплата сопровождающему не суммирует полную ставку на каждого котёнка: первый подопечный использует базовый коэффициент, второй — множитель 1,5, каждый следующий — дополнительный множитель 1,15. Сайт добавляет строки дополнительных котят динамически; VK поддерживает сегмент `доп. котята: Имя [ID], Имя2 [ID]`.
|
||||||
@@ -137,6 +137,16 @@ class VkConversationTests(unittest.TestCase):
|
|||||||
self.assertEqual(inspected["fields"]["start"], "21:00")
|
self.assertEqual(inspected["fields"]["start"], "21:00")
|
||||||
self.assertEqual(inspected["fields"]["end"], "22: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):
|
def test_training_supports_stepwise_and_natural_bulk(self):
|
||||||
dialog = BelkiDialog()
|
dialog = BelkiDialog()
|
||||||
self.assertIn("сопровождающ", dialog.handle(102, "/урок").lower())
|
self.assertIn("сопровождающ", dialog.handle(102, "/урок").lower())
|
||||||
|
|||||||
Reference in new issue
Block a user