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:
+354
@@ -0,0 +1,354 @@
|
||||
"""Batch V3: Generate + Verify + Auto-Retry.
|
||||
|
||||
Extends V2 with automatic verification: after Claude generates a script,
|
||||
it is exec'd on 2 sample files. If it fails, Claude retries with error feedback.
|
||||
|
||||
Flow:
|
||||
1. Upload zip + target + task description (same as V2)
|
||||
2. Claude Code (sonnet) generates script
|
||||
3. Script is exec'd on 2 samples → verify
|
||||
4. If fail → retry with error feedback (up to 3 times)
|
||||
5. User confirms → script runs on all files
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import csv
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
import traceback
|
||||
import zipfile
|
||||
import xml.etree.ElementTree as ET
|
||||
from pathlib import Path
|
||||
from typing import AsyncGenerator
|
||||
|
||||
from batch import read_xlsx_xml, extract_zip
|
||||
from batch_v2 import (
|
||||
build_claude_prompt,
|
||||
convert_all_to_csv,
|
||||
prepare_samples,
|
||||
_read_result_files,
|
||||
DOCKER_IMAGE,
|
||||
CLAUDE_CONFIG_DIR,
|
||||
DOCKER_HOST_GW,
|
||||
XRAY_PORT,
|
||||
)
|
||||
|
||||
# V3 job storage (separate from V2)
|
||||
_jobs: dict[str, dict] = {}
|
||||
|
||||
|
||||
def create_job(job_id: str) -> dict:
|
||||
_jobs[job_id] = {
|
||||
"id": job_id,
|
||||
"status": "created",
|
||||
"total_files": 0,
|
||||
"processed": 0,
|
||||
"errors": [],
|
||||
"verified": False,
|
||||
"verify_attempts": 0,
|
||||
"verify_errors": [],
|
||||
}
|
||||
return _jobs[job_id]
|
||||
|
||||
|
||||
def get_job(job_id: str) -> dict | None:
|
||||
return _jobs.get(job_id)
|
||||
|
||||
|
||||
def verify_script(
|
||||
script: str,
|
||||
source_dir: str,
|
||||
target_file: str,
|
||||
job_dir: Path,
|
||||
) -> dict:
|
||||
"""Execute script on 2 sample files to verify correctness.
|
||||
|
||||
Returns {"ok": True/False, "processed": int, "errors": [...], "error": str}.
|
||||
"""
|
||||
# Select 2 sample xlsx files
|
||||
all_xlsx = sorted(
|
||||
f for f in Path(source_dir).rglob("*.xlsx")
|
||||
if not f.name.startswith("~$") and not f.name.startswith("._")
|
||||
)
|
||||
samples = [str(f) for f in all_xlsx[:2]]
|
||||
if not samples:
|
||||
return {"ok": False, "error": "No xlsx files found in source", "processed": 0, "errors": []}
|
||||
|
||||
# Copy target to temp file
|
||||
verify_target = job_dir / "verify_target.xlsx"
|
||||
shutil.copy2(target_file, str(verify_target))
|
||||
|
||||
mini_job = {"processed": 0, "errors": []}
|
||||
exec_globals = {
|
||||
"__builtins__": __builtins__,
|
||||
"source_files": samples,
|
||||
"target_file": str(verify_target),
|
||||
"job": mini_job,
|
||||
"read_xlsx_xml": read_xlsx_xml,
|
||||
"Path": Path,
|
||||
"csv": csv,
|
||||
"json": json,
|
||||
"zipfile": zipfile,
|
||||
"ET": ET,
|
||||
"os": os,
|
||||
"re": re,
|
||||
}
|
||||
try:
|
||||
import openpyxl
|
||||
exec_globals["openpyxl"] = openpyxl
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
try:
|
||||
exec(script, exec_globals)
|
||||
except Exception as e:
|
||||
return {
|
||||
"ok": False,
|
||||
"error": f"{type(e).__name__}: {e}\n{traceback.format_exc()}",
|
||||
"processed": mini_job["processed"],
|
||||
"errors": mini_job["errors"],
|
||||
}
|
||||
finally:
|
||||
if verify_target.exists():
|
||||
verify_target.unlink()
|
||||
|
||||
if mini_job["processed"] > 0 and len(mini_job["errors"]) == 0:
|
||||
return {"ok": True, "processed": mini_job["processed"], "errors": []}
|
||||
|
||||
error_msg = f"processed={mini_job['processed']}/{len(samples)}, errors={mini_job['errors']}"
|
||||
return {
|
||||
"ok": False,
|
||||
"error": error_msg,
|
||||
"processed": mini_job["processed"],
|
||||
"errors": mini_job["errors"],
|
||||
}
|
||||
|
||||
|
||||
def build_retry_prompt(original_prompt: str, script: str, error: str, attempt: int) -> str:
|
||||
"""Build prompt for retry after verification failure."""
|
||||
return f"""{original_prompt}
|
||||
|
||||
## PREVIOUS ATTEMPT FAILED (attempt {attempt}/3)
|
||||
|
||||
Your previously generated script was tested on 2 sample xlsx files and FAILED.
|
||||
|
||||
### The script that failed:
|
||||
```python
|
||||
{script}
|
||||
```
|
||||
|
||||
### Error:
|
||||
{error}
|
||||
|
||||
## Fix the bugs. Common issues:
|
||||
- ALWAYS use read_xlsx_xml(path, max_rows=9999) — default is only 50 rows!
|
||||
- Column indices: A=0, B=1, ..., H=7 (0-based in read_xlsx_xml)
|
||||
- openpyxl uses 1-based row/col numbering
|
||||
- Handle missing sheets/values gracefully (skip, don't crash)
|
||||
- Don't forget to handle files with encoding issues in filenames
|
||||
|
||||
Write corrected /data/batch_script.py and /data/batch_summary.json.
|
||||
"""
|
||||
|
||||
|
||||
async def run_claude_v3(
|
||||
job_dir: Path,
|
||||
prompt: str,
|
||||
) -> AsyncGenerator[dict, None]:
|
||||
"""Run Claude Code in Docker with --model sonnet. Yields SSE events."""
|
||||
cmd = [
|
||||
"docker", "run", "--rm",
|
||||
"--memory=1g",
|
||||
"--cpus=2",
|
||||
"--network=host",
|
||||
"-v", f"{job_dir.resolve()}:/data",
|
||||
"-v", f"{CLAUDE_CONFIG_DIR}:/home/worker/.claude",
|
||||
"-v", f"{os.path.expanduser('~')}/.claude.json:/home/worker/.claude.json",
|
||||
"-e", f"HTTPS_PROXY=http://{DOCKER_HOST_GW}:{XRAY_PORT}",
|
||||
"-e", f"HTTP_PROXY=http://{DOCKER_HOST_GW}:{XRAY_PORT}",
|
||||
"-e", "HOME=/home/worker",
|
||||
"-w", "/data",
|
||||
DOCKER_IMAGE,
|
||||
"-p", prompt,
|
||||
"--model", "sonnet",
|
||||
"--output-format", "stream-json",
|
||||
"--verbose",
|
||||
"--allowedTools", "Bash,Read,Write,Edit,Glob,Grep",
|
||||
"--max-turns", "30",
|
||||
]
|
||||
|
||||
try:
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
*cmd,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.DEVNULL,
|
||||
)
|
||||
except FileNotFoundError:
|
||||
yield {"type": "done", "script": "", "result": "Docker not found"}
|
||||
return
|
||||
|
||||
got_result = False
|
||||
try:
|
||||
while True:
|
||||
raw_line = await proc.stdout.readline()
|
||||
if not raw_line:
|
||||
break
|
||||
line = raw_line.decode().strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
event = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
|
||||
etype = event.get("type", "")
|
||||
if etype == "assistant":
|
||||
msg = event.get("message", {})
|
||||
for block in msg.get("content", []):
|
||||
if block.get("type") == "text":
|
||||
yield {"type": "text", "text": block["text"]}
|
||||
elif block.get("type") == "tool_use":
|
||||
yield {"type": "tool", "tool": block.get("name", "")}
|
||||
elif etype == "result":
|
||||
got_result = True
|
||||
yield {"type": "done", **_read_result_files(job_dir)}
|
||||
finally:
|
||||
if proc.returncode is None:
|
||||
proc.terminate()
|
||||
try:
|
||||
await asyncio.wait_for(proc.wait(), timeout=5)
|
||||
except asyncio.TimeoutError:
|
||||
proc.kill()
|
||||
|
||||
if not got_result:
|
||||
yield {"type": "done", **_read_result_files(job_dir)}
|
||||
|
||||
|
||||
async def run_generate_and_verify(
|
||||
job_dir: Path,
|
||||
task_description: str,
|
||||
target_filename: str,
|
||||
total_xlsx_count: int,
|
||||
sample_info: dict,
|
||||
source_dir: str,
|
||||
target_file: str,
|
||||
) -> AsyncGenerator[dict, None]:
|
||||
"""Orchestrator: generate script → verify → retry if needed."""
|
||||
original_prompt = build_claude_prompt(
|
||||
task_description,
|
||||
sample_info["sample_csv_dir"],
|
||||
str(job_dir / "target_csv"),
|
||||
target_filename,
|
||||
total_xlsx_count,
|
||||
sample_info["sample_files"],
|
||||
)
|
||||
prompt = original_prompt
|
||||
|
||||
for attempt in range(1, 4):
|
||||
# Phase 1: Generate
|
||||
yield {"type": "generation_start", "attempt": attempt}
|
||||
|
||||
script = ""
|
||||
summary = {}
|
||||
async for event in run_claude_v3(job_dir, prompt):
|
||||
if event["type"] in ("text", "tool"):
|
||||
yield event
|
||||
elif event["type"] == "done":
|
||||
script = event.get("script", "")
|
||||
summary = event.get("summary", {})
|
||||
|
||||
if not script:
|
||||
yield {"type": "error", "error": "Script not generated", "attempt": attempt}
|
||||
return
|
||||
|
||||
# Phase 2: Verify
|
||||
yield {"type": "verify_start", "attempt": attempt}
|
||||
result = verify_script(script, source_dir, target_file, str(job_dir))
|
||||
|
||||
if result["ok"]:
|
||||
yield {
|
||||
"type": "verify_ok",
|
||||
"attempt": attempt,
|
||||
"processed": result["processed"],
|
||||
}
|
||||
yield {
|
||||
"type": "done",
|
||||
"script": script,
|
||||
"summary": summary,
|
||||
"verified": True,
|
||||
"attempts": attempt,
|
||||
}
|
||||
return
|
||||
|
||||
# Phase 3: Failed
|
||||
yield {
|
||||
"type": "verify_fail",
|
||||
"attempt": attempt,
|
||||
"error": result["error"],
|
||||
"processed": result["processed"],
|
||||
}
|
||||
|
||||
if attempt < 3:
|
||||
yield {"type": "retry", "attempt": attempt + 1}
|
||||
prompt = build_retry_prompt(original_prompt, script, result["error"], attempt)
|
||||
# Clean up for next attempt
|
||||
(job_dir / "batch_script.py").unlink(missing_ok=True)
|
||||
(job_dir / "batch_summary.json").unlink(missing_ok=True)
|
||||
|
||||
# All 3 attempts failed — still return the last script
|
||||
yield {
|
||||
"type": "done",
|
||||
"script": script,
|
||||
"summary": summary,
|
||||
"verified": False,
|
||||
"attempts": 3,
|
||||
"last_error": result["error"],
|
||||
}
|
||||
|
||||
|
||||
def run_batch_v3(job_id: str, script: str, source_dir: str, target_file: str):
|
||||
"""Execute script on all files (same as V2)."""
|
||||
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"] = []
|
||||
|
||||
output_file = str(Path(target_file).parent / f"result_{Path(target_file).name}")
|
||||
shutil.copy2(target_file, output_file)
|
||||
|
||||
try:
|
||||
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,
|
||||
"os": os,
|
||||
"re": re,
|
||||
}
|
||||
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()
|
||||
@@ -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")))
|
||||
|
||||
@@ -0,0 +1,349 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Пакетная обработка V3 — Verify</title>
|
||||
<style>
|
||||
:root { --bg: #f5f0eb; --card: #fff; --text: #3a3a3a; --muted: #6b6b6b; --accent: #c4463a; --border: #d4c5b2; --radius: 10px; --green: #2d8a56; }
|
||||
* { 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: 750px; margin: 0 auto; }
|
||||
h1 { font-size: 1.3rem; margin-bottom: .3rem; }
|
||||
.subtitle { color: var(--muted); font-size: .9rem; margin-bottom: 1.5rem; }
|
||||
.badge { display: inline-block; background: var(--green); color: #fff; font-size: .7rem; padding: 2px 8px; border-radius: 12px; vertical-align: middle; margin-left: .5rem; }
|
||||
.badge-warn { background: #d4a017; }
|
||||
.card { background: var(--card); border-radius: var(--radius); padding: 1.5rem; margin-bottom: 1rem; box-shadow: 0 1px 4px rgba(0,0,0,.06); }
|
||||
.card.hidden { display: none; }
|
||||
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: 80px; }
|
||||
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; }
|
||||
.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; max-height: 200px; overflow-y: auto; }
|
||||
pre { background: #2c2c2c; color: #f5f0eb; padding: .8rem; border-radius: 6px; overflow-x: auto; font-size: .78rem; margin: .5rem 0; max-height: 400px; overflow-y: auto; white-space: pre-wrap; word-break: break-word; }
|
||||
.log { background: #1a1a2e; color: #a0d2db; padding: .8rem; border-radius: 6px; font-size: .78rem; margin: .5rem 0; max-height: 300px; overflow-y: auto; font-family: monospace; white-space: pre-wrap; word-break: break-word; }
|
||||
.info-row { display: flex; gap: 1rem; margin: .5rem 0; font-size: .85rem; color: var(--muted); }
|
||||
.info-row span { background: #ede5db; padding: 3px 10px; border-radius: 6px; }
|
||||
.spinner { display: inline-block; width: 16px; height: 16px; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin .8s linear infinite; vertical-align: middle; margin-right: 6px; }
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
.verify-ok { background: #e8f5e9; border: 1px solid var(--green); border-radius: 6px; padding: .5rem .8rem; margin: .5rem 0; font-size: .85rem; color: var(--green); }
|
||||
.verify-fail { background: #fce4ec; border: 1px solid var(--accent); border-radius: 6px; padding: .5rem .8rem; margin: .5rem 0; font-size: .85rem; color: var(--accent); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<a class="back" href="/">← Вернуться в чат</a>
|
||||
<h1>Пакетная обработка смет <span class="badge">V3 Verify</span></h1>
|
||||
<p class="subtitle">Claude генерирует скрипт + автоматическая проверка на 2 файлах + auto-retry</p>
|
||||
|
||||
<!-- Step 1: Upload -->
|
||||
<div class="card" id="step-upload">
|
||||
<label>1. Архив со сметами (.zip)</label>
|
||||
<p class="hint">Все файлы локальных смет в одном архиве (до 2000 файлов)</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>
|
||||
<p class="hint">Опишите что именно нужно сделать — Claude прочитает файлы и разберётся</p>
|
||||
<textarea id="task-desc" placeholder="Из каждого файла взять итоговые суммы по типам работ (строительные, монтажные, оборудование, прочие) и внести в соответствующие строки и колонки сводного файла. Значения в исходных файлах в рублях, в сводном — тыс.руб."></textarea>
|
||||
<br><br>
|
||||
<button id="btn-upload" onclick="uploadFiles()">Загрузить и конвертировать</button>
|
||||
</div>
|
||||
|
||||
<!-- Step 2: Analysis + Verification -->
|
||||
<div class="card hidden" id="step-analyze">
|
||||
<label>2. Генерация + верификация</label>
|
||||
<div class="info-row" id="csv-info"></div>
|
||||
<p style="margin:.5rem 0;font-size:.9rem"><span class="spinner" id="analyze-spinner"></span> <span id="analyze-status">Claude генерирует скрипт...</span> <span id="analyze-timer" style="color:var(--muted);font-size:.8rem"></span></p>
|
||||
<div id="verify-status"></div>
|
||||
<div class="log" id="analyze-log"></div>
|
||||
</div>
|
||||
|
||||
<!-- Step 3: Confirm -->
|
||||
<div class="card hidden" id="step-confirm">
|
||||
<label>3. Проверьте найденные параметры</label>
|
||||
<div id="verify-badge"></div>
|
||||
<div id="summary-view" style="font-size:.9rem;line-height:1.6"></div>
|
||||
<details style="margin-top:.8rem">
|
||||
<summary style="cursor:pointer;color:var(--muted);font-size:.8rem">Показать скрипт (для разработчиков)</summary>
|
||||
<pre id="script-code"></pre>
|
||||
</details>
|
||||
<div style="display:flex;gap:.5rem;margin-top:.8rem">
|
||||
<button id="btn-run" onclick="runScript()">Запустить обработку</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Step 4: Execution -->
|
||||
<div class="card hidden" id="step-run">
|
||||
<label>4. Выполнение</label>
|
||||
<p id="run-status"></p>
|
||||
<div class="progress"><div class="progress-bar" id="run-progress" style="width:0%"></div></div>
|
||||
<p id="run-count" style="font-size:.85rem;color:var(--muted)"></p>
|
||||
<div class="error-list" id="run-errors"></div>
|
||||
<button id="btn-download" style="display:none" onclick="downloadResult()">Скачать результат</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const token = localStorage.getItem('token');
|
||||
if (!token) window.location.href = '/';
|
||||
|
||||
const API = '/api/batch-v3';
|
||||
const H = {'Authorization': 'Bearer ' + token};
|
||||
let jobId = null;
|
||||
let verified = false;
|
||||
let timerInterval = null;
|
||||
let timerStart = 0;
|
||||
|
||||
function show(id) { document.getElementById(id).classList.remove('hidden'); }
|
||||
function hide(id) { document.getElementById(id).classList.add('hidden'); }
|
||||
function startTimer() {
|
||||
timerStart = Date.now();
|
||||
timerInterval = setInterval(() => {
|
||||
const s = Math.floor((Date.now() - timerStart) / 1000);
|
||||
const m = Math.floor(s / 60);
|
||||
const sec = s % 60;
|
||||
document.getElementById('analyze-timer').textContent = m > 0 ? m + 'м ' + sec + 'с' : sec + 'с';
|
||||
}, 1000);
|
||||
}
|
||||
function stopTimer() { if (timerInterval) { clearInterval(timerInterval); timerInterval = null; } }
|
||||
|
||||
async function uploadFiles() {
|
||||
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 btn = document.getElementById('btn-upload');
|
||||
btn.disabled = true; btn.textContent = 'Загружаю...';
|
||||
|
||||
const fd = new FormData();
|
||||
fd.append('zip_file', zipFile);
|
||||
fd.append('target_file', targetFile);
|
||||
fd.append('task_description', taskDesc || 'Перенести итоги из смет в сводный файл');
|
||||
|
||||
try {
|
||||
const r = await fetch(API + '/upload', {method: 'POST', headers: H, body: fd});
|
||||
if (r.status === 401) { window.location.href = '/'; return; }
|
||||
const data = await r.json();
|
||||
jobId = data.job_id;
|
||||
const info = data.csv_info;
|
||||
document.getElementById('csv-info').innerHTML =
|
||||
`<span>${data.total_files} xlsx</span><span>${info.sample_count} CSV сэмплов</span><span>~${Math.round(info.estimated_tokens/1000)}K токенов</span>`;
|
||||
show('step-analyze');
|
||||
startAnalysis();
|
||||
} catch(e) { alert('Ошибка: ' + e.message); }
|
||||
finally { btn.disabled = false; btn.textContent = 'Загрузить и конвертировать'; }
|
||||
}
|
||||
|
||||
async function startAnalysis() {
|
||||
const log = document.getElementById('analyze-log');
|
||||
const vstat = document.getElementById('verify-status');
|
||||
log.textContent = '';
|
||||
vstat.innerHTML = '';
|
||||
verified = false;
|
||||
startTimer();
|
||||
|
||||
try {
|
||||
const r = await fetch(API + '/analyze/' + jobId, {method: 'POST', headers: H});
|
||||
const reader = r.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
|
||||
while (true) {
|
||||
const {done, value} = await reader.read();
|
||||
if (done) break;
|
||||
buffer += decoder.decode(value, {stream: true});
|
||||
const lines = buffer.split('\n');
|
||||
buffer = lines.pop();
|
||||
|
||||
let eventType = '';
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('event: ')) { eventType = line.slice(7); continue; }
|
||||
if (!line.startsWith('data: ')) continue;
|
||||
try {
|
||||
const d = JSON.parse(line.slice(6));
|
||||
|
||||
if (eventType === 'text') {
|
||||
log.textContent += d.text;
|
||||
log.scrollTop = log.scrollHeight;
|
||||
} else if (eventType === 'tool') {
|
||||
log.textContent += '\n[tool: ' + d.tool + ']\n';
|
||||
log.scrollTop = log.scrollHeight;
|
||||
} else if (eventType === 'generation_start') {
|
||||
const att = d.attempt || 1;
|
||||
document.getElementById('analyze-status').textContent = att > 1
|
||||
? 'Попытка ' + att + '/3: Claude перегенерирует скрипт...'
|
||||
: 'Claude генерирует скрипт...';
|
||||
if (att > 1) log.textContent += '\n--- Попытка ' + att + ' ---\n';
|
||||
} else if (eventType === 'verify_start') {
|
||||
document.getElementById('analyze-status').textContent = 'Проверяю скрипт на 2 файлах...';
|
||||
vstat.innerHTML = '<p style="font-size:.85rem;color:var(--muted)">Выполняю скрипт на 2 сэмплах...</p>';
|
||||
} else if (eventType === 'verify_ok') {
|
||||
vstat.innerHTML = '<div class="verify-ok">Скрипт проверен: обработано ' + d.processed + ' файлов без ошибок</div>';
|
||||
} else if (eventType === 'verify_fail') {
|
||||
vstat.innerHTML = '<div class="verify-fail">Попытка ' + d.attempt + '/3: ошибка — ' + (d.error || '').slice(0, 200) + '</div>';
|
||||
} else if (eventType === 'retry') {
|
||||
log.textContent += '\n[retry: attempt ' + d.attempt + ']\n';
|
||||
} else if (eventType === 'done') {
|
||||
document.getElementById('analyze-spinner').style.display = 'none';
|
||||
stopTimer();
|
||||
verified = d.verified || false;
|
||||
if (d.script) {
|
||||
document.getElementById('analyze-status').textContent = 'Анализ завершён' + (d.attempts > 1 ? ' (попытка ' + d.attempts + ')' : '');
|
||||
document.getElementById('script-code').textContent = d.script;
|
||||
renderSummary(d.summary);
|
||||
// Verify badge
|
||||
const vb = document.getElementById('verify-badge');
|
||||
if (verified) {
|
||||
vb.innerHTML = '<div class="verify-ok">Скрипт прошёл автоматическую проверку</div>';
|
||||
} else {
|
||||
vb.innerHTML = '<div class="verify-fail">Скрипт НЕ прошёл проверку после 3 попыток. Запуск на ваш риск.</div>';
|
||||
}
|
||||
show('step-confirm');
|
||||
} else {
|
||||
document.getElementById('analyze-status').textContent = 'Claude не сгенерировал скрипт';
|
||||
document.getElementById('analyze-status').style.color = 'var(--accent)';
|
||||
}
|
||||
}
|
||||
} catch(e) {}
|
||||
}
|
||||
}
|
||||
} catch(e) {
|
||||
// Stream closed — fall through to polling
|
||||
}
|
||||
|
||||
// Polling fallback
|
||||
if (document.getElementById('step-confirm').classList.contains('hidden')) {
|
||||
stopTimer();
|
||||
document.getElementById('analyze-status').textContent = 'Проверяю результат...';
|
||||
for (let i = 0; i < 15; i++) {
|
||||
await new Promise(r => setTimeout(r, 3000));
|
||||
try {
|
||||
const sr = await fetch(API + '/status/' + jobId, {headers: H});
|
||||
const sd = await sr.json();
|
||||
if (sd.status === 'analyzed' && sd.script) {
|
||||
document.getElementById('analyze-spinner').style.display = 'none';
|
||||
document.getElementById('analyze-status').textContent = 'Анализ завершён';
|
||||
document.getElementById('script-code').textContent = sd.script;
|
||||
verified = sd.verified || false;
|
||||
renderSummary(sd.summary || {});
|
||||
const vb = document.getElementById('verify-badge');
|
||||
vb.innerHTML = verified
|
||||
? '<div class="verify-ok">Скрипт прошёл автоматическую проверку</div>'
|
||||
: '<div class="verify-fail">Скрипт НЕ прошёл проверку. Запуск на ваш риск.</div>';
|
||||
show('step-confirm');
|
||||
return;
|
||||
}
|
||||
} catch(e2) {}
|
||||
}
|
||||
document.getElementById('analyze-spinner').style.display = 'none';
|
||||
document.getElementById('analyze-status').textContent = 'Таймаут — попробуйте ещё раз';
|
||||
document.getElementById('analyze-status').style.color = 'var(--accent)';
|
||||
}
|
||||
}
|
||||
|
||||
async function runScript() {
|
||||
if (!verified) {
|
||||
if (!confirm('Скрипт НЕ прошёл автоматическую проверку. Запустить на свой риск?')) return;
|
||||
}
|
||||
try {
|
||||
const r = await fetch(API + '/run/' + jobId, {method: 'POST', headers: H});
|
||||
if (!r.ok) { alert('Ошибка запуска'); return; }
|
||||
show('step-run');
|
||||
pollStatus();
|
||||
} catch(e) { alert('Ошибка: ' + e.message); }
|
||||
}
|
||||
|
||||
async function pollStatus() {
|
||||
const r = await fetch(API + '/status/' + jobId, {headers: H});
|
||||
const d = await r.json();
|
||||
const pct = d.total > 0 ? (d.processed / d.total * 100) : 0;
|
||||
document.getElementById('run-progress').style.width = pct + '%';
|
||||
document.getElementById('run-count').textContent = d.processed + ' / ' + d.total + ' файлов';
|
||||
|
||||
if (d.status === 'running') {
|
||||
document.getElementById('run-status').textContent = 'Обработка...';
|
||||
setTimeout(pollStatus, 1500);
|
||||
} else if (d.status === 'completed') {
|
||||
document.getElementById('run-status').textContent = 'Готово! Обработано: ' + d.processed + ' из ' + d.total;
|
||||
document.getElementById('run-status').style.color = 'var(--green)';
|
||||
document.getElementById('btn-download').style.display = 'inline-block';
|
||||
} else if (d.status === 'failed') {
|
||||
document.getElementById('run-status').textContent = 'Ошибка выполнения';
|
||||
document.getElementById('run-status').style.color = 'var(--accent)';
|
||||
}
|
||||
if (d.errors && d.errors.length > 0) {
|
||||
document.getElementById('run-errors').innerHTML = '<b>Ошибки:</b><br>' + d.errors.map(e => '• ' + e).join('<br>');
|
||||
}
|
||||
}
|
||||
|
||||
function renderSummary(s) {
|
||||
const el = document.getElementById('summary-view');
|
||||
if (!s || !s.source_patterns) {
|
||||
el.innerHTML = '<p style="color:var(--muted)">Параметры не распознаны — проверьте скрипт вручную</p>';
|
||||
return;
|
||||
}
|
||||
const src = s.source_patterns || {};
|
||||
const tgt = s.target_mapping || {};
|
||||
let html = '';
|
||||
if (s.description) html += `<p><b>${s.description}</b></p>`;
|
||||
|
||||
html += '<table style="width:100%;border-collapse:collapse;margin:.5rem 0;font-size:.85rem">';
|
||||
html += '<tr style="background:#ede5db"><td colspan="2" style="padding:6px;font-weight:600">Исходные файлы</td></tr>';
|
||||
if (src.sheet) html += row('Лист', src.sheet);
|
||||
if (src.id_field) html += row('Шифр/название', src.id_field);
|
||||
if (src.value_column) html += row('Столбец значений', src.value_column);
|
||||
if (src.units) html += row('Единицы', src.units);
|
||||
if (src.totals) {
|
||||
html += '<tr style="background:#ede5db"><td colspan="2" style="padding:6px;font-weight:600">Паттерны поиска итогов</td></tr>';
|
||||
for (const [k, v] of Object.entries(src.totals)) html += row(k, '<code>' + v + '</code>');
|
||||
}
|
||||
html += '<tr style="background:#ede5db"><td colspan="2" style="padding:6px;font-weight:600">Сводный файл</td></tr>';
|
||||
if (tgt.sheet) html += row('Лист', tgt.sheet);
|
||||
if (tgt.match_column) html += row('Столбец сопоставления', tgt.match_column);
|
||||
if (tgt.value_columns) {
|
||||
for (const [k, v] of Object.entries(tgt.value_columns)) html += row(k + ' →', 'столбец ' + v);
|
||||
}
|
||||
if (tgt.units) html += row('Единицы', tgt.units);
|
||||
if (s.conversion) html += row('Конвертация', s.conversion);
|
||||
html += '</table>';
|
||||
|
||||
if (s.preview && s.preview.length > 0) {
|
||||
html += '<div style="margin-top:.8rem"><b>Превью маппинга (по сэмплам):</b></div>';
|
||||
html += '<table style="width:100%;border-collapse:collapse;margin:.3rem 0;font-size:.8rem">';
|
||||
html += '<tr style="background:#ede5db"><td style="padding:5px">Исходный файл</td><td style="padding:5px">Извлечённые значения</td><td style="padding:5px">→ Куда</td><td style="padding:5px">Записываемые значения</td></tr>';
|
||||
for (const p of s.preview) {
|
||||
const srcVals = p.source_values ? Object.entries(p.source_values).map(([k,v]) => k + ': ' + v).join('<br>') : '-';
|
||||
const tgtVals = p.target_values ? Object.entries(p.target_values).map(([k,v]) => k + '=' + v).join(', ') : '-';
|
||||
const tgtWhere = (p.target_sheet || '') + '<br>' + (p.target_row || '');
|
||||
html += '<tr><td style="padding:4px 5px;border-bottom:1px solid #eee;word-break:break-all">' + (p.source_file || '') + '</td><td style="padding:4px 5px;border-bottom:1px solid #eee;font-size:.75rem">' + srcVals + '</td><td style="padding:4px 5px;border-bottom:1px solid #eee;font-size:.75rem">' + tgtWhere + '</td><td style="padding:4px 5px;border-bottom:1px solid #eee"><code>' + tgtVals + '</code></td></tr>';
|
||||
}
|
||||
html += '</table>';
|
||||
}
|
||||
el.innerHTML = html;
|
||||
function row(label, value) {
|
||||
return `<tr><td style="padding:4px 6px;border-bottom:1px solid #eee;color:var(--muted);width:40%">${label}</td><td style="padding:4px 6px;border-bottom:1px solid #eee">${value}</td></tr>`;
|
||||
}
|
||||
}
|
||||
|
||||
function downloadResult() {
|
||||
fetch(API + '/download/' + jobId, {headers: H})
|
||||
.then(r => r.blob())
|
||||
.then(b => {
|
||||
const u = URL.createObjectURL(b);
|
||||
const a = document.createElement('a');
|
||||
a.href = u; a.download = 'result.xlsx'; a.click();
|
||||
URL.revokeObjectURL(u);
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user