diff --git a/batch.py b/batch.py new file mode 100644 index 0000000..fc54c68 --- /dev/null +++ b/batch.py @@ -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] diff --git a/main.py b/main.py index 906c94e..a379f85 100644 --- a/main.py +++ b/main.py @@ -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"))) diff --git a/static/batch.html b/static/batch.html new file mode 100644 index 0000000..5d9d601 --- /dev/null +++ b/static/batch.html @@ -0,0 +1,157 @@ + + +
+ + +Загрузите архив со сметами и сводный файл — ИИ проанализирует структуру и перенесёт данные
+ +Все файлы локальных смет в одном архиве
+ + + +Файл, в который нужно внести данные (ССР, ведомость и т.д.)
+ + + + +