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:
@@ -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()
|
||||
Reference in New Issue
Block a user