Files
smeta-web/gge_tools.py
T
anorandClaude Opus 4.8 59aeb54aa1 feat: парсер .gsfx (ГРАНД-Смета новый формат) + MCP-tool parse_gsfx_file
Пункт 1 мастер-плана по анализу корпуса: .gsfx (555 файлов) не читался. .gsfx = zip с
Properties.txt (шапка/итог cp1251) + Data.xml (позиции windows-1251). gge_tools.parse_gsfx_file
достаёт code/name/region/total + позиции (Code/Caption/Units/Quantity.Result), XXE-safe
(defusedxml→fallback). MCP-tool parse_gsfx_file + .gsfx в ALLOWED_EXTENSIONS обоих bridge.
Real-тест поймал баг: русская запятая в Result (0,24) → _ru_float. Юнит mutation-safe +
серверный real-тест на настоящем .gsfx (ЛС-07-01-01, 87 позиций, итог 16.1М). APP_VERSION→2026-07-15c.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 20:39:27 +10:00

349 lines
13 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.
"""gge_tools — работа с архивами .gge (XML смет ГГЭ) и xlsx-реестрами.
Универсальный, без привязки к конкретной задаче (ИГИ/ТС). Чат-агент
сам комбинирует tools для нужного сценария.
Зависимости: openpyxl + stdlib (zipfile, xml.etree, json). Без plotly,
sentence-transformers и т.п. — работает в sandbox-контейнере.
"""
from __future__ import annotations
import json
import zipfile
import xml.etree.ElementTree as ET
from pathlib import Path
def _decode_zip_name(info: zipfile.ZipInfo) -> str:
"""Python 3 zipfile авто-декодирует cp437 если флаг UTF-8 (0x800) не задан.
Реальные байты могут быть в UTF-8 (macOS `zip`) или cp866 (Windows-архиватор).
Пробуем оба, берём результат без replacement chars."""
if info.flag_bits & 0x800:
return info.filename
try:
raw = info.filename.encode('cp437')
except UnicodeEncodeError:
return info.filename
for codec in ('utf-8', 'cp866'):
try:
decoded = raw.decode(codec)
if '�' not in decoded:
return decoded
except UnicodeDecodeError:
continue
return info.filename
def extract_archive(zip_path: Path, target_dir: Path) -> dict:
"""Распаковать zip с .gge файлами в target_dir. Сохраняет древовидную
структуру внутри архива. Корректно декодирует cp866-имена.
Возвращает: {target: <abs path>, total_files: N, gge_files: M, skipped: K}
"""
import os
target_dir.mkdir(parents=True, exist_ok=True)
target_resolved = target_dir.resolve()
total = gge = skipped = 0
with zipfile.ZipFile(zip_path) as z:
for info in z.infolist():
if info.is_dir():
continue
total += 1
name = _decode_zip_name(info).replace('\\', '/')
# path traversal guard
out = (target_dir / name).resolve()
try:
out.relative_to(target_resolved)
except ValueError:
skipped += 1
continue
out.parent.mkdir(parents=True, exist_ok=True)
try:
with z.open(info) as src, open(out, 'wb') as dst:
while chunk := src.read(64 * 1024):
dst.write(chunk)
if name.lower().endswith('.gge'):
gge += 1
except Exception:
skipped += 1
return {
'target': str(target_dir),
'total_files': total,
'gge_files': gge,
'skipped': skipped,
}
def parse_gge_file(path: Path) -> dict:
"""Извлечь данные одной сметы из .gge XML.
Возвращает: code, name, schema_kind ('local' | 'object' | 'unknown'),
has_excavation, has_transport_summary, totals (всё что есть в
EstimatePrice/Summary), positions (список dict с name/code/quantity/
unit/price_total из <Cost>; для перевозочных позиций <Transport>
тоже включаем).
"""
try:
tree = ET.parse(str(path))
except (ET.ParseError, OSError) as e:
return {'error': f'{type(e).__name__}: {e}', 'path': str(path)}
root = tree.getroot()
schema_loc = root.attrib.get(
'{http://www.w3.org/2001/XMLSchema-instance}noNamespaceSchemaLocation', '')
if 'LocalEstimate' in schema_loc:
schema_kind = 'local'
elif 'ObjectEstimate' in schema_loc:
schema_kind = 'object'
else:
schema_kind = 'unknown'
code = (root.findtext('.//Estimate/Num') or '').strip()
name = (root.findtext('.//Estimate/Name') or '').strip()
# Totals: EstimatePrice/Summary
totals: dict[str, float] = {}
summary = root.find('.//EstimatePrice/Summary')
if summary is not None:
for child in summary:
if len(list(child)) > 0:
# Materials/Total etc.
for sub in child:
if sub.text:
try:
totals[f'{child.tag}.{sub.tag}'] = float(sub.text.strip())
except ValueError:
pass
elif child.text:
try:
totals[child.tag] = float(child.text.strip())
except ValueError:
pass
# Positions: Item/Cost (work) + Item/Transport (carrier line)
positions: list[dict] = []
has_excavation = False
for it in root.iter('Item'):
for kind_tag in ('Cost', 'Transport'):
node = it.find(kind_tag)
if node is None:
continue
pname = (node.findtext('Name') or '').strip()
if not pname:
continue
pcode = (node.findtext('Code') or '').strip()
qty = node.findtext('Quantity') or ''
unit = (node.findtext('Unit') or '').strip()
ptcur = node.findtext('PriceTotalCur') or ''
direct = node.findtext('.//Totals/Current/Direct') or ''
try: qty_f = float(qty) if qty else 0.0
except ValueError: qty_f = 0.0
try: pt_f = float(ptcur) if ptcur else 0.0
except ValueError: pt_f = 0.0
try: dir_f = float(direct) if direct else 0.0
except ValueError: dir_f = 0.0
positions.append({
'kind': kind_tag.lower(), # 'cost' | 'transport'
'name': pname,
'code': pcode,
'quantity': qty_f,
'unit': unit,
'price_total_cur': pt_f,
'direct': dir_f,
})
if 'разработка грунта' in pname.lower():
has_excavation = True
has_transport_summary = (totals.get('Transport', 0.0) > 0)
return {
'path': str(path),
'code': code,
'name': name,
'schema_kind': schema_kind,
'has_excavation': has_excavation,
'has_transport_summary': has_transport_summary,
'totals': totals,
'positions': positions,
}
def _ru_float(s: str) -> float:
"""ГРАНД пишет десятичные с запятой (Data.xml) или точкой (Properties.txt)."""
if not s:
return 0.0
try:
return float(s.strip().replace(' ', '').replace(',', '.'))
except (ValueError, AttributeError):
return 0.0
def _safe_xml_root(data: bytes):
"""Разобрать XML из байтов, устойчиво к XXE/billion-laughs. defusedxml если
есть (хост/dev), иначе stdlib (минимальный sandbox). data — БАЙТЫ: кодировка
берётся из XML-декларации (windows-1251 у ГРАНД)."""
try:
from defusedxml.ElementTree import fromstring as _fromstring
return _fromstring(data)
except ImportError:
return ET.fromstring(data)
def parse_gsfx_file(path: Path) -> dict:
"""Разобрать .gsfx (ГРАНД-Смета, новый формат). .gsfx — это zip с
Properties.txt (шапка+итог, cp1251) + Data.xml (позиции, windows-1251) + Data.sign.
Возвращает: code (Attribs.LocNum), name (ConName/Description), region, total
(Properties.Total), positions [{code=@Code, name=@Caption, unit=@Units,
quantity=Quantity/@Result}], positions_count.
"""
try:
with zipfile.ZipFile(str(path)) as z:
names = z.namelist()
props_name = next((n for n in names if n.lower().endswith('.txt')), None)
data_name = next((n for n in names if n.lower().endswith('.xml')), None)
props_raw = z.read(props_name) if props_name else b''
data_raw = z.read(data_name) if data_name else b''
except (zipfile.BadZipFile, OSError, KeyError) as e:
return {'error': f'{type(e).__name__}: {e}', 'path': str(path)}
# Properties.txt — key=value, шапка и итог.
props: dict[str, str] = {}
for line in props_raw.decode('cp1251', 'replace').splitlines():
if '=' in line:
k, v = line.split('=', 1)
props[k.strip()] = v.strip()
code = props.get('Attribs.LocNum', '').strip()
name = (props.get('Attribs.ConName') or props.get('Attribs.Description') or '').strip()
region = props.get('RegionInfo.RegionName', '').strip()
total = _ru_float(props.get('Total', ''))
# Data.xml — позиции сметы.
positions: list[dict] = []
if data_raw:
try:
root = _safe_xml_root(data_raw)
except ET.ParseError as e:
return {'error': f'Data.xml ParseError: {e}', 'path': str(path),
'format': 'gsfx', 'code': code, 'name': name, 'total': total}
for pos in root.iter('Position'):
pcode = (pos.attrib.get('Code') or '').strip()
pname = (pos.attrib.get('Caption') or '').strip()
unit = (pos.attrib.get('Units') or '').strip()
qty_el = pos.find('Quantity')
qty = (qty_el.attrib.get('Result') if qty_el is not None else '') or ''
qty_f = _ru_float(qty)
if pname or pcode:
positions.append({'code': pcode, 'name': pname,
'unit': unit, 'quantity': qty_f})
return {
'path': str(path),
'format': 'gsfx',
'code': code,
'name': name,
'region': region,
'total': total,
'positions_count': len(positions),
'positions': positions,
}
def index_gge_directory(dir_path: Path, save_index_to: Path | None = None) -> dict:
"""Пройти все .gge в dir_path рекурсивно, распарсить.
Returns: {by_code: {code: {has_excavation, has_transport_summary,
name, total_rub, schema_kind, path}}, summary: {...}, parse_errors: N}.
Если save_index_to задан — пишет полный индекс (с positions) в JSON.
Возврат компактнее (без positions), чтобы влез в MCP-ответ.
"""
files = sorted(p for p in dir_path.rglob('*.gge'))
by_code: dict[str, dict] = {}
full_index: dict[str, dict] = {}
parse_errors = 0
schemas: dict[str, int] = {}
excav = transp = 0
rub_sum = 0.0
for f in files:
data = parse_gge_file(f)
if 'error' in data:
parse_errors += 1
continue
code = data['code']
if not code:
continue
# Сводный (компактный) вид без positions для MCP-ответа.
compact = {
'name': data['name'],
'schema_kind': data['schema_kind'],
'has_excavation': data['has_excavation'],
'has_transport_summary': data['has_transport_summary'],
'total_rub': data['totals'].get('Total') or data['totals'].get('Price') or 0.0,
'transport_rub': data['totals'].get('Transport', 0.0),
'path': data['path'],
}
prev = by_code.get(code)
if prev is None or compact['total_rub'] > prev['total_rub']:
by_code[code] = compact
full_index[code] = data
schemas[data['schema_kind']] = schemas.get(data['schema_kind'], 0) + 1
if data['has_excavation']:
excav += 1
if data['has_transport_summary']:
transp += 1
rub_sum += compact['total_rub']
summary = {
'files_total': len(files),
'parse_errors': parse_errors,
'unique_codes': len(by_code),
'schemas': schemas,
'with_excavation': excav,
'with_transport_summary': transp,
'sum_total_rub': rub_sum,
}
if save_index_to is not None:
save_index_to.write_text(
json.dumps({'by_code': full_index, 'summary': summary},
ensure_ascii=False),
encoding='utf-8',
)
return {'by_code': by_code, 'summary': summary}
def update_xlsx_cells(src_path: Path, out_path: Path, sheet: str,
updates: list[dict]) -> dict:
"""Записать список ячеек в xlsx.
updates: [{"row": 5, "col": "E" | 5, "value": "ИГИ"}, ...]
Сохраняет копию в out_path. Не трогает остальной контент книги.
"""
import openpyxl
wb = openpyxl.load_workbook(str(src_path))
if sheet not in wb.sheetnames:
return {'error': f'Лист «{sheet}» не найден',
'available_sheets': wb.sheetnames}
ws = wb[sheet]
written = 0
skipped = 0
for u in updates:
try:
row = int(u['row'])
col = u['col']
if isinstance(col, str):
col_idx = openpyxl.utils.column_index_from_string(col)
else:
col_idx = int(col)
ws.cell(row, col_idx).value = u.get('value')
written += 1
except (KeyError, ValueError, TypeError):
skipped += 1
wb.save(str(out_path))
return {
'output_path': str(out_path),
'sheet': sheet,
'cells_written': written,
'cells_skipped': skipped,
}