Files
smeta-web/main.py
T
anorandClaude Opus 4.7 e1b721bfcb feat: AI_BACKEND=hybrid — DeepSeek + Claude CLI с domain MCP (Этап 3)
Новая ветка роутинга в main.py: нормативные вопросы (НР, СП, приказы,
ГЭСН) уходят в DeepSeek (дёшево), агентские задачи (открыть/прочитать/
заполнить xlsm, batch) — в Claude CLI через подписку с подключённым
smeta MCP server. Anthropic API не используется.

Эвристика по keywords (как существующая auto-ветка), но без Sonnet —
вместо него DeepSeek. Расширены keyword-списки под реальные кейсы из
логов («столбец D», «лист 15», «заполни пункт», «извлеки» и т.д.).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 18:47:59 +10:00

1505 lines
55 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""smeta-web: AI assistant for estimators — FastAPI + Claude Code or GLM-5."""
import json
import os
import shutil
import time
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_audit_log, get_history, get_history_any_user, init_db, list_sessions, log_action, 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 == "hybrid":
# DeepSeek для нормативных вопросов (95% запросов из логов),
# Claude CLI через подписку Pro/Max + Domain MCP — для агентских
# задач (открыть/проанализировать/заполнить xlsm). Без расходов на
# Anthropic API.
from claude_bridge_glm import (
clear_session, get_work_dir, is_allowed_file, list_user_files,
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"):
msg_lower = message.lower()
# Сильные индикаторы агентской задачи → Claude CLI
agent_actions = [
"создай файл", "сохрани в", "запиши в", "сделай таблиц",
"перенеси данн", "измени файл", "отредактируй", "скопируй",
"проверь файл", "открой файл",
"загруж", "прикреп", ".xlsx", ".xlsm", ".docx", ".pdf", ".csv",
"ячейк", "столбец d", "столбец e", "лист 15", "вкладк",
"заполни пункт", "сматчи", "сопостав", "извлеки",
]
# Сильные индикаторы нормативки → DeepSeek
reference_words = [
"какой нр", "какой сп", "какая нр", "какая сп",
"коэффициент", "зимнее удорожан", "временные здани",
"расценк", "найди расценку", "найди норму",
"сметная цена", "цена материал",
"приказ ", "фснб", "методик",
"посчитай нр", "посчитай сп", "рассчитай",
"что ты умеешь", "помощь", "help",
]
# Файл из work_dir упомянут по имени → Claude
from claude_bridge_glm import get_work_dir as _gw
work_dir = _gw(username, tab_id)
mentions_file = False
if work_dir.exists():
for f in work_dir.iterdir():
if f.is_file() and not f.name.startswith("."):
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
is_agent = mentions_file or any(kw in msg_lower for kw in agent_actions)
is_reference = any(kw in msg_lower for kw in reference_words)
if is_agent and not is_reference:
stream_fn = _stream_claude
elif is_reference and not is_agent:
stream_fn = _stream_glm
elif is_agent and is_reference:
stream_fn = _stream_claude # ambiguous → агент сильнее
else:
stream_fn = _stream_glm
async for chunk in stream_fn(message, username, tab_id):
yield chunk
elif AI_BACKEND == "auto":
from claude_bridge_glm import (
clear_session, get_work_dir, is_allowed_file, list_user_files,
)
from claude_bridge_sonnet import stream_claude as _stream_sonnet
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()
# Step 1: Strong file indicators (high confidence → Claude)
file_actions = [
"создай файл", "сохрани в", "запиши в", "сделай таблиц",
"перенеси данн", "измени файл", "отредактируй", "скопируй",
"проверь файл", "открой файл", "покажи файл",
"загруж", "прикреп", ".xlsx", ".docx", ".pdf", ".csv",
"ячейк",
]
# 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)
mentions_file = False
if work_dir.exists():
for f in work_dir.iterdir():
if f.is_file() and not f.name.startswith("."):
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
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
stream_fn = _stream_claude if use_claude else _stream_sonnet
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 = 100 * 1024 * 1024 # 100 MB
MAX_MESSAGE_LEN = 10_000
# Audit: path → action name mapping
_AUDIT_MAP = [
("POST", "/api/login", "login"),
("POST", "/api/register", "register"),
("POST", "/api/verify-email", "verify_email"),
("POST", "/api/refresh", "refresh"),
("POST", "/api/chat", "chat"),
("POST", "/api/upload", "upload"),
("GET", "/api/files/", "download"),
("GET", "/api/files", "list_files"),
("POST", "/api/clear-files", "clear_files"),
("POST", "/api/reset", "reset_session"),
("POST", "/api/batch-v2/", "batch_v2"),
("GET", "/api/batch-v2/", "batch_v2"),
("POST", "/api/batch-v3/", "batch_v3"),
("GET", "/api/batch-v3/", "batch_v3"),
("POST", "/api/ssr/", "ssr"),
("GET", "/api/ssr/", "ssr"),
("POST", "/api/check/", "check"),
("POST", "/api/gen/", "generate"),
("GET", "/api/gen/", "generate"),
("POST", "/api/wizard/", "wizard"),
("GET", "/api/wizard/", "wizard"),
("GET", "/api/ref/", "reference"),
("GET", "/api/history", "history"),
("GET", "/api/sessions", "sessions"),
("GET", "/api/admin/", "admin"),
("POST", "/api/admin/", "admin"),
]
_SKIP_PREFIXES = ("/static/", "/favicon")
def _resolve_action(method: str, path: str) -> str | None:
if any(path.startswith(p) for p in _SKIP_PREFIXES):
return None
for m, prefix, action in _AUDIT_MAP:
if method == m and path.startswith(prefix):
# For admin sub-actions: admin.invite, admin.block, etc.
if action == "admin":
sub = path.removeprefix("/api/admin/").split("/")[0].split("?")[0]
return f"admin.{sub}" if sub else "admin"
return action
# Pages (GET /, /batch2, /admin, etc.) — skip
if not path.startswith("/api/"):
return None
return method.lower() + ":" + path
@app.on_event("startup")
async def startup():
init_db()
# Actions logged manually in handlers (with richer detail)
_MANUAL_ACTIONS = {"login", "login_fail", "chat", "upload", "register", "register_fail"}
@app.middleware("http")
async def audit_middleware(request: Request, call_next):
method = request.method
path = request.url.path
action = _resolve_action(method, path)
response = await call_next(request)
if action is None or action in _MANUAL_ACTIONS:
return response
# Extract username from JWT (best-effort, don't fail)
username = None
try:
auth_header = request.headers.get("authorization", "")
tok = auth_header.removeprefix("Bearer ").strip()
if tok:
username = verify_token(tok)
except Exception:
pass
# Extract detail based on action
detail = None
if action == "download":
parts = path.split("/api/files/")
detail = parts[1] if len(parts) > 1 else None
elif action in ("batch_v2", "batch_v3", "ssr", "generate"):
sub = path.split("/")[-1] if "/" in path else None
detail = sub
ip = request.client.host if request.client else None
try:
log_action(username, action, method, path, detail, ip, response.status_code)
except Exception:
pass
return response
# 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()
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:
log_action(username, "login_fail", "POST", "/api/login", None, client_ip, 401)
raise HTTPException(401, "Wrong credentials")
from auth import _make_refresh_token, get_token_role
role = get_token_role(token)
refresh = _make_refresh_token(username, role)
log_action(username, "login", "POST", "/api/login", f"role={role}", client_ip, 200)
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")
async def register(request: Request):
body = await request.json()
email = body.get("email", "")
password = body.get("password", "")
invite = body.get("invite", "")
from auth import register_user
result = register_user(email, password, invite)
client_ip = request.client.host if request.client else ""
if not result["ok"]:
log_action(email, "register_fail", "POST", "/api/register", result["error"], client_ip, 400)
raise HTTPException(400, result["error"])
log_action(email, "register", "POST", "/api/register", None, client_ip, 200)
# Send verification code via email
code = result.get("code", "")
if code:
from email_service import send_verification_code
sent = send_verification_code(email, code)
if not sent:
return {"message": "Аккаунт создан, но email не отправлен. Обратитесь к администратору."}
return {"message": result["message"]}
@app.post("/api/verify-email")
async def verify_email_endpoint(request: Request):
body = await request.json()
email = body.get("email", "")
code = body.get("code", "")
from auth import verify_email
result = verify_email(email, code)
if not result["ok"]:
raise HTTPException(400, result["error"])
return {"message": result["message"]}
@app.get("/register", response_class=HTMLResponse)
async def register_page():
return Path("static/register.html").read_text(encoding="utf-8")
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)
_check_rate_limit(user)
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)")
ip = request.client.host if request.client else None
log_action(user, "chat", "POST", "/api/chat", f"tab={tab_id} | {message[:120]}", ip, 200)
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")
# Try own history first; if empty and admin — try any user's history for this tab
result = get_history(user, tab_id)
if not result:
from auth import get_token_role
token = request.headers.get("authorization", "").removeprefix("Bearer ").strip()
if get_token_role(token) == "admin":
result = get_history_any_user(tab_id)
return result
@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, xls, docx, pdf, csv, txt, xml, json, yaml, gge, esw, zip",
)
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} байт)")
ip = request.client.host if request.client else None
log_action(user, "upload", "POST", "/api/upload", f"{safe_name} ({total}B) tab={tab_id}", ip, 200)
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/extract_complaints")
async def extract_complaints_endpoint(request: Request):
"""Detrministic regex extraction of (пункт → смета) pairs from xlsm.
Body: {"tab_id": "...", "filename": "..."} — file must already be uploaded.
Returns: stats + pairs + no_code_rows.
"""
from complaints import extract_pairs
user = _get_user(request)
body = await request.json()
tab_id = body.get("tab_id") or request.headers.get("x-tab-id", "default")
filename = body.get("filename")
if not filename:
raise HTTPException(400, "filename required")
safe_name = Path(filename).name
fpath = get_work_dir(user, tab_id) / safe_name
if not fpath.exists():
raise HTTPException(404, "File not found in work directory")
try:
result = extract_pairs(fpath)
except ValueError as e:
raise HTTPException(400, str(e))
ip = request.client.host if request.client else None
log_action(user, "extract_complaints", "POST", "/api/extract_complaints",
f"{safe_name} pairs={result['stats']['total_pairs']}", ip, 200)
return result
@app.post("/api/apply_matches")
async def apply_matches_endpoint(request: Request):
"""Fill column D in sheet «РеестрСМ» with matching пункт-замечания.
Body: {"tab_id": "...", "filename": "..."} — original xlsm with both sheets.
Saves <stem>_filled.xlsm into the same work directory and returns
download URL + stats.
"""
from complaints import apply_to_registry
user = _get_user(request)
body = await request.json()
tab_id = body.get("tab_id") or request.headers.get("x-tab-id", "default")
filename = body.get("filename")
if not filename:
raise HTTPException(400, "filename required")
safe_name = Path(filename).name
work_dir = get_work_dir(user, tab_id)
fpath = work_dir / safe_name
if not fpath.exists():
raise HTTPException(404, "File not found in work directory")
# openpyxl drops VBA macros when saving — write as .xlsx so Excel
# opens it cleanly even when the source was .xlsm
out_name = f"{Path(safe_name).stem}_filled.xlsx"
out_path = work_dir / out_name
try:
result = apply_to_registry(fpath, out_path)
except ValueError as e:
raise HTTPException(400, str(e))
ip = request.client.host if request.client else None
log_action(user, "apply_matches", "POST", "/api/apply_matches",
f"{safe_name} filled={result['cells_filled']}", ip, 200)
return {
**result,
"output_filename": out_name,
"download_url": f"/api/files/{out_name}",
}
@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 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
# === 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["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_v3.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_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."""
_get_user(request)
job = batch_v3.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_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):
_get_user(request)
job = batch_v3.get_job(job_id)
if not job:
raise HTTPException(404, "Job not found")
# 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):
_get_user(request)
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)
# === Admin: view user sessions ===
@app.get("/api/admin/sessions")
async def admin_sessions(request: Request):
"""List all sessions with last activity — for admin use."""
_require_admin(request)
from db import _conn
with _conn() as conn:
rows = conn.execute(
"SELECT username, tab_id, MAX(timestamp) as last_ts, COUNT(*) as msg_count, "
"(SELECT content FROM messages m2 WHERE m2.tab_id = messages.tab_id "
" AND m2.role = 'user' ORDER BY m2.id DESC LIMIT 1) as last_question "
"FROM messages GROUP BY tab_id ORDER BY last_ts DESC LIMIT 50",
).fetchall()
return [dict(r) for r in rows]
@app.get("/api/admin/audit")
async def admin_audit(request: Request):
"""Full audit log — admin only."""
_require_admin(request)
limit = int(request.query_params.get("limit", "200"))
offset = int(request.query_params.get("offset", "0"))
username = request.query_params.get("username") or None
action = request.query_params.get("action") or None
return get_audit_log(limit, offset, username, action)
@app.get("/api/admin/stats")
async def admin_stats(request: Request):
"""Dashboard stats: messages per day, total sessions, etc."""
_require_admin(request)
from db import _conn
with _conn() as conn:
# Messages per day (last 14 days)
import time as _time
cutoff = _time.time() - 14 * 86400
daily = conn.execute(
"SELECT date(timestamp, 'unixepoch', '+10 hours') as day, "
"COUNT(*) as total, "
"SUM(CASE WHEN role='user' THEN 1 ELSE 0 END) as questions, "
"SUM(CASE WHEN role='assistant' THEN 1 ELSE 0 END) as answers "
"FROM messages WHERE timestamp > ? "
"GROUP BY day ORDER BY day DESC",
(cutoff,),
).fetchall()
# Totals
totals = conn.execute(
"SELECT COUNT(*) as messages, COUNT(DISTINCT tab_id) as sessions, "
"COUNT(DISTINCT username) as users "
"FROM messages",
).fetchone()
return {"daily": [dict(r) for r in daily], "totals": dict(totals)}
@app.post("/api/admin/invite")
async def create_invite_endpoint(request: Request):
"""Create invite link. Admin only."""
_require_admin(request)
user = _get_user(request)
import secrets
from db import create_invite
invite_token = secrets.token_urlsafe(24)
create_invite(invite_token, user)
return {"invite_token": invite_token, "url": f"https://infosmeta.ru/register?invite={invite_token}"}
@app.get("/api/admin/invites")
async def list_invites_endpoint(request: Request):
_require_admin(request)
from db import list_invites
return list_invites()
@app.get("/api/admin/users")
async def list_users_endpoint(request: Request):
_require_admin(request)
from db import list_users
return list_users()
def _require_admin(request: Request):
"""Check that current user is admin."""
_get_user(request)
from auth import get_token_role
token = request.headers.get("authorization", "").removeprefix("Bearer ").strip()
if get_token_role(token) != "admin":
raise HTTPException(403, "Admin only")
@app.post("/api/admin/users/block")
async def block_user_endpoint(request: Request):
_require_admin(request)
body = await request.json()
email = body.get("email", "")
blocked = body.get("blocked", True)
from db import block_user
block_user(email, blocked)
return {"ok": True}
@app.post("/api/admin/users/delete")
async def delete_user_endpoint(request: Request):
_require_admin(request)
body = await request.json()
email = body.get("email", "")
current_user = _get_user(request)
if email.lower() == current_user.lower():
raise HTTPException(400, "Нельзя удалить себя")
from db import delete_user
delete_user(email)
return {"ok": True}
@app.post("/api/admin/users/role")
async def set_role_endpoint(request: Request):
_require_admin(request)
body = await request.json()
email = body.get("email", "")
role = body.get("role", "user")
from db import set_user_role
set_user_role(email, role)
return {"ok": True}
@app.post("/api/admin/users/verify")
async def admin_verify_endpoint(request: Request):
_require_admin(request)
body = await request.json()
email = body.get("email", "")
from db import admin_verify_user
admin_verify_user(email)
return {"ok": True}
@app.get("/api/admin/file_users")
async def admin_file_users_endpoint(request: Request):
"""Юзеры, у которых есть файлы в DATA_DIR.
Источник — FS, не таблица users: бывают env-only аккаунты (`smeta`)
и удалённые из БД пользователи, чьи файлы остались. Админу нужно
видеть всех с реальными файлами.
"""
_require_admin(request)
data_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data"))
if not data_dir.exists():
return {"users": []}
out = []
for d in sorted(data_dir.iterdir()):
if not d.is_dir() or d.name.startswith(".") or d.name.startswith("_"):
continue
n = 0
for tab in d.iterdir():
if tab.is_dir() and not tab.name.startswith("."):
for f in tab.iterdir():
if f.is_file() and not f.name.startswith("."):
n += 1
out.append({"username": d.name, "file_count": n})
out.sort(key=lambda x: -x["file_count"])
return {"users": out}
@app.get("/api/admin/files")
async def admin_list_files_endpoint(request: Request):
"""All files uploaded by a specific user (across every tab).
Спец-значение `username=__all__` — файлы всех юзеров. Каждая
запись содержит поле `username` (для одиночного режима тоже —
UI единообразно).
"""
_require_admin(request)
target_user = request.query_params.get("username", "").strip()
if not target_user:
raise HTTPException(400, "username query param required")
data_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data"))
files = []
def _collect(user_dir: Path, username: str):
if not user_dir.exists() or not user_dir.is_dir():
return
for tab_dir in sorted(user_dir.iterdir()):
if not tab_dir.is_dir() or tab_dir.name.startswith("."):
continue
for f in sorted(tab_dir.iterdir()):
if f.is_file() and not f.name.startswith("."):
st = f.stat()
files.append({
"username": username,
"tab_id": tab_dir.name,
"filename": f.name,
"size": st.st_size,
"mtime": st.st_mtime,
})
if target_user == "__all__":
if data_dir.exists():
for d in sorted(data_dir.iterdir()):
if not d.is_dir() or d.name.startswith(".") or d.name.startswith("_"):
continue
_collect(d, d.name)
return {"username": "__all__", "count": len(files), "files": files}
safe_user = Path(target_user).name
if safe_user != target_user or not safe_user:
raise HTTPException(400, "Invalid username")
_collect(data_dir / safe_user, safe_user)
return {"username": safe_user, "count": len(files), "files": files}
@app.get("/api/admin/file_download")
async def admin_download_file_endpoint(request: Request):
"""Download any user's uploaded file (admin only).
Path components passed as query params to avoid URL-escaping pain
with names like `!Реестр СМ..xlsm` and tab_ids containing slashes.
"""
_require_admin(request)
target_user = request.query_params.get("username", "").strip()
tab_id = request.query_params.get("tab_id", "").strip()
filename = request.query_params.get("filename", "").strip()
if not (target_user and tab_id and filename):
raise HTTPException(400, "username, tab_id, filename required")
safe_user = Path(target_user).name
safe_tab = Path(tab_id).name
safe_name = Path(filename).name
if not (safe_user and safe_tab and safe_name):
raise HTTPException(400, "Invalid path component")
data_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data")).resolve()
fpath = (data_dir / safe_user / safe_tab / safe_name).resolve()
try:
fpath.relative_to(data_dir)
except ValueError:
raise HTTPException(400, "Path traversal denied")
if not fpath.exists() or not fpath.is_file():
raise HTTPException(404, "File not found")
return FileResponse(fpath, filename=safe_name)
ADMIN_HTML_VERSION = "20260506g"
@app.get("/admin", response_class=HTMLResponse)
async def admin_page(request: Request):
# Если у юзера в браузере осталась старая закэшированная копия
# /admin без no-store, то любые серверные заголовки уже не
# помогут — браузер сам решает, делать ли revalidation. Поэтому:
# - на запрос без актуальной ?v= делаем 302 на URL с query
# - URL с query !== закэшированный URL без query → промах кэша →
# браузер делает свежий запрос, получает no-store, дальше всегда
# свежий
from fastapi.responses import RedirectResponse
if request.query_params.get("v") != ADMIN_HTML_VERSION:
return RedirectResponse(url=f"/admin?v={ADMIN_HTML_VERSION}", status_code=302)
html = Path("static/admin.html").read_text(encoding="utf-8")
return HTMLResponse(
html,
headers={
"Cache-Control": "no-store, no-cache, must-revalidate, max-age=0",
"Pragma": "no-cache",
"Expires": "0",
},
)
# === 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["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."""
_get_user(request)
job = batch_v3.get_job(job_id)
if not job:
raise HTTPException(404, "Job not found")
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):
_get_user(request)
job = batch_v3.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")
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):
_get_user(request)
job = batch_v3.get_job(job_id)
if not job:
raise HTTPException(404, "Job not found")
# 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):
_get_user(request)
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)
# ── 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")
def _import_ssr_scripts():
"""Import smeta-railway scripts (installed via pip install -e)."""
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)
@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):
_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")
# ── Wizard Aggregator ──────────────────────────────────────────────────────
def _import_smeta_railway():
"""Ensure smeta-railway src/ is importable."""
import sys
for src_dir in [
str(Path(__file__).resolve().parent / ".." / "smeta-railway" / "src"),
str(Path.home() / "smeta-railway" / "src"),
]:
if Path(src_dir).exists() and src_dir not in sys.path:
sys.path.insert(0, src_dir)
_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
app.include_router(_wizard_router, prefix="/api/wizard")
app.include_router(_gen_router, prefix="/api/gen")
app.include_router(_chat_sr_router, prefix="/api/ref") # /api/ref/search, /api/ref/nr, /api/ref/sp
@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
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:
return {"error": str(exc), "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."""
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}
@app.get("/api/gen/download/{job_id}")
async def download_estimate(job_id: str):
"""Download generated Excel estimate."""
data_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / "_estimates"
xlsx_path = data_dir / f"estimate_{job_id}.xlsx"
if not xlsx_path.exists():
raise HTTPException(404, "Файл не найден")
return FileResponse(str(xlsx_path), filename=f"smeta_{job_id}.xlsx")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "8000")))