Files
themiz/eunomia/practice.py
T

1564 lines
100 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Судебная практика СудАкта в Эвномии: хранилище, импорт из Lynceuz, чтение.
Корпус собирает Lynceuz; Themiz на sudact.ru не ходит. Импорт читает только
`corpus export` и сверяет каждый текст с SHA-256 экспорта до записи; повторный
импорт того же файла ничего не меняет. Связи «акт - статья» считает
legal_graph.article_refs: одна грамматика ссылок на весь дом. Хранилище
отдельное, потому что ~96 тыс. актов не помещаются узлами в JSON-снимок графа.
Слаги дел доверителей сюда не попадают: источник один - публичный экспорт.
python3 eunomia/practice.py install # задача launchd: каждый час, первый запуск сразу
python3 eunomia/practice.py status [--json]
python3 eunomia/practice.py tick [--force-build] # то, что задача делает раз в час
python3 eunomia/practice.py import [--full] [--export FILE]
python3 eunomia/practice.py classify # переотнести все акты к отраслям
python3 eunomia/practice.py uninstall
python3 eunomia/practice.py progress # доля скачанного СудАкта по диску, JSON
python3 eunomia/practice.py publish # локальная страница загрузки: .agent/maintenance/practice/status/
python3 eunomia/practice.py install --publish # задача launchd: publish раз в минуту
python3 eunomia/practice.py parts # параллельная докачка частями: один кусок 15 минут
python3 eunomia/practice.py install --parts # задача launchd: parts подряд, пока карта не пройдена
python3 eunomia/practice.py graph # общий граф права: нормы, пленумы и практика, graphify
"""
from __future__ import annotations
import argparse
import fcntl
import hashlib
import json
import os
import plistlib
import re
import shutil
import sqlite3
import string
import subprocess
import sys
import time
import zlib
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from contextlib import closing, contextmanager, redirect_stdout
from itertools import combinations
from datetime import UTC, datetime, timedelta
from pathlib import Path
CODE_ROOT = Path(__file__).resolve().parents[1]
if str(CODE_ROOT / 'scripts') not in sys.path: # launchd запускает файл напрямую
sys.path.insert(0, str(CODE_ROOT / 'scripts'))
import legal_graph # noqa: E402
from legal_graph import CODE_NAME_RE, CODE_NAMES, _original, short_codes # noqa: E402,F401
from practice_search import dot_date, identify_act, parse_court_line # noqa: E402
STATE_REL = Path('.agent/maintenance/practice')
LABEL = 'com.themiz.practice'
HOUR, DAY, WEEK = timedelta(hours=1), timedelta(days=1), timedelta(days=7)
# Lynceuz ставит fetched_at до записи в журнал; при двух потоках запись может
# лечь позже более нового акта. Перекрытие --since ловит ее, повтор бесплатен.
OVERLAP = timedelta(hours=1)
# launchd не запускает задачу, пока идет прошлый запуск: сборка по 55 минут при часовом
# тике докачивает корпус почти без пауз, а новые акты попадают в Эвномию каждый час.
BUILD_SECONDS = 3300
# Без явных пределов Lynceuz берет свои: 100 страниц и 50 МБ за прогон, то есть 100 актов
# в час вместо тысяч (замер 02.10.2026). Пределы - из ручной сборки владельца 01.10.2026;
# прогон держит время.
BUILD_PAGES, BUILD_BYTES = 5000, 2_000_000_000
# Скорость. Быстрая - решение владельца 02.10.2026: до 10 запросов в секунду, куски по 15 минут,
# чтобы проверка на перегруз шла чаще. Вежливая - предел владельца от 01.10: до 2 в секунду.
# СудАкт отвечает за 1,7 с (медиана 4 415 запросов), отсюда число потоков.
FAST = {'concurrency': 20, 'delay': 0.1, 'seconds': 900}
POLITE = {'concurrency': 4, 'delay': 0.5, 'seconds': BUILD_SECONDS}
# Перегруз в быстром режиме - отказ сайта или больше 10% сбоев в куске: задача переходит на
# вежливую скорость и сама больше не ускоряется.
REFUSALS = {'rate_limited', 'access_denied', 'auth_required', 'captcha', 'paywall', 'paid_required'}
STRAIN_SHARE, STRAIN_MIN = 0.1, 20
DOWNLOADING = 'корпус докачивается, остались документы'
CHUNKS = 24 # кусков подряд в одном запуске: сутки докачки без часа простоя между кусками
# Сбой сети на robots.txt Lynceuz повторяет с паузами 30, 60 и 90 с, отказ 401/403/429 - нет.
# Стоп robots_denied позже этого срока - сеть, а не сайт.
# ponytail: причина выводится из длительности; точнее - когда Lynceuz запишет ее в манифест.
ROBOTS_NETWORK_SECONDS = 150
RETRIES = 3 # столько импортов подряд строка с отказом сверки приходит снова, потом - в отчет
MAX_TEXT_BYTES = 8 * 1024 * 1024
PAGE = 12
SCHEDULER_PATH = os.pathsep.join((str(Path(sys.executable).parent), '/usr/local/bin',
'/opt/homebrew/bin', '/usr/bin', '/bin', '/usr/sbin', '/sbin'))
# launchd не читает ~/.zshenv. Без пула fake-IP VPN Lynceuz видит адрес СудАкта
# непубличным и сам не выпускает запрос (policy_denied); замер 02.10.2026. install берет
# пул из оболочки, а без него - из прежнего задания: лишний пул безвреден, публичный
# ответ DNS в него не попадает.
# ponytail: значение застывает при install; сменился пул - повторить install.
SCHEDULER_ENV = ('LYNCEUZ_FAKE_IP_POOLS',)
# Тик launchd приходит на секунды раньше часа, а срок считается от конца сборки:
# без допуска повтор «через час» ждал бы второй тик.
TICK_SLACK = timedelta(minutes=5)
# Локальная страница загрузки (решение владельца 02.10.2026: смотреть с этого Mac): publish раз
# в минуту кладет страницу и status.js в .agent/maintenance/practice/status/. В state.json
# publish не пишет: его пишет идущая сборка без блокировки, второй писатель потерял бы ее ключи.
PUBLISH_LABEL = 'com.themiz.practice-status'
STATUS_PAGE = Path(__file__).with_name('status') / 'index.html'
SITEMAP_DOC_RE = re.compile(rb'<loc>https://sudact\.ru/[a-z]+/doc/')
SPEED_WINDOW = timedelta(minutes=10)
# Параллельная докачка (решение владельца 02.10.2026: до 1000 актов в минуту, ступенями). Один процесс
# Lynceuz упирается в себя, а не в СудАкт: ответ ~3,6 с и при 2, и при 16 запросах сразу, а в работе в
# среднем 7 запросов из 20 (замер 02.10.2026). Карта делится на PARTS частей по первой букве номера акта
# (62 буквы, по 1 465-1 649 актов на букву), у каждой свой корень данных: замок сборки Lynceuz - на корень.
# Шаг 0,6 с держит часть на 1,67 запроса в секунду: 5 частей - ~500 актов в минуту, 10 - ~1000.
# Сначала идут FIRST_PARTS частей; кусок без отказа СудАкта включает все.
PARTS, FIRST_PARTS = 10, 5
PART_PACE = {'concurrency': 10, 'delay': 0.6, 'seconds': 900}
PARTS_LABEL = 'com.themiz.practice-parts'
# Кнопка «Обновить судебные акты» в Эвномии (просьба владельца 03.10.2026): сервер кладет файл-просьбу, задача
# частей при следующем запуске (до минуты) снимает его и начинает обход. state.json пишет только задача частей.
REFRESH_REL = STATE_REL / 'parts' / 'refresh'
ID_CHARS = string.digits + string.ascii_uppercase + string.ascii_lowercase
WORKING = (DOWNLOADING, 'карта СудАкта пройдена', 'новых документов нет')
# Части прошли всю карту 03.10.2026. Основная сборка о них не знает и перекачала бы ~73 тыс. актов,
# поэтому, пока части не остановлены отказом СудАкта, она не качает, а только импортирует.
# Общий граф права (решение владельца 03.10.2026): нормативный граф legal_graph - кодексы, пленумы,
# индекс практики - и практика Эвномии одним graph.json в схеме graphify. Статья практики берет ID узла
# нормативного графа, поэтому статьи сливаются; акт узлом не становится (см. шапку модуля). Тексты
# норм в общий граф не идут: они в снимке legal_graph (523 МБ) и в Эвномии. Отдельно от графа кода.
GRAPH_REL = STATE_REL / 'graph' / 'graphify-out' / 'graph.json'
PRACTICE_FILES = ('eunomia/practice', 'eunomia/practice_taxonomy.json') # источник узлов и ребер практики
TOGETHER_MIN, AREA_MIN = 10, 3 # ребро: пару статей цитируют вместе столько актов, отрасль - столько
PARTS_LEAD = 'сборку ведут части (python3 eunomia/practice.py parts), основная не качает, чтобы не дублировать'
URL_RE = re.compile(r'https://sudact\.ru/([a-z]+)/doc/([A-Za-z0-9]{6,32})/')
DOC_RE = re.compile(r'[A-Za-z0-9]{6,32}')
HASH_RE = re.compile(r'sha256:([0-9a-f]{64})')
LINK_RE = re.compile(r'\[([^\]\n]*)\]\([^)\n]*\)')
KIND_RE = re.compile(r'^\s*(.+?)\s+(?:№|от\s+\d)')
SUBJECT_RE = re.compile(r'(?iu)\bпо\s+(?:административному\s+)?(?:исков\w+\s+заявлению|иску|заявлению|'
r'апелляционн\w+\s+(?:жалоб|представлени)\w+|частн\w+\s+жалоб\w+)[^.;]{20,360}')
CODE_RE = re.compile(r'[a-z0-9-]{2,40}')
ARTICLE_RE = re.compile(r'\d{1,4}(?:\.\d{1,3}){0,2}')
STOP = {'рф', 'ст', 'статья', 'статьи', 'статье', 'п', 'пункт', 'ч', 'часть', 'от', 'и', 'в',
'на', 'по', 'с', 'о', 'об', 'к', 'не', 'а', 'или'}
SHORT = {slug: name.upper() for name, slug in legal_graph.CODE_ALIASES.items()}
SHORT.update({'koap-rf': 'КоАП РФ', 'nk-rf-gosposhlina': 'НК РФ'})
SCHEMA = """
CREATE TABLE IF NOT EXISTS acts (
id INTEGER PRIMARY KEY, url TEXT NOT NULL UNIQUE, doc TEXT NOT NULL UNIQUE, section TEXT,
title TEXT, kind TEXT, number TEXT, act_date TEXT, court TEXT, area TEXT, category TEXT,
lastmod TEXT, fetched_at TEXT, text_sha256 TEXT, text_bytes INTEGER, source_sha256 TEXT,
removed_at TEXT, removed_code TEXT);
CREATE INDEX IF NOT EXISTS acts_date ON acts(act_date);
CREATE INDEX IF NOT EXISTS acts_court ON acts(court);
CREATE TABLE IF NOT EXISTS texts (id INTEGER PRIMARY KEY, body BLOB NOT NULL);
CREATE TABLE IF NOT EXISTS refs (act INTEGER NOT NULL, code TEXT NOT NULL, article TEXT NOT NULL,
PRIMARY KEY (act, code, article)) WITHOUT ROWID;
CREATE INDEX IF NOT EXISTS refs_article ON refs(code, article);
CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5(title, body, content='', contentless_delete=1,
tokenize='unicode61 remove_diacritics 2');
CREATE TABLE IF NOT EXISTS cats (act INTEGER NOT NULL, node TEXT NOT NULL, reason TEXT,
PRIMARY KEY (act, node)) WITHOUT ROWID;
CREATE INDEX IF NOT EXISTS cats_node ON cats(node);
CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);
"""
TAXONOMY = Path(__file__).with_name('practice_taxonomy.json')
NODE_RE = re.compile(r'[a-z0-9-]{1,40}')
CLAIM_MARK_RE = re.compile(r'(?iu)с\s+иском|по\s+иску|исков\w*\s+заявлени\w*|встречн\w*\s+иск\w*|(?:по|с)\s+заявлени\w*|обратил\w*\s+в\s+суд')
# ponytail: предмет требования ищется в 300 знаках после «иск», «заявление», «обратился в суд»
# в первых 6000 знаках акта; глубже идут чужие требования и цитаты. Неточно на
# актах без этих слов - тогда работают статьи главы кодекса.
HEAD_CHARS, ZONE_CHARS = 6000, 300
BATCH = 500 # строк экспорта на коммит
CLASSIFIER_VERSION = '2' # меняется вместе с правилами кода: смена переотносит все акты
class PracticeError(RuntimeError):
pass
def stamp(value: datetime | None = None) -> str:
return (value or datetime.now(UTC)).isoformat(timespec='seconds').replace('+00:00', 'Z')
def parse_time(value: object) -> datetime | None:
try:
parsed = datetime.fromisoformat(str(value))
except ValueError:
return None
return parsed if parsed.tzinfo else None
def fold(text: str) -> str:
return text.replace('ё', 'е').replace('Ё', 'Е')
def lynceuz_home() -> Path:
return Path(os.environ.get('LYNCEUZ_HOME', str(Path.home() / 'Проекты' / 'lynceuz')))
def default_data_root() -> Path:
return Path(os.environ.get('THEMIZ_PRACTICE_DATA', str(lynceuz_home() / '.lynceuz/practice/.lynceuz')))
def label(code: str, article: str) -> str:
return f'ст. {article} {SHORT.get(code, code)}'
def citations(text: str) -> list[tuple[int, int, str, str]]:
"""[(начало, конец, кодекс, статья)] в координатах исходного текста; без кодекса не связываем."""
short, marks = short_codes(text)
return [(_original(start, marks), _original(end, marks), slug, number)
for start, end, number, slug in legal_graph.article_refs(short) if slug]
def split_text(text: str) -> tuple[str, str, str]:
"""Страница СудАкта → (заголовок, строка суда, текст акта) без меню и подвала сайта."""
start = text.find('\n# ')
if start < 0:
return '', '', text.strip()
rest = text[start + 3:]
end = rest.find('\n### Суд:')
heading, _, rest = (rest if end < 0 else rest[:end]).partition('\n')
first, _, body = rest.lstrip('\n').partition('\n')
if not first.lstrip().startswith('['):
return heading.strip(), '', rest.strip()
return heading.strip(), LINK_RE.sub(r'\1', first).strip(), body.strip()
def describe(row: dict, text: str) -> tuple[dict, str]:
"""Реквизиты акта разбирают общие разборщики Themiz (practice_search), не второй парсер."""
heading, court_line, body = split_text(text)
title = str(row.get('title') or '').removesuffix(':: СудАкт.ру').strip() or heading
kind = KIND_RE.match(title)
found = identify_act({'title': title, 'url': row['url']}, section=row.get('section') or '',
source='lynceuz') or {}
day = found.get('date') or dot_date(title)
court = parse_court_line(court_line) if court_line else {}
return {'title': title, 'kind': kind[1] if kind else 'Судебный акт',
'number': found.get('number') or '',
'act_date': '-'.join(reversed(day.split('.'))) if day else None,
'court': court.get('court') or None, 'area': court.get('area') or None,
'category': court.get('category') or None}, body
def state_path(root: Path) -> Path:
return Path(root) / STATE_REL / 'state.json'
def read_state(root: Path) -> dict:
try:
value = json.loads(state_path(root).read_text(encoding='utf-8'))
except FileNotFoundError:
return {'schema': 1}
if not isinstance(value, dict) or value.get('schema') != 1:
raise PracticeError('поврежден файл состояния практики; он не перезаписан')
return value
def update_state(root: Path, key: str, value: dict) -> None:
state = read_state(root)
state[key] = value
path = state_path(root)
path.parent.mkdir(parents=True, exist_ok=True)
temp = path.with_suffix('.tmp')
temp.write_text(json.dumps(state, ensure_ascii=False, indent=1), encoding='utf-8')
os.replace(temp, path)
@contextmanager
def _lock(root: Path, name: str, busy: str = 'импорт практики уже идет'):
directory = Path(root) / STATE_REL
directory.mkdir(parents=True, exist_ok=True)
with (directory / name).open('a+') as handle:
try:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
raise PracticeError(busy) from None
try:
yield
finally:
fcntl.flock(handle, fcntl.LOCK_UN)
def _writer(root: Path) -> sqlite3.Connection:
path = Path(root) / STATE_REL / 'practice.sqlite3'
path.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(path, timeout=30, isolation_level=None)
conn.row_factory = sqlite3.Row
conn.execute('PRAGMA journal_mode=WAL')
conn.executescript(SCHEMA)
return conn
def _inside(base: Path, relative: object) -> Path:
rel = str(relative or '')
path = (base / rel).resolve()
if not rel or '\0' in rel or Path(rel).is_absolute() or not path.is_relative_to(base):
raise ValueError('путь вне корня данных Lynceuz')
return path
def _verified(data_root: Path, ref: dict, digest: str) -> bytes:
size = ref.get('bytes')
if type(size) is not int or not 0 < size <= MAX_TEXT_BYTES:
raise ValueError('недопустимый размер текста')
with _inside(data_root, ref.get('path')).open('rb') as handle:
raw = handle.read(MAX_TEXT_BYTES + 1)
if len(raw) != size or hashlib.sha256(raw).hexdigest() != digest:
raise ValueError('SHA-256 текста не совпал с экспортом')
return raw
def _at(value: object) -> str:
if not isinstance(value, str) or parse_time(value) is None:
raise ValueError('нет времени записи')
return value
def _apply(conn: sqlite3.Connection, row: dict, data_root: Path) -> tuple[str, str | None]:
if not isinstance(row, dict) or row.get('v') != 1:
raise ValueError('неизвестная версия строки экспорта')
match = URL_RE.fullmatch(str(row.get('url', '')))
if row.get('host') != 'sudact.ru' or not match:
return 'skipped', None, None
url, doc = match[0], match[2]
old = conn.execute('SELECT id, text_sha256, fetched_at, removed_at FROM acts WHERE url = ?',
(url,)).fetchone()
if row.get('removed') is True:
at = _at(row.get('at'))
if old and ((old['removed_at'] or '') >= at or (old['fetched_at'] or '') > at):
return 'unchanged', at, None
if old:
conn.execute('UPDATE acts SET removed_at = ?, removed_code = ? WHERE id = ?',
(at, str(row.get('code') or ''), old['id']))
conn.execute('DELETE FROM fts WHERE rowid = ?', (old['id'],))
# Удаленный акт не считается ни в статьях, ни в отраслях; счет идет по индексу без соединения.
conn.execute('DELETE FROM refs WHERE act = ?', (old['id'],))
conn.execute('DELETE FROM cats WHERE act = ?', (old['id'],))
else:
conn.execute('INSERT INTO acts (url, doc, section, removed_at, removed_code) VALUES (?, ?, ?, ?, ?)',
(url, doc, match[1], at, str(row.get('code') or '')))
return 'removed', at, None
fetched = _at(row.get('fetched_at'))
text = row.get('text') if isinstance(row.get('text'), dict) else {}
source = row.get('source') if isinstance(row.get('source'), dict) else {}
digest = HASH_RE.fullmatch(str(text.get('hash', '')))
if not digest:
raise ValueError('нет SHA-256 текста')
if old and ((old['fetched_at'] or '') > fetched or (old['removed_at'] or '') >= fetched):
return 'unchanged', fetched, None # старый экспорт не воскрешает удаленный позже акт
if old and old['text_sha256'] == digest[1] and not old['removed_at']:
return 'unchanged', fetched, None
raw = _verified(data_root, text, digest[1])
meta, body = describe({**row, 'url': url}, raw.decode('utf-8'))
source_hash = HASH_RE.fullmatch(str(source.get('hash', '')))
values = (match[1], meta['title'], meta['kind'], meta['number'], meta['act_date'], meta['court'],
meta['area'], meta['category'], str(row.get('lastmod') or '') or None, fetched, digest[1],
len(raw), source_hash[1] if source_hash else None)
if old:
act = old['id']
conn.execute('UPDATE acts SET section=?, title=?, kind=?, number=?, act_date=?, court=?, area=?, '
'category=?, lastmod=?, fetched_at=?, text_sha256=?, text_bytes=?, source_sha256=?, '
'removed_at=NULL, removed_code=NULL WHERE id=?', (*values, act))
conn.execute('DELETE FROM fts WHERE rowid = ?', (act,))
conn.execute('DELETE FROM refs WHERE act = ?', (act,))
else:
act = conn.execute('INSERT INTO acts (url, doc, section, title, kind, number, act_date, court, area, '
'category, lastmod, fetched_at, text_sha256, text_bytes, source_sha256) '
'VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', (url, doc, *values)).lastrowid
conn.execute('INSERT OR REPLACE INTO texts (id, body) VALUES (?, ?)', (act, zlib.compress(raw, 3)))
conn.execute('INSERT INTO fts (rowid, title, body) VALUES (?, ?, ?)', (act, fold(meta['title']), fold(body)))
conn.executemany('INSERT OR IGNORE INTO refs (act, code, article) VALUES (?, ?, ?)',
{(act, code, article) for _, _, code, article in citations(body)})
return ('updated' if old else 'added'), fetched, act
def code_chapters(root: Path, code: str) -> dict[str, str]:
"""{номер статьи: «Глава N»} из текста кодекса в корпусе Themiz; нет текста - пусто."""
try:
import corpus_registry
resource = next((item for item in corpus_registry.registry(Path(root))
if item.get('id') == f'legal-corpus:code:{code}'), None)
text = legal_graph._source_path(Path(root), resource['output']).read_text(encoding='utf-8') if resource else ''
except (OSError, ValueError, KeyError, TypeError):
return {}
chapters, current = {}, None
for line in text.splitlines():
heading = re.match(r'#{1,6}\s+(Глава\s+\d+(?:\.\d+)*)', line)
if heading:
current = heading[1]
continue
article = re.match(r'#{1,6}\s+Статья\s+(\d+(?:\.\d+)*)', line)
if article and current:
chapters[article[1]] = current
return chapters
def taxonomy(root: Path) -> dict:
"""Дерево отраслей с собранными правилами; отпечаток меняется вместе с деревом и главами."""
raw = TAXONOMY.read_bytes()
digest, areas = hashlib.sha256(raw + CLASSIFIER_VERSION.encode()), []
for area in json.loads(raw)['areas']:
chapters = code_chapters(root, area['code'])
digest.update(json.dumps(chapters, sort_keys=True, ensure_ascii=False).encode())
children = [{**child, 'articles': {a for a, ch in chapters.items() if ch in set(child.get('chapters', []))},
'claim': re.compile('|'.join(f'(?:{p})' for p in child.get('claims', [])) or '(?!)', re.I)}
for child in area['children']]
areas.append({**area, 'children': children, 'chapters_found': bool(chapters)})
return {'areas': areas, 'fingerprint': digest.hexdigest()}
def _number(article: str) -> list[int]:
return [int(part) for part in article.split('.')]
def classify(tax: dict, body: str, cited: list[tuple[str, str]]) -> list[tuple[str, str]]:
"""[(узел, причина)] без модели: предмет требования либо статьи главы; отрасль - по подкатегориям.
Одна статья мимоходом не относит: замер 01.10.2026 - ст. 34 СК в уголовном
деле, ст. 35 СК в споре о купле-продаже.
"""
head = body[:HEAD_CHARS]
pieces = (head[m.end():m.end() + ZONE_CHARS] for m in CLAIM_MARK_RE.finditer(head))
zone = '\n'.join(piece.rsplit(' ', 1)[0] if len(piece) == ZONE_CHARS else piece for piece in pieces)
result = []
for area in tax['areas']:
own = {article for code, article in cited if code == area['code']} - {'1'}
found = []
for child in area['children']:
claim = child['claim'].search(zone)
hits = sorted(child['articles'] & own, key=_number)
if claim:
left = max(zone.rfind(' ', 0, max(0, claim.start() - 24)), zone.rfind('\n', 0, claim.start())) + 1
ends = [i for i in (zone.find(' ', claim.end() + 40), zone.find('\n', claim.end())) if i >= 0]
phrase = ' '.join(zone[left:min(ends, default=len(zone))].split()).strip(' ,;:')
found.append((child, f'предмет требования: «{phrase}»'))
elif len(own) >= area['min_code_articles'] and len(hits) >= area['min_articles']:
found.append((child, f"статьи {', '.join(hits)} {SHORT.get(area['code'], area['code'])}"))
if found:
result.append((area['id'], ', '.join(child['title'] for child, _ in found)))
result += [(child['id'], reason) for child, reason in found]
return result
def _place(conn: sqlite3.Connection, tax: dict, act: int, clear: bool = True) -> bool:
"""Отнести один акт; пишется в той же транзакции, что и сам акт."""
if clear:
conn.execute('DELETE FROM cats WHERE act = ?', (act,))
row = conn.execute('SELECT body FROM texts WHERE id = ?', (act,)).fetchone()
if row is None:
return False
cited = conn.execute('SELECT code, article FROM refs WHERE act = ?', (act,)).fetchall()
pairs = classify(tax, split_text(zlib.decompress(row[0]).decode('utf-8'))[2], cited)
conn.executemany('INSERT INTO cats (act, node, reason) VALUES (?, ?, ?)', [(act, n, r) for n, r in pairs])
return bool(pairs)
def _tree_changed(conn: sqlite3.Connection, tax: dict) -> bool:
known = conn.execute("SELECT value FROM meta WHERE key = 'taxonomy'").fetchone()
return known is None or known[0] != tax['fingerprint']
def _classify_all(conn: sqlite3.Connection, tax: dict) -> int:
"""Новое дерево, главы кодекса или версия правил - переотнести все акты из хранилища, без Lynceuz.
Отпечаток пишется последним в той же транзакции: сбой посередине оставит
старый отпечаток, и следующий импорт переотнесет все заново.
"""
conn.execute('BEGIN')
conn.execute('DELETE FROM cats')
acts = conn.execute('SELECT id FROM acts WHERE text_sha256 IS NOT NULL AND removed_at IS NULL').fetchall()
placed = sum(_place(conn, tax, act, clear=False) for (act,) in acts)
conn.execute("INSERT OR REPLACE INTO meta (key, value) VALUES ('taxonomy', ?)", (tax['fingerprint'],))
conn.execute('COMMIT')
return placed
def import_file(root: Path, export: Path, data_root: Path) -> dict:
"""Один экспорт Lynceuz → хранилище. Строка с чужим хешем отклоняется, прежняя версия остается."""
root, data_root, export = Path(root), Path(data_root).resolve(), Path(export)
counts = dict.fromkeys(('rows', 'added', 'updated', 'unchanged', 'removed', 'rejected', 'skipped'), 0)
reasons, latest, started, classified, retry = {}, None, time.monotonic(), 0, []
tax = taxonomy(root)
with _lock(root, 'import.lock'):
conn = _writer(root)
try:
before = conn.total_changes
# Акт и его отрасли коммитятся вместе: сбой между пакетом и отнесением не оставит акт без отрасли.
everything = _tree_changed(conn, tax)
conn.execute('BEGIN')
with export.open(encoding='utf-8') as lines:
for number, line in enumerate(lines, 1):
if not line.strip():
continue
counts['rows'] += 1
conn.execute('SAVEPOINT line')
row = None
try:
row = json.loads(line)
outcome, at, act = _apply(conn, row, data_root)
if act and not everything:
classified += _place(conn, tax, act)
conn.execute('RELEASE line')
except (ValueError, TypeError, OSError, sqlite3.IntegrityError) as exc:
conn.execute('ROLLBACK TO line')
conn.execute('RELEASE line')
outcome, at = 'rejected', None
if len(reasons) < 10:
reasons.setdefault(str(exc)[:160], number)
if isinstance(row, dict) and parse_time(row.get('fetched_at')) and len(retry) < 1000:
retry.append({'url': str(row.get('url'))[:300], 'at': str(row['fetched_at'])})
counts[outcome] += 1
latest = max(latest or '', at or '') or None
if number % BATCH == 0:
conn.execute('COMMIT')
conn.execute('BEGIN')
conn.execute('COMMIT')
if everything:
classified = _classify_all(conn, tax)
changes = conn.total_changes - before
if changes: # статистика планировщику; без нее запрос графа отрасли - 2,8 с на 96 тыс. актов
conn.execute('PRAGMA analysis_limit = 400')
for table in ('acts', 'refs', 'cats'):
conn.execute(f'ANALYZE {table}')
acts = conn.execute('SELECT count(*) FROM acts WHERE removed_at IS NULL AND text_sha256 IS NOT NULL').fetchone()[0]
links = conn.execute('SELECT count(*) FROM refs JOIN acts ON acts.id = refs.act '
'WHERE acts.removed_at IS NULL').fetchone()[0]
except BaseException:
if conn.in_transaction:
conn.execute('ROLLBACK')
raise
finally:
conn.close()
return {**counts, 'acts': acts, 'links': links, 'classified': classified, 'changes': changes, 'latest': latest,
'reasons': reasons, 'rejected_rows': retry, 'seconds': round(time.monotonic() - started, 2),
'export': export.name, 'finished_at': stamp()}
def lynceuz(args: list[str], timeout: float) -> dict:
"""Единственная дверь к Lynceuz: его CLI. Конверт JSON и код выхода."""
node, entry = shutil.which('node'), lynceuz_home() / 'src' / 'lynceuz.mjs'
if not node or not entry.is_file():
raise PracticeError(f'Lynceuz недоступен: нужен node и {entry}')
proc = subprocess.run([node, str(entry), *args, '--json'], capture_output=True, text=True,
timeout=timeout, cwd=entry.parents[1])
try:
envelope = json.loads(proc.stdout.strip().splitlines()[-1])
except (IndexError, ValueError):
envelope = {}
return {**(envelope if isinstance(envelope, dict) else {}), 'exit_code': proc.returncode}
def run_import(root: Path, *, full: bool = False, export: Path | None = None,
data_root: Path | None = None, runner=lynceuz) -> dict:
"""Экспорт --since от прошлого импорта (с перекрытием) и импорт; итог - в state.json.
Строка, не прошедшая сверку, приходит снова еще RETRIES - 1 раз: --since берется от
самой ранней такой строки. Потом она уходит в отчет и знак больше не держит: иначе
одна битая строка раздувала бы каждый часовой экспорт до полного.
"""
data_root = Path(data_root or default_data_root()).resolve()
state = read_state(root)
previous, retry = state.get('last_import') or {}, state.get('retry') or {}
marks = [mark for mark in (parse_time(previous.get('watermark')),
*(parse_time(item.get('at')) for item in retry.values())) if mark]
since = None if full or export or not marks else stamp(min(marks) - OVERLAP)
if export is None:
envelope = runner(['corpus', 'export', '--data-root', str(data_root),
*(['--since', since] if since else [])], 900)
if envelope.get('status') != 'ok' or not envelope.get('artifact_path'):
raise PracticeError(f"экспорт Lynceuz: {envelope.get('code') or envelope.get('exit_code')}")
export = _inside(data_root, envelope['artifact_path'])
summary = import_file(root, Path(export), data_root)
summary['since'] = since
latest = summary.pop('latest')
if latest and parse_time(latest) > datetime.now(UTC):
latest = stamp() # дата из будущего заморозила бы --since
summary['watermark'] = max(previous.get('watermark') or '', latest or '') or None
again = {}
for row in summary.pop('rejected_rows'):
tries = (retry.get(row['url']) or {}).get('tries', 0) + 1
if tries < RETRIES:
again[row['url']] = {'at': row['at'], 'tries': tries}
summary['retrying'], summary['given_up'] = len(again), summary['rejected'] - len(again)
update_state(root, 'retry', again)
update_state(root, 'last_import', summary)
return summary
def journal_signature(data_root: Path) -> list | None:
"""Размер и время журналов корпуса Lynceuz: не изменились - экспорт не гоняется зря."""
try:
return [[path.parent.name, path.stat().st_size, path.stat().st_mtime_ns]
for path in sorted(Path(data_root).glob('corpus/*/progress.jsonl'))] or None
except OSError:
return None
def build_facts(result: dict, data_root: Path) -> dict:
"""Счетчики, лимит и причина остановки прогона - из манифеста Lynceuz, без него - из сообщения."""
try:
manifest = _inside(Path(data_root).resolve(), result.get('manifest_path'))
corpus = json.loads(manifest.read_text(encoding='utf-8'))['corpus']
counts = corpus['counts']
return {'indexed': int(counts.get('indexed', 0)), 'unchanged': int(counts.get('unchanged', 0)),
'skipped': int(counts.get('skipped', 0)), 'failed': int(counts.get('failed', 0)),
'documents': corpus.get('documents'), 'limit': corpus.get('limit'), 'stop': corpus.get('stop')}
except (OSError, ValueError, KeyError, TypeError, AttributeError):
message = str(result.get('message') or '')
found = lambda pattern: re.search(pattern, message)
number = lambda name: int(match[1]) if (match := found(rf'(\d+) {name}')) else 0
limit, stop = found(r'stopped at (\w+)'), found(r'stopped by (\w+)')
return {'indexed': number('indexed'), 'unchanged': number('unchanged'), 'skipped': number('skipped'),
'failed': number('failed'), 'documents': number('documents in index') or None,
'limit': limit[1] if limit else None, 'stop': stop[1] if stop else None}
def build_verdict(result: dict, facts: dict) -> tuple[str, timedelta]:
"""Что значит прогон и когда следующий. Правило Lynceuz: отказ сайта - повтор через неделю.
Чужая блокировка - не отказ сайта: та сборка качает, ее акты импортируются каждый
час, а проверка блокировки сети не трогает. Сбой сети и своя политика - тоже не отказ.
"""
code = result.get('exit_code')
if code == 5 and result.get('code') == 'blocked':
return 'идет другая сборка Lynceuz, ее акты импортируются каждый час', HOUR
if 'policy_denied' in (facts.get('stop'), result.get('code')): # до сайта запрос не дошел: повтор
# на любом следующем запуске, в том числе сразу после install с новым окружением
return 'Lynceuz сам не выпустил запрос (policy_denied): сеть машины, обычно VPN; повтор при следующем запуске', timedelta(0)
if facts.get('stop') == 'robots_denied' and (facts.get('seconds') or 0) >= ROBOTS_NETWORK_SECONDS:
return ('СудАкт не ответил на robots.txt и после повторов Lynceuz (robots_denied): сбой сети; '
'повтор при следующем запуске', timedelta(0))
if code == 5 or facts.get('stop'):
return f"СудАкт отказал ({facts.get('stop') or result.get('code') or 'код 5'}), повтор через неделю", WEEK
if code == 3 and facts.get('limit') and facts['indexed'] + facts['unchanged'] + facts['skipped'] > 0:
return DOWNLOADING, timedelta(0)
if code == 0:
return 'карта СудАкта пройдена', WEEK
if code == 4:
return 'новых документов нет', WEEK
if code == 3:
return 'карта пройдена, часть документов не загрузилась, повтор через неделю', WEEK
return f'сборка не удалась (код {code})', DAY
def _strained(facts: dict) -> bool:
failed = facts.get('failed') or 0
return facts.get('stop') in REFUSALS or (
failed >= STRAIN_MIN and failed > STRAIN_SHARE * (failed + (facts.get('indexed') or 0)))
def _build_args(data_root: Path, pace: dict, scope: tuple[str, ...] = ()) -> list[str]:
return ['corpus', 'build', 'https://sudact.ru/', '--data-root', str(data_root), '--max-time', str(pace['seconds']),
'--max-pages', str(BUILD_PAGES), '--max-bytes', str(BUILD_BYTES),
'--concurrency', str(pace['concurrency']), '--delay', str(pace['delay']), *scope]
def _build(root: Path, data_root: Path, runner, now: datetime) -> dict:
"""Один кусок сборки Lynceuz; попытка записывается до сети. Быстрая скорость при признаке
перегруза СудАкта сменяется вежливой насовсем."""
record = {'attempted_at': stamp(now), 'running': True, 'meaning': 'идет сборка'}
state = read_state(root)
update_state(root, 'build', {**(state.get('build') or {}), **record})
speed = (state.get('speed') or {}).get('mode', 'fast')
pace = FAST if speed == 'fast' else POLITE
started = time.monotonic()
try:
result = runner(_build_args(data_root, pace), pace['seconds'] + 900)
facts = {**build_facts(result, data_root), 'seconds': time.monotonic() - started}
meaning, wait = build_verdict(result, facts)
if speed == 'fast' and _strained(facts):
update_state(root, 'speed', {'mode': 'polite', 'since': stamp(),
'reason': facts.get('stop') or f"сбоев {facts.get('failed')}"})
if facts.get('stop') == 'rate_limited': # сайт просит сбавить, а не закрывает доступ
meaning, wait = 'СудАкт попросил сбавить (rate_limited): дальше до 2 запросов в секунду, повтор через час', HOUR
record['speed'] = speed
record.update(exit_code=result.get('exit_code'), code=result.get('code'),
message=str(result.get('message') or '')[:300], **facts)
except Exception as exc: # сбой запуска не отменяет импорт уже скачанного
meaning, wait = 'сборка не запустилась', DAY
record['message'] = f'{type(exc).__name__}: {exc}'[:300]
seconds = time.monotonic() - started
finished = now + timedelta(seconds=seconds)
record.update(running=False, meaning=meaning, seconds=round(seconds, 1),
finished_at=stamp(finished), next_due=stamp(finished + wait))
update_state(root, 'build', record)
return record
def _import_if_new(root: Path, data_root: Path, runner, now: datetime) -> dict | None:
"""Импорт, только если журнал Lynceuz изменился; журнала не видно - не чаще раза в сутки."""
state = read_state(root)
signature = journal_signature(data_root)
last = parse_time((state.get('last_import') or {}).get('finished_at'))
if signature is not None:
fresh = signature == state.get('journal')
else:
fresh = last is not None and now - last < DAY
if fresh:
return None
try:
summary = run_import(root, data_root=data_root, runner=runner)
except Exception as exc: # экспорт не удался - акты прежние, причина в отчете
return {'error': f'{type(exc).__name__}: {exc}'[:300]}
update_state(root, 'journal', signature)
return {key: summary.get(key) for key in ('added', 'updated', 'removed', 'rejected', 'retrying',
'acts', 'links', 'seconds', 'since')}
def tick(root: Path, *, force_build: bool = False, runner=lynceuz, now: datetime | None = None) -> dict:
"""Час launchd: новые акты Lynceuz - в Эвномию; сборка - кусками подряд, пока корпус не
докачан, потом раз в неделю. Импорт идет до сборки и после каждого куска: сбой сборки
его не отменяет, а новые акты попадают в Эвномию раз в час и во время докачки."""
real_clock, now = now is None, now or datetime.now(UTC)
data_root = default_data_root()
with _lock(root, 'tick.lock', 'задача практики уже идет'):
report = {'at': stamp(now), 'import': _import_if_new(root, data_root, runner, now)}
build = read_state(root).get('build') or {}
due = parse_time(build.get('next_due'))
if _parts_lead(root) and not force_build:
if build.get('meaning') != PARTS_LEAD:
update_state(root, 'build', {**build, 'running': False, 'meaning': PARTS_LEAD})
elif force_build or due is None or now >= due - TICK_SLACK:
for _ in range(CHUNKS):
report['build'] = _build(root, data_root, runner, now)
now = datetime.now(UTC) if real_clock else now + timedelta(seconds=report['build']['seconds'])
report['import_after'] = _import_if_new(root, data_root, runner, now)
update_state(root, 'tick', report)
if report['build']['meaning'] != DOWNLOADING:
break
update_state(root, 'tick', report)
return report
def _parts_lead(root: Path) -> bool:
"""Части ведут корпус, пока их докачка не остановлена отказом СудАкта."""
try:
return not json.loads((Path(root) / STATE_REL / 'parts' / 'state.json').read_text(encoding='utf-8')).get('stopped')
except (OSError, ValueError, AttributeError):
return False
def _agent(label: str = LABEL) -> Path:
return Path.home() / 'Library' / 'LaunchAgents' / f'{label}.plist'
# Задачи launchd: команда, интервал, отчет и ошибки. Отчета страницы нет: раз в минуту он рос бы без конца.
JOBS = {LABEL: ('tick', 3600, 'launchd.log', 'launchd.err.log'),
PUBLISH_LABEL: ('publish', 60, None, 'status-launchd.err.log'),
PARTS_LABEL: ('parts', 60, 'parts-launchd.log', 'parts-launchd.err.log')}
def _plist_env(path: Path) -> dict | None:
try:
return plistlib.loads(path.read_bytes()).get('EnvironmentVariables') or {}
except Exception: # нет или битый plist
return None
def _payload(root: Path, old: dict | None = None, label: str = LABEL) -> dict:
state, kept = Path(root) / STATE_REL, (old or {}).get('EnvironmentVariables') or {}
if label == PARTS_LABEL and not kept: # пул VPN частям нужен так же, как сборке: берется из ее задачи
kept = _plist_env(_agent()) or {}
env = {name: os.environ.get(name) or kept.get(name) for name in SCHEDULER_ENV}
command, every, out, err = JOBS[label]
payload = {'Label': label, 'ProgramArguments': [sys.executable, str(Path(__file__).resolve()), command,
'--root', str(root)],
'WorkingDirectory': str(CODE_ROOT), 'StartInterval': every, 'RunAtLoad': True,
'ProcessType': 'Background', 'LowPriorityIO': True,
'EnvironmentVariables': {'PATH': SCHEDULER_PATH, **({} if label == PUBLISH_LABEL else # странице
{name: value for name, value in env.items() if value})}, # пул не нужен
'StandardOutPath': str(state / out) if out else '/dev/null', 'StandardErrorPath': str(state / err)}
if label == PARTS_LABEL: # Background держит процессы на энергоэффективных ядрах с низким приоритетом
payload['ProcessType'] = 'Standard'
del payload['LowPriorityIO']
return payload
def _missing_env() -> list[str]:
"""Переменные оболочки, которых нет в задаче: с ними задача шла бы иначе (пул VPN)."""
if (env := _plist_env(_agent())) is None: # нет или битый plist - не повод ронять отчет
return []
return [name for name in SCHEDULER_ENV if os.environ.get(name) and env.get(name) != os.environ[name]]
def _own_agent(target: Path, refusal: str) -> dict | None:
"""Прежнее задание этого файла или None; чужое задание с той же меткой не трогаем."""
if not target.exists():
return None
old = plistlib.loads(target.read_bytes())
if str(Path(__file__).resolve()) not in old.get('ProgramArguments', []):
raise PracticeError(refusal)
return old
def install(root: Path, label: str = LABEL) -> dict:
"""LaunchAgent: тик каждый час, первый - сразу после установки. Повторная установка безопасна.
Прежнее задание этого файла заменяется и перезагружается: launchd держит plist с момента
загрузки. Перезагрузка прерывает идущую сборку; Lynceuz продолжит ее со следующего тика.
"""
target, domain = _agent(label), f'gui/{os.getuid()}'
old = _own_agent(target, 'задание с этой меткой чужое; существующее не перезаписано')
payload = _payload(root, old, label)
Path(payload['StandardErrorPath']).parent.mkdir(parents=True, exist_ok=True)
loaded = lambda: not subprocess.run(['launchctl', 'print', f'{domain}/{label}'],
capture_output=True, timeout=10).returncode
running = loaded()
if running and old != payload:
subprocess.run(['launchctl', 'bootout', f'{domain}/{label}'], capture_output=True, timeout=60)
for _ in range(30): # bootout может вернуться раньше, чем задание остановится
if not (running := loaded()):
break
time.sleep(1)
if running: # plist не тронут: повторный install попробует снова
raise PracticeError('прежнее задание не остановилось за 30 с; повторите install')
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(plistlib.dumps(payload))
if not running:
subprocess.run(['launchctl', 'bootstrap', domain, str(target)], check=True, capture_output=True, timeout=20)
return {'status': 'installed', 'label': label, 'plist': str(target)}
def uninstall(label: str = LABEL) -> dict:
target = _agent(label)
_own_agent(target, 'задание с этой меткой чужое; существующее не удалено')
subprocess.run(['launchctl', 'bootout', f'gui/{os.getuid()}/{label}'], capture_output=True, timeout=20)
target.unlink(missing_ok=True)
return {'status': 'uninstalled', 'label': label}
def part_roots(root: Path) -> list[Path]:
return [Path(root) / STATE_REL / 'parts' / str(part) / '.lynceuz' for part in range(PARTS)] # имя требует Lynceuz
def progress(root: Path, data_root: Path | None = None, now: datetime | None = None) -> dict:
"""Доля скачанного СудАкта по диску, без сети: акты индексов Lynceuz (основная сборка и части,
без повторов) против адресов актов в карте сайта. Скорость - акты, впервые скачанные за последние
10 минут, то есть прирост «скачано» без выборок в состоянии. Карта считается заново: 0,04 с на
96 тыс. адресов (замер 02.10.2026)."""
data_root, now = Path(data_root or default_data_root()).resolve(), now or datetime.now(UTC)
roots, total = [data_root, *part_roots(root)], 0
# карта - из корня, обходившего ее последним: основная сборка, пока ведут части, ее не обновляет
fresh = max((base for base in roots if (base / 'corpus/sudact.ru/sitemaps.json').is_file()),
key=lambda base: (base / 'corpus/sudact.ru/sitemaps.json').stat().st_mtime_ns)
for meta in json.loads((fresh / 'corpus/sudact.ru/sitemaps.json').read_text(encoding='utf-8')).values():
data = _inside(fresh.resolve(), meta.get('path')).read_bytes()
total += len(SITEMAP_DOC_RE.findall(zlib.decompress(data, 31) if data[:2] == b'\x1f\x8b' else data))
since = (now - SPEED_WINDOW).strftime('%Y-%m-%dT%H:%M:%S') # fetched_at - ISO UTC: строки сравнимы
main, *rest = [path for path in (base / 'corpus/sudact.ru/index.sqlite' for base in roots) if path.is_file()]
with closing(sqlite3.connect(main.as_uri() + '?mode=ro', uri=True, timeout=5)) as conn:
for number, path in enumerate(rest): # 10 частей - ровно предел ATTACH в SQLite
conn.execute(f'attach database ? as p{number}', (path.as_uri() + '?mode=ro',))
union = ' union all '.join(f'select url, fetched_at from {name}.docs'
for name in ('main', *(f'p{number}' for number in range(len(rest)))))
done, recent = conn.execute('select count(*), count(*) filter (where fetched >= ?) from '
f'(select min(fetched_at) fetched from ({union}) group by url)', (since,)).fetchone()
per_min, rest, state = recent * 60 / SPEED_WINDOW.total_seconds(), max(total - done, 0), read_state(root)
return {'done': done, 'total': total, 'per_min': round(per_min, 1),
'eta_min': 0 if not rest else round(rest / per_min) if per_min else None,
'meaning': (state.get('build') or {}).get('meaning'),
'speed': (state.get('speed') or {}).get('mode', 'fast'), 'updated_at': stamp(now)}
def next_day(moment: datetime) -> datetime:
"""Начало следующих суток по часам Mac. Задача частей просыпается раз в минуту, поэтому обход идет при
первом запуске в новые сутки - ночью или когда Mac проснется (решение владельца 03.10.2026). Нет сети -
Lynceuz отвечает сбоем сети, и обход повторяется через минуту."""
local = moment.astimezone()
return (local + timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0).astimezone(UTC)
def _part(root: Path, part: int, runner) -> dict:
data_root = part_roots(root)[part]
data_root.mkdir(parents=True, exist_ok=True)
scope = tuple(arg for char in ID_CHARS[part::PARTS] for arg in ('--include', f'/*/doc/{char}**'))
started = time.monotonic()
result = runner(_build_args(data_root, PART_PACE, scope), PART_PACE['seconds'] + 900)
facts = {**build_facts(result, data_root), 'seconds': round(time.monotonic() - started, 1)}
return {'part': part, **facts, 'exit_code': result.get('exit_code'), 'meaning': build_verdict(result, facts)[0]}
def _import_parts(root: Path, marks: dict, runner) -> tuple[dict, dict]:
"""Акты частей - в Эвномию: экспорт --since от последнего акта прошлого импорта части (с перекрытием).
Журнал части не менялся - экспорт не гоняется. Импорт сборки занят - остальные части в следующий раз."""
marks, report = dict(marks), {}
for part, data_root in enumerate(part_roots(root)):
journal = data_root / 'corpus/sudact.ru/progress.jsonl'
if not journal.is_file():
continue
known = marks.get(str(part)) or {}
signature = [journal.stat().st_size, journal.stat().st_mtime_ns]
if signature == known.get('sig'):
continue
since = stamp(parse_time(known['mark']) - OVERLAP) if parse_time(known.get('mark')) else None
try:
envelope = runner(['corpus', 'export', '--data-root', str(data_root),
*(['--since', since] if since else [])], 900)
if envelope.get('status') != 'ok' or not envelope.get('artifact_path'):
raise PracticeError(f"экспорт Lynceuz: {envelope.get('code') or envelope.get('exit_code')}")
summary = import_file(root, _inside(data_root.resolve(), envelope['artifact_path']), data_root)
except PracticeError as exc:
report[str(part)] = str(exc)[:200]
if 'уже идет' in str(exc):
break
continue
marks[str(part)] = {'mark': max(known.get('mark') or '', summary.get('latest') or '') or None, 'sig': signature}
report[str(part)] = summary.get('added', 0)
return marks, report
def parts(root: Path, runner=lynceuz) -> dict:
"""Параллельная докачка: кусок по 15 минут во всех включенных частях сразу, затем импорт новых актов
частей в Эвномию. Отказ СудАкта или всплеск сбоев в любой части останавливает докачку всех частей
насовсем: снять - удалить parts/state.json. Карта пройдена во всех частях - обход раз в день."""
path, ask = Path(root) / STATE_REL / 'parts' / 'state.json', Path(root) / REFRESH_REL
def save(state: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temp = path.with_suffix('.tmp')
temp.write_text(json.dumps(state, ensure_ascii=False, indent=1), encoding='utf-8')
os.replace(temp, path)
with _lock(root, 'parts.lock', 'параллельная докачка уже идет'):
state = json.loads(path.read_text(encoding='utf-8')) if path.is_file() else {'active': FIRST_PARTS}
due = parse_time(state.get('next_due')) or next_day(parse_time(state.get('at')) or datetime.now(UTC))
# новые сутки - новые акты СудАкта (решение владельца 03.10.2026) или кнопка Эвномии
if state.get('done') and (ask.exists() or datetime.now(UTC) >= due):
state.pop('done')
state['found'] = 0
if not (state.get('stopped') or state.get('done')):
ask.unlink(missing_ok=True)
state['at'] = stamp()
save(state) # начало обхода видно сразу: Эвномия не ждет конца 15-минутного куска
with ThreadPoolExecutor(state['active']) as pool:
results = list(pool.map(lambda part: _part(root, part, runner), range(state['active'])))
refused = [r for r in results if _strained(r) or r['meaning'].startswith('СудАкт отказал')]
clean = all(r['meaning'] in WORKING for r in results) # ступень - только после рабочего куска
state.update(active=PARTS if clean else state['active'], at=stamp(), parts=results,
found=state.get('found', 0) + sum(r.get('indexed') or 0 for r in results))
if refused:
state['stopped'] = f"часть {refused[0]['part']}: {refused[0]['meaning']}; все части остановлены"
elif len(results) == PARTS and all(r['meaning'] in WORKING[1:] for r in results):
state.update(done=True, next_due=stamp(next_day(datetime.now(UTC))))
state['imported'], state['import'] = _import_parts(root, state.get('imported') or {}, runner)
if state.get('done'): # обход кончился: общий граф права - если сменились акты или снимок норм
state['graph'] = _graph_if_new(root, state.get('graph') or {})
save(state)
return state
def walk(root: Path, now: datetime | None = None) -> dict:
"""Обход карты СудАкта глазами Эвномии, только чтение: идет ли, ждет ли просьба, остановка,
следующий срок и сколько актов скачал последний обход."""
path, ask = Path(root) / STATE_REL / 'parts' / 'state.json', Path(root) / REFRESH_REL
state = json.loads(path.read_text(encoding='utf-8')) if path.is_file() else {}
done = bool(state.get('done'))
due = parse_time(state.get('next_due')) or next_day(parse_time(state.get('at')) or now or datetime.now(UTC))
try:
asked = stamp(datetime.fromtimestamp(ask.stat().st_mtime, UTC))
except FileNotFoundError:
asked = None
# ponytail: обход идет, пока в state.json нет done; задачу частей сняли посреди обхода - кнопка ждет
# до ее возвращения. Точнее - проба замка parts.lock, если это случится.
return {'running': bool(state) and not done and not state.get('stopped'), 'requested_at': asked,
'stopped': state.get('stopped'), 'at': state.get('at'), 'next_due': stamp(due) if done else None,
'found': state.get('found')}
def request_walk(root: Path) -> dict:
"""Кнопка Эвномии: файл-просьба для задачи частей. Остановленные отказом СудАкта части обход не начнут -
об этом ошибка, а не молчание. Идущий обход или ждущая просьба второй просьбы не дают."""
now = walk(root)
if now['stopped']:
raise PracticeError(f"Докачка СудАкта остановлена: {now['stopped']}. Обход не запущен.")
if now['running'] or now['requested_at']:
return {**now, 'started': False}
ask = Path(root) / REFRESH_REL
ask.parent.mkdir(parents=True, exist_ok=True)
ask.write_text(stamp() + '\n', encoding='utf-8')
return {**walk(root), 'started': True}
def article_id(code: str, article: str) -> str:
return f'doc:legal-corpus:code:{code}:article:{article}' # ID статьи в нормативном графе legal_graph
GRAPH_VERSION = 2 # разбор практики для графа: 2 - номера без точки, акты ВС узлами (03.10.2026)
GLUED_EXCEPT = {'koap-rf'} # КоАП нумерует «глава.статья» точкой в тексте, надстрочных номеров у него нет
SUPREME = 'vsrf' # акты Верховного Суда - узлами графа: верх иерархии практики, 690 актов (замер 03.10.2026)
def unglue(code: str, article: str, known: set[str]) -> str | None:
"""Номер статьи из практики → номер статьи графа права. СудАкт теряет надстрочный знак: «статьи 29111
АПК» в тексте акта - это ст. 291.11 (замер 03.10.2026: 886 статей практики вне графа, среди них такие).
Номер вне графа, который ровно одним способом делится точкой на статью графа, - эта статья; иначе None."""
if article_id(code, article) in known:
return article
if '.' in article or code in GLUED_EXCEPT:
return None
hits = [f'{article[:i]}.{article[i:]}' for i in range(1, len(article))]
hits = [number for number in hits if article_id(code, number) in known]
return hits[0] if len(hits) == 1 else None
def practice_extraction(root: Path, known: set[str] | None = None) -> dict:
"""Практика Эвномии для графа: статьи с числом цитирующих актов, отрасли, акты Верховного Суда, ребра
«цитируют вместе», «отрасль цитирует» и «акт цитирует». known - ID статей нормативного графа: номер без
точки сводится к своей статье (unglue), остальные статьи вне графа в граф не идут и считаются по кодексам
(нет кодекса или главы в корпусе права, утратившая силу статья, опечатка суда)."""
store = (Path(root) / STATE_REL / 'practice.sqlite3').resolve()
with closing(sqlite3.connect(store.as_uri() + '?mode=ro', uri=True, timeout=30)) as conn:
cited = conn.execute('select code, article, count(*) from refs group by 1, 2').fetchall()
mapping = {(code, article): (code, unglue(code, article, known) if known is not None else article)
for code, article, _ in cited}
pairs, act, refs = Counter(), None, []
for current, code, article in conn.execute('select act, code, article from refs order by act, code, article'):
if current != act:
pairs.update(combinations(sorted(set(refs)), 2))
act, refs = current, []
if mapping[(code, article)][1]:
refs.append(mapping[(code, article)])
pairs.update(combinations(sorted(set(refs)), 2))
areas = conn.execute('select node, count(*) from cats group by 1').fetchall()
area_refs = conn.execute('select c.node, r.code, r.article, count(*) from cats c join refs r on r.act = c.act '
'group by 1, 2, 3').fetchall()
supreme = conn.execute('select a.id, a.doc, a.title, a.url, a.act_date, r.code, r.article from acts a join refs r '
'on r.act = a.id where a.section = ? and a.removed_at is null', (SUPREME,)).fetchall()
articles, area_counts, dropped = Counter(), Counter(), Counter()
for code, article, acts in cited:
target = mapping[(code, article)]
if target[1]:
articles[target] += acts
else:
dropped[code] += 1
for node, code, article, acts in area_refs:
if mapping[(code, article)][1]:
area_counts[(node, mapping[(code, article)])] += acts
edge = lambda source, target, relation, acts: {'source': source, 'target': target, 'relation': relation,
'confidence': 'EXTRACTED', 'confidence_score': 1.0, 'weight': acts,
'acts': acts, 'source_file': 'eunomia/practice'}
titles = _nodes()
nodes = [{'id': article_id(*ref), 'label': label(*ref), 'file_type': 'document',
'kind': 'article', 'source_file': 'eunomia/practice', 'practice_acts': acts}
for ref, acts in articles.items()]
nodes += [{'id': f'practice:area:{node}', 'label': (titles.get(node) or {}).get('title', node), 'file_type': 'document',
'kind': 'practice_area', 'source_file': 'eunomia/practice_taxonomy.json', 'practice_acts': acts}
for node, acts in areas]
edges = [edge(article_id(*first), article_id(*second), 'cited_together', acts)
for (first, second), acts in pairs.items() if acts >= TOGETHER_MIN]
edges += [edge(f'practice:area:{node}', article_id(*ref), 'cites', acts)
for (node, ref), acts in area_counts.items() if acts >= AREA_MIN]
acts_seen = {}
for number, doc, title, url, day, code, article in supreme:
target = mapping.get((code, article), (code, None))
if not target[1]:
continue
# ID - номер строки базы, префикс не «practice»: graphify переписывает ID с заглавными буквами и ID, начатые основой имени файла источника
acts_seen.setdefault(number, {'id': f'sudact:act:{number}', 'label': title, 'file_type': 'document',
'kind': 'practice_act', 'source_file': 'eunomia/practice', 'doc': doc,
'source_url': url, 'act_date': day})
edges.append(edge(f'sudact:act:{number}', article_id(*target), 'cites', 1))
nodes += list(acts_seen.values())
unique = {(item['source'], item['target'], item['relation']): item for item in edges}
return {'nodes': nodes, 'edges': list(unique.values()), 'dropped': sum(dropped.values()),
'dropped_by_code': dict(dropped.most_common()),
'unglued': sum(1 for (code, article), target in mapping.items() if target[1] and target[1] != article)}
def _embed_practice(root: Path, built: dict, out: Path) -> dict:
"""Практика встраивается в готовый граф (решение владельца 03.10.2026: огромный граф каждый день не
пересобирать): числа актов у статей и ребра практики - заново, узлы норм, их ребра и сообщества - как
были. Новый узел берет сообщество соседа по самому сильному ребру."""
from graphify.build import _norm_label
nodes = {node['id']: node for node in built['nodes']}
legal = {node_id for node_id, node in nodes.items() if node.get('source_file') not in PRACTICE_FILES}
practice = practice_extraction(root, legal or None)
strongest = {}
for edge in practice['edges']:
for one, other in ((edge['source'], edge['target']), (edge['target'], edge['source'])):
if edge['weight'] > strongest.get(one, (0, None))[0]:
strongest[one] = (edge['weight'], other)
fresh = {node['id'] for node in practice['nodes']}
nodes = {node_id: node for node_id, node in nodes.items() # акт, снятый с СудАкта, уходит и из графа
if node.get('source_file') not in PRACTICE_FILES or node_id in fresh}
for node in nodes.values():
node.pop('practice_acts', None)
added = 0
for node in practice['nodes']:
if node['id'] in nodes:
nodes[node['id']]['practice_acts'] = node['practice_acts']
continue
neighbor = nodes.get(strongest.get(node['id'], (0, None))[1]) or {}
nodes[node['id']] = {**node, 'norm_label': _norm_label(node['label']), 'community': neighbor.get('community', -1)}
added += 1
built.update(nodes=list(nodes.values()),
links=[edge for edge in built['links'] if edge.get('source_file') not in PRACTICE_FILES] + practice['edges'])
temp = out.with_name(f'.graph.{os.getpid()}.json')
temp.write_text(json.dumps(built, ensure_ascii=False), encoding='utf-8')
os.replace(temp, out)
return {'graph': str(out), 'mode': 'embed', 'nodes': len(built['nodes']), 'edges': len(built['links']),
'practice_articles': sum(node['kind'] == 'article' for node in practice['nodes']),
'practice_edges': len(practice['edges']), 'added_nodes': added, 'dropped_articles': practice['dropped'],
'dropped_by_code': practice['dropped_by_code'], 'unglued': practice['unglued'],
'legal_snapshot': (built.get('graph') or {}).get('legal_snapshot')}
def graph(root: Path, full: bool = False) -> dict:
"""Общий граф права: снимок legal_graph без текстов и практика Эвномии. Полная сборка - библиотекой
graphify, сообщества заново, без LLM: когда графа нет, сменился снимок legal_graph или full. Иначе
практика встраивается в готовый граф. Снимка нормативного графа нет - в графе только практика."""
out = Path(root) / GRAPH_REL
snapshot, _ = legal_graph._current(Path(root) / legal_graph.STATE_REL)
if not full and out.is_file():
built = json.loads(out.read_text(encoding='utf-8'))
if (built.get('graph') or {}).get('legal_snapshot') == (snapshot.name if snapshot else None):
return _embed_practice(root, built, out)
del built
from graphify.build import _norm_label, build_from_json # _norm_label - ключ слияния узлов graphify
from graphify.cluster import cluster
from graphify.export import to_json
nodes, edges = {}, []
if snapshot is not None:
legal = json.loads((snapshot / 'graphify-out' / 'graph.json').read_text(encoding='utf-8'))
nodes = {node['id']: {key: value for key, value in node.items() if key not in ('text', 'community')}
for node in legal['nodes']}
edges = legal.get('links') or legal.get('edges') or []
del legal
practice = practice_extraction(root, set(nodes) if nodes else None)
for node in practice['nodes']: # у слитой статьи остается название нормы, практика добавляет число актов
nodes[node['id']] = {**node, **nodes.get(node['id'], {}), **{k: node[k] for k in ('practice_acts',) if k in node}}
# graphify сливает узлы с одним названием: «§ 1. Основные положения» разных глав стали бы одним
# узлом (замер 03.10.2026: 1 291 узел). Совпавшие названия различают файл и строка источника; на
# одной строке остаются настоящие дубли снимка - их слияние верное (замер: 992, ни одного разного).
key = lambda node: _norm_label(str(node.get('label', '')))
named = Counter(key(node) for node in nodes.values())
for node in nodes.values():
if named[key(node)] > 1 and node.get('source_location'):
node['label'] = f"{node['label']} ({Path(str(node.get('source_file'))).stem}, строка {str(node['source_location']).lstrip('L')})"
node.pop('norm_label', None)
built = build_from_json({'nodes': list(nodes.values()), 'edges': edges + practice['edges'], 'hyperedges': [],
'input_tokens': 0, 'output_tokens': 0}, directed=True)
built.graph['legal_snapshot'] = snapshot.name if snapshot else None # по нему встраивание узнает свой снимок
out.parent.mkdir(parents=True, exist_ok=True)
temp = out.with_name(f'.graph.{os.getpid()}.json')
with redirect_stdout(sys.stderr): # библиотека пишет диагностику в stdout, а stdout CLI - JSON
if not to_json(built, cluster(built), str(temp), force=True):
raise PracticeError('graphify отказал в экспорте общего графа')
os.replace(temp, out)
return {'graph': str(out), 'mode': 'full', 'nodes': built.number_of_nodes(), 'edges': built.number_of_edges(),
'practice_articles': sum(node['kind'] == 'article' for node in practice['nodes']),
'practice_edges': len(practice['edges']), 'dropped_articles': practice['dropped'],
'dropped_by_code': practice['dropped_by_code'], 'unglued': practice['unglued'],
'legal_snapshot': snapshot.name if snapshot else None}
def _graph_if_new(root: Path, last: dict) -> dict:
try:
store = (Path(root) / STATE_REL / 'practice.sqlite3').resolve()
with closing(sqlite3.connect(store.as_uri() + '?mode=ro', uri=True, timeout=30)) as conn:
acts = conn.execute('select count(*) from acts').fetchone()[0]
snapshot, _ = legal_graph._current(Path(root) / legal_graph.STATE_REL)
legal = snapshot.name if snapshot else None
if (last.get('acts'), last.get('legal'), last.get('version')) == (acts, legal, GRAPH_VERSION) \
and (Path(root) / GRAPH_REL).is_file():
return last
# встраивание или полная сборка; новая версия разбора практики пересобирает граф без новых актов
return {**graph(root), 'acts': acts, 'legal': legal, 'version': GRAPH_VERSION, 'at': stamp()}
except Exception as exc: # граф не держит докачку: сбой виден в parts/state.json, повтор через минуту
return {**last, 'error': f'{type(exc).__name__}: {exc}'[:300]}
def publish(root: Path) -> dict:
"""Локальная страница загрузки: index.html и status.js рядом в .agent/. Данные - скриптом,
а не status.json: страница открывается как файл, fetch из file:// браузеры запрещают."""
value, folder = progress(root), Path(root) / STATE_REL / 'status'
folder.mkdir(parents=True, exist_ok=True)
for name, data in (('index.html', STATUS_PAGE.read_bytes()),
('status.js', f'showStatus({json.dumps(value, ensure_ascii=False)})\n'.encode())):
temp = folder / f'.{name}.{os.getpid()}.tmp' # браузер не застанет файл недописанным
temp.write_bytes(data)
os.replace(temp, folder / name)
return {'status': 'published', 'page': (folder / 'index.html').as_uri(), 'done': value['done'],
'total': value['total'], 'updated_at': value['updated_at']}
def parse_query(query: str) -> tuple[list[str], list[tuple[str, str]], str]:
"""Запрос → (основы слов, статьи [(кодекс, номер)], выражение FTS5). Синтаксис FTS не пропускается."""
short, _ = short_codes(re.sub(r'[\x00-\x1f]', ' ', fold(query)))
refs, rest = [], short
for start, end, number, slug in legal_graph.article_refs(short):
if slug:
refs.append((slug, number))
rest = rest[:start] + ' ' * (end - start) + rest[end:]
phrases = [p.strip().casefold() for p in re.findall(r'"([^"]+)"', rest) if p.strip()][:4]
words = [w for w in re.findall(r'\w+', re.sub(r'"[^"]*"', ' ', rest).casefold())
if w not in STOP and len(w) > 1][:8] # одна буква и десятки слов давали секунды поиска
# ponytail: наивная основа (отрезать 1-2 буквы окончания) вместо морфологии;
# нужна точность - подключить pymorphy-подобный лемматизатор после разрешения.
stems = [w[:len(w) - (2 if len(w) >= 7 else 1 if len(w) >= 5 else 0)] if w.isalpha() else w for w in words]
expression = ' AND '.join([f'"{p}"' for p in phrases]
+ [f'"{s}"*' if s.isalpha() and len(s) >= 3 else f'"{s}"' for s in stems])
return phrases + stems, refs, expression
def _window(body: str, terms: list[str]) -> str:
low = fold(body).casefold()
hits = [i for i in (low.find(t) for t in terms if t) if i >= 0]
if not hits:
return ''
start = max(0, min(hits) - 140)
start = body.find(' ', start) + 1 if start else 0
return ('…' if start else '') + ' '.join(body[start:start + 420].split()) + '…'
def _excerpt(body: str, code: str, article: str) -> str:
"""Дословное место ссылки. Точки сокращений («ст.», «г.») режут предложение - тогда окно."""
for start, end, slug, number in citations(body):
if slug == code and number == article:
sentence = ' '.join(legal_graph._evidence_excerpt(body, start, end).split())
if 160 <= len(sentence) <= 480:
return sentence
left = max(0, start - 220)
left = body.find(' ', left) + 1 if left else 0
right = body.rfind(' ', end, end + 200)
right = len(body) if end + 200 >= len(body) else (right if right > end else end + 200)
return ('…' if left else '') + ' '.join(body[left:right].split()) + ('…' if right < len(body) else '')
return ''
def _nodes() -> dict[str, dict]:
"""{узел: {title, parent}} по файлу дерева, без глав кодекса."""
nodes = {}
for area in json.loads(TAXONOMY.read_text(encoding='utf-8'))['areas']:
nodes[area['id']] = {'title': area['title'], 'parent': None}
nodes.update({child['id']: {'title': child['title'], 'parent': area['id']} for child in area['children']})
return nodes
class Practice:
"""Чтение для HTTP Эвномии: только SELECT, без сети и записи."""
def __init__(self, root: Path, library=None):
self.root = Path(root)
self.path = self.root / STATE_REL / 'practice.sqlite3'
self.library = library
self._cache = {}
def _cached(self, key: tuple, build):
"""Срезы базы меняются только записью: ключ - отпечаток файлов базы и дерева отраслей."""
version = [TAXONOMY.stat().st_mtime_ns]
for path in (self.path, self.path.with_name(self.path.name + '-wal')):
try:
stat = path.stat()
version.append((stat.st_mtime_ns, stat.st_size))
except FileNotFoundError:
version.append(None)
hit = self._cache.get(key)
if hit and hit[0] == version:
return hit[1]
value = build()
self._cache[key] = (version, value)
return value
def _db(self) -> sqlite3.Connection:
if not self.path.is_file():
raise FileNotFoundError('Судебная практика еще не загружена')
conn = sqlite3.connect(self.path, timeout=10)
conn.row_factory = sqlite3.Row
return conn
def summary(self) -> dict:
try:
state = read_state(self.root)
except PracticeError as exc:
state = {'error': str(exc)}
last = state.get('last_import') or {}
return {'ready': self.path.is_file(), 'acts': last.get('acts', 0), 'links': last.get('links', 0),
'last_import': {k: last.get(k) for k in ('finished_at', 'seconds', 'added', 'updated', 'removed',
'rejected', 'retrying', 'given_up', 'watermark')} if last else None,
'build': state.get('build'), 'speed': state.get('speed'), 'tick': (state.get('tick') or {}).get('at'),
'error': state.get('error'),
'schedule': {'label': LABEL, 'installed': _agent().is_file(), 'interval_hours': 1,
'missing_env': _missing_env()}}
def facets(self) -> dict:
return self._cached(('facets',), self._facets)
def _facets(self) -> dict:
if not self.path.is_file():
return {'ready': False, 'months': [], 'kinds': [], 'courts': [], 'categories': []}
live = 'FROM acts WHERE removed_at IS NULL AND text_sha256 IS NOT NULL'
with closing(self._db()) as conn:
group = lambda column, order: [{'value': v, 'count': n} for v, n in conn.execute(
f'SELECT {column} AS v, count(*) {live} AND v IS NOT NULL GROUP BY v ORDER BY {order}')]
return {'ready': True, 'months': group('substr(act_date, 1, 7)', 'v DESC'),
'kinds': group('kind', 'count(*) DESC'), 'courts': group('court', 'v'),
'categories': group('category', 'count(*) DESC')}
def _reader(self, code: str, article: str) -> dict | None:
resource = f'legal-corpus:code:{code}'
item = (self.library.documents if self.library else {}).get(resource)
fragment = f"{legal_graph._graph_id(resource)}_article_{article.replace('.', '_')}"
if item and any(part['id'] == fragment for part in item.get('fragments', [])):
return {'id': resource, 'fragment': fragment}
return None
def browse(self, params: dict) -> dict:
query = str(params.get('q') or '').strip()
if len(query) > 300:
raise ValueError('Запрос длиннее 300 символов')
terms, refs, expression = parse_query(query)
code, article = params.get('code'), params.get('article')
if code or article:
if not (CODE_RE.fullmatch(str(code)) and ARTICLE_RE.fullmatch(str(article))):
raise ValueError('Статья указана неверно')
refs.append((code, article))
try:
page = int(params.get('page') or 1)
except ValueError:
page = 1
page = min(max(page, 1), 10000)
articles = [{'code': c, 'article': a, 'label': label(c, a), 'reader': self._reader(c, a)}
for c, a in dict.fromkeys(refs)]
empty = {'ready': self.path.is_file(), 'items': [], 'total': 0, 'page': 1, 'pages': 1,
'terms': terms, 'articles': articles}
if not self.path.is_file():
return empty
where, args = ['a.removed_at IS NULL', 'a.text_sha256 IS NOT NULL'], []
for name, column in (('kind', 'a.kind'), ('court', 'a.court'), ('category', 'a.category'),
('month', 'substr(a.act_date, 1, 7)'), ('section', 'a.section')):
if params.get(name):
where.append(f'{column} = ?')
args.append(str(params[name])[:200])
for c, a in dict.fromkeys(refs):
where.append('a.id IN (SELECT act FROM refs WHERE code = ? AND article = ?)')
args += [c, a]
for node in [n for n in str(params.get('area') or '').split(',') if n][:3]: # несколько узлов - пересечение
if not NODE_RE.fullmatch(node):
raise ValueError('Отрасль указана неверно')
where.append('a.id IN (SELECT act FROM cats WHERE node = ?)')
args.append(node)
source, order = 'acts a', 'a.act_date DESC, a.id DESC'
if params.get('sort') == 'old':
order = 'a.act_date IS NULL, a.act_date, a.id'
if expression:
source, order = 'fts JOIN acts a ON a.id = fts.rowid', 'bm25(fts, 10.0, 1.0)'
where.insert(0, 'fts MATCH ?')
args.insert(0, expression)
clause = ' AND '.join(where)
with closing(self._db()) as conn:
total = conn.execute(f'SELECT count(*) FROM {source} WHERE {clause}', args).fetchone()[0]
pages = max(1, -(-total // PAGE))
page = min(page, pages)
# Сначала номера страницы, потом тексты 12 актов: сжатые тексты всех совпадений до сортировки
# читались целиком - 2,3 с на 97 тыс. актов (замер 02.10.2026).
ids = [row[0] for row in conn.execute(f'SELECT a.id FROM {source} WHERE {clause} ORDER BY {order} '
'LIMIT ? OFFSET ?', [*args, PAGE, (page - 1) * PAGE])]
found = {row['id']: row for row in conn.execute(
f"SELECT a.*, t.body AS raw FROM acts a JOIN texts t ON t.id = a.id WHERE a.id IN ({','.join('?' * len(ids))})",
ids)} if ids else {}
rows = [found[act] for act in ids if act in found]
items = []
for row in rows:
body = split_text(zlib.decompress(row['raw']).decode('utf-8'))[2]
excerpt = next((x for x in (_excerpt(body, c, a) for c, a in refs) if x), '')
subject = SUBJECT_RE.search(body[:4000])
items.append({**self._card(row), 'excerpt': excerpt or _window(body, terms),
'subject': ' '.join(subject[0].split()) if subject else ''})
return {**empty, 'items': items, 'total': total, 'page': page, 'pages': pages}
@staticmethod
def _card(row: sqlite3.Row) -> dict:
return {k: row[k] for k in ('doc', 'url', 'title', 'kind', 'number', 'act_date', 'court', 'area', 'category')}
def act(self, doc: str) -> dict:
if not DOC_RE.fullmatch(doc or ''):
raise KeyError('Акт не найден')
with closing(self._db()) as conn:
row = conn.execute('SELECT a.*, t.body AS raw FROM acts a LEFT JOIN texts t ON t.id = a.id '
'WHERE a.doc = ?', (doc,)).fetchone()
if row is None:
raise KeyError('Акт не найден')
raw = zlib.decompress(row['raw']) if row['raw'] else b''
verified = bool(raw) and hashlib.sha256(raw).hexdigest() == row['text_sha256']
heading, court_line, body = split_text(raw.decode('utf-8')) if verified else ('', '', '')
links = citations(body)
articles = []
for code, article in dict.fromkeys((c, a) for _, _, c, a in links):
total = conn.execute('SELECT count(*) FROM refs WHERE code = ? AND article = ?',
(code, article)).fetchone()[0]
articles.append({'code': code, 'article': article, 'label': label(code, article),
'total': total, 'reader': self._reader(code, article)})
placed = conn.execute('SELECT node, reason FROM cats WHERE act = ?', (row['id'],)).fetchall()
articles.sort(key=lambda x: (x['code'], [int(n) for n in x['article'].split('.')]))
nodes = _nodes()
areas = [{'id': node, 'title': nodes[node]['title'], 'parent': nodes[node].get('parent'),
'parent_title': nodes.get(nodes[node].get('parent') or '', {}).get('title'), 'reason': reason}
for node, reason in placed if node in nodes and nodes[node].get('parent')]
return {'act': {**self._card(row), 'url': row['url'], 'fetched_at': row['fetched_at'],
'lastmod': row['lastmod'], 'sha256': row['text_sha256'], 'bytes': row['text_bytes'],
'verified': verified, 'removed_at': row['removed_at'], 'removed_code': row['removed_code']},
'heading': heading, 'court_line': court_line, 'text': body if verified else None,
'links': [{'start': s, 'end': e, 'code': c, 'article': a} for s, e, c, a in links],
'articles': articles, 'areas': areas}
def tree(self) -> dict:
return self._cached(('tree',), self._tree)
def _tree(self) -> dict:
"""Отрасли и подкатегории с числом актов; производства СудАкта - отдельным срезом."""
counts, productions, total = {}, [], 0
if self.path.is_file():
with closing(self._db()) as conn:
counts = dict(conn.execute('SELECT node, count(*) FROM cats GROUP BY node'))
total = conn.execute('SELECT count(*) FROM acts WHERE removed_at IS NULL '
'AND text_sha256 IS NOT NULL').fetchone()[0]
productions = [{'value': v, 'count': n} for v, n in conn.execute(
'SELECT category, count(*) FROM acts WHERE removed_at IS NULL AND text_sha256 IS NOT NULL '
'AND category IS NOT NULL GROUP BY category ORDER BY count(*) DESC')]
return {'ready': self.path.is_file(), 'total': total, 'productions': productions,
'areas': [{'id': area['id'], 'title': area['title'], 'count': counts.get(area['id'], 0),
'children': [{'id': child['id'], 'title': child['title'], 'count': counts.get(child['id'], 0)}
for child in area['children']]}
for area in json.loads(TAXONOMY.read_text(encoding='utf-8'))['areas']]}
def area(self, area_id: str) -> dict:
return self._cached(('area', area_id), lambda: self._area(area_id))
def _area(self, area_id: str) -> dict:
"""Малый граф одной отрасли: подкатегории, их пересечения по общим актам и самые цитируемые статьи."""
area = next((item for item in json.loads(TAXONOMY.read_text(encoding='utf-8'))['areas']
if item['id'] == area_id), None)
if area is None:
raise KeyError('Отрасль не найдена')
ids = [child['id'] for child in area['children']]
value = {'ready': self.path.is_file(), 'area': {'id': area['id'], 'title': area['title'], 'count': 0},
'children': [{'id': child['id'], 'title': child['title'], 'count': 0} for child in area['children']],
'intersections': [], 'articles': [], 'productions': []}
if not self.path.is_file():
return value
marks, live = ','.join('?' * len(ids)), 'JOIN acts x ON x.id = c.act'
with closing(self._db()) as conn:
counts = dict(conn.execute(f'SELECT c.node, count(*) FROM cats c {live} WHERE c.node IN ({marks}) '
'GROUP BY c.node', ids))
value['area']['count'] = conn.execute(f'SELECT count(*) FROM cats c {live} WHERE c.node = ?',
(area_id,)).fetchone()[0]
value['intersections'] = [{'a': a, 'b': b, 'count': n} for a, b, n in conn.execute(
f'SELECT c.node, d.node, count(*) FROM cats c {live} JOIN cats d ON d.act = c.act AND c.node < d.node '
f'WHERE c.node IN ({marks}) AND d.node IN ({marks}) GROUP BY c.node, d.node ORDER BY count(*) DESC',
ids + ids)]
top = conn.execute(f'SELECT c.node, r.article, count(*) FROM cats c {live} JOIN refs r ON r.act = c.act '
f'AND r.code = ? WHERE c.node IN ({marks}) AND r.article != ? GROUP BY c.node, r.article '
'ORDER BY count(*) DESC', [area['code'], *ids, '1']).fetchall()
value['productions'] = [{'value': v, 'count': n} for v, n in conn.execute(
f'SELECT x.category, count(*) FROM cats c {live} WHERE c.node = ? GROUP BY x.category '
'ORDER BY count(*) DESC', (area_id,))]
for child in value['children']:
child['count'] = counts.get(child['id'], 0)
per = {}
for node, article, count in top:
if len(per.setdefault(node, [])) < 3:
per[node].append({'node': node, 'code': area['code'], 'article': article, 'count': count,
'label': label(area['code'], article), 'reader': self._reader(area['code'], article)})
value['articles'] = [item for node in ids for item in per.get(node, [])]
return value
def norm(self, resource_id: str, fragment: str) -> dict:
"""Статья читателя Эвномии → сколько актов ее цитируют."""
code = re.search(r':code:([a-z0-9-]+)$', resource_id or '')
article = re.search(r'_article_(\d+(?:_\d+)*)(?=_point_|$)', fragment or '')
if not code or not article:
return {'code': None, 'article': None, 'total': 0, 'ready': self.path.is_file()}
code, article = code[1], article[1].replace('_', '.')
total = 0
if self.path.is_file():
with closing(self._db()) as conn:
total = conn.execute('SELECT count(*) FROM refs WHERE code = ? AND article = ?',
(code, article)).fetchone()[0]
return {'code': code, 'article': article, 'label': label(code, article), 'total': total,
'ready': self.path.is_file()}
def report(summary: dict) -> str:
"""Отчет владельцу словами: сколько актов, когда импорт, что со сборкой, стоит ли задача."""
def when(value: object) -> str:
moment = parse_time(value)
return moment.astimezone().strftime('%d.%m.%Y %H:%M') if moment else 'нет'
def count(value: object) -> str:
return f'{value or 0:,}'.replace(',', ' ')
last, build = summary.get('last_import') or {}, summary.get('build') or {}
added = f", новых актов: {count(last['added'])}" if last.get('added') else ''
lines = [f"Судебная практика: {count(summary['acts'])} актов, {count(summary['links'])} связей со статьями.",
f"Последний импорт: {when(last.get('finished_at'))}{added}."]
if last.get('rejected'):
lines.append(f"Не прошли сверку SHA-256: {last['rejected']}, придут повторно: {last.get('retrying', 0)}.")
due = '' if build.get('running') or not build.get('next_due') else f", следующая - {when(build['next_due'])}"
lines.append(f"Сборка Lynceuz: {build.get('meaning', 'еще не запускалась')}{due}.")
speed = summary.get('speed') or {}
lines.append('Скорость: ' + (f"вежливая, до 2 запросов в секунду, с {when(speed.get('since'))}: {speed.get('reason')}."
if speed.get('mode') == 'polite' else 'быстрая, до 10 запросов в секунду.'))
schedule = summary['schedule']
lines.append('Задача: ' + ('не установлена, команда: python3 eunomia/practice.py install' if not schedule['installed']
else f"стоит, но без {', '.join(schedule['missing_env'])} из оболочки, "
'команда: python3 eunomia/practice.py install' if schedule.get('missing_env')
else 'стоит, запуск каждый час.'))
if summary.get('error'):
lines.append('Ошибка состояния: ' + summary['error'])
return '\n'.join(lines)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description='Судебная практика СудАкта для Эвномии')
parser.add_argument('command', choices=('install', 'status', 'tick', 'import', 'classify', 'uninstall',
'progress', 'publish', 'parts', 'graph'))
parser.add_argument('--root', type=Path, default=CODE_ROOT)
parser.add_argument('--full', action='store_true', help='import: экспорт без --since; graph: полная пересборка')
parser.add_argument('--export', type=Path, help='готовый JSONL экспорта Lynceuz')
parser.add_argument('--data-root', type=Path, help='корень данных Lynceuz')
parser.add_argument('--force-build', action='store_true', help='сборка Lynceuz сейчас, вне очереди')
parser.add_argument('--json', action='store_true', help='ответ в JSON')
parser.add_argument('--publish', action='store_true', help='install/uninstall: задача страницы загрузки')
parser.add_argument('--parts', action='store_true', help='install/uninstall: задача параллельной докачки')
args = parser.parse_args(argv)
root = args.root.resolve()
label = PUBLISH_LABEL if args.publish else PARTS_LABEL if args.parts else LABEL
try:
if args.command == 'import':
value = run_import(root, full=args.full, export=args.export, data_root=args.data_root)
elif args.command == 'classify':
with _lock(root, 'import.lock'):
conn = _writer(root)
try:
value = {'classified': _classify_all(conn, taxonomy(root)), 'tree': Practice(root).tree()['areas']}
finally:
conn.close()
elif args.command == 'tick':
value = tick(root, force_build=args.force_build)
elif args.command == 'install':
value = install(root, label)
elif args.command == 'uninstall':
value = uninstall(label)
elif args.command == 'progress':
value = progress(root)
elif args.command == 'publish':
value = publish(root)
elif args.command == 'parts':
value = parts(root)
elif args.command == 'graph':
value = graph(root, full=args.full)
else:
value = Practice(root).summary()
except (PracticeError, OSError, sqlite3.Error, ValueError, subprocess.SubprocessError) as exc:
detail = f'{type(exc).__name__}: {exc}'
print(json.dumps({'status': 'error', 'detail': detail}, ensure_ascii=False) if args.json else f'Ошибка: {detail}')
return 1
if args.json or label != LABEL or args.command not in ('status', 'install'):
print(json.dumps(value, ensure_ascii=False, indent=1))
else:
head = ('Задача поставлена. Первый запуск уже идет: практика докачается сама, '
'дальше - пополнение раз в неделю.\n') if args.command == 'install' else ''
print(head + report(Practice(root).summary()))
return 0
if __name__ == '__main__':
raise SystemExit(main())