Files
smeta-web/main.py
T
anorandClaude Opus 4.6 678337ab3d 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>
2026-03-30 04:36:12 +10:00

961 lines
33 KiB
Python

"""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_history, get_history_any_user, 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_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 = 50 * 1024 * 1024 # 50 MB
MAX_MESSAGE_LEN = 10_000
@app.on_event("startup")
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()
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")
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")
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)
if not result["ok"]:
raise HTTPException(400, result["error"])
# 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)")
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} байт)")
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 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."""
_get_user(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/stats")
async def admin_stats(request: Request):
"""Dashboard stats: messages per day, total sessions, etc."""
_get_user(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://smeta.kazin.ru/register?invite={invite_token}"}
@app.get("/api/admin/invites")
async def list_invites_endpoint(request: Request):
_get_user(request)
from db import list_invites
return list_invites()
@app.get("/api/admin/users")
async def list_users_endpoint(request: Request):
_get_user(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("/admin", response_class=HTMLResponse)
async def admin_page():
return Path("static/admin.html").read_text(encoding="utf-8")
# === 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")
@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")))