Files
smeta-railway/scripts/parse_gge_structure.py
T
anorandClaude Opus 4.6 e45a0734d8 feat: генератор ССР — РАСПРЕДЕЛЕНИЕ + ССРСС из GGE-данных
Скрипт generate_ssr.py генерирует xlsx с двумя листами:
- РАСПРЕДЕЛЕНИЕ: иерархия глава/раздел/ОС/ЛС, суммы Y-AC
- ССРСС: главы 1-7 из GGE + расчётные главы 8-12 + резерв + НДС

Расчётные позиции: временные (332/пр), зимнее (325/пр),
стройконтроль (ПП468), авторский надзор (421/пр).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 23:26:37 +10:00

301 lines
11 KiB
Python
Raw 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.
#!/usr/bin/env python3
"""
Parse GGE files from ZIP → structured project data for SSR generation.
Extracts from each GGE:
- Estimate code (5 groups: etap-glava-razdel-os-num)
- Name
- Totals by WorkType (строительные, монтажные, оборудование, прочие)
- Groups into chapters/sections/OS hierarchy
Usage:
python scripts/parse_gge_structure.py source.zip
python scripts/parse_gge_structure.py source.zip --output project_data.json
"""
import argparse
import json
import re
import sys
import xml.etree.ElementTree as ET
import zipfile
from collections import defaultdict
from datetime import datetime
from pathlib import Path
def fix_zip_encoding(filename: str) -> str:
for enc in ("utf-8", "cp866"):
try:
return filename.encode("cp437").decode(enc)
except (UnicodeDecodeError, UnicodeEncodeError):
continue
return filename
def parse_code(code: str) -> dict | None:
"""Parse estimate code into 5 groups."""
# Remove prefix
clean = re.sub(r"^(ЛСР|ЛС|ОСР|ОС)-", "", code.strip())
m = re.match(r"(\d+)-(\d+)-(\d+)-(\d+)-(\d+)(?:-(\d+))?", clean)
if not m:
return None
groups = m.groups()
return {
"etap": int(groups[0]), # 1: этап строительства
"glava": int(groups[1]), # 2: глава ССР
"razdel": int(groups[2]), # 3: раздел в главе
"os_num": int(groups[3]), # 4: объектная смета (0=одиночная)
"ls_num": int(groups[4]), # 5: порядковый номер ЛС
"sub_num": int(groups[5]) if groups[5] else None, # 6: подномер (если есть)
}
def parse_gge(content: bytes) -> dict | None:
"""Parse GGE XML → structured estimate data."""
try:
root = ET.fromstring(content)
except ET.ParseError:
return None
est = root.find(".//Estimate")
if est is None:
return None
num_el = est.find("Num")
name_el = est.find("Name")
if num_el is None or not num_el.text:
return None
code = num_el.text.strip()
name = (name_el.text or "").strip()
prefix = "ЛСР" # default
if code.startswith(("ОС-", "ОСР-")):
prefix = code.split("-")[0]
elif code.startswith(("ЛС-", "ЛСР-")):
prefix = code.split("-")[0]
parsed_code = parse_code(code)
if not parsed_code:
return None
# Collect totals by WorkType
totals = {"Строительные": 0.0, "Монтажные": 0.0, "Оборудование": 0.0, "Прочие": 0.0}
for section in est.iter("Section"):
# Get section name
sec_name_el = section.find("Name")
sec_name = (sec_name_el.text or "").strip() if sec_name_el is not None else ""
# Determine WorkType
work_type = None
items = section.find("Items")
if items is not None:
for item in items.findall("Item"):
wt = item.find("WorkType")
if wt is not None and wt.text:
work_type = wt.text.strip()
break
# Get section total
sp = section.find("SectionPrice")
if sp is not None:
summary = sp.find("Summary")
if summary is not None:
total_el = summary.find("Total")
if total_el is not None and total_el.text:
total = float(total_el.text)
if work_type == "Перевозка":
totals["Прочие"] += total
elif work_type in totals:
totals[work_type] += total
else:
totals["Строительные"] += total
grand_total = sum(totals.values())
# Fallback
if grand_total == 0:
for ep in est.iter("EstimatePrice"):
t = ep.find("Total")
if t is not None and t.text:
grand_total = float(t.text)
totals["Строительные"] = grand_total
break
return {
"code": code,
"prefix": prefix,
"name": name,
"parsed": parsed_code,
"totals_rub": totals,
"totals_tys": {k: round(v / 1000, 2) for k, v in totals.items()},
"grand_total_rub": grand_total,
"grand_total_tys": round(grand_total / 1000, 2),
}
def build_hierarchy(estimates: list[dict]) -> dict:
"""Build chapter → section → OS → LS hierarchy."""
hierarchy = defaultdict(lambda: {
"name": "",
"razrely": defaultdict(lambda: {
"name": "",
"os": defaultdict(lambda: {
"name": "",
"estimates": [],
"totals_tys": {"Строительные": 0, "Монтажные": 0, "Оборудование": 0, "Прочие": 0},
}),
}),
"totals_tys": {"Строительные": 0, "Монтажные": 0, "Оборудование": 0, "Прочие": 0},
})
chapter_names = {
1: "Подготовка территории строительства",
2: "Основные объекты строительства",
3: "Объекты подсобного и обслуживающего назначения",
4: "Объекты энергетического хозяйства",
5: "Объекты транспортного хозяйства и связи",
6: "Наружные сети и сооружения",
7: "Благоустройство и озеленение территории",
8: "Временные здания и сооружения",
9: "Прочие работы и затраты",
10: "Содержание службы заказчика",
11: "Подготовка эксплуатационных кадров",
12: "Проектные и изыскательские работы",
}
for est in estimates:
p = est["parsed"]
ch = p["glava"]
rz = p["razdel"]
os_num = p["os_num"]
hierarchy[ch]["name"] = chapter_names.get(ch, f"Глава {ch}")
# Add to OS group
os_group = hierarchy[ch]["razrely"][rz]["os"][os_num]
os_group["estimates"].append(est)
# Sum totals
for wtype, val in est["totals_tys"].items():
os_group["totals_tys"][wtype] += val
hierarchy[ch]["totals_tys"][wtype] += val
return dict(hierarchy)
def main():
parser = argparse.ArgumentParser(description="Parse GGE → project structure")
parser.add_argument("zip_file", help="ZIP с GGE-файлами")
parser.add_argument("--output", default=None, help="Output JSON file")
args = parser.parse_args()
if not Path(args.zip_file).exists():
print(f"ZIP not found: {args.zip_file}")
sys.exit(1)
output = args.output or f"project_data_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
# Parse all GGE files
print("Parsing GGE files...")
estimates = []
errors = []
with zipfile.ZipFile(args.zip_file) as z:
gge_infos = [i for i in z.infolist()
if i.filename.lower().endswith(".gge") and i.file_size > 100]
for i, info in enumerate(gge_infos):
if not (info.flag_bits & 0x800):
info.filename = fix_zip_encoding(info.filename)
content = z.read(info)
parsed = parse_gge(content)
if parsed:
parsed["source_file"] = Path(info.filename).name
estimates.append(parsed)
else:
errors.append(info.filename)
if (i + 1) % 300 == 0:
print(f" {i + 1}/{len(gge_infos)}...")
print(f"Parsed: {len(estimates)} estimates, {len(errors)} errors")
# Build hierarchy
print("Building hierarchy...")
hierarchy = build_hierarchy(estimates)
# Summary
print(f"\n=== СТРУКТУРА ПРОЕКТА ===\n")
grand_totals = {"Строительные": 0, "Монтажные": 0, "Оборудование": 0, "Прочие": 0}
for ch_num in sorted(hierarchy):
ch = hierarchy[ch_num]
ch_total = sum(ch["totals_tys"].values())
n_estimates = sum(
len(os_data["estimates"])
for rz in ch["razrely"].values()
for os_data in rz["os"].values()
)
n_os = sum(len(rz["os"]) for rz in ch["razrely"].values())
n_rz = len(ch["razrely"])
print(f" Глава {ch_num}: {ch['name']}")
print(f" Разделов: {n_rz}, ОС: {n_os}, ЛС: {n_estimates}")
print(f" Стр: {ch['totals_tys']['Строительные']:>12,.2f} "
f"Монт: {ch['totals_tys']['Монтажные']:>12,.2f} "
f"Обор: {ch['totals_tys']['Оборудование']:>12,.2f} "
f"Проч: {ch['totals_tys']['Прочие']:>12,.2f} "
f"ИТОГО: {ch_total:>14,.2f} тыс.руб")
for wtype, val in ch["totals_tys"].items():
grand_totals[wtype] += val
grand = sum(grand_totals.values())
print(f"\n ВСЕГО по главам 1-{max(hierarchy.keys())}:")
print(f" Стр: {grand_totals['Строительные']:>12,.2f} "
f"Монт: {grand_totals['Монтажные']:>12,.2f} "
f"Обор: {grand_totals['Оборудование']:>12,.2f} "
f"Проч: {grand_totals['Прочие']:>12,.2f} "
f"ИТОГО: {grand:>14,.2f} тыс.руб")
# Save
result = {
"generated": datetime.now().isoformat(),
"source": args.zip_file,
"total_estimates": len(estimates),
"total_errors": len(errors),
"grand_totals_tys": grand_totals,
"grand_total_tys": grand,
"chapters": {},
}
# Convert hierarchy to serializable format
for ch_num, ch_data in hierarchy.items():
ch_dict = {
"name": ch_data["name"],
"totals_tys": dict(ch_data["totals_tys"]),
"sections": {},
}
for rz_num, rz_data in ch_data["razrely"].items():
rz_dict = {"os_groups": {}}
for os_num, os_data in rz_data["os"].items():
rz_dict["os_groups"][str(os_num)] = {
"totals_tys": dict(os_data["totals_tys"]),
"estimates": [
{
"code": e["code"],
"name": e["name"][:100],
"totals_tys": e["totals_tys"],
"grand_total_tys": e["grand_total_tys"],
}
for e in os_data["estimates"]
],
}
ch_dict["sections"][str(rz_num)] = rz_dict
result["chapters"][str(ch_num)] = ch_dict
with open(output, "w", encoding="utf-8") as f:
json.dump(result, f, ensure_ascii=False, indent=2)
print(f"\nSaved: {output}")
if __name__ == "__main__":
main()