feat: пакетная обработка смет (batch processor)

Новая страница /batch для массовых операций с файлами:
1. Загрузка zip со сметами + сводный файл
2. GLM-5 анализирует 3 примера → генерирует Python-скрипт
3. Пользователь подтверждает алгоритм
4. Скрипт обрабатывает ВСЕ файлы без LLM

- batch.py: XML-чтение xlsx, LLM-анализ, exec скрипта
- static/batch.html: UI с прогрессом и скачиванием результата
- Кнопка "Пакетная" в шапке чата

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-25 19:26:55 +10:00
co-authored by Claude Opus 4.6
parent 844046a516
commit 4d52c53702
4 changed files with 493 additions and 0 deletions
+230
View File
@@ -0,0 +1,230 @@
"""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=120, 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": "user", "content": prompt}],
"temperature": 0.1,
"max_tokens": 4000,
},
)
resp.raise_for_status()
content = resp.json()["choices"][0]["message"]["content"]
# 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]
+105
View File
@@ -259,6 +259,111 @@ async def clear_files(request: Request):
return {"status": "ok"}
# === Batch processing ===
from batch import analyze_structure, create_job, extract_zip, get_job, run_batch
import threading
import uuid
BATCH_DIR = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / "_batch"
@app.get("/batch", response_class=HTMLResponse)
async def batch_page():
return Path("static/batch.html").read_text(encoding="utf-8")
@app.post("/api/batch/upload")
async def batch_upload(request: Request):
"""Upload zip + target file, extract, analyze structure."""
user = _get_user(request)
form = await request.form()
zip_file = form.get("zip_file")
target_file = form.get("target_file")
task_desc = form.get("task_description", "Перенести итоги из смет в сводный файл")
if not zip_file or not target_file:
raise HTTPException(400, "Need zip_file and target_file")
job_id = str(uuid.uuid4())[:8]
job_dir = BATCH_DIR / user / job_id
job_dir.mkdir(parents=True, exist_ok=True)
# Save target
target_path = job_dir / Path(target_file.filename).name
target_content = await target_file.read()
target_path.write_bytes(target_content)
# Save and extract zip
zip_path = job_dir / "source.zip"
zip_content = await zip_file.read()
zip_path.write_bytes(zip_content)
source_dir = job_dir / "source"
source_dir.mkdir(exist_ok=True)
source_files = extract_zip(str(zip_path), str(source_dir))
# Analyze with LLM
analysis = await analyze_structure(source_files, str(target_path), task_desc)
job = create_job(job_id)
job["source_dir"] = str(source_dir)
job["target_file"] = str(target_path)
job["total_files"] = len(source_files)
job["analysis"] = analysis
job["status"] = "analyzed"
return {
"job_id": job_id,
"total_files": len(source_files),
"analysis": analysis,
}
@app.post("/api/batch/run/{job_id}")
async def batch_run(job_id: str, request: Request):
"""Confirm and run the batch script."""
_get_user(request)
job = get_job(job_id)
if not job:
raise HTTPException(404, "Job not found")
script = job.get("analysis", {}).get("python_script", "")
if not script:
raise HTTPException(400, "No script generated")
# Run in background thread
threading.Thread(
target=run_batch,
args=(job_id, script, job["source_dir"], job["target_file"]),
daemon=True,
).start()
return {"status": "started", "job_id": job_id}
@app.get("/api/batch/status/{job_id}")
async def batch_status(job_id: str, request: Request):
_get_user(request)
job = get_job(job_id)
if not job:
raise HTTPException(404, "Job not found")
return {
"status": job["status"],
"total": job.get("total_files", 0),
"processed": job.get("processed", 0),
"errors": job.get("errors", [])[:10],
"description": job.get("analysis", {}).get("description", ""),
}
@app.get("/api/batch/download/{job_id}")
async def batch_download(job_id: str, request: Request):
_get_user(request)
job = get_job(job_id)
if not job or not job.get("output_file"):
raise HTTPException(404, "Result not ready")
return FileResponse(job["output_file"], filename=Path(job["output_file"]).name)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "8000")))
+157
View File
@@ -0,0 +1,157 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Пакетная обработка смет</title>
<style>
:root { --bg: #f5f0eb; --card: #fff; --text: #3a3a3a; --muted: #6b6b6b; --accent: #c4463a; --border: #d4c5b2; --radius: 10px; }
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: 'Inter', -apple-system, sans-serif; background: var(--bg); color: var(--text); min-height: 100vh; padding: 2rem; }
.container { max-width: 700px; margin: 0 auto; }
h1 { font-size: 1.3rem; margin-bottom: .3rem; }
.subtitle { color: var(--muted); font-size: .9rem; margin-bottom: 1.5rem; }
.card { background: var(--card); border-radius: var(--radius); padding: 1.5rem; margin-bottom: 1rem; box-shadow: 0 1px 4px rgba(0,0,0,.06); }
label { display: block; font-weight: 600; margin-bottom: .4rem; font-size: .9rem; }
.hint { color: var(--muted); font-size: .8rem; margin-bottom: .6rem; }
input[type=file] { width: 100%; padding: .5rem; border: 1.5px dashed var(--border); border-radius: var(--radius); margin-bottom: 1rem; }
textarea { width: 100%; padding: .6rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-family: inherit; font-size: .9rem; resize: vertical; min-height: 60px; }
button { padding: .7rem 1.5rem; background: var(--accent); color: #fff; border: none; border-radius: var(--radius); font-size: .95rem; font-weight: 600; cursor: pointer; }
button:hover { background: #a83830; }
button:disabled { background: var(--border); cursor: not-allowed; }
.back { display: inline-block; margin-bottom: 1rem; color: var(--accent); text-decoration: none; font-size: .85rem; }
#status { display: none; }
#analysis { display: none; }
.progress { background: #ede5db; border-radius: 6px; height: 8px; margin: .5rem 0; }
.progress-bar { background: var(--accent); height: 100%; border-radius: 6px; transition: width .3s; }
.error-list { color: #c4463a; font-size: .8rem; margin-top: .5rem; }
pre { background: #2c2c2c; color: #f5f0eb; padding: .8rem; border-radius: 6px; overflow-x: auto; font-size: .8rem; margin: .5rem 0; }
</style>
</head>
<body>
<div class="container">
<a class="back" href="/">← Вернуться в чат</a>
<h1>Пакетная обработка смет</h1>
<p class="subtitle">Загрузите архив со сметами и сводный файл — ИИ проанализирует структуру и перенесёт данные</p>
<div class="card" id="upload-form">
<label>Архив со сметами (.zip)</label>
<p class="hint">Все файлы локальных смет в одном архиве</p>
<input type="file" id="zip-file" accept=".zip">
<label>Сводный файл (.xlsx)</label>
<p class="hint">Файл, в который нужно внести данные (ССР, ведомость и т.д.)</p>
<input type="file" id="target-file" accept=".xlsx,.xls">
<label>Описание задачи</label>
<textarea id="task-desc" placeholder="Например: Из каждой сметы взять итого строительных работ (тыс.руб.) и внести в соответствующую строку ССР"></textarea>
<br><br>
<button onclick="startBatch()">Анализировать</button>
</div>
<div class="card" id="analysis">
<h3>Результат анализа</h3>
<p id="analysis-desc"></p>
<details>
<summary>Сгенерированный скрипт</summary>
<pre id="analysis-script"></pre>
</details>
<p id="analysis-files" style="margin:.5rem 0;color:var(--muted);font-size:.85rem"></p>
<button onclick="runBatch()">Запустить обработку</button>
</div>
<div class="card" id="status">
<h3>Обработка</h3>
<p id="status-text"></p>
<div class="progress"><div class="progress-bar" id="progress-bar" style="width:0%"></div></div>
<p id="status-count" style="font-size:.85rem;color:var(--muted)"></p>
<div class="error-list" id="error-list"></div>
<button id="download-btn" style="display:none" onclick="downloadResult()">Скачать результат</button>
</div>
</div>
<script>
const API = '';
let token = localStorage.getItem('token');
let jobId = null;
if (!token) { window.location.href = '/'; }
function authHeaders() { return {'Authorization': 'Bearer ' + token}; }
async function startBatch() {
const zipFile = document.getElementById('zip-file').files[0];
const targetFile = document.getElementById('target-file').files[0];
const taskDesc = document.getElementById('task-desc').value;
if (!zipFile || !targetFile) { alert('Загрузите оба файла'); return; }
const fd = new FormData();
fd.append('zip_file', zipFile);
fd.append('target_file', targetFile);
fd.append('task_description', taskDesc || 'Перенести итоги из смет в сводный файл');
document.querySelector('#upload-form button').disabled = true;
document.querySelector('#upload-form button').textContent = 'Анализирую...';
try {
const r = await fetch(API + '/api/batch/upload', {method: 'POST', headers: authHeaders(), body: fd});
if (r.status === 401) { window.location.href = '/'; return; }
const data = await r.json();
if (data.analysis?.error) { alert('Ошибка: ' + data.analysis.error); return; }
jobId = data.job_id;
document.getElementById('analysis-desc').textContent = data.analysis.description || 'Анализ завершён';
document.getElementById('analysis-script').textContent = data.analysis.python_script || '(нет скрипта)';
document.getElementById('analysis-files').textContent = 'Файлов: ' + data.total_files;
document.getElementById('analysis').style.display = 'block';
} catch(e) { alert('Ошибка: ' + e.message); }
finally {
document.querySelector('#upload-form button').disabled = false;
document.querySelector('#upload-form button').textContent = 'Анализировать';
}
}
async function runBatch() {
if (!jobId) return;
document.querySelector('#analysis button').disabled = true;
const r = await fetch(API + '/api/batch/run/' + jobId, {method: 'POST', headers: authHeaders()});
if (!r.ok) { alert('Ошибка запуска'); return; }
document.getElementById('status').style.display = 'block';
pollStatus();
}
async function pollStatus() {
const r = await fetch(API + '/api/batch/status/' + jobId, {headers: authHeaders()});
const data = await r.json();
const pct = data.total > 0 ? (data.processed / data.total * 100) : 0;
document.getElementById('progress-bar').style.width = pct + '%';
document.getElementById('status-count').textContent = data.processed + ' / ' + data.total + ' файлов';
if (data.status === 'running') {
document.getElementById('status-text').textContent = 'Обработка...';
setTimeout(pollStatus, 2000);
} else if (data.status === 'completed') {
document.getElementById('status-text').textContent = 'Готово!';
document.getElementById('download-btn').style.display = 'inline-block';
} else if (data.status === 'failed') {
document.getElementById('status-text').textContent = 'Ошибка: ' + (data.errors[0] || 'неизвестная');
}
if (data.errors.length > 0) {
document.getElementById('error-list').innerHTML = '<b>Ошибки:</b><br>' + data.errors.map(e => '• ' + e).join('<br>');
}
}
function downloadResult() {
const a = document.createElement('a');
a.href = API + '/api/batch/download/' + jobId;
fetch(a.href, {headers: authHeaders()}).then(r => r.blob()).then(b => {
const u = URL.createObjectURL(b);
const l = document.createElement('a'); l.href = u; l.download = 'result.xlsx'; l.click();
});
}
</script>
</body>
</html>
+1
View File
@@ -117,6 +117,7 @@ body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Robo
<div id="header">
<h1>Сметный ИИ-ассистент</h1>
<div class="header-actions">
<button onclick="window.open('/batch','_blank')">Пакетная</button>
<button onclick="showSessions()">История</button>
<button onclick="resetSession()">Новый диалог</button>
<button onclick="listFiles()">Файлы</button>