Files
smeta-web/batch_v3.py
T
anorandClaude Opus 4.6 56ba1bd5aa chore: закоммичены все рабочие файлы smeta-web
Предотвращение потери данных при деплое:
batch_v3, search_engine, xlsx_utils, тесты, скрипты деплоя,
архитектура, security page, admin page.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 04:48:52 +10:00

767 lines
26 KiB
Python

"""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 xlsx_utils 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")
# 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
# V3 job storage (separate from V2)
_jobs: dict[str, dict] = {}
# ---------------------------------------------------------------------------
# Functions merged from batch_v2.py
# ---------------------------------------------------------------------------
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
SMETA_EXT = {'.xlsx', '.xls', '.gge', '.esw', '.xml'}
xlsx_files = sorted(
f for f in Path(source_dir).rglob("*")
if f.is_file() and f.suffix.lower() in SMETA_EXT
and not f.name.startswith("~$") and not f.name.startswith("._")
)
for xlsx in xlsx_files:
# .gge/.esw are XML — copy as-is (no xlsx conversion needed)
if xlsx.suffix.lower() in ('.gge', '.esw', '.xml'):
dst = Path(csv_dir) / f"{xlsx.stem}.xml"
shutil.copy2(str(xlsx), str(dst))
size = dst.stat().st_size
all_csv.append({"path": str(dst), "name": dst.name, "bytes": size})
total_bytes += size
continue
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).
"""
SMETA_EXT = {'.xlsx', '.xls', '.gge', '.esw', '.xml'}
xlsx_files = sorted(
[f for f in Path(source_dir).rglob("*")
if f.is_file() and f.suffix.lower() in SMETA_EXT
and not f.name.startswith("~$") and 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:
# .gge/.esw/.xml — copy as-is, no xlsx conversion
if Path(xlsx).suffix.lower() in ('.gge', '.esw', '.xml'):
dst = sample_csv_dir / f"{Path(xlsx).stem}.xml"
shutil.copy2(xlsx, str(dst))
converted_xlsx.append(xlsx)
sample_csvs.append(str(dst))
total_bytes += dst.stat().st_size
continue
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. FIRST write /data/batch_summary.json, THEN write /data/batch_script.py
## MANDATORY: /data/batch_summary.json — write this FIRST!
The user is a construction estimator, not a programmer. This summary is shown to them for review.
JSON with these fields (in Russian):
```json
{{
"description": "Краткое описание что будет сделано",
"source_patterns": {{
"sheet": "на каком листе искать данные",
"id_field": "где шифр/название сметы (например: имя файла, ячейка B5)",
"totals": {{
"строительные работы": "паттерн поиска (например: ВСЕГО строительные работы)",
"монтажные работы": "паттерн поиска",
"оборудование": "паттерн поиска",
"прочие затраты": "паттерн поиска"
}},
"value_column": "в каком столбце значения (например: A или H)",
"units": "рубли или тыс.руб"
}},
"target_mapping": {{
"sheet": "на какой лист сводного файла записывать",
"match_column": "столбец с шифрами для сопоставления (например: B)",
"value_columns": {{
"строительные работы": "столбец (например: D)",
"монтажные работы": "столбец (например: E)",
"оборудование": "столбец (например: F)",
"прочие затраты": "столбец (например: G)"
}},
"units": "тыс.руб"
}},
"conversion": "делить на 1000 (руб → тыс.руб)" или "без конвертации",
"preview": [
{{
"source_file": "имя файла источника",
"source_values": {{"строительные работы": 15460805.77, "монтажные работы": 0}},
"target_sheet": "ССРСС ТУЦ",
"target_row": "строка 17 (ЛС-01-02-2-00-01 Устройство насыпи)",
"target_values": {{"D": 15460.81, "E": 0, "F": 0, "G": 0}}
}}
]
}}
```
The "preview" array must contain entries for ALL sample files — show the actual extracted values
and where they will go in the target. This is the most important part for the user to verify!
### File 2: /data/batch_script.py — Python script
## 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]]]
IMPORTANT: ALWAYS pass max_rows=9999! Default is only 50 rows — totals are at the END of files!
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)
"""
def _read_result_files(job_dir: Path) -> dict:
"""Read batch_script.py and batch_summary.json from job dir."""
script_path = job_dir / "batch_script.py"
summary_path = job_dir / "batch_summary.json"
summary = {}
if summary_path.exists():
try:
summary = json.loads(summary_path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
pass
if script_path.exists():
return {"script": script_path.read_text(encoding="utf-8"), "summary": summary}
return {"script": "", "result": "Script not generated", "summary": summary}
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 (V2 style, no verify)."""
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"],
)
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,
"--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
result_data = _read_result_files(job_dir)
yield {"type": "done", **result_data}
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:
result_data = _read_result_files(job_dir)
yield {"type": "done", **result_data}
def run_batch_v2(job_id: str, script: str, source_dir: str, target_file: str):
"""Execute the Claude-generated script on all files."""
job = _jobs[job_id]
job["status"] = "running"
job["started_at"] = time.time()
SMETA_EXT = {'.xlsx', '.xls', '.gge', '.esw', '.xml'}
source_files = [
str(f) for f in Path(source_dir).rglob("*")
if f.is_file() and f.suffix.lower() in SMETA_EXT
and not f.name.startswith("~$") and 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()
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: str | Path,
) -> dict:
"""Execute script on 2 sample files to verify correctness.
Returns {"ok": True/False, "processed": int, "errors": [...], "error": str}.
"""
job_dir = Path(job_dir)
SMETA_EXT = {'.xlsx', '.xls', '.gge', '.esw', '.xml'}
# Select 2 sample files
all_files = sorted(
f for f in Path(source_dir).rglob("*")
if f.is_file() and f.suffix.lower() in SMETA_EXT
and not f.name.startswith("~$") and not f.name.startswith("._")
)
samples = [str(f) for f in all_files[: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 (run in thread to avoid blocking event loop)
yield {"type": "verify_start", "attempt": attempt}
loop = asyncio.get_event_loop()
result = await loop.run_in_executor(
None, 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()
SMETA_EXT = {'.xlsx', '.xls', '.gge', '.esw', '.xml'}
source_files = [
str(f) for f in Path(source_dir).rglob("*")
if f.is_file() and f.suffix.lower() in SMETA_EXT
and not f.name.startswith("~$") and 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()