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')