feat: расширение корпуса — .gge(ДВ)/.gsfx/.arp(ОСНБЖ) в ext-индекс (#2-#5)
Три глубоких парсера (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>
This commit is contained in:
+249
@@ -0,0 +1,249 @@
|
||||
"""arp_deep — глубокий разбор .arp/.arps (АРПС 1.10, Smeta.RU / ПК АВС):
|
||||
расценки с базисными/текущими стоимостями, РЕАЛЬНО ПРИМЕНЁННЫМИ коэффициентами
|
||||
(Кнр/Ксп/Кизп/поправочными) и ресурсным составом. База — ОЕРЖ/ОСНБЖ (ж/д).
|
||||
|
||||
Семантика полей верифицирована численно на 283 реальных .arp (11900/12000):
|
||||
итог шапки (тип 3 f14) = Σ по позициям (ПЗтек + (Кнр+Ксп)×(ОТтек+ЗПМтек)) × f26,
|
||||
сходится с точностью <0.1% на 281/283 файлах → объём позиции = f26 (не f25).
|
||||
тип 3 — шапка: f4=шифр, f5=имя, f14=итог. f12/f13 = ФИО — НЕ извлекаются (allow-list).
|
||||
тип 0 — параметры (Метод расчета, Год нормативной базы) и свободные комментарии,
|
||||
в т.ч. обоснование пересчёта в текущие цены (распоряжение ОАО РЖД → price_level).
|
||||
тип 10 — раздел: f3=имя.
|
||||
тип 20 — позиция: f2=обоснование (1-й токен=шифр), f3=ед., f4=имя,
|
||||
f5..f9 = БАЗИСНЫЕ ПЗ/ОТ/ЭМ/ЗПМ/МР на ед. (2001),
|
||||
f13/f14 = труд рабочих/машинистов на ед. баз., f23/f24 — с коэф.,
|
||||
f15..f19 = ТЕКУЩИЕ ПЗ/ОТ/ЭМ/ЗПМ/МР на ед. (с коэф. и индексами), f26=объём.
|
||||
тип 25 — применённый коэффициент: f1=группа (0=индекс пересчёта Кизп/Киэм/Кимр/…,
|
||||
2=Кнр, 3=Ксп, 4=поправочный Кзп/Ктрр/Кvмаш/…, 10=Ктр/Кзср),
|
||||
f2=статья (0=ОТ,1=ЭМ,2=МР,3=ЗПМ,4=ТЗ раб.,5=ТЗ маш.), f4=значение,
|
||||
f5=имя, f6=обоснование (обычно пусто — обоснования в комментариях типа 0).
|
||||
тип 30 — ресурс: f1=код (1=труд рабочих, 1.1=средний разряд, 3=труд машинистов),
|
||||
f2=ед., f3=имя, f4=вид (0=труд,1=машина,2=материал),
|
||||
f5=расход на ЕД. позиции С УЧЁТОМ коэффициентов, f6=цена базисная 2001
|
||||
(f6==f7==f8 на всех 68898 записях корпуса).
|
||||
|
||||
Обезличивание: свободный текст (имена/обоснования/комментарии/разделы) — через
|
||||
corpus_anon.scrub; ФИО подписантов и рег.номер не извлекаются вовсе.
|
||||
Зависимости: stdlib + corpus_anon. Совместимо с sandbox.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from corpus_anon import scrub
|
||||
|
||||
_COEF_GROUPS = {"0": "index", "2": "overhead", "3": "profit",
|
||||
"4": "adjust", "10": "mat_extra"}
|
||||
_COEF_TARGETS = {"0": "ОТ", "1": "ЭМ", "2": "МР", "3": "ЗПМ",
|
||||
"4": "ТЗ раб.", "5": "ТЗ маш.", "10": "МР"}
|
||||
# пересчёт в текущие цены: «…по распоряжению N1288р от 13.05.2022г…»
|
||||
_RECALC_RE = re.compile(
|
||||
r"(?:распоряжени\w+|письму)\D{0,40}?N?[№\s]*(?:[Ии]сх-)?(\d{3,5})\s*/?\s*р?\b"
|
||||
r".{0,20}?(\d{2}\.\d{2}\.\d{4})", re.DOTALL)
|
||||
_NORM_BASE_RE = re.compile(r"ОСНБЖ|ОЕРЖ|ОСОЦЖ")
|
||||
|
||||
|
||||
def _rf(s: str) -> float:
|
||||
"""АРПС пишет десятичные с запятой."""
|
||||
try:
|
||||
return float(s.strip().replace(" ", "").replace(",", "."))
|
||||
except (ValueError, AttributeError):
|
||||
return 0.0
|
||||
|
||||
|
||||
# шифр расценки/материала: 01-02-058-03, 318533-0003, 500-9004-013*, 204-0100, 1
|
||||
_CODE_TOKEN_RE = re.compile(r"\d[\d\-.]*\*?")
|
||||
|
||||
|
||||
def _code_from_just(just: str) -> str:
|
||||
"""Шифр из обоснования. Бывает и «<код> <норм.док>» (28-02-013-01 ОЕРЖ-2001…),
|
||||
и «<норм.док> <код>» (ОЕРЖм 08-01-121-01) — брать первый КОДОПОДОБНЫЙ токен,
|
||||
иначе 161 разная расценка склеится под ключом 'ОЕРЖм'. У прайс-позиций
|
||||
(Т ТЦ_…) кодоподобного токена нет — пустой код, агрегация пойдёт по имени."""
|
||||
for tok in just.split(" ")[:3]:
|
||||
if _CODE_TOKEN_RE.fullmatch(tok):
|
||||
return tok
|
||||
return ""
|
||||
|
||||
|
||||
def _new_position(f: list[str], section: str) -> dict:
|
||||
just = f[2].strip()
|
||||
g = lambda i: _rf(f[i]) if len(f) > i else 0.0 # noqa: E731
|
||||
return {
|
||||
"num": f[1].strip(),
|
||||
"code": _code_from_just(just),
|
||||
"justification": scrub(just),
|
||||
"unit": f[3].strip(),
|
||||
"name": scrub(f[4].strip()),
|
||||
"section": section,
|
||||
"quantity": g(26),
|
||||
"base_costs": {"direct": g(5), "labor": g(6), "machines": g(7),
|
||||
"machinist": g(8), "materials": g(9)},
|
||||
"cur_costs": {"direct": g(15), "labor": g(16), "machines": g(17),
|
||||
"machinist": g(18), "materials": g(19)},
|
||||
"labor_ch": g(13), "labor_ch_adj": g(23),
|
||||
"machinist_ch": g(14), "machinist_ch_adj": g(24),
|
||||
"unit_cost_cur": 0.0, "total_cur": 0.0, # после сбора Кнр/Ксп
|
||||
"coefficients": [],
|
||||
"resources": {"workers": [], "machines": [], "materials": []},
|
||||
}
|
||||
|
||||
|
||||
def _add_coefficient(pos: dict, f: list[str]) -> None:
|
||||
kind = f[5].strip() if len(f) > 5 else ""
|
||||
val = _rf(f[4])
|
||||
if not kind and not val:
|
||||
return
|
||||
pos["coefficients"].append({
|
||||
"kind": kind,
|
||||
"group": _COEF_GROUPS.get(f[1].strip(), f[1].strip()),
|
||||
"target": _COEF_TARGETS.get(f[2].strip(), f[2].strip()),
|
||||
"value": val,
|
||||
"reason": scrub(f[6].strip()) if len(f) > 6 and f[6].strip() else "",
|
||||
})
|
||||
|
||||
|
||||
def _add_resource(pos: dict, f: list[str]) -> None:
|
||||
if len(f) < 6:
|
||||
return
|
||||
code, unit, name, flag = f[1].strip(), f[2].strip(), f[3].strip(), f[4].strip()
|
||||
if code == "1.1": # средний разряд — свойство последнего труд-ресурса
|
||||
if pos["resources"]["workers"]:
|
||||
pos["resources"]["workers"][-1]["grade"] = f[5].strip()
|
||||
return
|
||||
rec = {"code": code, "name": scrub(name), "unit": unit,
|
||||
"consumption": _rf(f[5]),
|
||||
"price_base": _rf(f[6]) if len(f) > 6 else 0.0}
|
||||
if flag == "1":
|
||||
pos["resources"]["machines"].append(rec)
|
||||
elif flag == "2":
|
||||
pos["resources"]["materials"].append(rec)
|
||||
else: # 0 = труд (рабочие-строители / машинисты)
|
||||
rec["grade"] = ""
|
||||
pos["resources"]["workers"].append(rec)
|
||||
|
||||
|
||||
def _finalize_position(pos: dict) -> None:
|
||||
"""Полная цена ед. в тек. ценах: ПЗ + НР + СП, где НР/СП = К × (ОТ+ЗПМ).
|
||||
Формула верифицирована сходимостью с итогом шапки на 281/283 реальных файлах."""
|
||||
knr = ksp = 0.0
|
||||
for c in pos["coefficients"]:
|
||||
if c["target"] == "ОТ":
|
||||
if c["kind"] == "Кнр":
|
||||
knr = c["value"]
|
||||
elif c["kind"] == "Ксп":
|
||||
ksp = c["value"]
|
||||
fot = pos["cur_costs"]["labor"] + pos["cur_costs"]["machinist"]
|
||||
pos["unit_cost_cur"] = round(pos["cur_costs"]["direct"] + (knr + ksp) * fot, 2)
|
||||
pos["total_cur"] = round(pos["unit_cost_cur"] * pos["quantity"], 2)
|
||||
|
||||
|
||||
def parse_arp_text(text: str, path: str = "") -> dict:
|
||||
"""Разобрать содержимое .arp (уже декодированное из cp866)."""
|
||||
code = name = method = base_year = ""
|
||||
total = 0.0
|
||||
comments: list[str] = []
|
||||
positions: list[dict] = []
|
||||
section = ""
|
||||
cur: dict | None = None
|
||||
|
||||
for line in text.splitlines():
|
||||
if "#" not in line:
|
||||
continue
|
||||
f = line.split("#")
|
||||
rec = f[0]
|
||||
if rec == "3" and len(f) > 5:
|
||||
code = f[4].strip()
|
||||
name = scrub(f[5].strip())
|
||||
if len(f) > 14:
|
||||
total = _rf(f[14])
|
||||
elif rec == "0" and len(f) > 1:
|
||||
key = f[1].strip()
|
||||
val = f[2].strip() if len(f) > 2 else ""
|
||||
if key.startswith("Метод расчета"):
|
||||
method = val
|
||||
elif key == "Год нормативной базы":
|
||||
base_year = val
|
||||
elif key == "Регистрационный номер":
|
||||
continue # идентификатор — не извлекаем
|
||||
else:
|
||||
txt = " ".join(x.strip() for x in f[1:] if x.strip())
|
||||
if len(txt) > 10: # служебную мелочь (Формат и т.п.) не тащим
|
||||
comments.append(txt)
|
||||
elif rec == "10" and len(f) > 3:
|
||||
section = scrub(f[3].strip())
|
||||
elif rec == "20" and len(f) > 4:
|
||||
if cur is not None:
|
||||
_finalize_position(cur)
|
||||
cur = _new_position(f, section)
|
||||
positions.append(cur)
|
||||
elif rec == "25" and len(f) > 5 and cur is not None:
|
||||
_add_coefficient(cur, f)
|
||||
elif rec == "30" and cur is not None:
|
||||
_add_resource(cur, f)
|
||||
if cur is not None:
|
||||
_finalize_position(cur)
|
||||
|
||||
# пересчёт в тек. цены (пункт #5): распоряжение/письмо из комментариев
|
||||
recalc = None
|
||||
for c in comments:
|
||||
m = _RECALC_RE.search(c)
|
||||
if m:
|
||||
recalc = {"doc": m.group(1) + "р", "date": m.group(2), "reason": scrub(c)}
|
||||
break
|
||||
if recalc:
|
||||
price_level = f"тек. {recalc['date'][3:]} (расп. {recalc['doc']})"
|
||||
elif method.startswith("базисный"):
|
||||
price_level = "тек. (базисно-индексный, Кизп)"
|
||||
else:
|
||||
price_level = ""
|
||||
|
||||
# сводка фактических индексов пересчёта (группа 0: Кизп/Киэм/Кимр/Кизпм/Киоб)
|
||||
kizp_values: dict[str, dict[str, int]] = {}
|
||||
for p in positions:
|
||||
for c in p["coefficients"]:
|
||||
if c["group"] == "index" and c["kind"]:
|
||||
v = str(c["value"]).replace(".", ",")
|
||||
kizp_values.setdefault(c["kind"], {})
|
||||
kizp_values[c["kind"]][v] = kizp_values[c["kind"]].get(v, 0) + 1
|
||||
kizp_main = None
|
||||
if kizp_values.get("Кизп"):
|
||||
top = max(kizp_values["Кизп"].items(), key=lambda kv: kv[1])[0]
|
||||
kizp_main = _rf(top)
|
||||
|
||||
# нормативная база — только по фактическим маркерам (не выдумываем)
|
||||
hay = " ".join(comments) + " " + " ".join(p["justification"] for p in positions)
|
||||
norm_base = "ОСНБЖ" if _NORM_BASE_RE.search(hay) else ""
|
||||
|
||||
# гейт: итог шапки против суммы позиций по верифицированной формуле
|
||||
total_computed = round(sum(p["total_cur"] for p in positions), 2)
|
||||
total_check_ok = bool(total) and abs(total_computed - total) / total < 1e-3
|
||||
|
||||
return {
|
||||
"path": path,
|
||||
"format": "arp",
|
||||
"code": code,
|
||||
"name": name,
|
||||
"method": method,
|
||||
"base_year": base_year,
|
||||
"norm_base": norm_base,
|
||||
"price_level": price_level,
|
||||
"recalc": recalc,
|
||||
"total": total,
|
||||
"total_computed": total_computed,
|
||||
"total_check_ok": total_check_ok,
|
||||
"comments": [scrub(c) for c in comments],
|
||||
"kizp": {"main": kizp_main, "values": kizp_values},
|
||||
"positions_count": len(positions),
|
||||
"positions": positions,
|
||||
}
|
||||
|
||||
|
||||
def parse_arp_full(path: Path) -> dict:
|
||||
"""Полный разбор .arp/.arps с диска (cp866)."""
|
||||
try:
|
||||
raw = Path(path).read_bytes()
|
||||
except OSError as e:
|
||||
return {"error": f"{type(e).__name__}: {e}", "path": str(path)}
|
||||
return parse_arp_text(raw.decode("cp866", "replace"), path=str(path))
|
||||
@@ -502,13 +502,18 @@ def _search_corpus(message: str) -> str:
|
||||
# ФОТ/ед для расчёта НР/СП (find_in_real_estimates считает масштаб)
|
||||
fot_unit = r.get("fot_unit")
|
||||
fot_str = f" | ФОТ/ед ≈ {fot_unit} руб (база для НР/СП)" if fot_unit else ""
|
||||
nb = r.get("norm_base") or ""
|
||||
pl = r.get("price_level")
|
||||
base_str = (f" | база: {nb}" if nb else "") + (f" | уровень цен: {pl}" if pl else "")
|
||||
lines.append(
|
||||
f"[{code}] {r['name']} | {r['unit']} | цена/ед(тек прямые) = {r['unit_cost_cur']} руб"
|
||||
f"{fot_str} | НР {ov.get('value','?')}% от ФОТ | СП {pr.get('value','?')}% от ФОТ | регион: {regs}")
|
||||
f"{fot_str} | НР {ov.get('value','?')}% от ФОТ | СП {pr.get('value','?')}% от ФОТ | регион: {regs}{base_str}")
|
||||
if not lines:
|
||||
return ""
|
||||
return ("Реальные применённые расценки из корпуса смет (бери эти ЦЕНЫ/ед и КОДЫ "
|
||||
"для расчёта — это настоящие данные, не выдумывай):\n" + "\n".join(lines))
|
||||
"для расчёта — это настоящие данные, не выдумывай). СВЕРЯЙ уровень цен и базу "
|
||||
"нормативов: цены разных баз (ГЭСН/ФЕР vs ОСНБЖ) и уровней (текущие vs базис 2001) "
|
||||
"НЕ смешивай в одной смете:\n" + "\n".join(lines))
|
||||
|
||||
|
||||
async def stream_claude(
|
||||
|
||||
@@ -45,6 +45,9 @@ _DENY = [
|
||||
r"\b\d{4}[/.]\d{2}[/.]\d{2}[-\w]*",
|
||||
r"\b960-0\d[\w.\-]*",
|
||||
r"\b\d{8,}\b",
|
||||
# ИНН/длинный ID в underscore-контексте: «ТЦ_101_61_6164074370_2022_02»
|
||||
# (прайс-ссылки АРПС) — \b\d{8,}\b его не ловит, «_» = словесный символ
|
||||
r"_\d{8,}",
|
||||
]
|
||||
|
||||
_DENY_RE = [re.compile(p) for p in _DENY]
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -33,6 +33,20 @@
|
||||
- юнит на синтетическом реестре (mutation-safe) + real-build на настоящих реестрах: records>0,
|
||||
0 утечек в выходном индексе, счётчики confirmed/smeta осмысленны.
|
||||
|
||||
### Acceptance Criteria (Шаг: пункты #2-#5 расширения корпуса)
|
||||
Общее (анти-отравление, критично): каждая запись несёт `norm_base` (ГЭСН/ФЕР/ОЕРЖ/ОСНБЖ) и
|
||||
`price_level` (2025Q1 / 2001-базис); обезличено через `corpus_anon` (0 утечек); цена вне 5×
|
||||
медианы по коду → карантин; всё пишется в STAGING, живой индекс мержу отдельно после ревью.
|
||||
- #2 долить .gge: новые РИМ-сметы (регион ДВ, цены 2025) в estimates_index; КА из вложенных zip
|
||||
(рекурсия); БИМ-сметы (LocalEstimateBaseIndexMethod, 2001-базис) → карантин.
|
||||
- #3 gsfx_deep: глубокий парсер .gsfx (Resources+PriceCurr+comment-источник + WorksList состав) →
|
||||
записи расценок; юнит на синтетике + real-тест.
|
||||
- #4 arp_deep: АРПС (записи 20/25/30: база/текущие, реально применённые Кнр/Ксп/Кизп, ресурсы),
|
||||
norm_base=ОСНБЖ; парная .xls-распечатка = ground truth сверки итогов.
|
||||
- #5 индексы пересчёта: Кизп/распоряжения из .arp → поле/мини-индекс.
|
||||
- #6 (пары замечание→правка) и #7 (библиотека !_ТЗ ДЛЯ) — Fable рекомендовал НЕ автоматизировать
|
||||
(исследовательское / отравление устаревшими ценами); отложены осознанно, не молча.
|
||||
|
||||
---
|
||||
|
||||
# МАСТЕР-ПЛАН улучшений по анализу корпуса (2026-07-15, Fable)
|
||||
|
||||
+2
-1
@@ -319,7 +319,8 @@ def parse_ka(data: bytes) -> list[dict]:
|
||||
"storage": _f(_t(off, "Storage/Price")) or None,
|
||||
"transport": _f(_t(off, "Transportation/Price")) or None,
|
||||
"delivery": _t(off, "OfferPrice/DeliveryTerms"),
|
||||
"region": _t(off, "Region/Name"),
|
||||
# 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",
|
||||
|
||||
+307
@@ -0,0 +1,307 @@
|
||||
"""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,
|
||||
},
|
||||
}
|
||||
@@ -138,7 +138,7 @@ MAX_MESSAGE_LEN = 10_000
|
||||
|
||||
# ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква).
|
||||
# Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version).
|
||||
APP_VERSION = "2026-07-15h"
|
||||
APP_VERSION = "2026-07-16a"
|
||||
|
||||
# Audit: path → action name mapping
|
||||
_AUDIT_MAP = [
|
||||
|
||||
+11
-1
@@ -67,6 +67,13 @@ def _load_estimates() -> dict:
|
||||
p = _DATA / "estimates_index.json"
|
||||
_est_cache = json.loads(p.read_text(encoding="utf-8")) if p.exists() else {"items": []}
|
||||
items = _est_cache["items"]
|
||||
# Ext-индекс (новые домены: .gge ДВ / .gsfx / .arp ОСНБЖ) — ОТДЕЛЬНЫЙ файл,
|
||||
# живой ВСЖМ-индекс не трогаем. Каждая ext-запись несёт norm_base/price_level.
|
||||
ext_p = _DATA / "estimates_ext_index.json"
|
||||
if ext_p.exists():
|
||||
ext = json.loads(ext_p.read_text(encoding="utf-8"))
|
||||
items.extend(ext.get("items", []))
|
||||
_est_cache.setdefault("materials", []).extend(ext.get("materials", []))
|
||||
df: dict[str, int] = {}
|
||||
for it in items:
|
||||
it["_terms"] = _terms(it["name"])
|
||||
@@ -108,6 +115,9 @@ def _load_ka() -> dict:
|
||||
if _ka_cache is None:
|
||||
p = _DATA / "ka_index.json"
|
||||
_ka_cache = json.loads(p.read_text(encoding="utf-8")) if p.exists() else {"items": []}
|
||||
ext_p = _DATA / "estimates_ext_index.json"
|
||||
if ext_p.exists():
|
||||
_ka_cache["items"].extend(json.loads(ext_p.read_text(encoding="utf-8")).get("ka", []))
|
||||
df: dict[str, int] = {}
|
||||
for it in _ka_cache["items"]:
|
||||
it["_terms"] = _terms(it["name"])
|
||||
@@ -162,7 +172,7 @@ def find_in_real_estimates(query: str, top_k: int = 5) -> list[dict]:
|
||||
keys = ("code", "name", "unit", "prefix", "kind", "freq", "norm_sets", "regions",
|
||||
"qty", "comment", "unit_cost_cur", "fot_unit", "cost_structure", "labor_ch",
|
||||
"machinist_ch", "price_base", "price_cur", "overhead", "profit",
|
||||
"coef_applications", "resources", "examples")
|
||||
"coef_applications", "resources", "examples", "norm_base", "price_level")
|
||||
out = []
|
||||
for _, _, it in results[:top_k]:
|
||||
d = {k: it.get(k) for k in keys}
|
||||
|
||||
@@ -0,0 +1,413 @@
|
||||
"""build_arp_staging — STAGING-индекс расценок из .arp (АРПС 1.10, база ОСНБЖ/ОЕРЖ ж/д).
|
||||
|
||||
Живой индекс (estimates_index.json) НЕ трогает: пишет data/real_corpus/staging_arp.json
|
||||
(+ операционный staging_arp_quarantine.json с именами забракованных файлов — НЕ для
|
||||
корпуса, имена файлов могут содержать топонимы).
|
||||
|
||||
Гейты (все fail-loud, брак → карантин, не в staging):
|
||||
1. norm_base: в файле нет маркеров ОСНБЖ/ОЕРЖ/ОСОЦЖ → не помечаем чужую базу.
|
||||
2. Внутренний итог: сумма позиций по верифицированной формуле против итога шапки.
|
||||
3. Парная .xls-распечатка (ground truth): у .arp в том же zip ищется .xls с тем же
|
||||
нормализованным стемом («00_02_7_00_01Р (№…).arp» ↔ «00_02_7_00_01Р.xls»),
|
||||
итог из строки «Итого по смете» (в .xls округлён до рубля) сверяется с шапкой .arp.
|
||||
4. Утечки: has_identifier_leak по каждому текстовому полю → запись в карантин.
|
||||
5. Цена: unit_cost_cur вне 5× медианы по коду (при ≥3 образцах) → вхождение в карантин.
|
||||
|
||||
Пункт #5 дорожной карты: recalc_index — фактические индексы пересчёта (Кизп/Киэм/
|
||||
Кимр/Кизпм/Киоб) с распоряжениями ОАО РЖД, агрегированные по документу пересчёта.
|
||||
|
||||
Запуск: python3 scripts/build_arp_staging.py <файл.arp|архив.zip|каталог>... [--out ...]
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import posixpath
|
||||
import re
|
||||
import statistics
|
||||
import sys
|
||||
import zipfile
|
||||
from collections import Counter, defaultdict
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from arp_deep import parse_arp_text # noqa: E402
|
||||
from corpus_anon import has_identifier_leak # noqa: E402
|
||||
|
||||
try:
|
||||
import xlrd # .xls (BIFF) — парные распечатки
|
||||
except ImportError:
|
||||
xlrd = None
|
||||
|
||||
MAX_RES = 30
|
||||
_TOTAL_ROW_RE = re.compile(r"(?i)(?:итого|всего)\s+по\s+смете")
|
||||
|
||||
|
||||
def iter_strings(obj):
|
||||
"""Все строковые ЗНАЧЕНИЯ структуры. Канарейку гонять по ним, а не по
|
||||
json.dumps: JSON-кавычки превращают безобидное "Кизп" в ложное «имя в кавычках»."""
|
||||
if isinstance(obj, str):
|
||||
yield obj
|
||||
elif isinstance(obj, dict):
|
||||
for v in obj.values():
|
||||
yield from iter_strings(v)
|
||||
elif isinstance(obj, (list, tuple)):
|
||||
for v in obj:
|
||||
yield from iter_strings(v)
|
||||
|
||||
|
||||
def _struct_leaks(obj) -> bool:
|
||||
return any(has_identifier_leak(s) for s in iter_strings(obj))
|
||||
|
||||
|
||||
def _cp866_name(zip_name: str) -> str:
|
||||
"""Windows-zip без UTF-8 флага: имена в cp437-мусоре, реально cp866."""
|
||||
try:
|
||||
return zip_name.encode("cp437").decode("cp866")
|
||||
except (UnicodeEncodeError, UnicodeDecodeError):
|
||||
return zip_name
|
||||
|
||||
|
||||
def _norm_stem(name: str, ext: str) -> str:
|
||||
s = posixpath.basename(name)
|
||||
s = re.sub(rf"\.{ext}$", "", s, flags=re.I)
|
||||
s = re.sub(r"\s*\([^)]*\)\s*", "", s) # (№119400053)
|
||||
return s.replace("_", "-").replace(" ", "").lower()
|
||||
|
||||
|
||||
def _xls_total(data: bytes) -> float | None:
|
||||
"""Итог сметы из .xls-распечатки: последняя строка «Итого по смете»,
|
||||
последняя числовая ячейка (текущие цены, округлено до рубля)."""
|
||||
if xlrd is None:
|
||||
return None
|
||||
try:
|
||||
wb = xlrd.open_workbook(file_contents=data, formatting_info=False)
|
||||
except Exception:
|
||||
return None
|
||||
best = None
|
||||
for sh_i in range(wb.nsheets):
|
||||
sh = wb.sheet_by_index(sh_i)
|
||||
for r in range(sh.nrows):
|
||||
row = sh.row_values(r)
|
||||
if any(isinstance(v, str) and _TOTAL_ROW_RE.search(v) for v in row):
|
||||
nums = [v for v in row if isinstance(v, float) and v > 0]
|
||||
if nums:
|
||||
best = nums[-1]
|
||||
return best
|
||||
|
||||
|
||||
def _leak_fields(est: dict):
|
||||
yield est["name"]
|
||||
yield from est["comments"]
|
||||
for p in est["positions"]:
|
||||
yield p["name"]
|
||||
yield p["justification"]
|
||||
yield p["section"]
|
||||
for c in p["coefficients"]:
|
||||
yield c["reason"]
|
||||
for lst in p["resources"].values():
|
||||
for r in lst:
|
||||
yield r["name"]
|
||||
|
||||
|
||||
def _is_material(p: dict) -> bool:
|
||||
b = p["base_costs"]
|
||||
return b["labor"] == 0 and b["machines"] == 0 and b["materials"] > 0
|
||||
|
||||
|
||||
class Builder:
|
||||
def __init__(self):
|
||||
self.meta = Counter(files_seen=0, parsed_ok=0, parse_errors=0,
|
||||
duplicates=0, staged_files=0, positions_total=0,
|
||||
xls_pairs_found=0, xls_verified=0,
|
||||
price_outliers_quarantined=0)
|
||||
self.quarantine_counts = Counter()
|
||||
self.quarantine_log: list[dict] = [] # операционный, НЕ для корпуса
|
||||
self.seen_sha1: set[str] = set()
|
||||
self.seen_est: set[tuple] = set()
|
||||
# code -> список вхождений (сначала копим, цену фильтруем по медиане)
|
||||
self.occ: dict[str, list[dict]] = defaultdict(list)
|
||||
self.recalc: dict[tuple, dict] = {}
|
||||
|
||||
# ---------- приём одного .arp ----------
|
||||
def feed(self, raw: bytes, display: str, xls_lookup=None) -> None:
|
||||
self.meta["files_seen"] += 1
|
||||
sha = hashlib.sha1(raw).hexdigest()
|
||||
if sha in self.seen_sha1:
|
||||
self.meta["duplicates"] += 1
|
||||
return
|
||||
self.seen_sha1.add(sha)
|
||||
|
||||
est = parse_arp_text(raw.decode("cp866", "replace"), path=display)
|
||||
if "error" in est or not est["positions_count"]:
|
||||
self.meta["parse_errors"] += 1
|
||||
self._quar(display, "parse_error_or_empty", "")
|
||||
return
|
||||
self.meta["parsed_ok"] += 1
|
||||
|
||||
key = (est["code"], round(est["total"], 2))
|
||||
if key in self.seen_est:
|
||||
self.meta["duplicates"] += 1
|
||||
return
|
||||
self.seen_est.add(key)
|
||||
|
||||
if est["norm_base"] != "ОСНБЖ":
|
||||
self._quar(display, "unknown_base", est["norm_base"])
|
||||
return
|
||||
if not est["total_check_ok"]:
|
||||
self._quar(display, "total_formula_mismatch",
|
||||
f"шапка={est['total']} формула={est['total_computed']}")
|
||||
return
|
||||
|
||||
xls_verified = False
|
||||
if xls_lookup is not None:
|
||||
# кандидатов может быть несколько (тот же стем в ИЗМ/КОРР/ЛС —
|
||||
# разные ревизии); ground truth = хоть одна распечатка бьётся
|
||||
xts = xls_lookup(display)
|
||||
if xts:
|
||||
self.meta["xls_pairs_found"] += 1
|
||||
tol = max(2.0, est["total"] * 5e-4)
|
||||
if any(abs(est["total"] - x) <= tol for x in xts):
|
||||
xls_verified = True
|
||||
self.meta["xls_verified"] += 1
|
||||
else:
|
||||
nearest = min(xts, key=lambda x: abs(est["total"] - x))
|
||||
self._quar(display, "xls_total_mismatch",
|
||||
f"arp={est['total']} xls={nearest}")
|
||||
return
|
||||
|
||||
leaks = [t for t in _leak_fields(est) if t and has_identifier_leak(t)]
|
||||
if leaks:
|
||||
self._quar(display, "leak", leaks[0][:60])
|
||||
return
|
||||
|
||||
self._stage(est, xls_verified)
|
||||
|
||||
def _quar(self, display: str, reason: str, detail: str) -> None:
|
||||
self.quarantine_counts[reason] += 1
|
||||
self.quarantine_log.append({"file": display, "reason": reason, "detail": detail})
|
||||
|
||||
# ---------- стейджинг ----------
|
||||
def _stage(self, est: dict, xls_verified: bool) -> None:
|
||||
self.meta["staged_files"] += 1
|
||||
rk = (est["recalc"]["doc"], est["recalc"]["date"]) if est["recalc"] else ("", "")
|
||||
rec = self.recalc.setdefault(rk, {
|
||||
"doc": rk[0], "date": rk[1], "files": 0,
|
||||
"reason_sample": est["recalc"]["reason"] if est["recalc"] else "",
|
||||
"indices": defaultdict(Counter)})
|
||||
rec["files"] += 1
|
||||
for kind, vals in est["kizp"]["values"].items():
|
||||
for v, n in vals.items():
|
||||
rec["indices"][kind][v] += n
|
||||
|
||||
# файловые обоснования коэффициентов («коэффициент на … охранной зоне
|
||||
# ВЛ — 1,2 ОПДС-2821…») — единственный источник reason для большинства
|
||||
# 25-записей (их поле f6 обычно пусто)
|
||||
coef_notes = [c for c in est["comments"] if "коэффициент" in c.lower()]
|
||||
|
||||
for p in est["positions"]:
|
||||
if not p["name"] and not p["code"]:
|
||||
continue
|
||||
self.meta["positions_total"] += 1
|
||||
key = p["code"] if p["code"] else f"~{p['name'].lower()}"
|
||||
self.occ[key].append({
|
||||
"p": p, "est_code": est["code"],
|
||||
"price_level": est["price_level"],
|
||||
"kizp_main": est["kizp"]["main"],
|
||||
"coef_notes": coef_notes,
|
||||
"xls_verified": xls_verified,
|
||||
})
|
||||
|
||||
# ---------- финализация ----------
|
||||
def finalize(self) -> dict:
|
||||
items = []
|
||||
for key, occs in self.occ.items():
|
||||
# гейт 5: цена вне 5× медианы по коду → вхождение в карантин
|
||||
costs = [o["p"]["unit_cost_cur"] for o in occs if o["p"]["unit_cost_cur"] > 0]
|
||||
if len(costs) >= 3:
|
||||
med = statistics.median(costs)
|
||||
kept = []
|
||||
for o in occs:
|
||||
c = o["p"]["unit_cost_cur"]
|
||||
if c > 0 and med > 0 and (c > 5 * med or c < med / 5):
|
||||
self.meta["price_outliers_quarantined"] += 1
|
||||
self.quarantine_counts["price_outlier"] += 1
|
||||
self.quarantine_log.append({
|
||||
"file": "", "reason": "price_outlier",
|
||||
"detail": f"{key}: {c} vs медиана {round(med, 2)}"})
|
||||
else:
|
||||
kept.append(o)
|
||||
occs = kept
|
||||
if not occs:
|
||||
continue
|
||||
items.append(self._item(key, occs))
|
||||
items.sort(key=lambda x: x["freq"], reverse=True)
|
||||
|
||||
recalc_index = []
|
||||
for rec in self.recalc.values():
|
||||
recalc_index.append({
|
||||
"doc": rec["doc"], "date": rec["date"], "files": rec["files"],
|
||||
"reason_sample": rec["reason_sample"],
|
||||
"indices": {k: dict(v.most_common(8)) for k, v in rec["indices"].items()},
|
||||
})
|
||||
recalc_index.sort(key=lambda x: x["files"], reverse=True)
|
||||
|
||||
return {
|
||||
"meta": {
|
||||
**dict(self.meta),
|
||||
"quarantined": dict(self.quarantine_counts),
|
||||
"unique_items": len(items),
|
||||
"norm_base": "ОСНБЖ",
|
||||
"generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
||||
},
|
||||
"items": items,
|
||||
"recalc_index": recalc_index,
|
||||
}
|
||||
|
||||
def _item(self, key: str, occs: list[dict]) -> dict:
|
||||
names, units, plevels = Counter(), Counter(), Counter()
|
||||
qtys, coef_counter, notes = [], Counter(), Counter()
|
||||
coef_with = coef_without = 0
|
||||
best = None
|
||||
best_res = -1
|
||||
for o in occs:
|
||||
p = o["p"]
|
||||
if p["name"]:
|
||||
names[p["name"]] += 1
|
||||
if p["unit"]:
|
||||
units[p["unit"]] += 1
|
||||
if o["price_level"]:
|
||||
plevels[o["price_level"]] += 1
|
||||
if p["quantity"] > 0:
|
||||
qtys.append(p["quantity"])
|
||||
applied = [c for c in p["coefficients"] if c["group"] != "index"]
|
||||
if applied:
|
||||
coef_with += 1
|
||||
coef_counter.update((c["kind"], c["target"], str(c["value"]), c["reason"])
|
||||
for c in applied)
|
||||
notes.update(o["coef_notes"])
|
||||
else:
|
||||
coef_without += 1
|
||||
rn = sum(len(v) for v in p["resources"].values())
|
||||
if rn > best_res:
|
||||
best_res, best = rn, o
|
||||
bp = best["p"]
|
||||
qstat = {"min": round(min(qtys), 4), "median": round(statistics.median(qtys), 4),
|
||||
"max": round(max(qtys), 4)} if qtys else {}
|
||||
m = re.search(r"\b(ОЕРЖ\w*|ОСОЦЖ\w*|ОСНБЖ\w*|ГЭСН\w*|ФЕР\w*|ТЕР\w*)",
|
||||
bp["justification"])
|
||||
return {
|
||||
"code": bp["code"],
|
||||
"name": names.most_common(1)[0][0] if names else "",
|
||||
"unit": units.most_common(1)[0][0] if units else "",
|
||||
"kind": "material" if _is_material(bp) else "cost",
|
||||
"norm_base": "ОСНБЖ",
|
||||
"norm_doc": m.group(1) if m else "",
|
||||
"price_level": plevels.most_common(1)[0][0] if plevels else "",
|
||||
"freq": len(occs),
|
||||
"qty": qstat,
|
||||
"quantity_is_verified": True, # объём=f26 подтверждён формулой итога
|
||||
"base_costs": bp["base_costs"],
|
||||
"cur_costs": bp["cur_costs"],
|
||||
"unit_cost_cur": bp["unit_cost_cur"],
|
||||
"labor_ch": bp["labor_ch"], "machinist_ch": bp["machinist_ch"],
|
||||
"kizp": best["kizp_main"],
|
||||
"coef_applications": self._coef_apps(coef_counter, notes, coef_with,
|
||||
coef_without) if coef_with else None,
|
||||
"resources": {k: v[:MAX_RES] for k, v in bp["resources"].items()},
|
||||
"xls_verified": any(o["xls_verified"] for o in occs),
|
||||
"examples": [{"est": o["est_code"], "qty": o["p"]["quantity"],
|
||||
"unit": o["p"]["unit"]} for o in occs[:3]],
|
||||
}
|
||||
|
||||
|
||||
@staticmethod
|
||||
def _coef_apps(coef_counter: Counter, notes: Counter,
|
||||
coef_with: int, coef_without: int) -> dict:
|
||||
top = coef_counter.most_common(8)
|
||||
# редкий вариант с обоснованием (Кзтр по ОЕРЖ) не пробивает top-8 сквозь
|
||||
# ~9 стандартных коэф-записей позиции — гарантируем ему место
|
||||
if not any(key[3] for key, _ in top):
|
||||
top += [kv for kv in coef_counter.most_common() if kv[0][3]][:2]
|
||||
return {
|
||||
"with": coef_with, "without": coef_without,
|
||||
"coefs": [{"kind": k, "target": t, "value": v, "reason": r, "freq": n}
|
||||
for (k, t, v, r), n in top],
|
||||
"notes": [t for t, _ in notes.most_common(3)],
|
||||
}
|
||||
|
||||
|
||||
def _feed_zip(b: Builder, zpath: Path) -> None:
|
||||
with zipfile.ZipFile(zpath) as z:
|
||||
names = z.namelist()
|
||||
xls_by_stem: dict[str, list[str]] = defaultdict(list)
|
||||
for n in names:
|
||||
if n.lower().endswith(".xls"):
|
||||
xls_by_stem[_norm_stem(n, "xls")].append(n)
|
||||
xls_total_cache: dict[str, float | None] = {}
|
||||
|
||||
def lookup(member: str) -> list[float]:
|
||||
"""Итоги ВСЕХ парных .xls того же zip по нормализованному стему."""
|
||||
out = []
|
||||
for c in xls_by_stem.get(_norm_stem(member, "arps?"), []):
|
||||
if c not in xls_total_cache:
|
||||
xls_total_cache[c] = _xls_total(z.read(c))
|
||||
if xls_total_cache[c] is not None:
|
||||
out.append(xls_total_cache[c])
|
||||
return out
|
||||
|
||||
for n in names:
|
||||
if n.lower().endswith((".arp", ".arps")):
|
||||
b.feed(z.read(n), f"{zpath.name}::{_cp866_name(n)}",
|
||||
xls_lookup=lambda d, _n=n: lookup(_n))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("paths", nargs="+")
|
||||
ap.add_argument("--out", default="data/real_corpus/staging_arp.json")
|
||||
args = ap.parse_args()
|
||||
|
||||
b = Builder()
|
||||
for raw_path in args.paths:
|
||||
path = Path(raw_path)
|
||||
if path.is_dir():
|
||||
targets = sorted(list(path.rglob("*.arp")) + list(path.rglob("*.arps"))
|
||||
+ list(path.rglob("*.zip")))
|
||||
else:
|
||||
targets = [path]
|
||||
for t in targets:
|
||||
if t.suffix.lower() == ".zip":
|
||||
_feed_zip(b, t)
|
||||
else:
|
||||
b.feed(t.read_bytes(), str(t))
|
||||
|
||||
result = b.finalize()
|
||||
|
||||
# финальная канарейка: 0 утечек в том, что уходит в staging-файл
|
||||
kept = [it for it in result["items"] if not _struct_leaks(it)]
|
||||
if len(kept) != len(result["items"]):
|
||||
result["meta"]["quarantined"]["leak_final_pass"] = \
|
||||
len(result["items"]) - len(kept)
|
||||
result["items"] = kept
|
||||
result["meta"]["unique_items"] = len(kept)
|
||||
result["meta"]["leaks_in_staging"] = sum(
|
||||
1 for it in result["items"] + result["recalc_index"] if _struct_leaks(it))
|
||||
|
||||
out = Path(args.out)
|
||||
if not out.is_absolute():
|
||||
out = Path(__file__).resolve().parent.parent / out
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8")
|
||||
# карантин-лог с именами файлов — операционный артефакт, НЕ корпус
|
||||
(out.parent / (out.stem + "_quarantine.json")).write_text(
|
||||
json.dumps({"NOT_FOR_CORPUS": "имена файлов могут содержать идентификаторы",
|
||||
"entries": b.quarantine_log}, ensure_ascii=False, indent=1),
|
||||
encoding="utf-8")
|
||||
print(json.dumps(result["meta"], ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,122 @@
|
||||
"""Свести три staging'а (.gge #2, .gsfx #3, .arp #4) в ОТДЕЛЬНЫЙ ext-индекс расширения
|
||||
корпуса — data/real_corpus/estimates_ext_index.json. Живой estimates_index.json НЕ трогаем
|
||||
(нулевой риск отравления ВСЖМ). find_* грузит оба и объединяет.
|
||||
|
||||
Каждая запись несёт norm_base + price_level (анти-отравление: модель видит уровень цен).
|
||||
Дедуп по (code, norm_base): ОСНБЖ-2001 никогда не сливается с ГЭСН-2025.
|
||||
Запуск: python3 scripts/build_ext_index.py <dir_with_staging_json> [out.json]
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from corpus_anon import has_identifier_leak
|
||||
|
||||
# Общая схема item, совместимая с find_in_real_estimates (недостающее → None/пусто).
|
||||
_ITEM_FIELDS = ["code", "name", "unit", "prefix", "kind", "freq", "norm_sets", "regions",
|
||||
"qty", "comment", "unit_cost_cur", "cost_structure", "labor_ch",
|
||||
"machinist_ch", "price_base", "price_cur", "overhead", "profit",
|
||||
"coef_applications", "resources", "examples", "norm_base", "price_level",
|
||||
# глубокие поля (бонус, агент-путь может использовать)
|
||||
"works_list", "coefficients", "kizp", "norm_doc", "xls_verified"]
|
||||
|
||||
|
||||
def _norm_base(rec: dict, default: str) -> str:
|
||||
nb = rec.get("norm_base")
|
||||
if nb:
|
||||
return nb
|
||||
nbs = rec.get("norm_bases")
|
||||
if isinstance(nbs, list) and nbs:
|
||||
return nbs[0]
|
||||
return default
|
||||
|
||||
|
||||
def _is_material(rec: dict) -> bool:
|
||||
return (rec.get("kind") or "").lower() in ("material", "mat", "материал")
|
||||
|
||||
|
||||
def _norm_item(rec: dict, default_nb: str) -> dict:
|
||||
out = {k: rec.get(k) for k in _ITEM_FIELDS}
|
||||
out["name"] = rec.get("name") or ""
|
||||
out["code"] = rec.get("code") or ""
|
||||
out["freq"] = rec.get("freq") or 1
|
||||
out["norm_base"] = _norm_base(rec, default_nb)
|
||||
out["regions"] = rec.get("regions") or []
|
||||
return out
|
||||
|
||||
|
||||
def _key(it: dict) -> tuple:
|
||||
code = it["code"] or ("~" + it["name"].lower())
|
||||
return (code, it["norm_base"])
|
||||
|
||||
|
||||
def _record_lists(d: dict):
|
||||
"""Вернуть (estimates, materials, ka) из одного staging любой схемы."""
|
||||
est, mat, ka = [], [], []
|
||||
for rk in ("records", "items"):
|
||||
for rec in d.get(rk, []) or []:
|
||||
(mat if _is_material(rec) else est).append(rec)
|
||||
mat += d.get("materials", []) or []
|
||||
ka += d.get("ka_records", []) or []
|
||||
return est, mat, ka
|
||||
|
||||
|
||||
def build(src_dir: str, out_path: str) -> dict:
|
||||
base = Path(src_dir)
|
||||
est_by_key: dict = {}
|
||||
materials: list = []
|
||||
ka_items: list = []
|
||||
leaked = 0
|
||||
stagings = {"staging_gge.json": "ГЭСН", "staging_gsfx.json": "ФСНБ-2022", "staging_arp.json": "ОСНБЖ"}
|
||||
for fname, default_nb in stagings.items():
|
||||
p = base / fname
|
||||
if not p.exists():
|
||||
continue
|
||||
d = json.loads(p.read_text(encoding="utf-8"))
|
||||
est, mat, ka = _record_lists(d)
|
||||
for rec in est:
|
||||
it = _norm_item(rec, default_nb)
|
||||
if not it["name"]:
|
||||
continue
|
||||
if has_identifier_leak(it["name"]) or has_identifier_leak(it.get("comment") or ""):
|
||||
leaked += 1
|
||||
continue
|
||||
k = _key(it)
|
||||
prev = est_by_key.get(k)
|
||||
if prev is None or it["freq"] > prev["freq"]:
|
||||
if prev:
|
||||
it["freq"] += prev["freq"]
|
||||
est_by_key[k] = it
|
||||
else:
|
||||
prev["freq"] += it["freq"]
|
||||
for m in mat:
|
||||
name = m.get("name") or ""
|
||||
if not name or has_identifier_leak(name):
|
||||
leaked += 1 if name else 0
|
||||
continue
|
||||
materials.append({"name": name, "code": m.get("code", ""), "unit": m.get("unit", ""),
|
||||
"price_cur": m.get("price_cur") or m.get("unit_cost_cur"),
|
||||
"regions": m.get("regions") or [], "freq": m.get("freq") or 1,
|
||||
"norm_base": _norm_base(m, default_nb), "price_level": m.get("price_level")})
|
||||
for rec in ka:
|
||||
name = rec.get("name") or ""
|
||||
if not name or has_identifier_leak(name):
|
||||
leaked += 1 if name else 0
|
||||
continue
|
||||
ka_items.append(rec)
|
||||
|
||||
items = list(est_by_key.values())
|
||||
items.sort(key=lambda x: x["freq"], reverse=True)
|
||||
out = {"items": items, "materials": materials, "ka": ka_items,
|
||||
"summary": {"estimates": len(items), "materials": len(materials),
|
||||
"ka": len(ka_items), "leaked_skipped": leaked}}
|
||||
Path(out_path).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(out_path).write_text(json.dumps(out, ensure_ascii=False), encoding="utf-8")
|
||||
return out["summary"]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
src = sys.argv[1] if len(sys.argv) > 1 else "."
|
||||
out = sys.argv[2] if len(sys.argv) > 2 else "data/real_corpus/estimates_ext_index.json"
|
||||
print(json.dumps(build(src, out), ensure_ascii=False))
|
||||
@@ -0,0 +1,238 @@
|
||||
"""build_gsfx_staging — STAGING-индекс расценок из .gsfx (ГРАНД-Смета).
|
||||
|
||||
Проходит все .gsfx под заданным каталогом → gsfx_deep.parse_gsfx_full
|
||||
(обезличивание на извлечении) → агрегация по коду расценки (как в
|
||||
build_real_corpus: состав из самого полного вхождения, freq/qty/примеры по
|
||||
всем) → канарейка has_identifier_leak по КАЖДОМУ текстовому полю записи:
|
||||
утечка → запись целиком в карантин-файл, не в staging (fail-loud).
|
||||
|
||||
Пишет ТОЛЬКО staging_gsfx.json (+ staging_gsfx_quarantine.json при утечках).
|
||||
Живой индекс (estimates_index.json) НЕ трогает.
|
||||
|
||||
Запуск: python3 scripts/build_gsfx_staging.py "<каталог с .gsfx>" \
|
||||
[--out data/real_corpus]
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import statistics
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from corpus_anon import has_identifier_leak # noqa: E402
|
||||
from gsfx_deep import parse_gsfx_full # noqa: E402
|
||||
|
||||
MAX_RES = 30 # лимит ресурсов каждого типа в карточке
|
||||
RATIO_BAND = (0.5, 1.5) # мягкая сверка сумм: за пределами — в meta как outlier
|
||||
|
||||
|
||||
def _texts(obj):
|
||||
"""Все строковые значения записи — для пополевой проверки утечек
|
||||
(has_identifier_leak по целому JSON-дампу нельзя: кавычки JSON ложно
|
||||
срабатывают на правило «имя в кавычках»)."""
|
||||
if isinstance(obj, str):
|
||||
yield obj
|
||||
elif isinstance(obj, dict):
|
||||
for v in obj.values():
|
||||
yield from _texts(v)
|
||||
elif isinstance(obj, (list, tuple)):
|
||||
for v in obj:
|
||||
yield from _texts(v)
|
||||
|
||||
|
||||
def _leaks(record: dict) -> list[str]:
|
||||
return [t for t in _texts(record) if has_identifier_leak(t)]
|
||||
|
||||
|
||||
def _cap_resources(res: dict) -> dict:
|
||||
return {k: v[:MAX_RES] for k, v in res.items()}
|
||||
|
||||
|
||||
def build(root: Path, out_dir: Path) -> dict:
|
||||
agg: dict[str, dict] = {}
|
||||
mat_agg: dict[str, dict] = {}
|
||||
n_files = n_err = n_pos = n_mat = n_other = 0
|
||||
ratios: list[float] = []
|
||||
ratio_outliers: list[dict] = []
|
||||
|
||||
for f in sorted(root.rglob("*.gsfx")):
|
||||
data = parse_gsfx_full(f)
|
||||
n_files += 1
|
||||
if "error" in data:
|
||||
n_err += 1
|
||||
continue
|
||||
est_code = data.get("code", "")
|
||||
norm_base = data.get("norm_base", "")
|
||||
region = data.get("region", "")
|
||||
price_level = data.get("price_level", {})
|
||||
tc = data.get("totals_check") or {}
|
||||
# сверка осмысленна только для смет с расценками: у ОС/ССР все строки
|
||||
# сводные (пропущены) → computed=0, это не расхождение
|
||||
if tc.get("ratio") is not None and data["positions"]:
|
||||
ratios.append(tc["ratio"])
|
||||
if not (RATIO_BAND[0] <= tc["ratio"] <= RATIO_BAND[1]):
|
||||
ratio_outliers.append({"est": est_code, "ratio": tc["ratio"]})
|
||||
|
||||
for p in data["positions"]:
|
||||
if not p["name"]:
|
||||
continue
|
||||
if p["kind"] == "work":
|
||||
n_pos += 1
|
||||
key = p["code"]
|
||||
rec = agg.get(key)
|
||||
if rec is None:
|
||||
rec = agg[key] = {
|
||||
"code": p["code"],
|
||||
"names": defaultdict(int), "units": defaultdict(int),
|
||||
"norm_bases": defaultdict(int), "regions": defaultdict(int),
|
||||
"qtys": [], "examples": [], "freq": 0, "_best_res": -1,
|
||||
"unit_cost_cur": None, "labor_ch": 0.0, "machinist_ch": 0.0,
|
||||
"price_level": {}, "price_source": "",
|
||||
"overhead": None, "profit": None,
|
||||
"resources": {"workers": [], "machines": [], "materials": []},
|
||||
"works_list": [], "coefficients": [],
|
||||
}
|
||||
rec["names"][p["name"]] += 1
|
||||
if p["unit"]:
|
||||
rec["units"][p["unit"]] += 1
|
||||
if norm_base:
|
||||
rec["norm_bases"][norm_base] += 1
|
||||
if region:
|
||||
rec["regions"][region] += 1
|
||||
if p["quantity"] > 0:
|
||||
rec["qtys"].append(p["quantity"])
|
||||
rec["freq"] += 1
|
||||
if len(rec["examples"]) < 3 and est_code:
|
||||
rec["examples"].append(
|
||||
{"est": est_code, "qty": p["quantity"], "unit": p["unit"]})
|
||||
res = p["resources"]
|
||||
res_n = (len(res["workers"]) + len(res["machines"])
|
||||
+ len(res["materials"]) + len(p["works_list"]))
|
||||
if res_n > rec["_best_res"]:
|
||||
rec["_best_res"] = res_n
|
||||
rec["unit_cost_cur"] = p["unit_cost_cur"]
|
||||
rec["labor_ch"] = p["labor_ch"]
|
||||
rec["machinist_ch"] = p["machinist_ch"]
|
||||
rec["price_level"] = price_level
|
||||
rec["price_source"] = p["price_source"]
|
||||
rec["overhead"] = p["overhead"]
|
||||
rec["profit"] = p["profit"]
|
||||
rec["resources"] = _cap_resources(res)
|
||||
rec["works_list"] = p["works_list"]
|
||||
rec["coefficients"] = p["coefficients"]
|
||||
elif p["kind"] == "material":
|
||||
n_mat += 1
|
||||
key = p["code"] or p["name"].lower()
|
||||
mr = mat_agg.get(key)
|
||||
if mr is None:
|
||||
mr = mat_agg[key] = {
|
||||
"code": p["code"], "name": p["name"], "unit": p["unit"],
|
||||
"prices": [], "freq": 0, "regions": defaultdict(int),
|
||||
"price_level": price_level,
|
||||
# DBComment (приказ) либо ССЦ-каталог из PriceCurr@Comment
|
||||
"price_source": p["price_source"] or p["price_comment"],
|
||||
}
|
||||
if p["unit_cost_cur"]:
|
||||
mr["prices"].append(p["unit_cost_cur"])
|
||||
if region:
|
||||
mr["regions"][region] += 1
|
||||
mr["freq"] += 1
|
||||
else:
|
||||
n_other += 1
|
||||
|
||||
items = []
|
||||
for rec in agg.values():
|
||||
qtys = rec["qtys"]
|
||||
qstat = {"min": round(min(qtys), 3),
|
||||
"median": round(statistics.median(qtys), 3),
|
||||
"max": round(max(qtys), 3)} if qtys else {}
|
||||
items.append({
|
||||
"code": rec["code"],
|
||||
"name": max(rec["names"].items(), key=lambda kv: kv[1])[0],
|
||||
"unit": max(rec["units"].items(), key=lambda kv: kv[1])[0] if rec["units"] else "",
|
||||
"kind": "work",
|
||||
"freq": rec["freq"],
|
||||
"qty": qstat,
|
||||
"norm_bases": sorted(rec["norm_bases"], key=rec["norm_bases"].get, reverse=True),
|
||||
"regions": sorted(rec["regions"], key=rec["regions"].get, reverse=True)[:5],
|
||||
"price_level": rec["price_level"],
|
||||
"price_source": rec["price_source"],
|
||||
"unit_cost_cur": rec["unit_cost_cur"],
|
||||
"labor_ch": rec["labor_ch"], "machinist_ch": rec["machinist_ch"],
|
||||
"overhead": rec["overhead"], "profit": rec["profit"],
|
||||
"resources": rec["resources"],
|
||||
"works_list": rec["works_list"],
|
||||
"coefficients": rec["coefficients"],
|
||||
"examples": rec["examples"],
|
||||
})
|
||||
items.sort(key=lambda x: x["freq"], reverse=True)
|
||||
|
||||
materials = []
|
||||
for mr in mat_agg.values():
|
||||
pr = mr["prices"]
|
||||
materials.append({
|
||||
"name": mr["name"], "code": mr["code"], "unit": mr["unit"],
|
||||
"kind": "material", "freq": mr["freq"],
|
||||
"price_cur": round(statistics.median(pr), 2) if pr else None,
|
||||
"price_level": mr["price_level"],
|
||||
"price_source": mr["price_source"],
|
||||
"regions": sorted(mr["regions"], key=mr["regions"].get, reverse=True)[:3],
|
||||
})
|
||||
materials.sort(key=lambda x: x["freq"], reverse=True)
|
||||
|
||||
# Канарейка: запись с утечкой — в карантин, не в staging (fail-loud).
|
||||
quarantine = []
|
||||
clean_items, clean_materials = [], []
|
||||
for lst, clean in ((items, clean_items), (materials, clean_materials)):
|
||||
for r in lst:
|
||||
bad = _leaks(r)
|
||||
if bad:
|
||||
quarantine.append({"code": r.get("code", ""), "kind": r["kind"],
|
||||
"leaked": bad[:5]})
|
||||
else:
|
||||
clean.append(r)
|
||||
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
meta = {
|
||||
"source": "gsfx",
|
||||
"files_parsed": n_files, "parse_errors": n_err,
|
||||
"work_positions": n_pos, "material_positions": n_mat,
|
||||
"other_positions_skipped": n_other,
|
||||
"unique_items": len(clean_items), "unique_materials": len(clean_materials),
|
||||
"quarantined": len(quarantine),
|
||||
"totals_check": {
|
||||
"files_checked": len(ratios),
|
||||
"ratio_median": round(statistics.median(ratios), 4) if ratios else None,
|
||||
"outliers": len(ratio_outliers),
|
||||
},
|
||||
}
|
||||
(out_dir / "staging_gsfx.json").write_text(
|
||||
json.dumps({"meta": meta, "items": clean_items, "materials": clean_materials},
|
||||
ensure_ascii=False), encoding="utf-8")
|
||||
if quarantine:
|
||||
(out_dir / "staging_gsfx_quarantine.json").write_text(
|
||||
json.dumps(quarantine, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
meta["ratio_outliers_sample"] = ratio_outliers[:10]
|
||||
return meta
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("base", help="каталог, под которым лежат .gsfx (rglob)")
|
||||
ap.add_argument("--out", default="data/real_corpus")
|
||||
args = ap.parse_args()
|
||||
root = Path(args.base)
|
||||
if not root.exists():
|
||||
print(f"Каталог не найден: {root}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
out = Path(args.out)
|
||||
if not out.is_absolute():
|
||||
out = Path(__file__).resolve().parent.parent / out
|
||||
print(json.dumps(build(root, out), ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,493 @@
|
||||
"""merge_gge — staging-расширение анти-фабрикационного корпуса из новых .gge.
|
||||
|
||||
Дорожная карта #2: РИМ-сметы (Дальний Восток, цены 2025) → staging_gge.json.
|
||||
Живой estimates_index.json НЕ модифицируется (guard в merge) — merge в живой
|
||||
индекс делается руками после ревью staging.
|
||||
|
||||
Пайплайн: рекурсивный обход каталога, включая zip-в-zip (СМ.КА кладёт
|
||||
MarketAnalysis-3_01.gge во вложенные zip) → parse_estimate_full / parse_ka →
|
||||
corpus_anon.scrub КАЖДОГО свободнотекстового поля → три гейта (fail-loud):
|
||||
1. БИМ (schema *BaseIndexMethod) ИЛИ нет PriceLevelCur: unit_cost в базисных
|
||||
ценах (2001) отравил бы корпус → карантин файла целиком;
|
||||
2. канарейка has_identifier_leak по ВСЕМ строковым полям записи → карантин;
|
||||
3. unit_cost_cur вне 5× значения этого кода в ЖИВОМ индексе → карантин.
|
||||
|
||||
Регион: RegionName из .gge — класс-уровень (область/край/республика; поле
|
||||
region_class из corpus_anon.ALLOWED_FIELDS) — сохраняется по allow-list-паттерну
|
||||
и НЕ прогоняется через scrub: deny-лист режет ДВ-топонимы («Хабаровск…»), а
|
||||
класс-регион — ценность корпуса, не идентификатор объекта. Не-класс регион
|
||||
(город/станция) через allow-list не проходит и скрабится как свободный текст.
|
||||
Города в офферах КА сохраняются — как в живом ka_index (README корпуса).
|
||||
|
||||
Формат записи = 1:1 items из build_real_corpus + norm_base/price_level,
|
||||
чтобы merge после ревью был тривиален.
|
||||
|
||||
Запуск: python3 scripts/merge_gge.py <src> [--live estimates_index.json] [--out staging_gge.json]
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import statistics
|
||||
import sys
|
||||
import tempfile
|
||||
import zipfile
|
||||
from collections import Counter, defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
_ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(_ROOT))
|
||||
from corpus_anon import has_identifier_leak, scrub # noqa: E402
|
||||
from gge_deep import parse_estimate_full, parse_ka # noqa: E402
|
||||
from gge_tools import _decode_zip_name # noqa: E402
|
||||
|
||||
MAX_RES = 30 # как в build_real_corpus
|
||||
MAX_OFFERS = 8 # как в build_ka_index
|
||||
PRICE_GATE = 5.0 # новая цена вне [live/5, live*5] → карантин
|
||||
MAX_ZIP_DEPTH = 4
|
||||
|
||||
# Класс-уровень региона (allow-list): область/край/республика/АО/города фед. значения.
|
||||
_REGION_CLASS_RE = re.compile(
|
||||
r"^(?:[А-ЯЁ][а-яё-]+(?:\s+[а-яё-]+)*\s+(?:область|край)"
|
||||
r"|Республика\s+[А-ЯЁ][\w ()-]*"
|
||||
r"|[А-ЯЁ][а-яё-]+\s+Республика(?:\s+[А-ЯЁ][\w ()-]*)?"
|
||||
r"|[А-ЯЁ][\w-]+(?:\s+[А-ЯЁа-яё-]+)*\s+автономн\w+\s+округ(?:\s*[—–-]\s*[\w-]+)?"
|
||||
r"|Москва|Санкт-Петербург|Севастополь|Байконур)$")
|
||||
|
||||
# Ключи-регионы: класс-уровень (сметы) либо города офферов КА как в живом
|
||||
# ka_index — из канарейки исключены, валидируются отдельно (_region_class).
|
||||
_REGION_KEYS = {"region", "regions"}
|
||||
|
||||
|
||||
def _region_class(raw: str) -> str:
|
||||
"""Регион класс-уровня — как есть; иначе это свободный текст → scrub."""
|
||||
raw = (raw or "").strip()
|
||||
if not raw:
|
||||
return ""
|
||||
return raw if _REGION_CLASS_RE.match(raw) else scrub(raw)
|
||||
|
||||
|
||||
def collect_leaks(obj, _key: str | None = None) -> list[str]:
|
||||
"""Строки с остаточной утечкой идентификатора по всем вложенным полям
|
||||
(кроме регион-ключей). Гейт пайплайна И верификация готового staging."""
|
||||
if _key in _REGION_KEYS:
|
||||
return []
|
||||
if isinstance(obj, str):
|
||||
return [obj] if has_identifier_leak(obj) else []
|
||||
if isinstance(obj, dict):
|
||||
return [x for k, v in obj.items() for x in collect_leaks(v, k)]
|
||||
if isinstance(obj, (list, tuple)):
|
||||
return [x for v in obj for x in collect_leaks(v, _key)]
|
||||
return []
|
||||
|
||||
|
||||
# ── обход: .gge с ФС + из zip (вложенность до MAX_ZIP_DEPTH) ────────────────
|
||||
_extract_n = 0
|
||||
|
||||
|
||||
def _iter_zip(zf: zipfile.ZipFile, label: str, tmp: Path, depth: int):
|
||||
global _extract_n
|
||||
for info in zf.infolist():
|
||||
if info.is_dir():
|
||||
continue
|
||||
name = _decode_zip_name(info)
|
||||
low = name.lower()
|
||||
if low.endswith(".gge"):
|
||||
_extract_n += 1
|
||||
out = tmp / f"{_extract_n:05d}_{Path(name.replace(chr(92), '/')).name}"
|
||||
out.write_bytes(zf.read(info))
|
||||
yield out, f"{label}::{name}"
|
||||
elif low.endswith(".zip") and depth < MAX_ZIP_DEPTH:
|
||||
try:
|
||||
inner = zipfile.ZipFile(io.BytesIO(zf.read(info)))
|
||||
except zipfile.BadZipFile:
|
||||
continue
|
||||
yield from _iter_zip(inner, f"{label}::{name}", tmp, depth + 1)
|
||||
|
||||
|
||||
def _iter_gge(src: Path, tmp: Path):
|
||||
"""yield (путь на диске, origin-метка) для каждого найденного .gge.
|
||||
Топ-уровневые zip (сотни МБ) стримятся с диска, вложенные — из памяти."""
|
||||
for p in sorted(src.rglob("*")):
|
||||
suf = p.suffix.lower()
|
||||
if suf == ".gge":
|
||||
yield p, str(p.relative_to(src))
|
||||
elif suf == ".zip":
|
||||
try:
|
||||
zf = zipfile.ZipFile(p)
|
||||
except zipfile.BadZipFile:
|
||||
continue
|
||||
yield from _iter_zip(zf, p.name, tmp, 0)
|
||||
|
||||
|
||||
# ── классификаторы записи ───────────────────────────────────────────────────
|
||||
def _norm_base(prefix: str) -> str:
|
||||
"""ГЭСН/ФЕР по префиксу расценки. ТЕР — семейство ФЕР (базисная
|
||||
номенклатура). Пустой префикс в РИМ-смете = ГЭСН (методика 421/пр).
|
||||
Не-нормативные префиксы (ФССЦ/ФСБЦ/ФСЭМ — ценники ресурсов) — как есть."""
|
||||
p = (prefix or "").upper()
|
||||
if "ГЭСН" in p:
|
||||
return "ГЭСН"
|
||||
if p.startswith("ФЕР") or p.startswith("ТЕР"):
|
||||
return "ФЕР"
|
||||
return prefix if prefix else "ГЭСН"
|
||||
|
||||
|
||||
def _price_level(price_cur: str) -> str:
|
||||
"""Год текущего уровня цен файла («2025 Q3» → «2025»); нет → «базис»."""
|
||||
m = re.match(r"\s*(\d{4})", price_cur or "")
|
||||
return m.group(1) if m else "базис"
|
||||
|
||||
|
||||
def _norm_set(code: str) -> str:
|
||||
c = (code or "").upper()
|
||||
return "ОСР" if c.startswith("ОС") else "ЛСР"
|
||||
|
||||
|
||||
# ── извлечение (зеркалит build_real_corpus, но scrub = corpus_anon) ─────────
|
||||
def _scrub_resources(res: dict) -> dict:
|
||||
for lst in res.values():
|
||||
for r in lst:
|
||||
if r.get("name"):
|
||||
r["name"] = scrub(r["name"])
|
||||
r.pop("coef", None)
|
||||
if r.get("machinist"):
|
||||
r["machinist"].pop("coef", None)
|
||||
return {k: v[:MAX_RES] for k, v in res.items()}
|
||||
|
||||
|
||||
def _coef_apps(position: dict) -> list[tuple]:
|
||||
apps = []
|
||||
for c in position.get("coefficients", []):
|
||||
if c.get("value"):
|
||||
apps.append((scrub(c.get("reason", "")), c.get("target", ""), str(c["value"])))
|
||||
for lst in position["resources"].values():
|
||||
for r in lst:
|
||||
for src in (r.get("coef"), (r.get("machinist") or {}).get("coef")):
|
||||
if src and src.get("factors"):
|
||||
for target, factor in src["factors"].items():
|
||||
apps.append((scrub(src.get("reason", "")), target, str(factor)))
|
||||
return apps
|
||||
|
||||
|
||||
def _add_estimate(agg: dict, mat_agg: dict, data: dict, plevel: str,
|
||||
regions: Counter) -> int:
|
||||
"""Позиции/материалы одного РИМ-файла → агрегаторы. Возвращает n позиций."""
|
||||
region = _region_class(data.get("region", ""))
|
||||
if region:
|
||||
regions[region] += 1
|
||||
nset = _norm_set(data.get("code", ""))
|
||||
est_code = scrub(data.get("code", ""))
|
||||
n_pos = 0
|
||||
|
||||
for p in data["positions"]:
|
||||
name = scrub(p["name"])
|
||||
if not name:
|
||||
continue
|
||||
n_pos += 1
|
||||
code = p["code"]
|
||||
key = code if code else f"~{name.lower()}"
|
||||
rec = agg.get(key)
|
||||
if rec is None:
|
||||
rec = agg[key] = {
|
||||
"code": code, "names": defaultdict(int), "units": defaultdict(int),
|
||||
"prefix": p["prefix"], "kind": p.get("kind", "cost"),
|
||||
"norm_base": _norm_base(p["prefix"]), "price_level": plevel,
|
||||
"norm_sets": defaultdict(int),
|
||||
"regions": defaultdict(int), "qtys": [], "examples": [],
|
||||
"freq": 0, "_best_res": -1,
|
||||
"coef_with": 0, "coef_without": 0, "coef_counter": Counter(),
|
||||
"unit_cost_cur": 0.0, "labor_ch": 0.0, "machinist_ch": 0.0,
|
||||
"price_base": "", "price_cur": "", "comment": "",
|
||||
"cost_structure": None, "overhead": None, "profit": None,
|
||||
"resources": {"workers": [], "machines": [], "materials": []},
|
||||
}
|
||||
rec["names"][name] += 1
|
||||
if p["unit"]:
|
||||
rec["units"][p["unit"]] += 1
|
||||
rec["norm_sets"][nset] += 1
|
||||
if region:
|
||||
rec["regions"][region] += 1
|
||||
if p["quantity"] > 0:
|
||||
rec["qtys"].append(p["quantity"])
|
||||
rec["freq"] += 1
|
||||
if len(rec["examples"]) < 3 and est_code:
|
||||
rec["examples"].append({"est": est_code, "qty": p["quantity"], "unit": p["unit"]})
|
||||
apps = _coef_apps(p)
|
||||
if apps:
|
||||
rec["coef_with"] += 1
|
||||
rec["coef_counter"].update(apps)
|
||||
else:
|
||||
rec["coef_without"] += 1
|
||||
res = p["resources"]
|
||||
res_n = len(res["workers"]) + len(res["machines"]) + len(res["materials"])
|
||||
if res_n > rec["_best_res"]:
|
||||
rec["_best_res"] = res_n
|
||||
rec["unit_cost_cur"] = p["unit_cost_cur"]
|
||||
rec["labor_ch"] = p["labor_ch"]
|
||||
rec["machinist_ch"] = p["machinist_ch"]
|
||||
rec["price_base"] = data.get("price_base", "")
|
||||
rec["price_cur"] = data.get("price_cur", "")
|
||||
rec["price_level"] = plevel
|
||||
rec["comment"] = scrub(p.get("comment", ""))
|
||||
rec["cost_structure"] = p.get("cost_structure")
|
||||
rec["overhead"] = p["overhead"]
|
||||
rec["profit"] = p["profit"]
|
||||
rec["resources"] = _scrub_resources(res)
|
||||
|
||||
for m in data.get("direct_materials", []):
|
||||
name = scrub(m["name"])
|
||||
if not name:
|
||||
continue
|
||||
key = name.lower()
|
||||
mr = mat_agg.get(key)
|
||||
if mr is None:
|
||||
mr = mat_agg[key] = {"name": name, "code": m["code"], "unit": m["unit"],
|
||||
"prices": [], "freq": 0, "regions": defaultdict(int)}
|
||||
if m["price_cur"] > 0:
|
||||
mr["prices"].append(m["price_cur"])
|
||||
if region:
|
||||
mr["regions"][region] += 1
|
||||
mr["freq"] += 1
|
||||
return n_pos
|
||||
|
||||
|
||||
def _add_ka(ka_agg: dict, mats: list[dict], regions: set, periods: set) -> int:
|
||||
"""Материалы одного КА-файла → агрегатор (зеркалит build_ka_index)."""
|
||||
n = 0
|
||||
for mat in mats:
|
||||
name = scrub(mat["name"])
|
||||
if not name:
|
||||
continue
|
||||
n += 1
|
||||
rec = ka_agg.get(name.lower())
|
||||
if rec is None:
|
||||
rec = ka_agg[name.lower()] = {
|
||||
"name": name, "unit": mat["unit"], "type": mat["type"],
|
||||
"offers": [], "regions": defaultdict(int), "periods": defaultdict(int),
|
||||
}
|
||||
for o in mat["offers"]:
|
||||
o["delivery"] = scrub(o.get("delivery", ""))
|
||||
if o["region"]:
|
||||
rec["regions"][o["region"]] += 1
|
||||
regions.add(o["region"])
|
||||
if o["period"]:
|
||||
rec["periods"][o["period"]] += 1
|
||||
periods.add(o["period"])
|
||||
if len(rec["offers"]) < MAX_OFFERS:
|
||||
rec["offers"].append(o)
|
||||
return n
|
||||
|
||||
|
||||
# ── финализация записей ─────────────────────────────────────────────────────
|
||||
def _final_item(rec: dict) -> dict:
|
||||
qtys = rec["qtys"]
|
||||
qstat = {"min": round(min(qtys), 3), "median": round(statistics.median(qtys), 3),
|
||||
"max": round(max(qtys), 3)} if qtys else {}
|
||||
return {
|
||||
"code": rec["code"],
|
||||
"name": max(rec["names"].items(), key=lambda kv: kv[1])[0],
|
||||
"unit": max(rec["units"].items(), key=lambda kv: kv[1])[0] if rec["units"] else "",
|
||||
"prefix": rec["prefix"],
|
||||
"kind": rec["kind"],
|
||||
"norm_base": rec["norm_base"],
|
||||
"price_level": rec["price_level"],
|
||||
"freq": rec["freq"],
|
||||
"norm_sets": sorted(rec["norm_sets"], key=rec["norm_sets"].get, reverse=True),
|
||||
"regions": sorted(rec["regions"], key=rec["regions"].get, reverse=True)[:5],
|
||||
"qty": qstat,
|
||||
"comment": rec["comment"],
|
||||
"unit_cost_cur": rec["unit_cost_cur"],
|
||||
"cost_structure": rec["cost_structure"],
|
||||
"labor_ch": rec["labor_ch"], "machinist_ch": rec["machinist_ch"],
|
||||
"price_base": rec["price_base"], "price_cur": rec["price_cur"],
|
||||
"overhead": rec["overhead"], "profit": rec["profit"],
|
||||
"coef_applications": {
|
||||
"with": rec["coef_with"], "without": rec["coef_without"],
|
||||
"coefs": [{"reason": r, "target": t, "factor": f, "freq": c}
|
||||
for (r, t, f), c in rec["coef_counter"].most_common(6)],
|
||||
} if rec["coef_with"] else None,
|
||||
"resources": rec["resources"],
|
||||
"examples": rec["examples"],
|
||||
}
|
||||
|
||||
|
||||
def _load_live(path: Path) -> tuple[dict, dict, set, set]:
|
||||
live = json.loads(path.read_text(encoding="utf-8"))
|
||||
price_ref = {it["code"]: it["unit_cost_cur"] for it in live.get("items", [])
|
||||
if it.get("code") and it.get("unit_cost_cur")}
|
||||
mat_ref = {m["name"].lower(): m["price_cur"] for m in live.get("materials", [])
|
||||
if m.get("price_cur")}
|
||||
keys = {it["code"] or f"~{it['name'].lower()}" for it in live.get("items", [])}
|
||||
mat_names = {m["name"].lower() for m in live.get("materials", [])}
|
||||
return price_ref, mat_ref, keys, mat_names
|
||||
|
||||
|
||||
def _price_ok(ref: float | None, val: float) -> bool:
|
||||
if not ref or not val:
|
||||
return True # нет эталона / нет цены — гейтить не по чему
|
||||
return ref / PRICE_GATE <= val <= ref * PRICE_GATE
|
||||
|
||||
|
||||
def merge(src: Path, live_path: Path, out_path: Path) -> dict:
|
||||
if out_path.name == "estimates_index.json":
|
||||
raise ValueError("merge_gge пишет ТОЛЬКО в staging — живой estimates_index.json не трогаем")
|
||||
if not live_path.exists():
|
||||
raise ValueError(f"Живой индекс не найден: {live_path} — без него ценовой гейт 5× "
|
||||
"не работает (fail-loud, тихий пропуск запрещён)")
|
||||
price_ref, mat_ref, live_keys, live_mat_names = _load_live(live_path)
|
||||
|
||||
agg: dict[str, dict] = {}
|
||||
mat_agg: dict[str, dict] = {}
|
||||
ka_agg: dict[str, dict] = {}
|
||||
quarantine: list[dict] = []
|
||||
regions: Counter = Counter()
|
||||
ka_regions: set[str] = set()
|
||||
ka_periods: set[str] = set()
|
||||
n_files = n_err = n_pos_parsed = n_ka_files = n_ka_items = n_vor = n_svod = 0
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="merge_gge_") as td:
|
||||
for path, origin in _iter_gge(src, Path(td)):
|
||||
data = parse_estimate_full(path)
|
||||
n_files += 1
|
||||
if "error" in data:
|
||||
n_err += 1
|
||||
continue
|
||||
schema = data.get("schema", "")
|
||||
if "MarketAnalysis" in schema:
|
||||
n_ka_files += 1
|
||||
n_ka_items += _add_ka(ka_agg, parse_ka(path.read_bytes()),
|
||||
ka_regions, ka_periods)
|
||||
continue
|
||||
if "QuantityTakeoff" in schema:
|
||||
n_vor += 1 # ВОР — вне объёма staging (отдельный индекс)
|
||||
continue
|
||||
if not data["positions"] and not data.get("direct_materials"):
|
||||
n_svod += 1 # ОСР/ССР-свод без расценок — мержить нечего
|
||||
continue
|
||||
plevel = _price_level(data.get("price_cur", ""))
|
||||
if "BaseIndexMethod" in schema or plevel == "базис":
|
||||
quarantine.append({
|
||||
"kind": "file", "tag": "БИМ", "file": origin, "schema": schema,
|
||||
"positions": len(data["positions"]),
|
||||
"price_base": data.get("price_base", ""),
|
||||
"reason": "БИМ/базисный уровень цен (нет PriceLevelCur) — "
|
||||
"unit_cost не в текущих ценах, в корпус нельзя",
|
||||
})
|
||||
continue
|
||||
n_pos_parsed += _add_estimate(agg, mat_agg, data, plevel, regions)
|
||||
|
||||
# расценки: канарейка утечки → ценовой гейт → staging
|
||||
records, n_new_codes = [], 0
|
||||
for key, rec in agg.items():
|
||||
item = _final_item(rec)
|
||||
leaks = collect_leaks(item)
|
||||
if leaks:
|
||||
quarantine.append({"kind": "record", "tag": "утечка", "record": item,
|
||||
"leaks": leaks[:5],
|
||||
"reason": "утечка идентификатора после scrub"})
|
||||
continue
|
||||
if not _price_ok(price_ref.get(item["code"]), item["unit_cost_cur"]):
|
||||
quarantine.append({"kind": "record", "tag": "цена", "record": item,
|
||||
"reason": f"цена вне 5× живого индекса: live "
|
||||
f"{price_ref[item['code']]} vs new {item['unit_cost_cur']}"})
|
||||
continue
|
||||
if key not in live_keys:
|
||||
n_new_codes += 1
|
||||
records.append(item)
|
||||
records.sort(key=lambda x: x["freq"], reverse=True)
|
||||
|
||||
# прямые материалы: те же гейты (эталон = медианная цена в живом индексе)
|
||||
materials, n_new_mats = [], 0
|
||||
for key, mr in mat_agg.items():
|
||||
m = {"name": mr["name"], "code": mr["code"], "unit": mr["unit"],
|
||||
"freq": mr["freq"],
|
||||
"price_cur": round(statistics.median(mr["prices"]), 2) if mr["prices"] else 0.0,
|
||||
"regions": sorted(mr["regions"], key=mr["regions"].get, reverse=True)[:3]}
|
||||
leaks = collect_leaks(m)
|
||||
if leaks:
|
||||
quarantine.append({"kind": "material", "tag": "утечка", "record": m,
|
||||
"leaks": leaks[:5],
|
||||
"reason": "утечка идентификатора после scrub"})
|
||||
continue
|
||||
if not _price_ok(mat_ref.get(key), m["price_cur"]):
|
||||
quarantine.append({"kind": "material", "tag": "цена", "record": m,
|
||||
"reason": f"цена вне 5× живого индекса: live "
|
||||
f"{mat_ref[key]} vs new {m['price_cur']}"})
|
||||
continue
|
||||
if key not in live_mat_names:
|
||||
n_new_mats += 1
|
||||
materials.append(m)
|
||||
materials.sort(key=lambda x: x["freq"], reverse=True)
|
||||
|
||||
# КА-материалы (ka-подобный staging, формат = items живого ka_index)
|
||||
ka_records = []
|
||||
for rec in ka_agg.values():
|
||||
prices = [p for p in ((o.get("estimate_price") or o.get("market_price") or 0.0)
|
||||
for o in rec["offers"]) if p > 0]
|
||||
winner = next(((o.get("estimate_price") or o.get("market_price"))
|
||||
for o in rec["offers"] if o["winner"]), None)
|
||||
regs = sorted(rec["regions"], key=rec["regions"].get, reverse=True)
|
||||
pers = sorted(rec["periods"], key=rec["periods"].get, reverse=True)
|
||||
item = {"name": rec["name"], "unit": rec["unit"], "type": rec["type"],
|
||||
"region": regs[0] if regs else "", "period": pers[0] if pers else "",
|
||||
"offers": rec["offers"],
|
||||
"price": {"min": round(min(prices), 2), "median": round(statistics.median(prices), 2),
|
||||
"max": round(max(prices), 2), "winner": winner} if prices else {}}
|
||||
leaks = collect_leaks(item)
|
||||
if leaks:
|
||||
quarantine.append({"kind": "ka", "tag": "утечка", "record": item,
|
||||
"leaks": leaks[:5],
|
||||
"reason": "утечка идентификатора после scrub"})
|
||||
continue
|
||||
ka_records.append(item)
|
||||
ka_records.sort(key=lambda x: len(x["offers"]), reverse=True)
|
||||
|
||||
summary = {
|
||||
"new_files": n_files,
|
||||
"parse_errors": n_err,
|
||||
"positions": sum(r["freq"] for r in records),
|
||||
"positions_parsed": n_pos_parsed,
|
||||
"quarantined": len(quarantine),
|
||||
"quarantine_reasons": dict(Counter(q["tag"] for q in quarantine)),
|
||||
"merged_new_codes": n_new_codes,
|
||||
"region": regions.most_common(1)[0][0] if regions else "",
|
||||
"regions": sorted(regions),
|
||||
"records": len(records),
|
||||
"price_levels": sorted({r["price_level"] for r in records}),
|
||||
"materials_staged": len(materials),
|
||||
"new_materials": n_new_mats,
|
||||
"ka_files": n_ka_files,
|
||||
"ka_items_raw": n_ka_items,
|
||||
"ka_materials": len(ka_records),
|
||||
"ka_regions": sorted(ka_regions),
|
||||
"ka_periods": sorted(ka_periods),
|
||||
"vor_skipped": n_vor,
|
||||
"svod_skipped": n_svod,
|
||||
}
|
||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
out_path.write_text(json.dumps(
|
||||
{"records": records, "materials": materials, "ka_records": ka_records,
|
||||
"quarantine": quarantine, "summary": summary},
|
||||
ensure_ascii=False), encoding="utf-8")
|
||||
return summary
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser(description="Staging-расширение корпуса из .gge (живой индекс не трогает)")
|
||||
ap.add_argument("src", help="каталог с .gge / zip-архивами (zip-в-zip поддержан)")
|
||||
ap.add_argument("--live", default=str(_ROOT / "data/real_corpus/estimates_index.json"))
|
||||
ap.add_argument("--out", default=str(_ROOT / "data/real_corpus/staging_gge.json"))
|
||||
args = ap.parse_args()
|
||||
src = Path(args.src)
|
||||
if not src.is_dir():
|
||||
print(f"Не каталог: {src}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
summary = merge(src, Path(args.live), Path(args.out))
|
||||
print(json.dumps(summary, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,210 @@
|
||||
"""Юнит-тест arp_deep.parse_arp_full на синтетическом АРПС 1.10 (cp866, '#'-поля).
|
||||
|
||||
RED-GREEN: тест написан ДО arp_deep.py. Ассерты выведены из семантики полей,
|
||||
верифицированной на 283 реальных .arp (11900.zip/12000.zip):
|
||||
тип 20: f5..f9 = базисные ПЗ/ОТ/ЭМ/ЗПМ/МР на ед.; f15..f19 = текущие на ед.;
|
||||
f13/f14 = труд раб/маш баз. на ед.; f23/f24 = то же с коэф.; f26 = ОБЪЁМ
|
||||
(f25 — НЕ объём: в тесте f25 != f26, съезд индекса валит quantity и итог);
|
||||
тип 25: f1=группа (0=индекс пересчёта, 2=Кнр, 3=Ксп, 4=поправочный),
|
||||
f2=статья, f4=значение, f5=имя, f6=обоснование (опц.);
|
||||
тип 30: f1=код, f2=ед., f3=имя, f4=вид (0=труд,1=машина,2=материал), f5=расход
|
||||
(на ед. позиции, С УЧЁТОМ коэф.), f6=цена (базисная 2001);
|
||||
итог сметы (тип 3 f14) = Σ (ПЗтек + (Кнр+Ксп)×(ОТтек+ЗПМтек)) × объём.
|
||||
Числа позиций — реальные (00_02_7_00_01Р), итог шапки посчитан по формуле.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
from arp_deep import parse_arp_full # noqa: E402
|
||||
|
||||
# Формула: pos1 = 20881,25 + (1,09+0,65)×(3550,8+1403,76) = 29502,1844 ×10 = 295021,84
|
||||
# pos2 = 10387,88 × 14 = 145430,32; pos3 = 561×2 = 1122;
|
||||
# pos4 = 250×4 = 1000; итог = 442574,16
|
||||
ARP = "\r\n".join([
|
||||
"1#АРПС 1.10#Программный комплекс АВС#2022.2.1",
|
||||
"0#Регистрационный номер#119400053#",
|
||||
"0#Метод расчета#базисный (базисно-индексный)#",
|
||||
"0#Год нормативной базы#2014",
|
||||
"3####00-02-7-00-01Р#Контактная сеть. Электрофикация 404 пути на станции Находка"
|
||||
"#######Антонова А.С.#Неверова Л.В.#442574,16##0",
|
||||
"0# Расчет сметы выполнен с применением отраслевой сметно-нормативной базы ОСНБЖ-2001 с изменением 4#",
|
||||
"0# 1.коэффициент на производство работ в охранной зоне ВЛ - 1,2 ОПДС-2821.2011 прил.4 таб.1 п.5#",
|
||||
"0# 2. смета пересчитана в текущие цены по распоряжению N1288р от 13.05.2022г. тб. N1, П.2.7.4/2#",
|
||||
"10#0#1# Строительные работы ",
|
||||
"20#1#28-02-013-01 ОЕРЖ-2001 от 25.04.2015 № 326/пр#1 опора#"
|
||||
"Установка опор \"с пути\" массой, т: до 0,6#"
|
||||
"1953,85#320,03#1372,92#126,52#260,9#0###27,78#7,16#"
|
||||
"20881,25#3550,8#15232,82#1403,76#2097,64#0#0#0#38,34#9,88#1#10,0#0##",
|
||||
"25#4#0#0#1,38#Кзп#",
|
||||
"25#4#4#0#1,1#Кзтр#ОЕРЖм часть 8 п.1.8.3 Кзтр=1,1",
|
||||
"25#0#0#0#8,04#Кизп#",
|
||||
"25#0#2#0#8,04#Кимр#",
|
||||
"25#2#0#0#1,09#Кнр#",
|
||||
"25#2#3#0#1,09#Кнр#",
|
||||
"25#3#0#0#0,65#Ксп#",
|
||||
"25#3#3#0#0,65#Ксп#",
|
||||
"30#1#чел.-ч#Затраты труда рабочих-строителей#0#38,3364#11,52#11,52#11,52",
|
||||
"30#1.1##Средний разряд работы#0#3,3###",
|
||||
"30#3#чел.-ч#Затраты труда машинистов#0#9,8808#142,07#142,07#142,07",
|
||||
"30#021312#маш.-ч#Краны на железнодорожном ходу 16 т#1#2,4702#211,94#211,94#211,94",
|
||||
"30#101-0125#т#Гайки шестигранные диаметр резьбы 20-22 мм#2#0,0032#10166,95#10166,95#10166,95",
|
||||
"10#0#2# Демонтажные работы ",
|
||||
"20#2#318533-0003 ОСОЦЖо 81-01-2001#шт.#Газоразрядный прибор защиты ГРПЗ-1У УХЛ1#"
|
||||
"1851,67#0#0#0#1851,67#0#####"
|
||||
"10387,88#0#0#0#10387,88#0#0#0#0#0#14#14,0#0##",
|
||||
"25#0#2#0#5,61#Киоб#",
|
||||
# обоснование начинается с норм-дока, код — второй токен (реальный кейс ОЕРЖм/ОССЦЖ)
|
||||
"20#3#ОЕРЖм 08-01-121-01#компл.#Монтаж блока зажимов#"
|
||||
"100#0#0#0#100#0#####561#0#0#0#561#0#0#0#0#0#1#2,0#0##",
|
||||
# прайс-позиция: кодоподобного токена нет (код пуст), в обосновании ИНН в подчёркиваниях
|
||||
"20#4#Т ТЦ_101_61_6164074370_2022_02 ПРАЙС-ЛИСТЫ СТР.4 П.1#шт.#"
|
||||
"Защитное устройство многократного действия#"
|
||||
"50#0#0#0#50#0#####250#0#0#0#250#0#0#0#0#0#1#4,0#0##",
|
||||
]) + "\r\n"
|
||||
|
||||
|
||||
def _parse(text: str = ARP) -> dict:
|
||||
p = Path(tempfile.mkdtemp()) / "смета.arp"
|
||||
p.write_bytes(text.encode("cp866"))
|
||||
return parse_arp_full(p)
|
||||
|
||||
|
||||
def test_header_and_anon():
|
||||
r = _parse()
|
||||
assert "error" not in r, r
|
||||
assert r["code"] == "00-02-7-00-01Р", r["code"]
|
||||
# имя обезличено: топоним вырезан, техническая суть осталась
|
||||
assert "Находка" not in r["name"], r["name"]
|
||||
assert "Контактная сеть" in r["name"], r["name"]
|
||||
assert abs(r["total"] - 442574.16) < 0.01, r["total"]
|
||||
# allow-list: ФИО подписантов и рег.номер не извлекаются ВООБЩЕ
|
||||
dump = json.dumps(r, ensure_ascii=False)
|
||||
assert "Антонова" not in dump and "Неверова" not in dump
|
||||
assert "119400053" not in dump
|
||||
assert r["method"].startswith("базисный"), r["method"]
|
||||
assert r["base_year"] == "2014", r["base_year"]
|
||||
assert r["norm_base"] == "ОСНБЖ", r["norm_base"]
|
||||
# файловые обоснования коэффициентов сохранены в comments (ОПДС-2821)
|
||||
assert any("ОПДС-2821" in c for c in r["comments"]), r["comments"]
|
||||
|
||||
|
||||
def test_price_level_and_recalc():
|
||||
r = _parse()
|
||||
assert r["recalc"], r
|
||||
assert r["recalc"]["doc"] == "1288р", r["recalc"]
|
||||
assert r["recalc"]["date"] == "13.05.2022", r["recalc"]
|
||||
assert "1288р" in r["price_level"] and "2022" in r["price_level"], r["price_level"]
|
||||
|
||||
|
||||
def test_position_costs_and_quantity():
|
||||
r = _parse()
|
||||
assert r["positions_count"] == 4, r["positions_count"]
|
||||
p = r["positions"][0]
|
||||
assert p["code"] == "28-02-013-01", p["code"]
|
||||
assert "ОЕРЖ-2001" in p["justification"], p["justification"]
|
||||
assert p["unit"] == "1 опора", p["unit"]
|
||||
assert p["section"] == "Строительные работы", p["section"]
|
||||
# объём = f26 (проверено формулой итога на 283 файлах); f25 тут = 1 — ловушка
|
||||
assert abs(p["quantity"] - 10.0) < 1e-9, p["quantity"]
|
||||
b, c = p["base_costs"], p["cur_costs"]
|
||||
assert abs(b["direct"] - 1953.85) < 0.01 and abs(c["direct"] - 20881.25) < 0.01, (b, c)
|
||||
assert abs(b["labor"] - 320.03) < 0.01 and abs(c["labor"] - 3550.8) < 0.01, (b, c)
|
||||
assert abs(b["machines"] - 1372.92) < 0.01 and abs(c["machines"] - 15232.82) < 0.01, (b, c)
|
||||
assert abs(b["machinist"] - 126.52) < 0.01 and abs(c["machinist"] - 1403.76) < 0.01, (b, c)
|
||||
assert abs(b["materials"] - 260.9) < 0.01 and abs(c["materials"] - 2097.64) < 0.01, (b, c)
|
||||
assert abs(p["labor_ch"] - 27.78) < 0.01 and abs(p["labor_ch_adj"] - 38.34) < 0.01, p
|
||||
assert abs(p["machinist_ch"] - 7.16) < 0.01 and abs(p["machinist_ch_adj"] - 9.88) < 0.01, p
|
||||
# полная цена ед. в тек. ценах = ПЗ + (Кнр+Ксп)×(ОТ+ЗПМ)
|
||||
assert abs(p["unit_cost_cur"] - 29502.18) < 0.01, p["unit_cost_cur"]
|
||||
p2 = r["positions"][1]
|
||||
assert abs(p2["quantity"] - 14.0) < 1e-9, p2["quantity"]
|
||||
assert abs(p2["unit_cost_cur"] - 10387.88) < 0.01, p2["unit_cost_cur"]
|
||||
assert p2["section"] == "Демонтажные работы", p2["section"]
|
||||
|
||||
|
||||
def test_code_extraction_variants():
|
||||
r = _parse()
|
||||
# «<норм.док> <код>»: код — первый кодоподобный токен, не «ОЕРЖм»
|
||||
p3 = r["positions"][2]
|
||||
assert p3["code"] == "08-01-121-01", p3["code"]
|
||||
assert abs(p3["quantity"] - 2.0) < 1e-9, p3["quantity"]
|
||||
# прайс-позиция без кодоподобного токена: код пуст (агрегация пойдёт по имени)
|
||||
p4 = r["positions"][3]
|
||||
assert p4["code"] == "", p4["code"]
|
||||
# ИНН в подчёркиваниях (_6164074370_) обязан вырезаться скрабом
|
||||
assert "6164074370" not in p4["justification"], p4["justification"]
|
||||
|
||||
|
||||
def test_total_formula_check():
|
||||
r = _parse()
|
||||
assert abs(r["total_computed"] - 442574.16) < 0.5, r["total_computed"]
|
||||
assert r["total_check_ok"] is True, r
|
||||
# mutation-ловушка: порча итога шапки должна валить проверку
|
||||
bad = _parse(ARP.replace("442574,16", "999999,99"))
|
||||
assert bad["total_check_ok"] is False, bad["total_computed"]
|
||||
|
||||
|
||||
def test_coefficients():
|
||||
r = _parse()
|
||||
cs = r["positions"][0]["coefficients"]
|
||||
by_kind = {}
|
||||
for c in cs:
|
||||
by_kind.setdefault(c["kind"], []).append(c)
|
||||
assert abs(by_kind["Кзп"][0]["value"] - 1.38) < 1e-9, by_kind["Кзп"]
|
||||
assert by_kind["Кзп"][0]["group"] == "adjust", by_kind["Кзп"]
|
||||
assert abs(by_kind["Кнр"][0]["value"] - 1.09) < 1e-9, by_kind["Кнр"]
|
||||
assert by_kind["Кнр"][0]["group"] == "overhead", by_kind["Кнр"]
|
||||
assert abs(by_kind["Ксп"][0]["value"] - 0.65) < 1e-9, by_kind["Ксп"]
|
||||
assert by_kind["Ксп"][0]["group"] == "profit", by_kind["Ксп"]
|
||||
assert abs(by_kind["Кизп"][0]["value"] - 8.04) < 1e-9, by_kind["Кизп"]
|
||||
assert by_kind["Кизп"][0]["group"] == "index", by_kind["Кизп"]
|
||||
# обоснование конкретного коэффициента (f6) извлечено
|
||||
assert "ОЕРЖм часть 8 п.1.8.3" in by_kind["Кзтр"][0]["reason"], by_kind["Кзтр"]
|
||||
# сводка индексов пересчёта (пункт #5): главный Кизп
|
||||
assert abs(r["kizp"]["main"] - 8.04) < 1e-9, r["kizp"]
|
||||
assert "8,04" in r["kizp"]["values"]["Кизп"] or "8.04" in str(r["kizp"]["values"]["Кизп"]), r["kizp"]
|
||||
assert "Киоб" in r["kizp"]["values"], r["kizp"]
|
||||
|
||||
|
||||
def test_resources():
|
||||
r = _parse()
|
||||
res = r["positions"][0]["resources"]
|
||||
w = res["workers"]
|
||||
assert len(w) == 2, w # рабочие-строители + машинисты; разряд свёрнут в grade
|
||||
assert abs(w[0]["consumption"] - 38.3364) < 1e-9, w[0]
|
||||
assert abs(w[0]["price_base"] - 11.52) < 0.01, w[0]
|
||||
assert w[0]["grade"] == "3,3", w[0]
|
||||
assert "машинист" in w[1]["name"], w[1]
|
||||
assert abs(w[1]["consumption"] - 9.8808) < 1e-9, w[1]
|
||||
m = res["machines"]
|
||||
assert len(m) == 1 and m[0]["code"] == "021312", m
|
||||
assert "Краны" in m[0]["name"] and m[0]["unit"] == "маш.-ч", m
|
||||
assert abs(m[0]["consumption"] - 2.4702) < 1e-9 and abs(m[0]["price_base"] - 211.94) < 0.01, m
|
||||
mat = res["materials"]
|
||||
assert len(mat) == 1 and mat[0]["code"] == "101-0125", mat
|
||||
assert abs(mat[0]["consumption"] - 0.0032) < 1e-9 and abs(mat[0]["price_base"] - 10166.95) < 0.01, mat
|
||||
|
||||
|
||||
def test_bad_file():
|
||||
d = Path(tempfile.mkdtemp())
|
||||
p = d / "x.arp"
|
||||
p.write_bytes(b"\xff\xfe garbage not arps")
|
||||
r = parse_arp_full(p)
|
||||
assert r["positions_count"] == 0, r # не падает
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import traceback
|
||||
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)]
|
||||
failed = 0
|
||||
for fn in fns:
|
||||
try:
|
||||
fn(); print(f" ok: {fn.__name__}")
|
||||
except Exception:
|
||||
failed += 1; print(f" FAIL: {fn.__name__}"); traceback.print_exc()
|
||||
print("ALL PASS" if not failed else f"{failed} FAILED")
|
||||
sys.exit(failed and 1)
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Real-тест arp_deep + staging на настоящих .arp (гонять на dev2).
|
||||
|
||||
Якоря — из реального файла 00_02_7_00_01Р (КС, 11900.zip), значения сверены
|
||||
глазами по сырому АРПС-тексту и парной .xls-распечатке (Итого по смете).
|
||||
Запускать ПОСЛЕ scripts/build_arp_staging.py (проверяет и staging-файл).
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
from arp_deep import parse_arp_text # noqa: E402
|
||||
from corpus_anon import has_identifier_leak # noqa: E402
|
||||
from build_arp_staging import _norm_stem, _struct_leaks, _xls_total # noqa: E402
|
||||
|
||||
SRC = Path("/home/mcp-user/smeta-web-data/smeta/b1f47437-2254-4267-a584-4d2ea050e100/11900.zip")
|
||||
STAGING = ROOT / "data/real_corpus/staging_arp.json"
|
||||
|
||||
z = zipfile.ZipFile(SRC)
|
||||
arp_name = next(n for n in z.namelist() if n.lower().endswith(".arp"))
|
||||
est = parse_arp_text(z.read(arp_name).decode("cp866", "replace"), path="real")
|
||||
|
||||
# --- шапка + гейт формулы итога ---
|
||||
assert est["code"] == "00-02-7-00-01Р", est["code"]
|
||||
assert abs(est["total"] - 6105760.71) < 0.01, est["total"]
|
||||
assert est["total_check_ok"] is True, (est["total"], est["total_computed"])
|
||||
assert est["positions_count"] == 70, est["positions_count"]
|
||||
assert est["norm_base"] == "ОСНБЖ", est["norm_base"]
|
||||
assert est["base_year"] == "2014", est["base_year"]
|
||||
print(f" шапка: {est['code']} | итог={est['total']} | формула={est['total_computed']} | позиций={est['positions_count']}")
|
||||
|
||||
# --- пункт #5: индекс пересчёта с обоснованием ---
|
||||
assert est["recalc"] and est["recalc"]["doc"] == "1288р", est["recalc"]
|
||||
assert est["recalc"]["date"] == "13.05.2022", est["recalc"]
|
||||
assert abs(est["kizp"]["main"] - 8.04) < 1e-9, est["kizp"]
|
||||
print(f" price_level: {est['price_level']} | Кизп={est['kizp']['main']}")
|
||||
|
||||
# --- реально применённые коэффициенты позиции 1 (Копание ям) ---
|
||||
p0 = est["positions"][0]
|
||||
assert p0["code"] == "01-02-058-03", p0["code"]
|
||||
ks = {(c["kind"], c["target"]): c["value"] for c in p0["coefficients"]}
|
||||
assert abs(ks[("Кзп", "ОТ")] - 1.3) < 1e-9, ks
|
||||
assert abs(ks[("Кнр", "ОТ")] - 0.89) < 1e-9, ks
|
||||
assert abs(ks[("Ксп", "ОТ")] - 0.4) < 1e-9, ks
|
||||
assert abs(ks[("Кизп", "ОТ")] - 8.04) < 1e-9, ks
|
||||
groups = {c["kind"]: c["group"] for c in p0["coefficients"]}
|
||||
assert groups["Кнр"] == "overhead" and groups["Ксп"] == "profit", groups
|
||||
assert groups["Кизп"] == "index" and groups["Кзп"] == "adjust", groups
|
||||
assert abs(p0["quantity"] - 0.00448) < 1e-9, p0["quantity"]
|
||||
|
||||
# --- ресурсы позиции 2 (Установка опор) ---
|
||||
p1 = est["positions"][1]
|
||||
w = p1["resources"]["workers"]
|
||||
assert abs(w[0]["consumption"] - 38.3364) < 1e-6 and w[0]["grade"] == "3,3", w
|
||||
m = {r["code"]: r for r in p1["resources"]["machines"]}
|
||||
assert abs(m["021312"]["consumption"] - 2.4702) < 1e-6, m
|
||||
assert abs(m["021312"]["price_base"] - 211.94) < 0.01, m
|
||||
mat = {r["code"]: r for r in p1["resources"]["materials"]}
|
||||
assert abs(mat["101-0125"]["consumption"] - 0.0032) < 1e-9, mat
|
||||
print(f" ресурсы поз.2: workers={len(w)} machines={len(m)} materials={len(mat)}")
|
||||
|
||||
# --- обезличивание: топоним из шапки вырезан, ФИО не извлечены ---
|
||||
dump = json.dumps(est, ensure_ascii=False)
|
||||
assert "Находка" not in dump, "топоним утёк"
|
||||
assert "Антонова" not in dump and "Неверова" not in dump, "ФИО утекли"
|
||||
assert not has_identifier_leak(est["name"]), est["name"]
|
||||
|
||||
# --- ground truth: итог парной .xls === итог .arp ---
|
||||
stem = _norm_stem(arp_name, "arps?")
|
||||
xls_name = next(n for n in z.namelist()
|
||||
if n.lower().endswith(".xls") and _norm_stem(n, "xls") == stem)
|
||||
xt = _xls_total(z.read(xls_name))
|
||||
assert xt is not None, "итог из .xls не извлёкся"
|
||||
assert abs(est["total"] - xt) <= 2.0, (est["total"], xt)
|
||||
print(f" сверка с парной .xls: arp={est['total']} xls={xt} — сошлось")
|
||||
|
||||
# --- staging: счётчики, 0 утечек, живой индекс не тронут по построению ---
|
||||
assert STAGING.exists(), "staging_arp.json не построен — сначала build_arp_staging.py"
|
||||
st = json.loads(STAGING.read_text(encoding="utf-8"))
|
||||
meta = st["meta"]
|
||||
assert meta["staged_files"] > 0 and meta["unique_items"] > 0, meta
|
||||
assert meta["leaks_in_staging"] == 0, meta
|
||||
assert meta["xls_verified"] > 0, meta
|
||||
# арифметика приёмки: staged + duplicates + карантин(файлы, вкл. parse_error) == files_seen
|
||||
quar_files = sum(v for k, v in meta["quarantined"].items()
|
||||
if k not in ("price_outlier", "leak_final_pass"))
|
||||
assert meta["staged_files"] + meta["duplicates"] + quar_files == meta["files_seen"], meta
|
||||
# независимая канарейка утечек: по строковым значениям каждого item
|
||||
leaks = sum(1 for it in st["items"] + st["recalc_index"] if _struct_leaks(it))
|
||||
assert leaks == 0, f"{leaks} утечек в staging"
|
||||
# записи с реально применёнными коэффициентами и Кнр/Ксп в топе
|
||||
with_coefs = [it for it in st["items"] if it["coef_applications"]]
|
||||
assert with_coefs, "нет ни одной записи с коэффициентами"
|
||||
kinds = {c["kind"] for it in with_coefs for c in it["coef_applications"]["coefs"]}
|
||||
assert "Кнр" in kinds and "Ксп" in kinds, kinds
|
||||
# пункт #5: recalc_index с распоряжением 1288р и Кизп
|
||||
docs = {r["doc"] for r in st["recalc_index"]}
|
||||
assert "1288р" in docs, docs
|
||||
r1288 = next(r for r in st["recalc_index"] if r["doc"] == "1288р")
|
||||
assert "Кизп" in r1288["indices"], r1288["indices"]
|
||||
assert all(it["norm_base"] == "ОСНБЖ" and it["price_level"] for it in st["items"][:50])
|
||||
print(f" staging: items={meta['unique_items']} staged={meta['staged_files']} "
|
||||
f"dup={meta['duplicates']} quar={dict(meta['quarantined'])} "
|
||||
f"xls_verified={meta['xls_verified']}/{meta['xls_pairs_found']} leaks=0")
|
||||
print("ALL PASS")
|
||||
+14
-4
@@ -165,6 +165,15 @@ def test_parse_ka(tmp_path):
|
||||
assert "Ромашка" not in blob and "9722010798" not in blob
|
||||
|
||||
|
||||
def test_parse_ka_regionname_fallback():
|
||||
# КА ДВ-корпуса 2025: регион оффера лежит в Region/RegionName, не Region/Name
|
||||
xml = KA_XML.replace("<Region><Name>г. Москва</Name></Region>",
|
||||
"<Region><RegionCode>77</RegionCode>"
|
||||
"<RegionName>г. Москва</RegionName></Region>")
|
||||
items = parse_ka(xml.encode("utf-8"))
|
||||
assert items[0]["offers"][0]["region"] == "г. Москва"
|
||||
|
||||
|
||||
def test_scrub():
|
||||
assert scrub("960-06-1356-СМ3.8.1") == "[…]"
|
||||
assert scrub("Кабель 960-06-ТКР34") == "Кабель […]"
|
||||
@@ -183,7 +192,8 @@ if __name__ == "__main__":
|
||||
fn(Path(td))
|
||||
passed += 1
|
||||
print(f"OK {fn.__name__}")
|
||||
test_scrub()
|
||||
passed += 1
|
||||
print(f"OK test_scrub")
|
||||
print(f"\n{passed}/4 тестов прошли")
|
||||
for fn in (test_parse_ka_regionname_fallback, test_scrub):
|
||||
fn()
|
||||
passed += 1
|
||||
print(f"OK {fn.__name__}")
|
||||
print(f"\n{passed}/5 тестов прошли")
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
"""Юнит-тест parse_gsfx_full на СИНТЕТИЧЕСКОМ .gsfx — zip с Properties.txt +
|
||||
Data.xml в cp1251, структура скопирована с реального файла ГРАНД 15.3
|
||||
(Tzr/Tzm/Mch/Mat + PriceCurr/PriceBase, Vids_Rab-каталог НР/СП, WorksList,
|
||||
Koefficients, ССР-строка без кода). Реальные файлы проверяются отдельно на
|
||||
сервере (test_gsfx_deep_real.py).
|
||||
|
||||
Mutation-safe: числа подобраны так, что чтение не той цены (PriceBase вместо
|
||||
PriceCurr), потеря материала или неразбор запятой ломают точные asserts.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
from gsfx_deep import parse_gsfx_full # noqa: E402
|
||||
from corpus_anon import has_identifier_leak # noqa: E402
|
||||
|
||||
PROPS = (
|
||||
"DocType=sdtSmeta\r\n"
|
||||
"Attribs.LocNum=ЛС-02-01-01-И2\r\n"
|
||||
"Attribs.ObjName=Контактная сеть\r\n"
|
||||
"Attribs.ConName=Электрификация тракционных путей Комсомольск-Сортировочный\r\n"
|
||||
"Attribs.Description=Контактная сеть\r\n"
|
||||
"Total=21230.89\r\n"
|
||||
"TotalCalcMethod=Res\r\n"
|
||||
"RegionInfo.RegionName=ФСНБ-2022 (с Изм. 1-12)\r\n"
|
||||
"RegionInfo.ZoneName=Базовый район\r\n"
|
||||
"GSmetaVersion=15.3.3.54868\r\n"
|
||||
)
|
||||
|
||||
DATA = (
|
||||
'<?xml version="1.0" encoding="windows-1251"?>\r\n'
|
||||
'<Document ProgramVersion="15.3.3.54868" Generator="GrandSmeta">\r\n'
|
||||
'<Properties LocNum="ЛС-02-01-01-И2" Object="Контактная сеть"'
|
||||
' Constr="Электрификация тракционных путей Комсомольск-Сортировочный"/>\r\n'
|
||||
'<GsDocSignatures>\r\n'
|
||||
' <Item Caption="Составил" ID="300" Value="Голубенко Н.В."/>\r\n'
|
||||
'</GsDocSignatures>\r\n'
|
||||
'<DocDates BasePriceDate="01.01.2022" CurrPriceDate="01.10.2024"/>\r\n'
|
||||
'<RegionInfo RegionName="ФСНБ-2022 (с Изм. 1-12)" Zone01Name="Базовый район"'
|
||||
' AdmRegionCode="27" AdmRegionZone="Хабаровский край (2 зона)"/>\r\n'
|
||||
'<Vids_Rab Type="Виды работ 2001г">\r\n'
|
||||
' <VidRab_Group Caption="Общестроительные работы" ID="0">\r\n'
|
||||
' <Vid_Rab Caption="Электрификация железных дорог" ID="10032"'
|
||||
' NrCode="Пр/812-020.2" SpCode="Пр/774-020.2" Nacl="105" Plan="62"'
|
||||
' NaclCurr="105" PlanCurr="62" NaclMask="ФОТ" PlanMask="ФОТ"/>\r\n'
|
||||
' </VidRab_Group>\r\n'
|
||||
'</Vids_Rab>\r\n'
|
||||
'<Chapters><Chapter Caption="Строительные работы" SysID="1">\r\n'
|
||||
'<Position Caption="Установка консолей неизолированных на перегоне Тында"'
|
||||
' SysID="11" Number="1" Code="ГЭСН28-02-022-02" Units="шт" PriceLevel="2001"'
|
||||
' Comment="(монтаж на станции Дипкун)"'
|
||||
' DBComment="Приказ Минстроя России от 10.02.2023 №84/пр"'
|
||||
' Quantity="ОКР(24/100; 7)" PzSync="Yes" Vr2001="10032">\r\n'
|
||||
' <Quantity Fx="24/100" Precision="7" Result="0,24"/>\r\n'
|
||||
' <Resources>\r\n'
|
||||
' <Tzr Caption="Средний разряд работы 3,3" Code="1-100-33" Units="чел.-ч"'
|
||||
' Quantity="7,14" WorkClass="3,3">\r\n'
|
||||
' <PriceCurr Value="675,52" Comment="ССЦ 2024 зона 161 сметные цены"/>\r\n'
|
||||
' </Tzr>\r\n'
|
||||
' <Tzm Caption="Затраты труда машинистов" Code="2" Units="чел.-ч" Quantity="1,96"/>\r\n'
|
||||
' <Mch Caption="Платформы широкой колеи, грузоподъемность 73 т"'
|
||||
' Code="91.09.03-035" Units="маш.час" Quantity="0,63" IndexCode="1041">\r\n'
|
||||
' <PriceBase Value="150,13"/>\r\n'
|
||||
' <PriceCurr Value="283,75" ZM="100,5" Comment="ССЦ 2024 ЭММ"/>\r\n'
|
||||
' <Tzm2022 WorkClass="6" Quantity="2" Price="984,56"/>\r\n'
|
||||
' </Mch>\r\n'
|
||||
' <Mat Caption="Консоли неизолированные" Code="25.2.02.03" Units="шт"'
|
||||
' Options="NotCount" Quantity="1"/>\r\n'
|
||||
' <Mat Caption="Болт анкерный" Code="01.7.15" Units="кг" Quantity="2,5">\r\n'
|
||||
' <PriceCurr Value="10" Comment="ССЦ 2024"/>\r\n'
|
||||
' </Mat>\r\n'
|
||||
' </Resources>\r\n'
|
||||
' <Koefficients>\r\n'
|
||||
' <K Caption="Продолжительность «окна», час: от 2 до 4" Code="Прил.28.1 п.1.7"'
|
||||
' Options="Base Curr" Value_OZ="0,9" Value_EM="0,9" Level="1"/>\r\n'
|
||||
' <K Caption="Стеснённые условия" Code="Том 9.4.4 23-СМ.ВОР.СС п.18"'
|
||||
' Options="Base Curr" Value_PZ="1,15" Level="2"/>\r\n'
|
||||
' </Koefficients>\r\n'
|
||||
' <WorksList>\r\n'
|
||||
' <Work Caption="Сборка и армирование консолей с изоляторами."/>\r\n'
|
||||
' <Work Caption="Установка на станции Дипкун."/>\r\n'
|
||||
' </WorksList>\r\n'
|
||||
'</Position>\r\n'
|
||||
'<Position Caption="Щебень М 800, фракция 20-40 мм" SysID="67" Number="2"'
|
||||
' Code="ФСБЦ-02.2.05.04-2090" Units="м3" PriceLevel="2001" Mass="1750"'
|
||||
' DBComment="Приказ Минстроя России от 18.05.2022 №378/пр"'
|
||||
' Quantity="ОКР(6; 7)" Vr2001="10091">\r\n'
|
||||
' <Quantity Fx="6" Precision="7" Result="6"/>\r\n'
|
||||
' <Transportation>\r\n'
|
||||
' <Item Caption="Перевозка до 15 т на 30 км" Code="02-15-1-01-0030"'
|
||||
' Units="1т груза" PriceCurr="437,02" KC="-1"/>\r\n'
|
||||
' <Item Caption="Перевозка до 15 т на 39 км" Code="02-15-1-01-0039"'
|
||||
' Units="1т груза" PriceCurr="506,15"/>\r\n'
|
||||
' </Transportation>\r\n'
|
||||
' <PriceBase PZ="2184,44" MT="2184,44"/>\r\n'
|
||||
' <PriceCurr MT="2075,22" Comment="ССЦ 2024 зона 161"/>\r\n'
|
||||
'</Position>\r\n'
|
||||
'<Position Caption="Опора анкерная (по прайсу)" SysID="90" Number="3"'
|
||||
' Code="ТЦ_НИПИГАЗ_2801210780_6.1" Units="шт" Quantity="ОКР(2; 7)">\r\n'
|
||||
' <Quantity Fx="2" Precision="7" Result="2"/>\r\n'
|
||||
' <PriceCurr Value="150" Comment="прайс"/>\r\n'
|
||||
'</Position>\r\n'
|
||||
'<Position Caption="Контактная сеть Комсомольск" SysID="30" Number="4"'
|
||||
' Obosn="11569/12.0659/1728-09-3844-СМ" Units="м" UnitsQty="1870">\r\n'
|
||||
' <Total Pz="53692710" Nr="5325670" Sp="2727860" Total="65575180"/>\r\n'
|
||||
'</Position>\r\n'
|
||||
'</Chapter></Chapters>\r\n'
|
||||
'</Document>\r\n'
|
||||
)
|
||||
|
||||
# Ручной расчёт по синтетике (для mutation-safe asserts):
|
||||
# ПЗ/ед поз.1 = 7.14*675.52 + 0.63*283.75 + 2.5*10 = 5026.9753
|
||||
# ФОТ/ед = 7.14*675.52 + 0.63*100.5 = 4886.5278
|
||||
# итог поз.1 = 0.24*(5026.9753 + 4886.5278*(105+62)/100) = 3164.99
|
||||
# итог поз.2 = 6*2075.22 + 1.75*6*506.15 = 17765.895
|
||||
# итог поз.3 (прайс) = 2*150 = 300 → declared Total=21230.89
|
||||
UNIT_COST_1 = 5026.98
|
||||
COMPUTED_TOTAL = 21230.89
|
||||
|
||||
|
||||
def _make_gsfx(dirpath: Path, props: str = PROPS, data: str = DATA) -> Path:
|
||||
p = dirpath / "смета.gsfx"
|
||||
with zipfile.ZipFile(p, "w") as z:
|
||||
z.writestr("Properties.txt", props.encode("cp1251"))
|
||||
z.writestr("Data.xml", data.encode("cp1251"))
|
||||
z.writestr("Data.sign", b"\x00\x01")
|
||||
return p
|
||||
|
||||
|
||||
def _parsed():
|
||||
d = Path(tempfile.mkdtemp())
|
||||
r = parse_gsfx_full(_make_gsfx(d))
|
||||
assert "error" not in r, r
|
||||
return r
|
||||
|
||||
|
||||
def test_header_and_meta():
|
||||
r = _parsed()
|
||||
assert r["code"] == "ЛС-02-01-01-И2", r
|
||||
# имя обезличено: проектный топоним вырезан
|
||||
assert "Комсомольск" not in r["name"], r["name"]
|
||||
assert "Электрификация" in r["name"], r["name"]
|
||||
assert r["norm_base"] == "ФСНБ-2022 (с Изм. 1-12)", r
|
||||
assert r["region"] == "Базовый район", r
|
||||
assert r["price_level"] == {"base": "01.01.2022", "cur": "01.10.2024"}, r
|
||||
assert abs(r["total"] - 21230.89) < 0.01, r
|
||||
|
||||
|
||||
def test_work_position_resources():
|
||||
r = _parsed()
|
||||
assert len(r["positions"]) == 3, [p["code"] for p in r["positions"]]
|
||||
p = r["positions"][0]
|
||||
assert p["code"] == "ГЭСН28-02-022-02", p
|
||||
assert p["kind"] == "work", p
|
||||
# scrub: топоним в названии и комментарии вырезан
|
||||
assert "Тында" not in p["name"] and "[…]" in p["name"], p["name"]
|
||||
assert "Дипкун" not in p["comment"], p["comment"]
|
||||
assert "84/пр" in p["price_source"], p["price_source"]
|
||||
assert abs(p["quantity"] - 0.24) < 1e-9, p # русская запятая в Result
|
||||
assert p["unit"] == "шт", p
|
||||
|
||||
res = p["resources"]
|
||||
assert len(res["workers"]) == 1, res
|
||||
w = res["workers"][0]
|
||||
assert w["code"] == "1-100-33" and w["work_class"] == "3,3", w
|
||||
assert abs(w["consumption"] - 7.14) < 1e-9, w
|
||||
assert abs(w["price_cur"] - 675.52) < 1e-9, w
|
||||
assert "ССЦ 2024" in w["price_comment"], w
|
||||
|
||||
assert len(res["machines"]) == 1, res
|
||||
m = res["machines"][0]
|
||||
assert m["code"] == "91.09.03-035", m
|
||||
assert abs(m["consumption"] - 0.63) < 1e-9, m
|
||||
assert abs(m["price_base"] - 150.13) < 1e-9, m
|
||||
assert abs(m["price_cur"] - 283.75) < 1e-9, m
|
||||
assert abs(m["zm_cur"] - 100.5) < 1e-9, m
|
||||
assert m["machinist"] == {"work_class": "6", "count": 2.0, "price_cur": 984.56}, m
|
||||
|
||||
mats = res["materials"]
|
||||
assert len(mats) == 2, mats
|
||||
assert mats[0]["not_counted"] is True and mats[0]["price_cur"] is None, mats[0]
|
||||
assert abs(mats[1]["consumption"] - 2.5) < 1e-9, mats[1]
|
||||
assert abs(mats[1]["price_cur"] - 10.0) < 1e-9, mats[1]
|
||||
|
||||
assert abs(p["labor_ch"] - 7.14) < 1e-9, p
|
||||
assert abs(p["machinist_ch"] - 1.96) < 1e-9, p
|
||||
assert abs(p["unit_cost_cur"] - UNIT_COST_1) < 0.01, p["unit_cost_cur"]
|
||||
|
||||
|
||||
def test_works_list_and_coefficients():
|
||||
p = _parsed()["positions"][0]
|
||||
wl = p["works_list"]
|
||||
assert len(wl) == 2, wl
|
||||
assert wl[0] == "Сборка и армирование консолей с изоляторами.", wl
|
||||
assert "Дипкун" not in wl[1] and "[…]" in wl[1], wl # scrub состава работ
|
||||
ks = p["coefficients"]
|
||||
assert len(ks) == 2, ks
|
||||
assert ks[0]["code"] == "Прил.28.1 п.1.7", ks # норматив не порезан
|
||||
assert abs(ks[0]["oz"] - 0.9) < 1e-9 and abs(ks[0]["em"] - 0.9) < 1e-9, ks
|
||||
assert ks[0]["mt"] is None and ks[0]["pz"] is None, ks
|
||||
# K@Code — свободное поле: шифр тома (реквизит) должен быть вырезан
|
||||
assert "Том 9.4.4" not in ks[1]["code"], ks[1]
|
||||
assert abs(ks[1]["pz"] - 1.15) < 1e-9, ks[1]
|
||||
|
||||
|
||||
def test_overhead_profit_from_vids_rab():
|
||||
r = _parsed()
|
||||
p = r["positions"][0]
|
||||
assert p["overhead"] == {"pct": 105.0, "base": "ФОТ", "code": "Пр/812-020.2",
|
||||
"vid_rab": "Электрификация железных дорог"}, p["overhead"]
|
||||
assert p["profit"] == {"pct": 62.0, "base": "ФОТ", "code": "Пр/774-020.2",
|
||||
"vid_rab": "Электрификация железных дорог"}, p["profit"]
|
||||
# Vr2001=10091 нет в каталоге → None, а не выдумка
|
||||
p2 = r["positions"][1]
|
||||
assert p2["overhead"] is None and p2["profit"] is None, p2
|
||||
|
||||
|
||||
def test_material_position():
|
||||
p = _parsed()["positions"][1]
|
||||
assert p["kind"] == "material", p
|
||||
assert p["code"] == "ФСБЦ-02.2.05.04-2090", p
|
||||
assert abs(p["quantity"] - 6.0) < 1e-9, p
|
||||
# цена из PriceCurr@MT (не @Value и не базовая 2184.44)
|
||||
assert abs(p["unit_cost_cur"] - 2075.22) < 1e-9, p
|
||||
assert p["price_comment"] == "ССЦ 2024 зона 161", p # источник цены
|
||||
assert p["resources"] == {"workers": [], "machines": [], "materials": []}, p
|
||||
|
||||
|
||||
def test_summary_row_skipped():
|
||||
r = _parsed()
|
||||
# ССР-строка (без Code, с <Total>) не попадает в positions — и её
|
||||
# необезличенный Caption не утекает
|
||||
assert r["summary_rows"] == 1, r
|
||||
dump = json.dumps(r, ensure_ascii=False)
|
||||
assert "Контактная сеть Комсомольск" not in dump, "ССР-строка утекла"
|
||||
assert "11569/12.0659" not in dump, "Obosn утёк"
|
||||
assert "Голубенко" not in dump, "подписант утёк"
|
||||
|
||||
|
||||
def test_price_code_scrubbed():
|
||||
# @Code — обычно нормативный шифр, но прайс-ссылки (ТЦ_…) содержат
|
||||
# реквизиты (поставщик/номер прайса/ИНН) → scrub обязателен и для кода
|
||||
p = _parsed()["positions"][2]
|
||||
assert p["kind"] == "material", p
|
||||
assert abs(p["unit_cost_cur"] - 150.0) < 1e-9, p
|
||||
assert "НИПИГАЗ" not in p["code"], p["code"]
|
||||
assert p["code"].startswith("ТЦ_"), p["code"] # техчасть кода сохранена
|
||||
|
||||
|
||||
def test_totals_check():
|
||||
tc = _parsed()["totals_check"]
|
||||
assert abs(tc["declared"] - 21230.89) < 0.01, tc
|
||||
assert abs(tc["computed"] - COMPUTED_TOTAL) < 1.0, tc
|
||||
assert 0.99 < tc["ratio"] < 1.01, tc
|
||||
|
||||
|
||||
def _iter_texts(obj):
|
||||
"""Все строковые значения структуры (проверка утечек — по ПОЛЯМ, не по
|
||||
JSON-дампу: кавычки JSON ложно срабатывают на правило «имя в кавычках»)."""
|
||||
if isinstance(obj, str):
|
||||
yield obj
|
||||
elif isinstance(obj, dict):
|
||||
for v in obj.values():
|
||||
yield from _iter_texts(v)
|
||||
elif isinstance(obj, (list, tuple)):
|
||||
for v in obj:
|
||||
yield from _iter_texts(v)
|
||||
|
||||
|
||||
def test_no_identifier_leak_anywhere():
|
||||
r = _parsed()
|
||||
r.pop("path") # путь к tmp-файлу — не поле корпуса
|
||||
leaks = [t for t in _iter_texts(r) if has_identifier_leak(t)]
|
||||
assert not leaks, leaks
|
||||
|
||||
|
||||
def test_bad_zip_returns_error():
|
||||
d = Path(tempfile.mkdtemp())
|
||||
bad = d / "broken.gsfx"
|
||||
bad.write_bytes(b"not a zip at all")
|
||||
assert "error" in parse_gsfx_full(bad)
|
||||
|
||||
|
||||
def test_broken_xml_returns_error():
|
||||
d = Path(tempfile.mkdtemp())
|
||||
r = parse_gsfx_full(_make_gsfx(d, data="<Document><oops></Document>"))
|
||||
assert "error" in r, r
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import traceback
|
||||
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)]
|
||||
failed = 0
|
||||
for fn in fns:
|
||||
try:
|
||||
fn(); print(f" ok: {fn.__name__}")
|
||||
except Exception:
|
||||
failed += 1; print(f" FAIL: {fn.__name__}"); traceback.print_exc()
|
||||
print("ALL PASS" if not failed else f"{failed} FAILED")
|
||||
sys.exit(failed)
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Real-тест gsfx_deep на НАСТОЯЩИХ .gsfx (сервер). Запуск:
|
||||
GSFX_REAL_DIR=/tmp/gsfx_work python3 tests/test_gsfx_deep_real.py
|
||||
Без GSFX_REAL_DIR — тесты пропускаются (локально реальных файлов нет).
|
||||
|
||||
Проверяет: ресурсы+состав работ извлекаются массово, суммы позиций бьются
|
||||
с Properties.Total (медианный ratio в мягкой полосе), и в staging-выходе
|
||||
0 утечек идентификаторов по каждому текстовому полю.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import statistics
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
from gsfx_deep import parse_gsfx_full # noqa: E402
|
||||
from corpus_anon import has_identifier_leak # noqa: E402
|
||||
|
||||
REAL_DIR = os.environ.get("GSFX_REAL_DIR", "")
|
||||
|
||||
|
||||
def _skip() -> bool:
|
||||
if not REAL_DIR or not Path(REAL_DIR).exists():
|
||||
print(" skip: GSFX_REAL_DIR не задан или не существует")
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _texts(obj):
|
||||
if isinstance(obj, str):
|
||||
yield obj
|
||||
elif isinstance(obj, dict):
|
||||
for v in obj.values():
|
||||
yield from _texts(v)
|
||||
elif isinstance(obj, (list, tuple)):
|
||||
for v in obj:
|
||||
yield from _texts(v)
|
||||
|
||||
|
||||
def test_real_resources_and_works_extracted():
|
||||
if _skip():
|
||||
return
|
||||
files = sorted(Path(REAL_DIR).rglob("*.gsfx"))
|
||||
assert files, REAL_DIR
|
||||
n_ok = n_res = n_works = n_price = 0
|
||||
for f in files:
|
||||
r = parse_gsfx_full(f)
|
||||
if "error" in r:
|
||||
continue
|
||||
n_ok += 1
|
||||
for p in r["positions"]:
|
||||
res = p["resources"]
|
||||
if res["workers"] or res["machines"] or res["materials"]:
|
||||
n_res += 1
|
||||
if any(w["price_cur"] for w in res["workers"]):
|
||||
n_price += 1
|
||||
if p["works_list"]:
|
||||
n_works += 1
|
||||
print(f" files_ok={n_ok} pos_with_resources={n_res} "
|
||||
f"pos_with_works={n_works} pos_with_worker_price={n_price}")
|
||||
assert n_ok > 100, n_ok
|
||||
assert n_res > 1000, n_res # ресурсный состав реально извлекается
|
||||
assert n_works > 1000, n_works # состав работ реально извлекается
|
||||
assert n_price > 500, n_price # цены (с запятой) реально парсятся
|
||||
|
||||
|
||||
def test_real_totals_match_properties():
|
||||
if _skip():
|
||||
return
|
||||
ratios = []
|
||||
for f in sorted(Path(REAL_DIR).rglob("*.gsfx")):
|
||||
r = parse_gsfx_full(f)
|
||||
if "error" in r:
|
||||
continue
|
||||
tc = r["totals_check"]
|
||||
# сверяем только сметы с итогом и рабочими позициями
|
||||
if tc["ratio"] and r["positions"]:
|
||||
ratios.append(tc["ratio"])
|
||||
assert len(ratios) > 50, len(ratios)
|
||||
med = statistics.median(ratios)
|
||||
in_band = sum(1 for x in ratios if 0.5 <= x <= 1.5) / len(ratios)
|
||||
print(f" n={len(ratios)} median_ratio={med:.4f} in_band={in_band:.2%}")
|
||||
# медиана в узкой полосе, подавляющее большинство — в мягкой
|
||||
assert 0.85 <= med <= 1.15, med
|
||||
assert in_band >= 0.75, in_band
|
||||
|
||||
|
||||
def test_real_staging_zero_leaks():
|
||||
if _skip():
|
||||
return
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
|
||||
from build_gsfx_staging import build # noqa: E402
|
||||
out = Path(tempfile.mkdtemp())
|
||||
meta = build(Path(REAL_DIR), out)
|
||||
print(" meta:", json.dumps(meta, ensure_ascii=False))
|
||||
staging = json.loads((out / "staging_gsfx.json").read_text(encoding="utf-8"))
|
||||
assert meta["unique_items"] > 100, meta
|
||||
leaks = [t for t in _texts({"items": staging["items"],
|
||||
"materials": staging["materials"]})
|
||||
if has_identifier_leak(t)]
|
||||
assert not leaks, leaks[:10]
|
||||
# у топ-расценок есть состав: ресурсы, работы, НР/СП
|
||||
top = staging["items"][:50]
|
||||
with_res = sum(1 for i in top if i["resources"]["workers"] or i["resources"]["machines"])
|
||||
with_works = sum(1 for i in top if i["works_list"])
|
||||
with_nrsp = sum(1 for i in top if i["overhead"])
|
||||
print(f" top50: with_resources={with_res} with_works={with_works} with_nrsp={with_nrsp}")
|
||||
assert with_res >= 25, with_res
|
||||
assert with_works >= 25, with_works
|
||||
assert with_nrsp >= 25, with_nrsp
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import traceback
|
||||
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)]
|
||||
failed = 0
|
||||
for fn in fns:
|
||||
try:
|
||||
print(f"[{fn.__name__}]"); fn(); print(" ok")
|
||||
except Exception:
|
||||
failed += 1; print(" FAIL"); traceback.print_exc()
|
||||
print("ALL PASS" if not failed else f"{failed} FAILED")
|
||||
sys.exit(failed)
|
||||
@@ -0,0 +1,275 @@
|
||||
"""Тесты scripts/merge_gge.py — staging-расширение анти-фабрикационного корпуса.
|
||||
|
||||
RED-GREEN: написаны ДО реализации. Синтетика (без SSD/сервера): РИМ-смета
|
||||
ДВ-региона (цены 2025), БИМ-смета (базисные, без PriceLevelCur), КА внутри
|
||||
zip-в-zip (как СМ.КА в реальных архивах), фейковый живой индекс для гейта 5×.
|
||||
|
||||
Запуск: python3 tests/test_merge_gge.py (или pytest tests/test_merge_gge.py)
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
|
||||
import merge_gge # noqa: E402
|
||||
|
||||
# РИМ-смета: позиция ГЭСН (код есть в живом индексе → ценовой гейт),
|
||||
# позиция ФЕР (нового кода → merged_new_codes), прямой материал.
|
||||
# В имени позиции — проект-токен «Тумнинская» (scrub обязан вырезать).
|
||||
RIM_TPL = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Construction xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="LocalEstimateResourceIndexMethod-3_01.xsd">
|
||||
<Object><Estimate>
|
||||
<Num>ЛСР-02-01-001</Num>
|
||||
<Region><RegionName>Хабаровский край</RegionName></Region>
|
||||
<PriceLevelBase><Year>2022</Year><Quarter>1</Quarter></PriceLevelBase>
|
||||
<PriceLevelCur><Year>2025</Year><Quarter>3</Quarter></PriceLevelCur>
|
||||
<Sections><Section><Items>
|
||||
<Item>
|
||||
<Cost>
|
||||
<Code>01-01-030-05</Code><Prefix>ГЭСН</Prefix>
|
||||
<Name>Разработка грунта бульдозерами на площадке Тумнинская</Name>
|
||||
<Unit>1000 м3</Unit><QuantityTotal>2</QuantityTotal>
|
||||
<PerUnit><LaborCosts>0</LaborCosts><MachinistLaborCosts>5.5</MachinistLaborCosts></PerUnit>
|
||||
<ResourcesInternal>
|
||||
<Machine><Code>91.01.01-035</Code><Name>Бульдозеры 79 кВт</Name>
|
||||
<Consumption>5.5</Consumption><Unit>маш.-ч</Unit>
|
||||
<PricePerUnitCur>1500</PricePerUnitCur></Machine>
|
||||
</ResourcesInternal>
|
||||
<Totals><Current><Direct>{direct}</Direct><Machines>1600</Machines>
|
||||
<Materials>0</Materials><Salary>400</Salary>
|
||||
<MachinistSalary>400</MachinistSalary><WorkersSalary>0</WorkersSalary></Current></Totals>
|
||||
</Cost>
|
||||
<Overheads><Value>89</Value><Target>ФОТ</Target><Reason>Пр/812-001.1-1</Reason><PriceCur>356</PriceCur></Overheads>
|
||||
<Profits><Value>41</Value><Target>ФОТ</Target><Reason>Пр/774-001.1</Reason><PriceCur>164</PriceCur></Profits>
|
||||
</Item>
|
||||
<Item>
|
||||
<Cost>
|
||||
<Code>ФЕР02-01-001-01</Code><Prefix>ФЕР</Prefix>
|
||||
<Name>Планировка площадей механизированным способом</Name>
|
||||
<Unit>1000 м2</Unit><QuantityTotal>4</QuantityTotal>
|
||||
<Totals><Current><Direct>2000</Direct></Current></Totals>
|
||||
</Cost>
|
||||
</Item>
|
||||
<Item><Material>
|
||||
<Code>ФСБЦ-05</Code><Name>Щебень фракции 20-40</Name><Unit>м3</Unit>
|
||||
<ConsumptionTotal>10</ConsumptionTotal><PricePerUnitCur>1200</PricePerUnitCur>
|
||||
<IsReturnMat>false</IsReturnMat>
|
||||
</Material></Item>
|
||||
</Items></Section></Sections>
|
||||
</Estimate></Object>
|
||||
</Construction>"""
|
||||
|
||||
# БИМ: базисно-индексный метод, PriceLevelCur нет — unit_cost НЕ в текущих
|
||||
# ценах, должна уйти в карантин ЦЕЛИКОМ (файл-уровень).
|
||||
BIM_XML = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Construction xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="LocalEstimateBaseIndexMethod-3_01.xsd">
|
||||
<Object><Estimate>
|
||||
<Num>ЛС-08-01-001</Num>
|
||||
<Region><RegionName>Хабаровский край</RegionName></Region>
|
||||
<PriceLevelBase><Year>2001</Year><Quarter>1</Quarter></PriceLevelBase>
|
||||
<Sections><Section><Items>
|
||||
<Item>
|
||||
<Cost>
|
||||
<Code>08-02-001-01</Code><Prefix>ФЕР</Prefix>
|
||||
<Name>Кладка стен кирпичных наружных</Name>
|
||||
<Unit>м3</Unit><QuantityTotal>10</QuantityTotal>
|
||||
<Totals><Current><Direct>5000</Direct></Current></Totals>
|
||||
</Cost>
|
||||
</Item>
|
||||
</Items></Section></Sections>
|
||||
</Estimate></Object>
|
||||
</Construction>"""
|
||||
|
||||
# КА нового квартала/региона; в имени материала — орг-идентификатор (scrub).
|
||||
# Регион — в Region/RegionName (формат ДВ-корпуса 2025), не Region/Name.
|
||||
KA_XML = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Construction xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="MarketAnalysis-3_01.xsd">
|
||||
<Items><Item>
|
||||
<Name>Шкаф металлический ООО «Вектор» 1860x300</Name><Unit>шт</Unit><Type>оборудование</Type>
|
||||
<Offer>
|
||||
<OfferCompany><CompanyName>ООО Вектор</CompanyName><INN>2724000000</INN></OfferCompany>
|
||||
<OfferPrice><OfferUnitWithoutVAT>10000</OfferUnitWithoutVAT>
|
||||
<EstimateWithoutVAT>10500</EstimateWithoutVAT><OfferWithVAT>12000</OfferWithVAT>
|
||||
<DeliveryTerms>с учетом доставки</DeliveryTerms></OfferPrice>
|
||||
<Region><RegionCode>25</RegionCode><RegionName>г. Владивосток</RegionName></Region>
|
||||
<OfferDate><Year>2025</Year><Quarter>1</Quarter></OfferDate>
|
||||
<OriginCountry>РФ</OriginCountry><Winner>true</Winner>
|
||||
</Offer>
|
||||
</Item></Items>
|
||||
</Construction>"""
|
||||
|
||||
# ОСР-свод без позиций (и без PriceLevelCur): мержить нечего — должен
|
||||
# скипаться, а НЕ падать в карантин с меткой «БИМ».
|
||||
OSR_XML = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Construction xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="ObjectEstimate-3_01.xsd">
|
||||
<Object><Estimate>
|
||||
<Num>ОС-00-01</Num>
|
||||
<Region><RegionName>Хабаровский край</RegionName></Region>
|
||||
</Estimate></Object>
|
||||
</Construction>"""
|
||||
|
||||
# Живой индекс (фейк): код ГЭСН-позиции с эталонной ценой для гейта 5×.
|
||||
LIVE_INDEX = {
|
||||
"meta": {},
|
||||
"items": [{"code": "01-01-030-05", "name": "Разработка грунта бульдозерами",
|
||||
"unit_cost_cur": 1000.0, "freq": 10}],
|
||||
"materials": [{"name": "Щебень фракции 20-40", "price_cur": 1000.0, "freq": 3}],
|
||||
}
|
||||
|
||||
|
||||
def _make_src(tmp: Path, direct: str = "1600"):
|
||||
"""src-каталог: rim.gge + bim.gge на ФС, КА — .gge внутри zip-в-zip."""
|
||||
src = tmp / "src"
|
||||
src.mkdir(exist_ok=True)
|
||||
(src / "rim.gge").write_text(RIM_TPL.format(direct=direct), encoding="utf-8")
|
||||
(src / "bim.gge").write_text(BIM_XML, encoding="utf-8")
|
||||
(src / "osr.gge").write_text(OSR_XML, encoding="utf-8")
|
||||
inner = io.BytesIO()
|
||||
with zipfile.ZipFile(inner, "w") as z:
|
||||
z.writestr("КА-01/MarketAnalysis-3_01.gge", KA_XML)
|
||||
with zipfile.ZipFile(src / "СМ.КА.zip", "w") as z:
|
||||
z.writestr("вложенный.zip", inner.getvalue())
|
||||
live = tmp / "live.json"
|
||||
live.write_text(json.dumps(LIVE_INDEX, ensure_ascii=False), encoding="utf-8")
|
||||
return src, live, tmp / "staging_gge.json"
|
||||
|
||||
|
||||
def test_staging_basic(tmp_path):
|
||||
src, live, out = _make_src(tmp_path)
|
||||
summary = merge_gge.merge(src, live, out)
|
||||
data = json.loads(out.read_text(encoding="utf-8"))
|
||||
|
||||
# summary — обязательные счётчики
|
||||
assert summary["new_files"] == 4 # rim + bim + osr + ka (из zip-в-zip)
|
||||
assert summary["positions"] == 2 # ГЭСН + ФЕР позиции в staged records
|
||||
assert summary["quarantined"] == 1 # только БИМ-файл
|
||||
assert summary["merged_new_codes"] == 1 # ФЕР02-01-001-01 нет в живом
|
||||
assert summary["region"] == "Хабаровский край"
|
||||
assert summary["svod_skipped"] == 1 # ОСР без позиций — скип, не «БИМ»-карантин
|
||||
|
||||
by_code = {r["code"]: r for r in data["records"]}
|
||||
assert set(by_code) == {"01-01-030-05", "ФЕР02-01-001-01"}
|
||||
|
||||
r = by_code["01-01-030-05"]
|
||||
assert r["norm_base"] == "ГЭСН"
|
||||
assert r["price_level"] == "2025"
|
||||
assert r["unit_cost_cur"] == 800.0 # 1600 / 2
|
||||
assert r["regions"] == ["Хабаровский край"] # класс-регион сохранён, НЕ вырезан
|
||||
assert "Тумнин" not in r["name"] and "[…]" in r["name"] # scrub сработал
|
||||
assert r["overhead"]["value"] == "89" and r["profit"]["value"] == "41"
|
||||
assert r["examples"][0]["est"] == "ЛСР-02-01-001"
|
||||
assert by_code["ФЕР02-01-001-01"]["norm_base"] == "ФЕР"
|
||||
|
||||
# БИМ — в карантине целиком, её позиция НЕ в records
|
||||
assert "08-02-001-01" not in by_code
|
||||
q = [q for q in data["quarantine"] if "БИМ" in q["reason"]]
|
||||
assert len(q) == 1 and q[0]["positions"] == 1 and "bim.gge" in q[0]["file"]
|
||||
|
||||
# КА из zip-в-zip: обезличено, новый квартал/регион на месте
|
||||
assert len(data["ka_records"]) == 1
|
||||
ka = data["ka_records"][0]
|
||||
assert "Вектор" not in ka["name"] and ka["name"].startswith("Шкаф металлический")
|
||||
assert ka["offers"][0]["vendor"] == "Поставщик 1"
|
||||
assert ka["offers"][0]["region"] == "г. Владивосток" # города КА — как в живом ka_index
|
||||
assert ka["period"] == "2025 Q1"
|
||||
assert ka["price"]["median"] == 10500.0
|
||||
|
||||
# прямой материал попал в staging materials
|
||||
mat = {m["name"]: m for m in data["materials"]}
|
||||
assert mat["Щебень фракции 20-40"]["price_cur"] == 1200.0
|
||||
|
||||
# 0 утечек по всем свободнотекстовым полям staged-записей
|
||||
leaks = merge_gge.collect_leaks(data["records"]) \
|
||||
+ merge_gge.collect_leaks(data["materials"]) \
|
||||
+ merge_gge.collect_leaks(data["ka_records"])
|
||||
assert leaks == []
|
||||
raw = out.read_text(encoding="utf-8")
|
||||
assert "Тумнин" not in raw and "Вектор" not in raw and "2724000000" not in raw
|
||||
|
||||
|
||||
def test_price_gate(tmp_path):
|
||||
# цена 5000× живой → карантин записи, ФЕР-позиция (нет эталона) остаётся
|
||||
src, live, out = _make_src(tmp_path, direct="10000000") # unit_cost 5 000 000
|
||||
merge_gge.merge(src, live, out)
|
||||
data = json.loads(out.read_text(encoding="utf-8"))
|
||||
codes = {r["code"] for r in data["records"]}
|
||||
assert "01-01-030-05" not in codes and "ФЕР02-01-001-01" in codes
|
||||
q = [q for q in data["quarantine"] if q.get("kind") == "record"]
|
||||
assert len(q) == 1 and "5×" in q[0]["reason"]
|
||||
assert q[0]["record"]["code"] == "01-01-030-05"
|
||||
|
||||
# и нижняя граница: цена в 10 000 раз НИЖЕ живой → тоже карантин
|
||||
tmp2 = tmp_path / "low"
|
||||
tmp2.mkdir()
|
||||
src2, live2, out2 = _make_src(tmp2, direct="0.2") # unit_cost 0.1
|
||||
merge_gge.merge(src2, live2, out2)
|
||||
data2 = json.loads(out2.read_text(encoding="utf-8"))
|
||||
assert "01-01-030-05" not in {r["code"] for r in data2["records"]}
|
||||
assert any("5×" in q["reason"] for q in data2["quarantine"])
|
||||
|
||||
|
||||
def test_leak_gate(tmp_path, monkeypatch):
|
||||
# scrub «промахнулся» (identity) → канарейка has_identifier_leak обязана
|
||||
# отправить запись в карантин, а не молча пропустить в staging
|
||||
monkeypatch.setattr(merge_gge, "scrub", lambda t: t)
|
||||
src, live, out = _make_src(tmp_path)
|
||||
merge_gge.merge(src, live, out)
|
||||
data = json.loads(out.read_text(encoding="utf-8"))
|
||||
assert "01-01-030-05" not in {r["code"] for r in data["records"]}
|
||||
q = [q for q in data["quarantine"] if "утечк" in q["reason"]]
|
||||
assert q and any("Тумнин" in leak for e in q for leak in e["leaks"])
|
||||
|
||||
|
||||
def test_live_index_guard(tmp_path):
|
||||
src, live, _ = _make_src(tmp_path)
|
||||
# писать в файл с именем живого индекса запрещено (fail-loud)
|
||||
try:
|
||||
merge_gge.merge(src, live, tmp_path / "estimates_index.json")
|
||||
assert False, "ожидали ValueError при попытке писать в живой индекс"
|
||||
except ValueError:
|
||||
pass
|
||||
# без живого индекса ценовой гейт не работает → отказ, не тихий пропуск
|
||||
try:
|
||||
merge_gge.merge(src, tmp_path / "нет_такого.json", tmp_path / "s.json")
|
||||
assert False, "ожидали ValueError при отсутствии живого индекса"
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import tempfile
|
||||
|
||||
class _MP: # мини-shim pytest.monkeypatch для запуска без pytest
|
||||
def __init__(self):
|
||||
self._saved = []
|
||||
|
||||
def setattr(self, obj, name, val):
|
||||
self._saved.append((obj, name, getattr(obj, name)))
|
||||
setattr(obj, name, val)
|
||||
|
||||
def undo(self):
|
||||
for obj, name, val in reversed(self._saved):
|
||||
setattr(obj, name, val)
|
||||
|
||||
passed = 0
|
||||
for fn in (test_staging_basic, test_price_gate, test_live_index_guard):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
fn(Path(td))
|
||||
passed += 1
|
||||
print(f"OK {fn.__name__}")
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
mp = _MP()
|
||||
try:
|
||||
test_leak_gate(Path(td), mp)
|
||||
finally:
|
||||
mp.undo()
|
||||
passed += 1
|
||||
print("OK test_leak_gate")
|
||||
print(f"\n{passed}/4 тестов прошли")
|
||||
Reference in New Issue
Block a user