Три глубоких парсера (Fable): merge_gge (РИМ .gge регион ДВ/цены 2025), gsfx_deep (ресурсы+ состав работ+НР/СП+источник цены из 555 .gsfx), arp_deep (ОСНБЖ ж/д: Кнр/Ксп/Кизв+ресурсы, объём f26 численно верифицирован, сверка с парной .xls). Анти-отравление: каждая запись несёт norm_base+price_level, БИМ-сметы 2001 и ценовые выбросы 5× → карантин, обезличено corpus_anon (0 утечек). Сведено в ОТДЕЛЬНЫЙ estimates_ext_index.json (1891 расценка+1703 мат+1114 КА) — живой ВСЖМ-индекс не тронут; _load_estimates/_load_ka грузят оба; find_in_real_estimates отдаёт norm_base/price_level; _search_corpus предупреждает «не смешивай базы/уровни цен». Попутно: gge_deep KA-регион fallback, corpus_anon +паттерн ИНН в underscore. Все тесты (юнит mutation-safe + real-data) зелёные, регресс ВСЖМ цел. APP_VERSION→2026-07-16a. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
494 lines
23 KiB
Python
494 lines
23 KiB
Python
"""merge_gge — staging-расширение анти-фабрикационного корпуса из новых .gge.
|
||
|
||
Дорожная карта #2: РИМ-сметы (Дальний Восток, цены 2025) → staging_gge.json.
|
||
Живой estimates_index.json НЕ модифицируется (guard в merge) — merge в живой
|
||
индекс делается руками после ревью staging.
|
||
|
||
Пайплайн: рекурсивный обход каталога, включая zip-в-zip (СМ.КА кладёт
|
||
MarketAnalysis-3_01.gge во вложенные zip) → parse_estimate_full / parse_ka →
|
||
corpus_anon.scrub КАЖДОГО свободнотекстового поля → три гейта (fail-loud):
|
||
1. БИМ (schema *BaseIndexMethod) ИЛИ нет PriceLevelCur: unit_cost в базисных
|
||
ценах (2001) отравил бы корпус → карантин файла целиком;
|
||
2. канарейка has_identifier_leak по ВСЕМ строковым полям записи → карантин;
|
||
3. unit_cost_cur вне 5× значения этого кода в ЖИВОМ индексе → карантин.
|
||
|
||
Регион: RegionName из .gge — класс-уровень (область/край/республика; поле
|
||
region_class из corpus_anon.ALLOWED_FIELDS) — сохраняется по allow-list-паттерну
|
||
и НЕ прогоняется через scrub: deny-лист режет ДВ-топонимы («Хабаровск…»), а
|
||
класс-регион — ценность корпуса, не идентификатор объекта. Не-класс регион
|
||
(город/станция) через allow-list не проходит и скрабится как свободный текст.
|
||
Города в офферах КА сохраняются — как в живом ka_index (README корпуса).
|
||
|
||
Формат записи = 1:1 items из build_real_corpus + norm_base/price_level,
|
||
чтобы merge после ревью был тривиален.
|
||
|
||
Запуск: python3 scripts/merge_gge.py <src> [--live estimates_index.json] [--out staging_gge.json]
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import io
|
||
import json
|
||
import re
|
||
import statistics
|
||
import sys
|
||
import tempfile
|
||
import zipfile
|
||
from collections import Counter, defaultdict
|
||
from pathlib import Path
|
||
|
||
_ROOT = Path(__file__).resolve().parent.parent
|
||
sys.path.insert(0, str(_ROOT))
|
||
from corpus_anon import has_identifier_leak, scrub # noqa: E402
|
||
from gge_deep import parse_estimate_full, parse_ka # noqa: E402
|
||
from gge_tools import _decode_zip_name # noqa: E402
|
||
|
||
MAX_RES = 30 # как в build_real_corpus
|
||
MAX_OFFERS = 8 # как в build_ka_index
|
||
PRICE_GATE = 5.0 # новая цена вне [live/5, live*5] → карантин
|
||
MAX_ZIP_DEPTH = 4
|
||
|
||
# Класс-уровень региона (allow-list): область/край/республика/АО/города фед. значения.
|
||
_REGION_CLASS_RE = re.compile(
|
||
r"^(?:[А-ЯЁ][а-яё-]+(?:\s+[а-яё-]+)*\s+(?:область|край)"
|
||
r"|Республика\s+[А-ЯЁ][\w ()-]*"
|
||
r"|[А-ЯЁ][а-яё-]+\s+Республика(?:\s+[А-ЯЁ][\w ()-]*)?"
|
||
r"|[А-ЯЁ][\w-]+(?:\s+[А-ЯЁа-яё-]+)*\s+автономн\w+\s+округ(?:\s*[—–-]\s*[\w-]+)?"
|
||
r"|Москва|Санкт-Петербург|Севастополь|Байконур)$")
|
||
|
||
# Ключи-регионы: класс-уровень (сметы) либо города офферов КА как в живом
|
||
# ka_index — из канарейки исключены, валидируются отдельно (_region_class).
|
||
_REGION_KEYS = {"region", "regions"}
|
||
|
||
|
||
def _region_class(raw: str) -> str:
|
||
"""Регион класс-уровня — как есть; иначе это свободный текст → scrub."""
|
||
raw = (raw or "").strip()
|
||
if not raw:
|
||
return ""
|
||
return raw if _REGION_CLASS_RE.match(raw) else scrub(raw)
|
||
|
||
|
||
def collect_leaks(obj, _key: str | None = None) -> list[str]:
|
||
"""Строки с остаточной утечкой идентификатора по всем вложенным полям
|
||
(кроме регион-ключей). Гейт пайплайна И верификация готового staging."""
|
||
if _key in _REGION_KEYS:
|
||
return []
|
||
if isinstance(obj, str):
|
||
return [obj] if has_identifier_leak(obj) else []
|
||
if isinstance(obj, dict):
|
||
return [x for k, v in obj.items() for x in collect_leaks(v, k)]
|
||
if isinstance(obj, (list, tuple)):
|
||
return [x for v in obj for x in collect_leaks(v, _key)]
|
||
return []
|
||
|
||
|
||
# ── обход: .gge с ФС + из zip (вложенность до MAX_ZIP_DEPTH) ────────────────
|
||
_extract_n = 0
|
||
|
||
|
||
def _iter_zip(zf: zipfile.ZipFile, label: str, tmp: Path, depth: int):
|
||
global _extract_n
|
||
for info in zf.infolist():
|
||
if info.is_dir():
|
||
continue
|
||
name = _decode_zip_name(info)
|
||
low = name.lower()
|
||
if low.endswith(".gge"):
|
||
_extract_n += 1
|
||
out = tmp / f"{_extract_n:05d}_{Path(name.replace(chr(92), '/')).name}"
|
||
out.write_bytes(zf.read(info))
|
||
yield out, f"{label}::{name}"
|
||
elif low.endswith(".zip") and depth < MAX_ZIP_DEPTH:
|
||
try:
|
||
inner = zipfile.ZipFile(io.BytesIO(zf.read(info)))
|
||
except zipfile.BadZipFile:
|
||
continue
|
||
yield from _iter_zip(inner, f"{label}::{name}", tmp, depth + 1)
|
||
|
||
|
||
def _iter_gge(src: Path, tmp: Path):
|
||
"""yield (путь на диске, origin-метка) для каждого найденного .gge.
|
||
Топ-уровневые zip (сотни МБ) стримятся с диска, вложенные — из памяти."""
|
||
for p in sorted(src.rglob("*")):
|
||
suf = p.suffix.lower()
|
||
if suf == ".gge":
|
||
yield p, str(p.relative_to(src))
|
||
elif suf == ".zip":
|
||
try:
|
||
zf = zipfile.ZipFile(p)
|
||
except zipfile.BadZipFile:
|
||
continue
|
||
yield from _iter_zip(zf, p.name, tmp, 0)
|
||
|
||
|
||
# ── классификаторы записи ───────────────────────────────────────────────────
|
||
def _norm_base(prefix: str) -> str:
|
||
"""ГЭСН/ФЕР по префиксу расценки. ТЕР — семейство ФЕР (базисная
|
||
номенклатура). Пустой префикс в РИМ-смете = ГЭСН (методика 421/пр).
|
||
Не-нормативные префиксы (ФССЦ/ФСБЦ/ФСЭМ — ценники ресурсов) — как есть."""
|
||
p = (prefix or "").upper()
|
||
if "ГЭСН" in p:
|
||
return "ГЭСН"
|
||
if p.startswith("ФЕР") or p.startswith("ТЕР"):
|
||
return "ФЕР"
|
||
return prefix if prefix else "ГЭСН"
|
||
|
||
|
||
def _price_level(price_cur: str) -> str:
|
||
"""Год текущего уровня цен файла («2025 Q3» → «2025»); нет → «базис»."""
|
||
m = re.match(r"\s*(\d{4})", price_cur or "")
|
||
return m.group(1) if m else "базис"
|
||
|
||
|
||
def _norm_set(code: str) -> str:
|
||
c = (code or "").upper()
|
||
return "ОСР" if c.startswith("ОС") else "ЛСР"
|
||
|
||
|
||
# ── извлечение (зеркалит build_real_corpus, но scrub = corpus_anon) ─────────
|
||
def _scrub_resources(res: dict) -> dict:
|
||
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]:
|
||
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 _add_estimate(agg: dict, mat_agg: dict, data: dict, plevel: str,
|
||
regions: Counter) -> int:
|
||
"""Позиции/материалы одного РИМ-файла → агрегаторы. Возвращает n позиций."""
|
||
region = _region_class(data.get("region", ""))
|
||
if region:
|
||
regions[region] += 1
|
||
nset = _norm_set(data.get("code", ""))
|
||
est_code = scrub(data.get("code", ""))
|
||
n_pos = 0
|
||
|
||
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_base": _norm_base(p["prefix"]), "price_level": plevel,
|
||
"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["price_level"] = plevel
|
||
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
|
||
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
|
||
return n_pos
|
||
|
||
|
||
def _add_ka(ka_agg: dict, mats: list[dict], regions: set, periods: set) -> int:
|
||
"""Материалы одного КА-файла → агрегатор (зеркалит build_ka_index)."""
|
||
n = 0
|
||
for mat in mats:
|
||
name = scrub(mat["name"])
|
||
if not name:
|
||
continue
|
||
n += 1
|
||
rec = ka_agg.get(name.lower())
|
||
if rec is None:
|
||
rec = ka_agg[name.lower()] = {
|
||
"name": name, "unit": mat["unit"], "type": mat["type"],
|
||
"offers": [], "regions": defaultdict(int), "periods": defaultdict(int),
|
||
}
|
||
for o in mat["offers"]:
|
||
o["delivery"] = scrub(o.get("delivery", ""))
|
||
if o["region"]:
|
||
rec["regions"][o["region"]] += 1
|
||
regions.add(o["region"])
|
||
if o["period"]:
|
||
rec["periods"][o["period"]] += 1
|
||
periods.add(o["period"])
|
||
if len(rec["offers"]) < MAX_OFFERS:
|
||
rec["offers"].append(o)
|
||
return n
|
||
|
||
|
||
# ── финализация записей ─────────────────────────────────────────────────────
|
||
def _final_item(rec: dict) -> dict:
|
||
qtys = rec["qtys"]
|
||
qstat = {"min": round(min(qtys), 3), "median": round(statistics.median(qtys), 3),
|
||
"max": round(max(qtys), 3)} if qtys else {}
|
||
return {
|
||
"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"],
|
||
"norm_base": rec["norm_base"],
|
||
"price_level": rec["price_level"],
|
||
"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"],
|
||
}
|
||
|
||
|
||
def _load_live(path: Path) -> tuple[dict, dict, set, set]:
|
||
live = json.loads(path.read_text(encoding="utf-8"))
|
||
price_ref = {it["code"]: it["unit_cost_cur"] for it in live.get("items", [])
|
||
if it.get("code") and it.get("unit_cost_cur")}
|
||
mat_ref = {m["name"].lower(): m["price_cur"] for m in live.get("materials", [])
|
||
if m.get("price_cur")}
|
||
keys = {it["code"] or f"~{it['name'].lower()}" for it in live.get("items", [])}
|
||
mat_names = {m["name"].lower() for m in live.get("materials", [])}
|
||
return price_ref, mat_ref, keys, mat_names
|
||
|
||
|
||
def _price_ok(ref: float | None, val: float) -> bool:
|
||
if not ref or not val:
|
||
return True # нет эталона / нет цены — гейтить не по чему
|
||
return ref / PRICE_GATE <= val <= ref * PRICE_GATE
|
||
|
||
|
||
def merge(src: Path, live_path: Path, out_path: Path) -> dict:
|
||
if out_path.name == "estimates_index.json":
|
||
raise ValueError("merge_gge пишет ТОЛЬКО в staging — живой estimates_index.json не трогаем")
|
||
if not live_path.exists():
|
||
raise ValueError(f"Живой индекс не найден: {live_path} — без него ценовой гейт 5× "
|
||
"не работает (fail-loud, тихий пропуск запрещён)")
|
||
price_ref, mat_ref, live_keys, live_mat_names = _load_live(live_path)
|
||
|
||
agg: dict[str, dict] = {}
|
||
mat_agg: dict[str, dict] = {}
|
||
ka_agg: dict[str, dict] = {}
|
||
quarantine: list[dict] = []
|
||
regions: Counter = Counter()
|
||
ka_regions: set[str] = set()
|
||
ka_periods: set[str] = set()
|
||
n_files = n_err = n_pos_parsed = n_ka_files = n_ka_items = n_vor = n_svod = 0
|
||
|
||
with tempfile.TemporaryDirectory(prefix="merge_gge_") as td:
|
||
for path, origin in _iter_gge(src, Path(td)):
|
||
data = parse_estimate_full(path)
|
||
n_files += 1
|
||
if "error" in data:
|
||
n_err += 1
|
||
continue
|
||
schema = data.get("schema", "")
|
||
if "MarketAnalysis" in schema:
|
||
n_ka_files += 1
|
||
n_ka_items += _add_ka(ka_agg, parse_ka(path.read_bytes()),
|
||
ka_regions, ka_periods)
|
||
continue
|
||
if "QuantityTakeoff" in schema:
|
||
n_vor += 1 # ВОР — вне объёма staging (отдельный индекс)
|
||
continue
|
||
if not data["positions"] and not data.get("direct_materials"):
|
||
n_svod += 1 # ОСР/ССР-свод без расценок — мержить нечего
|
||
continue
|
||
plevel = _price_level(data.get("price_cur", ""))
|
||
if "BaseIndexMethod" in schema or plevel == "базис":
|
||
quarantine.append({
|
||
"kind": "file", "tag": "БИМ", "file": origin, "schema": schema,
|
||
"positions": len(data["positions"]),
|
||
"price_base": data.get("price_base", ""),
|
||
"reason": "БИМ/базисный уровень цен (нет PriceLevelCur) — "
|
||
"unit_cost не в текущих ценах, в корпус нельзя",
|
||
})
|
||
continue
|
||
n_pos_parsed += _add_estimate(agg, mat_agg, data, plevel, regions)
|
||
|
||
# расценки: канарейка утечки → ценовой гейт → staging
|
||
records, n_new_codes = [], 0
|
||
for key, rec in agg.items():
|
||
item = _final_item(rec)
|
||
leaks = collect_leaks(item)
|
||
if leaks:
|
||
quarantine.append({"kind": "record", "tag": "утечка", "record": item,
|
||
"leaks": leaks[:5],
|
||
"reason": "утечка идентификатора после scrub"})
|
||
continue
|
||
if not _price_ok(price_ref.get(item["code"]), item["unit_cost_cur"]):
|
||
quarantine.append({"kind": "record", "tag": "цена", "record": item,
|
||
"reason": f"цена вне 5× живого индекса: live "
|
||
f"{price_ref[item['code']]} vs new {item['unit_cost_cur']}"})
|
||
continue
|
||
if key not in live_keys:
|
||
n_new_codes += 1
|
||
records.append(item)
|
||
records.sort(key=lambda x: x["freq"], reverse=True)
|
||
|
||
# прямые материалы: те же гейты (эталон = медианная цена в живом индексе)
|
||
materials, n_new_mats = [], 0
|
||
for key, mr in mat_agg.items():
|
||
m = {"name": mr["name"], "code": mr["code"], "unit": mr["unit"],
|
||
"freq": mr["freq"],
|
||
"price_cur": round(statistics.median(mr["prices"]), 2) if mr["prices"] else 0.0,
|
||
"regions": sorted(mr["regions"], key=mr["regions"].get, reverse=True)[:3]}
|
||
leaks = collect_leaks(m)
|
||
if leaks:
|
||
quarantine.append({"kind": "material", "tag": "утечка", "record": m,
|
||
"leaks": leaks[:5],
|
||
"reason": "утечка идентификатора после scrub"})
|
||
continue
|
||
if not _price_ok(mat_ref.get(key), m["price_cur"]):
|
||
quarantine.append({"kind": "material", "tag": "цена", "record": m,
|
||
"reason": f"цена вне 5× живого индекса: live "
|
||
f"{mat_ref[key]} vs new {m['price_cur']}"})
|
||
continue
|
||
if key not in live_mat_names:
|
||
n_new_mats += 1
|
||
materials.append(m)
|
||
materials.sort(key=lambda x: x["freq"], reverse=True)
|
||
|
||
# КА-материалы (ka-подобный staging, формат = items живого ka_index)
|
||
ka_records = []
|
||
for rec in ka_agg.values():
|
||
prices = [p for p in ((o.get("estimate_price") or o.get("market_price") or 0.0)
|
||
for o in rec["offers"]) if p > 0]
|
||
winner = next(((o.get("estimate_price") or o.get("market_price"))
|
||
for o in rec["offers"] if o["winner"]), None)
|
||
regs = sorted(rec["regions"], key=rec["regions"].get, reverse=True)
|
||
pers = sorted(rec["periods"], key=rec["periods"].get, reverse=True)
|
||
item = {"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": {"min": round(min(prices), 2), "median": round(statistics.median(prices), 2),
|
||
"max": round(max(prices), 2), "winner": winner} if prices else {}}
|
||
leaks = collect_leaks(item)
|
||
if leaks:
|
||
quarantine.append({"kind": "ka", "tag": "утечка", "record": item,
|
||
"leaks": leaks[:5],
|
||
"reason": "утечка идентификатора после scrub"})
|
||
continue
|
||
ka_records.append(item)
|
||
ka_records.sort(key=lambda x: len(x["offers"]), reverse=True)
|
||
|
||
summary = {
|
||
"new_files": n_files,
|
||
"parse_errors": n_err,
|
||
"positions": sum(r["freq"] for r in records),
|
||
"positions_parsed": n_pos_parsed,
|
||
"quarantined": len(quarantine),
|
||
"quarantine_reasons": dict(Counter(q["tag"] for q in quarantine)),
|
||
"merged_new_codes": n_new_codes,
|
||
"region": regions.most_common(1)[0][0] if regions else "",
|
||
"regions": sorted(regions),
|
||
"records": len(records),
|
||
"price_levels": sorted({r["price_level"] for r in records}),
|
||
"materials_staged": len(materials),
|
||
"new_materials": n_new_mats,
|
||
"ka_files": n_ka_files,
|
||
"ka_items_raw": n_ka_items,
|
||
"ka_materials": len(ka_records),
|
||
"ka_regions": sorted(ka_regions),
|
||
"ka_periods": sorted(ka_periods),
|
||
"vor_skipped": n_vor,
|
||
"svod_skipped": n_svod,
|
||
}
|
||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||
out_path.write_text(json.dumps(
|
||
{"records": records, "materials": materials, "ka_records": ka_records,
|
||
"quarantine": quarantine, "summary": summary},
|
||
ensure_ascii=False), encoding="utf-8")
|
||
return summary
|
||
|
||
|
||
def main() -> None:
|
||
ap = argparse.ArgumentParser(description="Staging-расширение корпуса из .gge (живой индекс не трогает)")
|
||
ap.add_argument("src", help="каталог с .gge / zip-архивами (zip-в-zip поддержан)")
|
||
ap.add_argument("--live", default=str(_ROOT / "data/real_corpus/estimates_index.json"))
|
||
ap.add_argument("--out", default=str(_ROOT / "data/real_corpus/staging_gge.json"))
|
||
args = ap.parse_args()
|
||
src = Path(args.src)
|
||
if not src.is_dir():
|
||
print(f"Не каталог: {src}", file=sys.stderr)
|
||
sys.exit(1)
|
||
summary = merge(src, Path(args.live), Path(args.out))
|
||
print(json.dumps(summary, ensure_ascii=False, indent=2))
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|