feat: полнота извлечения — ресурсные индексы/машинисты, структура стоимости, сметная цена КА

Ре-аудит покрытия .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>
This commit is contained in:
anor
2026-06-09 01:20:59 +10:00
co-authored by Claude Opus 4.8
parent 4e0777e078
commit 6f78d9a32c
9 changed files with 308 additions and 95 deletions
+10 -54
View File
@@ -22,66 +22,19 @@ 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, пикеты, имя проекта)
from gge_deep import parse_ka, scrub # noqa: E402 общий парсер + обезличиватель
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 _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:
@@ -102,7 +55,10 @@ def build(price_dir: Path, out_dir: Path) -> dict:
n_no_gge += 1
continue
for gi in gge_infos:
for mat in _parse_ka_gge(z.read(gi)):
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)
@@ -124,8 +80,8 @@ def build(price_dir: Path, out_dir: Path) -> dict:
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)
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 = {