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:
anor
2026-03-25 23:14:50 +10:00
co-authored by Claude Opus 4.6
parent 84a0ee234f
commit 5ebf9db332
3 changed files with 781 additions and 0 deletions
+384
View File
@@ -0,0 +1,384 @@
"""Batch V2: Claude Code analyzes ALL files, generates custom script.
Unlike V1 (GLM + deterministic template), V2 uses Claude Code (1M context)
to read actual file contents and generate a tailored Python script.
Flow:
1. User uploads zip (smetas) + target xlsx + task description
2. Server extracts, converts ALL xlsx → CSV (handles broken openpyxl files)
3. Claude Code reads CSVs + target, generates Python script
4. User confirms → script executes on all files
5. Result: updated target xlsx
"""
import asyncio
import csv
import json
import os
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
DOCKER_IMAGE = os.environ.get("CLAUDE_DOCKER_IMAGE", "smeta-claude-sandbox")
CLAUDE_CONFIG_DIR = os.environ.get(
"CLAUDE_CONFIG_DIR", os.path.expanduser("~/.claude")
)
DOCKER_HOST_GW = os.environ.get("DOCKER_HOST_GW", "172.17.0.1")
XRAY_PORT = os.environ.get("XRAY_PORT", "10809")
# Batch V2 jobs storage
_jobs: dict[str, dict] = {}
# Token estimation: ~0.3 tokens per byte for CSV text
TOKENS_PER_BYTE = 0.3
MAX_CONTEXT_TOKENS = 800_000 # leave headroom from 1M
MAX_SAMPLE_FILES = 15 # sample xlsx for Claude to read
MAX_SAMPLE_BYTES = 500_000 # max total bytes of sample CSVs
def convert_xlsx_to_csv(xlsx_path: str, output_dir: str) -> list[str]:
"""Convert xlsx to CSV files via XML parser (handles broken styles).
Returns list of created CSV file paths.
"""
data = read_xlsx_xml(xlsx_path, max_rows=9999)
if "_error" in data and len(data) == 1:
return []
created = []
stem = Path(xlsx_path).stem
for sheet_name, rows in data.items():
if sheet_name == "_error":
continue
# Skip empty sheets
if not rows or all(not any(cell for cell in row) for row in rows):
continue
safe_name = "".join(c if c.isalnum() or c in " _-" else "_" for c in sheet_name)
csv_path = Path(output_dir) / f"{stem}__{safe_name}.csv"
with open(csv_path, "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
for row in rows:
writer.writerow(row)
created.append(str(csv_path))
return created
def convert_all_to_csv(source_dir: str, csv_dir: str) -> dict:
"""Convert all xlsx files in source_dir to CSV in csv_dir.
Returns {"files": [...], "total_bytes": int, "estimated_tokens": int}.
"""
Path(csv_dir).mkdir(parents=True, exist_ok=True)
all_csv = []
total_bytes = 0
xlsx_files = sorted(Path(source_dir).rglob("*.xlsx"))
xlsx_files = [f for f in xlsx_files if not f.name.startswith("~$")]
for xlsx in xlsx_files:
csvs = convert_xlsx_to_csv(str(xlsx), csv_dir)
for c in csvs:
size = Path(c).stat().st_size
all_csv.append({"path": c, "name": Path(c).name, "bytes": size})
total_bytes += size
return {
"files": all_csv,
"total_bytes": total_bytes,
"estimated_tokens": int(total_bytes * TOKENS_PER_BYTE),
"xlsx_count": len(xlsx_files),
}
def select_samples(source_dir: str, csv_info: dict) -> list[str]:
"""Select a diverse sample of xlsx files for Claude to analyze.
Strategy: pick files of different sizes and from different subdirs.
Returns list of xlsx file paths (originals, not CSV).
"""
xlsx_files = sorted(
[f for f in Path(source_dir).rglob("*.xlsx") if not f.name.startswith("~$")],
key=lambda f: f.stat().st_size,
)
if len(xlsx_files) <= MAX_SAMPLE_FILES:
return [str(f) for f in xlsx_files]
# Pick diverse: smallest, largest, and evenly spaced
n = len(xlsx_files)
indices = set()
indices.add(0) # smallest
indices.add(n - 1) # largest
# Evenly spaced
step = max(1, n // (MAX_SAMPLE_FILES - 2))
for i in range(0, n, step):
indices.add(i)
if len(indices) >= MAX_SAMPLE_FILES:
break
# If still room, add from different directories
if len(indices) < MAX_SAMPLE_FILES:
dirs_seen = set()
for i, f in enumerate(xlsx_files):
d = str(f.parent)
if d not in dirs_seen:
dirs_seen.add(d)
indices.add(i)
if len(indices) >= MAX_SAMPLE_FILES:
break
return [str(xlsx_files[i]) for i in sorted(indices)][:MAX_SAMPLE_FILES]
def prepare_samples(source_dir: str, job_dir: Path, csv_info: dict) -> dict:
"""Convert only sample files to CSV in /data/sample_csv/ for Claude.
Returns {"sample_files": [...], "sample_csv_dir": str}.
"""
sample_xlsx = select_samples(source_dir, csv_info)
sample_csv_dir = job_dir / "sample_csv"
sample_csv_dir.mkdir(parents=True, exist_ok=True)
converted_xlsx = []
sample_csvs = []
total_bytes = 0
for xlsx in sample_xlsx:
csvs = convert_xlsx_to_csv(xlsx, str(sample_csv_dir))
converted_xlsx.append(xlsx)
for c in csvs:
size = Path(c).stat().st_size
sample_csvs.append(c)
total_bytes += size
if total_bytes > MAX_SAMPLE_BYTES:
break
return {
"sample_files": converted_xlsx,
"sample_csv_dir": str(sample_csv_dir),
"sample_csv_count": len(sample_csvs),
"sample_bytes": total_bytes,
}
def build_claude_prompt(
task_description: str,
sample_csv_dir: str,
target_csv_dir: str,
target_filename: str,
total_xlsx_count: int,
sample_xlsx_names: list[str],
) -> str:
"""Build the prompt for Claude Code to analyze sample files and generate script."""
sample_names = "\n".join(f"- {Path(f).name}" for f in sample_xlsx_names)
return f"""You are an expert in Russian construction cost estimation (smeta).
## Task
{task_description}
## Source files
There are {total_xlsx_count} xlsx source files total. You have {len(sample_xlsx_names)} SAMPLE files
converted to CSV in /data/sample_csv/ for analysis.
CSV naming: {{original_xlsx_stem}}__{{sheet_name}}.csv
Sample files:
{sample_names}
## Target file
The target summary file is converted to CSV in /data/target_csv/.
Original filename: {target_filename}
NOTE: In the script, use the `target_file` variable (not a hardcoded path).
## Your job
1. Read the sample CSV files in /data/sample_csv/ — understand their structure
2. Read the target CSV files in /data/target_csv/ — understand where data goes
3. Figure out: what to extract from each source, how to match to target rows
4. Write a COMPLETE Python script to /data/batch_script.py
## CRITICAL: The script will run on ALL {total_xlsx_count} files, not just samples!
The script must handle any file with the same general structure as the samples.
## Script execution context (these variables will be available):
- `source_files`: list[str] — paths to ALL {total_xlsx_count} original xlsx files
- `target_file`: str — path to target xlsx (a copy, safe to modify)
- `job`: dict — job["processed"] += 1 per file, job["errors"].append("msg") for errors
- `read_xlsx_xml(path, max_rows=9999)`: dict[sheet_name, list[list[str]]]
Column indices: A=0, B=1, C=2, ..., H=7, etc. Values are strings.
- `openpyxl`: for writing to target xlsx
- `Path`, `csv`, `json`, `re`, `os`
## Script requirements
- Self-contained, using ONLY the variables above
- NO `if __name__` or `def main()` wrappers — top-level code
- Robust: skip files with unexpected structure, log to job["errors"]
- Track progress: job["processed"] += 1 after each successful file
- Save at the end: wb.save(target_file)
"""
async def run_claude_analysis(
job_dir: Path,
task_description: str,
target_filename: str,
total_xlsx_count: int,
sample_info: dict,
) -> AsyncGenerator[dict, None]:
"""Run Claude Code in Docker to analyze files and generate script.
Yields SSE-like dicts: {"type": "text", "text": "..."} or {"type": "tool", "tool": "..."}
Final yield: {"type": "done", "script": "..."} or {"type": "error", "error": "..."}
"""
target_csv_dir = str(job_dir / "target_csv")
prompt = build_claude_prompt(
task_description,
sample_info["sample_csv_dir"],
target_csv_dir,
target_filename,
total_xlsx_count,
sample_info["sample_files"],
)
# Docker command — mount job_dir as /data
cmd = [
"docker", "run", "--rm",
"--memory=1g",
"--cpus=2",
"--network=host",
# Mount job directory as /data (rw)
"-v", f"{job_dir.resolve()}:/data",
# Mount Claude auth
"-v", f"{CLAUDE_CONFIG_DIR}:/home/worker/.claude",
"-v", f"{os.path.expanduser('~')}/.claude.json:/home/worker/.claude.json",
# Environment
"-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,
# Claude args
"-p", prompt,
"--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.PIPE,
)
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
script_path = job_dir / "batch_script.py"
if script_path.exists():
script = script_path.read_text(encoding="utf-8")
yield {"type": "done", "script": script}
else:
result_text = event.get("result", "")
yield {"type": "done", "script": "", "result": result_text}
finally:
if proc.returncode is None:
proc.terminate()
await proc.wait()
# If Claude exited without result event — read stderr
if not got_result:
stderr = await proc.stderr.read()
err_msg = stderr.decode()[:500] if stderr else "Claude exited without result"
yield {"type": "done", "script": "", "result": f"Error: {err_msg}"}
def run_batch_v2(job_id: str, script: str, source_dir: str, target_file: str):
"""Execute the Claude-generated script. Same as V1 but with more imports."""
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"] = []
# Copy target to output
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": __import__("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()
def create_job(job_id: str) -> dict:
_jobs[job_id] = {
"id": job_id,
"status": "created",
"total_files": 0,
"processed": 0,
"errors": [],
}
return _jobs[job_id]
def get_job(job_id: str) -> dict | None:
return _jobs.get(job_id)
+161
View File
@@ -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")))
+236
View File
@@ -0,0 +1,236 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Пакетная обработка V2 — Claude Code</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; }
.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); } }
</style>
</head>
<body>
<div class="container">
<a class="back" href="/">&#8592; Вернуться в чат</a>
<h1>Пакетная обработка смет <span class="badge">V2 Claude</span></h1>
<p class="subtitle">Claude Code читает ВСЕ файлы, понимает структуру, генерирует скрипт обработки</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 -->
<div class="card hidden" id="step-analyze">
<label>2. Анализ Claude Code</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></p>
<div class="log" id="analyze-log"></div>
</div>
<!-- Step 3: Confirm script -->
<div class="card hidden" id="step-confirm">
<label>3. Сгенерированный скрипт</label>
<p class="hint">Проверьте скрипт и нажмите «Запустить»</p>
<pre id="script-code"></pre>
<div style="display:flex;gap:.5rem;margin-top:.8rem">
<button onclick="runScript()">Запустить обработку</button>
<button onclick="reanalyze()" style="background:var(--border);color:var(--text)">Переанализировать</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 H = {'Authorization': 'Bearer ' + token};
let jobId = null;
function show(id) { document.getElementById(id).classList.remove('hidden'); }
function hide(id) { document.getElementById(id).classList.add('hidden'); }
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/batch-v2/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');
log.textContent = '';
try {
const r = await fetch('/api/batch-v2/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(); // keep incomplete line
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 === 'done') {
document.getElementById('analyze-spinner').style.display = 'none';
if (d.script) {
document.getElementById('analyze-status').textContent = 'Анализ завершён';
document.getElementById('script-code').textContent = d.script;
show('step-confirm');
} else {
document.getElementById('analyze-status').textContent = 'Claude не сгенерировал скрипт';
document.getElementById('analyze-status').style.color = 'var(--accent)';
}
}
} catch(e) {}
}
}
} catch(e) {
document.getElementById('analyze-spinner').style.display = 'none';
document.getElementById('analyze-status').textContent = 'Ошибка: ' + e.message;
document.getElementById('analyze-status').style.color = 'var(--accent)';
}
}
async function reanalyze() {
hide('step-confirm');
document.getElementById('analyze-spinner').style.display = 'inline-block';
document.getElementById('analyze-status').textContent = 'Claude анализирует файлы...';
document.getElementById('analyze-status').style.color = '';
startAnalysis();
}
async function runScript() {
try {
const r = await fetch('/api/batch-v2/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/batch-v2/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 => '&bull; ' + e).join('<br>');
}
}
function downloadResult() {
fetch('/api/batch-v2/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>