- response_format: {"type": "json_object"} для строгого JSON
- system prompt: "только валидный JSON"
- fallback на reasoning_content (GLM-5 может вернуть туда ответ)
- timeout 300с для batch-анализа
Sources: docs.z.ai/guides/capabilities/struct-output
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
236 lines
9.0 KiB
Python
236 lines
9.0 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()
|
|
rns = 'http://schemas.openxmlformats.org/package/2006/relationships'
|
|
rid_map = {r.get('Id', ''): r.get('Target', '') for r in rels.findall(f'.//{{{rns}}}Relationship')}
|
|
|
|
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', '')
|
|
target = rid_map.get(rid, '')
|
|
if not target:
|
|
continue
|
|
try:
|
|
sheet_xml = ET.parse(z.open(f'xl/{target}')).getroot()
|
|
except KeyError:
|
|
continue
|
|
rows = []
|
|
for row_el in sheet_xml.findall('.//s:row', ns):
|
|
if len(rows) >= max_rows:
|
|
break
|
|
cells = []
|
|
for c in row_el.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
|
|
cells.append(val)
|
|
rows.append(cells)
|
|
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."""
|
|
with zipfile.ZipFile(zip_path) as z:
|
|
z.extractall(dest_dir)
|
|
files = []
|
|
for f in Path(dest_dir).rglob('*.xlsx'):
|
|
if 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
|
|
samples = []
|
|
for f in sample_files[:3]:
|
|
data = read_xlsx_xml(f, max_rows=30)
|
|
samples.append({
|
|
'filename': Path(f).name,
|
|
'sheets': {k: v[:15] for k, v in data.items() if k != '_error'},
|
|
})
|
|
|
|
# Read target structure
|
|
target_data = read_xlsx_xml(target_file, max_rows=40)
|
|
target_info = {
|
|
'filename': Path(target_file).name,
|
|
'sheets': {k: v[:20] for k, v in target_data.items() if k != '_error'},
|
|
}
|
|
|
|
prompt = f"""Ты — эксперт по автоматизации сметного дела. Пользователь хочет перенести данные из множества Excel-файлов в один сводный файл.
|
|
|
|
Задача пользователя: {task_description}
|
|
|
|
## Примеры исходных файлов (3 из ~2000):
|
|
{json.dumps(samples, ensure_ascii=False, indent=2)[:8000]}
|
|
|
|
## Сводный файл (куда вносить):
|
|
{json.dumps(target_info, ensure_ascii=False, indent=2)[:4000]}
|
|
|
|
## Что нужно определить:
|
|
1. В каком месте исходного файла находится ШИФР/НАЗВАНИЕ сметы
|
|
2. В каком месте — итоговые суммы (строительные, монтажные, оборудование, прочие)
|
|
3. В сводном файле — какой лист, какие столбцы, как сопоставить строки
|
|
|
|
Ответь СТРОГО в формате JSON:
|
|
{{
|
|
"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": "краткое описание алгоритма на русском для пользователя"
|
|
}}"""
|
|
|
|
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]
|
|
return json.loads(content)
|
|
except (json.JSONDecodeError, IndexError):
|
|
return {"error": "Failed to parse LLM response", "raw": content[:2000]}
|
|
|
|
|
|
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"] = []
|
|
|
|
# Create a safe execution environment
|
|
output_file = str(Path(target_file).parent / f"result_{Path(target_file).name}")
|
|
shutil.copy2(target_file, output_file)
|
|
|
|
try:
|
|
# Execute the script with controlled globals
|
|
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]
|