feat: Batch V3 — генерация + верификация + auto-retry

Новая страница /batch3 с автоматической проверкой скрипта:
1. Claude (sonnet) генерирует скрипт (как V2)
2. Скрипт exec на 2 сэмплах → verify processed>0, errors=0
3. Если fail → retry с feedback (до 3 попыток)
4. Если не верифицирован → confirm dialog при запуске

Файлы: batch_v3.py, static/batch3.html
V2 не тронут, без кнопки на главной.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-26 14:52:57 +10:00
co-authored by Claude Opus 4.6
parent 6b98045184
commit c76c79cd56
3 changed files with 874 additions and 0 deletions
+171
View File
@@ -541,6 +541,177 @@ async def batch_v2_download(job_id: str, request: Request):
return FileResponse(job["output_file"], filename=Path(job["output_file"]).name)
# === Batch V3: Generate + Verify + Auto-Retry ===
import batch_v3
@app.get("/batch3", response_class=HTMLResponse)
async def batch3_page():
return Path("static/batch3.html").read_text(encoding="utf-8")
@app.post("/api/batch-v3/upload")
async def batch_v3_upload(request: Request):
"""Upload zip + target — same as V2 but separate storage."""
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 = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / "_batch_v3" / user / job_id
job_dir.mkdir(parents=True, exist_ok=True)
target_name = Path(target_file.filename).name
target_path = job_dir / target_name
target_content = await target_file.read()
target_path.write_bytes(target_content)
(job_dir / "target.xlsx").write_bytes(target_content)
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))
target_only_dir = job_dir / "_target_only"
target_only_dir.mkdir(exist_ok=True)
shutil.copy2(str(target_path), str(target_only_dir / target_name))
target_csv_dir = str(job_dir / "target_csv")
batch_v3.convert_all_to_csv(str(target_only_dir), target_csv_dir)
shutil.rmtree(str(target_only_dir))
sample_info = batch_v3.prepare_samples(str(source_dir), job_dir, {})
job = batch_v3.create_job(job_id)
job["source_dir"] = str(source_dir)
job["target_file"] = str(target_path)
job["target_name"] = target_name
job["job_dir"] = str(job_dir)
job["total_files"] = len(source_files)
job["task_description"] = task_desc
job["sample_info"] = sample_info
job["status"] = "uploaded"
return {
"job_id": job_id,
"total_files": len(source_files),
"csv_info": {
"sample_count": sample_info["sample_csv_count"],
"sample_bytes": sample_info["sample_bytes"],
"estimated_tokens": int(sample_info["sample_bytes"] * 0.3),
"xlsx_count": len(source_files),
},
}
@app.post("/api/batch-v3/analyze/{job_id}")
async def batch_v3_analyze(job_id: str, request: Request):
"""Generate + verify + auto-retry — SSE stream."""
_get_user(request)
job = batch_v3.get_job(job_id)
if not job:
raise HTTPException(404, "Job not found")
job_dir = Path(job["job_dir"])
async def event_stream():
async for event in batch_v3.run_generate_and_verify(
job_dir,
job["task_description"],
job["target_name"],
job["total_files"],
job["sample_info"],
job["source_dir"],
job["target_file"],
):
etype = event.get("type", "")
if etype in ("text", "tool", "generation_start", "verify_start",
"verify_ok", "verify_fail", "retry", "error"):
yield f"event: {etype}\ndata: {json.dumps(event, ensure_ascii=False)}\n\n"
elif etype == "done":
script = event.get("script", "")
summary = event.get("summary", {})
verified = event.get("verified", False)
attempts = event.get("attempts", 0)
if script:
job["analysis"] = {"python_script": script, "summary": summary}
job["status"] = "analyzed"
job["verified"] = verified
job["verify_attempts"] = attempts
else:
job["status"] = "analysis_failed"
yield f"event: done\ndata: {json.dumps({'script': script, 'summary': summary, 'verified': verified, 'attempts': attempts, 'status': job['status']}, ensure_ascii=False)}\n\n"
return StreamingResponse(
event_stream(),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)
@app.post("/api/batch-v3/run/{job_id}")
async def batch_v3_run(job_id: str, request: Request):
_get_user(request)
job = batch_v3.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")
threading.Thread(
target=batch_v3.run_batch_v3,
args=(job_id, script, job["source_dir"], job["target_file"]),
daemon=True,
).start()
return {"status": "started", "job_id": job_id}
@app.get("/api/batch-v3/status/{job_id}")
async def batch_v3_status(job_id: str, request: Request):
_get_user(request)
job = batch_v3.get_job(job_id)
if not job:
raise HTTPException(404, "Job not found")
# Fallback: check disk if SSE didn't deliver
if job["status"] == "uploaded" and job.get("job_dir"):
result_data = batch_v3._read_result_files(Path(job["job_dir"]))
if result_data.get("script"):
job["analysis"] = {
"python_script": result_data["script"],
"summary": result_data.get("summary", {}),
}
job["status"] = "analyzed"
analysis = job.get("analysis", {})
return {
"status": job["status"],
"total": job.get("total_files", 0),
"processed": job.get("processed", 0),
"errors": job.get("errors", [])[:20],
"script": analysis.get("python_script", ""),
"summary": analysis.get("summary", {}),
"verified": job.get("verified", False),
"verify_attempts": job.get("verify_attempts", 0),
"verify_errors": job.get("verify_errors", []),
}
@app.get("/api/batch-v3/download/{job_id}")
async def batch_v3_download(job_id: str, request: Request):
_get_user(request)
job = batch_v3.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")))