diff --git a/.claude/rules/ai.md b/.claude/rules/ai.md new file mode 100644 index 0000000..7cab3e2 --- /dev/null +++ b/.claude/rules/ai.md @@ -0,0 +1,13 @@ +--- +paths: ["src/smeta_railway/ai/**"] +--- + +# AI Module Rules + +- All LLM prompts MUST include few-shot examples for structured output +- Never trust raw LLM JSON output — always validate with try/except + retry +- CAG context (~4K tokens) is pre-built; do not load full tables at runtime +- When adding new prompts: include 2-3 input/output examples +- System prompts must cite normative sources (document, paragraph, column) +- Test prompt changes with real questions before committing +- GLM-5 is primary provider; Anthropic/OpenAI are alternatives — keep all working diff --git a/.claude/rules/calc.md b/.claude/rules/calc.md new file mode 100644 index 0000000..db82458 --- /dev/null +++ b/.claude/rules/calc.md @@ -0,0 +1,12 @@ +--- +paths: ["src/smeta_railway/calc/**"] +--- + +# Calculation Module Rules + +- Formulas MUST match normative documents (Prikazs 421/pr, 812/pr, 774/pr, Appendix 28.1) +- Never change coefficient values without citing the source document +- НР and СП are calculated from ФОТ (ОТ + ЗП маш.), NOT from ПЗ +- Coefficients multiply, never add: K_total = K1 * K2 * K3 +- Always run `check_yaml_config()` after modifying calculation logic +- Test on real project YAML (projects/sviyagino_2026q1.yaml) before committing diff --git a/.claude/rules/output.md b/.claude/rules/output.md new file mode 100644 index 0000000..1a80f4d --- /dev/null +++ b/.claude/rules/output.md @@ -0,0 +1,10 @@ +--- +paths: ["src/smeta_railway/output/**"] +--- + +# Output Module Rules + +- Excel output follows 27-column "Stroitelny Expert" layout — do not change column order +- Column letters and headers are defined in excel_se.py constants — modify constants, not hardcoded values +- Always test output with openpyxl load_workbook() to verify no corruption +- Preserve existing cell formatting (fonts, borders, number formats) when modifying diff --git a/.claude/rules/web.md b/.claude/rules/web.md new file mode 100644 index 0000000..4fbbe31 --- /dev/null +++ b/.claude/rules/web.md @@ -0,0 +1,11 @@ +--- +paths: ["src/smeta_railway/web/**", "scripts/wizard_server.py"] +--- + +# Web Module Rules + +- Wizard sessions are in-memory with 1h TTL — no persistent state +- All file paths must be validated within session temp directory (path traversal prevention) +- Return structured error responses with error_category field (transient/validation/business) +- File uploads: validate .xlsx/.zip extensions AND content (not just filename) +- Test endpoints with curl after changes diff --git a/scripts/wizard_server.py b/scripts/wizard_server.py index 37160ec..90f0fa1 100644 --- a/scripts/wizard_server.py +++ b/scripts/wizard_server.py @@ -1,10 +1,16 @@ #!/usr/bin/env python3 """ -Wizard-aggregator web server. +Smeta Railway — unified web server. + +Serves: + - /api/wizard/* — xlsx aggregation wizard + - /api/chat/* — GESN search, questions, NR/SP lookup + - /api/gen/* — estimate generation pipeline + - /* — static files (index.html with tabs) Usage: python scripts/wizard_server.py - # Open http://localhost:8102/wizard.html + # Open http://localhost:8102 """ import sys @@ -16,12 +22,18 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src")) from fastapi import FastAPI from fastapi.staticfiles import StaticFiles -from smeta_railway.web.wizard_api import router +from smeta_railway.web.wizard_api import router as wizard_router +from smeta_railway.web.chat_api import router as chat_router +from smeta_railway.web.generator_api import router as gen_router -app = FastAPI(title="Smeta Wizard Aggregator") -app.include_router(router, prefix="/api/wizard") +app = FastAPI(title="Smeta Railway") -# Serve static files (wizard.html) +# API routers +app.include_router(wizard_router, prefix="/api/wizard") +app.include_router(chat_router, prefix="/api/chat") +app.include_router(gen_router, prefix="/api/gen") + +# Serve static files (index.html, wizard.html) static_dir = Path(__file__).resolve().parent.parent / "static" app.mount("/", StaticFiles(directory=str(static_dir), html=True), name="static") diff --git a/src/smeta_railway/ai/bot.py b/src/smeta_railway/ai/bot.py index a638dd5..564a489 100644 --- a/src/smeta_railway/ai/bot.py +++ b/src/smeta_railway/ai/bot.py @@ -113,7 +113,10 @@ async def cmd_search(update: Update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text("\n".join(lines), parse_mode="Markdown") except Exception as e: - await update.message.reply_text(f"Ошибка: {e}") + from smeta_railway.errors import classify_error + err = classify_error(e) + logger.error("Search error: %s [%s]", err.message, err.category) + await update.message.reply_text(err.user_message()) async def cmd_ask(update: Update, context: ContextTypes.DEFAULT_TYPE): @@ -139,8 +142,10 @@ async def cmd_ask(update: Update, context: ContextTypes.DEFAULT_TYPE): footer = f"\n\n_({result['model']}, {tokens} tokens)_" await update.message.reply_text(answer + footer, parse_mode="Markdown") except Exception as e: - logger.exception("Error in /ask") - await update.message.reply_text(f"Ошибка: {e}") + from smeta_railway.errors import classify_error + err = classify_error(e) + logger.error("Ask error: %s [%s] detail=%s", err.message, err.category, err.detail) + await update.message.reply_text(err.user_message()) async def cmd_nr(update: Update, context: ContextTypes.DEFAULT_TYPE): diff --git a/src/smeta_railway/ai/generator.py b/src/smeta_railway/ai/generator.py index 8489542..64099ec 100644 --- a/src/smeta_railway/ai/generator.py +++ b/src/smeta_railway/ai/generator.py @@ -27,16 +27,30 @@ PARSE_PROMPT = """Ты — инженер-сметчик. Из описания - qty: количество (число) - note: примечание (если есть) -Ответ СТРОГО в JSON формате: +## ПРИМЕРЫ + +Описание: "Замена 500 шпал на перегоне, очистка щебня 2 км, замена 3 пар рельсовых плетей по 800м" ```json [ - {"description": "...", "unit": "...", "qty": ..., "note": "..."}, - ... + {{"description": "Замена шпал железобетонных", "unit": "шт", "qty": 500, "note": ""}}, + {{"description": "Очистка щебёночного балласта", "unit": "км", "qty": 2, "note": ""}}, + {{"description": "Замена рельсовых плетей", "unit": "пар резок", "qty": 3, "note": "длина 800м"}} ] ``` -НЕ придумывай позиции, которых нет в описании. -Если единица/количество не указаны — укажи "уточнить". +Описание: "Капремонт пути 5.2 км: подъёмочный ремонт, выправка пути, регулировка зазоров" +```json +[ + {{"description": "Подъёмочный ремонт пути", "unit": "км", "qty": 5.2, "note": ""}}, + {{"description": "Выправка пути в плане и профиле", "unit": "км", "qty": 5.2, "note": ""}}, + {{"description": "Регулировка зазоров", "unit": "км", "qty": 5.2, "note": ""}} +] +``` + +## ПРАВИЛА +- НЕ придумывай позиции, которых нет в описании. +- Если единица/количество не указаны — укажи "уточнить". +- Ответ СТРОГО в JSON формате (массив объектов). Описание: {text}""" @@ -85,23 +99,40 @@ class EstimateGenerator: ) return response.choices[0].message.content or "" + def _extract_json(self, response: str) -> list[dict]: + """Extract JSON array from LLM response text.""" + if "```json" in response: + json_str = response.split("```json")[1].split("```")[0] + elif "```" in response: + json_str = response.split("```")[1].split("```")[0] + else: + json_str = response + result = json.loads(json_str) + if not isinstance(result, list): + raise ValueError(f"Expected JSON array, got {type(result).__name__}") + return result + def parse_description(self, text: str) -> list[dict]: """Step 1: Parse natural language → list of work items.""" prompt = PARSE_PROMPT.format(text=text) response = self._call_llm(prompt) - # Extract JSON from response try: - # Find JSON block in response - if "```json" in response: - json_str = response.split("```json")[1].split("```")[0] - elif "```" in response: - json_str = response.split("```")[1].split("```")[0] - else: - json_str = response - return json.loads(json_str) - except (json.JSONDecodeError, IndexError): - return [] + return self._extract_json(response) + except (json.JSONDecodeError, IndexError, ValueError) as first_err: + # Retry once with the specific error in prompt + retry_prompt = ( + f"{prompt}\n\n" + f"ПРЕДЫДУЩАЯ ПОПЫТКА ВЕРНУЛА НЕВАЛИДНЫЙ JSON.\n" + f"Ошибка: {first_err}\n" + f"Ответ (начало): {response[:200]}\n\n" + f"Верни ТОЛЬКО валидный JSON-массив, без markdown-обёрток." + ) + retry_response = self._call_llm(retry_prompt) + try: + return self._extract_json(retry_response) + except (json.JSONDecodeError, IndexError, ValueError): + return [] def match_gesn(self, items: list[dict]) -> list[dict]: """Step 2: Match each work description to GESN code.""" @@ -135,6 +166,11 @@ class EstimateGenerator: okno: bool = True, ) -> str: """Step 3: Generate YAML config from matched items.""" + # Precondition: at least one matched norm + matched_count = sum(1 for m in matched_items if m.get("score", 0) > 0.3) + if matched_count == 0: + return "# ERROR: Ни одна норма ГЭСН не найдена с достаточным score (>0.3)" + positions_json = json.dumps(matched_items, ensure_ascii=False, indent=2) prompt = YAML_PROMPT.format( @@ -163,8 +199,16 @@ class EstimateGenerator: okno: bool = True, ) -> dict: """Full pipeline: description → parsed → matched → YAML.""" + # Precondition: non-empty description + if not description or not description.strip(): + return {"error": "Пустое описание работ", "items": [], "yaml": "", + "item_count": 0, "matched_count": 0} + print("1. Parsing description...") items = self.parse_description(description) + if not items: + return {"error": "Не удалось извлечь позиции из описания", + "items": [], "yaml": "", "item_count": 0, "matched_count": 0} print(f" Found {len(items)} work items") print("2. Matching GESN codes...") diff --git a/src/smeta_railway/errors.py b/src/smeta_railway/errors.py new file mode 100644 index 0000000..7927bbd --- /dev/null +++ b/src/smeta_railway/errors.py @@ -0,0 +1,62 @@ +""" +Structured error handling for smeta-railway. + +Error categories: +- transient: network/API timeouts, retryable +- validation: bad input, show to user +- business: normative rule violation, needs expert review +""" + +from dataclasses import dataclass + + +@dataclass +class SmetaError: + category: str # "transient", "validation", "business" + message: str + is_retryable: bool + detail: str = "" + + def user_message(self) -> str: + """Format error for end user (Telegram/web).""" + if self.category == "transient": + return f"Временная ошибка: {self.message}. Попробуйте через минуту." + if self.category == "validation": + return f"Ошибка данных: {self.message}" + if self.category == "business": + return f"Нарушение правил: {self.message}" + return self.message + + +def classify_error(exc: Exception) -> SmetaError: + """Classify an exception into a structured error.""" + msg = str(exc) + exc_type = type(exc).__name__ + + # Transient: network, API, timeout + if exc_type in ("ConnectError", "ReadTimeout", "APITimeoutError", + "Timeout", "TimeoutError"): + return SmetaError("transient", "Сервер не отвечает", True, msg) + if "timeout" in msg.lower() or "timed out" in msg.lower(): + return SmetaError("transient", "Превышено время ожидания", True, msg) + if "connection" in msg.lower() or "connect" in exc_type.lower(): + return SmetaError("transient", "Ошибка соединения", True, msg) + if "rate limit" in msg.lower() or "429" in msg: + return SmetaError("transient", "Превышен лимит запросов", True, msg) + if "500" in msg or "502" in msg or "503" in msg: + return SmetaError("transient", "Ошибка сервера API", True, msg) + + # Validation: bad input, file format + if exc_type in ("ValueError", "TypeError", "KeyError"): + return SmetaError("validation", msg, False) + if "json" in msg.lower() or exc_type == "JSONDecodeError": + return SmetaError("validation", "Невалидный формат данных", False, msg) + if "xlsx" in msg.lower() or "openpyxl" in msg.lower(): + return SmetaError("validation", "Ошибка чтения Excel-файла", False, msg) + + # Business: normative violations + if any(w in msg.lower() for w in ["не существует в фснб", "вне допустимого диапазона"]): + return SmetaError("business", msg, False) + + # Unknown → treat as validation (non-retryable) + return SmetaError("validation", f"Ошибка: {msg}", False, exc_type) diff --git a/src/smeta_railway/web/chat_api.py b/src/smeta_railway/web/chat_api.py new file mode 100644 index 0000000..18ea804 --- /dev/null +++ b/src/smeta_railway/web/chat_api.py @@ -0,0 +1,122 @@ +""" +Chat API — search GESN norms, ask questions, lookup NR/SP. + +Endpoints: + POST /api/chat/search — semantic search in GESN database + POST /api/chat/ask — ask question via RAG (requires GLM API key) + POST /api/chat/nr — lookup NR percentage by work type + POST /api/chat/sp — lookup SP percentage by work type +""" + +import logging + +from fastapi import APIRouter +from pydantic import BaseModel + +from smeta_railway.errors import classify_error + +logger = logging.getLogger(__name__) + +router = APIRouter() + +# Lazy-loaded singletons +_search = None +_assistant = None + + +def _get_search(): + global _search + if _search is None: + from smeta_railway.ai.search import GESNSearch + _search = GESNSearch() + return _search + + +def _get_assistant(): + global _assistant + if _assistant is None: + from smeta_railway.ai.rag import SmetaAssistant + _assistant = SmetaAssistant() + return _assistant + + +# --- Models --- + +class SearchRequest(BaseModel): + query: str + top_k: int = 5 + collection: str | None = None + + +class AskRequest(BaseModel): + question: str + + +class NrSpRequest(BaseModel): + query: str + + +# --- Endpoints --- + +@router.post("/search") +async def search(req: SearchRequest): + """Semantic search in GESN norms (local, no API key needed).""" + try: + s = _get_search() + results = s.find(req.query, top_k=req.top_k, collection=req.collection) + return { + "results": [ + { + "code": r.code, + "name": r.name, + "unit": r.unit, + "score": round(r.score, 3), + "collection": r.collection, + } + for r in results + ], + "count": len(results), + } + except Exception as exc: + err = classify_error(exc) + return {"error": err.message, "error_category": err.category, "results": []} + + +@router.post("/ask") +async def ask(req: AskRequest): + """Ask a question via RAG assistant (requires GLM API key).""" + try: + assistant = _get_assistant() + answer = assistant.ask(req.question) + return {"answer": answer, "error": None} + except Exception as exc: + err = classify_error(exc) + logger.error("Ask error: %s [%s]", err.message, err.category) + return {"answer": None, "error": err.user_message(), + "error_category": err.category, "is_retryable": err.is_retryable} + + +@router.post("/nr") +async def nr_lookup(req: NrSpRequest): + """Lookup NR percentage by work type.""" + from smeta_railway.data.nr_sp_tables import NR_TABLE + return _lookup_table(NR_TABLE, req.query, "НР") + + +@router.post("/sp") +async def sp_lookup(req: NrSpRequest): + """Lookup SP percentage by work type.""" + from smeta_railway.data.nr_sp_tables import SP_TABLE + return _lookup_table(SP_TABLE, req.query, "СП") + + +def _lookup_table(table: dict, query: str, label: str) -> dict: + """Search NR/SP table by keyword.""" + query_lower = query.lower() + results = [] + for key, (name, pct) in table.items(): + if query_lower in name.lower(): + results.append({"key": key, "name": name, "percent": pct}) + # Sort by key (numeric-ish) + results.sort(key=lambda x: x["key"]) + return {"label": label, "query": query, "results": results[:20], "count": len(results)} diff --git a/src/smeta_railway/web/generator_api.py b/src/smeta_railway/web/generator_api.py new file mode 100644 index 0000000..908d364 --- /dev/null +++ b/src/smeta_railway/web/generator_api.py @@ -0,0 +1,109 @@ +""" +Generator API — 3-step estimate generation with human-in-the-loop. + +Endpoints: + POST /api/gen/parse — Step 1: description → list of work items + POST /api/gen/match — Step 2: items → GESN code matching + POST /api/gen/yaml — Step 3: matched items → YAML config +""" + +import logging + +from fastapi import APIRouter +from pydantic import BaseModel + +from smeta_railway.errors import classify_error + +logger = logging.getLogger(__name__) + +router = APIRouter() + +_generator = None + + +def _get_generator(): + global _generator + if _generator is None: + from smeta_railway.ai.generator import EstimateGenerator + _generator = EstimateGenerator() + return _generator + + +# --- Models --- + +class ParseRequest(BaseModel): + description: str + + +class MatchRequest(BaseModel): + items: list[dict] + + +class YamlRequest(BaseModel): + matched_items: list[dict] + region: str = "Приморский край" + trains_per_day: str = "91-108" + vl_zone: bool = True + okno: bool = True + + +# --- Endpoints --- + +@router.post("/parse") +async def parse(req: ParseRequest): + """Step 1: Parse text description → list of work items.""" + if not req.description.strip(): + return {"error": "Пустое описание", "items": []} + try: + gen = _get_generator() + items = gen.parse_description(req.description) + return {"items": items, "count": len(items), "error": None} + except Exception as exc: + err = classify_error(exc) + logger.error("Parse error: %s [%s]", err.message, err.category) + return {"items": [], "count": 0, "error": err.user_message(), + "is_retryable": err.is_retryable} + + +@router.post("/match") +async def match(req: MatchRequest): + """Step 2: Match work items → GESN codes (local FAISS, no API key).""" + if not req.items: + return {"error": "Нет позиций для поиска", "matched": []} + try: + gen = _get_generator() + matched = gen.match_gesn(req.items) + matched_count = sum(1 for m in matched if m.get("score", 0) > 0.3) + return { + "matched": matched, + "total": len(matched), + "matched_count": matched_count, + "error": None, + } + except Exception as exc: + err = classify_error(exc) + logger.error("Match error: %s [%s]", err.message, err.category) + return {"matched": [], "total": 0, "matched_count": 0, + "error": err.user_message()} + + +@router.post("/yaml") +async def generate_yaml(req: YamlRequest): + """Step 3: Generate YAML config from matched items.""" + if not req.matched_items: + return {"error": "Нет позиций", "yaml": ""} + try: + gen = _get_generator() + yaml_str = gen.generate_yaml( + req.matched_items, + region=req.region, + trains_per_day=req.trains_per_day, + vl_zone=req.vl_zone, + okno=req.okno, + ) + has_error = yaml_str.startswith("# ERROR") + return {"yaml": yaml_str, "error": yaml_str if has_error else None} + except Exception as exc: + err = classify_error(exc) + logger.error("YAML gen error: %s [%s]", err.message, err.category) + return {"yaml": "", "error": err.user_message()} diff --git a/src/smeta_railway/web/wizard_api.py b/src/smeta_railway/web/wizard_api.py index a87029b..87b7abd 100644 --- a/src/smeta_railway/web/wizard_api.py +++ b/src/smeta_railway/web/wizard_api.py @@ -11,9 +11,11 @@ import uuid from pathlib import Path from fastapi import APIRouter, HTTPException, UploadFile, File -from fastapi.responses import FileResponse +from fastapi.responses import FileResponse, JSONResponse from pydantic import BaseModel +from smeta_railway.errors import classify_error + from .xlsx_aggregator import ( AggConfig, analyze_xlsx, @@ -154,14 +156,22 @@ async def upload(zip_file: UploadFile = File(...), target_file: UploadFile = Fil async def analyze(req: AnalyzeRequest): """Search for keyword in sources, return matching rows for preview.""" sess = _get_session(req.session_id) - results = search_in_sources( - sess["sources_dir"], - req.source_sheet, - req.search_column, - req.search_keyword, - req.value_column, - max_rows=30, - ) + try: + results = search_in_sources( + sess["sources_dir"], + req.source_sheet, + req.search_column, + req.search_keyword, + req.value_column, + max_rows=30, + ) + except Exception as exc: + err = classify_error(exc) + return JSONResponse( + status_code=400 if not err.is_retryable else 503, + content={"error": err.message, "error_category": err.category, + "is_retryable": err.is_retryable}, + ) # Unique keys keys = sorted( set(r["key"] for r in results if r.get("key")), @@ -227,7 +237,15 @@ async def run(req: PreviewRequest): unmatched=req.unmatched, ) output_path = Path(sess["path"]) / "result.xlsx" - result = run_aggregation(sess["target_path"], output_path, sess["sources_dir"], config) + try: + result = run_aggregation(sess["target_path"], output_path, sess["sources_dir"], config) + except Exception as exc: + err = classify_error(exc) + return JSONResponse( + status_code=400 if not err.is_retryable else 503, + content={"error": err.message, "error_category": err.category, + "is_retryable": err.is_retryable}, + ) sess["output_path"] = str(output_path) return {