diff --git a/batch.py b/batch.py index 7229ba9..2b06728 100644 --- a/batch.py +++ b/batch.py @@ -48,34 +48,65 @@ def read_xlsx_xml(path: str, max_rows: int = 50) -> dict: # Sheet names and rels wb = ET.parse(z.open('xl/workbook.xml')).getroot() rels = ET.parse(z.open('xl/_rels/workbook.xml.rels')).getroot() - rns = 'http://schemas.openxmlformats.org/package/2006/relationships' - rid_map = {r.get('Id', ''): r.get('Target', '') for r in rels.findall(f'.//{{{rns}}}Relationship')} + # Parse rels regardless of namespace + rid_map = {} + for r in rels.iter(): + rid = r.get('Id', '') + tgt = r.get('Target', '') + if rid and tgt: + rid_map[rid] = tgt for sheet in wb.findall('.//s:sheet', ns): name = sheet.get('name', '') - rid = sheet.get(f'{{{ns.get("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships")}}}id', '') - if not rid: - rid = sheet.attrib.get('{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id', '') + rid = sheet.attrib.get('{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id', '') target = rid_map.get(rid, '') if not target: continue + # Normalize path (handle leading / or relative) + if target.startswith('/'): + sheet_path = target.lstrip('/') + elif target.startswith('xl/'): + sheet_path = target + else: + sheet_path = f'xl/{target}' try: - sheet_xml = ET.parse(z.open(f'xl/{target}')).getroot() + sheet_xml = ET.parse(z.open(sheet_path)).getroot() except KeyError: continue rows = [] for row_el in sheet_xml.findall('.//s:row', ns): + row_num = int(row_el.get('r', len(rows) + 1)) + # Pad with empty rows if needed + while len(rows) < row_num - 1: + rows.append([]) if len(rows) >= max_rows: break - cells = [] + # Parse cells with proper column positions + row_data = [''] * 26 # A-Z for c in row_el.findall('s:c', ns): + ref = c.get('r', '') # e.g. "B5", "H29" + cell_type = c.get('t', '') v = c.find('s:v', ns) val = v.text if v is not None else '' - if c.get('t') == 's' and val.isdigit(): + if cell_type == 's' and val.isdigit(): idx = int(val) val = strings[idx] if idx < len(strings) else val - cells.append(val) - rows.append(cells) + elif cell_type == 'inlineStr': + # Inline string: text + is_el = c.find('s:is', ns) + if is_el is not None: + val = ''.join(t.text or '' for t in is_el.findall('.//s:t', ns)) + # Extract column index from ref (A=0, B=1, ..., H=7) + col_letters = ''.join(ch for ch in ref if ch.isalpha()) + col_idx = 0 + for ch in col_letters.upper(): + col_idx = col_idx * 26 + (ord(ch) - ord('A')) + if col_idx < len(row_data): + row_data[col_idx] = val + # Trim trailing empty cells + while row_data and row_data[-1] == '': + row_data.pop() + rows.append(row_data) result[name] = rows z.close() except Exception as e: @@ -112,35 +143,36 @@ async def analyze_structure(sample_files: list[str], target_file: str, task_desc 'sheets': {k: v[:20] for k, v in target_data.items() if k != '_error'}, } - prompt = f"""Ты — эксперт по автоматизации сметного дела. Пользователь хочет перенести данные из множества Excel-файлов в один сводный файл. + prompt = f"""Ты — эксперт по автоматизации сметного дела. -Задача пользователя: {task_description} +Задача: {task_description} -## Примеры исходных файлов (3 из ~2000): -{json.dumps(samples, ensure_ascii=False, indent=2)[:8000]} +## Примеры исходных файлов (3 штуки): +{json.dumps(samples, ensure_ascii=False, indent=2)[:6000]} -## Сводный файл (куда вносить): -{json.dumps(target_info, ensure_ascii=False, indent=2)[:4000]} +## Сводный файл: +{json.dumps(target_info, ensure_ascii=False, indent=2)[:3000]} -## Что нужно определить: -1. В каком месте исходного файла находится ШИФР/НАЗВАНИЕ сметы -2. В каком месте — итоговые суммы (строительные, монтажные, оборудование, прочие) -3. В сводном файле — какой лист, какие столбцы, как сопоставить строки +## Определи: +1. Где в исходном файле шифр сметы (лист, строка, столбец) +2. Где итоговые суммы (строительные, монтажные, оборудование, прочие) +3. Где в сводном файле строки для записи (лист, столбец с шифрами, столбцы для значений) -Ответь СТРОГО в формате JSON: +## ВАЖНО: В скрипте используй ТОЛЬКО эти переменные: +- `source_files` — list[str] путей ко всем xlsx файлам +- `target_file` — str путь к сводному файлу (уже скопирован, пиши в него) +- `job` — dict: job["processed"] += 1 (int счётчик), job["errors"].append("описание") (list строк) +- `read_xlsx_xml(path, max_rows=999)` — функция чтения xlsx через XML, возвращает dict[sheet_name, list[list[str]]] +- `openpyxl` — для записи в target_file + +Ответь ТОЛЬКО JSON (без markdown, без ```): {{ - "source_structure": {{ - "code_location": "описание где шифр (например: лист 'Смета', ячейка B2)", - "totals_location": "описание где итоги", - "totals_fields": {{"строительные": "cell", "монтажные": "cell", "оборудование": "cell", "прочие": "cell"}} - }}, - "target_structure": {{ - "sheet_name": "название листа в сводном файле", - "match_column": "столбец с шифрами для сопоставления", - "value_columns": {{"строительные": "col", "монтажные": "col", "оборудование": "col", "прочие": "col"}} - }}, - "python_script": "полный Python-скрипт для обработки всех файлов (import, чтение XML, запись openpyxl)", - "description": "краткое описание алгоритма на русском для пользователя" + "description": "описание алгоритма на русском", + "source_code_cell": "B5", + "source_totals": {{"строительные": "H29", "монтажные": "H30", "оборудование": "H31", "прочие": "H32"}}, + "target_sheet": "ССРСС-1 ТУЦ", + "target_match_col": "B", + "target_value_cols": {{"строительные": "D", "монтажные": "E", "оборудование": "F", "прочие": "G"}} }}""" proxy = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY") @@ -169,10 +201,92 @@ async def analyze_structure(sample_files: list[str], target_file: str, task_desc content = content.split("```json")[1].split("```")[0] elif "```" in content: content = content.split("```")[1].split("```")[0] - return json.loads(content) + params = json.loads(content) except (json.JSONDecodeError, IndexError): return {"error": "Failed to parse LLM response", "raw": content[:2000]} + # Generate deterministic script from params + params["python_script"] = _build_batch_script(params) + return params + + +def _col_to_idx(col: str) -> int: + """A→0, B→1, H→7""" + result = 0 + for ch in col.upper(): + result = result * 26 + (ord(ch) - ord('A')) + return result + + +def _build_batch_script(params: dict) -> str: + """Build deterministic Python script from LLM-extracted params.""" + code_cell = params.get("source_code_cell", "B5") + totals = params.get("source_totals", {}) + target_sheet = params.get("target_sheet", "") + match_col = params.get("target_match_col", "B") + value_cols = params.get("target_value_cols", {}) + + # Parse code cell → row, col indices + code_col = ''.join(c for c in code_cell if c.isalpha()) + code_row = ''.join(c for c in code_cell if c.isdigit()) + code_col_idx = _col_to_idx(code_col) + code_row_idx = int(code_row) - 1 if code_row else 4 + + # Parse total cells + total_cells = [] + for name, cell in totals.items(): + col = ''.join(c for c in cell if c.isalpha()) + row = ''.join(c for c in cell if c.isdigit()) + total_cells.append((name, _col_to_idx(col), int(row) - 1 if row else 0)) + + # Parse target columns + target_cols = {} + for name, col in value_cols.items(): + target_cols[name] = _col_to_idx(col) + 1 # openpyxl is 1-indexed + + match_col_idx = _col_to_idx(match_col) + 1 + + # Build value extraction lines + value_lines = [] + for name, ci, ri in total_cells: + tcol = target_cols.get(name, ci + 4) + value_lines.append( + f" v=0\n" + f" if len(sheet)>{ri} and len(sheet[{ri}])>{ci}:\n" + f" try: v=float(str(sheet[{ri}][{ci}] or 0).replace(',','.').replace(' ','') or 0)\n" + f" except: v=0\n" + f" ws.cell(row, {tcol}).value = v" + ) + values_code = "\n".join(value_lines) + + return ( + "import openpyxl\n" + "wb = openpyxl.load_workbook(target_file)\n" + f"ws = wb['{target_sheet}'] if '{target_sheet}' in wb.sheetnames else wb.active\n" + "code_to_row = {}\n" + f"for r in range(1, ws.max_row + 1):\n" + f" v = ws.cell(r, {match_col_idx}).value\n" + " if v:\n" + " code_to_row[str(v).strip()] = r\n" + "for f in source_files:\n" + " try:\n" + " data = read_xlsx_xml(f, max_rows=100)\n" + " if not data:\n" + " job['errors'].append(f + ': empty'); continue\n" + " sheet = list(data.values())[0]\n" + f" if len(sheet) <= {code_row_idx} or len(sheet[{code_row_idx}]) <= {code_col_idx}:\n" + " job['errors'].append(f + ': no code'); continue\n" + f" code = str(sheet[{code_row_idx}][{code_col_idx}]).strip()\n" + " if not code or code not in code_to_row:\n" + " job['errors'].append(f + ': ' + code + ' not found'); continue\n" + " row = code_to_row[code]\n" + f"{values_code}\n" + " job['processed'] += 1\n" + " except Exception as e:\n" + " job['errors'].append(f + ': ' + str(e))\n" + "wb.save(target_file)\n" + ) + def run_batch(job_id: str, script: str, source_dir: str, target_file: str): """Execute generated script on all files. Updates job status.""" @@ -184,13 +298,33 @@ def run_batch(job_id: str, script: str, source_dir: str, target_file: str): job["total_files"] = len(source_files) job["processed"] = 0 job["errors"] = [] + job["error_count"] = 0 # int counter for scripts that do += 1 # Create a safe execution environment output_file = str(Path(target_file).parent / f"result_{Path(target_file).name}") shutil.copy2(target_file, output_file) + # Fix common LLM mistakes in generated scripts + import re + script = script.replace("job['errors'] += 1", "job['errors'].append('error')") + script = script.replace('job["errors"] += 1', 'job["errors"].append("error")') + # Fix sheet name access — add fallback to active sheet + script = re.sub( + r"wb_target\['([^']+)'\]", + r"(wb_target['\1'] if '\1' in wb_target.sheetnames else wb_target.active)", + script + ) + script = re.sub( + r'wb_target\["([^"]+)"\]', + r'(wb_target["\1"] if "\1" in wb_target.sheetnames else wb_target.active)', + script + ) + # If LLM wrapped in def main() / if __name__, call main() at the end + if "def main()" in script and "if __name__" in script: + script = re.sub(r"if __name__\s*==\s*['\"]__main__['\"]\s*:\s*\n\s*main\(\)", "", script) + script += "\nmain()\n" + try: - # Execute the script with controlled globals exec_globals = { "__builtins__": __builtins__, "source_files": source_files, diff --git a/scripts/test_batch.py b/scripts/test_batch.py new file mode 100644 index 0000000..e70a2df --- /dev/null +++ b/scripts/test_batch.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +"""Manual test of batch processing pipeline.""" +import json, sys, shutil, traceback, asyncio +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent.parent)) +from batch import read_xlsx_xml, extract_zip, analyze_structure +import openpyxl + +# Setup +source_dir = "/tmp/batch_manual/source" +Path(source_dir).mkdir(parents=True, exist_ok=True) +source_files = extract_zip("/tmp/smetas.zip", source_dir) +target_orig = "/tmp/ССР_сводный.xlsx" +target_file = "/tmp/batch_manual/result.xlsx" +shutil.copy2(target_orig, target_file) + +print(f"Source files: {len(source_files)}") +print(f"Target: {target_file}") + +# Get script from GLM +task = "B5=шифр, H29=строит работы, H30=монтаж, H31=оборуд, H32=прочие (тыс.руб). Внести в сводный файл по шифру (столбец B), значения в столбцы D,E,F,G" +analysis = asyncio.run(analyze_structure(source_files, target_orig, task)) +script = analysis.get("python_script", "") +desc = analysis.get("description", "") +print(f"Description: {desc}") +print(f"Script ({len(script)} chars):") +print(script) +print("---") + +if not script: + print("NO SCRIPT. Analysis:", json.dumps(analysis, ensure_ascii=False, indent=2)[:1000]) + sys.exit(1) + +# Fix common GLM mistakes +import re +script_fixed = script.replace("job['errors'] += 1", "job['errors'].append('error')") +script_fixed = script_fixed.replace('job["errors"] += 1', 'job["errors"].append("error")') +script_fixed = re.sub(r"wb_target\['([^']+)'\]", r"(wb_target['\1'] if '\1' in wb_target.sheetnames else wb_target.active)", script_fixed) +script_fixed = re.sub(r'wb_target\["([^"]+)"\]', r'(wb_target["\1"] if "\1" in wb_target.sheetnames else wb_target.active)', script_fixed) +# If wrapped in def main(), call it +if "def main()" in script_fixed and "if __name__" in script_fixed: + script_fixed = re.sub(r"if __name__\s*==\s*['\"]__main__['\"]\s*:\s*\n\s*main\(\)", "", script_fixed) + script_fixed += "\nmain()\n" + +# Execute +job = {"processed": 0, "errors": []} +try: + exec(script_fixed, { + "__builtins__": __builtins__, + "source_files": source_files, + "target_file": target_file, + "job": job, + "read_xlsx_xml": read_xlsx_xml, + "Path": Path, + "openpyxl": openpyxl, + "json": json, + }) + print(f"\nSUCCESS! Processed: {job['processed']}/{len(source_files)}") + print(f"Errors: {len(job['errors'])}") +except Exception: + traceback.print_exc() + print(f"\nFAILED. Processed: {job['processed']}") + +# Verify result +wb = openpyxl.load_workbook(target_file) +ws = wb.active +print(f"\nResult (sheet '{ws.title}'):") +for r in range(3, 14): + vals = [] + for c in range(1, 9): + v = ws.cell(r, c).value + vals.append(str(v) if v is not None else "") + print(" Row %d: %s" % (r, " | ".join(vals)))