feat(parser): prioritize explicit participant roles

This commit is contained in:
nyan404 committed 2026-08-25 03:43:10 +03:00
1 parent a105be4822
commit 586693dc72
4 files changed
+58 -15

No files matched your search

+46 -15
View File
@@ -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")
# Натуральное имя: "Имя [ID" или "Имя ID"
_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):
@@ -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