Ре-аудит покрытия .gge: добавлено что выбрасывалось — индекс пересчёта ресурсов с обоснованием, детали машинистов, структура стоимости расценки (машины/материалы/ зарплата), comment позиции, накладные/прибыль в рублях, возвратные материалы. Фикс Transport (цена из PricePerUnitCur, была 0). КА: сметная цена EstimateWithoutVAT (идёт в смету, ≠ рыночная) + склад + перевозка. Все парсеры сведены в gge_deep (parse_ka перенесён из build-скрипта), убраны дубли хелперов. Добавлены юнит-тесты парсеров (tests/test_gge_deep.py, 4/4). verify_corpus exit 0, обезличивание чисто (email/телефон/ИНН = 0). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
135 lines
5.5 KiB
Python
135 lines
5.5 KiB
Python
"""build_ka_index — индекс конъюнктурного анализа (КА) цен из zip-прайсов.
|
|
|
|
Источник: 3.Прайс/*.zip, внутри каждого — КА-смета в .gge (схема
|
|
MarketAnalysis-3_01.xsd) + PDF коммерческих предложений. Извлекаем из .gge
|
|
структурные цены: материал → офферы поставщиков → цена/регион/квартал →
|
|
победитель. PDF не трогаем (цены уже в XML).
|
|
|
|
КА — самая трудоёмкая часть сметы (3 прайса на каждый материал). Этот индекс
|
|
даёт ассистенту «материал → реальная рыночная цена с разбросом по поставщикам».
|
|
|
|
Обезличивание: поставщики → «Поставщик N» (ordinal), вычищаем CompanyName,
|
|
ИНН, КПП, сайт, склад, OfferCode (содержит ИНН), имя PDF, ObjectName, ФИО.
|
|
Остаются техника+цена: материал, ед.изм, цена(ы), регион, квартал, победитель.
|
|
|
|
Запуск:
|
|
python3 scripts/build_ka_index.py "<путь к базе>" [--out data/real_corpus]
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import statistics
|
|
import sys
|
|
import zipfile
|
|
from collections import defaultdict
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
|
from gge_tools import _decode_zip_name # noqa: E402
|
|
from gge_deep import parse_ka, scrub # noqa: E402 общий парсер + обезличиватель
|
|
|
|
MAX_OFFERS = 8 # храним до 8 офферов на материал (показать разброс)
|
|
|
|
|
|
def _offer_price(o: dict) -> float:
|
|
"""Цена для статистики: СМЕТНАЯ (идёт в смету), fallback — рыночная оффера."""
|
|
return o.get("estimate_price") or o.get("market_price") or 0.0
|
|
|
|
|
|
def build(price_dir: Path, out_dir: Path) -> dict:
|
|
agg: dict[str, dict] = {}
|
|
n_zip = n_items = n_no_gge = 0
|
|
regions_seen: set[str] = set()
|
|
periods_seen: set[str] = set()
|
|
|
|
for zp in sorted(price_dir.glob("*.zip")):
|
|
n_zip += 1
|
|
try:
|
|
z = zipfile.ZipFile(zp)
|
|
except zipfile.BadZipFile:
|
|
continue
|
|
gge_infos = [i for i in z.infolist()
|
|
if _decode_zip_name(i).lower().endswith(".gge")]
|
|
if not gge_infos:
|
|
n_no_gge += 1
|
|
continue
|
|
for gi in gge_infos:
|
|
for mat in parse_ka(z.read(gi)):
|
|
mat["name"] = scrub(mat["name"])
|
|
if not mat["name"]:
|
|
continue
|
|
n_items += 1
|
|
key = mat["name"].lower()
|
|
rec = agg.get(key)
|
|
if rec is None:
|
|
rec = agg[key] = {
|
|
"name": mat["name"], "unit": mat["unit"],
|
|
"type": mat["type"], "offers": [],
|
|
"regions": defaultdict(int), "periods": defaultdict(int),
|
|
}
|
|
for o in mat["offers"]:
|
|
if o["region"]:
|
|
rec["regions"][o["region"]] += 1
|
|
regions_seen.add(o["region"])
|
|
if o["period"]:
|
|
rec["periods"][o["period"]] += 1
|
|
periods_seen.add(o["period"])
|
|
if len(rec["offers"]) < MAX_OFFERS:
|
|
rec["offers"].append(o)
|
|
|
|
items = []
|
|
for rec in agg.values():
|
|
prices = [p for p in (_offer_price(o) for o in rec["offers"]) if p > 0]
|
|
winner = next((_offer_price(o) for o in rec["offers"] if o["winner"]), None)
|
|
pstat = {}
|
|
if prices:
|
|
pstat = {
|
|
"min": round(min(prices), 2),
|
|
"median": round(statistics.median(prices), 2),
|
|
"max": round(max(prices), 2),
|
|
"winner": winner,
|
|
}
|
|
regs = sorted(rec["regions"], key=rec["regions"].get, reverse=True)
|
|
pers = sorted(rec["periods"], key=rec["periods"].get, reverse=True)
|
|
items.append({
|
|
"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": pstat,
|
|
})
|
|
items.sort(key=lambda x: len(x["offers"]), reverse=True)
|
|
|
|
out_dir.mkdir(parents=True, exist_ok=True)
|
|
index = {
|
|
"meta": {
|
|
"zip_files": n_zip, "zip_without_gge": n_no_gge,
|
|
"ka_items_raw": n_items, "unique_materials": len(items),
|
|
"regions": sorted(regions_seen), "periods": sorted(periods_seen),
|
|
},
|
|
"items": items,
|
|
}
|
|
(out_dir / "ka_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()
|
|
price_dir = Path(args.base) / "3.Прайс"
|
|
if not price_dir.exists():
|
|
print(f"Не найдено 3.Прайс в {args.base}", file=sys.stderr)
|
|
sys.exit(1)
|
|
out = Path(args.out)
|
|
if not out.is_absolute():
|
|
out = Path(__file__).resolve().parent.parent / out
|
|
meta = build(price_dir, out)
|
|
print(json.dumps(meta, ensure_ascii=False, indent=2))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|