"""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 defusedxml.ElementTree import parse as _safe_parse, fromstring as _safe_fromstring # XXE/billion-laughs-safe (пентест XXE-DOS-01) 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 _index(node) -> dict | None: """Индекс пересчёта ресурса база→текущий с обоснованием (Index/Reason).""" idx = node.find("Index") if idx is None: return None val = _f(_t(idx, "Value/IndexValue")) or _f(_t(idx, "Value/Final")) reason = _t(idx, "Reason") if not val and not reason: return None return {"value": val, "reason": reason} def _res_coef(node) -> dict | None: """Поправочный коэффициент НА РЕСУРС (Coefficients/Final по Target). Норма Consumption — БАЗОВАЯ (ГЭСН); эффективная = норма × factors[Target]. Target: «Расход» (к норме расхода труда/машин/материалов), «Стоимость». Reason — обоснование Приказом Минстроя (571/пр — демонтаж/разборка, 421/пр — условия производства работ). Встречается в ~11% позиций.""" cs = node.find("Coefficients") if cs is None: return None factors = {} fin = cs.find("Final") if fin is not None: for v in fin.findall(".//Values/Value"): tg = _t(v, "Target") if tg: factors[tg] = _f(_t(v, "CoefValue")) reasons = [r for r in (_t(c, "Reason") for c in cs.findall("Coefficient")) if r] if not factors and not reasons: return None return {"factors": factors, "reason": "; ".join(dict.fromkeys(reasons))} def _material(mat, external=False) -> dict: d = { "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")), "index": _index(mat), "coef": _res_coef(mat), } if external: d["external"] = True return d def _resources(cost) -> dict: """Ресурсный состав расценки (нормы на единицу): рабочие/машины/материалы, с индексами пересчёта и деталями машинистов.""" out = {"workers": [], "machines": [], "materials": []} ri = cost.find("ResourcesInternal") if ri is None: ri = ET.Element("empty") 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")), "coef": _res_coef(w), }) for m in ri.findall("Machine"): mach = m.find("Machinist") 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")), "index": _index(m), "coef": _res_coef(m), "machinist": { "consumption": _f(_t(mach, "Consumption")), "price_cur": _f(_t(mach, "PricePerUnitCur")), "grade": _t(mach, "Grade"), "coef": _res_coef(mach), } if mach is not None else None, }) for mat in ri.findall("Material"): out["materials"].append(_material(mat)) # Внешние ресурсы (оборудование/неучтённые материалы из Cost/Resources) ext = cost.find("Resources") if ext is not None: for mat in ext.findall("Material"): out["materials"].append(_material(mat, 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"): v = c.find(".//Values/Value") out.append({ "name": _t(c, "Name"), "reason": _t(c, "Reason"), "value": _t(v, "CoefValue") if v is not None else "", "target": _t(v, "Target") if v is not None else "", }) return out def parse_estimate_full(path: Path) -> dict: """Полный разбор ЛСР/ОСР. Возвращает estimate-метаданные + позиции с ресурсным составом, ценами база/текущие, накладными/прибылью, коэффициентами.""" try: root = _safe_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_base": _f(_t(dm, "PricePerUnitBase")), "price_cur": _f(_t(dm, "PricePerUnitCur")), "comment": _t(dm, "Comment"), "is_return": _t(dm, "IsReturnMat").lower() == "true", }) # Перевозочная позиция (Transport — доставка грузов). # Цена в PricePerUnitCur (у Transport нет Totals/Current/Direct). tr = it.find("Transport") if tr is not None and _t(tr, "Name"): qty = _f(_t(tr, "QuantityTotal")) or _f(_t(tr, "Quantity")) positions.append({ "code": _t(tr, "Code"), "name": (_t(tr, "Name") or "").strip(), "prefix": _t(tr, "Prefix"), "unit": _t(tr, "Unit"), "quantity": qty, "comment": _t(tr, "Comment"), "labor_ch": 0.0, "machinist_ch": 0.0, "unit_cost_cur": _f(_t(tr, "PricePerUnitCur")), "cost_structure": None, "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")) tc = cost.find("Totals/Current") direct_cur = _f(_t(tc, "Direct")) if tc is not None else 0.0 unit_cost_cur = round(direct_cur / qty_total, 2) if qty_total else 0.0 # Структура стоимости расценки: сколько на машины/материалы/зарплату cost_structure = { "machines": _f(_t(tc, "Machines")), "materials": _f(_t(tc, "Materials")), "salary": _f(_t(tc, "Salary")), "machinist_salary": _f(_t(tc, "MachinistSalary")), "workers_salary": _f(_t(tc, "WorkersSalary")), } if tc is not None else None 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, "comment": _t(cost, "Comment"), "labor_ch": _f(_t(cost, "PerUnit/LaborCosts")), "machinist_ch": _f(_t(cost, "PerUnit/MachinistLaborCosts")), "unit_cost_cur": unit_cost_cur, "cost_structure": cost_structure, "overhead": {"value": _t(ov, "Value"), "target": _t(ov, "Target"), "reason": _t(ov, "Reason"), "price_cur": _f(_t(ov, "PriceCur"))} if ov is not None else None, "profit": {"value": _t(pr, "Value"), "target": _t(pr, "Target"), "reason": _t(pr, "Reason"), "price_cur": _f(_t(pr, "PriceCur"))} 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 = _safe_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 "" page = _t(link, "PageNumber") 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": (f"{source} л.{page}" if page else source).strip(), }) return { "num": _t(root, "Num"), "reason": _t(root, "Reason"), "works": works, } def parse_ka(data: bytes) -> list[dict]: """Разбор КА (MarketAnalysis): материал → офферы поставщиков с ценами. Возвращает RAW (обезличивание — на стороне индексатора). Per оффер: market_price (цена оффера без НДС), estimate_price (СМЕТНАЯ цена, идёт в смету), price_vat (с НДС), storage/transport (заготовит.-складские/перевозка), delivery (условия), region, period, winner, реквизиты поставщика (для обезличивания индексатором). """ try: root = _safe_fromstring(data) except ET.ParseError: return [] items = [] for item in root.iter("Item"): name = (_t(item, "Name") or "").strip() if not name: continue offers = [] for n, off in enumerate(item.findall("Offer"), 1): op = off.find("OfferPrice") market = _f(_t(off, "OfferPrice/OfferUnitWithoutVAT")) \ or _f(_t(off, "OfferPrice/OfferWithoutVAT")) if market <= 0: continue offers.append({ "vendor": f"Поставщик {n}", # позиционно; реквизиты не извлекаем "market_price": round(market, 2), "estimate_price": round(_f(_t(op, "EstimateWithoutVAT")), 2) if op is not None else 0.0, "price_vat": round(_f(_t(off, "OfferPrice/OfferWithVAT")), 2) or None, "storage": _f(_t(off, "Storage/Price")) or None, "transport": _f(_t(off, "Transportation/Price")) or None, "delivery": _t(off, "OfferPrice/DeliveryTerms"), # Region/Name — ВСМ-корпус; Region/RegionName — ДВ-корпус 2025 "region": _t(off, "Region/Name") or _t(off, "Region/RegionName"), "period": f"{_t(off, 'OfferDate/Year')} Q{_t(off, 'OfferDate/Quarter')}".strip(), "country": _t(off, "OriginCountry"), "winner": _t(off, "Winner").lower() == "true", }) if offers: items.append({"name": name, "unit": _t(item, "Unit"), "type": _t(item, "Type"), "offers": offers}) return items