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:
@@ -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")))
|
||||
|
||||
Reference in New Issue
Block a user