estimate_contract.calc_estimate(positions): детерминированный расчёт по кодам+объёмам на реальных resources.json + fgis (ленивый кэш). engine_enabled() — флаг go-live (off по умолчанию: выкат инертно → проверка на реальных данных → включение в .env). Числа только из движка. 6 тестов. Движок на сервере синхронизирован (f7b9400→038d4a1, keystone зелёный).
117 lines
5.3 KiB
Python
117 lines
5.3 KiB
Python
"""estimate_contract — контракт «LLM структурирует, код считает» (срез 4.3).
|
|
|
|
LLM выдаёт EstimateDraft (список позиций: код+объём) → детерминированный движок
|
|
(strict) считает числа → estimate_verify проверяет → результат. LLM НИКОГДА не
|
|
называет числа: они из движка. Не прошёл strict/verify → ok=False (не отдавать как
|
|
готовую смету). НР/СП — из reserve_nr_sp (реальные), не хардкод.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
from pydantic import BaseModel, Field
|
|
|
|
# smeta_railway на пути (как в main.py/claude_bridge_glm)
|
|
_SR = Path(__file__).resolve().parent.parent / "smeta-railway" / "src"
|
|
if _SR.exists() and str(_SR) not in sys.path:
|
|
sys.path.insert(0, str(_SR))
|
|
_SR_ROOT = _SR.parent # ~/smeta-railway — тут resources.json и fgis_split_form.xlsx
|
|
|
|
import estimate_verify # noqa: E402
|
|
|
|
|
|
def engine_enabled() -> bool:
|
|
"""Флаг go-live движка (срез 4.4). Владелец: включать сразу по готовности.
|
|
Значение по умолчанию OFF — чтобы код можно было выкатить инертно и проверить
|
|
на реальных данных ДО включения. Включается ESTIMATE_ENGINE=on в .env."""
|
|
return os.environ.get("ESTIMATE_ENGINE", "off").strip().lower() in ("on", "1", "true", "yes")
|
|
|
|
|
|
class DraftPosition(BaseModel):
|
|
code: str
|
|
qty: float
|
|
unit: str = ""
|
|
name: str = ""
|
|
|
|
|
|
class DraftMeta(BaseModel):
|
|
region: str = ""
|
|
price_level: str = ""
|
|
norm_base: str = "ФСНБ-2022"
|
|
vat_pct: float = 22.0
|
|
|
|
|
|
class EstimateDraft(BaseModel):
|
|
meta: DraftMeta = Field(default_factory=DraftMeta)
|
|
positions: list[DraftPosition] = Field(default_factory=list)
|
|
|
|
|
|
def build_and_calc(draft: EstimateDraft, resources: dict, fgis) -> dict:
|
|
"""EstimateDraft → расчёт движком (strict) → verify. Возвращает
|
|
{ok, grand_total, grand_total_with_limits, missing, verify, positions_count}.
|
|
ok=False → в смете нерассчитанные позиции или несходимость: НЕ отдавать файл."""
|
|
from smeta_railway.calc.estimate import EstimateCalculator
|
|
from smeta_railway.config import Section, Subsection, WorkItem
|
|
|
|
items = [WorkItem(code=p.code, name=p.name or p.code, unit=p.unit, qty=p.qty)
|
|
for p in draft.positions]
|
|
section = Section(name="Смета", subsections=[Subsection(name="", items=items)])
|
|
calc = EstimateCalculator(fgis=fgis, resources=resources, strict=True)
|
|
result = calc.calculate([section])
|
|
|
|
vp = draft.meta.vat_pct
|
|
gt = result.grand_total
|
|
vat = round(gt * vp / 100, 2)
|
|
norm = {
|
|
"positions": [{"code": p.gesn_code, "name": p.name, "unit": p.unit,
|
|
"qty": p.qty, "total": p.total, "norm_base": draft.meta.norm_base}
|
|
for p in result.positions if not p.unresolved],
|
|
"totals": {"grand_total": gt, "vat_pct": vp, "vat": vat,
|
|
"total_with_vat": round(gt + vat, 2)},
|
|
}
|
|
v = estimate_verify.verify(norm)
|
|
return {
|
|
"ok": result.ok and v["ok"],
|
|
"grand_total": gt,
|
|
"grand_total_with_limits": result.grand_total_with_limits,
|
|
"missing": result.missing,
|
|
"verify": v,
|
|
"positions_count": len(result.positions),
|
|
"positions": norm["positions"],
|
|
}
|
|
|
|
|
|
# Ленивый кэш реальных ресурсов/ФГИС (тяжёлые: ~24k расценок + прайс-лист ФГИС).
|
|
_RES_CACHE = None
|
|
_FGIS_CACHE = None
|
|
|
|
|
|
def _load_engine_data():
|
|
"""Загрузить реальные resources.json + fgis_split_form.xlsx (один раз на процесс)."""
|
|
global _RES_CACHE, _FGIS_CACHE
|
|
if _RES_CACHE is None or _FGIS_CACHE is None:
|
|
from smeta_railway.data.gesn import load_resources
|
|
from smeta_railway.data.fgis import load_fgis
|
|
res_path = _SR_ROOT / "resources.json"
|
|
fgis_xlsx = _SR_ROOT / "fgis_split_form.xlsx"
|
|
fgis_cache = _SR_ROOT / "fgis_cache.pkl"
|
|
_RES_CACHE = load_resources(res_path)
|
|
_FGIS_CACHE = load_fgis(str(fgis_xlsx), str(fgis_cache))
|
|
return _RES_CACHE, _FGIS_CACHE
|
|
|
|
|
|
def calc_estimate(positions: list[dict], meta: dict | None = None) -> dict:
|
|
"""Детерминированный расчёт сметы по позициям (код+объём) на РЕАЛЬНЫХ данных.
|
|
positions: [{code, qty, unit?, name?}]. Возвращает то же, что build_and_calc
|
|
(ok, grand_total, missing, verify, positions). Числа — только из движка, не из LLM.
|
|
Не готово к включению (ESTIMATE_ENGINE=off) → вызывающий сам решает; функция считает
|
|
всегда (флаг проверяет вызывающий на границе агент/эндпоинт)."""
|
|
resources, fgis = _load_engine_data()
|
|
draft = EstimateDraft(
|
|
meta=DraftMeta(**(meta or {})),
|
|
positions=[DraftPosition(**p) for p in positions],
|
|
)
|
|
return build_and_calc(draft, resources, fgis)
|