refactor: декомпозиция монолита в пакет smeta-railway

- Пакетная структура src/smeta_railway/ с модулями calc/, data/, output/
- Pydantic-конфиг: всё через YAML, сметчик не трогает Python
- EstimateCalculator: ядро расчёта, параметризованные коэффициенты
- FGISLookup: pickle cache (4.7с → ~50мс при повторном запуске)
- CLI: smeta generate/fetch-resources/validate (typer)
- 28 тестов (coefficients, overhead, fgis, estimate)
- Исправлен баг: НР/СП для земляных работ (92%/46% вместо 109%/65%)
- ПЗ совпадают бит-в-бит со старым генератором

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-20 18:42:19 +10:00
co-authored by Claude Opus 4.6
parent bfe5479424
commit 897d2d1b76
25 changed files with 4663 additions and 0 deletions
View File
+139
View File
@@ -0,0 +1,139 @@
"""
FGIS CS (ФГИС ЦС) lookup — indices, base prices, current prices.
Loads from fgis_split_form.xlsx with pickle cache for fast restarts.
"""
import os
import pickle
import time
from dataclasses import dataclass, field
import openpyxl
@dataclass
class FGISLookup:
"""Lookup tables built from FGIS split form."""
index_map: dict[str, float] = field(default_factory=dict)
base_price_map: dict[str, float] = field(default_factory=dict)
current_price_map: dict[str, float] = field(default_factory=dict)
labor_price_map: dict[str, float] = field(default_factory=dict)
def get_index(self, code: str) -> float | None:
return self.index_map.get(code)
def get_base_price(self, code: str, fallback: float = 0) -> float:
return self.base_price_map.get(code, fallback)
def get_current_price(self, code: str) -> float | None:
return self.current_price_map.get(code)
def get_labor_price(self, code: str, default: float = 545.28) -> float:
return self.labor_price_map.get(code, default)
def _parse_float(val) -> float | None:
if val is None or val == "-":
return None
try:
return float(val)
except (ValueError, TypeError):
return None
def build_fgis_lookup(xlsx_path: str) -> FGISLookup:
"""Parse fgis_split_form.xlsx and build lookup tables."""
wb = openpyxl.load_workbook(xlsx_path, read_only=True)
ws = wb.active
lookup = FGISLookup()
for row in ws.iter_rows(min_row=1, values_only=True):
code = str(row[0]).strip() if row[0] else ""
if not code or len(code) < 5:
continue
# Labor codes: 1-100-XX or 4-100-XXX
if code.startswith("1-100-") or code.startswith("4-100-"):
price = _parse_float(row[7])
if price is not None:
lookup.labor_price_map[code] = price
continue
# Machine codes (91.xx)
if code.startswith("91."):
bp = _parse_float(row[4])
if bp is not None:
lookup.base_price_map[code] = bp
cp = _parse_float(row[7])
if cp is not None:
lookup.current_price_map[code] = cp
idx = _parse_float(row[8])
if idx is not None:
lookup.index_map[code] = idx
continue
# Material codes
for bp_col in [3, 4]:
bp = _parse_float(row[bp_col])
if bp is not None:
lookup.base_price_map[code] = bp
break
cp = _parse_float(row[7])
if cp is not None:
lookup.current_price_map[code] = cp
idx = _parse_float(row[8])
if idx is not None:
lookup.index_map[code] = idx
wb.close()
return lookup
def load_fgis(xlsx_path: str, cache_path: str | None = None) -> FGISLookup:
"""
Load FGIS lookup with pickle cache.
If cache_path is provided and exists and is newer than xlsx,
loads from pickle (~50ms). Otherwise parses xlsx and saves cache.
"""
if cache_path and os.path.exists(cache_path):
xlsx_mtime = os.path.getmtime(xlsx_path)
cache_mtime = os.path.getmtime(cache_path)
if cache_mtime > xlsx_mtime:
with open(cache_path, "rb") as f:
return pickle.load(f)
t0 = time.monotonic()
lookup = build_fgis_lookup(xlsx_path)
elapsed = time.monotonic() - t0
print(f"FGIS loaded in {elapsed:.2f}s: "
f"{len(lookup.index_map)} indices, "
f"{len(lookup.base_price_map)} base prices, "
f"{len(lookup.current_price_map)} current prices, "
f"{len(lookup.labor_price_map)} labor prices")
if cache_path:
with open(cache_path, "wb") as f:
pickle.dump(lookup, f)
return lookup
def get_labor_code(razryad: float, prefix: str = "1-100-") -> str:
"""Build labor code from razryad: 3.0 -> '1-100-30', 5.0 -> '4-100-050'."""
r = int(round(razryad * 10))
if prefix == "4-100-":
return f"4-100-0{r:02d}"
return f"1-100-{r:02d}"
def get_labor_current_price(
fgis: FGISLookup,
razryad: float,
is_machinist: bool = False,
) -> float:
"""Get current labor price from FGIS lookup."""
prefix = "4-100-" if is_machinist else "1-100-"
code = get_labor_code(razryad, prefix)
return fgis.get_labor_price(code)
+365
View File
@@ -0,0 +1,365 @@
"""
Fetch GESN resource breakdowns from cs.smetnoedelo.ru.
Parses HTML tables and saves to resources.json.
"""
import json
import os
import re
import subprocess
import sys
import time
from html.parser import HTMLParser
from pathlib import Path
from smeta_railway.models import (
LaborResource,
MachineResource,
MaterialResource,
NormResources,
)
class TableParser(HTMLParser):
"""Extract rows from the second table with class 'table-bordered'."""
def __init__(self):
super().__init__()
self.table_count = 0
self.in_target_table = False
self.in_row = False
self.in_cell = False
self.rows: list[list[str]] = []
self.current_row: list[str] = []
self.current_cell = ""
self.row_classes: list[str] = []
self.current_row_class = ""
def handle_starttag(self, tag, attrs):
attrs_dict = dict(attrs)
if tag == "table":
cls = attrs_dict.get("class", "")
if "table-bordered" in cls:
self.table_count += 1
if self.table_count == 2:
self.in_target_table = True
elif self.in_target_table:
if tag == "tr":
self.in_row = True
self.current_row = []
self.current_row_class = attrs_dict.get("class", "")
elif tag == "td" and self.in_row:
self.in_cell = True
self.current_cell = ""
def handle_endtag(self, tag):
if tag == "table" and self.in_target_table:
self.in_target_table = False
elif tag == "tr" and self.in_row and self.in_target_table:
self.rows.append(self.current_row)
self.row_classes.append(self.current_row_class)
self.in_row = False
elif tag == "td" and self.in_cell and self.in_target_table:
self.current_row.append(self.current_cell.strip())
self.in_cell = False
def handle_data(self, data):
if self.in_cell and self.in_target_table:
self.current_cell += data
def parse_number(s: str) -> float | None:
"""Parse a number like '122 149,32' or '337.28'."""
s = s.strip().replace("\xa0", " ").replace("\u00a0", " ")
if not s or s == "-":
return None
s = s.replace(" ", "").replace(",", ".")
try:
return float(s)
except ValueError:
return None
def parse_table(html: str) -> dict | None:
"""Parse the second table-bordered and extract resource breakdown."""
parser = TableParser()
parser.feed(html)
rows = parser.rows
classes = parser.row_classes
if len(rows) < 5:
return None
result = {
"norm_code": None, "norm_name": None, "unit": None,
"ozp": None, "machines": [], "materials": [], "totals": {},
}
for row in rows:
if len(row) >= 4:
m = re.search(
r"ГЭСН\s+(\d{2}-\d{2}-\d{3}-\d{2})",
row[1] if len(row) > 1 else "",
)
if m:
result["norm_code"] = m.group(1)
result["norm_name"] = row[2].strip() if len(row) > 2 else None
result["unit"] = row[3].strip() if len(row) > 3 else None
break
section = None
for i, row in enumerate(rows):
cls = classes[i] if i < len(classes) else ""
if len(row) < 3:
continue
col2 = row[2].strip() if len(row) > 2 else ""
col1 = row[1].strip() if len(row) > 1 else ""
if col2 == "ОТ(ЗТ)" and "font-weight-bold" in cls:
section = "ozp"
continue
if "Средний разряд" in col2 and section == "ozp":
razryad_match = re.search(
r"(\d+[.,]\d+|\d+)",
col2.replace("Средний разряд работы", "")
.replace("Средний разряд -", "")
.replace("Средний разряд", "").strip(),
)
razryad = razryad_match.group(1).replace(",", ".") if razryad_match else None
chel_hours = parse_number(row[4]) if len(row) > 4 else None
if chel_hours is None and len(row) > 6:
chel_hours = parse_number(row[6])
cost_base = parse_number(row[9]) if len(row) > 9 else None
result["ozp"] = {
"razryad": float(razryad) if razryad else None,
"chel_hours": chel_hours,
"cost_base": cost_base,
}
section = None
continue
if col2 == "ЭМ" and "font-weight-bold" in cls:
section = "em"
continue
if col2 in ("ОТм(ЗТм)", "ОТм(Зтм)") and "font-weight-bold" in cls:
continue
if col2 == "М" and "font-weight-bold" in cls:
section = "mat"
continue
if "Итого прямые затраты" in col2:
total_val = parse_number(row[-1]) if row else None
result["totals"]["pz"] = total_val
section = None
continue
if col2 == "ФОТ":
continue
if "text-secondary" in cls and "Средний разряд машинистов" in col2:
razryad_match = re.search(r"(\d+[.,]\d+|\d+)\s*$", col2)
if razryad_match and result["machines"]:
result["machines"][-1]["razryad_mash"] = float(
razryad_match.group(1).replace(",", ".")
)
continue
if section == "em" and len(row) >= 10:
code = col1.strip()
if re.match(r"\d{2}\.\d{2}\.\d{2}-\d{3}", code):
name = col2
unit = row[3].strip() if len(row) > 3 else ""
qty = parse_number(row[4]) if len(row) > 4 else None
if qty is None and len(row) > 6:
qty = parse_number(row[6])
cost_base = parse_number(row[9]) if len(row) > 9 else None
result["machines"].append({
"code": code, "name": name, "unit": unit,
"qty": qty, "cost_base": cost_base,
})
continue
if section == "mat" and len(row) >= 10:
code = col1.strip()
if re.match(r"\d{2}\.\d+\.\d{2}\.\d{2}-\d{4}", code):
name = col2
unit = row[3].strip() if len(row) > 3 else ""
qty = parse_number(row[4]) if len(row) > 4 else None
if qty is None and len(row) > 6:
qty = parse_number(row[6])
cost_base = parse_number(row[9]) if len(row) > 9 else None
result["materials"].append({
"code": code, "name": name, "unit": unit,
"qty": qty, "cost_base": cost_base,
})
continue
# Extract totals from bold summary rows
for i, row in enumerate(rows):
cls = classes[i] if i < len(classes) else ""
if "font-weight-bold" not in cls or len(row) < 3:
continue
col2 = row[2].strip()
val = parse_number(row[-1]) if row else None
if col2 == "ОТ(ЗТ)":
result["totals"]["ozp"] = val
elif col2 == "ЭМ":
result["totals"]["em"] = val
elif col2 in ("ОТм(ЗТм)", "ОТм(Зтм)"):
result["totals"]["em_zp"] = val
elif col2 == "М":
result["totals"]["mat"] = val
return result
def fetch_page(code: str) -> str | None:
"""Fetch HTML page from cs.smetnoedelo.ru."""
url = f"https://cs.smetnoedelo.ru/gesn2/gesn{code}.html"
try:
result = subprocess.run(
["curl", "-s", "--noproxy", "*", "--max-time", "15",
url, "-H", "User-Agent: Mozilla/5.0"],
capture_output=True, text=True,
env={k: v for k, v in os.environ.items()
if k not in ("HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy")},
)
if result.returncode != 0:
return None
html = result.stdout
if not html or "<title>" not in html:
return None
return html
except Exception:
return None
DEFAULT_NORMS = [
"28-01-037-01", "28-01-037-02", "28-01-068-07", "28-01-031-01",
"28-01-041-01", "28-01-155-01", "28-01-155-11", "28-01-155-12",
"28-01-155-13", "28-01-155-14", "28-01-155-15", "28-01-155-16",
"28-01-155-17", "28-01-155-18", "28-01-075-01", "28-01-073-01",
"28-01-054-01", "28-01-027-04", "28-01-007-04", "28-01-043-01",
"28-01-008-01", "28-01-033-01", "28-01-076-01", "28-01-075-02",
"28-01-044-01", "01-02-057-02", "01-01-036-01",
]
def fetch_resources(
output_path: str | Path,
norms: list[str] | None = None,
force: bool = False,
) -> dict:
"""Fetch resources for norms and save to JSON."""
norms = norms or DEFAULT_NORMS
output_path = Path(output_path)
existing: dict = {}
if output_path.exists() and not force:
with open(output_path, encoding="utf-8") as f:
try:
existing = json.load(f)
except json.JSONDecodeError:
existing = {}
results = dict(existing)
fetched = skipped = errors = 0
for code in norms:
if code in results and not force:
print(f"[SKIP] {code}")
skipped += 1
continue
print(f"[FETCH] {code} ...", end=" ", flush=True)
html = fetch_page(code)
if not html:
errors += 1
results[code] = {"error": "fetch_failed"}
continue
if "404" in html and "не найден" in html.lower():
print("NOT FOUND")
errors += 1
results[code] = {"error": "not_found_404"}
time.sleep(2)
continue
parsed = parse_table(html)
if not parsed or not parsed["norm_code"]:
print("PARSE ERROR")
errors += 1
results[code] = {"error": "parse_failed"}
continue
results[code] = parsed
fetched += 1
n_m = len(parsed.get("machines", []))
n_mat = len(parsed.get("materials", []))
print(f"OK ({n_m} machines, {n_mat} materials)")
with open(output_path, "w", encoding="utf-8") as f:
json.dump(results, f, ensure_ascii=False, indent=2)
if code != norms[-1]:
time.sleep(2)
with open(output_path, "w", encoding="utf-8") as f:
json.dump(results, f, ensure_ascii=False, indent=2)
print(f"\nDone: {fetched} fetched, {skipped} skipped, {errors} errors")
return results
def load_resources(path: str | Path) -> dict[str, NormResources]:
"""Load resources.json and convert to NormResources."""
with open(path, encoding="utf-8") as f:
raw = json.load(f)
result: dict[str, NormResources] = {}
for code, data in raw.items():
if "error" in data:
continue
ozp = None
if data.get("ozp"):
o = data["ozp"]
ozp = LaborResource(
razryad=o.get("razryad", 3.0),
chel_hours=o.get("chel_hours", 0),
cost_base=o.get("cost_base"),
)
machines = [
MachineResource(
code=m["code"], name=m["name"], unit=m.get("unit", ""),
qty=m.get("qty", 0), cost_base=m.get("cost_base", 0),
razryad_mash=m.get("razryad_mash"),
)
for m in data.get("machines", [])
]
materials = [
MaterialResource(
code=m["code"], name=m["name"], unit=m.get("unit", ""),
qty=m.get("qty", 0), cost_base=m.get("cost_base", 0),
)
for m in data.get("materials", [])
]
result[code] = NormResources(
norm_code=data.get("norm_code", code),
norm_name=data.get("norm_name"),
unit=data.get("unit"),
ozp=ozp,
machines=machines,
materials=materials,
totals=data.get("totals", {}),
)
return result
+103
View File
@@ -0,0 +1,103 @@
"""
GESN base prices and transport prices.
Separated from monolithic prices.py for clarity.
GESN_PRICES: gesn_code -> (name, unit, base_price, ozp, em, mat, note)
TRANSPORT_PRICES: code -> (name, unit, current_price, ...)
"""
# GESN-2022 base prices (Collection 28, supplement 17)
GESN_PRICES: dict[str, tuple] = {
"28-01-037-01": ("Замена рельсов на плети, КБ, 2000 шп/км",
"км пути", 12_473_450.04, 129_722.09, 77_050.93, 12_266_677.03, ""),
"28-01-037-02": ("Замена рельсов на плети, КБ, 1840 шп/км",
"км пути", 12_464_484.16, 122_149.32, 75_657.81, 12_266_677.03, ""),
"28-01-068-07": ("Глубокая очистка щебня ЩОМ, ж/б, 1840 шп/км",
"км пути", 1_150_086.00, None, None, None, "без разд. слоя"),
"28-01-068-09": ("Глубокая очистка щебня ЩОМ самоходные, ж/б, 1840",
"км пути", 645_635.00, None, None, None, "600-800 м³/ч"),
"28-01-031-01": ("Выправка пути ВПО, 1 проход",
"км", 25_454.00, None, None, None, ""),
"28-01-031-03": ("Выправка пути ВПРМ до 2000 шп/ч, 1 проход",
"км", 70_128.00, None, None, None, ""),
"28-01-041-01": ("Сварка рельсовых плетей ПРСМ",
"2 стыка", 100_481.10, 4_966.32, 95_495.32, None, ""),
"28-01-042-01": ("Сварка стыков алюминотермитным способом",
"2 стыка", 51_406.00, None, None, None, ""),
"28-01-155-01": ("Замена скреплений КБ, 1 класс, средний",
"км", 277_544.00, None, None, None, ""),
"28-01-155-11": ("Подкладки (за 100 шт)", "100 шт", 132_005.00, None, None, None, ""),
"28-01-155-12": ("Болты закладные с гайками (за 100 шт)", "100 шт", 11_211.00, None, None, None, ""),
"28-01-155-13": ("Болты клеммные с гайками (за 100 шт)", "100 шт", 8_867.00, None, None, None, ""),
"28-01-155-14": ("Шайбы двухвитковые (за 100 шт)", "100 шт", 3_384.00, None, None, None, ""),
"28-01-155-15": ("Клеммы промежуточные (за 100 шт)", "100 шт", 11_853.00, None, None, None, ""),
"28-01-155-16": ("Прокладки под рельс (за 100 шт)", "100 шт", 6_478.00, None, None, None, ""),
"28-01-155-17": ("Прокладки под подкладки (за 100 шт)", "100 шт", 20_132.00, None, None, None, ""),
"28-01-155-18": ("Втулки изолирующие (за 100 шт)", "100 шт", 4_815.00, None, None, None, ""),
"28-01-075-01": ("Уборка срезанного балласта", "100 м³", 12_103.84, 4_084.36, 8_019.48, None, ""),
"28-01-073-01": ("Очистка балласта вручную в местах препятствий",
"м", 2_382.79, 1_498.55, 884.24, None, "глубина до 20 см"),
"28-01-054-01": ("Замена РШР бесстыкового пути с резкой плетей",
"км", 435_850.24, 96_890.17, 338_960.08, None, "2000 шп/км"),
"28-01-027-04": ("Балластировка пути, ж/б шпалы, щебень",
"1000 м³", 3_396_794.00, None, None, None, ""),
"28-01-007-04": ("Разборка пути на мостах поэлементно",
"км", 612_447.00, None, None, None, ""),
"28-01-043-01": ("Резка рельсов рельсорезным станком",
"пар резок", 8_432.00, None, None, None, ""),
"28-01-008-01": ("Демонтаж пути поэлементно",
"км", 612_447.00, None, None, None, ""),
"28-01-033-01": ("Балластировка пути на ж/б шпалах",
"м³", 3_396.79, None, None, None, ""),
"28-01-076-01": ("Очистка кюветов МКТ",
"м", 856.00, None, None, None, ""),
"28-01-075-02": ("Формирование бровки з.п., вырезка балласта",
"100 м³", 14_520.00, None, None, None, ""),
"28-01-044-01": ("Устройство изолирующего стыка вварного",
"пара", 45_800.00, None, None, None, ""),
"01-02-057-02": ("Разработка грунта экскаватором ковш 0,65 м³",
"100 м³", 7_853.00, None, None, None, ""),
"01-01-036-01": ("Планировка площадей бульдозером 121 кВт",
"1000 м²", 2_145.00, None, None, None, ""),
}
# Transport prices — FGIS CS, current Q1 2026
TRANSPORT_PRICES: dict[str, tuple] = {
"ФССЦпг-236019-00-0071-0080": (
"Перевозка ж/д транспортом балласта, ХДВ, 73 км",
"1 т груза", 815.96, None, None, None, ""),
"ФССЦпг-236019-00-0001-0005": (
"Перевозка ж/д транспортом балласта (засорители), ХДВ, 5 км",
"1 т груза", 731.17, None, None, None, ""),
"ФССЦпг-371051-04-0071-0080": (
"Перевозка ж/д транспортом металлоконструкций, платформы, 73 км",
"1 т груза", 2_887.50, None, None, None, ""),
"ФССЦпг-371051-04-0071-0080-new": (
"Перевозка ж/д транспортом металлоконструкций (новые), платформы, 73 км",
"1 т груза", 2_887.50, None, None, None, ""),
"ФССЦпг-371051-05-0331-0360": (
"Перевозка ж/д старогодных плетей, сцеп платформ, 337 км",
"1 т груза", 4_171.60, None, None, None, ""),
"ФССЦпг-02-15-1-03-0003": (
"Перевозка автосамосвалами грунта, 3 км",
"1 т груза", 116.12, None, None, None, ""),
"ФССЦпг-01-20-3-01-0012": (
"Перевозка автобортовыми оборудования СЦБ, 12 км",
"1 т груза", 865.92, None, None, None, ""),
}
# Commercial proposals (КП)
KP_PRICES: dict[str, tuple] = {
"КП-РСП-19": ("Сварка рельсов Р65 на РСП-19 ст. Хабаровск-II",
"стык", 8_129.21, None, None, None,
"КП РСП-19, цена текущая Q1 2026, конъюнктурный анализ"),
}
def get_all_prices() -> dict[str, tuple]:
"""Combined dict of all prices for backward compat."""
all_prices = {}
all_prices.update(GESN_PRICES)
all_prices.update(TRANSPORT_PRICES)
all_prices.update(KP_PRICES)
return all_prices