Files
smeta-web/arp_deep.py
anorandClaude Opus 4.8 13cb936c5c feat: расширение корпуса — .gge(ДВ)/.gsfx/.arp(ОСНБЖ) в ext-индекс (#2-#5)
Три глубоких парсера (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>
2026-07-16 00:18:39 +10:00

250 lines
12 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""arp_deep — глубокий разбор .arp/.arps (АРПС 1.10, Smeta.RU / ПК АВС):
расценки с базисными/текущими стоимостями, РЕАЛЬНО ПРИМЕНЁННЫМИ коэффициентами
(Кнр/Ксп/Кизп/поправочными) и ресурсным составом. База — ОЕРЖ/ОСНБЖ (ж/д).
Семантика полей верифицирована численно на 283 реальных .arp (11900/12000):
итог шапки (тип 3 f14) = Σ по позициям (ПЗтек + (Кнр+Ксп)×(ОТтек+ЗПМтек)) × f26,
сходится с точностью <0.1% на 281/283 файлах → объём позиции = f26 (не f25).
тип 3 — шапка: f4=шифр, f5=имя, f14=итог. f12/f13 = ФИО — НЕ извлекаются (allow-list).
тип 0 — параметры (Метод расчета, Год нормативной базы) и свободные комментарии,
в т.ч. обоснование пересчёта в текущие цены (распоряжение ОАО РЖД → price_level).
тип 10 — раздел: f3=имя.
тип 20 — позиция: f2=обоснование (1-й токен=шифр), f3=ед., f4=имя,
f5..f9 = БАЗИСНЫЕ ПЗ/ОТ/ЭМ/ЗПМ/МР на ед. (2001),
f13/f14 = труд рабочих/машинистов на ед. баз., f23/f24 — с коэф.,
f15..f19 = ТЕКУЩИЕ ПЗ/ОТ/ЭМ/ЗПМ/МР на ед. (с коэф. и индексами), f26=объём.
тип 25 — применённый коэффициент: f1=группа (0=индекс пересчёта Кизп/Киэм/Кимр/…,
2=Кнр, 3=Ксп, 4=поправочный Кзп/Ктрр/Кvмаш/…, 10=Ктр/Кзср),
f2=статья (0=ОТ,1=ЭМ,2=МР,3=ЗПМ,4=ТЗ раб.,5=ТЗ маш.), f4=значение,
f5=имя, f6=обоснование (обычно пусто — обоснования в комментариях типа 0).
тип 30 — ресурс: f1=код (1=труд рабочих, 1.1=средний разряд, 3=труд машинистов),
f2=ед., f3=имя, f4=вид (0=труд,1=машина,2=материал),
f5=расход на ЕД. позиции С УЧЁТОМ коэффициентов, f6=цена базисная 2001
(f6==f7==f8 на всех 68898 записях корпуса).
Обезличивание: свободный текст (имена/обоснования/комментарии/разделы) — через
corpus_anon.scrub; ФИО подписантов и рег.номер не извлекаются вовсе.
Зависимости: stdlib + corpus_anon. Совместимо с sandbox.
"""
from __future__ import annotations
import re
from pathlib import Path
from corpus_anon import scrub
_COEF_GROUPS = {"0": "index", "2": "overhead", "3": "profit",
"4": "adjust", "10": "mat_extra"}
_COEF_TARGETS = {"0": "ОТ", "1": "ЭМ", "2": "МР", "3": "ЗПМ",
"4": "ТЗ раб.", "5": "ТЗ маш.", "10": "МР"}
# пересчёт в текущие цены: «…по распоряжению N1288р от 13.05.2022г…»
_RECALC_RE = re.compile(
r"(?:распоряжени\w+|письму)\D{0,40}?N?[№\s]*(?:[Ии]сх-)?(\d{3,5})\s*/?\s*р?\b"
r".{0,20}?(\d{2}\.\d{2}\.\d{4})", re.DOTALL)
_NORM_BASE_RE = re.compile(r"ОСНБЖ|ОЕРЖ|ОСОЦЖ")
def _rf(s: str) -> float:
"""АРПС пишет десятичные с запятой."""
try:
return float(s.strip().replace(" ", "").replace(",", "."))
except (ValueError, AttributeError):
return 0.0
# шифр расценки/материала: 01-02-058-03, 318533-0003, 500-9004-013*, 204-0100, 1
_CODE_TOKEN_RE = re.compile(r"\d[\d\-.]*\*?")
def _code_from_just(just: str) -> str:
"""Шифр из обоснования. Бывает и «<код> <норм.док>» (28-02-013-01 ОЕРЖ-2001…),
и «<норм.док> <код>» (ОЕРЖм 08-01-121-01) — брать первый КОДОПОДОБНЫЙ токен,
иначе 161 разная расценка склеится под ключом 'ОЕРЖм'. У прайс-позиций
(Т ТЦ_…) кодоподобного токена нет — пустой код, агрегация пойдёт по имени."""
for tok in just.split(" ")[:3]:
if _CODE_TOKEN_RE.fullmatch(tok):
return tok
return ""
def _new_position(f: list[str], section: str) -> dict:
just = f[2].strip()
g = lambda i: _rf(f[i]) if len(f) > i else 0.0 # noqa: E731
return {
"num": f[1].strip(),
"code": _code_from_just(just),
"justification": scrub(just),
"unit": f[3].strip(),
"name": scrub(f[4].strip()),
"section": section,
"quantity": g(26),
"base_costs": {"direct": g(5), "labor": g(6), "machines": g(7),
"machinist": g(8), "materials": g(9)},
"cur_costs": {"direct": g(15), "labor": g(16), "machines": g(17),
"machinist": g(18), "materials": g(19)},
"labor_ch": g(13), "labor_ch_adj": g(23),
"machinist_ch": g(14), "machinist_ch_adj": g(24),
"unit_cost_cur": 0.0, "total_cur": 0.0, # после сбора Кнр/Ксп
"coefficients": [],
"resources": {"workers": [], "machines": [], "materials": []},
}
def _add_coefficient(pos: dict, f: list[str]) -> None:
kind = f[5].strip() if len(f) > 5 else ""
val = _rf(f[4])
if not kind and not val:
return
pos["coefficients"].append({
"kind": kind,
"group": _COEF_GROUPS.get(f[1].strip(), f[1].strip()),
"target": _COEF_TARGETS.get(f[2].strip(), f[2].strip()),
"value": val,
"reason": scrub(f[6].strip()) if len(f) > 6 and f[6].strip() else "",
})
def _add_resource(pos: dict, f: list[str]) -> None:
if len(f) < 6:
return
code, unit, name, flag = f[1].strip(), f[2].strip(), f[3].strip(), f[4].strip()
if code == "1.1": # средний разряд — свойство последнего труд-ресурса
if pos["resources"]["workers"]:
pos["resources"]["workers"][-1]["grade"] = f[5].strip()
return
rec = {"code": code, "name": scrub(name), "unit": unit,
"consumption": _rf(f[5]),
"price_base": _rf(f[6]) if len(f) > 6 else 0.0}
if flag == "1":
pos["resources"]["machines"].append(rec)
elif flag == "2":
pos["resources"]["materials"].append(rec)
else: # 0 = труд (рабочие-строители / машинисты)
rec["grade"] = ""
pos["resources"]["workers"].append(rec)
def _finalize_position(pos: dict) -> None:
"""Полная цена ед. в тек. ценах: ПЗ + НР + СП, где НР/СП = К × (ОТ+ЗПМ).
Формула верифицирована сходимостью с итогом шапки на 281/283 реальных файлах."""
knr = ksp = 0.0
for c in pos["coefficients"]:
if c["target"] == "ОТ":
if c["kind"] == "Кнр":
knr = c["value"]
elif c["kind"] == "Ксп":
ksp = c["value"]
fot = pos["cur_costs"]["labor"] + pos["cur_costs"]["machinist"]
pos["unit_cost_cur"] = round(pos["cur_costs"]["direct"] + (knr + ksp) * fot, 2)
pos["total_cur"] = round(pos["unit_cost_cur"] * pos["quantity"], 2)
def parse_arp_text(text: str, path: str = "") -> dict:
"""Разобрать содержимое .arp (уже декодированное из cp866)."""
code = name = method = base_year = ""
total = 0.0
comments: list[str] = []
positions: list[dict] = []
section = ""
cur: dict | None = None
for line in text.splitlines():
if "#" not in line:
continue
f = line.split("#")
rec = f[0]
if rec == "3" and len(f) > 5:
code = f[4].strip()
name = scrub(f[5].strip())
if len(f) > 14:
total = _rf(f[14])
elif rec == "0" and len(f) > 1:
key = f[1].strip()
val = f[2].strip() if len(f) > 2 else ""
if key.startswith("Метод расчета"):
method = val
elif key == "Год нормативной базы":
base_year = val
elif key == "Регистрационный номер":
continue # идентификатор — не извлекаем
else:
txt = " ".join(x.strip() for x in f[1:] if x.strip())
if len(txt) > 10: # служебную мелочь (Формат и т.п.) не тащим
comments.append(txt)
elif rec == "10" and len(f) > 3:
section = scrub(f[3].strip())
elif rec == "20" and len(f) > 4:
if cur is not None:
_finalize_position(cur)
cur = _new_position(f, section)
positions.append(cur)
elif rec == "25" and len(f) > 5 and cur is not None:
_add_coefficient(cur, f)
elif rec == "30" and cur is not None:
_add_resource(cur, f)
if cur is not None:
_finalize_position(cur)
# пересчёт в тек. цены (пункт #5): распоряжение/письмо из комментариев
recalc = None
for c in comments:
m = _RECALC_RE.search(c)
if m:
recalc = {"doc": m.group(1) + "р", "date": m.group(2), "reason": scrub(c)}
break
if recalc:
price_level = f"тек. {recalc['date'][3:]} (расп. {recalc['doc']})"
elif method.startswith("базисный"):
price_level = "тек. (базисно-индексный, Кизп)"
else:
price_level = ""
# сводка фактических индексов пересчёта (группа 0: Кизп/Киэм/Кимр/Кизпм/Киоб)
kizp_values: dict[str, dict[str, int]] = {}
for p in positions:
for c in p["coefficients"]:
if c["group"] == "index" and c["kind"]:
v = str(c["value"]).replace(".", ",")
kizp_values.setdefault(c["kind"], {})
kizp_values[c["kind"]][v] = kizp_values[c["kind"]].get(v, 0) + 1
kizp_main = None
if kizp_values.get("Кизп"):
top = max(kizp_values["Кизп"].items(), key=lambda kv: kv[1])[0]
kizp_main = _rf(top)
# нормативная база — только по фактическим маркерам (не выдумываем)
hay = " ".join(comments) + " " + " ".join(p["justification"] for p in positions)
norm_base = "ОСНБЖ" if _NORM_BASE_RE.search(hay) else ""
# гейт: итог шапки против суммы позиций по верифицированной формуле
total_computed = round(sum(p["total_cur"] for p in positions), 2)
total_check_ok = bool(total) and abs(total_computed - total) / total < 1e-3
return {
"path": path,
"format": "arp",
"code": code,
"name": name,
"method": method,
"base_year": base_year,
"norm_base": norm_base,
"price_level": price_level,
"recalc": recalc,
"total": total,
"total_computed": total_computed,
"total_check_ok": total_check_ok,
"comments": [scrub(c) for c in comments],
"kizp": {"main": kizp_main, "values": kizp_values},
"positions_count": len(positions),
"positions": positions,
}
def parse_arp_full(path: Path) -> dict:
"""Полный разбор .arp/.arps с диска (cp866)."""
try:
raw = Path(path).read_bytes()
except OSError as e:
return {"error": f"{type(e).__name__}: {e}", "path": str(path)}
return parse_arp_text(raw.decode("cp866", "replace"), path=str(path))