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>
This commit is contained in:
anor
2026-07-15 20:39:27 +10:00
co-authored by Claude Opus 4.8
parent 7074f0f5dc
commit 59aeb54aa1
8 changed files with 300 additions and 3 deletions
+81
View File
@@ -168,6 +168,87 @@ def parse_gge_file(path: Path) -> dict:
}
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 рекурсивно, распарсить.