diff --git a/batch.py b/batch.py
deleted file mode 100644
index 266eead..0000000
--- a/batch.py
+++ /dev/null
@@ -1,416 +0,0 @@
-"""Batch processor: LLM analyzes structure, generates script, runs on all files.
-
-Flow:
-1. User uploads zip (smetas) + target xlsx (summary)
-2. Server extracts, reads 3 sample files via XML
-3. GLM analyzes structure → generates Python processing script
-4. User confirms (or corrects)
-5. Script runs on ALL files without LLM
-6. Result: updated target xlsx + error log
-"""
-
-import csv
-import io
-import json
-import os
-import shutil
-import tempfile
-import time
-import traceback
-import zipfile
-import xml.etree.ElementTree as ET
-from pathlib import Path
-
-import httpx
-
-ZAI_API_KEY = os.environ.get("ZAI_API_KEY", "")
-ZAI_BASE_URL = os.environ.get("ZAI_BASE_URL", "https://open.bigmodel.cn/api/coding/paas/v4")
-try:
- import model_registry
- ZAI_MODEL = model_registry.model_id("batch") # единый реестр (env ZAI_MODEL override)
-except Exception: # noqa: BLE001 — fail-soft
- ZAI_MODEL = os.environ.get("ZAI_MODEL", "glm-5.1")
-
-# Batch jobs storage
-_jobs: dict[str, dict] = {}
-
-
-def read_xlsx_xml(path: str, max_rows: int = 50) -> dict:
- """Read xlsx via XML (handles broken styles). Returns {sheet_name: [[row], ...]}."""
- result = {}
- try:
- z = zipfile.ZipFile(path)
- ns = {'s': 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'}
- # Shared strings
- strings = []
- try:
- ss = ET.parse(z.open('xl/sharedStrings.xml')).getroot()
- for si in ss.findall('.//s:si', ns):
- strings.append(''.join(t.text or '' for t in si.findall('.//s:t', ns)))
- except KeyError:
- pass
- # Sheet names and rels
- wb = ET.parse(z.open('xl/workbook.xml')).getroot()
- rels = ET.parse(z.open('xl/_rels/workbook.xml.rels')).getroot()
- # Parse rels regardless of namespace
- rid_map = {}
- for r in rels.iter():
- rid = r.get('Id', '')
- tgt = r.get('Target', '')
- if rid and tgt:
- rid_map[rid] = tgt
-
- for sheet in wb.findall('.//s:sheet', ns):
- name = sheet.get('name', '')
- rid = sheet.attrib.get('{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id', '')
- target = rid_map.get(rid, '')
- if not target:
- continue
- # Normalize path (handle leading / or relative)
- if target.startswith('/'):
- sheet_path = target.lstrip('/')
- elif target.startswith('xl/'):
- sheet_path = target
- else:
- sheet_path = f'xl/{target}'
- try:
- sheet_xml = ET.parse(z.open(sheet_path)).getroot()
- except KeyError:
- continue
- rows = []
- for row_el in sheet_xml.findall('.//s:row', ns):
- row_num = int(row_el.get('r', len(rows) + 1))
- # Pad with empty rows if needed
- while len(rows) < row_num - 1:
- rows.append([])
- if len(rows) >= max_rows:
- break
- # Parse cells with proper column positions
- row_data = [''] * 26 # A-Z
- for c in row_el.findall('s:c', ns):
- ref = c.get('r', '') # e.g. "B5", "H29"
- cell_type = c.get('t', '')
- v = c.find('s:v', ns)
- val = v.text if v is not None else ''
- if cell_type == 's' and val.isdigit():
- idx = int(val)
- val = strings[idx] if idx < len(strings) else val
- elif cell_type == 'inlineStr':
- # Inline string: text
- is_el = c.find('s:is', ns)
- if is_el is not None:
- val = ''.join(t.text or '' for t in is_el.findall('.//s:t', ns))
- # Extract column index from ref (A=0, B=1, ..., H=7)
- col_letters = ''.join(ch for ch in ref if ch.isalpha())
- col_idx = 0
- for ch in col_letters.upper():
- col_idx = col_idx * 26 + (ord(ch) - ord('A'))
- if col_idx < len(row_data):
- row_data[col_idx] = val
- # Trim trailing empty cells
- while row_data and row_data[-1] == '':
- row_data.pop()
- rows.append(row_data)
- result[name] = rows
- z.close()
- except Exception as e:
- result['_error'] = str(e)
- return result
-
-
-def extract_zip(zip_path: str, dest_dir: str) -> list[str]:
- """Extract zip and return list of xlsx files.
-
- Handles Cyrillic filenames: Python's zipfile decodes names as CP437
- when the UTF-8 flag is not set. We detect and fix this.
- """
- with zipfile.ZipFile(zip_path) as z:
- for info in z.infolist():
- # Fix Cyrillic filenames: if flag bit 11 is not set,
- # Python decodes as CP437 — re-encode and decode as UTF-8
- if not (info.flag_bits & 0x800):
- try:
- fixed = info.filename.encode('cp437').decode('utf-8')
- info.filename = fixed
- except (UnicodeDecodeError, UnicodeEncodeError):
- pass # keep original if re-decode fails
- # Skip macOS resource fork files and __MACOSX directory
- basename = Path(info.filename).name
- if basename.startswith('._') or '__MACOSX' in info.filename:
- continue
- z.extract(info, dest_dir)
- # Collect all supported smeta file types
- SMETA_EXTENSIONS = {'.xlsx', '.xls', '.gge', '.esw', '.xml'}
- files = []
- for f in Path(dest_dir).rglob('*'):
- if f.is_file() and f.suffix.lower() in SMETA_EXTENSIONS \
- and not f.name.startswith('~$') and not f.name.startswith('._'):
- files.append(str(f))
- return sorted(files)
-
-
-async def analyze_structure(sample_files: list[str], target_file: str, task_description: str) -> dict:
- """Use LLM to analyze file structure and generate processing script."""
- # Read samples — head + tail to see structure AND totals
- samples = []
- for f in sample_files[:3]:
- data = read_xlsx_xml(f, max_rows=999)
- sample = {'filename': Path(f).name, 'sheets': {}}
- for k, v in data.items():
- if k == '_error':
- continue
- head = v[:15]
- tail = v[-50:] if len(v) > 50 else v[15:]
- # Compact: only non-empty rows
- head_compact = [[j, row[j]] for row in head for j in range(len(row)) if row[j]]
- tail_compact = []
- for i, row in enumerate(tail):
- row_idx = len(v) - len(tail) + i
- cells = [[j, row[j]] for j in range(len(row)) if row[j]]
- if cells:
- tail_compact.append({'row': row_idx, 'cells': cells[:6]})
- sample['sheets'][k] = {
- 'total_rows': len(v),
- 'head': head_compact[:30],
- 'tail': tail_compact[:30],
- }
- samples.append(sample)
-
- # Read target structure
- target_data = read_xlsx_xml(target_file, max_rows=50)
- target_info = {'filename': Path(target_file).name, 'sheets': {}}
- for k, v in target_data.items():
- if k == '_error':
- continue
- compact = []
- for i, row in enumerate(v[:30]):
- cells = [[j, row[j]] for j in range(len(row)) if row[j]]
- if cells:
- compact.append({'row': i, 'cells': cells[:8]})
- target_info['sheets'][k] = {'total_rows': len(v), 'rows': compact}
-
- prompt = f"""Ты — эксперт по автоматизации сметного дела.
-
-Задача: {task_description}
-
-## Примеры исходных файлов (3 штуки):
-{json.dumps(samples, ensure_ascii=False, indent=2)[:6000]}
-
-## Сводный файл:
-{json.dumps(target_info, ensure_ascii=False, indent=2)[:3000]}
-
-## Определи:
-1. Где в исходном файле шифр сметы (лист, строка, столбец)
-2. Где итоговые суммы (строительные, монтажные, оборудование, прочие)
-3. Где в сводном файле строки для записи (лист, столбец с шифрами, столбцы для значений)
-
-## ВАЖНО: В скрипте используй ТОЛЬКО эти переменные:
-- `source_files` — list[str] путей ко всем xlsx файлам
-- `target_file` — str путь к сводному файлу (уже скопирован, пиши в него)
-- `job` — dict: job["processed"] += 1 (int счётчик), job["errors"].append("описание") (list строк)
-- `read_xlsx_xml(path, max_rows=999)` — функция чтения xlsx через XML, возвращает dict[sheet_name, list[list[str]]]
-- `openpyxl` — для записи в target_file
-
-Ответь ТОЛЬКО JSON (без markdown, без ```):
-{{
- "description": "описание алгоритма на русском",
- "source_code_cell": "B5",
- "source_totals": {{"строительные": "H29", "монтажные": "H30", "оборудование": "H31", "прочие": "H32"}},
- "target_sheet": "ССРСС-1 ТУЦ",
- "target_match_col": "B",
- "target_value_cols": {{"строительные": "D", "монтажные": "E", "оборудование": "F", "прочие": "G"}}
-}}"""
-
- proxy = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")
- async with httpx.AsyncClient(timeout=300, proxy=proxy) as client:
- resp = await client.post(
- f"{ZAI_BASE_URL}/chat/completions",
- headers={"Authorization": f"Bearer {ZAI_API_KEY}"},
- json={
- "model": ZAI_MODEL,
- "messages": [
- {"role": "system", "content": "Ты генерируешь ТОЛЬКО валидный JSON. Никакого текста вне JSON."},
- {"role": "user", "content": prompt},
- ],
- "temperature": 0.1,
- "max_tokens": 4000,
- "response_format": {"type": "json_object"},
- "thinking": {"type": "disabled"},
- },
- )
- resp.raise_for_status()
- msg = resp.json()["choices"][0]["message"]
- content = msg.get("content") or msg.get("reasoning_content") or ""
-
- # Parse JSON from response
- try:
- if "```json" in content:
- content = content.split("```json")[1].split("```")[0]
- elif "```" in content:
- content = content.split("```")[1].split("```")[0]
- params = json.loads(content)
- except (json.JSONDecodeError, IndexError):
- return {"error": "Failed to parse LLM response", "raw": content[:2000]}
-
- # Generate deterministic script from params
- params["python_script"] = _build_batch_script(params)
- return params
-
-
-def _col_to_idx(col: str) -> int:
- """A→0, B→1, H→7"""
- result = 0
- for ch in col.upper():
- result = result * 26 + (ord(ch) - ord('A'))
- return result
-
-
-def _build_batch_script(params: dict) -> str:
- """Build deterministic Python script from LLM-extracted params."""
- code_cell = params.get("source_code_cell", "B5")
- totals = params.get("source_totals", {})
- target_sheet = params.get("target_sheet", "")
- match_col = params.get("target_match_col", "B")
- value_cols = params.get("target_value_cols", {})
-
- # Parse code cell → row, col indices
- code_col = ''.join(c for c in code_cell if c.isalpha())
- code_row = ''.join(c for c in code_cell if c.isdigit())
- code_col_idx = _col_to_idx(code_col)
- code_row_idx = int(code_row) - 1 if code_row else 4
-
- # Parse total cells
- total_cells = []
- for name, cell in totals.items():
- col = ''.join(c for c in cell if c.isalpha())
- row = ''.join(c for c in cell if c.isdigit())
- total_cells.append((name, _col_to_idx(col), int(row) - 1 if row else 0))
-
- # Parse target columns
- target_cols = {}
- for name, col in value_cols.items():
- target_cols[name] = _col_to_idx(col) + 1 # openpyxl is 1-indexed
-
- match_col_idx = _col_to_idx(match_col) + 1
-
- # Build value extraction lines
- value_lines = []
- for name, ci, ri in total_cells:
- tcol = target_cols.get(name, ci + 4)
- value_lines.append(
- f" v=0\n"
- f" if len(sheet)>{ri} and len(sheet[{ri}])>{ci}:\n"
- f" try: v=float(str(sheet[{ri}][{ci}] or 0).replace(',','.').replace(' ','') or 0)\n"
- f" except: v=0\n"
- f" ws.cell(row, {tcol}).value = v"
- )
- values_code = "\n".join(value_lines)
-
- return (
- "import openpyxl\n"
- "wb = openpyxl.load_workbook(target_file)\n"
- f"ws = wb['{target_sheet}'] if '{target_sheet}' in wb.sheetnames else wb.active\n"
- "code_to_row = {}\n"
- f"for r in range(1, ws.max_row + 1):\n"
- f" v = ws.cell(r, {match_col_idx}).value\n"
- " if v:\n"
- " code_to_row[str(v).strip()] = r\n"
- "for f in source_files:\n"
- " try:\n"
- " data = read_xlsx_xml(f, max_rows=100)\n"
- " if not data:\n"
- " job['errors'].append(f + ': empty'); continue\n"
- " sheet = list(data.values())[0]\n"
- f" if len(sheet) <= {code_row_idx} or len(sheet[{code_row_idx}]) <= {code_col_idx}:\n"
- " job['errors'].append(f + ': no code'); continue\n"
- f" code = str(sheet[{code_row_idx}][{code_col_idx}]).strip()\n"
- " if not code or code not in code_to_row:\n"
- " job['errors'].append(f + ': ' + code + ' not found'); continue\n"
- " row = code_to_row[code]\n"
- f"{values_code}\n"
- " job['processed'] += 1\n"
- " except Exception as e:\n"
- " job['errors'].append(f + ': ' + str(e))\n"
- "wb.save(target_file)\n"
- )
-
-
-def run_batch(job_id: str, script: str, source_dir: str, target_file: str):
- """Execute generated script on all files. Updates job status."""
- 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"] = []
- job["error_count"] = 0 # int counter for scripts that do += 1
-
- # Create a safe execution environment
- output_file = str(Path(target_file).parent / f"result_{Path(target_file).name}")
- shutil.copy2(target_file, output_file)
-
- # Fix common LLM mistakes in generated scripts
- import re
- script = script.replace("job['errors'] += 1", "job['errors'].append('error')")
- script = script.replace('job["errors"] += 1', 'job["errors"].append("error")')
- # Fix sheet name access — add fallback to active sheet
- script = re.sub(
- r"wb_target\['([^']+)'\]",
- r"(wb_target['\1'] if '\1' in wb_target.sheetnames else wb_target.active)",
- script
- )
- script = re.sub(
- r'wb_target\["([^"]+)"\]',
- r'(wb_target["\1"] if "\1" in wb_target.sheetnames else wb_target.active)',
- script
- )
- # If LLM wrapped in def main() / if __name__, call main() at the end
- if "def main()" in script and "if __name__" in script:
- script = re.sub(r"if __name__\s*==\s*['\"]__main__['\"]\s*:\s*\n\s*main\(\)", "", script)
- script += "\nmain()\n"
-
- 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,
- }
- 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 get_job(job_id: str) -> dict | None:
- return _jobs.get(job_id)
-
-
-def create_job(job_id: str):
- _jobs[job_id] = {
- "id": job_id,
- "status": "created",
- "total_files": 0,
- "processed": 0,
- "errors": [],
- }
- return _jobs[job_id]
diff --git a/batch_v3.py b/batch_v3.py
deleted file mode 100644
index c70c19e..0000000
--- a/batch_v3.py
+++ /dev/null
@@ -1,771 +0,0 @@
-"""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")
-try:
- import model_registry
- CLAUDE_MODEL = model_registry.model_id("sonnet_cli") # единый реестр (env CLAUDE_MODEL override)
-except Exception: # noqa: BLE001 — fail-soft
- CLAUDE_MODEL = os.environ.get("CLAUDE_MODEL", "sonnet")
-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 (--model из CLAUDE_MODEL). 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", CLAUDE_MODEL,
- "--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()
diff --git a/main.py b/main.py
index 7ef78a9..f92f572 100644
--- a/main.py
+++ b/main.py
@@ -964,17 +964,9 @@ async def clear_files(request: Request):
# === Batch processing ===
-from xlsx_utils import extract_zip
-import batch_v3
import threading
import uuid
-BATCH_DIR = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / "_batch"
-
-
-@app.get("/batch", response_class=HTMLResponse)
-async def batch_page():
- return Path("static/batch.html").read_text(encoding="utf-8")
# V1 batch endpoints removed — use /api/batch-v3/* instead
@@ -983,173 +975,6 @@ async def batch_page():
# === 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_v3.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_v3.prepare_samples(str(source_dir), job_dir, {})
-
- # Create job
- job = batch_v3.create_job(job_id)
- job["user"] = user # владелец — для проверки доступа в analyze/run/status/download
- 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."""
- user = _get_user(request)
- job = _require_job_owner(batch_v3.get_job(job_id), user)
-
- 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_v3.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", "")
- summary = event.get("summary", {})
- if script:
- job["analysis"] = {"python_script": script, "summary": summary}
- 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, 'summary': summary, '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."""
- user = _get_user(request)
- job = _require_job_owner(batch_v3.get_job(job_id), user)
-
- script = job.get("analysis", {}).get("python_script", "")
- if not script:
- raise HTTPException(400, "No script generated")
-
- threading.Thread(
- target=batch_v3.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):
- user = _get_user(request)
- job = _require_job_owner(batch_v3.get_job(job_id), user)
-
- # If status is still "uploaded" but files exist on disk — Claude finished
- # but SSE didn't deliver the done event
- if job["status"] == "uploaded" and job.get("job_dir"):
- job_dir = Path(job["job_dir"])
- result_data = batch_v3._read_result_files(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", {}),
- }
-
-
-@app.get("/api/batch-v2/download/{job_id}")
-async def batch_v2_download(job_id: str, request: Request):
- user = _get_user(request)
- job = _require_job_owner(batch_v3.get_job(job_id), user)
- if not job.get("output_file"):
- raise HTTPException(404, "Result not ready")
- return FileResponse(job["output_file"], filename=Path(job["output_file"]).name)
-
-
# === Admin: view user sessions ===
@@ -1484,169 +1309,6 @@ async def admin_page(request: Request):
# === 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["user"] = user # владелец — для проверки доступа в analyze/run/status/download
- 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."""
- user = _get_user(request)
- job = _require_job_owner(batch_v3.get_job(job_id), user)
-
- 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):
- user = _get_user(request)
- job = _require_job_owner(batch_v3.get_job(job_id), user)
- 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):
- user = _get_user(request)
- job = _require_job_owner(batch_v3.get_job(job_id), user)
-
- # 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):
- user = _get_user(request)
- job = _require_job_owner(batch_v3.get_job(job_id), user)
- if not job.get("output_file"):
- raise HTTPException(404, "Result not ready")
- return FileResponse(job["output_file"], filename=Path(job["output_file"]).name)
# ── SSR Generator ───────────────────────────────────────────────────────────
@@ -1655,11 +1317,6 @@ async def batch_v3_download(job_id: str, request: Request):
_ssr_jobs: dict[str, dict] = {}
-@app.get("/ssr", response_class=HTMLResponse)
-async def ssr_page():
- return Path("static/ssr.html").read_text(encoding="utf-8")
-
-
def _import_ssr_scripts():
"""Import smeta-railway scripts (installed via pip install -e)."""
import sys
@@ -1671,113 +1328,6 @@ def _import_ssr_scripts():
sys.path.insert(0, scripts_dir)
-@app.post("/api/ssr/upload")
-async def ssr_upload(request: Request):
- """Upload ZIP (+ optional xlsx) → fill or generate SSR → return preview."""
- user = _get_user(request)
- form = await request.form()
- zip_file: UploadFile = form.get("zip_file")
- if not zip_file or not zip_file.filename.lower().endswith(".zip"):
- raise HTTPException(400, "ZIP file required")
-
- xlsx_file: UploadFile = form.get("xlsx_file")
- mode = form.get("mode", "generate") # "fill" or "generate"
-
- # Params (for generate mode)
- winter_pct = float(form.get("winter_pct", 3.2))
- control_pct = float(form.get("control_pct", 0.55))
- reserve_pct = float(form.get("reserve_pct", 1.0))
- vat_pct = float(form.get("vat_pct", 22.0))
-
- job_id = str(uuid.uuid4())[:8]
- data_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data"))
- job_dir = data_dir / "_ssr" / user / job_id
- job_dir.mkdir(parents=True, exist_ok=True)
-
- # Save ZIP
- zip_path = job_dir / "source.zip"
- zip_path.write_bytes(await zip_file.read())
-
- _import_ssr_scripts()
-
- if mode == "fill" and xlsx_file:
- # Mode: fill existing xlsx with GGE data
- try:
- from fill_raspredelenie import fill_raspredelenie_from_zip
- except ImportError:
- raise HTTPException(500, "smeta-railway scripts not found")
-
- xlsx_path = job_dir / xlsx_file.filename
- xlsx_path.write_bytes(await xlsx_file.read())
-
- output_path = str(job_dir / f"filled_{xlsx_file.filename}")
- result = fill_raspredelenie_from_zip(str(zip_path), str(xlsx_path), output_path)
-
- if "error" in result:
- raise HTTPException(400, result["error"])
-
- html_path = str(job_dir / "protocol.html")
- Path(html_path).write_text(result["html"], encoding="utf-8")
-
- _ssr_jobs[job_id] = {
- "user": user, "job_dir": str(job_dir),
- "xlsx_path": output_path, "html_path": html_path,
- "result": result["stats"],
- }
-
- return {
- "job_id": job_id,
- "preview_html": result["html"],
- "stats": result["stats"],
- "mode": "fill",
- }
-
- else:
- # Mode: generate new SSR from scratch
- try:
- from parse_gge_structure import parse_gge_from_zip
- from generate_ssr import generate_ssr_from_data
- except ImportError:
- raise HTTPException(500, "smeta-railway scripts not found")
-
- data = parse_gge_from_zip(str(zip_path))
- xlsx_path = str(job_dir / "ssr.xlsx")
- html_path = str(job_dir / "ssr.html")
- result = generate_ssr_from_data(
- data, xlsx_path, html_path,
- winter_pct=winter_pct, control_pct=control_pct,
- reserve_pct=reserve_pct, vat_pct=vat_pct,
- )
-
- _ssr_jobs[job_id] = {
- "user": user, "job_dir": str(job_dir),
- "xlsx_path": xlsx_path, "html_path": html_path,
- "result": result,
- }
-
- preview_html = Path(html_path).read_text(encoding="utf-8")
- return {
- "job_id": job_id,
- "preview_html": preview_html,
- "stats": result,
- "mode": "generate",
- }
-
-
-@app.get("/api/ssr/preview/{job_id}")
-async def ssr_preview(job_id: str, request: Request):
- user = _get_user(request)
- job = _require_job_owner(_ssr_jobs.get(job_id), user)
- return HTMLResponse(Path(job["html_path"]).read_text(encoding="utf-8"))
-
-
-@app.get("/api/ssr/download/{job_id}")
-async def ssr_download(job_id: str, request: Request):
- user = _get_user(request)
- job = _require_job_owner(_ssr_jobs.get(job_id), user)
- return FileResponse(job["xlsx_path"], filename="ssr_generated.xlsx")
-
-
# ── Wizard Aggregator ──────────────────────────────────────────────────────
def _import_smeta_railway():
@@ -1793,166 +1343,32 @@ def _import_smeta_railway():
_import_smeta_railway()
-@app.get("/wizard", response_class=HTMLResponse)
-async def wizard_page():
- return Path("static/wizard.html").read_text(encoding="utf-8")
-
-
# Import and mount smeta-railway routers
-from smeta_railway.web.wizard_api import router as _wizard_router
-from smeta_railway.web.generator_api import router as _gen_router
-from smeta_railway.web.chat_api import router as _chat_sr_router
# Смонтированные роутеры не имели auth вообще → аноним жёг LLM/RAG-бюджет и грузил
# файлы (Fable verify). Гейт на уровне монтирования — БЕЗ правки чужого пакета smeta_railway.
# Живой чат их не использует (только депрекированные generate/reference/wizard).
-app.include_router(_wizard_router, prefix="/api/wizard", dependencies=[Depends(_auth_dep)])
-app.include_router(_gen_router, prefix="/api/gen", dependencies=[Depends(_auth_dep)])
-app.include_router(_chat_sr_router, prefix="/api/ref", dependencies=[Depends(_auth_dep)])
-
-
-@app.get("/generate", response_class=HTMLResponse)
-async def generate_page():
- return Path("static/generate.html").read_text(encoding="utf-8")
-
-
-@app.get("/reference", response_class=HTMLResponse)
-async def reference_page():
- return Path("static/reference.html").read_text(encoding="utf-8")
# ── Estimate Checker ──────────────────────────────────────────────────────
-@app.get("/check", response_class=HTMLResponse)
-async def check_page():
- return Path("static/check.html").read_text(encoding="utf-8")
-
-
-@app.post("/api/check/yaml")
-async def check_yaml_endpoint(request: Request):
- """Validate YAML config and return check report."""
- import tempfile
- from smeta_railway.ai.checker import check_yaml_config, format_report
-
- _get_user(request) # закрыт от анонима (был публичный compute-эндпоинт)
- body = await request.json()
- yaml_content = body.get("yaml", "")
- if not yaml_content.strip():
- raise HTTPException(400, "Empty YAML")
-
- # Write to temp file for checker
- with tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False) as f:
- f.write(yaml_content)
- tmp_path = f.name
-
- try:
- report = check_yaml_config(tmp_path)
- return {
- "errors": report.errors,
- "warnings": report.warnings,
- "info": report.info,
- "results": [
- {"level": r.level, "code": r.code, "message": r.message, "position": r.position}
- for r in report.results
- ],
- "formatted": format_report(report),
- }
- except Exception as exc:
- logger.exception("check_yaml failed") # детали — в лог оператору, не клиенту
- return {"error": "Не удалось проверить конфигурацию", "results": []}
- finally:
- Path(tmp_path).unlink(missing_ok=True)
-
-
# ── Full Pipeline: YAML → Calculate → Excel ───────────────────────────────
-@app.post("/api/gen/calculate")
-async def calculate_estimate(request: Request):
- """Take YAML config, run calculation, generate Excel, return download link."""
- _get_user(request) # был аноним; ниже мёртвый код с сырым traceback — закрыть до ревайва
- # ⛔ Путь LLM→движок пока НЕ оживлён: код ниже зовёт несуществующие методы
- # (ProjectConfig.from_yaml_string / NormResources.from_dict / FGISLookup(region=))
- # и отдавал сырой traceback пользователю. Кнопка «Генерация» депрекирована
- # (chat.html, 2026-05-07), путь достижим лишь прямым URL. До keystone-ревайва
- # (роадмап: оживить контракт с fail-loud цен + проверенным маппингом НР/СП по
- # 812/774/пр) — честный ответ вместо сырой ошибки. Логика ниже сохранена как
- # стартовая точка ревайва.
- return {
- "error": "Автоматический расчёт сметы пока в разработке — функция скоро появится.",
- "download_url": None,
- }
- import tempfile
- import yaml as pyyaml
- body = await request.json()
- yaml_str = body.get("yaml", "")
- if not yaml_str.strip():
- raise HTTPException(400, "Empty YAML")
-
- try:
- from smeta_railway.config import ProjectConfig
- from smeta_railway.calc.estimate import EstimateCalculator
- from smeta_railway.data.fgis import FGISLookup
- from smeta_railway.output.excel_se import write_excel
- from smeta_railway.models import NormResources
-
- # Parse config
- config = ProjectConfig.from_yaml_string(yaml_str)
-
- # Load resources
- resources_path = Path(__file__).resolve().parent / ".." / "smeta-railway" / "resources.json"
- if not resources_path.exists():
- resources_path = Path.home() / "smeta-railway" / "resources.json"
- if not resources_path.exists():
- return {"error": "resources.json не найден — расчёт невозможен", "download_url": None}
-
- import json as _json
- raw = _json.loads(resources_path.read_text(encoding="utf-8"))
- resources = {k: NormResources.from_dict(v) for k, v in raw.items()}
-
- # FGIS lookup
- fgis = FGISLookup(region=config.region)
-
- # Calculate
- calc = EstimateCalculator(
- fgis=fgis,
- resources=resources,
- coeff_config=config.coefficients,
- overhead_config=config.overhead,
- limited_costs_config=config.limited_costs,
- )
- result = calc.calculate(config.sections)
-
- # Write Excel
- data_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / "_estimates"
- data_dir.mkdir(parents=True, exist_ok=True)
- job_id = str(uuid.uuid4())[:8]
- xlsx_path = data_dir / f"estimate_{job_id}.xlsx"
- write_excel(result, str(xlsx_path), config)
-
- return {
- "download_url": f"/api/gen/download/{job_id}",
- "positions": len(result.positions),
- "total": result.total if hasattr(result, "total") else None,
- "error": None,
- }
- except Exception as exc:
- import traceback
- return {"error": str(exc), "detail": traceback.format_exc()[-500:], "download_url": None}
+# ── Депрекированные страницы → всё переехало в чат (Fable retire 2026-07-18) ──
+# Пакетная обработка/SSR/генерация: там ИИ-скрипт исполнялся на хосте (риск RCE
+# через смету-с-начинкой) + анонимные роуты. Функционал давно заменён чатом.
+from fastapi.responses import RedirectResponse as _DepRedirect
-@app.get("/api/gen/download/{job_id}")
-async def download_estimate(job_id: str, request: Request):
- """Download generated Excel estimate."""
- _get_user(request) # был публичный доступ к файлам по угадываемому id
- safe_id = Path(job_id).name # без traversal в имени файла
- data_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / "_estimates"
- xlsx_path = data_dir / f"estimate_{safe_id}.xlsx"
- if not xlsx_path.exists():
- raise HTTPException(404, "Файл не найден")
- return FileResponse(str(xlsx_path), filename=f"smeta_{safe_id}.xlsx")
+async def _deprecated_moved():
+ return _DepRedirect("/", status_code=302)
+for _dep_url in ("/batch", "/batch2", "/batch3", "/ssr", "/wizard",
+ "/generate", "/reference", "/check"):
+ app.add_api_route(_dep_url, _deprecated_moved, methods=["GET"], include_in_schema=False)
+
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "8000")))
diff --git a/static/batch.html b/static/batch.html
deleted file mode 100644
index 5d9d601..0000000
--- a/static/batch.html
+++ /dev/null
@@ -1,157 +0,0 @@
-
-
-
-
-
-Пакетная обработка смет
-
-
-
-
-
← Вернуться в чат
-
Пакетная обработка смет
-
Загрузите архив со сметами и сводный файл — ИИ проанализирует структуру и перенесёт данные
-
-
-
-
-
Результат анализа
-
-
- Сгенерированный скрипт
-
-
-
-
Запустить обработку
-
-
-
-
Обработка
-
-
-
-
-
Скачать результат
-
-
-
-
-
-
diff --git a/static/batch2.html b/static/batch2.html
deleted file mode 100644
index a6c50dc..0000000
--- a/static/batch2.html
+++ /dev/null
@@ -1,348 +0,0 @@
-
-
-
-
-
-Пакетная обработка V2 — Claude Code
-
-
-
-
-
← Вернуться в чат
-
Пакетная обработка смет V2 Claude
-
Claude Code читает ВСЕ файлы, понимает структуру, генерирует скрипт обработки
-
-
-
-
1. Архив со сметами (.zip)
-
Все файлы локальных смет в одном архиве (до 2000 файлов)
-
-
-
Сводный файл (.xlsx)
-
Файл, в который нужно внести данные (ССР, ведомость и т.д.)
-
-
-
Описание задачи
-
Опишите что именно нужно сделать — Claude прочитает файлы и разберётся
-
-
-
Загрузить и конвертировать
-
-
-
-
-
2. Анализ Claude Code
-
-
Claude анализирует файлы...
-
-
-
-
-
-
3. Проверьте найденные параметры
-
-
- Показать скрипт (для разработчиков)
-
-
-
- Запустить обработку
- Переанализировать
-
-
-
-
-
-
4. Выполнение
-
-
-
-
-
Скачать результат
-
-
-
-
-
-
diff --git a/static/batch3.html b/static/batch3.html
deleted file mode 100644
index 57be94b..0000000
--- a/static/batch3.html
+++ /dev/null
@@ -1,389 +0,0 @@
-
-
-
-
-
-Пакетная обработка V3 — Verify
-
-
-
-
-
← Вернуться в чат
-
Пакетная обработка смет V3 Verify
-
Claude генерирует скрипт + автоматическая проверка на 2 файлах + auto-retry
-
-
-
-
1. Архив со сметами (.zip)
-
Все файлы локальных смет в одном архиве (до 2000 файлов)
-
-
Сводный файл (.xlsx)
-
Файл, в который нужно внести данные (ССР, ведомость и т.д.)
-
-
Описание задачи
-
Опишите что именно нужно сделать — Claude прочитает файлы и разберётся
-
-
-
Загрузить и конвертировать
-
-
-
-
-
2. Генерация + верификация
-
-
Claude генерирует скрипт...
-
-
-
-
-
-
-
3. Проверьте найденные параметры
-
-
-
Копировать параметры
-
- Показать скрипт (для разработчиков)
-
-
-
- Запустить обработку
-
-
-
-
-
-
4. Выполнение
-
-
-
-
-
Скачать результат
-
-
-
-
-
-
diff --git a/static/check.html b/static/check.html
deleted file mode 100644
index dc4e6dd..0000000
--- a/static/check.html
+++ /dev/null
@@ -1,137 +0,0 @@
-
-
-
-
-
-Проверка сметы
-
-
-
-
-
-
-
-
Загрузите YAML-файл проекта:
-
-
или вставьте YAML вручную:
-
-
- Проверить
-
-
-
-
-
-
-
-
-
diff --git a/static/generate.html b/static/generate.html
deleted file mode 100644
index 1e5865f..0000000
--- a/static/generate.html
+++ /dev/null
@@ -1,219 +0,0 @@
-
-
-
-
-
-Генерация сметы
-
-
-
-
-
-
-
- Шаг 1 из 3
- Описание работ
-
-
-
-
-
Опишите работы
-
-
-
-
- Разобрать на позиции
-
-
-
-
-
-
-
Проверьте позиции и расценки
-
-
- Назад
-
- Сформировать смету
-
-
-
-
-
-
-
Конфигурация сметы
-
-
- Назад
-
- Рассчитать и скачать Excel
-
- Скопировать YAML
-
-
-
-
-
-
-
Смета готова
-
Расчёт выполнен. Скачайте файл Excel.
-
-
-
-
-
-
-
-
diff --git a/static/reference.html b/static/reference.html
deleted file mode 100644
index ded8084..0000000
--- a/static/reference.html
+++ /dev/null
@@ -1,115 +0,0 @@
-
-
-
-
-
-Справочники
-
-
-
-
-
-
-
- Поиск ГЭСН
- НР
- СП
-
-
-
-
-
-
-
-
diff --git a/static/ssr.html b/static/ssr.html
deleted file mode 100644
index 8c3ef4b..0000000
--- a/static/ssr.html
+++ /dev/null
@@ -1,204 +0,0 @@
-
-
-
-
-
-Генератор ССР
-
-
-
-
-
← Вернуться в чат
-
Генератор ССР из GGE
-
Загрузите ZIP с GGE-файлами — получите сводный сметный расчёт (9 листов) с превью
-
-
-
-
1. Архив с GGE-файлами (.zip) *
-
ZIP со всеми локальными сметами в формате GGE (до 2000 файлов)
-
-
-
2. Сводный файл (.xlsx) — необязательно
-
Ваш существующий ССР/РАСПРЕДЕЛЕНИЕ. Скрипт заполнит GGE-данные в лист РАСПРЕДЕЛЕНИЕ, остальные листы не тронет.
- Если не указан — будет сгенерирован новый файл с нуля (9 листов).
-
-
-
Параметры расчёта (для генерации с нуля)
-
-
-
Заполнить / Генерировать ССР
-
-
-
-
-
-
Парсинг GGE-файлов и генерация ССР...
-
Это может занять 10-30 секунд для крупных архивов
-
-
-
-
-
Результат
-
-
Скачать XLSX (9 листов)
-
-
Превью
-
-
-
-
-
-
-
diff --git a/static/wizard.html b/static/wizard.html
deleted file mode 100644
index 792e6a1..0000000
--- a/static/wizard.html
+++ /dev/null
@@ -1,235 +0,0 @@
-
-
-
-
-
-Агрегатор xlsx
-
-
-
-
-
-
-
-
-
-
-
Загрузка файлов
-
ZIP-архив с источниками
-
Целевой файл (.xlsx)
-
Загрузить
-
-
-
-
-
-
-
Критерий поиска
-
-
Лист
-
Колонка
-
Ключевое слово
-
-
Найти
-
-
-
-
-
-
Колонка значений
-
Из какой колонки брать числа?
-
Превью
-
-
-
-
-
-
Сопоставление с целевым
-
-
-
-
-
-
Действие
-
-
Операция Суммировать Заменить Максимум Минимум
-
Записать в колонку
-
-
-
-
-
-
Ненайденные строки
- Добавить новые строки Пропустить
-
-
-
-
-
Превью и подтверждение
-
-
-
-
Применить и скачать
-
-
-
-
- Назад
- Далее
-
-
-
-
-
-
diff --git a/tests/test_block1_auth.py b/tests/test_block1_auth.py
index f2fe716..cbe6355 100644
--- a/tests/test_block1_auth.py
+++ b/tests/test_block1_auth.py
@@ -61,57 +61,21 @@ def test_legit_tab_still_works(env):
assert r.json() == []
-# ---- анонимные эндпоинты закрыты ----
+# ---- депрекированный пакетный путь убран целиком (exec на хосте + анонимные роуты) ----
-def test_gen_download_requires_auth(env):
+def test_deprecated_pages_redirect(env):
_auth, _main, client, _tmp = env
- r = client.get("/api/gen/download/anything") # без Authorization
- assert r.status_code == 401
+ for url in ("/batch2", "/batch3", "/ssr", "/generate", "/wizard", "/reference", "/check"):
+ r = client.get(url, follow_redirects=False)
+ assert r.status_code == 302, f"{url} → {r.status_code}"
+ assert r.headers.get("location", "").endswith("/"), f"{url} → {r.headers.get('location')}"
-def test_check_yaml_requires_auth(env):
+def test_deprecated_api_endpoints_gone(env):
_auth, _main, client, _tmp = env
- r = client.post("/api/check/yaml", json={"yaml": "x: 1"})
- assert r.status_code == 401
-
-
-def test_mounted_routers_and_gen_reject_anon(env):
- """Fable verify #1/#4: /api/gen|ref|wizard/* были полностью анонимны (жгли LLM/RAG,
- грузили файлы). Ни один маршрут под этими префиксами не должен пускать без токена."""
- import re as _re
- _auth, main, client, _tmp = env
- targets = []
- for r in main.app.routes:
- p = getattr(r, "path", "")
- if p.startswith(("/api/ref/", "/api/wizard/", "/api/gen/")): # с '/' — не ловить /api/refresh
- methods = getattr(r, "methods", None) or {"GET"}
- m = "POST" if "POST" in methods else ("GET" if "GET" in methods else next(iter(methods)))
- targets.append((m, _re.sub(r"\{[^}]+\}", "x", p)))
- assert targets, "нет смонтированных маршрутов — тест бесполезен"
- for m, url in targets:
- resp = client.request(m, url) # без Authorization
- assert resp.status_code == 401, f"{m} {url} → {resp.status_code}, ждали 401"
-
-
-# ---- владелец job'а ----
-
-def test_require_job_owner_helper(env):
- _auth, main, _client, _tmp = env
- from fastapi import HTTPException
- assert main._require_job_owner({"user": "a@x"}, "a@x")["user"] == "a@x"
- with pytest.raises(HTTPException):
- main._require_job_owner({"user": "a@x"}, "b@x") # чужой → 404
- with pytest.raises(HTTPException):
- main._require_job_owner(None, "a@x") # нет job → 404
-
-
-def test_batch_v3_status_foreign_is_404(env):
- _auth, main, client, _tmp = env
- auth = _auth
- # заводим job вручную от имени owner@x, спрашиваем от mallory@x
- import batch_v3
- job = batch_v3.create_job("deadbeef")
- job["user"] = "owner@x"
- job["job_dir"] = "/tmp/nope"
- r = client.get("/api/batch-v3/status/deadbeef", headers=_h(auth, user="mallory@x"))
- assert r.status_code == 404
+ # exec-путь (batch v2/v3) + SSR + анонимные gen/check/ref/wizard удалены → маршрута нет
+ for m, url in [("POST", "/api/batch-v3/upload"), ("POST", "/api/batch-v2/upload"),
+ ("POST", "/api/ssr/upload"), ("POST", "/api/check/yaml"),
+ ("GET", "/api/gen/download/x"), ("POST", "/api/gen/parse"),
+ ("POST", "/api/ref/search"), ("POST", "/api/wizard/upload")]:
+ assert client.request(m, url).status_code == 404, f"{m} {url} всё ещё жив"