feat: smeta-web — веб-интерфейс ИИ-ассистента для сметчика
FastAPI + Claude Code CLI + vanilla JS чат. - JWT авторизация, SSE streaming - Загрузка файлов (Excel, Word, PDF, CSV, TXT) - Каждая вкладка — отдельная Claude-сессия - Системный промпт: русский язык, работа с файлами, уточняющие вопросы - Деплой: systemd + nginx + Let's Encrypt на smeta.kazin.ru Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,143 @@
|
||||
"""smeta-web: AI assistant for estimators — FastAPI + Claude Code."""
|
||||
|
||||
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 claude_bridge import (
|
||||
clear_session,
|
||||
get_work_dir,
|
||||
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
|
||||
|
||||
|
||||
def _get_user(request: Request) -> str:
|
||||
"""Extract and verify user from Authorization header."""
|
||||
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:
|
||||
"""Extract tab_id from request header or body."""
|
||||
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", "")
|
||||
token = authenticate(username, password)
|
||||
if not token:
|
||||
raise HTTPException(401, "Wrong credentials")
|
||||
return {"token": token, "username": username}
|
||||
|
||||
|
||||
@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")
|
||||
|
||||
return StreamingResponse(
|
||||
stream_claude(message, user, tab_id),
|
||||
media_type="text/event-stream",
|
||||
headers={
|
||||
"Cache-Control": "no-cache",
|
||||
"X-Accel-Buffering": "no",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@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)
|
||||
|
||||
content = await file.read()
|
||||
if len(content) > MAX_UPLOAD_SIZE:
|
||||
raise HTTPException(413, f"File too large (max {MAX_UPLOAD_SIZE // 1024 // 1024}MB)")
|
||||
|
||||
safe_name = Path(file.filename).name
|
||||
if not safe_name or safe_name.startswith("."):
|
||||
raise HTTPException(400, "Invalid filename")
|
||||
dest = work_dir / safe_name
|
||||
dest.write_bytes(content)
|
||||
return {"filename": safe_name, "size": len(content)}
|
||||
|
||||
|
||||
@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)
|
||||
body = await request.json()
|
||||
tab_id = _get_tab(request, body)
|
||||
clear_session(tab_id)
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.post("/api/clear-files")
|
||||
async def clear_files(request: Request):
|
||||
user = _get_user(request)
|
||||
body = await request.json()
|
||||
tab_id = _get_tab(request, body)
|
||||
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(tab_id)
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "8000")))
|
||||
Reference in New Issue
Block a user