release: Themiz на Gitea
This commit is contained in:
Regular → Executable
+418
-15
@@ -10,6 +10,7 @@
|
||||
practice_harvest.py кандидаты в базу (по убыванию частоты)
|
||||
practice_harvest.py --audit качество самой базы: записи без источника,
|
||||
дубли, категории без записей
|
||||
practice_harvest.py --apply CASE внести подтвержденные акты practice.md
|
||||
practice_harvest.py --md FILE выгрузить кандидатов в markdown для archivist
|
||||
practice_harvest.py --selftest проверка без сети
|
||||
|
||||
@@ -22,7 +23,9 @@ import glob
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
from collections import Counter, defaultdict
|
||||
from datetime import datetime
|
||||
|
||||
# Реквизиты актов. Пишем строго — «суд рассмотрел» без номера базе не нужен.
|
||||
PATTERNS = {
|
||||
@@ -43,6 +46,28 @@ PATTERNS = {
|
||||
SOURCE_GLOBS = (".agent/context/practice.md", ".agent/context/hunter_*.md",
|
||||
".agent/context/positions.md", ".agent/context/_practice/*.md")
|
||||
|
||||
INDEX_HEADER = ("# Индекс проверенной практики\n\n"
|
||||
"> Новый индекс пуст. Добавляйте только верифицированные акты "
|
||||
"без данных доверителей.\n")
|
||||
ACT_RE = re.compile(
|
||||
r"(?P<full>(?:Апелляционн\w+\s+определени\w*|"
|
||||
r"Кассационн\w+\s+определени\w*|Постановлени\w*|Определени\w*|"
|
||||
r"Решени\w*|Обзор\w*)[^\n|]{0,160}?\s+(?:от\s+"
|
||||
r"(?P<date>\d{2}\.\d{2}\.\d{4})(?:\s*г(?:ода|\.)?)?\s*[,;]?\s*"
|
||||
r"№\s*(?P<number>[0-9А-Яа-яA-Za-z]+(?:[-‑‒–—/][0-9А-Яа-яA-Za-z]+)*)|"
|
||||
# Тот же акт с номером перед датой: «Определение № 5-КГ23-14-К2 от 15.03.2023».
|
||||
r"№\s*(?P<number2>[0-9А-Яа-яA-Za-z]+(?:[-‑‒–—/][0-9А-Яа-яA-Za-z]+)*)"
|
||||
r"\s*[,;]?\s*от\s+(?P<date2>\d{2}\.\d{2}\.\d{4})(?:\s*г(?:ода|\.)?)?))",
|
||||
re.IGNORECASE)
|
||||
VERIFIED_RE = re.compile(
|
||||
r"(?:verify_act\.py[^\n|]{0,80}\bПОДТВЕРЖДЕН\b|"
|
||||
r"(?i:первоисточник\s*:\s*подтверждено))")
|
||||
UNVERIFIED_RE = re.compile(
|
||||
r"\bне(?:\s+\S+){0,2}\s*подтвержден|\bне\s*проверен|требует\s+проверки|не\s+найден|"
|
||||
r"из\s+памяти|канал\s+недоступен|расхождение", re.IGNORECASE)
|
||||
FORBIDDEN_SECTION_RE = re.compile(r"не\s+цитировать\s+до\s+проверки", re.IGNORECASE)
|
||||
GENERIC_SECTIONS = ("источник", "не найден", "подмен", "практика в нашу пользу")
|
||||
|
||||
|
||||
def act_key(kind: str, m: re.Match) -> str:
|
||||
if kind == "Пленум/Обзор ВС":
|
||||
@@ -58,6 +83,26 @@ def context_of(text: str, span: tuple[int, int], width: int = 160) -> str:
|
||||
return frag
|
||||
|
||||
|
||||
_OWN_NUMBER_LINE_RE = re.compile(
|
||||
r"(?im)^[\s#>*|-]*(?:номер\s+(?:дела|производства)|дело\s*№|№\s*дела)[^\n]*$")
|
||||
|
||||
|
||||
def own_numbers(case_dir: str) -> set[str]:
|
||||
"""Номера собственного производства дела: его материалы — не практика."""
|
||||
own = set()
|
||||
for probe in ("_case.md", ".agent/context/knowledge-map.md"):
|
||||
try:
|
||||
head = open(os.path.join(case_dir, probe), encoding="utf-8",
|
||||
errors="replace").read()
|
||||
except OSError:
|
||||
continue
|
||||
# Только строка-поле с номером производства: карта цитирует и чужую практику.
|
||||
for line in _OWN_NUMBER_LINE_RE.findall(head):
|
||||
own |= set(PATTERNS["СОЮ"].findall(line))
|
||||
own |= set(PATTERNS["Арбитраж"].findall(line))
|
||||
return own
|
||||
|
||||
|
||||
def harvest(cases_dir: str) -> dict[str, dict]:
|
||||
found: dict[str, dict] = defaultdict(lambda: {"count": 0, "cases": set(), "context": ""})
|
||||
for client in sorted(os.listdir(cases_dir)):
|
||||
@@ -70,15 +115,7 @@ def harvest(cases_dir: str) -> dict[str, dict]:
|
||||
continue
|
||||
# Номер САМОГО дела встречается в его же материалах на каждой странице —
|
||||
# и попадал в кандидаты как «практика». Собираем и исключаем.
|
||||
own = set()
|
||||
for probe in ("_case.md", ".agent/context/knowledge-map.md"):
|
||||
try:
|
||||
head = open(os.path.join(case_dir, probe), encoding="utf-8",
|
||||
errors="replace").read()
|
||||
except OSError:
|
||||
continue
|
||||
own |= set(PATTERNS["СОЮ"].findall(head))
|
||||
own |= set(PATTERNS["Арбитраж"].findall(head))
|
||||
own = own_numbers(case_dir)
|
||||
for pattern in SOURCE_GLOBS:
|
||||
for path in glob.glob(os.path.join(case_dir, pattern)):
|
||||
try:
|
||||
@@ -106,6 +143,353 @@ def already_in_index(index_path: str) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
def _atomic_write(path: str, text: str) -> None:
|
||||
parent = os.path.dirname(os.path.abspath(path))
|
||||
os.makedirs(parent, exist_ok=True)
|
||||
temporary = None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=parent,
|
||||
prefix=".practice-index.", suffix=".tmp",
|
||||
delete=False) as stream:
|
||||
temporary = stream.name
|
||||
stream.write(text)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
temporary = None
|
||||
finally:
|
||||
if temporary is not None:
|
||||
try:
|
||||
os.unlink(temporary)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
|
||||
def ensure_index(index_path: str) -> None:
|
||||
if os.path.islink(index_path):
|
||||
raise ValueError(f"индекс не может быть символьной ссылкой: {index_path}")
|
||||
if os.path.exists(index_path):
|
||||
if not os.path.isfile(index_path):
|
||||
raise ValueError(f"индекс не файл: {index_path}")
|
||||
return
|
||||
_atomic_write(index_path, INDEX_HEADER)
|
||||
|
||||
|
||||
def _clean_markdown(value: str, limit: int) -> str:
|
||||
value = re.sub(r"\[([^]]+)]\([^)]+\)", r"\1", value)
|
||||
value = re.sub(r"[*_`#]", "", value)
|
||||
value = " ".join(value.strip(" |-—\t").split())
|
||||
return value[:limit].rstrip()
|
||||
|
||||
|
||||
_PRIVATE_FIELD_RE = re.compile(
|
||||
r"(?im)^\s*(?:[-*]\s*)?(?:\*\*)?(?:ФИО|Адрес[^:*\n]{0,40}|Телефон[^:*\n]{0,20}|"
|
||||
r"E-?mail|Почта|Паспорт[^:*\n]{0,20}|ИНН|СНИЛС|Дата рождения)(?:\*\*)?\s*:\s*(.+)$")
|
||||
_PHONE_RE = re.compile(r"(?<!\d)(?:\+7|8)[\s(-]*\d{3}[\s)-]*\d{3}[\s-]*\d{2}[\s-]*\d{2}(?!\d)")
|
||||
_EMAIL_RE = re.compile(r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+")
|
||||
# ПД без профиля: распознаются по форме, а не по значению из _client.md.
|
||||
_GENERIC_PRIVATE_RES = (
|
||||
# Фамилия Имя Отчество / Имя Отчество в любом падеже.
|
||||
re.compile(r"(?:[А-ЯЁ][а-яё]+\s+){1,2}(?!Верховн)[А-ЯЁ][а-яё]+"
|
||||
r"(?:ич(?:а|у|ем|е)?|[оеё]вн(?:а|ы|е|у|ой)|ичн(?:а|ы|е|у|ой))(?![а-яё])"),
|
||||
# Фамилия И.О. и И.О. Фамилия.
|
||||
re.compile(r"[А-ЯЁ][а-яё]+\s+[А-ЯЁ]\.\s?(?:[А-ЯЁ]\.)?"),
|
||||
re.compile(r"(?<![А-Яа-яЁё])[А-ЯЁ]\.\s?(?:[А-ЯЁ]\.\s?)?[А-ЯЁ][а-яё]+"),
|
||||
# Паспорт, ИНН физлица, СНИЛС.
|
||||
re.compile(r"(?<!\d)\d{2}\s?\d{2}\s?\d{6}(?!\d)"),
|
||||
re.compile(r"(?<!\d)\d{12}(?!\d)"),
|
||||
re.compile(r"(?<!\d)\d{3}-\d{3}-\d{3}[\s-]?\d{2}(?!\d)"),
|
||||
# Дата рождения цифрами или словами.
|
||||
re.compile(r"(?i)(?:дат\w*\s+рождения|родил(?:ся|ась)|родивш\w+)\s*[:—-]?\s*[^,.;\n]{0,80}"),
|
||||
re.compile(r"(?i)(?:\d{1,2}\.\d{2}\.)?\d{4}\s*(?:г(?:ода|\.)?\s*)?р(?:ождения|\.)"),
|
||||
# Адрес: поле «адрес:», город, улица с номером дома, дом, корпус, квартира.
|
||||
re.compile(r"(?i:адрес\w*)\s*:\s*[^—;\n]{1,120}"),
|
||||
re.compile(r"(?<!\d)(?<!\d )\b(?i:г|гор|город|пос|пгт|село|дер)\.?\s+[А-ЯЁ][а-яё-]+"),
|
||||
re.compile(r"\b(?i:ул|улица|пр-т|проспект|пер|переулок|б-р|бульвар|шоссе|наб|"
|
||||
r"набережная|пл|площадь|мкр|микрорайон|проезд|тракт)\.?\s+"
|
||||
r"[А-ЯЁ0-9][\w-]*(?:\s+[А-ЯЁ][\w-]*)?(?:,?\s*\d+[А-Яа-я]?(?:/\d+)?)?"),
|
||||
re.compile(r"\b(?i:д|дом[аеу]?|корп|корпус[аеу]?|стр|строени[еия]|кв|квартир[аеуы]|оф|офис[аеу]?)\.?\s*№?\s*"
|
||||
r"\d+[А-Яа-я]?(?:/\d+)?"),
|
||||
)
|
||||
_MONTHS = ("января", "февраля", "марта", "апреля", "мая", "июня", "июля",
|
||||
"августа", "сентября", "октября", "ноября", "декабря")
|
||||
|
||||
|
||||
def _client_private_values(case_dir: str) -> tuple[str, ...]:
|
||||
"""Точные значения и основы слов из профиля доверителя: ФИО и адрес склоняются."""
|
||||
path = os.path.join(os.path.dirname(case_dir), "_client.md")
|
||||
if os.path.islink(path) or not os.path.isfile(path):
|
||||
return ()
|
||||
text = open(path, encoding="utf-8", errors="replace").read()
|
||||
values = _PRIVATE_FIELD_RE.findall(text)
|
||||
heading = re.search(r"(?m)^#\s+(.+)$", text)
|
||||
if heading:
|
||||
title = re.sub(r"^Профиль:\s*", "", heading.group(1), flags=re.IGNORECASE)
|
||||
if len(title.split()) >= 2:
|
||||
values.append(title)
|
||||
cleaned = []
|
||||
for value in values:
|
||||
value = re.sub(r"\s+\([^()]*\)\s*$", "", _clean_markdown(value, 500))
|
||||
if not value:
|
||||
continue
|
||||
cleaned.append(value)
|
||||
for day, month, year in re.findall(r"\b(\d{2})\.(\d{2})\.(\d{4})\b", value):
|
||||
if 1 <= int(month) <= 12:
|
||||
cleaned.append(f"{int(day)} {_MONTHS[int(month) - 1]} {year}")
|
||||
# ponytail: основа = слово без конечных гласных; редкие чередования
|
||||
# (Лев → Льва) не ловит, апгрейд — морфология pymorphy.
|
||||
for word in re.findall(r"[А-ЯЁA-Z][А-Яа-яЁёA-Za-z-]{2,}", value):
|
||||
stem = re.sub(r"[аеёиоуыэюяйь]+$", "", word, flags=re.IGNORECASE)
|
||||
cleaned.append(stem if len(stem) >= 3 else word)
|
||||
return tuple(dict.fromkeys(cleaned))
|
||||
|
||||
|
||||
def _private_pattern(private: str) -> str:
|
||||
"""Значение с цифрами сверяется по цифрам: пробелы и дефисы между ними не важны."""
|
||||
digits = re.sub(r"\D", "", private)
|
||||
if len(digits) >= 5 and not re.search(r"[^\W\d_]", private):
|
||||
return r"(?<!\d)" + r"[\s()+./-]*".join(digits) + r"(?!\d)"
|
||||
return rf"(?<![\w-]){re.escape(private)}[А-Яа-яЁё]{{0,4}}(?![\w-])"
|
||||
|
||||
|
||||
def _redact_private(value: str, private_values: tuple[str, ...]) -> str:
|
||||
mask = "[данные доверителя]"
|
||||
for private in sorted(private_values, key=len, reverse=True):
|
||||
value = re.sub(_private_pattern(private), mask, value, flags=re.IGNORECASE)
|
||||
value = _EMAIL_RE.sub(mask, _PHONE_RE.sub(mask, value))
|
||||
for pattern in _GENERIC_PRIVATE_RES:
|
||||
value = pattern.sub(mask, value)
|
||||
return value
|
||||
|
||||
|
||||
def _norm_number(number: str) -> str:
|
||||
return re.sub(r"[-‑‒–—]", "-", number.strip().lstrip("№").strip().rstrip(".")).upper()
|
||||
|
||||
|
||||
_DATE_RE = re.compile(r"\b\d{2}\.\d{2}\.\d{4}\b")
|
||||
_RECEIPT_RE = re.compile(r"(?:verify_act\.py|первоисточник\s*:)[^\n|]{0,80}", re.IGNORECASE)
|
||||
# Номер акта в квитанции и без знака №: 9-КГ24-99, 2-1234/2023, А65-1/2024, 6-П.
|
||||
_NUMBER_TOKEN_RE = re.compile(r"(?<![\w./-])(?:[А-ЯA-Z]\d{2}-|\d)\w*(?:[-‑‒–—/]\w+)+")
|
||||
|
||||
|
||||
def _verified(region: str, number: str, date: str) -> bool:
|
||||
"""Подтверждение относится к акту, только если стоит в его же отрезке текста,
|
||||
не называет чужой номер и чужую дату акта."""
|
||||
if (UNVERIFIED_RE.search(region) or FORBIDDEN_SECTION_RE.search(region)
|
||||
or not VERIFIED_RE.search(region)):
|
||||
return False
|
||||
if any(_norm_number(other) != number
|
||||
for other in re.findall(r"№\s*([0-9А-Яа-яA-Za-z][^\s,;()|]*)", region)):
|
||||
return False
|
||||
receipts = _RECEIPT_RE.findall(region)
|
||||
if any(_norm_number(token) != number
|
||||
for chunk in receipts for token in _NUMBER_TOKEN_RE.findall(chunk)):
|
||||
return False
|
||||
# Дата рядом с номером акта и дата внутри квитанции verify_act.py — дата акта.
|
||||
near = [region[max(0, m.start() - 40):m.end() + 40]
|
||||
for m in re.finditer(re.escape(number).replace("-", "[-‑‒–—]"), region,
|
||||
re.IGNORECASE)]
|
||||
# Дата проверки в «Первоисточник: подтверждено (…, дата)» — не дата акта.
|
||||
near += [chunk for chunk in receipts if chunk.lower().startswith("verify_act")]
|
||||
return all(found == date for chunk in near for found in _DATE_RE.findall(chunk))
|
||||
|
||||
|
||||
def _identity(match: re.Match) -> tuple[str, str]:
|
||||
return (_norm_number(match.group("number") or match.group("number2")),
|
||||
match.group("date") or match.group("date2"))
|
||||
|
||||
|
||||
def _index_identities(text: str) -> set[tuple[str, str]]:
|
||||
identities = {_identity(match) for match in ACT_RE.finditer(text)}
|
||||
number_re = re.compile(
|
||||
r"\b(?:А\d{2}-\d+/\d{4}|\d{1,2}-\d{2,6}/\d{4}|"
|
||||
r"\d{1,3}-(?:КГ|КАД|КАС|АД|ЭС|УД)\d{2}-"
|
||||
r"\d+(?:-К\d+)?)\b", re.IGNORECASE)
|
||||
for block in re.split(r"(?m)^###\s+", text)[1:]:
|
||||
field = re.search(r"(?im)^\s*-\s*\*\*(?:Дело|Акт):\*\*\s*(.+)$", block)
|
||||
if not field:
|
||||
continue
|
||||
value = field.group(1)
|
||||
dates = re.findall(r"\b\d{2}\.\d{2}\.\d{4}\b", value)
|
||||
if not dates:
|
||||
continue
|
||||
numbers = number_re.findall(value) or re.findall(r"№\s*([^\s,;/|]+)", value)
|
||||
first = value.split("/")[0].strip()
|
||||
if not numbers and "/" in value and re.fullmatch(r"№?\s*[0-9][0-9А-Яа-яA-Za-z-]*", first):
|
||||
numbers = [first] # старый формат «Дело: 25 / Пленум ВС РФ / дата»
|
||||
if not numbers:
|
||||
numbers = re.findall(r"№\s*([0-9][0-9А-Яа-яA-Za-z-]*)", block)
|
||||
identities.update((_norm_number(number), dates[0]) for number in numbers)
|
||||
return identities
|
||||
|
||||
|
||||
def _occurrences(text: str) -> list[dict]:
|
||||
"""Каждое упоминание акта: раздел, отрезок текста и запрет.
|
||||
|
||||
Отрезок — от начала строки акта (и строк абзаца перед первым актом) до
|
||||
следующего акта или заголовка. Абзац без актов после пустой строки дописывается
|
||||
к акту выше, только если тот один; отрицательный статус в таком абзаце
|
||||
поражает все акты выше. Под «НЕ ЦИТИРОВАТЬ до проверки» и под заголовком
|
||||
с отрицательным статусом акт запрещен до заголовка того же или старшего уровня."""
|
||||
text = re.sub(r"[*`]", "", text) # жирный и код не прячут реквизиты и поля
|
||||
section, forbidden_level, previous, found = "Прочее", 0, [], []
|
||||
for paragraph in re.split(r"\n\s*\n", text):
|
||||
for part in re.split(r"(?m)^(?=#{1,6}\s)", paragraph):
|
||||
heading = re.match(r"(#{1,6})\s+(.+)", part)
|
||||
if heading:
|
||||
level, title = len(heading.group(1)), _clean_markdown(heading.group(2), 120)
|
||||
if forbidden_level and level <= forbidden_level:
|
||||
forbidden_level = 0
|
||||
matches = list(ACT_RE.finditer(title))
|
||||
if not matches and (FORBIDDEN_SECTION_RE.search(title)
|
||||
or UNVERIFIED_RE.search(title)):
|
||||
forbidden_level = forbidden_level or level
|
||||
elif level <= 2 and not matches:
|
||||
section = title or "Прочее"
|
||||
previous = []
|
||||
matches = list(ACT_RE.finditer(part))
|
||||
label = FORBIDDEN_SECTION_RE.search(part)
|
||||
if not matches:
|
||||
if previous and not heading:
|
||||
if UNVERIFIED_RE.search(part) or label:
|
||||
for item in previous:
|
||||
item["negative"] = True
|
||||
elif len(previous) == 1:
|
||||
previous[0]["region"] += "\n" + part
|
||||
if label:
|
||||
forbidden_level = forbidden_level or 6
|
||||
continue
|
||||
current = []
|
||||
for i, match in enumerate(matches):
|
||||
start = 0 if i == 0 else part.rfind("\n", 0, match.start()) + 1
|
||||
end = matches[i + 1].start() if i + 1 < len(matches) else len(part)
|
||||
item = {"section": section, "region": part[start:end], "match": match,
|
||||
"negative": False,
|
||||
"forbidden": bool(forbidden_level
|
||||
or (label and label.start() < match.start()))}
|
||||
current.append(item)
|
||||
if len(current) > 1 and UNVERIFIED_RE.search(part[:matches[0].start()]):
|
||||
for item in current:
|
||||
item["negative"] = True
|
||||
found += current
|
||||
previous = current
|
||||
if label:
|
||||
forbidden_level = forbidden_level or 6
|
||||
return found
|
||||
|
||||
|
||||
def _position(region: str, match: re.Match) -> str:
|
||||
explicit = re.search(r"(?im)^\s*[-|]?\s*Позиция:\s*(.+)$", region)
|
||||
if explicit:
|
||||
return _clean_markdown(explicit.group(1).split("|")[0], 600)
|
||||
full = match.group("full")
|
||||
tail = region[region.find(full) + len(full):].split("\n")[0]
|
||||
tail = re.split(r"(?:[—|;,]\s*)?(?:Первоисточник|Статус|verify_act\.py)",
|
||||
tail, maxsplit=1, flags=re.IGNORECASE)[0]
|
||||
tail = re.sub(r"(?i)\bподтвержден\w*", "", tail)
|
||||
tail = _clean_markdown(tail, 600)
|
||||
return tail if re.search(r"[^\W\d_]{3}", tail) else ""
|
||||
|
||||
|
||||
def _is_receipt(region: str, match: re.Match) -> bool:
|
||||
"""Реквизиты внутри квитанции проверки — подтверждение, а не правовая позиция."""
|
||||
prefix = region[:region.find(match.group("full"))].rsplit("\n", 1)[-1]
|
||||
return bool(re.search(r"verify_act\.py|первоисточник", prefix, re.IGNORECASE))
|
||||
|
||||
|
||||
def verified_records(practice_path: str, private_values: tuple[str, ...] = (),
|
||||
own: frozenset[str] = frozenset()) -> list[dict[str, str]]:
|
||||
if os.path.islink(practice_path) or not os.path.isfile(practice_path):
|
||||
raise ValueError(f"practice.md не найден или небезопасен: {practice_path}")
|
||||
text = open(practice_path, encoding="utf-8", errors="replace").read()
|
||||
records, banned = {}, set()
|
||||
for occurrence in _occurrences(text):
|
||||
region, match = occurrence["region"], occurrence["match"]
|
||||
identity = _identity(match)
|
||||
# Любое упоминание с запретом или отрицательным статусом снимает акт целиком.
|
||||
if (identity[0] in own or occurrence["forbidden"] or occurrence["negative"]
|
||||
or UNVERIFIED_RE.search(region) or FORBIDDEN_SECTION_RE.search(region)):
|
||||
banned.add(identity)
|
||||
continue
|
||||
verified = _verified(region, *identity)
|
||||
position = "" if _is_receipt(region, match) else _position(region, match)
|
||||
current = records.get(identity)
|
||||
if current is not None:
|
||||
current["verified"] = current["verified"] or verified
|
||||
if verified and re.search(r"verify_act\.py", region, re.IGNORECASE):
|
||||
current["verification"] = "verify_act.py: ПОДТВЕРЖДЕН"
|
||||
if current["position"] or not position:
|
||||
continue
|
||||
category_match = re.search(r"(?im)^\s*[-|]?\s*Категория:\s*(.+)$", region)
|
||||
category = (_clean_markdown(category_match.group(1).split("|")[0], 120)
|
||||
if category_match else occurrence["section"])
|
||||
if any(token in category.lower() for token in GENERIC_SECTIONS):
|
||||
category = "Прочее"
|
||||
item = {
|
||||
"key": identity,
|
||||
"act": _redact_private(_clean_markdown(match.group("full"), 260), private_values),
|
||||
"number": identity[0],
|
||||
"date": identity[1],
|
||||
"category": _redact_private(category, private_values),
|
||||
"position": _redact_private(position, private_values),
|
||||
"verified": verified or bool(current and current["verified"]),
|
||||
"verification": (current["verification"] if current else
|
||||
"verify_act.py: ПОДТВЕРЖДЕН"
|
||||
if verified and re.search(r"verify_act\.py", region, re.I)
|
||||
else "первоисточник подтвержден охотой"),
|
||||
}
|
||||
records[identity] = item
|
||||
return [item for key, item in records.items()
|
||||
if item["verified"] and item["position"] and key not in banned]
|
||||
|
||||
|
||||
def _append_record(text: str, item: dict[str, str]) -> str:
|
||||
today = datetime.now().strftime("%d.%m.%Y")
|
||||
entry = (f"### {item['act']}\n"
|
||||
f"- **Акт:** {item['act']}\n"
|
||||
f"- **Категория:** {item['category']}\n"
|
||||
f"- **Позиция:** {item['position']}\n"
|
||||
f"- **Актуальность:** ✓ актуально\n"
|
||||
f"- **Источник:** `.agent/context/practice.md`; "
|
||||
f"{item['verification']}\n"
|
||||
f"- **Добавлено:** {today}\n")
|
||||
heading = f"## {item['category']}"
|
||||
found = re.search(rf"(?m)^{re.escape(heading)}\s*$", text)
|
||||
if not found:
|
||||
return text.rstrip() + f"\n\n{heading}\n\n{entry}"
|
||||
following = re.search(r"(?m)^##\s+", text[found.end():])
|
||||
end = found.end() + following.start() if following else len(text)
|
||||
return text[:end].rstrip() + "\n\n" + entry + "\n" + text[end:].lstrip("\n")
|
||||
|
||||
|
||||
def apply_case(case_dir: str, index_path: str) -> tuple[int, int]:
|
||||
case_dir = os.path.abspath(case_dir)
|
||||
if not os.path.isdir(case_dir) or os.path.islink(case_dir):
|
||||
raise ValueError(f"дело не найдено или небезопасно: {case_dir}")
|
||||
own = own_numbers(case_dir)
|
||||
records = verified_records(
|
||||
os.path.join(case_dir, ".agent/context/practice.md"),
|
||||
_client_private_values(case_dir) + tuple(own),
|
||||
frozenset(_norm_number(number) for number in own))
|
||||
index_existed = os.path.exists(index_path)
|
||||
ensure_index(index_path)
|
||||
text = already_in_index(index_path)
|
||||
existing = _index_identities(text)
|
||||
added = duplicate = 0
|
||||
for item in records:
|
||||
if item["key"] in existing:
|
||||
duplicate += 1
|
||||
continue
|
||||
text = _append_record(text, item)
|
||||
existing.add(item["key"])
|
||||
added += 1
|
||||
if added:
|
||||
_atomic_write(index_path, text.rstrip() + "\n")
|
||||
if added or not index_existed:
|
||||
sync_header(index_path)
|
||||
return added, duplicate
|
||||
|
||||
|
||||
# Номер дела первой инстанции — персональные данные, а не практика. По нему
|
||||
# открывается карточка на портале суда: стороны, предмет, движение. Номер, который
|
||||
# встретился РОВНО В ОДНОМ деле, почти всегда номер собственного производства
|
||||
@@ -183,16 +567,24 @@ def audit_index(index_path: str) -> list[str]:
|
||||
def sync_header(index_path: str) -> list[str]:
|
||||
"""Счетчики шапки и оглавления — с диска. Шапка обещала 101 запись при 82 на диске,
|
||||
и каждый агент, читавший базу, исходил из чужого числа."""
|
||||
ensure_index(index_path)
|
||||
text = already_in_index(index_path)
|
||||
if not text:
|
||||
return [f"{index_path}: не читается"]
|
||||
entries = re.findall(r"(?m)^### (.+)$", text)
|
||||
changed = []
|
||||
|
||||
new, n = re.subn(r"(Записей:\s*)\d+", lambda m: m.group(1) + str(len(entries)), text, count=1)
|
||||
if n and new != text:
|
||||
header = (f"_Обновлено: {datetime.now().strftime('%d.%m.%Y')} | "
|
||||
f"Записей: {len(entries)}_")
|
||||
new, n = re.subn(r"(?m)^_Обновлено:.*\|\s*Записей:\s*\d+_$",
|
||||
header, text, count=1)
|
||||
if n:
|
||||
if new != text:
|
||||
changed.append(f"шапка: записей → {len(entries)}")
|
||||
text = new
|
||||
else:
|
||||
first = re.search(r"(?m)^# .+$", text)
|
||||
at = first.end() if first else 0
|
||||
text = text[:at] + f"\n\n{header}" + text[at:]
|
||||
changed.append(f"шапка: записей → {len(entries)}")
|
||||
text = new
|
||||
|
||||
# счетчики по категориям в таблице «Содержание»
|
||||
per: dict[str, int] = {}
|
||||
@@ -222,7 +614,7 @@ def sync_header(index_path: str) -> list[str]:
|
||||
text)
|
||||
|
||||
if changed:
|
||||
open(index_path, "w", encoding="utf-8").write(text)
|
||||
_atomic_write(index_path, text)
|
||||
return changed
|
||||
|
||||
|
||||
@@ -329,6 +721,8 @@ def main() -> int:
|
||||
ap = argparse.ArgumentParser(description="Сбор практики из дел и аудит базы")
|
||||
ap.add_argument("--cases", default="cases")
|
||||
ap.add_argument("--index", default="knowledge/practice_index.md")
|
||||
ap.add_argument("--apply", metavar="CASE",
|
||||
help="внести подтвержденные акты из practice.md дела")
|
||||
ap.add_argument("--audit", action="store_true", help="проверить качество самой базы")
|
||||
ap.add_argument("--sync-header", action="store_true",
|
||||
help="привести счетчики шапки и оглавления к тому, что на диске")
|
||||
@@ -342,6 +736,15 @@ def main() -> int:
|
||||
if a.selftest:
|
||||
return selftest()
|
||||
|
||||
if a.apply:
|
||||
try:
|
||||
added, duplicate = apply_case(a.apply, a.index)
|
||||
except (OSError, UnicodeError, ValueError) as exc:
|
||||
print(f"ERROR: {exc}", file=sys.stderr)
|
||||
return 2
|
||||
print(f"внесено {added}, уже было {duplicate}")
|
||||
return 0
|
||||
|
||||
if a.sync_header:
|
||||
for line in sync_header(a.index) or ["счетчики уже сходятся"]:
|
||||
print(f" {line}")
|
||||
|
||||
Reference in New Issue
Block a user