diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md new file mode 100644 index 0000000..a8eca8b --- /dev/null +++ b/ARCHITECTURE.md @@ -0,0 +1,128 @@ +# Архитектура smeta-web + smeta-railway + +## Обзор + +``` +Пользователь (браузер) + │ + ▼ +┌─────────────────────────────────────────────┐ +│ nginx (443) → uvicorn (8101) │ +│ smeta-web/main.py (FastAPI) │ +│ │ +│ ┌─────────────────────────────────────┐ │ +│ │ AI_BACKEND routing (auto): │ │ +│ │ файлы → claude_bridge.py (Docker) │ │ +│ │ нормативка → claude_bridge_glm.py │ │ +│ │ верификация → claude_bridge_sonnet │ │ +│ └──────┬──────────────┬───────────────┘ │ +│ │ │ │ +│ ┌────▼────┐ ┌────▼──────────┐ │ +│ │ Claude │ │ GLM-5 (Z.AI) │ │ +│ │ Code │ │ + CAG + RAG │ │ +│ │ Docker │ │ + ФССЦ │ │ +│ │ sandbox│ │ + зимнее │ │ +│ └─────────┘ └───────────────┘ │ +└─────────────────────────────────────────────┘ + │ + ┌────▼──────────────────────────┐ + │ smeta-railway (knowledge) │ + │ ├── ai/index/ (FAISS RAG) │ + │ ├── data/ (НР/СП, коэфф.) │ + │ ├── resources.json (24K) │ + │ ├── data/gesn_extra/ (181K) │ + │ ├── data/fssc_2022/ (6.7M) │ + │ └── literature/ (PDF/HTM) │ + └───────────────────────────────┘ +``` + +## Модули smeta-web + +| Файл | Строк | Назначение | +|------|-------|------------| +| `main.py` | ~800 | FastAPI: endpoints, маршрутизация, auth | +| `claude_bridge.py` | ~240 | Claude Code через Docker sandbox | +| `claude_bridge_glm.py` | ~400 | GLM-5 API + CAG/RAG оркестрация | +| `claude_bridge_sonnet.py` | ~240 | Claude Sonnet + Chain-of-Verification | +| `search_engine.py` | ~190 | Поиск: ФССЦ, ГЭСН, зимнее (pymorphy2) | +| `batch_v3.py` | ~770 | Пакетная обработка файлов | +| `xlsx_utils.py` | ~110 | XML-парсер xlsx, распаковка zip | +| `db.py` | ~200 | SQLite: сообщения, пользователи, инвайты | +| `auth.py` | ~150 | JWT, bcrypt, email-верификация | +| `email_service.py` | ~80 | SMTP отправка кодов | + +## Потоки данных + +### Вопрос по нормативке (GLM backend) + +``` +1. Пользователь: "Какой НР для бетонных работ?" +2. main.py → auto-router → claude_bridge_glm.stream_claude() +3. Загрузка данных: + ├── CAG: НР/СП таблицы (всегда в system prompt, ~5700 токенов) + ├── search_engine._search_resources() → поиск в resources.json (24K) + ├── search_engine._search_gesn_extra() → поиск в gesn_extra (181K) + ├── search_engine._search_fssc() → поиск цен материалов (42K) + ├── search_engine._search_winter() → зоны зимнего удорожания + ├── RAG (FAISS, 30K чанков) → семантический поиск по PDF + └── _search_normative() → нормативный RAG (TG-посты) +4. Контексты добавляются в user message +5. POST → GLM-5 API → ответ со ссылками на документы +6. SSE stream → пользователю +``` + +### Работа с файлами (Claude backend) + +``` +1. Пользователь загружает xlsx +2. POST /api/upload → сохранение в DATA_DIR/{user}/{tab}/ +3. Пользователь: "Покажи итоги сметы" +4. auto-router → claude_bridge.stream_claude() +5. Docker: smeta-claude-sandbox + ├── mount /smeta (ro) — нормативная база + ├── mount /data (rw) — файлы пользователя + └── Claude Code CLI → читает xlsx, отвечает +6. SSE stream → пользователю +``` + +## Источники данных + +| Источник | Формат | Записей | Обновление | +|----------|--------|---------|------------| +| НР/СП (812/пр, 774/пр) | Python dict (CAG) | 274×2 | При изменении приказа | +| Коэффициенты 421/пр | Python dict (CAG) | ~80 | При изменении приказа | +| ГЭСН resources.json | JSON | 24K | API cs.smetnoedelo.ru | +| ГЭСН gesn_extra | 47 JSON | 181K | API cs.smetnoedelo.ru | +| ФССЦ-2022 | 86 JSON (по регионам) | 6.7M | ФГИС ЦС API (ежеквартально) | +| RAG index | FAISS + pickle | 30K чанков | Пересборка после добавления PDF | +| PDF документы | 100+ файлов | ~330 MB | Ручное скачивание | +| Зимнее удорожание | Python dict | 87 регионов | При изменении ГСН | +| Временные здания | Python dict | 50+ типов | При изменении ГСН | + +## Деплой + +``` +Сервер: 192.168.87.76 (git.kazin.ru = smeta.kazin.ru) +OS: Ubuntu, 32GB RAM, 8 CPU +Пользователь: mcp-user +Сервис: smeta-web.service (uvicorn:8101) +Nginx: 443 → 8101 + +Команды: + scp *.py server-mcp-user:/home/mcp-user/smeta-web/ + ssh server-mcp-user "sudo systemctl restart smeta-web" + +Тестирование: + python tests/test_chat_quality.py # 100 вопросов + python tests/test_chat_quality.py --quick # 20 вопросов + python scripts/verify_knowledge_base.py # целостность данных +``` + +## Для нового разработчика + +1. Прочитай `claude_bridge_glm.py` — основной AI backend +2. Прочитай `search_engine.py` — поиск по данным +3. Прочитай `main.py` строки 23-60 — маршрутизация +4. Запусти `python tests/test_chat_quality.py --quick` — проверь что работает +5. CAG-контекст: `smeta-railway/src/smeta_railway/ai/cag_context.py` +6. RAG-индекс: `smeta-railway/src/smeta_railway/ai/index/` diff --git a/batch_v3.py b/batch_v3.py index b558279..814371b 100644 --- a/batch_v3.py +++ b/batch_v3.py @@ -24,22 +24,423 @@ import xml.etree.ElementTree as ET from pathlib import Path from typing import AsyncGenerator -from batch import read_xlsx_xml, extract_zip -from batch_v2 import ( - build_claude_prompt, - convert_all_to_csv, - prepare_samples, - _read_result_files, - DOCKER_IMAGE, - CLAUDE_CONFIG_DIR, - DOCKER_HOST_GW, - XRAY_PORT, +from xlsx_utils import read_xlsx_xml, extract_zip + +DOCKER_IMAGE = os.environ.get("CLAUDE_DOCKER_IMAGE", "smeta-claude-sandbox") +CLAUDE_CONFIG_DIR = os.environ.get( + "CLAUDE_CONFIG_DIR", os.path.expanduser("~/.claude") ) +DOCKER_HOST_GW = os.environ.get("DOCKER_HOST_GW", "172.17.0.1") +XRAY_PORT = os.environ.get("XRAY_PORT", "10809") + +# Token estimation: ~0.3 tokens per byte for CSV text +TOKENS_PER_BYTE = 0.3 +MAX_CONTEXT_TOKENS = 800_000 # leave headroom from 1M +MAX_SAMPLE_FILES = 15 # sample xlsx for Claude to read +MAX_SAMPLE_BYTES = 500_000 # max total bytes of sample CSVs # V3 job storage (separate from V2) _jobs: dict[str, dict] = {} +# --------------------------------------------------------------------------- +# Functions merged from batch_v2.py +# --------------------------------------------------------------------------- + + +def convert_xlsx_to_csv(xlsx_path: str, output_dir: str) -> list[str]: + """Convert xlsx to CSV files via XML parser (handles broken styles). + + Returns list of created CSV file paths. + """ + data = read_xlsx_xml(xlsx_path, max_rows=9999) + if "_error" in data and len(data) == 1: + return [] + + created = [] + stem = Path(xlsx_path).stem + for sheet_name, rows in data.items(): + if sheet_name == "_error": + continue + # Skip empty sheets + if not rows or all(not any(cell for cell in row) for row in rows): + continue + safe_name = "".join(c if c.isalnum() or c in " _-" else "_" for c in sheet_name) + csv_path = Path(output_dir) / f"{stem}__{safe_name}.csv" + with open(csv_path, "w", newline="", encoding="utf-8") as f: + writer = csv.writer(f) + for row in rows: + writer.writerow(row) + created.append(str(csv_path)) + return created + + +def convert_all_to_csv(source_dir: str, csv_dir: str) -> dict: + """Convert all xlsx files in source_dir to CSV in csv_dir. + + Returns {"files": [...], "total_bytes": int, "estimated_tokens": int}. + """ + Path(csv_dir).mkdir(parents=True, exist_ok=True) + all_csv = [] + total_bytes = 0 + + SMETA_EXT = {'.xlsx', '.xls', '.gge', '.esw', '.xml'} + xlsx_files = sorted( + f for f in Path(source_dir).rglob("*") + if f.is_file() and f.suffix.lower() in SMETA_EXT + and not f.name.startswith("~$") and not f.name.startswith("._") + ) + + for xlsx in xlsx_files: + # .gge/.esw are XML — copy as-is (no xlsx conversion needed) + if xlsx.suffix.lower() in ('.gge', '.esw', '.xml'): + dst = Path(csv_dir) / f"{xlsx.stem}.xml" + shutil.copy2(str(xlsx), str(dst)) + size = dst.stat().st_size + all_csv.append({"path": str(dst), "name": dst.name, "bytes": size}) + total_bytes += size + continue + csvs = convert_xlsx_to_csv(str(xlsx), csv_dir) + for c in csvs: + size = Path(c).stat().st_size + all_csv.append({"path": c, "name": Path(c).name, "bytes": size}) + total_bytes += size + + return { + "files": all_csv, + "total_bytes": total_bytes, + "estimated_tokens": int(total_bytes * TOKENS_PER_BYTE), + "xlsx_count": len(xlsx_files), + } + + +def select_samples(source_dir: str, csv_info: dict) -> list[str]: + """Select a diverse sample of xlsx files for Claude to analyze. + + Strategy: pick files of different sizes and from different subdirs. + Returns list of xlsx file paths (originals, not CSV). + """ + SMETA_EXT = {'.xlsx', '.xls', '.gge', '.esw', '.xml'} + xlsx_files = sorted( + [f for f in Path(source_dir).rglob("*") + if f.is_file() and f.suffix.lower() in SMETA_EXT + and not f.name.startswith("~$") and not f.name.startswith("._")], + key=lambda f: f.stat().st_size, + ) + if len(xlsx_files) <= MAX_SAMPLE_FILES: + return [str(f) for f in xlsx_files] + + # Pick diverse: smallest, largest, and evenly spaced + n = len(xlsx_files) + indices = set() + indices.add(0) # smallest + indices.add(n - 1) # largest + # Evenly spaced + step = max(1, n // (MAX_SAMPLE_FILES - 2)) + for i in range(0, n, step): + indices.add(i) + if len(indices) >= MAX_SAMPLE_FILES: + break + # If still room, add from different directories + if len(indices) < MAX_SAMPLE_FILES: + dirs_seen = set() + for i, f in enumerate(xlsx_files): + d = str(f.parent) + if d not in dirs_seen: + dirs_seen.add(d) + indices.add(i) + if len(indices) >= MAX_SAMPLE_FILES: + break + + return [str(xlsx_files[i]) for i in sorted(indices)][:MAX_SAMPLE_FILES] + + +def prepare_samples(source_dir: str, job_dir: Path, csv_info: dict) -> dict: + """Convert only sample files to CSV in /data/sample_csv/ for Claude. + + Returns {"sample_files": [...], "sample_csv_dir": str}. + """ + sample_xlsx = select_samples(source_dir, csv_info) + sample_csv_dir = job_dir / "sample_csv" + sample_csv_dir.mkdir(parents=True, exist_ok=True) + + converted_xlsx = [] + sample_csvs = [] + total_bytes = 0 + for xlsx in sample_xlsx: + # .gge/.esw/.xml — copy as-is, no xlsx conversion + if Path(xlsx).suffix.lower() in ('.gge', '.esw', '.xml'): + dst = sample_csv_dir / f"{Path(xlsx).stem}.xml" + shutil.copy2(xlsx, str(dst)) + converted_xlsx.append(xlsx) + sample_csvs.append(str(dst)) + total_bytes += dst.stat().st_size + continue + csvs = convert_xlsx_to_csv(xlsx, str(sample_csv_dir)) + converted_xlsx.append(xlsx) + for c in csvs: + size = Path(c).stat().st_size + sample_csvs.append(c) + total_bytes += size + if total_bytes > MAX_SAMPLE_BYTES: + break + + return { + "sample_files": converted_xlsx, + "sample_csv_dir": str(sample_csv_dir), + "sample_csv_count": len(sample_csvs), + "sample_bytes": total_bytes, + } + + +def build_claude_prompt( + task_description: str, + sample_csv_dir: str, + target_csv_dir: str, + target_filename: str, + total_xlsx_count: int, + sample_xlsx_names: list[str], +) -> str: + """Build the prompt for Claude Code to analyze sample files and generate script.""" + sample_names = "\n".join(f"- {Path(f).name}" for f in sample_xlsx_names) + return f"""You are an expert in Russian construction cost estimation (smeta). + +## Task +{task_description} + +## Source files +There are {total_xlsx_count} xlsx source files total. You have {len(sample_xlsx_names)} SAMPLE files +converted to CSV in /data/sample_csv/ for analysis. +CSV naming: {{original_xlsx_stem}}__{{sheet_name}}.csv + +Sample files: +{sample_names} + +## Target file +The target summary file is converted to CSV in /data/target_csv/. +Original filename: {target_filename} +NOTE: In the script, use the `target_file` variable (not a hardcoded path). + +## Your job +1. Read the sample CSV files in /data/sample_csv/ — understand their structure +2. Read the target CSV files in /data/target_csv/ — understand where data goes +3. Figure out: what to extract from each source, how to match to target rows +4. FIRST write /data/batch_summary.json, THEN write /data/batch_script.py + +## MANDATORY: /data/batch_summary.json — write this FIRST! +The user is a construction estimator, not a programmer. This summary is shown to them for review. +JSON with these fields (in Russian): +```json +{{ + "description": "Краткое описание что будет сделано", + "source_patterns": {{ + "sheet": "на каком листе искать данные", + "id_field": "где шифр/название сметы (например: имя файла, ячейка B5)", + "totals": {{ + "строительные работы": "паттерн поиска (например: ВСЕГО строительные работы)", + "монтажные работы": "паттерн поиска", + "оборудование": "паттерн поиска", + "прочие затраты": "паттерн поиска" + }}, + "value_column": "в каком столбце значения (например: A или H)", + "units": "рубли или тыс.руб" + }}, + "target_mapping": {{ + "sheet": "на какой лист сводного файла записывать", + "match_column": "столбец с шифрами для сопоставления (например: B)", + "value_columns": {{ + "строительные работы": "столбец (например: D)", + "монтажные работы": "столбец (например: E)", + "оборудование": "столбец (например: F)", + "прочие затраты": "столбец (например: G)" + }}, + "units": "тыс.руб" + }}, + "conversion": "делить на 1000 (руб → тыс.руб)" или "без конвертации", + "preview": [ + {{ + "source_file": "имя файла источника", + "source_values": {{"строительные работы": 15460805.77, "монтажные работы": 0}}, + "target_sheet": "ССРСС ТУЦ", + "target_row": "строка 17 (ЛС-01-02-2-00-01 Устройство насыпи)", + "target_values": {{"D": 15460.81, "E": 0, "F": 0, "G": 0}} + }} + ] +}} +``` +The "preview" array must contain entries for ALL sample files — show the actual extracted values +and where they will go in the target. This is the most important part for the user to verify! + +### File 2: /data/batch_script.py — Python script + +## CRITICAL: The script will run on ALL {total_xlsx_count} files, not just samples! +The script must handle any file with the same general structure as the samples. + +## Script execution context (these variables will be available): +- `source_files`: list[str] — paths to ALL {total_xlsx_count} original xlsx files +- `target_file`: str — path to target xlsx (a copy, safe to modify) +- `job`: dict — job["processed"] += 1 per file, job["errors"].append("msg") for errors +- `read_xlsx_xml(path, max_rows=9999)`: dict[sheet_name, list[list[str]]] + IMPORTANT: ALWAYS pass max_rows=9999! Default is only 50 rows — totals are at the END of files! + Column indices: A=0, B=1, C=2, ..., H=7, etc. Values are strings. +- `openpyxl`: for writing to target xlsx +- `Path`, `csv`, `json`, `re`, `os` + +## Script requirements +- Self-contained, using ONLY the variables above +- NO `if __name__` or `def main()` wrappers — top-level code +- Robust: skip files with unexpected structure, log to job["errors"] +- Track progress: job["processed"] += 1 after each successful file +- Save at the end: wb.save(target_file) +""" + + +def _read_result_files(job_dir: Path) -> dict: + """Read batch_script.py and batch_summary.json from job dir.""" + script_path = job_dir / "batch_script.py" + summary_path = job_dir / "batch_summary.json" + summary = {} + if summary_path.exists(): + try: + summary = json.loads(summary_path.read_text(encoding="utf-8")) + except (json.JSONDecodeError, OSError): + pass + if script_path.exists(): + return {"script": script_path.read_text(encoding="utf-8"), "summary": summary} + return {"script": "", "result": "Script not generated", "summary": summary} + + +async def run_claude_analysis( + job_dir: Path, + task_description: str, + target_filename: str, + total_xlsx_count: int, + sample_info: dict, +) -> AsyncGenerator[dict, None]: + """Run Claude Code in Docker to analyze files and generate script (V2 style, no verify).""" + target_csv_dir = str(job_dir / "target_csv") + prompt = build_claude_prompt( + task_description, + sample_info["sample_csv_dir"], + target_csv_dir, + target_filename, + total_xlsx_count, + sample_info["sample_files"], + ) + + cmd = [ + "docker", "run", "--rm", + "--memory=1g", "--cpus=2", "--network=host", + "-v", f"{job_dir.resolve()}:/data", + "-v", f"{CLAUDE_CONFIG_DIR}:/home/worker/.claude", + "-v", f"{os.path.expanduser('~')}/.claude.json:/home/worker/.claude.json", + "-e", f"HTTPS_PROXY=http://{DOCKER_HOST_GW}:{XRAY_PORT}", + "-e", f"HTTP_PROXY=http://{DOCKER_HOST_GW}:{XRAY_PORT}", + "-e", "HOME=/home/worker", + "-w", "/data", + DOCKER_IMAGE, + "-p", prompt, + "--output-format", "stream-json", + "--verbose", + "--allowedTools", "Bash,Read,Write,Edit,Glob,Grep", + "--max-turns", "30", + ] + + try: + proc = await asyncio.create_subprocess_exec( + *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL, + ) + except FileNotFoundError: + yield {"type": "done", "script": "", "result": "Docker not found"} + return + + got_result = False + try: + while True: + raw_line = await proc.stdout.readline() + if not raw_line: + break + line = raw_line.decode().strip() + if not line: + continue + try: + event = json.loads(line) + except json.JSONDecodeError: + continue + etype = event.get("type", "") + if etype == "assistant": + msg = event.get("message", {}) + for block in msg.get("content", []): + if block.get("type") == "text": + yield {"type": "text", "text": block["text"]} + elif block.get("type") == "tool_use": + yield {"type": "tool", "tool": block.get("name", "")} + elif etype == "result": + got_result = True + result_data = _read_result_files(job_dir) + yield {"type": "done", **result_data} + finally: + if proc.returncode is None: + proc.terminate() + try: + await asyncio.wait_for(proc.wait(), timeout=5) + except asyncio.TimeoutError: + proc.kill() + + if not got_result: + result_data = _read_result_files(job_dir) + yield {"type": "done", **result_data} + + +def run_batch_v2(job_id: str, script: str, source_dir: str, target_file: str): + """Execute the Claude-generated script on all files.""" + job = _jobs[job_id] + job["status"] = "running" + job["started_at"] = time.time() + + SMETA_EXT = {'.xlsx', '.xls', '.gge', '.esw', '.xml'} + source_files = [ + str(f) for f in Path(source_dir).rglob("*") + if f.is_file() and f.suffix.lower() in SMETA_EXT + and not f.name.startswith("~$") and not f.name.startswith("._") + ] + job["total_files"] = len(source_files) + job["processed"] = 0 + job["errors"] = [] + + output_file = str(Path(target_file).parent / f"result_{Path(target_file).name}") + shutil.copy2(target_file, output_file) + + try: + exec_globals = { + "__builtins__": __builtins__, + "source_files": source_files, + "target_file": output_file, + "job": job, + "read_xlsx_xml": read_xlsx_xml, + "Path": Path, + "csv": csv, + "json": json, + "zipfile": zipfile, + "ET": ET, + "os": os, + "re": re, + } + try: + import openpyxl + exec_globals["openpyxl"] = openpyxl + except ImportError: + pass + exec(script, exec_globals) + job["status"] = "completed" + job["output_file"] = output_file + except Exception as e: + job["status"] = "failed" + job["error"] = f"{type(e).__name__}: {e}\n{traceback.format_exc()}" + + job["finished_at"] = time.time() + + def create_job(job_id: str) -> dict: _jobs[job_id] = { "id": job_id, diff --git a/claude_bridge_direct.py b/claude_bridge_direct.py.deprecated similarity index 100% rename from claude_bridge_direct.py rename to claude_bridge_direct.py.deprecated diff --git a/claude_bridge_glm.py b/claude_bridge_glm.py index 1459ebb..673605f 100644 --- a/claude_bridge_glm.py +++ b/claude_bridge_glm.py @@ -33,9 +33,7 @@ def _load_smeta_data(): if _cag_context: return - # Load CAG context - import sys - sys.path.insert(0, str(SMETA_DIR / "src")) + # Load CAG context (smeta-railway installed via pip install -e) try: from smeta_railway.ai.cag_context import CAG_CONTEXT _cag_context = CAG_CONTEXT @@ -51,15 +49,20 @@ def _load_smeta_data(): def _build_system_prompt() -> str: _load_smeta_data() - return f"""Ты — профессиональный ИИ-ассистент-сметчик железнодорожного строительства. + return f"""Ты — профессиональный ИИ-ассистент сметчика. Все 47 сборников ГЭСН, 181 000+ расценок. Отвечай ТОЛЬКО на русском языке. Пользователь — сметчик, НЕ программист. НИКОГДА не упоминай названия книг или учебников. Ссылайся только на нормативные документы. +Если расценка или норма НЕ найдена — скажи об этом прямо, НЕ возвращай пустой ответ. Ниже — актуальная нормативная база. Используй ТОЛЬКО эти данные для ответов: {_cag_context} -Если вопрос про конкретную расценку ГЭСН — скажи что проверишь по базе.""" +Дополнительные данные (используй при соответствующих вопросах): +- Зимнее удорожание: ГСН 81-05-02-2007, Приказ 325/пр. Якутия (центр) — зона VII, 1.X–30.IV. Москва — зона II, 15.XI–15.III. Хабаровск — зона IV, 25.X–10.IV. +- Временные здания: ГСН 81-05-01-2001. Жилые дома 1.8–3.0%, промышленное строительство 2.6–4.5%. +- ФСНБ-2022: 47 сборников ГЭСН, утв. приказом 1046/пр + 17 дополнений (И1-И17). +- Индексы пересчёта: 86 регионов, обновляются ежеквартально (письма Минстроя).""" # --- Normative RAG (TG posts + PDF from smeta-monitor) --- @@ -112,10 +115,6 @@ def _search_normative(query: str, top_k: int = 3) -> str: return "" try: - import sys - smeta_src = Path(__file__).parent.parent / "smeta-railway" / "src" - if str(smeta_src) not in sys.path: - sys.path.insert(0, str(smeta_src)) from smeta_railway.ai.embeddings import embed_query emb = embed_query(query) @@ -142,34 +141,7 @@ def _search_normative(query: str, top_k: int = 3) -> str: return "" -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) +from search_engine import _normalize, _search_fssc, _search_resources, _search_gesn_extra, _search_winter def get_work_dir(username: str, tab_id: str) -> Path: @@ -290,9 +262,50 @@ async def stream_claude( "кровел", "штукатур", "гидроизоляц", "теплоизоляц", "трубопровод", "кабел", "электромонтаж", "сантехн", "вентиляц", "благоустр", "сварочн", "устройство", "ремонт пути", "всп", "сцб", + "очист", "разбор", "уклад", "монтаж", "демонтаж", "подготов", + "расценк", "гэсн", "фер", "норм", ] if any(p in message.lower() for p in gesn_patterns): - resource_context = _search_resources(message) + resource_context = _search_resources(message, _resources) + # Also search in full 181K GESN extra + gesn_extra = _search_gesn_extra(message) + if gesn_extra: + resource_context = (resource_context + "\n\n" + gesn_extra) if resource_context else gesn_extra + + # Search ФССЦ material prices + fssc_context = "" + mat_patterns = ["цен", "стоимост", "материал", "бетон", "арматур", "кирпич", + "песок", "щебен", "цемент", "раствор", "труб", "кабел", "провод", + "фссц", "сметн цен"] + if any(p in message.lower() for p in mat_patterns): + fssc_context = _search_fssc(message, top_k=10) + + # Search winter zones + winter_context = "" + winter_patterns = ["зимн", "зона", "удорожан", "морозн", "температур"] + if any(p in message.lower() for p in winter_patterns): + winter_context = _search_winter(message) + + # Search main RAG (30K chunks from GESN PDFs, orders, etc.) + rag_context = "" + try: + from smeta_railway.ai.embeddings import embed_query as _embed_q + from smeta_railway.ai.chunker import load_rag_index as _load_rag + import faiss as _faiss + + _rag_idx, _rag_chunks = _load_rag("src/smeta_railway/ai/index") + _q = _embed_q(message) + _faiss.normalize_L2(_q) + _scores, _indices = _rag_idx.search(_q, 5) + _hits = [] + for _s, _i in zip(_scores[0], _indices[0]): + if _s > 0.82: + _c = _rag_chunks[_i] + _hits.append(f"[{_c.get('source','?')}] {_c['text'][:400]}") + if _hits: + rag_context = "Найденные фрагменты нормативных документов:\n" + "\n---\n".join(_hits) + except Exception: + pass # Read files from work directory if they exist file_context = _read_work_dir_files(work_dir) @@ -306,6 +319,12 @@ async def stream_claude( user_content = f"{message}\n\n[Файлы в рабочей директории]{file_context}" if resource_context: user_content += f"\n\n[Данные из базы ФСНБ-2022]\n{resource_context}" + if fssc_context: + user_content += f"\n\n[{fssc_context}]" + if winter_context: + user_content += f"\n\n[{winter_context}]" + if rag_context: + user_content += f"\n\n[{rag_context}]" if normative_context: user_content += f"\n\n[{normative_context}]" diff --git a/claude_bridge_sonnet.py b/claude_bridge_sonnet.py index f4bddd4..0819d26 100644 --- a/claude_bridge_sonnet.py +++ b/claude_bridge_sonnet.py @@ -18,7 +18,6 @@ from claude_bridge_glm import ( _build_system_prompt, _load_smeta_data, _search_normative, - _search_resources, _read_work_dir_files, get_work_dir, get_session_id, @@ -95,8 +94,9 @@ def _build_context(message: str, username: str, tab_id: str) -> str: "сварочн", "устройство", "ремонт пути", "всп", "сцб", ] if any(p in message.lower() for p in gesn_patterns): - from claude_bridge_glm import _search_resources - resource_context = _search_resources(message) + from claude_bridge_glm import _resources + from search_engine import _search_resources + resource_context = _search_resources(message, _resources) # Normative RAG normative_context = _search_normative(message) diff --git a/claude_project_instructions.md b/claude_project_instructions.md index 9eaa2c5..16a270d 100644 --- a/claude_project_instructions.md +++ b/claude_project_instructions.md @@ -6,29 +6,29 @@ - Будь вежлив и профессионален ## Кто ты -Ты — профессиональный ИИ-ассистент-сметчик железнодорожного строительства. Пользователь — профессиональный сметчик, НЕ программист. Не используй технический жаргон. Объясняй просто. +Ты — AI-ассистент сметчика по нормативной базе ФСНБ-2022. Все 47 сборников ГЭСН, 181 000+ расценок. Пользователь — профессиональный сметчик, НЕ программист. Не используй технический жаргон. Объясняй просто. ## При вопросе "кто ты?", "что ты умеешь?", "помощь", "help" — ответь ЭТИМ текстом: -Я — **Сметный ИИ-ассистент**. Вот что я умею: +Я — **AI-ассистент сметчика**. Нахожу нужную норму ФСНБ-2022 за секунды — с точной ссылкой на пункт и объяснением логики применения. -**Отвечу на вопросы по нормативке** со ссылкой на документ: +**Нормативная база** — 47 сборников ГЭСН, 181 000+ расценок, 18 приказов Минстроя: - Накладные расходы, сметная прибыль (приказы 812/пр, 774/пр) -- Коэффициенты стеснённых условий (приказ 421/пр) -- Индексы пересчёта (актуальные письма Минстроя) -- Расценки ГЭСН, зимнее удорожание, временные здания +- Коэффициенты условий производства работ (приказ 421/пр с изменениями) +- Расценки ГЭСН любого сборника — поиск по описанию работ +- Зимнее удорожание, временные здания, резерв на непредвиденные + +Каждый ответ — со ссылкой на конкретный пункт документа. **Работа с файлами** — загрузите xlsx, gge или esw: - Прочитаю файл любой сметной программы (ГРАНД-Смета, Строительный эксперт, Smeta.RU) - Покажу структуру, итоги, расценки - Проверю НР/СП по нормативам -- Внесу данные из одного файла в другой -- Создам новый файл +- Создам или изменю файл **Пакетная обработка** (кнопка «Пакетная»): - Загрузите ZIP с локальными сметами + сводный файл -- Я прочитаю структуру, покажу маппинг для проверки -- После подтверждения — обработаю все файлы автоматически +- Проверю и обработаю 100+ смет автоматически Задавайте вопрос или загрузите файл! diff --git a/scripts/deploy.sh b/scripts/deploy.sh new file mode 100644 index 0000000..6f1faaf --- /dev/null +++ b/scripts/deploy.sh @@ -0,0 +1,33 @@ +#!/bin/bash +# Auto-deploy script for smeta-web +# Called by Gitea webhook or manually: bash scripts/deploy.sh + +set -e +cd /home/mcp-user/smeta-web + +echo "[$(date)] Deploy started" + +# Pull latest +git pull origin main 2>&1 || true + +# Install deps if changed +pip3 install -q -r requirements.txt 2>&1 || true + +# Restart service +sudo systemctl restart smeta-web +sleep 3 + +# Verify service is running +if systemctl is-active --quiet smeta-web; then + echo "[$(date)] Service active" +else + echo "[$(date)] ERROR: Service not active!" + exit 1 +fi + +# Quick smoke test (5 questions) +export $(grep SESSION_SECRET .env) +RESULT=$(python3 tests/test_chat_quality.py --quick 2>&1 | grep "Passed:") +echo "[$(date)] Test: $RESULT" + +echo "[$(date)] Deploy complete" diff --git a/scripts/update_data.sh b/scripts/update_data.sh new file mode 100644 index 0000000..72b4ec1 --- /dev/null +++ b/scripts/update_data.sh @@ -0,0 +1,40 @@ +#!/bin/bash +# Quarterly data update: ФССЦ prices, ФСНБ supplements, RAG rebuild +# Cron: 0 6 1 */3 * bash /home/mcp-user/smeta-web/scripts/update_data.sh >> /tmp/data_update.log 2>&1 + +set -e +cd /home/mcp-user/smeta-railway +export PYTHONPATH=src + +echo "[$(date)] === Data update started ===" + +# 1. Update ФССЦ-2022 prices from ФГИС ЦС (all 86 regions) +echo "[$(date)] Updating ФССЦ-2022..." +python3 scripts/fetch_fssc_all_regions.py & +FSSC_PID=$! + +# 2. Try to fetch new ГЭСН norms (if API balance available) +echo "[$(date)] Checking ГЭСН API..." +python3 scripts/fetch_gesn_daily.py + +# 3. Wait for ФССЦ to finish +wait $FSSC_PID +echo "[$(date)] ФССЦ-2022 update complete" +python3 scripts/fetch_fssc_all_regions.py --status + +# 4. Rebuild RAG index +echo "[$(date)] Rebuilding RAG index..." +PYTHONPATH=src python3 -c "from smeta_railway.cli import app; app()" build-rag + +# 5. Verify knowledge base +echo "[$(date)] Verifying..." +PYTHONPATH=src python3 scripts/verify_knowledge_base.py + +# 6. Quick chat test +cd /home/mcp-user/smeta-web +sudo systemctl restart smeta-web +sleep 5 +export $(grep SESSION_SECRET .env) +python3 tests/test_chat_quality.py --quick + +echo "[$(date)] === Data update complete ===" diff --git a/search_engine.py b/search_engine.py new file mode 100644 index 0000000..9fec782 --- /dev/null +++ b/search_engine.py @@ -0,0 +1,213 @@ +"""Search functions for smeta-web. + +Provides text search in ФСНБ-2022 resources, ФССЦ materials (86 regions), +full ГЭСН norms (181K), and winter cost zones. Uses pymorphy2 for normalization. +""" + +import json +import os +import re +from pathlib import Path + +import pymorphy2 + +SMETA_DIR = Path(os.environ.get("SMETA_PROJECT_DIR", os.path.expanduser("~/smeta-railway"))) + +_morph = pymorphy2.MorphAnalyzer() + + +def _normalize(word: str) -> str: + """Normalize Russian word to its base form via pymorphy2.""" + word = re.sub(r'[^\w]', '', word) + if len(word) <= 2 or word.isdigit(): + return word.lower() + return _morph.parse(word.lower())[0].normal_form + + +# === ФССЦ (material prices, 86 regions) === + +_fssc_cache: dict[str, dict] = {} # key → loaded data + +_REGION_ALIASES = { + "москва": "Москва", "московск": "Московская область", + "питер": "Санкт-Петербург", "петербург": "Санкт-Петербург", + "ленинградск": "Ленинградская область", +} + + +def _detect_region(query: str) -> str | None: + """Try to detect region name from query.""" + query_lower = query.lower() + for alias, full in _REGION_ALIASES.items(): + if alias in query_lower: + return full + # Match "для Хабаровского края", "в Якутии", "по Новосибирской области" + m = re.search(r'(?:для|в|по)\s+(\S+(?:\s+(?:област|кра|республик|округ))?)', query_lower) + if m: + return m.group(1) + return None + + +def _load_fssc(region: str | None = None) -> dict | None: + """Load FSSC data. If region given, try to find matching file.""" + fssc_dir = SMETA_DIR / "data" / "fssc_2022" + if not fssc_dir.exists(): + return None + + if region: + region_lower = region.lower() + # Check cache + for key, data in _fssc_cache.items(): + if region_lower in key.lower(): + return data + # Search files + for rf in sorted(fssc_dir.glob("region_*.json")): + fname = rf.name.lower() + if region_lower[:5] in fname: # match by first 5 chars of region + data = json.loads(rf.read_text(encoding="utf-8")) + if data.get("complete"): + _fssc_cache[data.get("region", rf.stem)] = data + return data + + # Default: first complete region + if "__default__" in _fssc_cache: + return _fssc_cache["__default__"] + for rf in sorted(fssc_dir.glob("region_*.json")): + data = json.loads(rf.read_text(encoding="utf-8")) + if data.get("complete"): + _fssc_cache["__default__"] = data + return data + return None + + +def _search_fssc(query: str, top_k: int = 5) -> str: + """Search ФССЦ-2022 material prices. Auto-detects region from query.""" + region = _detect_region(query) + data = _load_fssc(region) + if not data: + return "" + + query_lower = query.lower() + terms = [_normalize(t) for t in query_lower.split() if len(t) > 2] + # Filter out non-material terms + skip = {"область", "край", "республика", "округ", "город", "для", + "какой", "какая", "какое", "сметный", "базисный", "цена"} + terms = [t for t in terms if t not in skip] + results = [] + + for zone_name, zone_data in data.get("zones", {}).items(): + for code, mat in zone_data.get("materials", {}).items(): + name = re.sub(r'[()«»""]', ' ', mat.get("name", "")).lower() + score = sum(1 for t in terms if t in name) + if score >= 2 or (score == 1 and len(terms) <= 2): + results.append((score, code, mat, zone_name)) + + results.sort(reverse=True, key=lambda x: x[0]) + if not results: + return "" + + region_name = data.get("region", "") + lines = [f"Сметные цены на материалы (ФССЦ-2022, {region_name}):"] + for score, code, mat, zone in results[:top_k]: + price = mat.get("price", "?") + unit = mat.get("unit", "?") + idx = mat.get("index", "?") + lines.append(f"- {code}: {mat['name']} [{unit}] цена={price} руб., индекс={idx}") + return "\n".join(lines) + + +# === ГЭСН extra (181K norms) === + +def _search_gesn_extra(query: str, top_k: int = 5) -> str: + """Search in full 181K GESN norms (gesn_extra JSON files).""" + gesn_dir = SMETA_DIR / "data" / "gesn_extra" + if not gesn_dir.exists(): + return "" + + query_lower = query.lower() + terms = [_normalize(t) for t in query_lower.split() if len(t) > 2] + results = [] + + for f in gesn_dir.glob("gesn_*.json"): + data = json.loads(f.read_text(encoding="utf-8")) + for code, info in data.items(): + if not isinstance(info, dict) or "error" in info: + continue + name = info.get("name", "").lower() + score = sum(1 for t in terms if t in name) + if score >= 2 or (score == 1 and len(terms) == 1): + results.append((score, code, info)) + + results.sort(reverse=True, key=lambda x: x[0]) + if not results: + return "" + + lines = ["Расценки из полной базы ГЭСН (181 000+ норм):"] + for score, code, info in results[:top_k]: + name = info.get("name", "") + unit = info.get("unit", "") + lines.append(f"- ГЭСН {code}: {name} [{unit}]") + return "\n".join(lines) + + +# === Winter zones === + +def _search_winter(query: str) -> str: + """Search winter cost zones for a region.""" + try: + from smeta_railway.data.winter_costs import REGION_ZONE_SIMPLE, REGION_ZONES + except ImportError: + return "" + + query_lower = query.lower() + results = [] + + for region, zone in REGION_ZONE_SIMPLE.items(): + if any(_normalize(t) in region.lower() for t in query_lower.split() if len(t) > 2): + results.append((region, zone)) + + if not results: + for region, info in REGION_ZONES.items(): + if any(_normalize(t) in region.lower() for t in query_lower.split() if len(t) > 2): + zone = info.get("zone", "?") + period = info.get("period", "?") + results.append((region, f"{zone} ({period})")) + + if not results: + return "" + + lines = ["Зоны зимнего удорожания (ГСН 81-05-02-2007):"] + for region, zone in results[:5]: + lines.append(f"- {region}: зона {zone}") + return "\n".join(lines) + + +# === Resources (resources.json, 24K norms) === + +def _search_resources(query: str, resources: dict, top_k: int = 5) -> str: + """Search in resources.json using pymorphy2 normalization.""" + if not resources: + return "" + + query_lower = query.lower() + terms = [_normalize(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) diff --git a/static/admin.html b/static/admin.html index 6ce7bf8..98f2d67 100644 --- a/static/admin.html +++ b/static/admin.html @@ -90,6 +90,13 @@ const token = localStorage.getItem('token'); if (!token) window.location.href = '/'; const H = {'Authorization': 'Bearer ' + token}; +// Check token validity — redirect to login on 401 +async function checkAuth() { + const r = await fetch('/api/admin/stats', {headers: H}); + if (r.status === 401) { localStorage.removeItem('token'); window.location.href = '/'; } +} +checkAuth(); + // Navigation function showPage(name) { document.querySelectorAll('.page').forEach(p => p.classList.remove('active')); diff --git a/static/security.html b/static/security.html new file mode 100644 index 0000000..a903823 --- /dev/null +++ b/static/security.html @@ -0,0 +1,127 @@ + + +
+ + +smeta.kazin.ru — AI-ассистент сметчика по нормативной базе ФСНБ-2022
+ +Когда речь заходит об онлайн-сервисах, естественно возникает вопрос: «А не утекут ли мои данные?» Это правильный вопрос. Но прежде чем оценивать риски нового инструмента, стоит посмотреть на то, чем вы уже пользуетесь каждый день.
+ +Каждый сметчик в России работает в Windows, Excel, Outlook, AutoCAD. Всё это — американское программное обеспечение. И у этого факта есть последствия, о которых мало кто задумывается.
+ +В июне 2013 года бывший сотрудник АНБ Эдвард Сноуден передал журналистам документы, доказывающие существование секретной программы PRISM.
+Clarifying Lawful Overseas Use of Data Act — федеральный закон США, подписан 23.03.2018.
+Вывод: каждый компьютер с Windows — это терминал, к которому американские спецслужбы имеют юридически гарантированный и технически доказанный доступ.
+| Программа | Компания | Страна | Доступ к данным |
|---|---|---|---|
| Windows 10/11 | Microsoft | США | ОС имеет root-доступ ко ВСЕМ файлам. Участник PRISM. Обязана по CLOUD Act |
| Microsoft Office | Microsoft | США | Все документы создаются в ПО, подконтрольном АНБ |
| Excel | Microsoft | США | Все сметы, все расчёты, все данные проектов |
| Outlook | Microsoft | США | Вся служебная переписка |
| AutoCAD / Revit | Autodesk | США | Вся проектная документация. Подпадает под CLOUD Act |
| Chrome / Edge | Google / Microsoft | США | Всё что вводится в поиск. Весь трафик |
| Windows Update | Microsoft | США | Может установить любой код без ведома пользователя |
А smeta.kazin.ru — справочник по публичным нормативам Минстроя. Вопрос «какой НР для бетонных работ?» не содержит конфиденциальной информации. Эти данные лежат на сайте minstroyrf.gov.ru бесплатно.
+ +| smeta.kazin.ru | Windows + Office на каждом ПК | |
|---|---|---|
| Что передаётся | Текст вопроса по нормативам | Все файлы, вся переписка, все пароли |
| Куда | Сервер в РФ | Microsoft (США), под PRISM и CLOUD Act |
| Файлы проектов | Не загружаются (справочный режим) | ВСЕ файлы на дисках доступны ОС |
| Доказанный бэкдор | Нет | Да (PRISM, 2007–2013+) |
| Обязательство выдать данные | Нет (сервер в РФ) | Да (CLOUD Act, 2018) |
| Можно отключить | Да (не заходить на сайт) | Нет (без Windows работа невозможна) |
«Я использую справочник по публичным нормативам Минстроя. Файлы проектов не загружаю. При этом каждый рабочий компьютер работает на Windows — ОС, про которую Сноуден доказал прямое сотрудничество с АНБ, а закон CLOUD Act обязывает Microsoft выдать любые данные по запросу. Если организация действительно обеспокоена утечками — начинать нужно с замены Windows на Astra Linux, а не с блокировки справочника по нормативам.»
+