feat: Уровень 3 (генерация сметы) + Уровень 4 (проверка ошибок)
Уровень 3 — generator.py: - smeta auto "описание работ" → YAML смета - Pipeline: LLM парсит описание → search ГЭСН → LLM генерирует YAML - /auto в Telegram-боте Уровень 4 — checker.py: - smeta check project.yaml → отчёт об ошибках - 6 правил: несуществующие нормы, НР/СП, лимитированные, объёмы - Проверено: 4 ошибки + 2 предупреждения на тестовом YAML CLI: smeta auto, smeta check (всего 13 команд) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,184 @@
|
||||
"""
|
||||
Level 4: Automatic estimate checker.
|
||||
|
||||
Imports xlsx estimate and checks for common errors:
|
||||
- Non-existent GESN codes
|
||||
- Wrong coefficients
|
||||
- Missing overhead/limited costs
|
||||
- Unreasonable values
|
||||
"""
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from smeta_railway.data.nr_sp_tables import NR_TABLE, SP_TABLE
|
||||
|
||||
|
||||
@dataclass
|
||||
class CheckResult:
|
||||
level: str # "error", "warning", "info"
|
||||
code: str # rule code
|
||||
message: str
|
||||
position: str = "" # which position
|
||||
|
||||
|
||||
@dataclass
|
||||
class CheckReport:
|
||||
results: list[CheckResult] = field(default_factory=list)
|
||||
errors: int = 0
|
||||
warnings: int = 0
|
||||
info: int = 0
|
||||
|
||||
def add(self, level: str, code: str, message: str, position: str = ""):
|
||||
self.results.append(CheckResult(level, code, message, position))
|
||||
if level == "error":
|
||||
self.errors += 1
|
||||
elif level == "warning":
|
||||
self.warnings += 1
|
||||
else:
|
||||
self.info += 1
|
||||
|
||||
|
||||
# Non-existent GESN codes in FSNB-2022
|
||||
NON_EXISTENT_NORMS = [
|
||||
"28-01-042", "28-01-043", "28-01-044", "28-01-045",
|
||||
"28-01-050", "28-01-051", "28-01-052",
|
||||
"28-01-055", "28-01-056", "28-01-057",
|
||||
"28-01-064", "28-01-065", "28-01-066",
|
||||
]
|
||||
|
||||
# Valid coefficient ranges from Приложение 28.1
|
||||
VALID_K_RANGES = {
|
||||
"dvizhenie": (1.05, 1.70),
|
||||
"vl": (1.20, 1.20),
|
||||
"okno": (1.51, 1.81),
|
||||
}
|
||||
|
||||
|
||||
def check_norm_exists(code: str, resources: dict) -> CheckResult | None:
|
||||
"""Check if GESN norm exists in FSNB-2022."""
|
||||
clean = code.replace("ГЭСН ", "").strip()
|
||||
for prefix in NON_EXISTENT_NORMS:
|
||||
if clean.startswith(prefix):
|
||||
return CheckResult(
|
||||
"error", "NORM_NOT_EXISTS",
|
||||
f"Норма {code} не существует в ФСНБ-2022. "
|
||||
f"Нумерация сб.28 пропускает {prefix}.",
|
||||
code,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def check_coefficient_value(key: str, value: float) -> CheckResult | None:
|
||||
"""Check if coefficient value is within valid range."""
|
||||
if key in VALID_K_RANGES:
|
||||
min_v, max_v = VALID_K_RANGES[key]
|
||||
if value < min_v or value > max_v:
|
||||
return CheckResult(
|
||||
"warning", "COEFF_OUT_OF_RANGE",
|
||||
f"Коэффициент {key}={value} вне допустимого диапазона "
|
||||
f"[{min_v}, {max_v}] (Прил. 28.1)",
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def check_overhead_percent(nr_pct: float, sp_pct: float,
|
||||
work_type: str) -> list[CheckResult]:
|
||||
"""Check if НР/СП percentages match tables."""
|
||||
results = []
|
||||
|
||||
# Find matching entry in NR_TABLE
|
||||
nr_found = False
|
||||
for key, (name, pct) in NR_TABLE.items():
|
||||
if work_type.lower() in name.lower():
|
||||
if nr_pct != pct:
|
||||
results.append(CheckResult(
|
||||
"error", "NR_WRONG",
|
||||
f"НР={nr_pct}% не соответствует таблице 812/пр: "
|
||||
f"п.{key} «{name}» = {pct}%",
|
||||
))
|
||||
nr_found = True
|
||||
break
|
||||
|
||||
if not nr_found and nr_pct not in [v[1] for v in NR_TABLE.values()]:
|
||||
results.append(CheckResult(
|
||||
"warning", "NR_NOT_IN_TABLE",
|
||||
f"НР={nr_pct}% не найден в таблице 812/пр",
|
||||
))
|
||||
|
||||
return results
|
||||
|
||||
|
||||
def check_yaml_config(yaml_path: str | Path) -> CheckReport:
|
||||
"""Check a YAML project config for common errors."""
|
||||
import yaml as pyyaml
|
||||
|
||||
report = CheckReport()
|
||||
|
||||
with open(yaml_path) as f:
|
||||
config = pyyaml.safe_load(f)
|
||||
|
||||
# 1. Check coefficients
|
||||
coeffs = config.get("coefficients", {})
|
||||
for cdef in coeffs.get("definitions", []):
|
||||
result = check_coefficient_value(cdef["key"], cdef["value"])
|
||||
if result:
|
||||
report.add(result.level, result.code, result.message)
|
||||
|
||||
# 2. Check overhead
|
||||
overhead = config.get("overhead", {})
|
||||
nr = overhead.get("nr_railway", 0)
|
||||
sp = overhead.get("sp_railway", 0)
|
||||
|
||||
nr_entry = NR_TABLE.get("22") # ж/д
|
||||
if nr_entry and nr != nr_entry[1]:
|
||||
report.add("error", "NR_WRONG",
|
||||
f"НР для ж/д = {nr}%, должно быть {nr_entry[1]}% (812/пр, п.22)")
|
||||
|
||||
sp_entry = SP_TABLE.get("22")
|
||||
if sp_entry and sp != sp_entry[1]:
|
||||
report.add("error", "SP_WRONG",
|
||||
f"СП для ж/д = {sp}%, должно быть {sp_entry[1]}% (774/пр, п.22)")
|
||||
|
||||
# 3. Check limited costs
|
||||
limited = config.get("limited_costs", {})
|
||||
if not limited:
|
||||
report.add("warning", "NO_LIMITED_COSTS",
|
||||
"Отсутствуют лимитированные затраты (временные здания, зимнее, резерв)")
|
||||
|
||||
if limited.get("contingency_pct", 0) > 3.0:
|
||||
report.add("warning", "CONTINGENCY_HIGH",
|
||||
f"Резерв {limited['contingency_pct']}% > 3% (максимум для производственных объектов)")
|
||||
|
||||
# 4. Check sections for non-existent norms
|
||||
for section in config.get("sections", []):
|
||||
for sub in section.get("subsections", []):
|
||||
for item in sub.get("items", []):
|
||||
code = item.get("code", "")
|
||||
result = check_norm_exists(code, {})
|
||||
if result:
|
||||
report.add(result.level, result.code, result.message, code)
|
||||
|
||||
# Check unreasonable quantities
|
||||
qty = item.get("qty", 0)
|
||||
if isinstance(qty, (int, float)) and qty > 10000:
|
||||
report.add("warning", "QTY_HIGH",
|
||||
f"Количество {qty} > 10000 — проверьте единицу измерения",
|
||||
code)
|
||||
|
||||
# 5. Summary
|
||||
report.add("info", "SUMMARY",
|
||||
f"Проверка завершена: {report.errors} ошибок, {report.warnings} предупреждений")
|
||||
|
||||
return report
|
||||
|
||||
|
||||
def format_report(report: CheckReport) -> str:
|
||||
"""Format check report for display."""
|
||||
lines = []
|
||||
for r in report.results:
|
||||
icon = {"error": "❌", "warning": "⚠️", "info": "ℹ️"}.get(r.level, "")
|
||||
pos = f" [{r.position}]" if r.position else ""
|
||||
lines.append(f"{icon} {r.message}{pos}")
|
||||
return "\n".join(lines)
|
||||
@@ -0,0 +1,184 @@
|
||||
"""
|
||||
Level 3: Generate estimate YAML from natural language description.
|
||||
|
||||
Flow:
|
||||
1. User describes work in plain text
|
||||
2. LLM parses → list of (work description, unit, qty)
|
||||
3. Semantic search → GESN codes for each work
|
||||
4. LLM validates + fills gaps (coefficients, transport, region)
|
||||
5. Output: YAML config ready for `smeta generate`
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
from smeta_railway.ai.cag_context import CAG_CONTEXT
|
||||
from smeta_railway.ai.search import GESNSearch
|
||||
|
||||
|
||||
PARSE_PROMPT = """Ты — инженер-сметчик. Из описания работ извлеки список позиций для сметы.
|
||||
|
||||
Для КАЖДОЙ позиции укажи:
|
||||
- description: что за работа (кратко, как в ГЭСН)
|
||||
- unit: единица измерения (км, м³, шт, 100 м³, 1000 м², пар резок, и т.д.)
|
||||
- qty: количество (число)
|
||||
- note: примечание (если есть)
|
||||
|
||||
Ответ СТРОГО в JSON формате:
|
||||
```json
|
||||
[
|
||||
{"description": "...", "unit": "...", "qty": ..., "note": "..."},
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
НЕ придумывай позиции, которых нет в описании.
|
||||
Если единица/количество не указаны — укажи "уточнить".
|
||||
|
||||
Описание:
|
||||
{text}"""
|
||||
|
||||
YAML_PROMPT = """Ты — инженер-сметчик. Сгенерируй YAML-конфиг сметы на основе:
|
||||
1. Списка позиций с кодами ГЭСН
|
||||
2. Параметров проекта
|
||||
|
||||
{cag_context}
|
||||
|
||||
Позиции:
|
||||
{positions_json}
|
||||
|
||||
Параметры:
|
||||
- Регион: {region}
|
||||
- Число поездов/сут: {trains_per_day}
|
||||
- Зона ВЛ: {vl_zone}
|
||||
- Работы в окно: {okno}
|
||||
|
||||
Сгенерируй YAML-конфиг в формате smeta-railway (sections → subsections → items).
|
||||
Каждый item: code, name, unit, qty, note.
|
||||
Включи: coefficients, overhead, limited_costs, transport (если ж/д).
|
||||
|
||||
Ответ — ТОЛЬКО YAML, без пояснений."""
|
||||
|
||||
|
||||
class EstimateGenerator:
|
||||
"""Generate estimate YAML from natural language description."""
|
||||
|
||||
def __init__(self, resources_path: str | Path = "resources.json"):
|
||||
self.search = GESNSearch(resources_path=str(resources_path))
|
||||
|
||||
def _call_llm(self, prompt: str) -> str:
|
||||
"""Call GLM-5 via Z.AI."""
|
||||
from openai import OpenAI
|
||||
|
||||
api_key = os.environ.get("ZAI_API_KEY")
|
||||
base_url = os.environ.get("ZAI_BASE_URL",
|
||||
"https://open.bigmodel.cn/api/coding/paas/v4")
|
||||
client = OpenAI(api_key=api_key, base_url=base_url)
|
||||
response = client.chat.completions.create(
|
||||
model="glm-5",
|
||||
messages=[{"role": "user", "content": prompt}],
|
||||
temperature=0,
|
||||
max_tokens=8192,
|
||||
)
|
||||
return response.choices[0].message.content or ""
|
||||
|
||||
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 []
|
||||
|
||||
def match_gesn(self, items: list[dict]) -> list[dict]:
|
||||
"""Step 2: Match each work description to GESN code."""
|
||||
matched = []
|
||||
for item in items:
|
||||
results = self.search.find(item["description"], top_k=3)
|
||||
if results:
|
||||
best = results[0]
|
||||
item["gesn_code"] = f"ГЭСН {best.code}"
|
||||
item["gesn_name"] = best.name
|
||||
item["gesn_unit"] = best.unit
|
||||
item["score"] = best.score
|
||||
item["alternatives"] = [
|
||||
{"code": r.code, "name": r.name[:50], "score": r.score}
|
||||
for r in results[1:]
|
||||
]
|
||||
else:
|
||||
item["gesn_code"] = "НЕ НАЙДЕН"
|
||||
item["gesn_name"] = ""
|
||||
item["score"] = 0
|
||||
item["alternatives"] = []
|
||||
matched.append(item)
|
||||
return matched
|
||||
|
||||
def generate_yaml(
|
||||
self,
|
||||
matched_items: list[dict],
|
||||
region: str = "Приморский край",
|
||||
trains_per_day: str = "91-108",
|
||||
vl_zone: bool = True,
|
||||
okno: bool = True,
|
||||
) -> str:
|
||||
"""Step 3: Generate YAML config from matched items."""
|
||||
positions_json = json.dumps(matched_items, ensure_ascii=False, indent=2)
|
||||
|
||||
prompt = YAML_PROMPT.format(
|
||||
cag_context=CAG_CONTEXT[:3000], # truncate for token limit
|
||||
positions_json=positions_json,
|
||||
region=region,
|
||||
trains_per_day=trains_per_day,
|
||||
vl_zone="да" if vl_zone else "нет",
|
||||
okno="да" if okno else "нет",
|
||||
)
|
||||
response = self._call_llm(prompt)
|
||||
|
||||
# Extract YAML from response
|
||||
if "```yaml" in response:
|
||||
return response.split("```yaml")[1].split("```")[0].strip()
|
||||
if "```" in response:
|
||||
return response.split("```")[1].split("```")[0].strip()
|
||||
return response.strip()
|
||||
|
||||
def auto(
|
||||
self,
|
||||
description: str,
|
||||
region: str = "Приморский край",
|
||||
trains_per_day: str = "91-108",
|
||||
vl_zone: bool = True,
|
||||
okno: bool = True,
|
||||
) -> dict:
|
||||
"""Full pipeline: description → parsed → matched → YAML."""
|
||||
print("1. Parsing description...")
|
||||
items = self.parse_description(description)
|
||||
print(f" Found {len(items)} work items")
|
||||
|
||||
print("2. Matching GESN codes...")
|
||||
matched = self.match_gesn(items)
|
||||
for m in matched:
|
||||
score_pct = f"{m['score']:.0%}" if m['score'] else "?"
|
||||
print(f" {m['gesn_code']}: {m['description'][:50]} ({score_pct})")
|
||||
|
||||
print("3. Generating YAML...")
|
||||
yaml_str = self.generate_yaml(matched, region, trains_per_day, vl_zone, okno)
|
||||
|
||||
return {
|
||||
"items": matched,
|
||||
"yaml": yaml_str,
|
||||
"item_count": len(items),
|
||||
"matched_count": sum(1 for m in matched if m["score"] > 0.3),
|
||||
}
|
||||
@@ -182,6 +182,46 @@ async def sp_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
await update.message.reply_text(f"Не найдено СП для «{query}».")
|
||||
|
||||
|
||||
async def auto_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
"""Generate estimate from description."""
|
||||
text = " ".join(context.args) if context.args else ""
|
||||
if not text:
|
||||
await update.message.reply_text(
|
||||
"Опишите работы. Пример:\n"
|
||||
"/auto Капремонт пути 2 км, ж/б шпалы, КБ-65, очистка щебня, замена рельсов Р65"
|
||||
)
|
||||
return
|
||||
|
||||
await update.message.reply_text("⚙️ Генерирую смету...")
|
||||
|
||||
try:
|
||||
from smeta_railway.ai.generator import EstimateGenerator
|
||||
gen = EstimateGenerator()
|
||||
result = gen.auto(text)
|
||||
|
||||
msg = f"📋 Найдено позиций: {result['matched_count']}/{result['item_count']}\n\n"
|
||||
for item in result["items"][:10]:
|
||||
score = f"{item['score']:.0%}" if item.get("score") else "?"
|
||||
msg += f"• `{item.get('gesn_code', '?')}` ({score})\n {item['description'][:60]}\n"
|
||||
|
||||
if len(msg) > 4000:
|
||||
msg = msg[:3900] + "\n\n... (сокращено)"
|
||||
|
||||
await update.message.reply_text(msg, parse_mode="Markdown")
|
||||
except Exception as e:
|
||||
logger.error(f"Auto error: {e}")
|
||||
await update.message.reply_text(f"Ошибка: {e}")
|
||||
|
||||
|
||||
async def check_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
"""Check estimate for errors."""
|
||||
await update.message.reply_text(
|
||||
"Отправьте YAML-файл проекта для проверки, или используйте CLI:\n"
|
||||
"`smeta check project.yaml`",
|
||||
parse_mode="Markdown",
|
||||
)
|
||||
|
||||
|
||||
async def text_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
"""Handle plain text — auto-detect search or question."""
|
||||
text = update.message.text.strip()
|
||||
@@ -224,6 +264,8 @@ def run_bot():
|
||||
app.add_handler(CommandHandler("ask", ask_command))
|
||||
app.add_handler(CommandHandler("nr", nr_command))
|
||||
app.add_handler(CommandHandler("sp", sp_command))
|
||||
app.add_handler(CommandHandler("auto", auto_command))
|
||||
app.add_handler(CommandHandler("check", check_command))
|
||||
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, text_message))
|
||||
|
||||
logger.info("Bot started. Polling...")
|
||||
|
||||
@@ -330,6 +330,44 @@ def build_rag_cmd(
|
||||
typer.echo(f"RAG index built: {len(chunks)} chunks")
|
||||
|
||||
|
||||
@app.command()
|
||||
def auto(
|
||||
description: str = typer.Argument(..., help="Work description in natural language"),
|
||||
region: str = typer.Option("Приморский край", "--region", "-r"),
|
||||
output: str | None = typer.Option(None, "--output", "-o", help="Output YAML path"),
|
||||
):
|
||||
"""Generate estimate YAML from work description (Level 3)."""
|
||||
from smeta_railway.ai.generator import EstimateGenerator
|
||||
|
||||
gen = EstimateGenerator()
|
||||
result = gen.auto(description, region=region)
|
||||
|
||||
typer.echo(f"\nMatched: {result['matched_count']}/{result['item_count']} items")
|
||||
|
||||
if output:
|
||||
with open(output, "w") as f:
|
||||
f.write(result["yaml"])
|
||||
typer.echo(f"YAML saved: {output}")
|
||||
else:
|
||||
typer.echo("\n--- YAML ---")
|
||||
typer.echo(result["yaml"])
|
||||
|
||||
|
||||
@app.command()
|
||||
def check(
|
||||
yaml_path: Path = typer.Argument(..., help="Project YAML to check"),
|
||||
):
|
||||
"""Check estimate YAML for errors (Level 4)."""
|
||||
from smeta_railway.ai.checker import check_yaml_config, format_report
|
||||
|
||||
if not yaml_path.exists():
|
||||
typer.echo(f"Error: {yaml_path} not found", err=True)
|
||||
raise typer.Exit(1)
|
||||
|
||||
report = check_yaml_config(yaml_path)
|
||||
typer.echo(format_report(report))
|
||||
|
||||
|
||||
@app.command()
|
||||
def bot():
|
||||
"""Start Telegram bot."""
|
||||
|
||||
Reference in New Issue
Block a user