feat: ресурсная смета v2 в формате "Строительный эксперт"

- 27 колонок, merged cells, полный формат образца
- Ресурсная разбивка каждой ГЭСН-нормы (ОТ, ЭМ, МАТ)
- Усложняющие коэффициенты: К_движение=1.60, К_ВЛ=1.20, К_окно=1.81
- Индексы ФГИС ЦС к каждому ресурсу индивидуально
- НР=109%, СП=65% по каждой позиции
- Транспортная схема Свиягино–Спасск-Дальний
- Сварка РСП-19: КП 8129.21 руб/стык
- 1074 строки, 48 позиций, итого 110 727 тыс. руб.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-20 13:16:54 +10:00
co-authored by Claude Opus 4.6
parent 9a5fbe0c86
commit bfe5479424
5 changed files with 3279 additions and 0 deletions
+167
View File
@@ -0,0 +1,167 @@
"""
Усложняющие коэффициенты для капремонта пути.
Техническая часть ГЭСН-2022, Сборник 28 «Железные дороги».
Участок: зона движения 91-108 поездов/сутки, зона ВЛ, работы в «окно».
Коды коэффициентов:
2022-13-ГЭСН-ПР-28-01-1.1.8-000 — движение 91-108 поездов/сутки
2022-13-ГЭСН-ПР-28-01-1.2-000 — вблизи объектов под напряжением (ВЛ)
2022-13-ГЭСН-ПР-28-01-1.3.1-000 — в «окно» с прекращением движения
Правила применения (ТЧ сб. 28, п. 1.1–1.3):
- К_движение (1.1.8): применяется к ЗТ, ЭМ, ЗТм — ко ВСЕМ нормам сб. 28
- К_ВЛ (1.2): применяется к ЭМ, ЗТм (НЕ к ЗТ рабочих)
- К_окно (1.3.1): применяется к ЭМ, ЗТм (НЕ к ЗТ рабочих).
Применяется ТОЛЬКО к нормам, в которых предусмотрены
путевые машины (ЩОМ, ВПО, ПРСМ, краны, тепловозы и т.д.),
НЕ применяется к ручным работам (замена скреплений и т.п.)
и НЕ к транспортным расценкам ФССЦпг.
"""
# Значения коэффициентов
K_DVIZHENIE = 1.60 # п. 1.1.8: 91-108 поездов/сутки
K_VL = 1.20 # п. 1.2: вблизи ВЛ под напряжением
K_OKNO = 1.81 # п. 1.3.1: в «окно» с прекращением движения
# Коды коэффициентов для отображения в смете
COEFF_CODES = {
"dvizhenie": "2022-13-ГЭСН-ПР-28-01-1.1.8-000",
"vl": "2022-13-ГЭСН-ПР-28-01-1.2-000",
"okno": "2022-13-ГЭСН-ПР-28-01-1.3.1-000",
}
COEFF_NAMES = {
"dvizhenie": "Выполнение работ в условиях движения поездов "
"для участков с размерами движения 91-108 поездов/сут",
"vl": "Производство работ вблизи объектов, "
"находящихся под высоким напряжением",
"okno": "Производство работ с прекращением движения "
"поездов по перегону (в «окно»)",
}
def get_coefficients(gesn_code: str) -> dict:
"""
Определить результирующие коэффициенты для нормы ГЭСН.
Returns dict with keys:
zt: коэффициент к затратам труда рабочих
em: коэффициент к эксплуатации машин
ztm: коэффициент к затратам труда машинистов
applied: list of applied coefficient names
formulas: dict with string formulas for display
"""
code = gesn_code.replace("ГЭСН ", "").strip()
# Определяем, какие коэффициенты применяются
# 1. К_движение — ко всем нормам сб. 28
apply_dvizhenie = code.startswith("28-01-")
# 2. К_ВЛ — ко всем нормам сб. 28 (весь участок в зоне ВЛ)
apply_vl = code.startswith("28-01-")
# 3. К_окно — только к нормам с путевыми машинами.
# НЕ применяется к:
# - 28-01-155-xx (замена скреплений — ручные работы)
# - 28-01-043-xx (резка рельсов — ручной станок)
# - 28-01-044-xx (изолирующие стыки — ручные)
# - 01-xx-xxx (земляные работы из сб. 1)
# - ФССЦпг (транспорт)
# - КП (коммерческие предложения)
norms_without_okno = [
"28-01-155-", # замена скреплений (ручные работы)
"28-01-043-", # резка рельсов рельсорезным станком
"28-01-044-", # изолирующие стыки
]
apply_okno = (
code.startswith("28-01-")
and not any(code.startswith(n) for n in norms_without_okno)
)
# Не применяем коэффициенты к нормам НЕ из сб. 28
if not code.startswith("28-01-"):
# Сборник 01 (земляные) — применяем только К_движение если на ж/д путях
# По ТЧ сб. 1 — нет коэффициентов на движение
return {
"zt": 1.0, "em": 1.0, "ztm": 1.0,
"applied": [],
"formulas": {"zt": "", "em": "", "ztm": ""},
}
# Расчёт результирующих коэффициентов
zt = 1.0
em = 1.0
ztm = 1.0
applied = []
parts_zt = []
parts_em = []
parts_ztm = []
if apply_dvizhenie:
zt *= K_DVIZHENIE
em *= K_DVIZHENIE
ztm *= K_DVIZHENIE
applied.append("dvizhenie")
parts_zt.append(f"{K_DVIZHENIE:.2f}")
parts_em.append(f"{K_DVIZHENIE:.2f}")
parts_ztm.append(f"{K_DVIZHENIE:.2f}")
if apply_vl:
# К_ВЛ НЕ применяется к ЗТ рабочих, только к ЭМ и ЗТм
em *= K_VL
ztm *= K_VL
applied.append("vl")
parts_em.append(f"{K_VL:.2f}")
parts_ztm.append(f"{K_VL:.2f}")
if apply_okno:
# К_окно НЕ применяется к ЗТ рабочих, только к ЭМ и ЗТм
em *= K_OKNO
ztm *= K_OKNO
applied.append("okno")
parts_em.append(f"{K_OKNO:.2f}")
parts_ztm.append(f"{K_OKNO:.2f}")
# Формулы для отображения
def formula(parts, result):
if len(parts) == 0:
return ""
if len(parts) == 1:
return f"{parts[0]}"
return "*".join(parts) + f"={result:.4f}"
return {
"zt": round(zt, 4),
"em": round(em, 4),
"ztm": round(ztm, 4),
"applied": applied,
"formulas": {
"zt": formula(parts_zt, zt),
"em": formula(parts_em, em),
"ztm": formula(parts_ztm, ztm),
},
}
if __name__ == "__main__":
# Test
test_codes = [
"ГЭСН 28-01-037-02", # замена рельсов — все 3 коэфф
"ГЭСН 28-01-068-07", # очистка щебня — все 3 коэфф
"ГЭСН 28-01-155-01", # замена скреплений — без «окна»
"ГЭСН 28-01-155-11", # подкладки — без «окна»
"ГЭСН 28-01-043-01", # резка рельсов — без «окна»
"ГЭСН 28-01-044-01", # изолирующие стыки — без «окна»
"ГЭСН 28-01-031-01", # выправка ВПО — все 3 коэфф
"ГЭСН 28-01-041-01", # сварка ПРСМ — все 3 коэфф
"ГЭСН 01-02-057-02", # земляные — без коэфф сб.28
]
for code in test_codes:
c = get_coefficients(code)
applied = ", ".join(c["applied"]) if c["applied"] else "нет"
print(f'{code:30s} | ЗТ={c["zt"]:.4f} | ЭМ={c["em"]:.4f} | '
f'ЗТм={c["ztm"]:.4f} | [{applied}]')
if c["formulas"]["em"]:
print(f'{"":30s} | ЭМ: {c["formulas"]["em"]}')
+346
View File
@@ -0,0 +1,346 @@
#!/usr/bin/env python3
"""
Fetch full resource breakdown for each ГЭСН norm from cs.smetnoedelo.ru.
Parses HTML table and saves to resources.json.
Usage:
python fetch_resources.py # skip already fetched norms
python fetch_resources.py --force # re-fetch all norms
"""
import json
import os
import re
import subprocess
import sys
import time
from html.parser import HTMLParser
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",
]
BASE_URL = "https://cs.smetnoedelo.ru/gesn2/gesn{code}.html"
OUTPUT_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "resources.json")
def fetch_page(code: str) -> str | None:
"""Fetch HTML page bypassing VPN proxy (site is geo-blocked, needs Russian IP)."""
url = BASE_URL.format(code=code)
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:
print(f" [ERROR] curl failed for {code}: rc={result.returncode}")
return None
html = result.stdout
if not html or "<title>" not in html:
print(f" [ERROR] Empty or invalid response for {code}")
return None
return html
except Exception as e:
print(f" [ERROR] Exception fetching {code}: {e}")
return None
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
# Remove spaces (thousands separator), replace comma with dot
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": {},
}
# Find the row with ГЭСН code — it has "ГЭСН XX-XX-XXX-XX" in column 2 (index 1)
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 # current section: 'em' or 'mat'
last_machine_idx = -1
for i, row in enumerate(rows):
cls = classes[i] if i < len(classes) else ""
if len(row) < 3:
continue
# Detect section headers
col2 = row[2].strip() if len(row) > 2 else ""
col1 = row[1].strip() if len(row) > 1 else ""
# ОТ(ЗТ) - labor costs header
if col2 == "ОТ(ЗТ)" and "font-weight-bold" in cls:
section = "ozp"
continue
# Средний разряд line (labor details)
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
# Try column 7 first (всего с учетом коэфф), then 4
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
# ЭМ - equipment section
if col2 == "ЭМ" and "font-weight-bold" in cls:
section = "em"
continue
# ОТм(ЗТм) total machine operator labor (bold, in EM section header)
if col2 in ("ОТм(ЗТм)", "ОТм(Зтм)") and "font-weight-bold" in cls:
# This is the total OTm line, skip it (we capture per-machine OTm)
continue
# М - materials section
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
# ФОТ line (after итого)
if col2 == "ФОТ":
continue
# Machine operator details for preceding machine
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
# Resource rows (machines or materials)
if section == "em" and len(row) >= 10:
code = col1.strip()
# Machine codes look like 91.xx.xx-xxx
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()
# Material codes look like xx.x.xx.xx-xxxx or xx.xx.xx.xx-xxxx
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 the bold summary rows
# Look for ОТ(ЗТ), ЭМ, М bold rows and their values in last column
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 ("ОТм(ЗТм)", "ОТм(Зтм)") and "font-weight-bold" in cls:
result["totals"]["em_zp"] = val
elif col2 == "М":
result["totals"]["mat"] = val
return result
def main():
force = "--force" in sys.argv
# Load existing data
existing = {}
if os.path.exists(OUTPUT_FILE) and not force:
with open(OUTPUT_FILE, "r", encoding="utf-8") as f:
try:
existing = json.load(f)
except json.JSONDecodeError:
existing = {}
results = dict(existing)
fetched = 0
skipped = 0
errors = 0
for code in NORMS:
if code in results and not force:
print(f"[SKIP] {code} (already fetched)")
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
# Detect 404 pages
if "404" in html and "не найден" in html.lower():
print("NOT FOUND (404)")
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_mach = len(parsed.get("machines", []))
n_mat = len(parsed.get("materials", []))
print(f"OK ({n_mach} machines, {n_mat} materials)")
# Save after each successful fetch (crash-safe)
with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
json.dump(results, f, ensure_ascii=False, indent=2)
# Be polite to the server
if code != NORMS[-1]:
time.sleep(2)
# Final save
with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
json.dump(results, f, ensure_ascii=False, indent=2)
print(f"\nDone: {fetched} fetched, {skipped} skipped, {errors} errors")
print(f"Saved to {OUTPUT_FILE}")
if __name__ == "__main__":
main()
+1167
View File
File diff suppressed because it is too large Load Diff
+1599
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.