Страница collections-of-add-ons/index.php — оглавление без PDF; настоящий список лежит в collections-of-add-ons-to-the-tsn-2001 (71 файл) и -13-2 (49). Пороги разделов подняты к фактическим числам (наполовину от факта), чтобы «похудение» раздела действительно останавливало обход. Co-Authored-By: Claude Code <noreply@anthropic.com>
357 lines
16 KiB
Python
357 lines
16 KiB
Python
"""niac_client — обход официальных разделов ГАУ «НИАЦ» с ТСН-2001.
|
||
|
||
Зачем: база ТСН опубликована на niac.mos.ru (исследование
|
||
`docs/RESEARCH_2026-11-18_tsn_open_sources.md`), но у неё нет ни API, ни выгрузки —
|
||
только страницы со ссылками на PDF. Модуль делает две вещи: превращает страницы
|
||
разделов в манифест документов с устойчивыми ключами и скачивает нужный файл,
|
||
проверяя, что это действительно целый PDF.
|
||
|
||
Правила, которые здесь зафиксированы:
|
||
- **Ключ документа не из URL.** Переезд файла внутри сайта не должен рождать
|
||
«новый документ»; ключ — раздел, книга, глава и версия. Совпавшие ключи
|
||
разводятся коротким хэшем адреса, чтобы разные файлы не терялись.
|
||
- **Только свой хост.** Абсолютная ссылка на чужой адрес в манифест не попадает:
|
||
иначе подсунутая страница уводит загрузчик на произвольный сервер.
|
||
- **Пустой или резко похудевший раздел — аномалия,** а не «нет обновлений».
|
||
- **Неопознанное не скачивается:** без книги, номера дополнения или выпуска
|
||
документ помечается `unclassified`.
|
||
- **Файл проверяется до подмены.** Скачиваем во временное имя, проверяем сигнатуру
|
||
и число страниц, и только потом заменяем целевой файл.
|
||
|
||
Сеть — через `ext_fetch` (ретраи, `.part`, атомарная замена): второго загрузчика
|
||
в проекте быть не должно.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import hashlib
|
||
import os
|
||
import re
|
||
from html.parser import HTMLParser
|
||
from pathlib import Path
|
||
from urllib.parse import unquote, urljoin, urlparse
|
||
|
||
import ext_fetch
|
||
import ext_sources
|
||
|
||
BASE = "https://niac.mos.ru/standards/tsn-2001/"
|
||
ALLOWED_HOST = "niac.mos.ru"
|
||
|
||
# Разделы, которые обходим. min_docs — нижняя граница «раздел жив»; резкое падение
|
||
# против прошлого обхода ловится отдельно (expected_at_least из состояния).
|
||
# Пороги сняты с боевых страниц 18.11.2026 и стоят заметно ниже факта:
|
||
# 8, 42, 41, 10, 20, 30, 18, 2, 71, 49, 151 файл соответственно. Порог ниже факта
|
||
# вдвое — это и есть «резкое похудение раздела», которое обязано остановить обход.
|
||
SECTIONS = (
|
||
{"name": "collections", "url": BASE + "collectors-tsn-2001/index.php", "min_docs": 5},
|
||
{"name": "collections_3", "url": BASE + "collectors-tsn-2001/tsn-2001-3/index.php", "min_docs": 20},
|
||
{"name": "collections_4", "url": BASE + "collectors-tsn-2001/tsn-2001-4/index.php", "min_docs": 20},
|
||
{"name": "collections_5", "url": BASE + "collectors-tsn-2001/tsn-2001-5/index.php", "min_docs": 5},
|
||
{"name": "collections_6", "url": BASE + "collectors-tsn-2001/tsn-2001-6/index.php", "min_docs": 10},
|
||
{"name": "collections_7", "url": BASE + "collectors-tsn-2001/tsn-2001-7/index.php", "min_docs": 15},
|
||
{"name": "collections_12", "url": BASE + "collectors-tsn-2001/tsn-2001-12/index.php", "min_docs": 8},
|
||
{"name": "collections_13", "url": BASE + "collectors-tsn-2001/tsn-2001-13/index.php", "min_docs": 1},
|
||
{"name": "additions", "url": BASE + "collections-of-add-ons-to-the-tsn-2001/index.php", "min_docs": 30},
|
||
{"name": "additions_13_2", "url": BASE + "collections-of-add-ons-to-the-tsn-2001-13-2/index.php", "min_docs": 20},
|
||
{"name": "indices", "url": BASE + "the-values-of-smr-recalculation/index.php", "min_docs": 80},
|
||
)
|
||
|
||
_RATE_BOOKS = {"3", "4", "5", "6", "7"}
|
||
|
||
|
||
class SourceEmptyError(ext_fetch.FetchError):
|
||
"""Раздел отдал меньше файлов, чем обязан: похоже, сайт изменил структуру."""
|
||
|
||
|
||
class _Anchors(HTMLParser):
|
||
"""Сбор ссылок. Незакрытый <a> не должен терять документ: следующая ссылка
|
||
закрывает предыдущую неявно, как это делает браузер."""
|
||
|
||
def __init__(self) -> None:
|
||
super().__init__(convert_charrefs=True)
|
||
self.items: list[tuple[str, str]] = []
|
||
self._href: str | None = None
|
||
self._text: list[str] = []
|
||
|
||
def _flush(self) -> None:
|
||
if self._href is not None:
|
||
self.items.append((self._href, " ".join("".join(self._text).split())))
|
||
self._href = None
|
||
self._text = []
|
||
|
||
def handle_starttag(self, tag, attrs):
|
||
if tag == "a":
|
||
self._flush()
|
||
self._href = dict(attrs).get("href")
|
||
self._text = []
|
||
|
||
def handle_data(self, data):
|
||
if self._href is not None:
|
||
self._text.append(data)
|
||
|
||
def handle_endtag(self, tag):
|
||
if tag == "a":
|
||
self._flush()
|
||
|
||
def close(self):
|
||
self._flush()
|
||
super().close()
|
||
|
||
|
||
_BOOK_RE = re.compile(r"ТСН[\s-]?2001\.(\d+)(?:-(\d+))?", re.IGNORECASE)
|
||
_ISSUE_RE = re.compile(r"Выпуск\s*(\d+)", re.IGNORECASE)
|
||
_ADDENDUM_RE = re.compile(r"дополнени\w*\s*№?\s*(\d+)|доп\.?\s*(\d+)", re.IGNORECASE)
|
||
_QUARTER_RE = re.compile(r"\b(I{1,3}V?|IV)\s*квартал\s*(\d{4})", re.IGNORECASE)
|
||
_DECREE_RE = re.compile(r"МКЭ-ОД/\d+-\d+", re.IGNORECASE)
|
||
_ROMAN = {"I": 1, "II": 2, "III": 3, "IV": 4}
|
||
|
||
|
||
def _short_hash(text: str) -> str:
|
||
return hashlib.sha1(text.encode("utf-8")).hexdigest()[:8]
|
||
|
||
|
||
def _slug(text: str) -> str:
|
||
out = re.sub(r"[^\wа-яё]+", "-", text.lower(), flags=re.IGNORECASE).strip("-")[:60] or "doc"
|
||
return f"{out}-{_short_hash(text)}"
|
||
|
||
|
||
def _is_allowed(url: str) -> bool:
|
||
"""Только официальный сайт: чужой хост в манифест не пускаем."""
|
||
u = urlparse(url)
|
||
return u.scheme == "https" and (u.hostname or "").endswith(ALLOWED_HOST)
|
||
|
||
|
||
def _is_pdf_link(url: str) -> bool:
|
||
return urlparse(url).path.lower().endswith(".pdf")
|
||
|
||
|
||
def _kind(title: str, url: str, book: str | None, issue_no: str | None,
|
||
addendum_no: str | None) -> str:
|
||
low = title.lower()
|
||
if "коэффициент" in low or "индекс" in low:
|
||
return "index_release"
|
||
if addendum_no:
|
||
return "addendum"
|
||
if book is None and issue_no:
|
||
return "index_release"
|
||
if not book:
|
||
return "unclassified"
|
||
number = book.removeprefix("ТСН-2001.").split("-")[0]
|
||
if number == "1":
|
||
return "price_book"
|
||
if number == "2":
|
||
return "machine_book"
|
||
if number in _RATE_BOOKS:
|
||
return "rate_book"
|
||
if number == "8":
|
||
return "nr_sp"
|
||
if number == "9":
|
||
return "winter"
|
||
if number == "10":
|
||
return "temp"
|
||
if number == "11":
|
||
return "other_works"
|
||
if number == "12":
|
||
return "rule"
|
||
return "book"
|
||
|
||
|
||
def parse_section_html(html: str, base_url: str, section: str = "") -> list[dict]:
|
||
"""Страница раздела → манифест документов. Чистая функция: сети не трогает.
|
||
|
||
- не-PDF ссылки и чужие хосты отбрасываются;
|
||
- при повторе URL остаётся самый информативный заголовок, а не первый;
|
||
- параметры адреса сохраняются: ссылка `/a.pdf?doc=2` должна качаться с ними;
|
||
- совпавшие ключи разводятся хэшем адреса, чтобы разные файлы не исчезали.
|
||
"""
|
||
parser = _Anchors()
|
||
parser.feed(html)
|
||
parser.close()
|
||
|
||
by_url: dict[str, str] = {}
|
||
for href, text in parser.items:
|
||
if not href:
|
||
continue
|
||
url = urljoin(base_url, href).split("#")[0]
|
||
if not _is_pdf_link(url) or not _is_allowed(url):
|
||
continue
|
||
title = text.strip() or unquote(os.path.basename(urlparse(url).path))
|
||
if url not in by_url or len(title) > len(by_url[url]):
|
||
by_url[url] = title
|
||
|
||
docs: list[dict] = []
|
||
for url, title in by_url.items():
|
||
book_m = _BOOK_RE.search(title)
|
||
book = chapter = None
|
||
if book_m:
|
||
book = f"ТСН-2001.{book_m.group(1)}"
|
||
if book_m.group(2):
|
||
chapter = f"{book_m.group(1)}-{book_m.group(2)}"
|
||
|
||
issue_m = _ISSUE_RE.search(title)
|
||
issue_no = issue_m.group(1) if issue_m else None
|
||
add_m = _ADDENDUM_RE.search(title)
|
||
addendum_no = (add_m.group(1) or add_m.group(2)) if add_m else None
|
||
quarter_m = _QUARTER_RE.search(title)
|
||
quarter = _ROMAN.get(quarter_m.group(1).upper()) if quarter_m else None
|
||
year = int(quarter_m.group(2)) if quarter_m else None
|
||
decree_m = _DECREE_RE.search(title)
|
||
|
||
kind = _kind(title, url, book, issue_no, addendum_no)
|
||
edition_bits = []
|
||
if addendum_no:
|
||
edition_bits.append(f"доп.{addendum_no}")
|
||
if issue_no:
|
||
edition_bits.append(f"выпуск {issue_no}")
|
||
edition = ", ".join(edition_bits) or (f"ред. {year}" if year else "")
|
||
|
||
if book and chapter and edition:
|
||
tail = f"{chapter}@{edition}"
|
||
elif book:
|
||
tail = chapter or edition or "base"
|
||
elif edition:
|
||
tail = edition
|
||
else:
|
||
tail = _slug(title)
|
||
|
||
docs.append({
|
||
"key": f"{section}/{book or 'nobook'}/{tail}",
|
||
"section": section,
|
||
"kind": kind,
|
||
"book": book,
|
||
"chapter": chapter,
|
||
"title": title,
|
||
"url": url,
|
||
"edition": edition,
|
||
"addendum_no": addendum_no,
|
||
"issue_no": issue_no,
|
||
"period_label": f"{quarter_m.group(1).upper()} квартал {year}" if quarter_m else None,
|
||
"quarter": quarter,
|
||
"year": year,
|
||
"decree": decree_m.group(0) if decree_m else None,
|
||
})
|
||
|
||
# Совпал ключ: одинаковые названия — это одна и та же ссылка, попавшая на
|
||
# страницу дважды (переезд файла) — оставляем одну; разные названия — разные
|
||
# документы (например, «часть 1» и «часть 2») — разводим хэшем адреса.
|
||
groups: dict[str, list[dict]] = {}
|
||
for d in docs:
|
||
groups.setdefault(d["key"], []).append(d)
|
||
result: list[dict] = []
|
||
for items in groups.values():
|
||
if len(items) == 1:
|
||
result.append(items[0])
|
||
continue
|
||
if len({x["title"] for x in items}) == 1:
|
||
result.append(items[0])
|
||
continue
|
||
for x in items:
|
||
x["key"] = f"{x['key']}--{_short_hash(x['url'])}"
|
||
result.append(x)
|
||
return result
|
||
|
||
|
||
def fetch_text(url: str, client=None) -> str: # обёртка: в тестах подменяется
|
||
return ext_fetch.fetch_text(url, client=client)
|
||
|
||
|
||
def discover_section(section: dict, client=None, expected_at_least: int | None = None) -> list[dict]:
|
||
"""Манифест одного раздела. Резкое падение числа файлов — аномалия."""
|
||
html = fetch_text(section["url"], client=client)
|
||
docs = parse_section_html(html, section["url"], section=section["name"])
|
||
floor = section.get("min_docs", 1)
|
||
if expected_at_least is not None:
|
||
floor = max(floor, int(expected_at_least * 0.5))
|
||
if len(docs) < floor:
|
||
raise SourceEmptyError(
|
||
f"раздел {section['name']} отдал {len(docs)} файлов, ожидалось не меньше {floor}"
|
||
+ (f" (в прошлый раз было {expected_at_least})" if expected_at_least else "")
|
||
+ " — похоже, структура сайта изменилась")
|
||
return docs
|
||
|
||
|
||
def discover(sections=None, client=None, previous_counts: dict | None = None) -> list[dict]:
|
||
"""Обойти разделы; вернуть общий манифест. Один упавший раздел валит обход."""
|
||
docs: list[dict] = []
|
||
seen: set[str] = set()
|
||
counts = previous_counts or {}
|
||
for section in (sections or SECTIONS):
|
||
part = discover_section(section, client=client,
|
||
expected_at_least=counts.get(section["name"]))
|
||
for doc in part:
|
||
if doc["key"] in seen:
|
||
continue
|
||
seen.add(doc["key"])
|
||
docs.append(doc)
|
||
return docs
|
||
|
||
|
||
def ensure_registered() -> ext_sources.Source:
|
||
"""Источник в общем реестре. Регистрация идемпотентна: повтор не падает."""
|
||
existing = ext_sources.by_name("niac_tsn")
|
||
if existing is not None:
|
||
return existing
|
||
return ext_sources.register(ext_sources.Source(
|
||
name="niac_tsn", kind="docs", title="ТСН-2001 (НИАЦ, Москва)", freq="daily",
|
||
check=None,
|
||
notes="PDF качаются и удаляются после разбора; см. docs/PLAN_2026-11-18_tsn.md"))
|
||
|
||
|
||
def _pdf_pages(path: str) -> tuple[int | None, str | None]:
|
||
"""(страницы, причина). «Нет библиотеки» и «файл битый» — разные вещи."""
|
||
try:
|
||
import fitz # PyMuPDF
|
||
except Exception: # noqa: BLE001
|
||
return None, "no_fitz"
|
||
try:
|
||
with fitz.open(path) as doc:
|
||
return doc.page_count, None
|
||
except Exception: # noqa: BLE001
|
||
return None, "corrupt"
|
||
|
||
|
||
def download(doc: dict, dest: os.PathLike | str, client=None) -> dict:
|
||
"""Скачать документ. Неопознанный — не качаем. Проверка ДО подмены файла."""
|
||
if doc.get("kind") == "unclassified":
|
||
return {"skipped": True, "reason": "документ не опознан (нет книги и версии)"}
|
||
dest = Path(dest)
|
||
incoming = dest.with_name(dest.name + ".incoming")
|
||
if incoming.exists():
|
||
incoming.unlink()
|
||
try:
|
||
got = ext_fetch.fetch_file(doc["url"], incoming, expect_min_size=10_000,
|
||
expected_content_type="application/pdf", client=client)
|
||
head = incoming.read_bytes()[:5]
|
||
if head != b"%PDF-":
|
||
raise ext_fetch.FetchError(f"не PDF: {doc['url']} начинается с {head!r}")
|
||
pages, problem = _pdf_pages(str(incoming))
|
||
if problem == "corrupt":
|
||
raise ext_fetch.FetchError(f"PDF не открывается: {doc['url']}")
|
||
os.replace(incoming, dest)
|
||
return {"skipped": False, "path": str(dest), "size": got["size"],
|
||
"sha256": got["sha256"], "pages": pages,
|
||
"note": "страницы не проверены: нет PyMuPDF" if problem == "no_fitz" else ""}
|
||
finally:
|
||
if incoming.exists():
|
||
incoming.unlink()
|
||
|
||
|
||
def probe_volatile(doc: dict, client=None) -> dict:
|
||
"""Заголовки ответа без скачивания. Ошибки не глотаем: 405/503 — не «не изменилось»."""
|
||
c = client or ext_fetch.make_client()
|
||
try:
|
||
try:
|
||
r = c.head(doc["url"])
|
||
except Exception as e: # noqa: BLE001 — сырой httpx наружу не пускаем
|
||
raise ext_fetch.FetchError(f"HEAD {doc['url']}: {type(e).__name__}: {e}") from e
|
||
if r.status_code >= 400:
|
||
raise ext_fetch.FetchError(f"HEAD {doc['url']}: {r.status_code}")
|
||
return {
|
||
"status": r.status_code,
|
||
"etag": r.headers.get("etag"),
|
||
"last_modified": r.headers.get("last-modified"),
|
||
"content_length": r.headers.get("content-length"),
|
||
}
|
||
finally:
|
||
if client is None:
|
||
c.close()
|