Files
smeta-web/batch.py
T
anorandClaude Opus 4.6 924468fb16 feat: поддержка .gge, .esw, .xml в пакетном обработчике
Файлы сметных программ (ГРАНД-Смета .gge/.esw) — это XML.
Теперь extract_zip, batch_v2, batch_v3 находят и обрабатывают
все сметные форматы: .xlsx, .xls, .gge, .esw, .xml
GGE/ESW копируются как XML без xlsx-конвертации.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 17:20:26 +10:00

412 lines
16 KiB
Python

"""Batch processor: LLM analyzes structure, generates script, runs on all files.
Flow:
1. User uploads zip (smetas) + target xlsx (summary)
2. Server extracts, reads 3 sample files via XML
3. GLM analyzes structure → generates Python processing script
4. User confirms (or corrects)
5. Script runs on ALL files without LLM
6. Result: updated target xlsx + error log
"""
import csv
import io
import json
import os
import shutil
import tempfile
import time
import traceback
import zipfile
import xml.etree.ElementTree as ET
from pathlib import Path
import httpx
ZAI_API_KEY = os.environ.get("ZAI_API_KEY", "")
ZAI_BASE_URL = os.environ.get("ZAI_BASE_URL", "https://open.bigmodel.cn/api/coding/paas/v4")
ZAI_MODEL = os.environ.get("ZAI_MODEL", "glm-5")
# Batch jobs storage
_jobs: dict[str, dict] = {}
def read_xlsx_xml(path: str, max_rows: int = 50) -> dict:
"""Read xlsx via XML (handles broken styles). Returns {sheet_name: [[row], ...]}."""
result = {}
try:
z = zipfile.ZipFile(path)
ns = {'s': 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'}
# 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
# Sheet names and rels
wb = ET.parse(z.open('xl/workbook.xml')).getroot()
rels = ET.parse(z.open('xl/_rels/workbook.xml.rels')).getroot()
# 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.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(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
# 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 cell_type == 's' and val.isdigit():
idx = int(val)
val = strings[idx] if idx < len(strings) else val
elif cell_type == 'inlineStr':
# Inline string: <is><t>text</t></is>
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:
result['_error'] = str(e)
return result
def extract_zip(zip_path: str, dest_dir: str) -> list[str]:
"""Extract zip and return list of xlsx files.
Handles Cyrillic filenames: Python's zipfile decodes names as CP437
when the UTF-8 flag is not set. We detect and fix this.
"""
with zipfile.ZipFile(zip_path) as z:
for info in z.infolist():
# Fix Cyrillic filenames: if flag bit 11 is not set,
# Python decodes as CP437 — re-encode and decode as UTF-8
if not (info.flag_bits & 0x800):
try:
fixed = info.filename.encode('cp437').decode('utf-8')
info.filename = fixed
except (UnicodeDecodeError, UnicodeEncodeError):
pass # keep original if re-decode fails
# Skip macOS resource fork files and __MACOSX directory
basename = Path(info.filename).name
if basename.startswith('._') or '__MACOSX' in info.filename:
continue
z.extract(info, dest_dir)
# Collect all supported smeta file types
SMETA_EXTENSIONS = {'.xlsx', '.xls', '.gge', '.esw', '.xml'}
files = []
for f in Path(dest_dir).rglob('*'):
if f.is_file() and f.suffix.lower() in SMETA_EXTENSIONS \
and not f.name.startswith('~$') and not f.name.startswith('._'):
files.append(str(f))
return sorted(files)
async def analyze_structure(sample_files: list[str], target_file: str, task_description: str) -> dict:
"""Use LLM to analyze file structure and generate processing script."""
# Read samples — head + tail to see structure AND totals
samples = []
for f in sample_files[:3]:
data = read_xlsx_xml(f, max_rows=999)
sample = {'filename': Path(f).name, 'sheets': {}}
for k, v in data.items():
if k == '_error':
continue
head = v[:15]
tail = v[-50:] if len(v) > 50 else v[15:]
# Compact: only non-empty rows
head_compact = [[j, row[j]] for row in head for j in range(len(row)) if row[j]]
tail_compact = []
for i, row in enumerate(tail):
row_idx = len(v) - len(tail) + i
cells = [[j, row[j]] for j in range(len(row)) if row[j]]
if cells:
tail_compact.append({'row': row_idx, 'cells': cells[:6]})
sample['sheets'][k] = {
'total_rows': len(v),
'head': head_compact[:30],
'tail': tail_compact[:30],
}
samples.append(sample)
# Read target structure
target_data = read_xlsx_xml(target_file, max_rows=50)
target_info = {'filename': Path(target_file).name, 'sheets': {}}
for k, v in target_data.items():
if k == '_error':
continue
compact = []
for i, row in enumerate(v[:30]):
cells = [[j, row[j]] for j in range(len(row)) if row[j]]
if cells:
compact.append({'row': i, 'cells': cells[:8]})
target_info['sheets'][k] = {'total_rows': len(v), 'rows': compact}
prompt = f"""Ты — эксперт по автоматизации сметного дела.
Задача: {task_description}
## Примеры исходных файлов (3 штуки):
{json.dumps(samples, ensure_ascii=False, indent=2)[:6000]}
## Сводный файл:
{json.dumps(target_info, ensure_ascii=False, indent=2)[:3000]}
## Определи:
1. Где в исходном файле шифр сметы (лист, строка, столбец)
2. Где итоговые суммы (строительные, монтажные, оборудование, прочие)
3. Где в сводном файле строки для записи (лист, столбец с шифрами, столбцы для значений)
## ВАЖНО: В скрипте используй ТОЛЬКО эти переменные:
- `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, без ```):
{{
"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")
async with httpx.AsyncClient(timeout=300, proxy=proxy) as client:
resp = await client.post(
f"{ZAI_BASE_URL}/chat/completions",
headers={"Authorization": f"Bearer {ZAI_API_KEY}"},
json={
"model": ZAI_MODEL,
"messages": [
{"role": "system", "content": "Ты генерируешь ТОЛЬКО валидный JSON. Никакого текста вне JSON."},
{"role": "user", "content": prompt},
],
"temperature": 0.1,
"max_tokens": 4000,
"response_format": {"type": "json_object"},
},
)
resp.raise_for_status()
msg = resp.json()["choices"][0]["message"]
content = msg.get("content") or msg.get("reasoning_content") or ""
# Parse JSON from response
try:
if "```json" in content:
content = content.split("```json")[1].split("```")[0]
elif "```" in content:
content = content.split("```")[1].split("```")[0]
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."""
job = _jobs[job_id]
job["status"] = "running"
job["started_at"] = time.time()
source_files = [str(f) for f in Path(source_dir).rglob("*.xlsx") if not f.name.startswith("~$")]
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:
exec_globals = {
"__builtins__": __builtins__,
"source_files": source_files,
"target_file": output_file,
"job": job,
"read_xlsx_xml": read_xlsx_xml,
"Path": Path,
"csv": csv,
"json": json,
"zipfile": zipfile,
"ET": ET,
}
try:
import openpyxl
exec_globals["openpyxl"] = openpyxl
except ImportError:
pass
exec(script, exec_globals)
job["status"] = "completed"
job["output_file"] = output_file
except Exception as e:
job["status"] = "failed"
job["error"] = f"{type(e).__name__}: {e}\n{traceback.format_exc()}"
job["finished_at"] = time.time()
def get_job(job_id: str) -> dict | None:
return _jobs.get(job_id)
def create_job(job_id: str):
_jobs[job_id] = {
"id": job_id,
"status": "created",
"total_files": 0,
"processed": 0,
"errors": [],
}
return _jobs[job_id]