Files
smeta-web/ext_pull.py
T
anor c5e210c918 feat(ext): Фаза 4/5 — охват всех источников/документов + все регионы
fgis_client: opendata_list/meta/download (15 датасетов: КСР/ФСНБ/СПСРП/оплата труда/9 ПССР),
bim_leaf_docs (дерево писем-индексов), download_by_guid, all_subject_ids. xsd_client: скрейп
.zip-схем экспертизы (html.parser, fail-loud на 0 ссылок). ext_pull: pull_opendata/bim/xsd,
--source opendata/bim/xsd/all-sources, --regions all (все 86). ext_check: check_opendata
(lastChangeDate)/check_bim(guid)/check_xsd(ссылки) + режим all-regions — чекер мониторит ВСЁ.
10 новых тестов.
2026-07-18 10:04:17 +10:00

269 lines
12 KiB
Python

"""ext_pull — скачивание внешних данных ФГИС ЦС в версионированные снапшоты (срез 1.2).
ОСОЗНАННЫЙ шаг (не чекер): качает сплит-форму / индексы ГОСР / оплату труда по региону+
кварталу, кладёт в снапшот (ext_state.register_snapshot — crash-safe, версионирование),
отмечает в state. НЕ активирует данные для движка (это ext_apply). НЕ рестартит сервис.
Объёмы: сплит-форма ~13.7МБ × регион × квартал. По умолчанию только EXT_REGIONS
(id регионов через запятую) — НЕ все 85. Периоды: latest, если не задан.
CLI: python3 ext_pull.py --source split_form --subject 323 [--zone 191] [--period 426]
python3 ext_pull.py --source all --regions 323 # split+indices+salary
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import tempfile
import time
from pathlib import Path
import ext_fetch
import ext_state
import fgis_client as fc
SNAP = "snapshots/fgis"
POLITE_PAUSE_S = 1.5 # пауза между запросами при обходах (вежливость к гос-API, анти-429)
def _verify_xlsx(path: Path, min_rows: int) -> None:
"""Лёгкая проверка скачанного xlsx ДО регистрации: открывается + строк ≥ min.
Ловит server-side обрезанные HTTP-200 выгрузки, которые прошли по размеру (баг Fable)."""
import openpyxl
try:
wb = openpyxl.load_workbook(str(path), read_only=True)
try:
ws = wb.active
n = sum(1 for _ in ws.iter_rows(min_col=1, max_col=1, values_only=True))
finally:
wb.close()
except Exception as e: # noqa: BLE001
raise ext_fetch.FetchError(f"скачанный файл не открывается как xlsx: {type(e).__name__}: {e}")
if n < min_rows:
raise ext_fetch.FetchError(f"скачано строк {n} < {min_rows} — обрезанная выгрузка?")
def _snap_dir(kind: str, subject_id: int, zone_id: int, period_id: int) -> Path:
return ext_state.ext_dir() / SNAP / kind / str(subject_id) / str(zone_id) / str(period_id)
def _record_state(kind: str, subject_id: int, zone_id: int, period_id: int, meta: dict) -> None:
with ext_state.update_state() as st:
srcs = st["sources"].setdefault(f"fgis_{kind}", {})
srcs[f"{subject_id}/{zone_id}"] = {
"period_id": period_id, "sha256": meta["sha256"],
"rev": meta["rev"], "pulled_at": meta["fetched_at"],
"reuploaded": meta.get("reuploaded", False),
}
def _resolve_period(zone_id: int, period_id: int | None) -> int:
if period_id:
return period_id
lp = fc.latest_period(zone_id)
if not lp:
raise ext_fetch.FetchError(f"нет периодов для зоны {zone_id}") # не SystemExit из библиотеки
return lp["id"]
def pull_split_form(subject_id: int, zone_id: int, period_id: int | None = None) -> dict:
period_id = _resolve_period(zone_id, period_id)
dest_dir = _snap_dir("split_form", subject_id, zone_id, period_id)
with tempfile.TemporaryDirectory() as td:
tmp = Path(td) / "fgis_split_form.xlsx"
res = fc.download_split_form(period_id, zone_id, tmp)
_verify_xlsx(tmp, min_rows=1000) # битое/обрезанное не регистрируем
meta = ext_state.register_snapshot(
dest_dir, tmp, source="fgis_split_form", key=f"{subject_id}/{zone_id}/{period_id}",
url=fc.BASE + "/api/EstimatedPrice/BuildingResources/ExportSplitForm",
params={"periodId": period_id, "priceZoneId": zone_id})
_record_state("split_form", subject_id, zone_id, period_id, meta)
return {**meta, "downloaded_size": res["size"]}
def pull_indices(subject_id: int, zone_id: int, period_id: int | None = None) -> dict:
period_id = _resolve_period(zone_id, period_id)
dest_dir = _snap_dir("indices_gosr", subject_id, zone_id, period_id)
with tempfile.TemporaryDirectory() as td:
tmp = Path(td) / "fgis_indices_gosr.xlsx"
fc.download_indices(period_id, zone_id, tmp)
_verify_xlsx(tmp, min_rows=50) # индексы ГОСР — сотни строк; обрезанное не регистрируем
meta = ext_state.register_snapshot(
dest_dir, tmp, source="fgis_indices_gosr", key=f"{subject_id}/{zone_id}/{period_id}",
url=fc.BASE + "/api/IndicesForResourcesGroups/GenerateCustomReport",
params={"periodId": period_id, "priceZoneId": zone_id})
_record_state("indices_gosr", subject_id, zone_id, period_id, meta)
return meta
def pull_salary(subject_id: int, zone_id: int, period_id: int | None = None) -> dict:
period_id = _resolve_period(zone_id, period_id)
dest_dir = _snap_dir("salary", subject_id, zone_id, period_id)
data = fc.salary_registry(zone_id, period_id)
with tempfile.TemporaryDirectory() as td:
tmp = Path(td) / "salary_registry.json"
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")
meta = ext_state.register_snapshot(
dest_dir, tmp, source="fgis_salary", key=f"{subject_id}/{zone_id}/{period_id}",
url=fc.BASE + "/api/EstimatedPrice/RimWorkerSalaryRegistry",
params={"priceZoneId": zone_id, "periodId": period_id})
_record_state("salary", subject_id, zone_id, period_id, meta)
return {**meta, "items": data.get("total")}
def pull_opendata(dataset_id: int) -> dict:
"""Скачать текущий файл датасета открытых данных (КСР/ФСНБ/СПСРП/оплата труда/ПССР)."""
dest_dir = ext_state.ext_dir() / "snapshots/fgis/opendata" / str(dataset_id)
with tempfile.TemporaryDirectory() as td:
tmp = Path(td) / "download.bin"
_res, name = fc.download_opendata(dataset_id, tmp)
named = Path(td) / (Path(name).name or f"dataset_{dataset_id}")
tmp.replace(named)
meta = ext_state.register_snapshot(
dest_dir, named, source="fgis_opendata", key=f"opendata/{dataset_id}",
url=fc.BASE + f"/api/OpenData/{dataset_id}")
return {**meta, "dataset_id": dataset_id}
def pull_all_opendata() -> list[dict]:
out = []
for ds in fc.opendata_list():
out.append(pull_opendata(ds["id"]))
time.sleep(POLITE_PAUSE_S)
return out
def pull_bim() -> list[dict]:
"""Скачать все письма-индексы (БИМ) — листовые документы дерева NormLegalDocPublished."""
out = []
docs = fc.bim_leaf_docs()
for d in docs:
dest_dir = ext_state.ext_dir() / "snapshots/fgis/bim_letters" / d["guid"]
with tempfile.TemporaryDirectory() as td:
tmp = Path(td) / (Path(str(d.get("filePath") or "letter")).name or "letter.pdf")
fc.download_by_guid(d["guid"], tmp, expect_min_size=500)
meta = ext_state.register_snapshot(
dest_dir, tmp, source="fgis_bim", key=f"bim/{d['guid']}",
url=fc.BASE + f"/api/values/GetFileContent/{d['guid']}")
out.append({**meta, "letter": d.get("name")})
time.sleep(POLITE_PAUSE_S)
return out
def pull_xsd() -> list[dict]:
"""Скачать все .zip-пакеты XSD-схем экспертизы со страницы Минстроя."""
import xsd_client
out = []
for href in xsd_client.schema_links():
fname = xsd_client._fname(href)
dest_dir = ext_state.ext_dir() / "snapshots/xsd" / fname
with tempfile.TemporaryDirectory() as td:
tmp = Path(td) / fname
xsd_client.download_schema(href, tmp)
meta = ext_state.register_snapshot(
dest_dir, tmp, source="xsd_schema", key=f"xsd/{fname}", url=href)
out.append(meta)
time.sleep(POLITE_PAUSE_S)
return out
def _zones_of(subject_id: int) -> list[int]:
return [z["id"] for z in fc.price_zones(subject_id)]
def all_subject_ids() -> list[int]:
return [s["id"] for s in fc.country_subjects()]
def pull_all_for_subject(subject_id: int, period_id: int | None = None) -> list[dict]:
out = []
for zone_id in _zones_of(subject_id):
out.append(pull_split_form(subject_id, zone_id, period_id))
time.sleep(POLITE_PAUSE_S) # вежливость к гос-API (анти-429)
out.append(pull_indices(subject_id, zone_id, period_id))
time.sleep(POLITE_PAUSE_S)
out.append(pull_salary(subject_id, zone_id, period_id))
time.sleep(POLITE_PAUSE_S)
return out
def _regions_from_env(cli_regions: str | None) -> list[int]:
raw = (cli_regions or os.environ.get("EXT_REGIONS", "")).strip()
if raw.lower() == "all":
return all_subject_ids()
return [int(x) for x in raw.replace(";", ",").split(",") if x.strip().isdigit()]
def _p(r: dict) -> None:
print(f" ✓ {r['source']} {r['key']} rev={r['rev']} sha={r['sha256'][:12]}"
+ (" ⚠ПЕРЕЗАЛИВ" if r.get("reuploaded") else ""))
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description="Скачать данные ФГИС/схемы в снапшоты (осознанный шаг).")
ap.add_argument("--source", required=True, choices=[
"split_form", "indices", "salary", "all", # цены ФГИС по региону
"opendata", "bim", "xsd", "all-sources"]) # справочники/письма/схемы
ap.add_argument("--subject", type=int, help="id региона")
ap.add_argument("--zone", type=int, help="id ценовой зоны (если не задан — все зоны региона)")
ap.add_argument("--period", type=int, help="id периода (по умолчанию последний)")
ap.add_argument("--dataset", type=int, help="id датасета для --source opendata (иначе все)")
ap.add_argument("--regions", help="id регионов через запятую, или 'all', или env EXT_REGIONS")
args = ap.parse_args(argv)
# источники без региона (opendata/bim/xsd) — не требуют ФГИС-alive-пречека кроме ФГИС-овских
if args.source in ("opendata", "bim", "all-sources") and not fc.alive():
print("ФГИС ЦС недоступен (/api/alive). Прервано.", file=sys.stderr)
return 2
if args.source == "opendata":
for r in ([pull_opendata(args.dataset)] if args.dataset else pull_all_opendata()):
_p(r)
return 0
if args.source == "bim":
for r in pull_bim():
_p(r)
return 0
if args.source == "xsd":
for r in pull_xsd():
_p(r)
return 0
if args.source == "all-sources":
for r in pull_all_opendata() + pull_bim() + pull_xsd():
_p(r)
return 0
# ФГИС по регионам (цены/индексы/оплата)
if not fc.alive():
print("ФГИС ЦС недоступен (/api/alive). Прервано.", file=sys.stderr)
return 2
if args.source == "all":
subjects = [args.subject] if args.subject else _regions_from_env(args.regions)
if not subjects:
print("не заданы регионы: --subject, --regions=all или env EXT_REGIONS", file=sys.stderr)
return 2
failed = 0
for sid in subjects:
try:
for r in pull_all_for_subject(sid, args.period):
_p(r)
except Exception as e: # noqa: BLE001 — один регион не валит остальные
failed += 1
print(f" ✗ регион {sid}: {type(e).__name__}: {e}", file=sys.stderr)
return 1 if failed else 0
if not args.subject:
print("--subject обязателен", file=sys.stderr)
return 2
zones = [args.zone] if args.zone else _zones_of(args.subject)
fn = {"split_form": pull_split_form, "indices": pull_indices, "salary": pull_salary}[args.source]
for zone_id in zones:
_p(fn(args.subject, zone_id, args.period))
return 0
if __name__ == "__main__":
raise SystemExit(main())