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:
+10
-54
@@ -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 = {
|
||||
|
||||
@@ -75,7 +75,8 @@ def build(root: Path, out_dir: Path) -> dict:
|
||||
"freq": 0, "_best_res": -1,
|
||||
# обогащённые поля (из самого полного вхождения)
|
||||
"unit_cost_cur": 0.0, "labor_ch": 0.0, "machinist_ch": 0.0,
|
||||
"price_base": "", "price_cur": "",
|
||||
"price_base": "", "price_cur": "", "comment": "",
|
||||
"cost_structure": None,
|
||||
"overhead": None, "profit": None, "coefficients": [],
|
||||
"resources": {"workers": [], "machines": [], "materials": []},
|
||||
}
|
||||
@@ -100,6 +101,8 @@ def build(root: Path, out_dir: Path) -> dict:
|
||||
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["coefficients"] = p["coefficients"][:5]
|
||||
@@ -138,7 +141,9 @@ def build(root: Path, out_dir: Path) -> dict:
|
||||
"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"],
|
||||
|
||||
Reference in New Issue
Block a user