feat(parser): normalize flexible free text
This commit is contained in:
1 parent
b78f211292
commit
9859994deb
5 files changed
+49
No files matched your search
@@ -7,7 +7,9 @@ import random
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
import unicodedata
|
||||
from datetime import datetime
|
||||
from difflib import SequenceMatcher
|
||||
from typing import Any, Iterator
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
@@ -66,6 +68,12 @@ _LABELED_PERSON_RE = re.compile(
|
||||
r"кот[- ]?сопровождающ\w*|ученик\w*|кот[её]нок\w*|бельчонок\w*|подопечн\w*)"
|
||||
r"\s*[:—-]?\s*(?P<name>[А-Яа-яЁёA-Za-z][А-Яа-яЁёA-Za-z _-]*?)\s*\[?(?P<id>\d{3,})\]?"
|
||||
)
|
||||
_SPACED_ID_RE = re.compile(r"(?<!\d)(\d{1,3}(?:\s+\d{3})+)(?!\d)")
|
||||
_ROLE_TYPO_WORDS = (
|
||||
"сопровождающий", "сопровождающая", "наставник", "наставница",
|
||||
"учитель", "учительница", "ведущий", "ведущая", "ученик", "ученица",
|
||||
"котёнок", "бельчонок", "подопечный", "подопечная",
|
||||
)
|
||||
|
||||
|
||||
class VkError(RuntimeError):
|
||||
@@ -108,6 +116,34 @@ def _natural_people(text: str) -> tuple[list[tuple[str, int]], list[tuple[str, i
|
||||
return escorts, kittens, people
|
||||
|
||||
|
||||
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", " ")
|
||||
text = text.replace("—", "-").replace("–", "-").replace("−", "-")
|
||||
text = re.sub(r"(?i)\b(?:id|айди|№)\s*(?=\d)", "", text)
|
||||
text = _SPACED_ID_RE.sub(lambda match: match.group(1).replace(" ", ""), text)
|
||||
text = re.sub(r"\b(\d{1,2})[/-](\d{1,2})\b", r"\1.\2", text)
|
||||
# A bare ``15.08`` is a date, not 15:08. Preserve the first dotted pair
|
||||
# as the report date and treat later dotted pairs as clock values.
|
||||
date_match = re.search(r"\b(?:[12]?\d|3[01])\.(?:0?\d|1[0-2])\b", text)
|
||||
|
||||
def normalise_dotted_time(match: re.Match[str]) -> str:
|
||||
if date_match is not None and match.start() == date_match.start():
|
||||
return match.group(0)
|
||||
return f"{match.group(1)}:{match.group(2)}"
|
||||
|
||||
text = re.sub(r"\b([01]?\d|2[0-3])\s*\.\s*([0-5]\d)\b", normalise_dotted_time, text)
|
||||
text = re.sub(r"\b([01]?\d|2[0-3])\s*ч\s*([0-5]\d)\b", r"\1:\2", text)
|
||||
text = re.sub(r"(?<![\d.])([01]?\d|2[0-3])\s*-\s*([0-5]\d)\b", r"\1:\2", text)
|
||||
|
||||
def correct_role(match: re.Match[str]) -> str:
|
||||
word = match.group(0)
|
||||
candidate = max(_ROLE_TYPO_WORDS, key=lambda role: SequenceMatcher(None, word.casefold(), role).ratio())
|
||||
return candidate if SequenceMatcher(None, word.casefold(), candidate).ratio() >= 0.84 else word
|
||||
|
||||
return re.sub(r"\b[А-Яа-яЁё]{5,}\b", correct_role, text)
|
||||
|
||||
|
||||
def _extra_kittens(value: str) -> tuple[tuple[str, int, str], ...]:
|
||||
"""
|
||||
Парсит дополнительных котят из строки команды.
|
||||
@@ -276,6 +312,7 @@ def parse_natural_bulk(text: str) -> tuple[dict[str, Any], list[str]] | None:
|
||||
|
||||
Возвращает (поля, вопросы) или None, если ввод не распознан.
|
||||
"""
|
||||
text = _normalise_natural_text(text)
|
||||
lowered = text.lower()
|
||||
if re.search(r"\b(урок|тренировк)\w*\b", lowered):
|
||||
people_text = re.sub(r"(?i)^\s*(?:урок|тренировк\w*)\s*", "", text)
|
||||
|
||||
Reference in new issue
Block a user