Files
smeta-web/scripts/build_real_corpus.py
anorandClaude Opus 4.8 dc4526c62c fix: коэффициенты как статистика применения, а не свойство расценки
Аудит вскрыл: дедуп брал коэф из одного репрезентативного вхождения, но 6.5%
расценок (97) применялись И с коэф, И без (01-02-061-01: 3 раза с, 851 без).
Хранить один коэф на расценку — вводит в заблуждение («всегда демонтаж»).
Теперь ресурсы = БАЗОВЫЕ нормы ГЭСН (свойство расценки), а коэф вынесен в
coef_applications: with/without + частоты [обоснование, target, factor] по ВСЕМ
вхождениям. Также проверено измерением: ОСР (279) = свод без расценок (0 позиций,
корректно), тихих потерь нет (10270=10270), непокрытые теги — только производные/ID.

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

236 lines
10 KiB
Python

"""build_real_corpus — обогащённый индекс реальных смет (ЛСР/ОСР) из .gge.
Через gge_deep вытаскивает ВСЁ ценное по каждой расценке: ресурсный состав
(рабочие/машины/материалы с нормами расхода и ценами), трудозатраты,
цену/ед (текущую), накладные/прибыль с обоснованиями, коэффициенты, уровни
цен. Дедуп по коду расценки: состав берём из самого полного вхождения,
freq/qty/регионы агрегируем по всем. Прямые материалы (Item/Material) идут
отдельными искомыми позициями с ценой.
Обезличивание: gge_deep.scrub чистит проект-токены (имя проекта, код 960-06,
пикеты ПК); реквизиты/ФИО не извлекаются вовсе.
Запуск: python3 scripts/build_real_corpus.py "<путь к базе>" [--out data/real_corpus]
"""
from __future__ import annotations
import argparse
import json
import statistics
import sys
from collections import Counter, defaultdict
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from gge_deep import parse_estimate_full, scrub # noqa: E402
MAX_RES = 30 # лимит ресурсов каждого типа в карточке
def _norm_set(code: str) -> str:
c = (code or "").upper()
return "ОСР" if c.startswith("ОС") else "ЛСР"
def _scrub_resources(res: dict) -> dict:
# Состав = БАЗОВЫЕ нормы (свойство расценки). Coef убираем отсюда —
# он свойство ПРИМЕНЕНИЯ (одна и та же расценка в 6.5% случаев применялась
# и с коэф, и без), агрегируется отдельно в coef_applications.
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]:
"""Коэффициенты применения позиции (позиционные + ресурсные) как
список (reason, target, factor) для частотной агрегации по расценке."""
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 build(root: Path, out_dir: Path) -> dict:
agg: dict[str, dict] = {}
mat_agg: dict[str, dict] = {}
n_files = n_pos = n_err = n_mat = 0
regions_seen: set[str] = set()
for f in sorted(root.rglob("*.gge")):
data = parse_estimate_full(f)
n_files += 1
if "error" in data:
n_err += 1
continue
region = data.get("region", "")
if region:
regions_seen.add(region)
nset = _norm_set(data.get("code", ""))
est_code = scrub(data.get("code", ""))
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_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["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
n_mat += 1
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
# финализация расценок
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 "",
"prefix": rec["prefix"],
"kind": rec["kind"],
"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"],
})
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"],
"freq": mr["freq"],
"price_cur": round(statistics.median(pr), 2) if pr else 0.0,
"regions": sorted(mr["regions"], key=mr["regions"].get, reverse=True)[:3],
})
materials.sort(key=lambda x: x["freq"], reverse=True)
out_dir.mkdir(parents=True, exist_ok=True)
index = {
"meta": {
"files_parsed": n_files, "parse_errors": n_err,
"positions_total": n_pos, "unique_items": len(items),
"direct_materials_total": n_mat, "unique_materials": len(materials),
"regions": sorted(regions_seen),
},
"items": items,
"materials": materials,
}
(out_dir / "estimates_index.json").write_text(
json.dumps(index, ensure_ascii=False), encoding="utf-8")
return index["meta"]
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("base")
ap.add_argument("--out", default="data/real_corpus")
args = ap.parse_args()
root = Path(args.base) / "2.Сметы"
if not root.exists():
print(f"Не найдено 2.Сметы в {args.base}", 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()