Files
smeta-web/gge_deep.py
T
anorandClaude Opus 4.8 78cc18d960 feat: корпус реальных смет/КА/ВОР — поиск расценок, цен и объёмов из сданного проекта
Три обезличенных индекса из базы реального проекта (gge_deep — глубокий разбор
всех схем): расценки с полным ресурсным составом + ценой/накладными/обоснованиями,
КА-цены (winner + офферы поставщиков «Поставщик N»), ВОР-объёмы с формулами расчёта.
Поиск (find_in_real_estimates / find_ka_price / find_in_vor) заведён в smeta_mcp
и tools_glm (активный прод-бэкенд glm). Обезличивание verify_corpus: exit 0.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-09 00:54:28 +10:00

225 lines
9.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""gge_deep — глубокий разбор .gge: вытаскивает ВСЁ ценное, что
parse_gge_file пропускает (ресурсный состав, цены база/текущие, индексы,
накладные/прибыль с обоснованиями, коэффициенты, трудозатраты), плюс разбор
ВОР (QuantityTakeoff — работа→объём→формула→ссылка на обоснование).
Используется индексаторами корпуса (scripts/build_*). Обезличивание —
ответственность вызывающего (scrub применяется в индексаторе), но имена
подписантов/ФИО и идентификаторы объекта здесь НЕ извлекаются вовсе.
Зависимости: только stdlib (xml.etree). Совместимо с sandbox.
"""
from __future__ import annotations
import re
import xml.etree.ElementTree as ET
from pathlib import Path
# Проект-специфичные идентификаторы для обезличивания (scrub в индексаторах).
DENY_RE = re.compile(
r"создани\w*\s+высокоскоростн\w*|высокоскоростн\w*|санкт-петербург\s*[–-]\s*москва"
r"|крюков\w*|алабушев\w*|вохр|960-06[\w.\-]*|ПК\s?\d+(?:\+\d+(?:,\d+)?)?"
r"|\bВСМ[\w.\-]*|нов\w*\s+тверь",
re.IGNORECASE)
def scrub(text: str) -> str:
return DENY_RE.sub("[…]", text) if text else text
def _t(el, path: str) -> str:
if el is None:
return ""
node = el.find(path)
return (node.text or "").strip() if node is not None and node.text else ""
def _f(s: str) -> float:
try:
return float(s)
except (ValueError, TypeError):
return 0.0
def _resources(cost) -> dict:
"""Ресурсный состав расценки (нормы на единицу): рабочие/машины/материалы."""
out = {"workers": [], "machines": [], "materials": []}
ri = cost.find("ResourcesInternal")
if ri is None:
return out
for w in ri.findall("Worker"):
out["workers"].append({
"name": (_t(w, "Name") or "").strip(),
"consumption": _f(_t(w, "Consumption")),
"unit": _t(w, "Unit"),
"price_cur": _f(_t(w, "PricePerUnitCur")),
})
for m in ri.findall("Machine"):
out["machines"].append({
"code": _t(m, "Code"),
"name": _t(m, "Name"),
"consumption": _f(_t(m, "Consumption")),
"unit": _t(m, "Unit"),
"price_base": _f(_t(m, "PricePerUnitBase")),
"price_cur": _f(_t(m, "PricePerUnitCur")),
"machinist_grade": _t(m, "Machinist/Grade"),
})
for mat in ri.findall("Material"):
out["materials"].append({
"code": _t(mat, "Code"),
"name": _t(mat, "Name"),
"consumption": _f(_t(mat, "Consumption")),
"unit": _t(mat, "Unit"),
"price_base": _f(_t(mat, "PricePerUnitBase")),
"price_cur": _f(_t(mat, "PricePerUnitCur")),
})
# Внешние ресурсы (оборудование/неучтённые материалы из Cost/Resources)
ext = cost.find("Resources")
if ext is not None:
for mat in ext.findall("Material"):
out["materials"].append({
"code": _t(mat, "Code"),
"name": _t(mat, "Name"),
"consumption": _f(_t(mat, "Consumption")),
"unit": _t(mat, "Unit"),
"price_base": _f(_t(mat, "PricePerUnitBase")),
"price_cur": _f(_t(mat, "PricePerUnitCur")),
"external": True,
})
return out
def _coefficients(cost) -> list[dict]:
out = []
cs = cost.find("Coefficients")
if cs is None:
return out
for c in cs.findall("Coefficient"):
val = c.find(".//Values/Value/CoefValue")
out.append({
"name": _t(c, "Name"),
"reason": _t(c, "Reason"),
"value": (val.text or "").strip() if val is not None and val.text else "",
})
return out
def parse_estimate_full(path: Path) -> dict:
"""Полный разбор ЛСР/ОСР. Возвращает estimate-метаданные + позиции с
ресурсным составом, ценами база/текущие, накладными/прибылью, коэффициентами."""
try:
root = ET.parse(str(path)).getroot()
except (ET.ParseError, OSError) as e:
return {"error": f"{type(e).__name__}: {e}", "path": str(path)}
schema = root.attrib.get(
"{http://www.w3.org/2001/XMLSchema-instance}noNamespaceSchemaLocation", "")
est = root.find(".//Object/Estimate")
if est is None:
est = root.find(".//Estimate")
region = _t(est, "Region/RegionName")
plb = est.find("PriceLevelBase") if est is not None else None
plc = est.find("PriceLevelCur") if est is not None else None
price_base = f"{_t(plb,'Year')} Q{_t(plb,'Quarter')}" if plb is not None else ""
price_cur = f"{_t(plc,'Year')} Q{_t(plc,'Quarter')}" if plc is not None else ""
positions = []
direct_materials = []
for it in root.iter("Item"):
cost = it.find("Cost")
if cost is None:
# Прямой материал в смете (Item/Material — напр. песок с реальной ценой)
dm = it.find("Material")
if dm is not None and _t(dm, "Name"):
direct_materials.append({
"code": _t(dm, "Code"),
"name": (_t(dm, "Name") or "").strip(),
"unit": _t(dm, "Unit"),
"consumption": _f(_t(dm, "ConsumptionTotal")) or _f(_t(dm, "Consumption")),
"price_cur": _f(_t(dm, "PricePerUnitCur")),
})
# Перевозочная позиция (Transport — доставка грузов)
tr = it.find("Transport")
if tr is not None and _t(tr, "Name"):
qty = _f(_t(tr, "QuantityTotal")) or _f(_t(tr, "Quantity"))
direct = _f(_t(tr, "Totals/Current/Direct")) or _f(_t(tr, "PriceTotalCur"))
positions.append({
"code": _t(tr, "Code"), "name": (_t(tr, "Name") or "").strip(),
"prefix": _t(tr, "Prefix"), "unit": _t(tr, "Unit"),
"quantity": qty,
"labor_ch": 0.0, "machinist_ch": 0.0,
"unit_cost_cur": round(direct / qty, 2) if qty else 0.0,
"overhead": None, "profit": None, "coefficients": [],
"resources": {"workers": [], "machines": [], "materials": []},
"kind": "transport",
})
continue
name = (_t(cost, "Name") or "").strip()
if not name:
continue
qty_total = _f(_t(cost, "QuantityTotal")) or _f(_t(cost, "Quantity"))
direct_cur = _f(_t(cost, "Totals/Current/Direct"))
unit_cost_cur = round(direct_cur / qty_total, 2) if qty_total else 0.0
ov = it.find("Overheads")
pr = it.find("Profits")
positions.append({
"code": _t(cost, "Code"),
"name": name,
"prefix": _t(cost, "Prefix"),
"unit": _t(cost, "Unit"),
"quantity": qty_total,
"labor_ch": _f(_t(cost, "PerUnit/LaborCosts")),
"machinist_ch": _f(_t(cost, "PerUnit/MachinistLaborCosts")),
"unit_cost_cur": unit_cost_cur,
"overhead": {"value": _t(ov, "Value"), "target": _t(ov, "Target"),
"reason": _t(ov, "Reason")} if ov is not None else None,
"profit": {"value": _t(pr, "Value"), "target": _t(pr, "Target"),
"reason": _t(pr, "Reason")} if pr is not None else None,
"coefficients": _coefficients(cost),
"resources": _resources(cost),
"kind": "cost",
})
return {
"schema": schema,
"code": _t(est, "Num"),
"region": region,
"price_base": price_base,
"price_cur": price_cur,
"positions": positions,
"direct_materials": direct_materials,
}
def parse_vor(path: Path) -> dict:
"""Разбор ВОР (QuantityTakeoff): секции → работы (объём, формула, ссылка)."""
try:
root = ET.parse(str(path)).getroot()
except (ET.ParseError, OSError) as e:
return {"error": f"{type(e).__name__}: {e}", "path": str(path)}
works = []
for sec in root.iter("Section"):
sec_name = _t(sec, "Name")
for w in sec.iter("Work"):
name = (_t(w, "Name") or "").strip()
if not name:
continue
link = w.find(".//Link")
source = _t(link, "PageDescription") if link is not None else ""
works.append({
"section": sec_name,
"name": name,
"unit": _t(w, "Unit"),
"quantity": _f(_t(w, "Quantity")),
"formula": _t(w, "QuantityFormula"),
"comment": _t(w, "Comment"),
"source": source,
})
return {
"num": _t(root, "Num"),
"reason": _t(root, "Reason"),
"works": works,
}