From 8137bd5b8b08af475ed10d7aa6b89e0867457f5f Mon Sep 17 00:00:00 2001 From: anor Date: Wed, 25 Mar 2026 18:25:11 +1000 Subject: [PATCH] =?UTF-8?q?feat:=20=D0=B0=D0=B2=D1=82=D0=BE=D0=BA=D0=BE?= =?UTF-8?q?=D0=BD=D0=B2=D0=B5=D1=80=D1=82=D0=B0=D1=86=D0=B8=D1=8F=20=D0=BF?= =?UTF-8?q?=D1=80=D0=BE=D0=B1=D0=BB=D0=B5=D0=BC=D0=BD=D1=8B=D1=85=20xlsx?= =?UTF-8?q?=20=D0=B2=20CSV=20=D0=BF=D0=B5=D1=80=D0=B5=D0=B4=20=D0=B7=D0=B0?= =?UTF-8?q?=D0=BF=D1=83=D1=81=D0=BA=D0=BE=D0=BC=20Claude?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Файлы из сметных программ (Гранд-Смета и др.) содержат стили которые ломают openpyxl. Теперь _preprocess_xlsx() автоматически: 1. Проверяет каждый xlsx — открывается ли openpyxl 2. Если нет — конвертирует через XML в CSV ({name}_csv/{sheet}.csv) 3. Claude видит CSV и работает без ошибок Прозрачно для пользователя — никакого XML/CSV знать не нужно. Co-Authored-By: Claude Opus 4.6 (1M context) --- claude_bridge.py | 71 ++++++++++++++++++++++++++++++++++ claude_project_instructions.md | 4 +- 2 files changed, 73 insertions(+), 2 deletions(-) diff --git a/claude_bridge.py b/claude_bridge.py index a0eafa0..f1329d4 100644 --- a/claude_bridge.py +++ b/claude_bridge.py @@ -26,6 +26,73 @@ _sessions: dict[tuple[str, str], str] = {} _semaphore = asyncio.Semaphore(3) +def _preprocess_xlsx(work_dir: Path): + """Convert xlsx files that openpyxl can't read into CSV + readable xlsx. + Runs BEFORE Claude sees the files — transparent to user.""" + import zipfile + import xml.etree.ElementTree as ET + import csv + + for f in work_dir.iterdir(): + if f.suffix.lower() not in ('.xlsx', '.xls') or f.name.startswith('.'): + continue + # Check if openpyxl can open it + try: + import openpyxl + openpyxl.load_workbook(str(f), data_only=True, read_only=True).close() + continue # OK, no conversion needed + except Exception: + pass + # openpyxl failed — convert via XML + try: + z = zipfile.ZipFile(str(f)) + ns = {'s': 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'} + # Read shared strings + strings = [] + try: + ss = ET.parse(z.open('xl/sharedStrings.xml')).getroot() + for si in ss.findall('.//s:si', ns): + strings.append(''.join(t.text or '' for t in si.findall('.//s:t', ns))) + except KeyError: + pass + # Get sheet names + wb = ET.parse(z.open('xl/workbook.xml')).getroot() + sheets = [(s.attrib.get('name', ''), s.attrib.get('{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id', '')) + for s in wb.findall('.//s:sheet', ns)] + # Read rels to map rId to file + rels = ET.parse(z.open('xl/_rels/workbook.xml.rels')).getroot() + rid_map = {r.get('{http://schemas.openxmlformats.org/package/2006/relationships}id', r.get('Id', '')): r.get('Target', '') + for r in rels.findall('.//{http://schemas.openxmlformats.org/package/2006/relationships}Relationship')} + # Convert each sheet to CSV + csv_dir = work_dir / f'{f.stem}_csv' + csv_dir.mkdir(exist_ok=True) + for sheet_name, rid in sheets: + target = rid_map.get(rid, '') + if not target: + continue + sheet_path = f'xl/{target}' + try: + sheet_xml = ET.parse(z.open(sheet_path)).getroot() + except KeyError: + continue + csv_path = csv_dir / f'{sheet_name}.csv' + with open(csv_path, 'w', newline='', encoding='utf-8') as out: + writer = csv.writer(out) + for row in sheet_xml.findall('.//s:row', ns): + vals = [] + for c in row.findall('s:c', ns): + v = c.find('s:v', ns) + val = v.text if v is not None else '' + if c.get('t') == 's' and val.isdigit(): + idx = int(val) + val = strings[idx] if idx < len(strings) else val + vals.append(val) + writer.writerow(vals) + z.close() + except Exception: + pass + + def get_work_dir(username: str, tab_id: str) -> Path: d = DATA_DIR / username / tab_id d.mkdir(parents=True, exist_ok=True) @@ -63,6 +130,10 @@ async def stream_claude( async with _semaphore: work_dir = get_work_dir(username, tab_id) session_id = get_session_id(username, tab_id) + + # Pre-process xlsx files that openpyxl can't read → CSV + _preprocess_xlsx(work_dir) + instructions = APP_DIR / "claude_project_instructions.md" # Build claude args diff --git a/claude_project_instructions.md b/claude_project_instructions.md index f80e3a2..c7624b6 100644 --- a/claude_project_instructions.md +++ b/claude_project_instructions.md @@ -97,8 +97,8 @@ else: ## Как работать с файлами пользователя - Файлы пользователя лежат в /data (текущая рабочая директория) -- Для ЧТЕНИЯ Excel — ВСЕГДА сначала пробуй XML-парсинг (работает с любыми файлами, включая сметные программы): -- Для ЗАПИСИ Excel — openpyxl (если файл открывается) или создание нового файла +- Для Excel — openpyxl или pandas. Если файл не открывается (ошибка стилей) — рядом автоматически создаётся папка `{имя}_csv/` с CSV-версиями каждого листа. Используй CSV для чтения данных. +- Для ЗАПИСИ — openpyxl (если открывается) или создание нового файла ```python import zipfile, xml.etree.ElementTree as ET z = zipfile.ZipFile('файл.xlsx')