Files
smeta-web/main.py
T
anorandClaude Opus 4.6 5ebf9db332 feat: Batch V2 — Claude Code анализирует файлы и генерирует скрипт
Вместо GLM + шаблонного скрипта (V1), V2 использует Claude Code (1M контекст):
- Сэмплирует 15 файлов из набора (до 2000+), конвертирует xlsx→CSV
- Claude читает сэмплы + target, генерирует кастомный Python-скрипт
- Адаптируется к ЛЮБОЙ структуре файлов (не hardcoded формат)
- Пользователь подтверждает → скрипт выполняется на всех файлах

Новые файлы: batch_v2.py, static/batch2.html
Новые endpoints: /batch2, /api/batch-v2/{upload,analyze,run,status,download}
V1 (/batch) остаётся как fallback.

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

531 lines
18 KiB
Python

"""smeta-web: AI assistant for estimators — FastAPI + Claude Code or GLM-5."""
import json
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 batch_v2
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)
# === Batch V2: Claude Code analysis ===
@app.get("/batch2", response_class=HTMLResponse)
async def batch2_page():
return Path("static/batch2.html").read_text(encoding="utf-8")
@app.post("/api/batch-v2/upload")
async def batch_v2_upload(request: Request):
"""Upload zip + target, convert xlsx→CSV, start Claude analysis (SSE stream)."""
user = _get_user(request)
form = await request.form()
zip_file = form.get("zip_file")
target_file = form.get("target_file")
task_desc = form.get("task_description", "Перенести итоги из смет в сводный файл")
if not zip_file or not target_file:
raise HTTPException(400, "Need zip_file and target_file")
job_id = str(uuid.uuid4())[:8]
job_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / "_batch_v2" / user / job_id
job_dir.mkdir(parents=True, exist_ok=True)
# Save target
target_name = Path(target_file.filename).name
target_path = job_dir / target_name
target_content = await target_file.read()
target_path.write_bytes(target_content)
# Also save as target.xlsx for Claude
(job_dir / "target.xlsx").write_bytes(target_content)
# Save and extract zip
zip_path = job_dir / "source.zip"
zip_content = await zip_file.read()
zip_path.write_bytes(zip_content)
source_dir = job_dir / "source"
source_dir.mkdir(exist_ok=True)
source_files = extract_zip(str(zip_path), str(source_dir))
# Convert target → CSV for Claude to read (only the target file)
target_only_dir = job_dir / "_target_only"
target_only_dir.mkdir(exist_ok=True)
shutil.copy2(str(target_path), str(target_only_dir / target_name))
target_csv_dir = str(job_dir / "target_csv")
batch_v2.convert_all_to_csv(str(target_only_dir), target_csv_dir)
shutil.rmtree(str(target_only_dir))
# Select and convert SAMPLE files (not all — could be 2000+)
sample_info = batch_v2.prepare_samples(str(source_dir), job_dir, {})
# Create job
job = batch_v2.create_job(job_id)
job["source_dir"] = str(source_dir)
job["target_file"] = str(target_path)
job["target_name"] = target_name
job["job_dir"] = str(job_dir)
job["total_files"] = len(source_files)
job["task_description"] = task_desc
job["sample_info"] = sample_info
job["status"] = "uploaded"
return {
"job_id": job_id,
"total_files": len(source_files),
"csv_info": {
"sample_count": sample_info["sample_csv_count"],
"sample_bytes": sample_info["sample_bytes"],
"estimated_tokens": int(sample_info["sample_bytes"] * 0.3),
"xlsx_count": len(source_files),
},
}
@app.post("/api/batch-v2/analyze/{job_id}")
async def batch_v2_analyze(job_id: str, request: Request):
"""Start Claude Code analysis — returns SSE stream."""
_get_user(request)
job = batch_v2.get_job(job_id)
if not job:
raise HTTPException(404, "Job not found")
job_dir = Path(job["job_dir"])
task_desc = job["task_description"]
target_name = job["target_name"]
total_files = job["total_files"]
sample_info = job["sample_info"]
async def event_stream():
async for event in batch_v2.run_claude_analysis(
job_dir, task_desc, target_name, total_files, sample_info
):
etype = event.get("type", "")
if etype == "text":
yield f"event: text\ndata: {json.dumps({'text': event['text']}, ensure_ascii=False)}\n\n"
elif etype == "tool":
yield f"event: tool\ndata: {json.dumps({'tool': event['tool']}, ensure_ascii=False)}\n\n"
elif etype == "done":
script = event.get("script", "")
if script:
job["analysis"] = {"python_script": script}
job["status"] = "analyzed"
else:
job["analysis"] = {"error": "Claude did not generate script", "result": event.get("result", "")}
job["status"] = "analysis_failed"
yield f"event: done\ndata: {json.dumps({'script': script, 'status': job['status']}, ensure_ascii=False)}\n\n"
return StreamingResponse(
event_stream(),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)
@app.post("/api/batch-v2/run/{job_id}")
async def batch_v2_run(job_id: str, request: Request):
"""Confirm and run the Claude-generated script."""
_get_user(request)
job = batch_v2.get_job(job_id)
if not job:
raise HTTPException(404, "Job not found")
script = job.get("analysis", {}).get("python_script", "")
if not script:
raise HTTPException(400, "No script generated")
threading.Thread(
target=batch_v2.run_batch_v2,
args=(job_id, script, job["source_dir"], job["target_file"]),
daemon=True,
).start()
return {"status": "started", "job_id": job_id}
@app.get("/api/batch-v2/status/{job_id}")
async def batch_v2_status(job_id: str, request: Request):
_get_user(request)
job = batch_v2.get_job(job_id)
if not job:
raise HTTPException(404, "Job not found")
return {
"status": job["status"],
"total": job.get("total_files", 0),
"processed": job.get("processed", 0),
"errors": job.get("errors", [])[:20],
"script": job.get("analysis", {}).get("python_script", ""),
}
@app.get("/api/batch-v2/download/{job_id}")
async def batch_v2_download(job_id: str, request: Request):
_get_user(request)
job = batch_v2.get_job(job_id)
if not job or not job.get("output_file"):
raise HTTPException(404, "Result not ready")
return FileResponse(job["output_file"], filename=Path(job["output_file"]).name)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "8000")))