feat: генератор ССР в веб-интерфейсе (/ssr)

Новая страница: загрузка ZIP с GGE → парсинг → 9 листов xlsx
+ HTML-превью в iframe для валидации перед скачиванием.
Кнопка "ССР" в навигации чата.
Эндпоинты: /api/ssr/upload, /api/ssr/preview, /api/ssr/download.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-30 04:36:12 +10:00
co-authored by Claude Opus 4.6
parent 1f3cf6d964
commit 678337ab3d
3 changed files with 384 additions and 120 deletions
+180 -115
View File
@@ -3,6 +3,7 @@
import json
import os
import shutil
import time
from pathlib import Path
from fastapi import FastAPI, HTTPException, Request, UploadFile
@@ -37,35 +38,54 @@ elif AI_BACKEND == "auto":
"""
msg_lower = message.lower()
# Keywords that need Claude Code (file operations)
claude_keywords = [
# Step 1: Strong file indicators (high confidence → Claude)
file_actions = [
"создай файл", "сохрани в", "запиши в", "сделай таблиц",
"перенеси данн", "измени файл", "отредактируй", "скопируй",
"проверь смет", "проверь файл", "открой файл", "покажи файл",
"загруж", "прикреп", "файл", ".xlsx", ".docx", ".pdf", ".csv",
"внеси", "обнови", "заполни", "строк", "ячейк", "лист",
"ссрсс", "ссрс", "ведомост", "смет",
"проверь файл", "открой файл", "покажи файл",
"загруж", "прикреп", ".xlsx", ".docx", ".pdf", ".csv",
"ячейк",
]
# Check if message references files in work directory (partial match)
# Step 2: Strong reference indicators (high confidence → GLM)
reference_words = [
"какой нр", "какой сп", "какая нр", "какая сп",
"коэффициент", "зимнее удорожан", "временные здани",
"расценк", "найди расценку", "найди норму",
"сметная цена", "цена материал",
"приказ ", "фснб", "методик",
"посчитай нр", "посчитай сп", "рассчитай",
"что ты умеешь", "помощь", "help",
]
# Step 3: Check file mentions in work directory
from claude_bridge_glm import get_work_dir as _get_wd
work_dir = _get_wd(username, tab_id)
has_files = False
mentions_file = False
if work_dir.exists():
for f in work_dir.iterdir():
if f.is_file() and not f.name.startswith("."):
has_files = True
# Check partial name match (without extension)
stem = f.stem.lower()
parts = [p for p in stem.replace("-", " ").replace("_", " ").split() if len(p) > 2]
if any(p in msg_lower for p in parts):
mentions_file = True
break
has_keyword = any(kw in msg_lower for kw in claude_keywords)
is_file_action = mentions_file or any(kw in msg_lower for kw in file_actions)
is_reference = any(kw in msg_lower for kw in reference_words)
# Decision: file action wins if explicit, otherwise reference
if is_file_action and not is_reference:
use_claude = True
elif is_reference and not is_file_action:
use_claude = False
elif is_file_action and is_reference:
# Ambiguous — file actions take priority (safer)
use_claude = True
else:
# Neither — default to GLM (normative reference)
use_claude = False
use_claude = mentions_file or has_keyword
stream_fn = _stream_claude if use_claude else _stream_sonnet
async for chunk in stream_fn(message, username, tab_id):
yield chunk
@@ -87,6 +107,22 @@ async def startup():
init_db()
# Rate limiting for chat API (10 requests/minute per user)
_chat_rate: dict[str, list[float]] = {}
CHAT_RATE_LIMIT = 10
CHAT_RATE_WINDOW = 60
def _check_rate_limit(user: str):
now = time.time()
times = _chat_rate.get(user, [])
times = [t for t in times if now - t < CHAT_RATE_WINDOW]
_chat_rate[user] = times
if len(times) >= CHAT_RATE_LIMIT:
raise HTTPException(429, "Too many requests. Wait a minute.")
times.append(now)
def _get_user(request: Request) -> str:
auth = request.headers.get("authorization", "")
token = auth.removeprefix("Bearer ").strip()
@@ -118,7 +154,24 @@ async def login(request: Request):
token = authenticate(username, password, client_ip)
if not token:
raise HTTPException(401, "Wrong credentials")
return {"token": token, "username": username}
from auth import _make_refresh_token, get_token_role
role = get_token_role(token)
refresh = _make_refresh_token(username, role)
return {"token": token, "refresh_token": refresh, "username": username}
@app.post("/api/refresh")
async def refresh_token(request: Request):
"""Exchange refresh token for new access token."""
body = await request.json()
refresh = body.get("refresh_token", "")
if not refresh:
raise HTTPException(400, "No refresh token")
from auth import refresh_access_token
new_token = refresh_access_token(refresh)
if not new_token:
raise HTTPException(401, "Invalid or expired refresh token")
return {"token": new_token}
@app.post("/api/register")
@@ -195,6 +248,7 @@ async def _stream_and_save(message: str, user: str, tab_id: str):
@app.post("/api/chat")
async def chat(request: Request):
user = _get_user(request)
_check_rate_limit(user)
body = await request.json()
message = body.get("message", "").strip()
tab_id = _get_tab(request, body)
@@ -309,8 +363,8 @@ async def clear_files(request: Request):
# === Batch processing ===
from batch import analyze_structure, create_job, extract_zip, get_job, run_batch
import batch_v2
from xlsx_utils import extract_zip
import batch_v3
import threading
import uuid
@@ -322,96 +376,7 @@ async def batch_page():
return Path("static/batch.html").read_text(encoding="utf-8")
@app.post("/api/batch/upload")
async def batch_upload(request: Request):
"""Upload zip + target file, extract, analyze structure."""
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 = BATCH_DIR / user / job_id
job_dir.mkdir(parents=True, exist_ok=True)
# Save target
target_path = job_dir / Path(target_file.filename).name
target_content = await target_file.read()
target_path.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))
# Analyze with LLM
analysis = await analyze_structure(source_files, str(target_path), task_desc)
job = create_job(job_id)
job["source_dir"] = str(source_dir)
job["target_file"] = str(target_path)
job["total_files"] = len(source_files)
job["analysis"] = analysis
job["status"] = "analyzed"
return {
"job_id": job_id,
"total_files": len(source_files),
"analysis": analysis,
}
@app.post("/api/batch/run/{job_id}")
async def batch_run(job_id: str, request: Request):
"""Confirm and run the batch script."""
_get_user(request)
job = 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")
# Run in background thread
threading.Thread(
target=run_batch,
args=(job_id, script, job["source_dir"], job["target_file"]),
daemon=True,
).start()
return {"status": "started", "job_id": job_id}
@app.get("/api/batch/status/{job_id}")
async def batch_status(job_id: str, request: Request):
_get_user(request)
job = 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", [])[:10],
"description": job.get("analysis", {}).get("description", ""),
}
@app.get("/api/batch/download/{job_id}")
async def batch_download(job_id: str, request: Request):
_get_user(request)
job = 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)
# V1 batch endpoints removed — use /api/batch-v3/* instead
# === Batch V2: Claude Code analysis ===
@@ -459,14 +424,14 @@ async def batch_v2_upload(request: Request):
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)
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_v2.prepare_samples(str(source_dir), job_dir, {})
sample_info = batch_v3.prepare_samples(str(source_dir), job_dir, {})
# Create job
job = batch_v2.create_job(job_id)
job = batch_v3.create_job(job_id)
job["source_dir"] = str(source_dir)
job["target_file"] = str(target_path)
job["target_name"] = target_name
@@ -492,7 +457,7 @@ async def batch_v2_upload(request: Request):
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)
job = batch_v3.get_job(job_id)
if not job:
raise HTTPException(404, "Job not found")
@@ -503,7 +468,7 @@ async def batch_v2_analyze(job_id: str, request: Request):
sample_info = job["sample_info"]
async def event_stream():
async for event in batch_v2.run_claude_analysis(
async for event in batch_v3.run_claude_analysis(
job_dir, task_desc, target_name, total_files, sample_info
):
etype = event.get("type", "")
@@ -533,7 +498,7 @@ async def batch_v2_analyze(job_id: str, request: Request):
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)
job = batch_v3.get_job(job_id)
if not job:
raise HTTPException(404, "Job not found")
@@ -542,7 +507,7 @@ async def batch_v2_run(job_id: str, request: Request):
raise HTTPException(400, "No script generated")
threading.Thread(
target=batch_v2.run_batch_v2,
target=batch_v3.run_batch_v2,
args=(job_id, script, job["source_dir"], job["target_file"]),
daemon=True,
).start()
@@ -553,7 +518,7 @@ async def batch_v2_run(job_id: str, request: Request):
@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)
job = batch_v3.get_job(job_id)
if not job:
raise HTTPException(404, "Job not found")
@@ -561,7 +526,7 @@ async def batch_v2_status(job_id: str, request: Request):
# 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_v2._read_result_files(job_dir)
result_data = batch_v3._read_result_files(job_dir)
if result_data.get("script"):
job["analysis"] = {
"python_script": result_data["script"],
@@ -583,7 +548,7 @@ async def batch_v2_status(job_id: str, request: Request):
@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)
job = batch_v3.get_job(job_id)
if not job or not job.get("output_file"):
raise HTTPException(404, "Result not ready")
return FileResponse(job["output_file"], filename=Path(job["output_file"]).name)
@@ -890,6 +855,106 @@ async def batch_v3_download(job_id: str, request: Request):
return FileResponse(job["output_file"], filename=Path(job["output_file"]).name)
# ── SSR Generator ───────────────────────────────────────────────────────────
# In-memory SSR job store (same pattern as batch)
_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")
@app.post("/api/ssr/upload")
async def ssr_upload(request: Request):
"""Upload ZIP with GGE files → parse → 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")
# Optional params
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))
title = form.get("title", "")
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 from smeta-railway/scripts (pip install -e ../smeta-railway)
import sys
for scripts_dir in [
str(Path(__file__).resolve().parent / ".." / "smeta-railway" / "scripts"),
str(Path.home() / "smeta-railway" / "scripts"),
]:
if Path(scripts_dir).exists() and scripts_dir not in sys.path:
sys.path.insert(0, scripts_dir)
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")
# Parse GGE
data = parse_gge_from_zip(str(zip_path))
if title:
data["title"] = title
# Generate SSR
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,
)
# Store job
_ssr_jobs[job_id] = {
"user": user,
"job_dir": str(job_dir),
"xlsx_path": xlsx_path,
"html_path": html_path,
"result": result,
}
# Return preview HTML content + stats
preview_html = Path(html_path).read_text(encoding="utf-8")
return {
"job_id": job_id,
"preview_html": preview_html,
"stats": result,
}
@app.get("/api/ssr/preview/{job_id}")
async def ssr_preview(job_id: str, request: Request):
_get_user(request)
job = _ssr_jobs.get(job_id)
if not job:
raise HTTPException(404, "Job not found")
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):
_get_user(request)
job = _ssr_jobs.get(job_id)
if not job:
raise HTTPException(404, "Job not found")
return FileResponse(job["xlsx_path"], filename="ssr_generated.xlsx")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "8000")))