Files
smeta-web/main.py
T
anorandClaude Opus 4.6 4d52c53702 feat: пакетная обработка смет (batch processor)
Новая страница /batch для массовых операций с файлами:
1. Загрузка zip со сметами + сводный файл
2. GLM-5 анализирует 3 примера → генерирует Python-скрипт
3. Пользователь подтверждает алгоритм
4. Скрипт обрабатывает ВСЕ файлы без LLM

- batch.py: XML-чтение xlsx, LLM-анализ, exec скрипта
- static/batch.html: UI с прогрессом и скачиванием результата
- Кнопка "Пакетная" в шапке чата

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 19:26:55 +10:00

370 lines
12 KiB
Python

"""smeta-web: AI assistant for estimators — FastAPI + Claude Code or GLM-5."""
import os
import shutil
from pathlib import Path
from fastapi import FastAPI, HTTPException, Request, UploadFile
from fastapi.responses import FileResponse, HTMLResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from auth import authenticate, verify_token
from db import get_history, init_db, list_sessions, save_message
# Backend: "claude" (Docker sandbox), "glm" (GLM-5 + CAG), "auto" (route by task)
AI_BACKEND = os.environ.get("AI_BACKEND", "claude")
if AI_BACKEND == "glm":
from claude_bridge_glm import (
clear_session, get_work_dir, is_allowed_file,
list_user_files, stream_claude,
)
elif AI_BACKEND == "auto":
from claude_bridge_glm import (
clear_session, get_work_dir, is_allowed_file, list_user_files,
)
from claude_bridge_glm import stream_claude as _stream_glm
from claude_bridge import stream_claude as _stream_claude
async def stream_claude(message: str, username: str, tab_id: str = "default"):
"""Auto-route: file-related → Claude Code, normative questions → GLM-5.
Logic:
1. Message mentions files/creating/editing → Claude
2. Message references uploaded file names → Claude
3. Everything else (НР, СП, коэффициенты, правила) → GLM
"""
msg_lower = message.lower()
# Keywords that need Claude Code (file operations)
claude_keywords = [
"создай файл", "сохрани в", "запиши в", "сделай таблиц",
"перенеси данн", "измени файл", "отредактируй", "скопируй",
"проверь смет", "проверь файл", "открой файл", "покажи файл",
"загруж", "прикреп", "файл", ".xlsx", ".docx", ".pdf", ".csv",
"внеси", "обнови", "заполни", "строк", "ячейк", "лист",
"ссрсс", "ссрс", "ведомост", "смет",
]
# Check if message references files in work directory (partial match)
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)
use_claude = mentions_file or has_keyword
stream_fn = _stream_claude if use_claude else _stream_glm
async for chunk in stream_fn(message, username, tab_id):
yield chunk
else:
from claude_bridge import (
clear_session, get_work_dir, is_allowed_file,
list_user_files, stream_claude,
)
app = FastAPI(title="smeta-web")
app.mount("/static", StaticFiles(directory="static"), name="static")
MAX_UPLOAD_SIZE = 50 * 1024 * 1024 # 50 MB
MAX_MESSAGE_LEN = 10_000
@app.on_event("startup")
async def startup():
init_db()
def _get_user(request: Request) -> str:
auth = request.headers.get("authorization", "")
token = auth.removeprefix("Bearer ").strip()
if not token:
raise HTTPException(401, "No token")
user = verify_token(token)
if not user:
raise HTTPException(401, "Invalid token")
return user
def _get_tab(request: Request, body: dict | None = None) -> str:
if body and "tab_id" in body:
return body["tab_id"]
return request.headers.get("x-tab-id", "default")
@app.get("/", response_class=HTMLResponse)
async def index():
return Path("static/chat.html").read_text(encoding="utf-8")
@app.post("/api/login")
async def login(request: Request):
body = await request.json()
username = body.get("username", "")
password = body.get("password", "")
client_ip = request.client.host if request.client else ""
token = authenticate(username, password, client_ip)
if not token:
raise HTTPException(401, "Wrong credentials")
return {"token": token, "username": username}
async def _stream_and_save(message: str, user: str, tab_id: str):
"""Wrap stream_claude to save messages to DB."""
save_message(user, tab_id, "user", message)
full_response = ""
async for chunk in stream_claude(message, user, tab_id):
yield chunk
# Collect text for saving
if "event: text" in chunk:
import json
for line in chunk.split("\n"):
if line.startswith("data: "):
try:
d = json.loads(line[6:])
full_response += d.get("text", "")
except Exception:
pass
elif "event: done" in chunk:
import json
for line in chunk.split("\n"):
if line.startswith("data: "):
try:
d = json.loads(line[6:])
if not full_response and d.get("result"):
full_response = d["result"]
except Exception:
pass
if full_response:
save_message(user, tab_id, "assistant", full_response)
@app.post("/api/chat")
async def chat(request: Request):
user = _get_user(request)
body = await request.json()
message = body.get("message", "").strip()
tab_id = _get_tab(request, body)
if not message:
raise HTTPException(400, "Empty message")
if len(message) > MAX_MESSAGE_LEN:
raise HTTPException(400, f"Message too long (max {MAX_MESSAGE_LEN} chars)")
return StreamingResponse(
_stream_and_save(message, user, tab_id),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no",
},
)
@app.get("/api/history")
async def history(request: Request):
user = _get_user(request)
tab_id = request.headers.get("x-tab-id", "default")
return get_history(user, tab_id)
@app.get("/api/sessions")
async def sessions(request: Request):
user = _get_user(request)
return list_sessions(user)
@app.post("/api/upload")
async def upload(request: Request, file: UploadFile):
user = _get_user(request)
tab_id = request.headers.get("x-tab-id", "default")
work_dir = get_work_dir(user, tab_id)
safe_name = Path(file.filename).name
if not safe_name or safe_name.startswith("."):
raise HTTPException(400, "Invalid filename")
if not is_allowed_file(safe_name):
raise HTTPException(
400,
f"File type not allowed. Allowed: xlsx, docx, pdf, csv, txt, xml, json, yaml",
)
chunks = []
total = 0
while True:
chunk = await file.read(1024 * 1024)
if not chunk:
break
total += len(chunk)
if total > MAX_UPLOAD_SIZE:
raise HTTPException(413, f"File too large (max {MAX_UPLOAD_SIZE // 1024 // 1024}MB)")
chunks.append(chunk)
dest = work_dir / safe_name
dest.write_bytes(b"".join(chunks))
save_message(user, tab_id, "system", f"Загружен файл: {safe_name} ({total} байт)")
return {"filename": safe_name, "size": total}
@app.get("/api/files")
async def files(request: Request):
user = _get_user(request)
tab_id = request.headers.get("x-tab-id", "default")
return list_user_files(user, tab_id)
@app.get("/api/files/{filename}")
async def download_file(filename: str, request: Request):
user = _get_user(request)
tab_id = request.headers.get("x-tab-id", "default")
safe_name = Path(filename).name
fpath = get_work_dir(user, tab_id) / safe_name
if not fpath.exists() or not fpath.is_file():
raise HTTPException(404, "File not found")
return FileResponse(fpath, filename=filename)
@app.post("/api/reset")
async def reset_session(request: Request):
user = _get_user(request)
tab_id = request.headers.get("x-tab-id", "default")
clear_session(user, tab_id)
return {"status": "ok"}
@app.post("/api/clear-files")
async def clear_files(request: Request):
user = _get_user(request)
tab_id = request.headers.get("x-tab-id", "default")
work_dir = get_work_dir(user, tab_id)
for f in work_dir.iterdir():
if f.name.startswith("."):
continue
if f.is_file():
f.unlink()
elif f.is_dir():
shutil.rmtree(f)
clear_session(user, tab_id)
return {"status": "ok"}
# === Batch processing ===
from batch import analyze_structure, create_job, extract_zip, get_job, run_batch
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")
@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)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "8000")))