release: Themiz на Gitea
This commit is contained in:
+198
-85
@@ -15,7 +15,7 @@ from html.parser import HTMLParser
|
||||
from pathlib import Path, PurePosixPath
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from update_legal_corpus import KODEKSY, SUDACT_PLENUM_CATALOG
|
||||
from update_legal_corpus import KODEKSY, SUDACT_PLENUM_CATALOG, TOC_ENTRY_TMPL, extract_article_text
|
||||
|
||||
|
||||
CONFIG = Path("config/corpus-needs.json")
|
||||
@@ -57,6 +57,11 @@ BLOCK_TAGS = frozenset({
|
||||
"ul",
|
||||
})
|
||||
DENIED_CLASS_PARTS = ("blocked-document", "snippet", "teaser", "pagination")
|
||||
# Оглавление страницы акта; после </a></li> родителя сразу идет вложенный <ul> с детьми.
|
||||
TOC_CLASS_RE = re.compile(r"""(?<![\w-])class\s*=\s*["'][^"']*(?<![\w-])document-page__toc(?![\w-])""", re.I)
|
||||
TOC_CHILD_RE = re.compile(r"\s*</li>\s*<ul\b")
|
||||
MONTHS = ("января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа",
|
||||
"сентября", "октября", "ноября", "декабря")
|
||||
|
||||
|
||||
def _plain_string(value: object, field: str, maximum: int = 1000) -> str:
|
||||
@@ -336,8 +341,9 @@ def registry(root: Path | str) -> list[dict]:
|
||||
|
||||
|
||||
class _ConsultantDocumentParser(HTMLParser):
|
||||
def __init__(self):
|
||||
def __init__(self, container: str = "document__text"):
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.container = container
|
||||
self.canonical: list[str] = []
|
||||
self.h1_depth = 0
|
||||
self.h1_parts: list[str] = []
|
||||
@@ -359,7 +365,7 @@ class _ConsultantDocumentParser(HTMLParser):
|
||||
denied_class = any(
|
||||
part in token.lower() for token in classes for part in DENIED_CLASS_PARTS)
|
||||
if self.container_stack:
|
||||
if "document__text" in classes:
|
||||
if self.container in classes:
|
||||
self.container_count += 1
|
||||
if denied_class:
|
||||
self.denied = True
|
||||
@@ -369,7 +375,7 @@ class _ConsultantDocumentParser(HTMLParser):
|
||||
self.container_stack.append(tag)
|
||||
if self.suppressed_depth or tag in {"script", "style"}:
|
||||
self.suppressed_depth += 1
|
||||
elif "document__text" in classes:
|
||||
elif self.container in classes:
|
||||
self.container_count += 1
|
||||
self.denied = self.denied or denied_class
|
||||
if tag in VOID_TAGS:
|
||||
@@ -427,27 +433,65 @@ def _yaml(value: str) -> str:
|
||||
return json.dumps(value, ensure_ascii=False)
|
||||
|
||||
|
||||
def build_generic_candidate(resource: object, receipt: object,
|
||||
now: datetime) -> tuple[str, bytes]:
|
||||
"""Строит полный verified Consultant act, не принимая snippets/чужой акт."""
|
||||
resource = validate_resource(resource)
|
||||
if resource["parser"] != "consultant-act":
|
||||
raise ValueError("generic candidate requires consultant-act")
|
||||
def _receipt_page(receipt: object, url: str) -> tuple[str, str]:
|
||||
"""Страница из квитанции: тело привязано к адресу и своему хешу, это UTF-8. Возвращает (текст, revision)."""
|
||||
if not isinstance(receipt, dict):
|
||||
raise ValueError("invalid receipt")
|
||||
body = receipt.get("body")
|
||||
if not isinstance(body, bytes) or not body or len(body) > MAX_DOCUMENT_BYTES:
|
||||
raise ValueError("invalid receipt body")
|
||||
revision = "sha256:" + hashlib.sha256(body).hexdigest()
|
||||
if (receipt.get("source_url") != resource["url"]
|
||||
or receipt.get("source_revision") != revision):
|
||||
if receipt.get("source_url") != url or receipt.get("source_revision") != revision:
|
||||
raise ValueError("receipt is not bound to resource")
|
||||
if not isinstance(now, datetime):
|
||||
raise ValueError("invalid timestamp")
|
||||
try:
|
||||
page = body.decode("utf-8")
|
||||
return body.decode("utf-8"), revision
|
||||
except UnicodeDecodeError as exc:
|
||||
raise ValueError("Consultant page is not UTF-8") from exc
|
||||
|
||||
|
||||
def _toc_html(page: str) -> str | None:
|
||||
"""Разметка оглавления: все внутри <div class="document-page__toc"> до его закрывающего </div>."""
|
||||
depth, start = 0, None
|
||||
for tag in re.finditer(r"<(/?)div\b[^>]*>", page, re.I):
|
||||
if start is None:
|
||||
if not tag.group(1) and TOC_CLASS_RE.search(tag.group(0)):
|
||||
depth, start = 1, tag.end()
|
||||
continue
|
||||
depth += -1 if tag.group(1) else 1
|
||||
if depth == 0:
|
||||
return page[start:tag.start()]
|
||||
if start is not None:
|
||||
raise ValueError("act table of contents is not closed")
|
||||
return None
|
||||
|
||||
|
||||
def _toc_parts(page: str, doc_id: str) -> list[dict]:
|
||||
"""Части акта по оглавлению: адреса по порядку без повторов (TOC_ENTRY_TMPL, как у кодексов). Ребенок
|
||||
идет вложенным <ul> сразу после </a></li> родителя. [] - на странице нет оглавления."""
|
||||
toc = _toc_html(page)
|
||||
if toc is None:
|
||||
return []
|
||||
entries = list(re.finditer(TOC_ENTRY_TMPL.format(doc_id=doc_id), toc))
|
||||
# Запись, которую регулярное выражение не берет, была бы молча пропущенной частью акта.
|
||||
if not entries or len(entries) != len(re.findall(r"<a\b", toc, re.I)):
|
||||
raise ValueError("act table of contents is not recognized")
|
||||
parts: dict[str, dict] = {}
|
||||
for entry in entries:
|
||||
parts.setdefault(entry.group(1), {
|
||||
"url": f"https://www.consultant.ru/document/cons_doc_LAW_{doc_id}/{entry.group(1)}/",
|
||||
"label": " ".join(html.unescape(entry.group(2)).split()),
|
||||
"parent": TOC_CHILD_RE.match(toc, entry.end()) is not None,
|
||||
})
|
||||
return list(parts.values())
|
||||
|
||||
|
||||
def _act_page(resource: object, receipt: object) -> tuple[dict, str, _ConsultantDocumentParser, list[dict]]:
|
||||
"""Страница акта: привязка квитанции, canonical и шапка (название, дата, номер). Возвращает (ресурс,
|
||||
revision, разбор страницы, части по оглавлению); части есть, только если у страницы нет document__text."""
|
||||
resource = validate_resource(resource)
|
||||
if resource["parser"] != "consultant-act":
|
||||
raise ValueError("generic candidate requires consultant-act")
|
||||
page, revision = _receipt_page(receipt, resource["url"])
|
||||
parser = _ConsultantDocumentParser()
|
||||
parser.feed(page)
|
||||
parser.close()
|
||||
@@ -463,90 +507,155 @@ def build_generic_candidate(resource: object, receipt: object,
|
||||
or resource["date"] not in heading
|
||||
or not re.search(rf"\bN\s*{re.escape(resource['number'])}\b", heading)):
|
||||
raise ValueError("act identity mismatch")
|
||||
toc = _toc_parts(page, expected_doc_id) if parser.container_count == 0 else []
|
||||
if not toc and (parser.container_count != 1 or parser.denied or parser.malformed
|
||||
or parser.container_stack):
|
||||
raise ValueError("full document__text is absent")
|
||||
return resource, revision, parser, toc
|
||||
|
||||
|
||||
def act_parts(resource: object, receipt: object) -> list[dict]:
|
||||
"""Части акта по оглавлению его страницы: [{url, label, parent}]. [] - весь текст лежит на странице."""
|
||||
return _act_page(resource, receipt)[3]
|
||||
|
||||
|
||||
def act_part_section(part: dict, receipt: object) -> str:
|
||||
"""Раздел акта по странице части: «## метка оглавления» и текст (extract_article_text, как у кодексов).
|
||||
Canonical равен адресу части, запрещенного класса внутри document-page__content нет. Текст пуст только у
|
||||
родителя вложенного списка, у которого на странице есть заголовок."""
|
||||
page, _ = _receipt_page(receipt, part["url"])
|
||||
parser = _ConsultantDocumentParser("document-page__content")
|
||||
parser.feed(page)
|
||||
parser.close()
|
||||
if parser.canonical != [part["url"]]:
|
||||
raise ValueError("act part canonical mismatch")
|
||||
if (parser.container_count != 1 or parser.denied or parser.malformed
|
||||
or parser.container_stack):
|
||||
raise ValueError("full document__text is absent")
|
||||
text = _normal_text(parser.body_parts)
|
||||
raise ValueError("full document-page__content is absent")
|
||||
text = extract_article_text(receipt["body"])
|
||||
if not re.search(r"[0-9A-Za-zА-Яа-я]", text):
|
||||
raise ValueError("full document__text is empty")
|
||||
lines = [
|
||||
"---",
|
||||
f"источник: {_yaml(resource['url'])}",
|
||||
f"название: {_yaml(resource['title'])}",
|
||||
f"дата_акта: {_yaml(resource['date'])}",
|
||||
f"номер_акта: {_yaml(resource['number'])}",
|
||||
f"canonical_doc_id: {_yaml(expected_doc_id)}",
|
||||
f"дата_выгрузки: {_yaml(now.strftime('%d.%m.%Y'))}",
|
||||
f"sha256: {_yaml(revision)}",
|
||||
"---",
|
||||
"",
|
||||
f"# {resource['title']}",
|
||||
"",
|
||||
text,
|
||||
"",
|
||||
]
|
||||
return resource["output"], "\n".join(lines).encode("utf-8")
|
||||
if not (part["parent"] and _normal_text(parser.h1_parts)):
|
||||
raise ValueError("act part text is empty")
|
||||
text = ""
|
||||
return f"## {part['label']}" + (f"\n\n{text}" if text else "")
|
||||
|
||||
|
||||
def _toc_text(toc: list[dict], parts: object, act_url: str, act_revision: str) -> tuple[str, str]:
|
||||
"""Текст акта из частей и общая revision страниц. Части - ровно по оглавлению: без пропусков, повторов,
|
||||
чужих страниц и перестановок."""
|
||||
if parts is None:
|
||||
raise ValueError("act parts are required")
|
||||
parts = list(parts)
|
||||
wanted = [part["url"] for part in toc]
|
||||
got = [item.get("source_url") if isinstance(item, dict) else None for item in parts]
|
||||
if got != wanted:
|
||||
if set(got) - set(wanted):
|
||||
raise ValueError("act part is foreign")
|
||||
if set(wanted) - set(got):
|
||||
raise ValueError("act part is missing")
|
||||
raise ValueError("act parts are out of order or repeated")
|
||||
text = "\n\n".join(act_part_section(part, item) for part, item in zip(toc, parts))
|
||||
pages = [(act_url, act_revision), *((part["url"], item["source_revision"])
|
||||
for part, item in zip(toc, parts))]
|
||||
digest = hashlib.sha256("\n".join(f"{url} {revision}" for url, revision in pages).encode()).hexdigest()
|
||||
return text, "sha256:" + digest
|
||||
|
||||
|
||||
def build_generic_candidate(resource: object, receipt: object, now: datetime,
|
||||
parts: list[dict] | None = None) -> tuple[str, bytes]:
|
||||
"""Строит полный verified Consultant act, не принимая snippets/чужой акт. Акт без document__text, но с
|
||||
оглавлением собирается по частям: parts - квитанции частей в порядке оглавления (act_parts)."""
|
||||
resource, revision, parser, toc = _act_page(resource, receipt)
|
||||
if not isinstance(now, datetime):
|
||||
raise ValueError("invalid timestamp")
|
||||
if toc:
|
||||
text, revision = _toc_text(toc, parts, resource["url"], revision)
|
||||
elif parts:
|
||||
raise ValueError("act part is foreign")
|
||||
else:
|
||||
text = _normal_text(parser.body_parts)
|
||||
if not re.search(r"[0-9A-Za-zА-Яа-я]", text):
|
||||
raise ValueError("full document__text is empty")
|
||||
return resource["output"], _markdown(
|
||||
[("источник", resource["url"]), ("название", resource["title"]), ("дата_акта", resource["date"]),
|
||||
("номер_акта", resource["number"]),
|
||||
("canonical_doc_id", CONSULTANT_RE.fullmatch(resource["url"]).group(1)),
|
||||
("дата_выгрузки", now.strftime("%d.%m.%Y")), ("sha256_источника", revision)],
|
||||
f"# {resource['title']}\n\n{text}\n")
|
||||
|
||||
|
||||
def _review_pdf_text(body: bytes) -> str:
|
||||
"""Текст PDF обзора через PDFium - основной путь чтения PDF в доме: pypdf рвет слова пробелами
|
||||
(«декаб ря», «граж данину»). Номер страницы в начале страницы снимается: иначе граф права принял бы его
|
||||
за пункт обзора. Строка без пробела или тире в конце - конец абзаца (так PDFium отдает текст из Word)."""
|
||||
import pypdfium2 as pdfium
|
||||
pdf = pdfium.PdfDocument(body)
|
||||
try:
|
||||
pages = []
|
||||
for page in pdf:
|
||||
lines = page.get_textpage().get_text_range().replace("\r\n", "\n").rstrip("\n").split("\n")
|
||||
if lines and lines[0].strip().isdigit():
|
||||
lines = lines[1:]
|
||||
pages.append("\n".join(lines))
|
||||
finally:
|
||||
pdf.close()
|
||||
text = "\n".join(pages).replace("", "-").replace("", "–")
|
||||
return _normal_text([re.sub(r"(?<![ –-])\n", "\n\n", text)])
|
||||
|
||||
|
||||
def _review_identity(value: str) -> str:
|
||||
"""Шапка PDF набрана прописными, к слову приклеена сноска («ФЕДЕРАЦИИ1»)."""
|
||||
return _identity(re.sub(r"(?<=[^\W\d_])\d{1,2}\b", "", value)).casefold()
|
||||
|
||||
|
||||
def build_review_candidate(resource: object, receipt: object,
|
||||
now: datetime) -> tuple[str, bytes]:
|
||||
"""Review parser disabled: `review_parser_not_verified` до отдельной приемки."""
|
||||
raise ValueError("review_parser_not_verified")
|
||||
|
||||
|
||||
def _build_review_candidate_unverified(resource: object, receipt: object,
|
||||
now: datetime) -> tuple[str, bytes]:
|
||||
"""Непринятый parser обзоров: сохранен только для отдельной приемки."""
|
||||
"""Строит полный обзор ВС РФ из PDF vsrf.ru: шапка с названием, номером и датой утверждения -
|
||||
этого обзора, текст полный. HTML-страницы (заглушки, капча) не принимаются."""
|
||||
resource = validate_resource(resource)
|
||||
if resource["parser"] != "vsrf-review":
|
||||
raise ValueError("review candidate requires vsrf-review")
|
||||
if not isinstance(receipt, dict) or not isinstance(receipt.get("body"), bytes):
|
||||
if not isinstance(receipt, dict):
|
||||
raise ValueError("invalid receipt")
|
||||
body = receipt["body"]
|
||||
body = receipt.get("body")
|
||||
if not isinstance(body, bytes) or not body or len(body) > MAX_DOCUMENT_BYTES:
|
||||
raise ValueError("invalid receipt body")
|
||||
revision = "sha256:" + hashlib.sha256(body).hexdigest()
|
||||
if receipt.get("source_url") != resource["url"] or receipt.get("source_revision") != revision:
|
||||
raise ValueError("receipt is not bound to resource")
|
||||
if not isinstance(now, datetime):
|
||||
raise ValueError("invalid timestamp")
|
||||
if body.startswith(b"%PDF-"):
|
||||
try:
|
||||
from pypdf import PdfReader
|
||||
import io
|
||||
pages = PdfReader(io.BytesIO(body)).pages
|
||||
text = _normal_text([page.extract_text() or "" for page in pages])
|
||||
except Exception as exc:
|
||||
raise ValueError("review PDF extraction failed") from exc
|
||||
heading = text[:2000]
|
||||
parser = None
|
||||
else:
|
||||
parser = _ConsultantDocumentParser()
|
||||
try:
|
||||
page = body.decode("utf-8")
|
||||
except UnicodeDecodeError as exc:
|
||||
raise ValueError("VS RF page is not UTF-8") from exc
|
||||
parser.feed(page)
|
||||
parser.close()
|
||||
heading = _normal_text(parser.h1_parts)
|
||||
text = _normal_text(parser.body_parts)
|
||||
if not heading:
|
||||
heading = resource["title"]
|
||||
if (_identity(heading) != _identity(resource["title"])
|
||||
or resource["date"] not in heading
|
||||
or resource["number"] not in heading):
|
||||
raise ValueError("review identity mismatch")
|
||||
if (parser is not None and (parser.denied or parser.malformed)) or not re.search(r"[0-9A-Za-zА-Яа-я]", text):
|
||||
raise ValueError("full review text is absent")
|
||||
if len(text) < 200:
|
||||
raise ValueError("review text is incomplete")
|
||||
checked = receipt.get("checked_at")
|
||||
if not isinstance(checked, str):
|
||||
raise ValueError("receipt checked_at missing")
|
||||
lines = ["---", f"источник: {_yaml(resource['url'])}",
|
||||
f"название: {_yaml(resource['title'])}", f"дата_акта: {_yaml(resource['date'])}",
|
||||
f"номер_акта: {_yaml(resource['number'])}", f"дата_выгрузки: {_yaml(now.strftime('%d.%m.%Y'))}",
|
||||
f"дата_проверки: {_yaml(checked)}", f"sha256: {_yaml(revision[7:])}", "---", "",
|
||||
f"# {resource['title']}", "", text, ""]
|
||||
return resource["output"], "\n".join(lines).encode("utf-8")
|
||||
if not body.startswith(b"%PDF-"):
|
||||
raise ValueError("review source is not PDF")
|
||||
try:
|
||||
text = _review_pdf_text(body)
|
||||
except Exception as exc: # noqa: BLE001 - любой сбой PDFium = документ не принят
|
||||
raise ValueError("review PDF extraction failed") from exc
|
||||
heading = _review_identity(text[:3000])
|
||||
day, month, year = resource["date"].split(".")
|
||||
date_words = f"{int(day)} {MONTHS[int(month) - 1]} {year}"
|
||||
if (_review_identity(resource["title"]) not in heading
|
||||
or (resource["date"] not in heading and date_words not in heading)
|
||||
or resource["number"].casefold() not in heading):
|
||||
raise ValueError("review identity mismatch")
|
||||
if len(text) < 200:
|
||||
raise ValueError("review text is incomplete")
|
||||
return resource["output"], _markdown(
|
||||
[("источник", resource["url"]), ("название", resource["title"]), ("дата_акта", resource["date"]),
|
||||
("номер_акта", resource["number"]), ("дата_выгрузки", now.strftime("%d.%m.%Y")),
|
||||
("дата_проверки", checked), ("sha256_источника", revision)],
|
||||
f"# {resource['title']}\n\n{text}\n")
|
||||
|
||||
|
||||
def _markdown(fields: list[tuple[str, str]], body: str) -> bytes:
|
||||
"""Frontmatter + тело. sha256 - хеш тела после frontmatter: его сверяет граф права
|
||||
(legal_graph._read_source); хеш скачанного источника - отдельным полем."""
|
||||
lines = ["---", *(f"{key}: {_yaml(value)}" for key, value in fields),
|
||||
f"sha256: {_yaml(hashlib.sha256(body.encode('utf-8')).hexdigest())}", "---", ""]
|
||||
return ("\n".join(lines) + body).encode("utf-8")
|
||||
|
||||
|
||||
def _write_config(root: Path, value: dict) -> None:
|
||||
@@ -618,7 +727,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1])
|
||||
parser.add_argument("--add", action="store_true")
|
||||
parser.add_argument("--source")
|
||||
parser.add_argument("--kind", choices=("federal-law", "bylaw"))
|
||||
parser.add_argument("--kind", choices=("federal-law", "bylaw", "review"))
|
||||
parser.add_argument("--title")
|
||||
parser.add_argument("--date")
|
||||
parser.add_argument("--number")
|
||||
@@ -630,10 +739,14 @@ def main(argv: list[str] | None = None) -> int:
|
||||
if any(value is None for value in fields):
|
||||
parser.error("--add требует source/kind/title/date/number/slug")
|
||||
try:
|
||||
resource = add_need(
|
||||
args.root, source=args.source, kind=args.kind, title=args.title,
|
||||
date=args.date, number=args.number, slug=args.slug,
|
||||
)
|
||||
if args.kind == "review": # обзор ВС РФ: PDF vsrf.ru, разборщик vsrf-review
|
||||
resource = add_review(args.root, source=args.source, title=args.title,
|
||||
date=args.date, number=args.number, slug=args.slug)
|
||||
else:
|
||||
resource = add_need(
|
||||
args.root, source=args.source, kind=args.kind, title=args.title,
|
||||
date=args.date, number=args.number, slug=args.slug,
|
||||
)
|
||||
except ValueError as exc:
|
||||
print(str(exc), file=sys.stderr)
|
||||
return 2
|
||||
|
||||
Reference in New Issue
Block a user