Три глубоких парсера (Fable): merge_gge (РИМ .gge регион ДВ/цены 2025), gsfx_deep (ресурсы+ состав работ+НР/СП+источник цены из 555 .gsfx), arp_deep (ОСНБЖ ж/д: Кнр/Ксп/Кизв+ресурсы, объём f26 численно верифицирован, сверка с парной .xls). Анти-отравление: каждая запись несёт norm_base+price_level, БИМ-сметы 2001 и ценовые выбросы 5× → карантин, обезличено corpus_anon (0 утечек). Сведено в ОТДЕЛЬНЫЙ estimates_ext_index.json (1891 расценка+1703 мат+1114 КА) — живой ВСЖМ-индекс не тронут; _load_estimates/_load_ka грузят оба; find_in_real_estimates отдаёт norm_base/price_level; _search_corpus предупреждает «не смешивай базы/уровни цен». Попутно: gge_deep KA-регион fallback, corpus_anon +паттерн ИНН в underscore. Все тесты (юнит mutation-safe + real-data) зелёные, регресс ВСЖМ цел. APP_VERSION→2026-07-16a. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
308 lines
15 KiB
Python
308 lines
15 KiB
Python
"""gsfx_deep — глубокий разбор .gsfx (ГРАНД-Смета): вытаскивает то, что
|
||
parse_gsfx_file (gge_tools) пропускает — ресурсный состав расценок
|
||
(Tzr/Tzm/Mch/Mat с ценами база/текущие и источником цены), состав работ
|
||
(WorksList), коэффициенты, НР/СП по видам работ (каталог Vids_Rab через
|
||
@Vr2001), уровни цен — для анти-фабрикационного корпуса.
|
||
|
||
.gsfx = zip: Properties.txt (шапка/итог, cp1251) + Data.xml (windows-1251,
|
||
корень <Document>). Нормы ресурсов (@Quantity) — НА ЕДИНИЦУ расценки
|
||
(проверено эмпирически: константа при разных объёмах позиции).
|
||
|
||
Обезличивание — corpus_anon.scrub прямо здесь, на извлечении (все свободные
|
||
тексты). ФИО/подписанты (GsDocSignatures), реквизиты (Obosn), пути и
|
||
поставщики (DocLink, MarketAnalysisDocLink, Supplier) НЕ извлекаются вовсе —
|
||
allow-list надёжнее regex. ССР-строки (без @Code, с <Total>) пропускаются:
|
||
это ссылки на другие сметы, их Caption = имена объектов.
|
||
|
||
НР/СП: если @Vr2001 не находится в каталоге Vids_Rab — overhead/profit = None
|
||
(пропуск лучше выдумки). totals_check — мягкая сверка: сумма позиций
|
||
(ПЗ + НР/СП по ФОТ + транспорт материалов) против Properties.Total; на
|
||
реальном файле ratio ≈ 0.98 (не учитываются зимние/индексы вне цен).
|
||
|
||
Зависимости: stdlib (+ defusedxml если установлен) + corpus_anon.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import xml.etree.ElementTree as ET
|
||
import zipfile
|
||
from pathlib import Path
|
||
|
||
from corpus_anon import scrub
|
||
|
||
|
||
def _ru_float(s: str | None) -> float:
|
||
"""ГРАНД пишет десятичные с запятой (Data.xml) или точкой (Properties.txt)."""
|
||
if not s:
|
||
return 0.0
|
||
try:
|
||
return float(s.strip().replace(" ", "").replace(",", "."))
|
||
except (ValueError, AttributeError):
|
||
return 0.0
|
||
|
||
|
||
def _ru_float_opt(s: str | None) -> float | None:
|
||
"""Как _ru_float, но отсутствие значения = None (не выдуманный 0)."""
|
||
if s is None or not s.strip():
|
||
return None
|
||
return _ru_float(s)
|
||
|
||
|
||
def _safe_xml_root(data: bytes):
|
||
"""XXE/billion-laughs-устойчивый разбор. Кодировка — из XML-декларации
|
||
(windows-1251 у ГРАНД), поэтому вход строго БАЙТЫ."""
|
||
try:
|
||
from defusedxml.ElementTree import fromstring as _fromstring
|
||
return _fromstring(data)
|
||
except ImportError:
|
||
return ET.fromstring(data)
|
||
|
||
|
||
def _vids_rab(root) -> dict[str, dict]:
|
||
"""Каталог видов работ: ID → НР/СП (проценты от ФОТ) с обоснованиями."""
|
||
cat: dict[str, dict] = {}
|
||
for v in root.iter("Vid_Rab"):
|
||
vid = v.get("ID")
|
||
if not vid:
|
||
continue
|
||
cat[vid] = {
|
||
"caption": scrub(v.get("Caption") or ""),
|
||
"nacl": _ru_float_opt(v.get("NaclCurr") or v.get("Nacl")),
|
||
"plan": _ru_float_opt(v.get("PlanCurr") or v.get("Plan")),
|
||
"nr_code": (v.get("NrCode") or "").strip(),
|
||
"sp_code": (v.get("SpCode") or "").strip(),
|
||
"nacl_mask": (v.get("NaclMask") or "").strip(),
|
||
"plan_mask": (v.get("PlanMask") or "").strip(),
|
||
}
|
||
return cat
|
||
|
||
|
||
def _price(el, tag: str) -> tuple[float | None, str]:
|
||
"""(значение, обезличенный comment-источник) из дочернего PriceCurr/PriceBase.
|
||
Value → PZ → MT: у расценок цена в @Value, у материалов-позиций в @MT/@PZ."""
|
||
node = el.find(tag)
|
||
if node is None:
|
||
return None, ""
|
||
val = (_ru_float_opt(node.get("Value"))
|
||
or _ru_float_opt(node.get("PZ"))
|
||
or _ru_float_opt(node.get("MT")))
|
||
return val, scrub(node.get("Comment") or "")
|
||
|
||
|
||
def _resources(res_el) -> dict:
|
||
"""Ресурсный состав: Tzr → workers, Mch → machines, Mat → materials.
|
||
consumption — норма НА ЕДИНИЦУ расценки. Tzm (труд машинистов) отдаётся
|
||
вызывающему отдельно (позиционное machinist_ch)."""
|
||
out: dict = {"workers": [], "machines": [], "materials": []}
|
||
for r in res_el:
|
||
cur, cur_comment = _price(r, "PriceCurr")
|
||
base, _ = _price(r, "PriceBase")
|
||
if r.tag == "Tzr":
|
||
out["workers"].append({
|
||
"name": scrub(r.get("Caption") or ""),
|
||
"code": (r.get("Code") or "").strip(),
|
||
"unit": (r.get("Units") or "").strip(),
|
||
"consumption": _ru_float(r.get("Quantity")),
|
||
"work_class": (r.get("WorkClass") or "").strip(),
|
||
"price_cur": cur,
|
||
"price_comment": cur_comment,
|
||
})
|
||
elif r.tag == "Mch":
|
||
pc = r.find("PriceCurr")
|
||
tzm = r.find("Tzm2022")
|
||
out["machines"].append({
|
||
"name": scrub(r.get("Caption") or ""),
|
||
"code": (r.get("Code") or "").strip(),
|
||
"unit": (r.get("Units") or "").strip(),
|
||
"consumption": _ru_float(r.get("Quantity")),
|
||
"price_base": base,
|
||
"price_cur": cur,
|
||
# ЗПМ внутри цены маш.часа (руб/маш.час) — база для НР/СП
|
||
"zm_cur": _ru_float_opt(pc.get("ZM")) if pc is not None else None,
|
||
"price_comment": cur_comment,
|
||
"machinist": {
|
||
"work_class": (tzm.get("WorkClass") or "").strip(),
|
||
"count": _ru_float(tzm.get("Quantity")),
|
||
"price_cur": _ru_float(tzm.get("Price")),
|
||
} if tzm is not None else None,
|
||
})
|
||
elif r.tag == "Mat":
|
||
out["materials"].append({
|
||
"name": scrub(r.get("Caption") or ""),
|
||
"code": (r.get("Code") or "").strip(),
|
||
"unit": (r.get("Units") or "").strip(),
|
||
"consumption": _ru_float(r.get("Quantity")),
|
||
"price_base": base,
|
||
"price_cur": cur,
|
||
"price_comment": cur_comment,
|
||
# NotCount = неучтённый материал (поставка заказчика, цены нет)
|
||
"not_counted": "NotCount" in (r.get("Options") or ""),
|
||
})
|
||
return out
|
||
|
||
|
||
def _coefficients(pos) -> list[dict]:
|
||
"""Поправочные коэффициенты позиции (K): к ОЗП/ЭМ/МТ/ПЗ, с обоснованием."""
|
||
out = []
|
||
ks = pos.find("Koefficients")
|
||
if ks is None:
|
||
return out
|
||
for k in ks.findall("K"):
|
||
out.append({
|
||
"name": scrub(k.get("Caption") or ""),
|
||
# K@Code — свободное поле: помимо нормативов («Прил.28.1 п.1.7»)
|
||
# встречаются шифры томов проекта (реквизиты) → scrub обязателен
|
||
"code": scrub((k.get("Code") or "").strip()),
|
||
"oz": _ru_float_opt(k.get("Value_OZ")),
|
||
"em": _ru_float_opt(k.get("Value_EM")),
|
||
"mt": _ru_float_opt(k.get("Value_MT")),
|
||
"pz": _ru_float_opt(k.get("Value_PZ")),
|
||
})
|
||
return out
|
||
|
||
|
||
def _nr_sp(vr: dict | None) -> tuple[dict | None, dict | None]:
|
||
"""(overhead, profit) из записи каталога Vids_Rab; None если ненадёжно."""
|
||
if not vr:
|
||
return None, None
|
||
ov = {"pct": vr["nacl"], "base": vr["nacl_mask"], "code": vr["nr_code"],
|
||
"vid_rab": vr["caption"]} if vr["nacl"] is not None else None
|
||
pr = {"pct": vr["plan"], "base": vr["plan_mask"], "code": vr["sp_code"],
|
||
"vid_rab": vr["caption"]} if vr["plan"] is not None else None
|
||
return ov, pr
|
||
|
||
|
||
def parse_gsfx_full(path: Path) -> dict:
|
||
"""Полный разбор .gsfx: шапка + позиции с ресурсным составом, составом
|
||
работ, НР/СП и мягкой сверкой суммы позиций с Properties.Total."""
|
||
try:
|
||
with zipfile.ZipFile(str(path)) as z:
|
||
names = z.namelist()
|
||
props_name = next((n for n in names if n.lower().endswith(".txt")), None)
|
||
data_name = next((n for n in names if n.lower().endswith(".xml")), None)
|
||
props_raw = z.read(props_name) if props_name else b""
|
||
data_raw = z.read(data_name) if data_name else b""
|
||
except (zipfile.BadZipFile, OSError, KeyError) as e:
|
||
return {"error": f"{type(e).__name__}: {e}", "path": str(path)}
|
||
|
||
props: dict[str, str] = {}
|
||
for line in props_raw.decode("cp1251", "replace").splitlines():
|
||
if "=" in line:
|
||
k, v = line.split("=", 1)
|
||
props[k.strip()] = v.strip()
|
||
total = _ru_float_opt(props.get("Total"))
|
||
|
||
if not data_raw:
|
||
return {"error": "нет Data.xml в архиве", "path": str(path)}
|
||
try:
|
||
root = _safe_xml_root(data_raw)
|
||
except ET.ParseError as e:
|
||
return {"error": f"Data.xml ParseError: {e}", "path": str(path)}
|
||
|
||
dd = root.find("DocDates")
|
||
price_level = {
|
||
"base": (dd.get("BasePriceDate") or "").strip() if dd is not None else "",
|
||
"cur": (dd.get("CurrPriceDate") or "").strip() if dd is not None else "",
|
||
}
|
||
cat = _vids_rab(root)
|
||
|
||
positions: list[dict] = []
|
||
summary_rows = 0
|
||
computed_total = 0.0
|
||
for pos in root.iter("Position"):
|
||
# нормативные шифры (ГЭСН…/ФСБЦ…) deny-правила не трогают, а
|
||
# прайс-ссылки (ТЦ_…) содержат номер прайса/ИНН → scrub и для кода
|
||
code = scrub((pos.get("Code") or "").strip())
|
||
# ССР-строки: ссылки на другие сметы (без кода расценки, итог в <Total>);
|
||
# их Caption/Obosn = имена объектов и реквизиты — не расценки, пропуск.
|
||
if not code or pos.find("Total") is not None:
|
||
summary_rows += 1
|
||
continue
|
||
qty_el = pos.find("Quantity")
|
||
qty = _ru_float(qty_el.get("Result")) if qty_el is not None else 0.0
|
||
res_el = pos.find("Resources")
|
||
cur, _cur_comment = _price(pos, "PriceCurr")
|
||
base, _ = _price(pos, "PriceBase")
|
||
|
||
if res_el is not None:
|
||
kind = "work"
|
||
resources = _resources(res_el)
|
||
machinist_ch = sum(_ru_float(t.get("Quantity"))
|
||
for t in res_el.findall("Tzm"))
|
||
unit_cost = fot = 0.0
|
||
for w in resources["workers"]:
|
||
if w["price_cur"]:
|
||
unit_cost += w["consumption"] * w["price_cur"]
|
||
fot += w["consumption"] * w["price_cur"]
|
||
for m in resources["machines"]:
|
||
if m["price_cur"]:
|
||
unit_cost += m["consumption"] * m["price_cur"]
|
||
if m["zm_cur"]:
|
||
fot += m["consumption"] * m["zm_cur"]
|
||
for mt in resources["materials"]:
|
||
if mt["price_cur"]:
|
||
unit_cost += mt["consumption"] * mt["price_cur"]
|
||
unit_cost_cur: float | None = round(unit_cost, 2)
|
||
labor_ch = sum(w["consumption"] for w in resources["workers"])
|
||
overhead, profit = _nr_sp(cat.get(pos.get("Vr2001") or ""))
|
||
nrsp_pct = ((overhead or {}).get("pct") or 0) + ((profit or {}).get("pct") or 0)
|
||
computed_total += qty * (unit_cost + fot * nrsp_pct / 100.0)
|
||
else:
|
||
# Позиция-материал/оборудование (цена прямо на позиции) или голая.
|
||
kind = "material" if (cur is not None or base is not None) else "other"
|
||
resources = {"workers": [], "machines": [], "materials": []}
|
||
labor_ch = machinist_ch = 0.0
|
||
unit_cost_cur = cur
|
||
overhead, profit = _nr_sp(cat.get(pos.get("Vr2001") or ""))
|
||
if cur is not None:
|
||
computed_total += qty * cur
|
||
# доставка: тонны (Mass кг/ед × объём) × тариф последней плечи
|
||
tr = pos.find("Transportation")
|
||
mass = _ru_float(pos.get("Mass"))
|
||
if tr is not None and mass:
|
||
items = tr.findall("Item")
|
||
if items:
|
||
computed_total += (mass / 1000.0) * qty * _ru_float(
|
||
items[-1].get("PriceCurr"))
|
||
|
||
positions.append({
|
||
"code": code,
|
||
"name": scrub((pos.get("Caption") or "").strip()),
|
||
"unit": (pos.get("Units") or "").strip(),
|
||
"quantity": qty,
|
||
"kind": kind,
|
||
"comment": scrub((pos.get("Comment") or "").strip()),
|
||
"price_source": scrub((pos.get("DBComment") or "").strip()),
|
||
# источник цены позиции-материала (ССЦ-каталог из PriceCurr@Comment)
|
||
"price_comment": _cur_comment,
|
||
"unit_cost_cur": unit_cost_cur,
|
||
"labor_ch": labor_ch,
|
||
"machinist_ch": machinist_ch,
|
||
"resources": resources,
|
||
"works_list": [scrub((w.get("Caption") or "").strip())
|
||
for w in pos.findall("WorksList/Work")],
|
||
"coefficients": _coefficients(pos),
|
||
"overhead": overhead,
|
||
"profit": profit,
|
||
})
|
||
|
||
return {
|
||
"path": str(path),
|
||
"format": "gsfx-full",
|
||
"code": props.get("Attribs.LocNum", "").strip(),
|
||
"name": scrub((props.get("Attribs.ConName")
|
||
or props.get("Attribs.Description") or "").strip()),
|
||
# гео-регион сознательно НЕ извлекаем (точный регион = проектный
|
||
# идентификатор по deny-листу); зона ценообразования — безопасна
|
||
"region": props.get("RegionInfo.ZoneName", "").strip(),
|
||
"norm_base": props.get("RegionInfo.RegionName", "").strip(),
|
||
"price_level": price_level,
|
||
"total": total,
|
||
"positions": positions,
|
||
"summary_rows": summary_rows,
|
||
"totals_check": {
|
||
"computed": round(computed_total, 2),
|
||
"declared": total,
|
||
"ratio": round(computed_total / total, 4) if total else None,
|
||
},
|
||
}
|