Files
smeta-web/scripts/build_ka_index.py
T
anorandClaude Opus 4.8 78cc18d960 feat: корпус реальных смет/КА/ВОР — поиск расценок, цен и объёмов из сданного проекта
Три обезличенных индекса из базы реального проекта (gge_deep — глубокий разбор
всех схем): расценки с полным ресурсным составом + ценой/накладными/обоснованиями,
КА-цены (winner + офферы поставщиков «Поставщик N»), ВОР-объёмы с формулами расчёта.
Поиск (find_in_real_estimates / find_ka_price / find_in_vor) заведён в smeta_mcp
и tools_glm (активный прод-бэкенд glm). Обезличивание verify_corpus: exit 0.

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

179 lines
7.0 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
import xml.etree.ElementTree as ET
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 scrub # noqa: E402 единый обезличиватель (960-06, пикеты, имя проекта)
MAX_OFFERS = 8 # храним до 8 офферов на материал (показать разброс)
def _txt(el, path: str) -> str:
node = el.find(path)
return (node.text or "").strip() if node is not None and node.text else ""
def _fnum(s: str) -> float:
try:
return float(s)
except (ValueError, TypeError):
return 0.0
def _parse_ka_gge(data: bytes) -> list[dict]:
"""Разобрать КА .gge → список материалов с обезличенными офферами."""
try:
root = ET.fromstring(data)
except ET.ParseError:
return []
items = []
for item in root.iter("Item"):
name = scrub(_txt(item, "Name"))
if not name:
continue
unit = _txt(item, "Unit")
mtype = _txt(item, "Type")
offers = []
for n, off in enumerate(item.findall("Offer"), 1):
price_unit = _fnum(_txt(off, "OfferPrice/OfferUnitWithoutVAT")) \
or _fnum(_txt(off, "OfferPrice/OfferWithoutVAT"))
price_vat = _fnum(_txt(off, "OfferPrice/OfferWithVAT"))
region = _txt(off, "Region/Name")
year = _txt(off, "OfferDate/Year")
quarter = _txt(off, "OfferDate/Quarter")
winner = _txt(off, "Winner").lower() == "true"
country = _txt(off, "OriginCountry")
if price_unit <= 0:
continue
offers.append({
"vendor": f"Поставщик {n}", # обезличено
"price": round(price_unit, 2),
"price_vat": round(price_vat, 2) if price_vat else None,
"region": region,
"period": f"{year} Q{quarter}" if year and quarter else year,
"country": country,
"winner": winner,
})
if offers:
items.append({"name": name, "unit": unit, "type": mtype, "offers": offers})
return items
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_gge(z.read(gi)):
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 = [o["price"] for o in rec["offers"] if o["price"] > 0]
winner = next((o["price"] 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()