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
+1 -1
View File
@@ -127,7 +127,7 @@ def clear_session(username: str, tab_id: str):
ALLOWED_EXTENSIONS = {
".xlsx", ".xlsm", ".xlsb", ".xls", ".ods", ".docx", ".doc", ".pdf",
".csv", ".txt", ".xml", ".json", ".yaml", ".yml",
".gge", ".esw", ".ges", ".smr", ".smt", # smeta programs: ГРАНД-Смета, Smeta.RU
".gge", ".gsfx", ".esw", ".ges", ".smr", ".smt", # smeta programs: ГРАНД-Смета, Smeta.RU
".zip", ".rar", ".7z",
}
+1 -1
View File
@@ -188,7 +188,7 @@ def clear_session(username: str, tab_id: str):
ALLOWED_EXTENSIONS = {
".xlsx", ".xlsm", ".xlsb", ".xls", ".ods", ".docx", ".doc", ".pdf",
".csv", ".txt", ".xml", ".json", ".yaml", ".yml",
".gge", ".esw", ".ges", ".smr", ".smt",
".gge", ".gsfx", ".esw", ".ges", ".smr", ".smt",
".zip", ".rar", ".7z",
}
+55
View File
@@ -1,3 +1,58 @@
# МАСТЕР-ПЛАН улучшений по анализу корпуса (2026-07-15, Fable)
Основа: реальный корпус загрузок (8317 файлов) доминируют форматы, которые приложение НЕ
читает; ответы модели не привязаны к «фактически прочитанному». Память: project_format_support_gaps.
Порядок = по пользе/цене. Каждый пункт — отдельный цикл /do (RED-тест → реализация → real-тест).
### Пункт 1 — .gsfx парсер (ГРАНД-Смета новый формат, 555 файлов) — В РАБОТЕ
Готово когда:
- `gge_tools.parse_gsfx_file(path)` открывает .gsfx (zip: Properties.txt + Data.xml cp1251)
и возвращает {code (Attribs.LocNum), name (ConName/Description), region, total (Properties.Total),
positions[{code=@Code, name=@Caption, unit=@Units, quantity=Quantity/@Result}]}; XXE-safe (defusedxml→fallback);
- MCP-tool `parse_gsfx_file` в smeta_mcp + запись в TOOLS; `.gsfx` в ALLOWED_EXTENSIONS обоих bridge;
- RED юнит на СИНТЕТИЧЕСКОМ .gsfx (сам собрал zip) — code/name/total/positions; mutation-safe;
- серверный real-тест на настоящем .gsfx → code=ЛС-07-01-01, total≈16113326.39, positions>0;
- APP_VERSION бампнут; выкат dev2 → прод.
### Пункт 2 — правки промптов (ось «ответы пользователю», главная)
Готово когда (в claude_project_instructions.md И зеркально в claude_bridge_glm._build_system_prompt):
- правило «говори о содержимом файла ТОЛЬКО если прочитал его в этом ответе; иначе — прямо
„не смог прочитать <имя>: <ошибка>“, без домысла»;
- «текущая загрузка ≠ история»: предмет ответа = файлы из последнего сообщения, сверка с ls /data,
учесть КАЖДЫЙ загруженный (разбор или явное «не прочитан»);
- каркас ответа: резюме → цифры (должны сходиться) → «Следующий шаг»; playbook реестра замечаний
(сметный срез + «что делать» по 2-3 критичным);
- код-фикс claude_bridge.py recap «Файлы из диалога — в /data» → «старые могли быть удалены, актуален ls /data»;
- проверка: харнесс dialog_replay / ручной прогон — на «покажи содержимое» при пустом /data модель
говорит «не смог/не вижу», а не пересказывает историю.
### Пункт 3 — .xls (легаси BIFF, 699 файлов; сейчас код ВРЁТ что поддерживает)
Готово когда: `xlrd>=2` в requirements + sandbox; read_xlsx_sheet/_read_work_dir_files/_preprocess_xlsx
открывают .xls через xlrd (или конверсия в csv); RED-тест на реальном .xls → строки читаются;
раньше отдавал «не смог» — теперь данные.
### Пункт 4 — .doc (легаси OLE2, 1568 файлов)
Готово когда: `catdoc` (или antiword) в sandbox Dockerfile; чтение .doc → текст (subprocess) в обоих путях;
RED-тест на реальном .doc → непустой текст. (LibreOffice для таблиц — опционально, +700МБ, позже.)
### Пункт 5 — .docx таблицы (баг GLM: читает только paragraphs)
Готово когда: `_read_work_dir_files` в claude_bridge_glm обходит doc.tables; RED-тест: docx только с
таблицей → её текст попадает в вывод (сейчас пусто).
### Пункт 6 — .arp (Smeta.RU / АРПС 1.10, 294 файла)
Готово когда: парсер АРПС (cp866, `#`-поля по спеке) → позиции/итоги; `.arp/.arps` в ALLOWED;
MCP-tool; RED-тест на реальном .arp.
### Пункт 7 — PDF-OCR (сканы среди 1975 pdf)
Готово когда: tesseract+rus в sandbox; триггер «fitz дал 0 символов → OCR первых N стр»;
real-тест на скан-pdf → непустой текст. Медленно/среднее качество — после форматов выше.
### Пункт 8 — .esw/.oew/.cew/.bma (63, проприетарный бинарь) — честный отказ
Готово когда: на эти форматы — сообщение «формат X не поддерживается, экспортируйте в АРПС/Excel»,
а не тихая ошибка/домысел. Реверс НЕ делаем.
---
# TASK — реализация бэклога (после прод-выката hardening)
Дата: 2026-06-11. Прод на 2026-06-10c. Работаем на dev2, прод — по готовности.
+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 рекурсивно, распарсить.
+1 -1
View File
@@ -138,7 +138,7 @@ MAX_MESSAGE_LEN = 10_000
# ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква).
# Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version).
APP_VERSION = "2026-07-15b"
APP_VERSION = "2026-07-15c"
# Audit: path → action name mapping
_AUDIT_MAP = [
+45
View File
@@ -267,6 +267,33 @@ def tool_parse_gge_file(*, filename: str, max_positions: int = 30) -> dict:
return data
def tool_parse_gsfx_file(*, filename: str, max_positions: int = 30) -> dict:
"""Распарсить одну .gsfx смету (ГРАНД-Смета, новый формат). filename —
относительный путь в work_dir или внутри распакованной папки.
Возвращает: code, name, region, total (итог сметы), первые max_positions
позиций (code=шифр ГЭСН/ФССЦ, name, unit, quantity). Родной формат
ГРАНД-Сметы — до этого приложение его не читало.
"""
user, tab = _user_tab()
work_dir = _work_dir(user, tab)
candidate = work_dir / filename
if not candidate.exists():
matches = list(work_dir.rglob(Path(filename).name))
if not matches:
return {"error": f"«{filename}» не найден в {user}/{tab}"}
candidate = matches[0]
from gge_tools import parse_gsfx_file
data = parse_gsfx_file(candidate)
if 'error' in data:
return data
if len(data['positions']) > max_positions:
data['positions_total'] = len(data['positions'])
data['positions'] = data['positions'][:max_positions]
data['positions_truncated'] = True
return data
def tool_update_xlsx_cells(*, filename: str, sheet: str,
updates: list, out_filename: str | None = None) -> dict:
"""Массовая запись ячеек в xlsx. Универсальный tool — годится для
@@ -469,6 +496,24 @@ TOOLS: dict[str, dict] = {
"required": ["filename"],
},
},
"parse_gsfx_file": {
"fn": tool_parse_gsfx_file,
"description": (
"Распарсить одну .gsfx смету (ГРАНД-Смета, НОВЫЙ формат — zip с "
"Data.xml внутри). Возвращает: code (шифр ЛС), name, region, total "
"(итог сметы, руб), positions (позиции: code=шифр ГЭСН/ФССЦ, name, "
"unit, quantity). ИСПОЛЬЗУЙ для файлов .gsfx — это родной формат "
"ГРАНД-Сметы, самой массовой сметной программы. Для .gge — parse_gge_file."
),
"inputSchema": {
"type": "object",
"properties": {
"filename": {"type": "string", "description": "Путь к .gsfx относительно work_dir (или basename — будет найден)"},
"max_positions": {"type": "integer", "description": "Лимит позиций в ответе (default 30)"},
},
"required": ["filename"],
},
},
"update_xlsx_cells": {
"fn": tool_update_xlsx_cells,
"description": (
+84
View File
@@ -0,0 +1,84 @@
"""Юнит-тест parse_gsfx_file на СИНТЕТИЧЕСКОМ .gsfx (сам собираю zip с
Properties.txt + Data.xml в cp1251). Реальный .gsfx проверяется отдельно на сервере.
Mutation-safe: сломай извлечение @Code/Total → соответствующий assert упадёт."""
import os
import sys
import tempfile
import zipfile
from pathlib import Path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from gge_tools import parse_gsfx_file
PROPS = (
"DocType=sdtSmeta\r\n"
"Attribs.LocNum=ЛС-07-01-01\r\n"
"Attribs.ConName=Электрификация путей\r\n"
"Attribs.Description=Наружное освещение\r\n"
"Total=16113326.39\r\n"
"RegionInfo.RegionName=ФСНБ-2022 (с Изм. 1-12)\r\n"
)
DATA = (
'<?xml version="1.0" encoding="windows-1251"?>\r\n'
'<Document ProgramVersion="14.3" Generator="GrandSmeta">\r\n'
' <Chapter>\r\n'
' <Position Number="1" Code="ГЭСНм08-03-596-08" Caption="Прожектор на мачте" Units="100 шт">\r\n'
' <Quantity Fx="24/100" Result="0,24"/>\r\n'
' </Position>\r\n'
' <Position Number="2" Code="ФССЦ-01.2.03" Caption="Кабель силовой" Units="1000 м">\r\n'
' <Quantity Result="1,5"/>\r\n'
' </Position>\r\n'
' </Chapter>\r\n'
'</Document>\r\n'
)
def _make_gsfx(dirpath: Path) -> Path:
p = dirpath / "смета.gsfx"
with zipfile.ZipFile(p, "w") as z:
z.writestr("Properties.txt", PROPS.encode("cp1251"))
z.writestr("Data.xml", DATA.encode("cp1251"))
z.writestr("Data.sign", b"\x00\x01")
return p
def test_header_from_properties():
d = Path(tempfile.mkdtemp())
r = parse_gsfx_file(_make_gsfx(d))
assert "error" not in r, r
assert r["code"] == "ЛС-07-01-01", r
assert r["name"] == "Электрификация путей", r
assert abs(r["total"] - 16113326.39) < 0.01, r
assert "ФСНБ-2022" in r["region"], r
def test_positions_from_dataxml():
d = Path(tempfile.mkdtemp())
r = parse_gsfx_file(_make_gsfx(d))
assert r["positions_count"] == 2, r
p0 = r["positions"][0]
assert p0["code"] == "ГЭСНм08-03-596-08", p0
assert p0["name"] == "Прожектор на мачте", p0
assert p0["unit"] == "100 шт", p0
assert abs(p0["quantity"] - 0.24) < 1e-6, p0
def test_bad_zip_returns_error():
d = Path(tempfile.mkdtemp())
bad = d / "broken.gsfx"
bad.write_bytes(b"not a zip at all")
r = parse_gsfx_file(bad)
assert "error" in r, r
if __name__ == "__main__":
import traceback
fns = [v for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)]
failed = 0
for fn in fns:
try:
fn(); print(f" ok: {fn.__name__}")
except Exception:
failed += 1; print(f" FAIL: {fn.__name__}"); traceback.print_exc()
print("ALL PASS" if not failed else f"{failed} FAILED")
sys.exit(failed)
+32
View File
@@ -0,0 +1,32 @@
"""Real-тест parse_gsfx_file на настоящем .gsfx (гонять на dev2).
Извлекает один .gsfx из реального архива и парсит.
Запуск: cd ~/smeta-web-dev2 && python3 test_gsfx_server.py"""
import shutil
import sys
import tempfile
import zipfile
from pathlib import Path
from gge_tools import parse_gsfx_file
SRC = Path("/home/mcp-user/smeta-web-data/smeta/b1f47437-2254-4267-a584-4d2ea050e100/АРХИВ ОБЩИЙ_Гранд-смета.zip")
tmp = Path(tempfile.mkdtemp())
with zipfile.ZipFile(SRC) as z:
name = next(n for n in z.namelist() if n.lower().endswith(".gsfx"))
p = tmp / "s.gsfx"
p.write_bytes(z.read(name))
r = parse_gsfx_file(p)
assert "error" not in r, r
print(f" code={r['code']} | total={r['total']} | positions={r['positions_count']} | region={r['region'][:28]}")
assert r["code"] == "ЛС-07-01-01", r["code"]
assert abs(r["total"] - 16113326.39) < 1.0, r["total"]
assert r["positions_count"] > 0, r
p0 = r["positions"][0]
assert p0["code"] and p0["name"], p0
# quantity>0 у хотя бы одной позиции — ловит баг русской запятой в Result.
assert any(p["quantity"] > 0 for p in r["positions"]), "все quantity == 0 (запятая?)"
print(f" пример позиции: {p0}")
shutil.rmtree(tmp, ignore_errors=True)
print("ALL PASS")