ГРАНД-Смета (.gge, .esw), Smeta.RU (.smr, .smt), плюс .zip/.rar/.7z Обновлены все 4 файла с ALLOWED_EXTENSIONS. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
282 lines
10 KiB
Python
282 lines
10 KiB
Python
"""GLM-5 + CAG/RAG backend — lightweight alternative to Claude Code.
|
|
|
|
Uses smeta-railway's CAG context (НР/СП/коэффициенты) as system prompt,
|
|
resources.json for code lookups, GLM-5 API for generation.
|
|
No Docker, no subprocess — pure Python, fast.
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import re
|
|
from pathlib import Path
|
|
from typing import AsyncGenerator
|
|
|
|
import httpx
|
|
|
|
SMETA_DIR = Path(os.environ.get("SMETA_PROJECT_DIR", os.path.expanduser("~/smeta-railway")))
|
|
ZAI_API_KEY = os.environ.get("ZAI_API_KEY", "")
|
|
ZAI_BASE_URL = os.environ.get("ZAI_BASE_URL", "https://open.bigmodel.cn/api/coding/paas/v4")
|
|
ZAI_MODEL = os.environ.get("ZAI_MODEL", "glm-5")
|
|
DATA_DIR = Path(os.environ.get("DATA_DIR", "./smeta-web-data"))
|
|
|
|
# Session tracking: (username, tab_id) -> conversation history
|
|
_conversations: dict[tuple[str, str], list[dict]] = {}
|
|
MAX_HISTORY = 20 # keep last N messages
|
|
|
|
# Preload CAG context and resources
|
|
_cag_context = ""
|
|
_resources: dict = {}
|
|
|
|
|
|
def _load_smeta_data():
|
|
global _cag_context, _resources
|
|
if _cag_context:
|
|
return
|
|
|
|
# Load CAG context
|
|
import sys
|
|
sys.path.insert(0, str(SMETA_DIR / "src"))
|
|
try:
|
|
from smeta_railway.ai.cag_context import CAG_CONTEXT
|
|
_cag_context = CAG_CONTEXT
|
|
except ImportError:
|
|
_cag_context = ""
|
|
|
|
# Load resources
|
|
res_path = SMETA_DIR / "resources.json"
|
|
if res_path.exists():
|
|
with open(res_path, encoding="utf-8") as f:
|
|
_resources = json.load(f)
|
|
|
|
|
|
def _build_system_prompt() -> str:
|
|
_load_smeta_data()
|
|
return f"""Ты — профессиональный ИИ-ассистент-сметчик железнодорожного строительства.
|
|
Отвечай ТОЛЬКО на русском языке. Пользователь — сметчик, НЕ программист.
|
|
НИКОГДА не упоминай названия книг или учебников. Ссылайся только на нормативные документы.
|
|
|
|
Ниже — актуальная нормативная база. Используй ТОЛЬКО эти данные для ответов:
|
|
|
|
{_cag_context}
|
|
|
|
Если вопрос про конкретную расценку ГЭСН — скажи что проверишь по базе."""
|
|
|
|
|
|
def _search_resources(query: str, top_k: int = 5) -> str:
|
|
"""Simple text search in resources.json."""
|
|
_load_smeta_data()
|
|
if not _resources:
|
|
return ""
|
|
|
|
query_lower = query.lower()
|
|
terms = [t for t in query_lower.split() if len(t) > 2]
|
|
results = []
|
|
|
|
for code, data in _resources.items():
|
|
if "error" in data:
|
|
continue
|
|
name = (data.get("name") or data.get("norm_name") or "").lower()
|
|
score = sum(1 for t in terms if t in name)
|
|
if score > 0:
|
|
results.append((score, code, data))
|
|
|
|
results.sort(reverse=True, key=lambda x: x[0])
|
|
if not results:
|
|
return ""
|
|
|
|
lines = ["Найденные расценки в базе ФСНБ-2022:"]
|
|
for score, code, data in results[:top_k]:
|
|
name = data.get("name") or data.get("norm_name") or ""
|
|
unit = data.get("unit") or ""
|
|
lines.append(f"- ГЭСН {code}: {name} [{unit}]")
|
|
return "\n".join(lines)
|
|
|
|
|
|
def get_work_dir(username: str, tab_id: str) -> Path:
|
|
d = DATA_DIR / username / tab_id
|
|
d.mkdir(parents=True, exist_ok=True)
|
|
return d
|
|
|
|
|
|
def get_session_id(username: str, tab_id: str) -> str | None:
|
|
return None # GLM doesn't use session IDs
|
|
|
|
|
|
def set_session_id(username: str, tab_id: str, sid: str):
|
|
pass
|
|
|
|
|
|
def clear_session(username: str, tab_id: str):
|
|
_conversations.pop((username, tab_id), None)
|
|
|
|
|
|
ALLOWED_EXTENSIONS = {
|
|
".xlsx", ".xls", ".docx", ".doc", ".pdf",
|
|
".csv", ".txt", ".xml", ".json", ".yaml", ".yml",
|
|
".gge", ".esw", ".ges", ".smr", ".smt",
|
|
".zip", ".rar", ".7z",
|
|
}
|
|
|
|
|
|
def is_allowed_file(filename: str) -> bool:
|
|
return Path(filename).suffix.lower() in ALLOWED_EXTENSIONS
|
|
|
|
|
|
def _read_work_dir_files(work_dir: Path, max_chars: int = 8000) -> str:
|
|
"""Read files from work directory and return text summary for LLM context."""
|
|
parts = []
|
|
total = 0
|
|
for f in sorted(work_dir.iterdir()):
|
|
if f.name.startswith(".") or not f.is_file():
|
|
continue
|
|
ext = f.suffix.lower()
|
|
try:
|
|
if ext in (".xlsx", ".xls"):
|
|
import openpyxl
|
|
wb = openpyxl.load_workbook(str(f), data_only=True)
|
|
for ws in wb.worksheets:
|
|
lines = [f"\n### Файл: {f.name}, Лист: {ws.title} ({ws.max_row}x{ws.max_column})"]
|
|
# Smart reading: header (20 rows) + last 10 rows + every Nth row
|
|
rows_to_read = set(range(1, min(21, ws.max_row + 1)))
|
|
rows_to_read |= set(range(max(1, ws.max_row - 9), ws.max_row + 1))
|
|
# Sample middle rows
|
|
step = max(1, ws.max_row // 30)
|
|
rows_to_read |= set(range(21, ws.max_row, step))
|
|
for r_idx in sorted(rows_to_read):
|
|
vals = []
|
|
for c in ws[r_idx]:
|
|
if c.value is not None:
|
|
vals.append(f"{c.column_letter}{r_idx}={str(c.value)[:50]}")
|
|
if vals:
|
|
lines.append(" | ".join(vals))
|
|
text = "\n".join(lines)
|
|
parts.append(text)
|
|
total += len(text)
|
|
elif ext in (".csv", ".txt", ".xml", ".json", ".yaml", ".yml"):
|
|
text = f.read_text(encoding="utf-8", errors="ignore")[:max_chars]
|
|
parts.append(f"\n### Файл: {f.name}\n{text}")
|
|
total += len(text)
|
|
elif ext == ".pdf":
|
|
try:
|
|
import fitz
|
|
doc = fitz.open(str(f))
|
|
text = ""
|
|
for page in doc[:5]: # first 5 pages
|
|
text += page.get_text()
|
|
parts.append(f"\n### Файл: {f.name} ({doc.page_count} стр.)\n{text[:max_chars]}")
|
|
total += min(len(text), max_chars)
|
|
except ImportError:
|
|
parts.append(f"\n### Файл: {f.name} (PDF, не удалось прочитать)")
|
|
elif ext in (".docx", ".doc"):
|
|
try:
|
|
import docx
|
|
doc = docx.Document(str(f))
|
|
text = "\n".join(p.text for p in doc.paragraphs)[:max_chars]
|
|
parts.append(f"\n### Файл: {f.name}\n{text}")
|
|
total += len(text)
|
|
except ImportError:
|
|
parts.append(f"\n### Файл: {f.name} (Word, не удалось прочитать)")
|
|
except Exception as e:
|
|
parts.append(f"\n### Файл: {f.name} (ошибка чтения: {e})")
|
|
|
|
if total > max_chars:
|
|
break
|
|
|
|
return "\n".join(parts) if parts else ""
|
|
|
|
|
|
async def stream_claude(
|
|
message: str,
|
|
username: str,
|
|
tab_id: str = "default",
|
|
) -> AsyncGenerator[str, None]:
|
|
"""Stream GLM-5 response with CAG context."""
|
|
_load_smeta_data()
|
|
key = (username, tab_id)
|
|
|
|
# Build conversation history
|
|
if key not in _conversations:
|
|
_conversations[key] = []
|
|
history = _conversations[key]
|
|
|
|
work_dir = get_work_dir(username, tab_id)
|
|
|
|
# Search resources if question looks like a GESN lookup
|
|
resource_context = ""
|
|
gesn_patterns = ["расценк", "гэсн", "норм", "28-", "01-", "единиц"]
|
|
if any(p in message.lower() for p in gesn_patterns):
|
|
resource_context = _search_resources(message)
|
|
|
|
# Read files from work directory if they exist
|
|
file_context = _read_work_dir_files(work_dir)
|
|
|
|
# Build user message with context
|
|
user_content = message
|
|
if file_context:
|
|
user_content = f"{message}\n\n[Файлы в рабочей директории]{file_context}"
|
|
if resource_context:
|
|
user_content += f"\n\n[Данные из базы ФСНБ-2022]\n{resource_context}"
|
|
|
|
history.append({"role": "user", "content": user_content})
|
|
|
|
# Trim history
|
|
if len(history) > MAX_HISTORY:
|
|
history[:] = history[-MAX_HISTORY:]
|
|
|
|
# Prepare messages
|
|
messages = [{"role": "system", "content": _build_system_prompt()}] + history
|
|
|
|
# Stream from GLM API
|
|
full_response = ""
|
|
proxy = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")
|
|
try:
|
|
async with httpx.AsyncClient(timeout=60, proxy=proxy) as client:
|
|
resp = await client.post(
|
|
f"{ZAI_BASE_URL}/chat/completions",
|
|
headers={"Authorization": f"Bearer {ZAI_API_KEY}"},
|
|
json={
|
|
"model": ZAI_MODEL,
|
|
"messages": messages,
|
|
"stream": True,
|
|
"temperature": 0.1,
|
|
"max_tokens": 2000,
|
|
},
|
|
)
|
|
resp.raise_for_status()
|
|
|
|
async for line in resp.aiter_lines():
|
|
if not line.startswith("data: "):
|
|
continue
|
|
data_str = line[6:]
|
|
if data_str == "[DONE]":
|
|
break
|
|
try:
|
|
chunk = json.loads(data_str)
|
|
delta = chunk["choices"][0].get("delta", {})
|
|
text = delta.get("content", "")
|
|
if text:
|
|
full_response += text
|
|
yield f"event: text\ndata: {json.dumps({'text': text}, ensure_ascii=False)}\n\n"
|
|
except (json.JSONDecodeError, KeyError, IndexError):
|
|
continue
|
|
|
|
except Exception as e:
|
|
error_msg = f"Ошибка GLM API: {e}"
|
|
yield f"event: text\ndata: {json.dumps({'text': error_msg}, ensure_ascii=False)}\n\n"
|
|
full_response = error_msg
|
|
|
|
# Save assistant response to history
|
|
if full_response:
|
|
history.append({"role": "assistant", "content": full_response})
|
|
|
|
yield f"event: done\ndata: {json.dumps({'result': full_response}, ensure_ascii=False)}\n\n"
|
|
|
|
|
|
def list_user_files(username: str, tab_id: str = "default") -> list[dict]:
|
|
work_dir = get_work_dir(username, tab_id)
|
|
files = []
|
|
for f in sorted(work_dir.iterdir()):
|
|
if f.is_file() and not f.name.startswith("."):
|
|
files.append({"name": f.name, "size": f.stat().st_size})
|
|
return files
|