Show coverage of all normative databases on public landing
This commit is contained in:
+99
-17
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
import html
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
@@ -16,6 +17,20 @@ _cache_value: dict | None = None
|
||||
_norm_sig: tuple | None = None
|
||||
_norm_value: int | None = None
|
||||
|
||||
# Метрики относятся к разным сущностям; их нельзя складывать в «число документов».
|
||||
_DB_METRICS = {
|
||||
"fsnb/fsnb_ref.sqlite": {"fsnb_works": "SELECT COUNT(*) FROM works",
|
||||
"fsnb_resources": "SELECT COUNT(*) FROM resources"},
|
||||
"fgis_ref/fgis_ref.sqlite": {"fgis_items": "SELECT COUNT(*) FROM items",
|
||||
"ksr": "SELECT COUNT(*) FROM ksr",
|
||||
"fgis_price_rows": "SELECT COALESCE(SUM(rows_loaded), 0) FROM zone_snapshots"},
|
||||
"tsn/tsn_ref.sqlite": {"tsn_works": "SELECT COUNT(*) FROM works",
|
||||
"tsn_prices": "SELECT COUNT(*) FROM price_items"},
|
||||
"regional_ref/regional_ref.sqlite": {"regional_works": "SELECT COUNT(*) FROM works",
|
||||
"regional_prices": "SELECT COUNT(*) FROM prices"},
|
||||
}
|
||||
_DB_KEYS = tuple(key for queries in _DB_METRICS.values() for key in queries)
|
||||
|
||||
|
||||
def clear_cache() -> None:
|
||||
"""Сброс снимка для тестов и оператора после ручного обновления корпуса."""
|
||||
@@ -47,7 +62,7 @@ def _date(value: object) -> tuple[str, str] | None:
|
||||
def _read_export(path: Path) -> dict:
|
||||
raw = _read_meta(path)
|
||||
if not raw or not isinstance(raw.get("count"), int) or raw["count"] < 0:
|
||||
return {"count": 0, "recent": []}
|
||||
return {"count": 0, "recent": [], "document_counts": {}}
|
||||
recent = []
|
||||
source_items = raw.get("recent")
|
||||
for doc in (source_items[:4] if isinstance(source_items, list) else []):
|
||||
@@ -58,7 +73,35 @@ def _read_export(path: Path) -> dict:
|
||||
if (isinstance(title, str) and title.strip() and
|
||||
source in ("ТСН Москвы", "ФГИС ЦС") and loaded):
|
||||
recent.append({"title": title, "source": source, "loaded": loaded})
|
||||
return {"count": raw["count"], "recent": recent}
|
||||
counts = raw.get("document_counts")
|
||||
counts = counts if isinstance(counts, dict) else {}
|
||||
return {"count": raw["count"], "recent": recent,
|
||||
"document_counts": {key: counts[key] for key in ("bim_letters", "tsn_documents")
|
||||
if type(counts.get(key)) is int and counts[key] >= 0}}
|
||||
|
||||
|
||||
def _external_metrics(root: Path) -> dict[str, int | None]:
|
||||
"""Только чтение фиксированных таблиц; на стенде — экспортированные агрегаты."""
|
||||
export = _read_meta(root / "landing_documents.json") or {}
|
||||
saved = export.get("metrics")
|
||||
saved = saved if isinstance(saved, dict) else {}
|
||||
values: dict[str, int | None] = {
|
||||
key: saved[key] if type(saved.get(key)) is int and saved[key] >= 0 else None
|
||||
for key in _DB_KEYS
|
||||
}
|
||||
for relative, queries in _DB_METRICS.items():
|
||||
db = root / "derived" / relative
|
||||
if not db.is_file():
|
||||
continue
|
||||
try:
|
||||
with sqlite3.connect(db.as_uri() + "?mode=ro", uri=True, timeout=1) as con:
|
||||
for key, query in queries.items():
|
||||
result = con.execute(query).fetchone()[0]
|
||||
values[key] = result if type(result) is int and result >= 0 else None
|
||||
except sqlite3.Error:
|
||||
for key in queries:
|
||||
values[key] = None
|
||||
return values
|
||||
|
||||
|
||||
def _collect(root: Path | None = None) -> dict:
|
||||
@@ -89,13 +132,18 @@ def _collect(root: Path | None = None) -> dict:
|
||||
|
||||
dated = [doc for doc in found if doc["loaded"]]
|
||||
dated.sort(key=lambda doc: doc["loaded"][0], reverse=True)
|
||||
return {"count": len(found), "recent": dated[:4]}
|
||||
return {"count": len(found), "recent": dated[:4],
|
||||
"document_counts": {
|
||||
"tsn_documents": sum(doc["source"] == "ТСН Москвы" for doc in found),
|
||||
"bim_letters": sum(doc["source"] == "ФГИС ЦС" for doc in found)}}
|
||||
|
||||
|
||||
def export_summary(source: Path, destination: Path) -> None:
|
||||
"""Копия метаданных внешнего нормативного корпуса для release-стенда."""
|
||||
data = _collect(Path(source))
|
||||
exported = {"count": data["count"], "recent": [
|
||||
exported = {"count": data["count"],
|
||||
"document_counts": data.get("document_counts", {}),
|
||||
"metrics": _external_metrics(Path(source)), "recent": [
|
||||
{"title": doc["title"], "source": doc["source"],
|
||||
"fetched_at": doc["loaded"][0]}
|
||||
for doc in data["recent"]
|
||||
@@ -116,6 +164,16 @@ def _literature_count() -> int:
|
||||
and path.suffix.lower() in {".pdf", ".doc", ".docx", ".htm", ".html"})
|
||||
|
||||
|
||||
def _fssc_count() -> int | None:
|
||||
project = os.environ.get("SMETA_PROJECT_DIR")
|
||||
if not project:
|
||||
return None
|
||||
root = Path(project) / "data" / "fssc_2022"
|
||||
if not root.is_dir():
|
||||
return None
|
||||
return sum(path.is_file() for path in root.glob("region_*.json"))
|
||||
|
||||
|
||||
def _norm_count() -> int | None:
|
||||
"""Число рабочих норм ГЭСН; повторно парсим JSON только при смене файлов."""
|
||||
global _norm_sig, _norm_value
|
||||
@@ -149,8 +207,17 @@ def snapshot() -> dict:
|
||||
now = time.monotonic()
|
||||
if _cache_value is None or now >= _cache_until:
|
||||
external = _collect()
|
||||
project = os.environ.get("SMETA_PROJECT_DIR")
|
||||
literature_root = Path(project) / "literature" if project else None
|
||||
literature = _literature_count() if literature_root and literature_root.is_dir() else None
|
||||
db_metrics = _external_metrics(ext_state.ext_dir())
|
||||
metrics = {**db_metrics,
|
||||
"gesn_norms": _norm_count(), "fssc_regions": _fssc_count(),
|
||||
"literature_files": literature,
|
||||
"bim_letters": external.get("document_counts", {}).get("bim_letters"),
|
||||
"tsn_documents": external.get("document_counts", {}).get("tsn_documents")}
|
||||
_cache_value = {"count": external["count"] + _literature_count(),
|
||||
"norm_count": _norm_count(),
|
||||
"norm_count": metrics["gesn_norms"], "metrics": metrics,
|
||||
"recent": external["recent"]}
|
||||
_cache_until = now + _CACHE_SECONDS
|
||||
return _cache_value
|
||||
@@ -158,10 +225,32 @@ def snapshot() -> dict:
|
||||
|
||||
def render() -> str:
|
||||
data = snapshot()
|
||||
count = data["count"]
|
||||
norm_count = data["norm_count"]
|
||||
norm_text = (f"{norm_count:,}".replace(",", "\u00a0")
|
||||
if norm_count is not None else "—")
|
||||
metrics = data["metrics"]
|
||||
|
||||
def number(key: str) -> str:
|
||||
value = metrics.get(key)
|
||||
return f"{value:,}".replace(",", "\u00a0") if value is not None else "—"
|
||||
|
||||
cards = (
|
||||
("ГЭСН", "gesn_norms", "норм", None, None),
|
||||
("ФСНБ", "fsnb_works", "расценок", "fsnb_resources", "ресурсов"),
|
||||
("ФГИС ЦС", "fgis_items", "ресурсов", "fgis_price_rows", "ценовых записей по зонам и периодам"),
|
||||
("КСР", "ksr", "позиций классификатора", None, None),
|
||||
("ТСН Москвы", "tsn_works", "расценок", "tsn_prices", "ценовых позиций"),
|
||||
("Региональные базы", "regional_works", "расценка", "regional_prices", "цен"),
|
||||
("ФССЦ", "fssc_regions", "региональных сборников", None, None),
|
||||
("БИМ", "bim_letters", "писем с индексами", None, None),
|
||||
("Методические документы", "literature_files", "файлов в библиотеке", None, None),
|
||||
)
|
||||
stats = "".join(
|
||||
'<li class="public-doc-stat-item">'
|
||||
f'<span class="public-doc-stat-name">{title}</span>'
|
||||
f'<strong id="public-{primary.replace("_", "-")}">{number(primary)}</strong>'
|
||||
f'<span>{label}</span>'
|
||||
+ (f'<small>{number(secondary)} {secondary_label}</small>' if secondary else "")
|
||||
+ '</li>'
|
||||
for title, primary, label, secondary, secondary_label in cards
|
||||
)
|
||||
if data["recent"]:
|
||||
items = "".join(
|
||||
'<li class="public-doc-item">'
|
||||
@@ -175,14 +264,7 @@ def render() -> str:
|
||||
else:
|
||||
feed = '<p class="public-doc-empty">Документы пока не загружены.</p>'
|
||||
return (
|
||||
'<div class="public-doc-stat">'
|
||||
'<div class="public-doc-primary">'
|
||||
f'<strong id="public-norm-count">{norm_text}</strong>'
|
||||
'<span>норм ГЭСН в поисковой базе</span></div>'
|
||||
'<div class="public-doc-secondary">'
|
||||
f'<strong id="public-doc-count">{count}</strong>'
|
||||
'<span>нормативных файлов-источников</span></div>'
|
||||
'</div><div class="public-doc-feed">'
|
||||
f'<ul class="public-doc-stat">{stats}</ul><div class="public-doc-feed">'
|
||||
'<h3>Последние загрузки из внешних источников</h3>'
|
||||
f'{feed}</div>'
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user