Include full normative library and stage public document summary

This commit is contained in:
anor
2026-12-01 16:55:45 +10:00
parent 0c698f56b3
commit e6985aad11
6 changed files with 115 additions and 25 deletions
+53 -10
View File
@@ -1,12 +1,9 @@
"""Публичный снимок загруженных нормативных документов для главной страницы.
Только два заведомо общих корпуса. Каталоги пользователей и файлы диалогов здесь
не просматриваются: их названия могут содержать персональные данные.
"""
"""Публичный снимок нормативных документов для главной страницы."""
from __future__ import annotations
import html
import json
import os
import time
from datetime import datetime
from pathlib import Path
@@ -43,8 +40,28 @@ def _date(value: object) -> tuple[str, str] | None:
return (d.isoformat(), d.strftime("%d.%m.%Y"))
def _collect() -> dict:
base = ext_state.ext_dir() / "snapshots"
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": []}
recent = []
source_items = raw.get("recent")
for doc in (source_items[:4] if isinstance(source_items, list) else []):
if not isinstance(doc, dict):
continue
title, source = doc.get("title"), doc.get("source")
loaded = _date(doc.get("fetched_at"))
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}
def _collect(root: Path | None = None) -> dict:
root = root if root is not None else ext_state.ext_dir()
base = root / "snapshots"
if not (base / "niac_tsn").is_dir() and not (base / "fgis" / "bim_letters").is_dir():
return _read_export(root / "landing_documents.json")
found = []
tsn = base / "niac_tsn"
for path in tsn.glob("*/*/meta.json"):
@@ -71,12 +88,38 @@ def _collect() -> dict:
return {"count": len(found), "recent": dated[:4]}
def export_summary(source: Path, destination: Path) -> None:
"""Копия метаданных внешнего нормативного корпуса для release-стенда."""
data = _collect(Path(source))
exported = {"count": data["count"], "recent": [
{"title": doc["title"], "source": doc["source"],
"fetched_at": doc["loaded"][0]}
for doc in data["recent"]
]}
ext_state._atomic_write_text(Path(destination),
json.dumps(exported, ensure_ascii=False))
def _literature_count() -> int:
project = os.environ.get("SMETA_PROJECT_DIR")
if not project:
return 0
root = Path(project) / "literature"
if not root.is_dir():
return 0
return sum(1 for path in root.rglob("*")
if path.is_file() and not path.is_symlink()
and path.suffix.lower() in {".pdf", ".doc", ".docx", ".htm", ".html"})
def snapshot() -> dict:
"""Снимок на пять минут: не читать сотни файлов на каждый просмотр главной."""
global _cache_until, _cache_value
now = time.monotonic()
if _cache_value is None or now >= _cache_until:
_cache_value = _collect()
external = _collect()
_cache_value = {"count": external["count"] + _literature_count(),
"recent": external["recent"]}
_cache_until = now + _CACHE_SECONDS
return _cache_value
@@ -99,8 +142,8 @@ def render() -> str:
return (
'<div class="public-doc-stat">'
f'<strong id="public-doc-count">{count}</strong>'
'<span>сборников ТСН и писем Минстроя<br>в загруженном корпусе</span>'
'<span>нормативных документов<br>в базе сервиса</span>'
'</div><div class="public-doc-feed">'
'<h3>Последние загрузки</h3>'
'<h3>Последние загрузки из внешних источников</h3>'
f'{feed}</div>'
)