Revise plain estimate answers from inline price zones

This commit is contained in:
anor
2026-12-02 23:21:25 +10:00
parent 2a3cdf8bd8
commit d908d183d5
8 changed files with 534 additions and 28 deletions
+147
View File
@@ -0,0 +1,147 @@
"""Price basis choices for a plain, saved assistant answer."""
from __future__ import annotations
import hashlib
import math
import re
def revision(content: str) -> str:
return hashlib.sha256(content.encode("utf-8")).hexdigest()
def options_for_label(content: str, label: str) -> tuple[list[dict], int]:
"""Only a catalog zone visibly named in this answer can open the selector."""
if not label or len(label) > 160 or len(content) > 30000 or label not in content:
raise ValueError("Ценовая зона не найдена в этом ответе")
import engine_prices
catalog = engine_prices.load_catalog() or {}
subject_ids = {row.get("subject_id") for row in catalog.get("zones") or []
if row.get("zone_name") == label and isinstance(row.get("subject_id"), int)}
if len(subject_ids) != 1:
raise ValueError("Такой ценовой зоны нет в каталоге")
subject_id = subject_ids.pop()
zones = engine_prices.basis_options(subject_id)
if not zones:
raise ValueError("Для этой зоны нет доступных ценовых форм")
return zones, subject_id
_CODE = re.compile(r"(?<!\d)(\d{2}-\d{2}-\d{3}-\d{2})(?![\d-])")
_VOLUME = re.compile(
r"(?<!\d)(\d+(?:[.,]\d+)?)\s+(?:(?:[А-ЯЁа-яё-]+\s+){0,3})?"
r"(?:извещател[А-ЯЁа-яё]*|шт\.?|штук)\b", re.IGNORECASE)
_EXPLICIT_VOLUME = re.compile(r"объ[её]м\s+работ\s*[=:—-]\s*(\d+(?:[.,]\d+)?)\s*шт\b",
re.IGNORECASE)
def extract_position(question: str, answer: str) -> tuple[str, float] | None:
"""Only one explicit norm and an explicit piece count; never infer a quantity."""
codes = set(_CODE.findall(question + "\n" + answer))
if len(codes) != 1:
return None
for source, pattern in ((question, _EXPLICIT_VOLUME), (answer, _EXPLICIT_VOLUME),
(question, _VOLUME), (answer, _VOLUME)):
matches = pattern.findall(source)
if matches:
qty = float(matches[0].replace(",", "."))
if math.isfinite(qty) and 0 < qty <= 1_000_000:
return codes.pop(), qty
return None
def _money(value: float) -> str:
return f"{value:,.2f}".replace(",", " ").replace(".", ",") + " ₽"
def format_plain_result(result: dict, code: str, qty: float, zone: str, period: str) -> str:
lines = [f"Ценовая зона: {zone}. Период цен: {period}.", "",
f"Норма: {code}. Объём: {qty:g} шт."]
if result.get("status") != "ok":
lines.extend(["", "Расчёт стоимости не выполнен: "
+ str(result.get("message") or "ценовая форма недоступна")])
return "\n".join(lines)
missing, unpriced = result.get("missing") or [], result.get("unpriced") or []
total = result.get("grand_total")
complete = result.get("ok") and not missing and not unpriced
lines.append("")
if complete and isinstance(total, (int, float)) and math.isfinite(total):
lines.append("Итого по локальной смете: " + _money(total))
else:
lines.append("Расчёт неполный — готовую смету по этим данным получить нельзя.")
if (result.get("positions") and isinstance(total, (int, float))
and math.isfinite(total) and total > 0):
lines.append("Стоимость учтённой части: " + _money(total)
+ ". Она не включает перечисленные ниже затраты.")
for item in missing:
lines.append("Не рассчитано: " + str(item.get("reason") or item.get("code") or "позиция"))
if unpriced:
lines.append("Часть ресурсов без цены в выбранной форме; их стоимость не включена.")
if result.get("limits_note"):
lines.extend(["", str(result["limits_note"])])
return "\n".join(lines)
def calculate_plain(question: str, old_answer: str, zone: str, period: str) -> str:
"""Calculate an explicit single GESN piece norm from audited resources and price form."""
extracted = extract_position(question, old_answer)
if extracted is None:
raise ValueError("В ответе нет одной нормы с подтверждённым объёмом в штуках")
code, qty = extracted
import engine_prices
import estimate_contract as ec
import fsnb_ref
from smeta_railway.models import LaborResource, MaterialResource, NormResources
found = fsnb_ref.find_gesn_composition(query=code, base="2022", limit=10)
candidates = [row for row in found.get("results") or []
if row.get("code") == code and row.get("base_type") in ("ГЭСН", "ГЭСНм")]
if len(candidates) != 1:
raise ValueError("Ресурсный состав этой нормы не найден однозначно")
work = candidates[0]
if not work.get("unit") or "шт" not in work["unit"].lower() or not work.get("resources"):
raise ValueError("Ресурсный состав или измеритель этой нормы не позволяет пересчёт")
labor = None
materials = []
for row in work["resources"]:
code_row, quantity = str(row.get("code") or ""), row.get("quantity")
if (not code_row or not isinstance(quantity, (int, float)) or not math.isfinite(quantity)
or quantity < 0 or row.get("quantity_note")):
raise ValueError("В норме есть ресурс с неопределённым расходом")
if code_row.startswith("1-100-"):
if labor is not None or not re.fullmatch(r"1-100-\d{2}", code_row):
raise ValueError("Разряд труда в норме не определён однозначно")
labor = LaborResource(razryad=int(code_row[-2:]) / 10, chel_hours=quantity)
elif code_row.startswith("91."):
raise ValueError("Норма содержит машины; их оплату нельзя пропустить при пересчёте")
elif code_row.startswith("4-100-"):
raise ValueError("Труд машинистов этой нормы требует отдельного расчёта")
elif re.match(r"\d{2}\.", code_row):
materials.append(MaterialResource(code=code_row, name=row.get("name") or code_row,
unit=row.get("unit") or "", qty=quantity))
else:
raise ValueError("В норме есть ресурс неизвестного вида — пересчёт остановлен")
norm_code = work["base_type"] + " " + code
norm = NormResources(norm_code=norm_code, norm_name=work.get("name"), unit=work["unit"],
ozp=labor, materials=materials)
resources = {norm_code: norm}
meta = {"region": zone, "zone": zone, "price_level": period}
basis = engine_prices.resolve(meta)
if basis.get("status") != "ok":
return format_plain_result(basis, code, qty, zone, period)
try:
lookup = engine_prices.load_lookup(basis["entry"])
except (OSError, ValueError):
return format_plain_result({"status": "catalog_unavailable",
"message": "ценовая форма не читается"}, code, qty, zone, period)
positions, refusal = ec._positions_in_measures(
[{"code": norm_code, "name": work.get("name") or code, "qty": qty, "unit": "шт"}], resources)
if refusal:
return format_plain_result(refusal, code, qty, zone, period)
draft = ec.EstimateDraft(meta=ec.DraftMeta(**meta),
positions=[ec.DraftPosition(**item) for item in positions])
result = ec.build_and_calc(draft, resources, lookup, basis)
# Этот узкий путь допускает только труд и материалы: перевозки здесь нет.
result["limits_note"] = ec.LIMITS_NOTE
return format_plain_result(result, code, qty, zone, period)