feat: Batch V2 — Claude Code анализирует файлы и генерирует скрипт
Вместо GLM + шаблонного скрипта (V1), V2 использует Claude Code (1M контекст):
- Сэмплирует 15 файлов из набора (до 2000+), конвертирует xlsx→CSV
- Claude читает сэмплы + target, генерирует кастомный Python-скрипт
- Адаптируется к ЛЮБОЙ структуре файлов (не hardcoded формат)
- Пользователь подтверждает → скрипт выполняется на всех файлах
Новые файлы: batch_v2.py, static/batch2.html
Новые endpoints: /batch2, /api/batch-v2/{upload,analyze,run,status,download}
V1 (/batch) остаётся как fallback.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
"""smeta-web: AI assistant for estimators — FastAPI + Claude Code or GLM-5."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
@@ -261,6 +262,7 @@ async def clear_files(request: Request):
|
||||
|
||||
# === Batch processing ===
|
||||
from batch import analyze_structure, create_job, extract_zip, get_job, run_batch
|
||||
import batch_v2
|
||||
import threading
|
||||
import uuid
|
||||
|
||||
@@ -364,6 +366,165 @@ async def batch_download(job_id: str, request: Request):
|
||||
return FileResponse(job["output_file"], filename=Path(job["output_file"]).name)
|
||||
|
||||
|
||||
# === Batch V2: Claude Code analysis ===
|
||||
|
||||
|
||||
@app.get("/batch2", response_class=HTMLResponse)
|
||||
async def batch2_page():
|
||||
return Path("static/batch2.html").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
@app.post("/api/batch-v2/upload")
|
||||
async def batch_v2_upload(request: Request):
|
||||
"""Upload zip + target, convert xlsx→CSV, start Claude analysis (SSE stream)."""
|
||||
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_v2" / user / job_id
|
||||
job_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Save target
|
||||
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)
|
||||
# Also save as target.xlsx for Claude
|
||||
(job_dir / "target.xlsx").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))
|
||||
|
||||
# Convert target → CSV for Claude to read (only the target file)
|
||||
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_v2.convert_all_to_csv(str(target_only_dir), target_csv_dir)
|
||||
shutil.rmtree(str(target_only_dir))
|
||||
|
||||
# Select and convert SAMPLE files (not all — could be 2000+)
|
||||
sample_info = batch_v2.prepare_samples(str(source_dir), job_dir, {})
|
||||
|
||||
# Create job
|
||||
job = batch_v2.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-v2/analyze/{job_id}")
|
||||
async def batch_v2_analyze(job_id: str, request: Request):
|
||||
"""Start Claude Code analysis — returns SSE stream."""
|
||||
_get_user(request)
|
||||
job = batch_v2.get_job(job_id)
|
||||
if not job:
|
||||
raise HTTPException(404, "Job not found")
|
||||
|
||||
job_dir = Path(job["job_dir"])
|
||||
task_desc = job["task_description"]
|
||||
target_name = job["target_name"]
|
||||
total_files = job["total_files"]
|
||||
sample_info = job["sample_info"]
|
||||
|
||||
async def event_stream():
|
||||
async for event in batch_v2.run_claude_analysis(
|
||||
job_dir, task_desc, target_name, total_files, sample_info
|
||||
):
|
||||
etype = event.get("type", "")
|
||||
if etype == "text":
|
||||
yield f"event: text\ndata: {json.dumps({'text': event['text']}, ensure_ascii=False)}\n\n"
|
||||
elif etype == "tool":
|
||||
yield f"event: tool\ndata: {json.dumps({'tool': event['tool']}, ensure_ascii=False)}\n\n"
|
||||
elif etype == "done":
|
||||
script = event.get("script", "")
|
||||
if script:
|
||||
job["analysis"] = {"python_script": script}
|
||||
job["status"] = "analyzed"
|
||||
else:
|
||||
job["analysis"] = {"error": "Claude did not generate script", "result": event.get("result", "")}
|
||||
job["status"] = "analysis_failed"
|
||||
yield f"event: done\ndata: {json.dumps({'script': script, '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-v2/run/{job_id}")
|
||||
async def batch_v2_run(job_id: str, request: Request):
|
||||
"""Confirm and run the Claude-generated script."""
|
||||
_get_user(request)
|
||||
job = batch_v2.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")
|
||||
|
||||
threading.Thread(
|
||||
target=batch_v2.run_batch_v2,
|
||||
args=(job_id, script, job["source_dir"], job["target_file"]),
|
||||
daemon=True,
|
||||
).start()
|
||||
|
||||
return {"status": "started", "job_id": job_id}
|
||||
|
||||
|
||||
@app.get("/api/batch-v2/status/{job_id}")
|
||||
async def batch_v2_status(job_id: str, request: Request):
|
||||
_get_user(request)
|
||||
job = batch_v2.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", [])[:20],
|
||||
"script": job.get("analysis", {}).get("python_script", ""),
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/batch-v2/download/{job_id}")
|
||||
async def batch_v2_download(job_id: str, request: Request):
|
||||
_get_user(request)
|
||||
job = batch_v2.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