Compare commits
22
Commits
53b4aa3ff5
..
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
60badbf08f | ||
|
|
855e2f2eef | ||
|
|
f763d22263 | ||
|
|
e1b721bfcb | ||
|
|
0da002f69b | ||
|
|
0153cb761b | ||
|
|
7a6c91829a | ||
|
|
3cbf6aa9e3 | ||
|
|
891323da85 | ||
|
|
96dab2d9b2 | ||
|
|
34b90c2b19 | ||
|
|
7c1aea6250 | ||
|
|
4c282f9653 | ||
|
|
15c864be22 | ||
|
|
1a7c179730 | ||
|
|
a9f3eabf27 | ||
|
|
811df5c103 | ||
|
|
ff207ab0fd | ||
|
|
3543314cdf | ||
|
|
e2635df90b | ||
|
|
bfd3197efd | ||
|
|
9f2e355298 |
@@ -0,0 +1,132 @@
|
||||
# TODO — переезд задач из отдельных страниц в чат
|
||||
|
||||
Цель: чат становится единым интерфейсом. Гибридный роутинг:
|
||||
- **DeepSeek** (через ZAI/`AI_BACKEND=glm`) — для нормативных вопросов и Q&A
|
||||
без файлов (95% запросов из логов: «какой НР», «приказ 421», расценки).
|
||||
Дёшево, быстро.
|
||||
- **Claude CLI** (через **подписку Pro/Max**, не Anthropic API) — для
|
||||
агентских задач (открыть/проанализировать/заполнить/сгенерировать
|
||||
xlsx, ssr, генерация смет, batch-обработка). Использует уже
|
||||
существующий `claude_bridge.py` (Docker + `claude -p
|
||||
--output-format stream-json`), модернизированный под domain MCP.
|
||||
|
||||
**Anthropic API не используем** — слишком дорого для MVP. Подписки
|
||||
достаточно. При росте нагрузки — добавляем 2-ю подписку или
|
||||
рейт-лимит per-user.
|
||||
|
||||
Источник анализа: 1104 user-сообщения из прод-БД + инвентаризация
|
||||
`static/*.html` и endpoints.
|
||||
|
||||
## Этап 1 — Domain MCP server (`smeta_mcp.py`)
|
||||
|
||||
Статус: ✅ done (skeleton, без интеграции с CLI)
|
||||
|
||||
Один MCP-сервер, переиспользуемый и DeepSeek-tools веткой, и
|
||||
Claude-CLI веткой. stdio-транспорт (стандартный для MCP).
|
||||
|
||||
- [x] Skeleton `smeta_mcp.py`: stdio MCP server (без зависимостей —
|
||||
newline-delimited JSON-RPC 2.0; на pypi `mcp` мигрировать при
|
||||
необходимости)
|
||||
- [x] Tools (обёртки над уже существующими функциями):
|
||||
- [x] `read_xlsx_sheet(filename, sheet?, max_rows=50)` ← `tools_glm.py`
|
||||
- [x] `find_in_normative(query, top_k=3)` ← `claude_bridge_glm._search_normative`
|
||||
- [x] `list_files()` ← `list_user_files`
|
||||
- [x] `extract_complaints_pairs(filename)` ← `complaints.extract_pairs`
|
||||
- [x] `apply_pukts_to_registry(filename)` ← `complaints.apply_to_registry`
|
||||
- [x] Контекст user/tab — через env vars (`SMETA_USER`, `SMETA_TAB`)
|
||||
- [x] Standalone-тест: tools/list и tools/call через stdio JSON-RPC
|
||||
|
||||
## Этап 2 — Реанимация `claude_bridge.py` (Claude CLI + MCP)
|
||||
|
||||
Статус: ✅ done (подключение MCP работает, E2E прошёл; оптимизации
|
||||
оставлены на отдельные итерации)
|
||||
|
||||
- [x] `sandbox/mcp_config.json` — MCP-конфиг для claude CLI
|
||||
- [x] Mount `smeta_mcp.py` + `complaints.py` + `mcp_config.json` в `/app/`
|
||||
- [x] `--mcp-config /app/mcp_config.json` к claude args
|
||||
- [x] `mcp__smeta__*` в `--allowedTools`
|
||||
- [x] env vars в Docker: SMETA_USER, SMETA_TAB, SMETA_WORK_DIR=/data
|
||||
- [x] Бамп ресурсов: `--memory=2g`, `--cpus=2`
|
||||
- [x] `smeta_mcp.py` self-contained
|
||||
- [x] `find_in_normative` fault-tolerant
|
||||
- [x] subprocess `limit=10*1024*1024` — отдельные stream-json события
|
||||
от MCP бывают >64K, default readline валился
|
||||
- [x] **E2E test: «прочитай 15.СМ через mcp__smeta__read_xlsx_sheet,
|
||||
без Bash» → Claude вызвал именно наш MCP-tool и вернул реальное
|
||||
`rows_with_data_total: 250`**
|
||||
|
||||
Оптимизации (отложены — не критичны для MVP):
|
||||
- [ ] Убрать глобальный `_semaphore` → per-(user,tab) lock
|
||||
- [ ] Per-user rate limit: 5 агентских запросов в час
|
||||
- [ ] E2E на apply_pukts_to_registry с возвратом download URL в чат
|
||||
|
||||
## Этап 3 — Гибридный роутер `AI_BACKEND=hybrid`
|
||||
|
||||
Статус: ✅ done (на dev включён, оба сценария отработали)
|
||||
|
||||
- [x] Новый ветка `AI_BACKEND=hybrid` в `main.py`
|
||||
- [x] Логика: keyword-эвристика (расширены агентские keywords под
|
||||
реальные кейсы из логов: «столбец D», «лист 15», «заполни пункт»)
|
||||
- [x] DeepSeek (`_stream_glm`) — для нормативки и default
|
||||
- [x] Claude CLI через подписку + MCP (`_stream_claude`) — для агента
|
||||
- [x] E2E на dev (8103, AI_BACKEND=hybrid):
|
||||
- [x] «Какой НР для ж/д работ?» → DeepSeek 8 сек, ответ
|
||||
«п.22: 109% от ФОТ, Приказ 812»
|
||||
- [x] «Используй mcp__smeta__read_xlsx_sheet…» → tool stream
|
||||
фиксирует `mcp__smeta__read_xlsx_sheet` + `mcp__smeta__list_files`
|
||||
(агент пробует вызвать наш MCP — роутер сработал)
|
||||
|
||||
## Этап 4 — UI tool-cards (общий протокол)
|
||||
|
||||
Статус: ⬜ planned
|
||||
|
||||
- [ ] SSE-протокол: новые events `tool_call.start`, `tool_call.delta`,
|
||||
`tool_call.result`, `step.complete`, `usage`
|
||||
- [ ] В `chat.html`: рендер карточек (pending/running/success/error),
|
||||
раскрытие диффов, ссылки на скачивание
|
||||
- [ ] Approval-кнопки для опасных операций (apply, write_cell)
|
||||
- [ ] Прогресс-индикатор для batch (вместо отдельной страницы)
|
||||
|
||||
## Этап 5 — Депрекация отдельных страниц
|
||||
|
||||
Статус: ⬜ planned
|
||||
|
||||
- [ ] `/wizard` → редирект на чат с подсказкой
|
||||
- [ ] `/ssr` → tool `generate_ssr` в MCP, страница опционально
|
||||
- [ ] `/generate`, `/check`, `/reference` → MCP tools
|
||||
- [ ] Удалить `/batch.html`, `/batch2.html` (legacy)
|
||||
- [ ] `/admin`, `/register`, `/security` — оставить (не задачи)
|
||||
|
||||
## Связанные правки, которые уже сделаны (не повторять)
|
||||
|
||||
- ✅ DeepSeek V4 как основной backend (`AI_BACKEND=glm`)
|
||||
- ✅ Расширение xlsm/xlsb/ods, стрим-чтение xlsm с per-sheet budget
|
||||
- ✅ Гибкий system prompt: модель не отказывает в анализе файлов;
|
||||
запрет на выдумывание содержимого по имени
|
||||
- ✅ Чтение листинга zip-архивов (cp866 для Windows-имён)
|
||||
- ✅ Endpoints `/api/extract_complaints` + `/api/apply_matches`
|
||||
(учтены: many-to-many, дубли строк, скрытые строки, .xlsx как формат)
|
||||
- ✅ Dev-сервер на 8103 (`smeta-web-dev.service`, ветка `dev`)
|
||||
- ✅ Fallback `crypto.randomUUID` для HTTP origin
|
||||
- ✅ Лимит загрузки 50 → 100 МБ
|
||||
- ✅ Админка: раздел «Файлы» — просмотр и скачивание файлов любого
|
||||
юзера (включая env-only `smeta` и удалённых аккаунтов)
|
||||
|
||||
## Решения / отложенные опции
|
||||
|
||||
- ❌ Anthropic API (Claude Agent SDK через `ANTHROPIC_API_KEY`) — отложено,
|
||||
слишком дорого для MVP. Возможно в будущем для production-scale.
|
||||
- 🟡 Docker-VM per session — сейчас Docker per-request с per-(user,tab)
|
||||
`cwd`. При росте до 50+ одновременных юзеров — мигрировать на
|
||||
long-lived containers с queue.
|
||||
- 🟡 Tool-calling на стороне DeepSeek (function calling в OpenAI-формате) —
|
||||
опционально, для случая когда юзер просит лёгкий tool без эскалации
|
||||
до Claude. Не приоритет.
|
||||
|
||||
## Ссылки
|
||||
|
||||
- Прод: `https://infosmeta.ru` → `127.0.0.1:8101` → `~/smeta-web/` (`main`)
|
||||
- Dev: `http://192.168.87.76:8103` → `~/smeta-web-dev/` (`dev`)
|
||||
- Repo: `https://git.kazin.ru/anor/smeta-web.git`
|
||||
- claude-agent-sdk docs: https://code.claude.com/docs/en/agent-sdk/overview
|
||||
- MCP custom tools: https://code.claude.com/docs/en/agent-sdk/custom-tools
|
||||
+43
-6
@@ -139,14 +139,31 @@ async def stream_claude(
|
||||
instructions = APP_DIR / "claude_project_instructions.md"
|
||||
|
||||
# Build claude args
|
||||
smeta_mcp_path = APP_DIR / "smeta_mcp.py"
|
||||
smeta_complaints_path = APP_DIR / "complaints.py"
|
||||
smeta_gge_tools_path = APP_DIR / "gge_tools.py"
|
||||
smeta_mcp_config = APP_DIR / "sandbox" / "mcp_config.json"
|
||||
mcp_available = (smeta_mcp_path.exists() and smeta_complaints_path.exists()
|
||||
and smeta_gge_tools_path.exists()
|
||||
and smeta_mcp_config.exists())
|
||||
|
||||
claude_args = [
|
||||
"-p", message,
|
||||
"--output-format", "stream-json",
|
||||
"--verbose",
|
||||
"--allowedTools", "Bash,Read,Write,Edit,Glob,Grep",
|
||||
"--allowedTools",
|
||||
("Bash,Read,Write,Edit,Glob,Grep,"
|
||||
"mcp__smeta__read_xlsx_sheet,"
|
||||
"mcp__smeta__list_files,"
|
||||
"mcp__smeta__extract_complaints_pairs,"
|
||||
"mcp__smeta__apply_pukts_to_registry,"
|
||||
"mcp__smeta__parse_gge_archive,"
|
||||
"mcp__smeta__parse_gge_file,"
|
||||
"mcp__smeta__update_xlsx_cells"),
|
||||
]
|
||||
if mcp_available:
|
||||
claude_args.extend(["--mcp-config", "/app/mcp_config.json"])
|
||||
if instructions.exists():
|
||||
# Mount instructions file into container
|
||||
claude_args.extend([
|
||||
"--append-system-prompt-file", "/instructions.md"
|
||||
])
|
||||
@@ -156,9 +173,9 @@ async def stream_claude(
|
||||
# Docker command
|
||||
cmd = [
|
||||
"docker", "run", "--rm",
|
||||
# Resource limits
|
||||
"--memory=512m",
|
||||
"--cpus=1",
|
||||
# Resource limits — bumped for xlsm parsing
|
||||
"--memory=2g",
|
||||
"--cpus=2",
|
||||
"--network=host", # access xray on host
|
||||
# Mount work directory as /data
|
||||
"-v", f"{work_dir.resolve()}:/data",
|
||||
@@ -167,8 +184,14 @@ async def stream_claude(
|
||||
"-v", f"{os.path.expanduser('~')}/.claude.json:/home/worker/.claude.json",
|
||||
# Mount smeta-railway project (read-only)
|
||||
"-v", f"{SMETA_PROJECT_DIR}:/smeta:ro",
|
||||
# Mount instructions
|
||||
]
|
||||
if mcp_available:
|
||||
cmd.extend([
|
||||
"-v", f"{smeta_mcp_path.resolve()}:/app/smeta_mcp.py:ro",
|
||||
"-v", f"{smeta_complaints_path.resolve()}:/app/complaints.py:ro",
|
||||
"-v", f"{smeta_gge_tools_path.resolve()}:/app/gge_tools.py:ro",
|
||||
"-v", f"{smeta_mcp_config.resolve()}:/app/mcp_config.json:ro",
|
||||
])
|
||||
if instructions.exists():
|
||||
cmd.extend(["-v", f"{instructions.resolve()}:/instructions.md:ro"])
|
||||
|
||||
@@ -177,6 +200,16 @@ async def stream_claude(
|
||||
"-e", f"HTTPS_PROXY=http://{DOCKER_HOST_GW}:{XRAY_PORT}",
|
||||
"-e", f"HTTP_PROXY=http://{DOCKER_HOST_GW}:{XRAY_PORT}",
|
||||
"-e", "HOME=/home/worker",
|
||||
])
|
||||
if mcp_available:
|
||||
# MCP видит файлы текущей вкладки прямо по /data — этот
|
||||
# путь смонтирован выше как work_dir пользователя
|
||||
cmd.extend([
|
||||
"-e", f"SMETA_USER={username}",
|
||||
"-e", f"SMETA_TAB={tab_id}",
|
||||
"-e", "SMETA_WORK_DIR=/data",
|
||||
])
|
||||
cmd.extend([
|
||||
# Working directory
|
||||
"-w", "/data",
|
||||
# Image + claude args
|
||||
@@ -184,10 +217,14 @@ async def stream_claude(
|
||||
])
|
||||
cmd.extend(claude_args)
|
||||
|
||||
# limit=10MB — отдельные stream-json события (особенно tool_result
|
||||
# от MCP с большим xlsx-листом) превышают default 64K и валят
|
||||
# readline() с LimitOverrunError
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
*cmd,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
limit=10 * 1024 * 1024,
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
@@ -215,7 +215,7 @@ def _read_work_dir_files(work_dir: Path, max_chars: int = 150000) -> str:
|
||||
truncated = False
|
||||
for r_idx, row in enumerate(ws.iter_rows(), 1):
|
||||
vals = [
|
||||
f"{c.column_letter}{r_idx}={str(c.value)[:150]}"
|
||||
f"{c.column_letter}{r_idx}={str(c.value)[:300]}"
|
||||
for c in row
|
||||
if c.value is not None and str(c.value).strip()
|
||||
]
|
||||
|
||||
@@ -458,13 +458,30 @@ for row in sheet.findall('.//s:row', ns):
|
||||
- ВСЕГДА показывай результат: первые строки, итоги
|
||||
- После создания файла — скажи что файл готов и можно скачать
|
||||
|
||||
## ⚡ Алгоритм работы со сложными задачами с файлами
|
||||
|
||||
При любой задаче на ОБРАБОТКУ файлов пользователя (заполнить, проанализировать, преобразовать, агрегировать) — **обязательно** соблюдай этот цикл:
|
||||
|
||||
1. **Понимание** — сформулируй СВОИМИ СЛОВАМИ, что понял из задачи: какой файл-источник, какая операция, какой результат, по каким правилам.
|
||||
2. **Уточнения** — если есть НЕОДНОЗНАЧНОСТИ — задай вопросы ПЕРЕД выполнением. Типичные неоднозначности: что считать триггером? откуда брать значение? куда писать (колонка, лист)? как обрабатывать дубли? перезаписать или создать новый файл?
|
||||
3. **Подтверждение** — дождись явного «да, делай» от пользователя. Не приступай по молчаливому согласию.
|
||||
4. **Выполнение** — реализуй задачу. Если по дороге появилось новое уточнение — спроси, не предполагай.
|
||||
5. **Проверка** — после выполнения покажи результат на эталонном примере (если он есть в задаче) и попроси пользователя подтвердить.
|
||||
|
||||
Этот цикл ВАЖНЕЕ скорости. Лучше задать 5 уточнений и сделать правильно с первого раза, чем сделать «как понял» и переделывать. Уточнения — это **признак понимания**, а не неуверенности.
|
||||
|
||||
## Правила поведения
|
||||
1. **Уточняй** — если запрос неясен, задай вопрос ПЕРЕД выполнением
|
||||
1. **Уточняй** — следуй алгоритму выше
|
||||
2. **Превью** — показывай предпросмотр результата
|
||||
3. **Подтверждение** — для удаления/перезаписи спрашивай
|
||||
4. **Ошибки** — объясни простым языком, предложи альтернативу
|
||||
5. **Не выполняй** сетевых запросов, не устанавливай пакеты
|
||||
|
||||
## Tools для работы со сметными архивами .gge
|
||||
- `mcp__smeta__parse_gge_archive(filename)` — распаковать .zip с .gge и проиндексировать. Для каждой сметы получишь has_excavation (есть «разработка грунта»), has_transport_summary, total_rub, schema_kind. Полный индекс с позициями сохраняется в `<stem>_index.json` — читай его через Bash python для глубокой аналитики (фильтры по Cost.Name, агрегаты).
|
||||
- `mcp__smeta__parse_gge_file(filename)` — распарсить одну смету: получишь все позиции (Cost+Transport), totals, флаги.
|
||||
- `mcp__smeta__update_xlsx_cells(filename, sheet, updates)` — массовая запись ячеек. updates: `[{row, col, value}, ...]`. Создаёт `<stem>_updated.xlsx`.
|
||||
|
||||
## Автоматические приёмы (применяй без запроса)
|
||||
- Перед работой с файлом — покажи структуру
|
||||
- Грязные данные — предупреди
|
||||
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
"""Deterministic extraction of (пункт замечания → код сметы) pairs from xlsm.
|
||||
|
||||
Used by /api/extract_complaints and /api/apply_matches. Pure regex + openpyxl,
|
||||
no LLM — for tasks where the input format is structural (smeta registry on
|
||||
sheet "РеестрСМ" + complaints log on sheet "15.СМ"), determinism beats AI.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import openpyxl
|
||||
|
||||
# Sheet names — fixed by user's xlsm convention
|
||||
SHEET_COMPLAINTS = "15.СМ"
|
||||
SHEET_REGISTRY_CANDIDATES = ("Реестр СМ", "РеестрСМ")
|
||||
COMPLAINTS_TEXT_COL = 4 # column D
|
||||
REGISTRY_CODE_COL = 3 # column C
|
||||
REGISTRY_TARGET_COL = 4 # column D — пункт замечания ГГЭ
|
||||
|
||||
_PUNKT_RE = re.compile(r"^\s*(\d+[.,]\d+)\s*\(")
|
||||
_CODE_RE = re.compile(r"(?:ЛСР|ОСР|ЛС|ССР|ССРСС)-\d+(?:-\d+)+")
|
||||
|
||||
|
||||
def _open_registry_sheet(wb):
|
||||
for name in SHEET_REGISTRY_CANDIDATES:
|
||||
if name in wb.sheetnames:
|
||||
return wb[name]
|
||||
raise ValueError(
|
||||
f"Не найден лист реестра. Ожидался один из: {SHEET_REGISTRY_CANDIDATES}"
|
||||
)
|
||||
|
||||
|
||||
def extract_pairs(path: str | Path) -> dict:
|
||||
"""Read complaints sheet, return list of (пункт, смета) pairs + stats.
|
||||
|
||||
Returns:
|
||||
{
|
||||
"stats": {"total_complaints": N, "with_code": M, "without_code": K, "total_pairs": P},
|
||||
"pairs": [{"row": 11, "пункт": "80.60", "смета": "ЛСР-..."}, ...],
|
||||
"no_code_rows": [{"row": 23, "пункт": "80.5"}, ...], # для прозрачности
|
||||
}
|
||||
"""
|
||||
wb = openpyxl.load_workbook(str(path), data_only=True)
|
||||
if SHEET_COMPLAINTS not in wb.sheetnames:
|
||||
raise ValueError(f"Не найден лист «{SHEET_COMPLAINTS}»")
|
||||
ws = wb[SHEET_COMPLAINTS]
|
||||
|
||||
pairs = []
|
||||
no_code = []
|
||||
total = 0
|
||||
with_code = 0
|
||||
empty_streak = 0
|
||||
for r_idx, row in enumerate(ws.iter_rows(values_only=True), 1):
|
||||
# Header rows have no D-text complaint; first complaints typically start at R11
|
||||
if r_idx < 11:
|
||||
continue
|
||||
d = row[COMPLAINTS_TEXT_COL - 1] if len(row) >= COMPLAINTS_TEXT_COL else None
|
||||
if not d or not str(d).strip():
|
||||
empty_streak += 1
|
||||
if empty_streak >= 30:
|
||||
break
|
||||
continue
|
||||
empty_streak = 0
|
||||
text = str(d)
|
||||
m = _PUNKT_RE.match(text)
|
||||
if not m:
|
||||
# Not a complaint line (could be a header/footer mid-table) — skip
|
||||
continue
|
||||
total += 1
|
||||
punkt = m.group(1).replace(",", ".")
|
||||
codes = _CODE_RE.findall(text)
|
||||
# dedupe codes within one complaint, keep order
|
||||
seen = set()
|
||||
unique_codes = []
|
||||
for c in codes:
|
||||
if c not in seen:
|
||||
seen.add(c)
|
||||
unique_codes.append(c)
|
||||
if not unique_codes:
|
||||
no_code.append({"row": r_idx, "пункт": punkt})
|
||||
continue
|
||||
with_code += 1
|
||||
for c in unique_codes:
|
||||
pairs.append({"row": r_idx, "пункт": punkt, "смета": c})
|
||||
|
||||
return {
|
||||
"stats": {
|
||||
"total_complaints": total,
|
||||
"with_code": with_code,
|
||||
"without_code": len(no_code),
|
||||
"total_pairs": len(pairs),
|
||||
},
|
||||
"pairs": pairs,
|
||||
"no_code_rows": no_code,
|
||||
}
|
||||
|
||||
|
||||
def apply_to_registry(path: str | Path, out_path: str | Path) -> dict:
|
||||
"""Extract pairs, then for each unique смета write `, `-joined sorted пункты
|
||||
into column D of every РеестрСМ row whose column C matches.
|
||||
|
||||
Saves modified workbook to `out_path`. Returns counts (cells_filled, smety_with_punkty).
|
||||
"""
|
||||
extracted = extract_pairs(path)
|
||||
pairs = extracted["pairs"]
|
||||
|
||||
# group by смета → set of пункты
|
||||
by_smeta: dict[str, set[str]] = {}
|
||||
for p in pairs:
|
||||
by_smeta.setdefault(p["смета"], set()).add(p["пункт"])
|
||||
|
||||
# Sort пункты by numeric value: 80.5 < 80.60 < 80.115
|
||||
def _punkt_key(s: str) -> tuple[float, str]:
|
||||
try:
|
||||
return (float(s), s)
|
||||
except ValueError:
|
||||
return (1e9, s)
|
||||
|
||||
by_smeta_str = {
|
||||
s: ", ".join(sorted(punkty, key=_punkt_key))
|
||||
for s, punkty in by_smeta.items()
|
||||
}
|
||||
|
||||
wb = openpyxl.load_workbook(str(path))
|
||||
ws = _open_registry_sheet(wb)
|
||||
|
||||
# Группируем строки реестра по коду сметы, разделяя видимые и скрытые.
|
||||
# В этом файле скрыто 2500 строк из 2978 (архив), и многие сметы из
|
||||
# замечаний есть ТОЛЬКО в скрытых. Поэтому стратегия:
|
||||
# 1) если у сметы есть видимая строка — пишем в первую видимую
|
||||
# 2) иначе — пишем в первую скрытую (увидится после unhide)
|
||||
visible_rows: dict[str, list[int]] = {}
|
||||
hidden_rows: dict[str, list[int]] = {}
|
||||
for r_idx in range(2, ws.max_row + 1):
|
||||
code = ws.cell(row=r_idx, column=REGISTRY_CODE_COL).value
|
||||
if not code:
|
||||
continue
|
||||
code = str(code).strip()
|
||||
rd = ws.row_dimensions.get(r_idx)
|
||||
bucket = hidden_rows if (rd is not None and rd.hidden) else visible_rows
|
||||
bucket.setdefault(code, []).append(r_idx)
|
||||
|
||||
cells_filled = 0
|
||||
filled_visible = 0
|
||||
filled_hidden = 0
|
||||
smety_matched: set[str] = set()
|
||||
for code, punkty in by_smeta_str.items():
|
||||
if code in visible_rows:
|
||||
target_row = visible_rows[code][0]
|
||||
filled_visible += 1
|
||||
elif code in hidden_rows:
|
||||
target_row = hidden_rows[code][0]
|
||||
filled_hidden += 1
|
||||
else:
|
||||
continue
|
||||
ws.cell(row=target_row, column=REGISTRY_TARGET_COL, value=punkty)
|
||||
cells_filled += 1
|
||||
smety_matched.add(code)
|
||||
|
||||
wb.save(str(out_path))
|
||||
return {
|
||||
"stats": extracted["stats"],
|
||||
"cells_filled": cells_filled,
|
||||
"filled_in_visible_rows": filled_visible,
|
||||
"filled_in_hidden_rows": filled_hidden,
|
||||
"smety_with_punkty": len(smety_matched),
|
||||
"smety_total_in_pairs": len(by_smeta_str),
|
||||
"smety_not_found_in_registry": sorted(set(by_smeta_str) - smety_matched),
|
||||
}
|
||||
+267
@@ -0,0 +1,267 @@
|
||||
"""gge_tools — работа с архивами .gge (XML смет ГГЭ) и xlsx-реестрами.
|
||||
|
||||
Универсальный, без привязки к конкретной задаче (ИГИ/ТС). Чат-агент
|
||||
сам комбинирует tools для нужного сценария.
|
||||
|
||||
Зависимости: openpyxl + stdlib (zipfile, xml.etree, json). Без plotly,
|
||||
sentence-transformers и т.п. — работает в sandbox-контейнере.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import zipfile
|
||||
import xml.etree.ElementTree as ET
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _decode_zip_name(info: zipfile.ZipInfo) -> str:
|
||||
"""Python 3 zipfile авто-декодирует cp437 если флаг UTF-8 (0x800) не задан.
|
||||
Реальные байты могут быть в UTF-8 (macOS `zip`) или cp866 (Windows-архиватор).
|
||||
Пробуем оба, берём результат без replacement chars."""
|
||||
if info.flag_bits & 0x800:
|
||||
return info.filename
|
||||
try:
|
||||
raw = info.filename.encode('cp437')
|
||||
except UnicodeEncodeError:
|
||||
return info.filename
|
||||
for codec in ('utf-8', 'cp866'):
|
||||
try:
|
||||
decoded = raw.decode(codec)
|
||||
if '�' not in decoded:
|
||||
return decoded
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
return info.filename
|
||||
|
||||
|
||||
def extract_archive(zip_path: Path, target_dir: Path) -> dict:
|
||||
"""Распаковать zip с .gge файлами в target_dir. Сохраняет древовидную
|
||||
структуру внутри архива. Корректно декодирует cp866-имена.
|
||||
|
||||
Возвращает: {target: <abs path>, total_files: N, gge_files: M, skipped: K}
|
||||
"""
|
||||
import os
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
target_resolved = target_dir.resolve()
|
||||
total = gge = skipped = 0
|
||||
with zipfile.ZipFile(zip_path) as z:
|
||||
for info in z.infolist():
|
||||
if info.is_dir():
|
||||
continue
|
||||
total += 1
|
||||
name = _decode_zip_name(info).replace('\\', '/')
|
||||
# path traversal guard
|
||||
out = (target_dir / name).resolve()
|
||||
try:
|
||||
out.relative_to(target_resolved)
|
||||
except ValueError:
|
||||
skipped += 1
|
||||
continue
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
with z.open(info) as src, open(out, 'wb') as dst:
|
||||
while chunk := src.read(64 * 1024):
|
||||
dst.write(chunk)
|
||||
if name.lower().endswith('.gge'):
|
||||
gge += 1
|
||||
except Exception:
|
||||
skipped += 1
|
||||
return {
|
||||
'target': str(target_dir),
|
||||
'total_files': total,
|
||||
'gge_files': gge,
|
||||
'skipped': skipped,
|
||||
}
|
||||
|
||||
|
||||
def parse_gge_file(path: Path) -> dict:
|
||||
"""Извлечь данные одной сметы из .gge XML.
|
||||
|
||||
Возвращает: code, name, schema_kind ('local' | 'object' | 'unknown'),
|
||||
has_excavation, has_transport_summary, totals (всё что есть в
|
||||
EstimatePrice/Summary), positions (список dict с name/code/quantity/
|
||||
unit/price_total из <Cost>; для перевозочных позиций <Transport>
|
||||
тоже включаем).
|
||||
"""
|
||||
try:
|
||||
tree = ET.parse(str(path))
|
||||
except (ET.ParseError, OSError) as e:
|
||||
return {'error': f'{type(e).__name__}: {e}', 'path': str(path)}
|
||||
root = tree.getroot()
|
||||
|
||||
schema_loc = root.attrib.get(
|
||||
'{http://www.w3.org/2001/XMLSchema-instance}noNamespaceSchemaLocation', '')
|
||||
if 'LocalEstimate' in schema_loc:
|
||||
schema_kind = 'local'
|
||||
elif 'ObjectEstimate' in schema_loc:
|
||||
schema_kind = 'object'
|
||||
else:
|
||||
schema_kind = 'unknown'
|
||||
|
||||
code = (root.findtext('.//Estimate/Num') or '').strip()
|
||||
name = (root.findtext('.//Estimate/Name') or '').strip()
|
||||
|
||||
# Totals: EstimatePrice/Summary
|
||||
totals: dict[str, float] = {}
|
||||
summary = root.find('.//EstimatePrice/Summary')
|
||||
if summary is not None:
|
||||
for child in summary:
|
||||
if len(list(child)) > 0:
|
||||
# Materials/Total etc.
|
||||
for sub in child:
|
||||
if sub.text:
|
||||
try:
|
||||
totals[f'{child.tag}.{sub.tag}'] = float(sub.text.strip())
|
||||
except ValueError:
|
||||
pass
|
||||
elif child.text:
|
||||
try:
|
||||
totals[child.tag] = float(child.text.strip())
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# Positions: Item/Cost (work) + Item/Transport (carrier line)
|
||||
positions: list[dict] = []
|
||||
has_excavation = False
|
||||
for it in root.iter('Item'):
|
||||
for kind_tag in ('Cost', 'Transport'):
|
||||
node = it.find(kind_tag)
|
||||
if node is None:
|
||||
continue
|
||||
pname = (node.findtext('Name') or '').strip()
|
||||
if not pname:
|
||||
continue
|
||||
pcode = (node.findtext('Code') or '').strip()
|
||||
qty = node.findtext('Quantity') or ''
|
||||
unit = (node.findtext('Unit') or '').strip()
|
||||
ptcur = node.findtext('PriceTotalCur') or ''
|
||||
direct = node.findtext('.//Totals/Current/Direct') or ''
|
||||
try: qty_f = float(qty) if qty else 0.0
|
||||
except ValueError: qty_f = 0.0
|
||||
try: pt_f = float(ptcur) if ptcur else 0.0
|
||||
except ValueError: pt_f = 0.0
|
||||
try: dir_f = float(direct) if direct else 0.0
|
||||
except ValueError: dir_f = 0.0
|
||||
positions.append({
|
||||
'kind': kind_tag.lower(), # 'cost' | 'transport'
|
||||
'name': pname,
|
||||
'code': pcode,
|
||||
'quantity': qty_f,
|
||||
'unit': unit,
|
||||
'price_total_cur': pt_f,
|
||||
'direct': dir_f,
|
||||
})
|
||||
if 'разработка грунта' in pname.lower():
|
||||
has_excavation = True
|
||||
|
||||
has_transport_summary = (totals.get('Transport', 0.0) > 0)
|
||||
|
||||
return {
|
||||
'path': str(path),
|
||||
'code': code,
|
||||
'name': name,
|
||||
'schema_kind': schema_kind,
|
||||
'has_excavation': has_excavation,
|
||||
'has_transport_summary': has_transport_summary,
|
||||
'totals': totals,
|
||||
'positions': positions,
|
||||
}
|
||||
|
||||
|
||||
def index_gge_directory(dir_path: Path, save_index_to: Path | None = None) -> dict:
|
||||
"""Пройти все .gge в dir_path рекурсивно, распарсить.
|
||||
|
||||
Returns: {by_code: {code: {has_excavation, has_transport_summary,
|
||||
name, total_rub, schema_kind, path}}, summary: {...}, parse_errors: N}.
|
||||
|
||||
Если save_index_to задан — пишет полный индекс (с positions) в JSON.
|
||||
Возврат компактнее (без positions), чтобы влез в MCP-ответ.
|
||||
"""
|
||||
files = sorted(p for p in dir_path.rglob('*.gge'))
|
||||
by_code: dict[str, dict] = {}
|
||||
full_index: dict[str, dict] = {}
|
||||
parse_errors = 0
|
||||
schemas: dict[str, int] = {}
|
||||
excav = transp = 0
|
||||
rub_sum = 0.0
|
||||
for f in files:
|
||||
data = parse_gge_file(f)
|
||||
if 'error' in data:
|
||||
parse_errors += 1
|
||||
continue
|
||||
code = data['code']
|
||||
if not code:
|
||||
continue
|
||||
# Сводный (компактный) вид без positions для MCP-ответа.
|
||||
compact = {
|
||||
'name': data['name'],
|
||||
'schema_kind': data['schema_kind'],
|
||||
'has_excavation': data['has_excavation'],
|
||||
'has_transport_summary': data['has_transport_summary'],
|
||||
'total_rub': data['totals'].get('Total') or data['totals'].get('Price') or 0.0,
|
||||
'transport_rub': data['totals'].get('Transport', 0.0),
|
||||
'path': data['path'],
|
||||
}
|
||||
prev = by_code.get(code)
|
||||
if prev is None or compact['total_rub'] > prev['total_rub']:
|
||||
by_code[code] = compact
|
||||
full_index[code] = data
|
||||
schemas[data['schema_kind']] = schemas.get(data['schema_kind'], 0) + 1
|
||||
if data['has_excavation']:
|
||||
excav += 1
|
||||
if data['has_transport_summary']:
|
||||
transp += 1
|
||||
rub_sum += compact['total_rub']
|
||||
|
||||
summary = {
|
||||
'files_total': len(files),
|
||||
'parse_errors': parse_errors,
|
||||
'unique_codes': len(by_code),
|
||||
'schemas': schemas,
|
||||
'with_excavation': excav,
|
||||
'with_transport_summary': transp,
|
||||
'sum_total_rub': rub_sum,
|
||||
}
|
||||
if save_index_to is not None:
|
||||
save_index_to.write_text(
|
||||
json.dumps({'by_code': full_index, 'summary': summary},
|
||||
ensure_ascii=False),
|
||||
encoding='utf-8',
|
||||
)
|
||||
return {'by_code': by_code, 'summary': summary}
|
||||
|
||||
|
||||
def update_xlsx_cells(src_path: Path, out_path: Path, sheet: str,
|
||||
updates: list[dict]) -> dict:
|
||||
"""Записать список ячеек в xlsx.
|
||||
|
||||
updates: [{"row": 5, "col": "E" | 5, "value": "ИГИ"}, ...]
|
||||
Сохраняет копию в out_path. Не трогает остальной контент книги.
|
||||
"""
|
||||
import openpyxl
|
||||
wb = openpyxl.load_workbook(str(src_path))
|
||||
if sheet not in wb.sheetnames:
|
||||
return {'error': f'Лист «{sheet}» не найден',
|
||||
'available_sheets': wb.sheetnames}
|
||||
ws = wb[sheet]
|
||||
written = 0
|
||||
skipped = 0
|
||||
for u in updates:
|
||||
try:
|
||||
row = int(u['row'])
|
||||
col = u['col']
|
||||
if isinstance(col, str):
|
||||
col_idx = openpyxl.utils.column_index_from_string(col)
|
||||
else:
|
||||
col_idx = int(col)
|
||||
ws.cell(row, col_idx).value = u.get('value')
|
||||
written += 1
|
||||
except (KeyError, ValueError, TypeError):
|
||||
skipped += 1
|
||||
wb.save(str(out_path))
|
||||
return {
|
||||
'output_path': str(out_path),
|
||||
'sheet': sheet,
|
||||
'cells_written': written,
|
||||
'cells_skipped': skipped,
|
||||
}
|
||||
@@ -21,6 +21,62 @@ if AI_BACKEND == "glm":
|
||||
clear_session, get_work_dir, is_allowed_file,
|
||||
list_user_files, stream_claude,
|
||||
)
|
||||
elif AI_BACKEND == "hybrid":
|
||||
# DeepSeek для нормативных вопросов (95% запросов из логов),
|
||||
# Claude CLI через подписку Pro/Max + Domain MCP — для агентских
|
||||
# задач (открыть/проанализировать/заполнить xlsm). Без расходов на
|
||||
# Anthropic API.
|
||||
from claude_bridge_glm import (
|
||||
clear_session, get_work_dir, is_allowed_file, list_user_files,
|
||||
stream_claude as _stream_glm,
|
||||
)
|
||||
from claude_bridge import stream_claude as _stream_claude
|
||||
|
||||
async def stream_claude(message: str, username: str, tab_id: str = "default"):
|
||||
msg_lower = message.lower()
|
||||
# Сильные индикаторы агентской задачи → Claude CLI
|
||||
agent_actions = [
|
||||
"создай файл", "сохрани в", "запиши в", "сделай таблиц",
|
||||
"перенеси данн", "измени файл", "отредактируй", "скопируй",
|
||||
"проверь файл", "открой файл",
|
||||
"загруж", "прикреп", ".xlsx", ".xlsm", ".docx", ".pdf", ".csv",
|
||||
"ячейк", "столбец d", "столбец e", "лист 15", "вкладк",
|
||||
"заполни пункт", "сматчи", "сопостав", "извлеки",
|
||||
]
|
||||
# Сильные индикаторы нормативки → DeepSeek
|
||||
reference_words = [
|
||||
"какой нр", "какой сп", "какая нр", "какая сп",
|
||||
"коэффициент", "зимнее удорожан", "временные здани",
|
||||
"расценк", "найди расценку", "найди норму",
|
||||
"сметная цена", "цена материал",
|
||||
"приказ ", "фснб", "методик",
|
||||
"посчитай нр", "посчитай сп", "рассчитай",
|
||||
"что ты умеешь", "помощь", "help",
|
||||
]
|
||||
# Файл из work_dir упомянут по имени → Claude
|
||||
from claude_bridge_glm import get_work_dir as _gw
|
||||
work_dir = _gw(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_agent = mentions_file or any(kw in msg_lower for kw in agent_actions)
|
||||
is_reference = any(kw in msg_lower for kw in reference_words)
|
||||
if is_agent and not is_reference:
|
||||
stream_fn = _stream_claude
|
||||
elif is_reference and not is_agent:
|
||||
stream_fn = _stream_glm
|
||||
elif is_agent and is_reference:
|
||||
stream_fn = _stream_claude # ambiguous → агент сильнее
|
||||
else:
|
||||
stream_fn = _stream_glm
|
||||
async for chunk in stream_fn(message, username, tab_id):
|
||||
yield chunk
|
||||
elif AI_BACKEND == "auto":
|
||||
from claude_bridge_glm import (
|
||||
clear_session, get_work_dir, is_allowed_file, list_user_files,
|
||||
@@ -433,6 +489,74 @@ async def download_file(filename: str, request: Request):
|
||||
return FileResponse(fpath, filename=filename)
|
||||
|
||||
|
||||
@app.post("/api/extract_complaints")
|
||||
async def extract_complaints_endpoint(request: Request):
|
||||
"""Detrministic regex extraction of (пункт → смета) pairs from xlsm.
|
||||
|
||||
Body: {"tab_id": "...", "filename": "..."} — file must already be uploaded.
|
||||
Returns: stats + pairs + no_code_rows.
|
||||
"""
|
||||
from complaints import extract_pairs
|
||||
|
||||
user = _get_user(request)
|
||||
body = await request.json()
|
||||
tab_id = body.get("tab_id") or request.headers.get("x-tab-id", "default")
|
||||
filename = body.get("filename")
|
||||
if not filename:
|
||||
raise HTTPException(400, "filename required")
|
||||
safe_name = Path(filename).name
|
||||
fpath = get_work_dir(user, tab_id) / safe_name
|
||||
if not fpath.exists():
|
||||
raise HTTPException(404, "File not found in work directory")
|
||||
try:
|
||||
result = extract_pairs(fpath)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e))
|
||||
ip = request.client.host if request.client else None
|
||||
log_action(user, "extract_complaints", "POST", "/api/extract_complaints",
|
||||
f"{safe_name} pairs={result['stats']['total_pairs']}", ip, 200)
|
||||
return result
|
||||
|
||||
|
||||
@app.post("/api/apply_matches")
|
||||
async def apply_matches_endpoint(request: Request):
|
||||
"""Fill column D in sheet «РеестрСМ» with matching пункт-замечания.
|
||||
|
||||
Body: {"tab_id": "...", "filename": "..."} — original xlsm with both sheets.
|
||||
Saves <stem>_filled.xlsm into the same work directory and returns
|
||||
download URL + stats.
|
||||
"""
|
||||
from complaints import apply_to_registry
|
||||
|
||||
user = _get_user(request)
|
||||
body = await request.json()
|
||||
tab_id = body.get("tab_id") or request.headers.get("x-tab-id", "default")
|
||||
filename = body.get("filename")
|
||||
if not filename:
|
||||
raise HTTPException(400, "filename required")
|
||||
safe_name = Path(filename).name
|
||||
work_dir = get_work_dir(user, tab_id)
|
||||
fpath = work_dir / safe_name
|
||||
if not fpath.exists():
|
||||
raise HTTPException(404, "File not found in work directory")
|
||||
# openpyxl drops VBA macros when saving — write as .xlsx so Excel
|
||||
# opens it cleanly even when the source was .xlsm
|
||||
out_name = f"{Path(safe_name).stem}_filled.xlsx"
|
||||
out_path = work_dir / out_name
|
||||
try:
|
||||
result = apply_to_registry(fpath, out_path)
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, str(e))
|
||||
ip = request.client.host if request.client else None
|
||||
log_action(user, "apply_matches", "POST", "/api/apply_matches",
|
||||
f"{safe_name} filled={result['cells_filled']}", ip, 200)
|
||||
return {
|
||||
**result,
|
||||
"output_filename": out_name,
|
||||
"download_url": f"/api/files/{out_name}",
|
||||
}
|
||||
|
||||
|
||||
@app.post("/api/reset")
|
||||
async def reset_session(request: Request):
|
||||
user = _get_user(request)
|
||||
@@ -814,17 +938,23 @@ async def admin_file_users_endpoint(request: Request):
|
||||
|
||||
@app.get("/api/admin/files")
|
||||
async def admin_list_files_endpoint(request: Request):
|
||||
"""All files uploaded by a specific user (across every tab)."""
|
||||
"""All files uploaded by a specific user (across every tab).
|
||||
|
||||
Спец-значение `username=__all__` — файлы всех юзеров. Каждая
|
||||
запись содержит поле `username` (для одиночного режима тоже —
|
||||
UI единообразно).
|
||||
"""
|
||||
_require_admin(request)
|
||||
target_user = request.query_params.get("username", "").strip()
|
||||
if not target_user:
|
||||
raise HTTPException(400, "username query param required")
|
||||
safe_user = Path(target_user).name
|
||||
if safe_user != target_user or not safe_user:
|
||||
raise HTTPException(400, "Invalid username")
|
||||
user_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / safe_user
|
||||
|
||||
data_dir = Path(os.environ.get("DATA_DIR", "./smeta-web-data"))
|
||||
files = []
|
||||
if user_dir.exists() and user_dir.is_dir():
|
||||
|
||||
def _collect(user_dir: Path, username: str):
|
||||
if not user_dir.exists() or not user_dir.is_dir():
|
||||
return
|
||||
for tab_dir in sorted(user_dir.iterdir()):
|
||||
if not tab_dir.is_dir() or tab_dir.name.startswith("."):
|
||||
continue
|
||||
@@ -832,11 +962,25 @@ async def admin_list_files_endpoint(request: Request):
|
||||
if f.is_file() and not f.name.startswith("."):
|
||||
st = f.stat()
|
||||
files.append({
|
||||
"username": username,
|
||||
"tab_id": tab_dir.name,
|
||||
"filename": f.name,
|
||||
"size": st.st_size,
|
||||
"mtime": st.st_mtime,
|
||||
})
|
||||
|
||||
if target_user == "__all__":
|
||||
if data_dir.exists():
|
||||
for d in sorted(data_dir.iterdir()):
|
||||
if not d.is_dir() or d.name.startswith(".") or d.name.startswith("_"):
|
||||
continue
|
||||
_collect(d, d.name)
|
||||
return {"username": "__all__", "count": len(files), "files": files}
|
||||
|
||||
safe_user = Path(target_user).name
|
||||
if safe_user != target_user or not safe_user:
|
||||
raise HTTPException(400, "Invalid username")
|
||||
_collect(data_dir / safe_user, safe_user)
|
||||
return {"username": safe_user, "count": len(files), "files": files}
|
||||
|
||||
|
||||
@@ -869,10 +1013,30 @@ async def admin_download_file_endpoint(request: Request):
|
||||
return FileResponse(fpath, filename=safe_name)
|
||||
|
||||
|
||||
ADMIN_HTML_VERSION = "20260506g"
|
||||
|
||||
|
||||
@app.get("/admin", response_class=HTMLResponse)
|
||||
async def admin_page():
|
||||
# Auth check is done client-side (JS) + all /api/admin/* endpoints require admin
|
||||
return Path("static/admin.html").read_text(encoding="utf-8")
|
||||
async def admin_page(request: Request):
|
||||
# Если у юзера в браузере осталась старая закэшированная копия
|
||||
# /admin без no-store, то любые серверные заголовки уже не
|
||||
# помогут — браузер сам решает, делать ли revalidation. Поэтому:
|
||||
# - на запрос без актуальной ?v= делаем 302 на URL с query
|
||||
# - URL с query !== закэшированный URL без query → промах кэша →
|
||||
# браузер делает свежий запрос, получает no-store, дальше всегда
|
||||
# свежий
|
||||
from fastapi.responses import RedirectResponse
|
||||
if request.query_params.get("v") != ADMIN_HTML_VERSION:
|
||||
return RedirectResponse(url=f"/admin?v={ADMIN_HTML_VERSION}", status_code=302)
|
||||
html = Path("static/admin.html").read_text(encoding="utf-8")
|
||||
return HTMLResponse(
|
||||
html,
|
||||
headers={
|
||||
"Cache-Control": "no-store, no-cache, must-revalidate, max-age=0",
|
||||
"Pragma": "no-cache",
|
||||
"Expires": "0",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
# === Batch V3: Generate + Verify + Auto-Retry ===
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"smeta": {
|
||||
"command": "python3",
|
||||
"args": ["/app/smeta_mcp.py"]
|
||||
}
|
||||
}
|
||||
}
|
||||
+492
@@ -0,0 +1,492 @@
|
||||
"""smeta_mcp — stdio MCP-сервер для домена смет.
|
||||
|
||||
Подключается к Claude CLI через `--mcp-config`. Принимает JSON-RPC 2.0 со
|
||||
stdin, ответы пишет на stdout (одно JSON-сообщение на строку).
|
||||
Контекст пользователя приходит через env vars: SMETA_USER, SMETA_TAB.
|
||||
|
||||
Запуск (вручную для теста):
|
||||
SMETA_USER=smeta SMETA_TAB=default python3 smeta_mcp.py < requests.jsonl
|
||||
|
||||
В будущем удобнее переехать на pypi `mcp` (FastMCP), но MVP — без
|
||||
зависимостей: stdio MCP это просто newline-delimited JSON-RPC 2.0.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
|
||||
PROTOCOL_VERSION = "2025-06-18"
|
||||
|
||||
|
||||
def _user_tab() -> tuple[str, str]:
|
||||
return (
|
||||
os.environ.get("SMETA_USER", "").strip(),
|
||||
os.environ.get("SMETA_TAB", "default").strip() or "default",
|
||||
)
|
||||
|
||||
|
||||
def _work_dir(user: str, tab: str) -> Path:
|
||||
"""Где лежат файлы пользователя.
|
||||
|
||||
SMETA_WORK_DIR (если задан) — прямой override абсолютным путём.
|
||||
Используется в Docker, где host-путь `~/smeta-web-data/<user>/<tab>`
|
||||
смонтирован в `/data`, и MCP должен идти туда напрямую.
|
||||
|
||||
Иначе — DATA_DIR/user/tab (как на хосте main-приложения).
|
||||
"""
|
||||
direct = os.environ.get("SMETA_WORK_DIR")
|
||||
if direct:
|
||||
return Path(direct)
|
||||
base = Path(os.environ.get("DATA_DIR", "./smeta-web-data"))
|
||||
d = base / user / tab
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
# ---------- Tool implementations (обёртки над существующими функциями) ----------
|
||||
|
||||
def tool_read_xlsx_sheet(*, filename: str, sheet: str | None = None, max_rows: int = 50) -> dict:
|
||||
"""Локальная реализация — не зависит от tools_glm/claude_bridge_glm,
|
||||
которые в Docker-sandbox-окружении могут отсутствовать."""
|
||||
import openpyxl
|
||||
user, tab = _user_tab()
|
||||
fpath = _work_dir(user, tab) / Path(filename).name
|
||||
if not fpath.exists():
|
||||
return {"error": f"Файл «{filename}» не найден"}
|
||||
if fpath.suffix.lower() not in {".xlsx", ".xlsm", ".xls"}:
|
||||
return {"error": f"Неподдерживаемый формат: {fpath.suffix}"}
|
||||
try:
|
||||
wb = openpyxl.load_workbook(str(fpath), data_only=True)
|
||||
except Exception as e:
|
||||
return {"error": f"Не удалось открыть файл: {e}"}
|
||||
if sheet is None:
|
||||
ws = wb.worksheets[0]
|
||||
sheet_name = ws.title
|
||||
elif sheet in wb.sheetnames:
|
||||
ws = wb[sheet]
|
||||
sheet_name = sheet
|
||||
else:
|
||||
return {"error": f"Лист «{sheet}» не найден", "available_sheets": wb.sheetnames}
|
||||
rows: list[dict] = []
|
||||
real_count = 0
|
||||
empty_streak = 0
|
||||
for r_idx, row in enumerate(ws.iter_rows(), 1):
|
||||
cells = {
|
||||
c.column_letter: str(c.value)[:300]
|
||||
for c in row
|
||||
if c.value is not None and str(c.value).strip()
|
||||
}
|
||||
if not cells:
|
||||
empty_streak += 1
|
||||
if empty_streak >= 30:
|
||||
break
|
||||
continue
|
||||
empty_streak = 0
|
||||
real_count += 1
|
||||
if len(rows) < max_rows:
|
||||
rows.append({"row": r_idx, "cells": cells})
|
||||
return {
|
||||
"filename": fpath.name,
|
||||
"sheet": sheet_name,
|
||||
"all_sheets": wb.sheetnames,
|
||||
"rows_with_data_total": real_count,
|
||||
"rows_returned": len(rows),
|
||||
"rows": rows,
|
||||
}
|
||||
|
||||
|
||||
def tool_find_in_normative(*, query: str, top_k: int = 3) -> dict:
|
||||
"""В Docker-sandbox обычно нет sentence_transformers — деградирует
|
||||
в `error`, не ломая MCP."""
|
||||
try:
|
||||
from claude_bridge_glm import _search_normative
|
||||
except Exception as e:
|
||||
return {"query": query, "error": f"RAG недоступен: {type(e).__name__}: {e}"}
|
||||
try:
|
||||
text = _search_normative(query, top_k=top_k)
|
||||
except Exception as e:
|
||||
return {"query": query, "error": f"Ошибка поиска: {type(e).__name__}: {e}"}
|
||||
return {"query": query, "result": text or "(нет совпадений)"}
|
||||
|
||||
|
||||
def tool_list_files() -> dict:
|
||||
user, tab = _user_tab()
|
||||
work_dir = _work_dir(user, tab)
|
||||
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 {"tab_id": tab, "files": files}
|
||||
|
||||
|
||||
def tool_extract_complaints_pairs(*, filename: str) -> dict:
|
||||
user, tab = _user_tab()
|
||||
from complaints import extract_pairs
|
||||
fpath = _work_dir(user, tab) / Path(filename).name
|
||||
if not fpath.exists():
|
||||
return {"error": f"Файл «{filename}» не найден в рабочей директории {user}/{tab}"}
|
||||
try:
|
||||
return extract_pairs(fpath)
|
||||
except ValueError as e:
|
||||
return {"error": str(e)}
|
||||
|
||||
|
||||
def tool_apply_pukts_to_registry(*, filename: str) -> dict:
|
||||
user, tab = _user_tab()
|
||||
from complaints import apply_to_registry
|
||||
work_dir = _work_dir(user, tab)
|
||||
fpath = work_dir / Path(filename).name
|
||||
if not fpath.exists():
|
||||
return {"error": f"Файл «{filename}» не найден"}
|
||||
out_name = f"{Path(filename).stem}_filled.xlsx"
|
||||
out_path = work_dir / out_name
|
||||
try:
|
||||
result = apply_to_registry(fpath, out_path)
|
||||
except ValueError as e:
|
||||
return {"error": str(e)}
|
||||
return {
|
||||
**result,
|
||||
"output_filename": out_name,
|
||||
"download_url": f"/api/files/{out_name}",
|
||||
}
|
||||
|
||||
|
||||
def tool_parse_gge_archive(*, filename: str, save_index: bool = True,
|
||||
include_codes: bool = False) -> dict:
|
||||
"""Распаковать zip с .gge и проиндексировать. Универсальный tool —
|
||||
под любую задачу с архивом смет ГГЭ. Если zip уже распакован
|
||||
(filename — папка), просто индексирует.
|
||||
|
||||
save_index=True пишет полный индекс с positions в <stem>_index.json
|
||||
в work_dir — Claude может читать его через Bash python для глубокого
|
||||
анализа без перепарсинга.
|
||||
|
||||
Возвращает: summary (счётчики, схемы), и first 20 codes как пример.
|
||||
Если include_codes=True — возвращает все коды (но без positions).
|
||||
"""
|
||||
user, tab = _user_tab()
|
||||
work_dir = _work_dir(user, tab)
|
||||
src = work_dir / Path(filename).name
|
||||
if not src.exists():
|
||||
return {"error": f"«{filename}» не найден в {user}/{tab}"}
|
||||
from gge_tools import extract_archive, index_gge_directory
|
||||
if src.is_dir():
|
||||
target = src
|
||||
extract_info = None
|
||||
elif src.suffix.lower() == '.zip':
|
||||
target = work_dir / src.stem
|
||||
extract_info = extract_archive(src, target)
|
||||
else:
|
||||
return {"error": f"Неподдерживаемый формат: {src.suffix}. Ожидается .zip или папка."}
|
||||
|
||||
index_path = work_dir / f"{Path(filename).stem}_index.json" if save_index else None
|
||||
idx = index_gge_directory(target, save_index_to=index_path)
|
||||
by_code = idx['by_code']
|
||||
summary = idx['summary']
|
||||
codes = sorted(by_code.keys())
|
||||
out = {
|
||||
"extracted_to": str(target),
|
||||
"extract_info": extract_info,
|
||||
"summary": summary,
|
||||
"index_file": str(index_path) if index_path else None,
|
||||
"sample_codes": codes[:20],
|
||||
}
|
||||
if include_codes:
|
||||
out["all_codes"] = codes
|
||||
return out
|
||||
|
||||
|
||||
def tool_parse_gge_file(*, filename: str, max_positions: int = 30) -> dict:
|
||||
"""Распарсить одну .gge смету (XML). filename — относительный путь
|
||||
в work_dir или внутри ранее распакованной папки.
|
||||
|
||||
Возвращает: code, name, schema_kind, has_excavation,
|
||||
has_transport_summary, totals (полностью), первые max_positions
|
||||
позиций. Удобно посмотреть структуру конкретной сметы.
|
||||
"""
|
||||
user, tab = _user_tab()
|
||||
work_dir = _work_dir(user, tab)
|
||||
candidate = work_dir / filename
|
||||
if not candidate.exists():
|
||||
# fall back: search by basename
|
||||
matches = list(work_dir.rglob(Path(filename).name))
|
||||
if not matches:
|
||||
return {"error": f"«{filename}» не найден в {user}/{tab}"}
|
||||
candidate = matches[0]
|
||||
from gge_tools import parse_gge_file
|
||||
data = parse_gge_file(candidate)
|
||||
if 'error' in data:
|
||||
return data
|
||||
if len(data['positions']) > max_positions:
|
||||
data['positions_total'] = len(data['positions'])
|
||||
data['positions'] = data['positions'][:max_positions]
|
||||
data['positions_truncated'] = True
|
||||
return data
|
||||
|
||||
|
||||
def tool_update_xlsx_cells(*, filename: str, sheet: str,
|
||||
updates: list, out_filename: str | None = None) -> dict:
|
||||
"""Массовая запись ячеек в xlsx. Универсальный tool — годится для
|
||||
любой задачи (заполнение реестра, добавление сводных строк).
|
||||
|
||||
updates: [{"row": int, "col": "E"|int, "value": <строка|число>}, ...]
|
||||
out_filename: если не задан — <stem>_updated.xlsx.
|
||||
Не модифицирует исходник; результат в work_dir.
|
||||
"""
|
||||
user, tab = _user_tab()
|
||||
work_dir = _work_dir(user, tab)
|
||||
src = work_dir / Path(filename).name
|
||||
if not src.exists():
|
||||
return {"error": f"«{filename}» не найден"}
|
||||
if not isinstance(updates, list):
|
||||
return {"error": "updates должен быть списком {row, col, value}"}
|
||||
out_name = out_filename or f"{Path(filename).stem}_updated.xlsx"
|
||||
out_path = work_dir / out_name
|
||||
from gge_tools import update_xlsx_cells
|
||||
res = update_xlsx_cells(src, out_path, sheet, updates)
|
||||
if 'error' in res:
|
||||
return res
|
||||
return {
|
||||
**res,
|
||||
"output_filename": out_name,
|
||||
"download_url": f"/api/files/{out_name}",
|
||||
}
|
||||
|
||||
|
||||
# ---------- Registry + JSON-Schema ----------
|
||||
|
||||
TOOLS: dict[str, dict] = {
|
||||
"read_xlsx_sheet": {
|
||||
"fn": tool_read_xlsx_sheet,
|
||||
"description": (
|
||||
"Прочитать первые непустые строки конкретного листа xlsx-файла "
|
||||
"из рабочей директории пользователя. Возвращает реальные значения "
|
||||
"ячеек по координатам. Используй когда нужно процитировать ячейки "
|
||||
"или понять структуру файла."
|
||||
),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"filename": {"type": "string", "description": "Имя файла как загружено (например 'РеестрСМ.xlsm')"},
|
||||
"sheet": {"type": "string", "description": "Имя листа. Если не указано — первый лист"},
|
||||
"max_rows": {"type": "integer", "description": "Сколько строк максимум (default 50)"},
|
||||
},
|
||||
"required": ["filename"],
|
||||
},
|
||||
},
|
||||
"find_in_normative": {
|
||||
"fn": tool_find_in_normative,
|
||||
"description": (
|
||||
"Семантический поиск по нормативной базе сметчика (ГЭСН, ФСНБ, "
|
||||
"приказы Минстроя, методики). Возвращает релевантные фрагменты "
|
||||
"с указанием источника."
|
||||
),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": {"type": "string", "description": "Поисковый запрос на русском"},
|
||||
"top_k": {"type": "integer", "description": "Кол-во совпадений (default 3)"},
|
||||
},
|
||||
"required": ["query"],
|
||||
},
|
||||
},
|
||||
"list_files": {
|
||||
"fn": tool_list_files,
|
||||
"description": "Список файлов, загруженных пользователем в текущей вкладке чата.",
|
||||
"inputSchema": {"type": "object", "properties": {}},
|
||||
},
|
||||
"extract_complaints_pairs": {
|
||||
"fn": tool_extract_complaints_pairs,
|
||||
"description": (
|
||||
"Извлечь из реестра РеестрСМ.xlsm все пары (пункт замечания, "
|
||||
"код сметы) с листа «15.СМ». Regex-парсер, без галлюцинаций. "
|
||||
"Возвращает stats и список pairs. Не модифицирует файл."
|
||||
),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"filename": {"type": "string", "description": "Имя xlsm-файла реестра"},
|
||||
},
|
||||
"required": ["filename"],
|
||||
},
|
||||
},
|
||||
"apply_pukts_to_registry": {
|
||||
"fn": tool_apply_pukts_to_registry,
|
||||
"description": (
|
||||
"Заполнить столбец D листа РеестрСМ номерами пунктов замечаний, "
|
||||
"извлечёнными с листа 15.СМ. Учитывает: many-to-many, дубли строк "
|
||||
"(пишем только в первую), скрытые строки (приоритет видимым). "
|
||||
"Создаёт новый файл <stem>_filled.xlsx, не трогает исходник. "
|
||||
"Возвращает download_url для скачивания через /api/files/."
|
||||
),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"filename": {"type": "string", "description": "Имя xlsm-файла реестра"},
|
||||
},
|
||||
"required": ["filename"],
|
||||
},
|
||||
},
|
||||
"parse_gge_archive": {
|
||||
"fn": tool_parse_gge_archive,
|
||||
"description": (
|
||||
"Распаковать .zip с .gge файлами (сметы ГГЭ, XML) и построить "
|
||||
"индекс по коду сметы (Estimate/Num). Для каждой сметы возвращает: "
|
||||
"schema_kind (local|object|unknown), has_excavation (есть ли в "
|
||||
"Cost.Name подстрока «разработка грунта»), has_transport_summary "
|
||||
"(EstimatePrice/Summary/Transport > 0), total_rub, transport_rub, "
|
||||
"name, path. Полный индекс с позициями сохраняется в "
|
||||
"<stem>_index.json — читай его через Bash python для глубокого "
|
||||
"анализа. Если filename — уже распакованная папка, просто "
|
||||
"индексирует. Универсальный tool: используй для любой задачи, где "
|
||||
"нужно агрегировать данные по архиву смет."
|
||||
),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"filename": {"type": "string", "description": "Имя .zip или папки в work_dir"},
|
||||
"save_index": {"type": "boolean", "description": "Сохранить полный индекс в JSON (default true)"},
|
||||
"include_codes": {"type": "boolean", "description": "Вернуть все коды смет (default false — только первые 20)"},
|
||||
},
|
||||
"required": ["filename"],
|
||||
},
|
||||
},
|
||||
"parse_gge_file": {
|
||||
"fn": tool_parse_gge_file,
|
||||
"description": (
|
||||
"Распарсить одну .gge смету (XML формата ГГЭ). Возвращает: "
|
||||
"code, name, schema_kind, has_excavation, has_transport_summary, "
|
||||
"totals (все поля EstimatePrice/Summary), positions (список "
|
||||
"Cost/Transport позиций с name/code/quantity/unit/price). "
|
||||
"Полезно для уточнения структуры конкретной сметы."
|
||||
),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"filename": {"type": "string", "description": "Путь к .gge файлу относительно work_dir (или просто basename — будет найден)"},
|
||||
"max_positions": {"type": "integer", "description": "Лимит позиций в ответе (default 30)"},
|
||||
},
|
||||
"required": ["filename"],
|
||||
},
|
||||
},
|
||||
"update_xlsx_cells": {
|
||||
"fn": tool_update_xlsx_cells,
|
||||
"description": (
|
||||
"Массовая запись ячеек в xlsx файл. Универсальный tool: годится "
|
||||
"для заполнения колонок (E=ИГИ, F=ТС), добавления сводных строк, "
|
||||
"правок отдельных ячеек. Создаёт копию <stem>_updated.xlsx, "
|
||||
"не трогает исходник. Возвращает download_url. "
|
||||
"ВАЖНО: если исходник .xlsm — VBA не сохранится, выход всегда .xlsx."
|
||||
),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"filename": {"type": "string", "description": "Имя xlsx/xlsm файла"},
|
||||
"sheet": {"type": "string", "description": "Имя листа"},
|
||||
"updates": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"row": {"type": "integer"},
|
||||
"col": {"description": "Буква (E) или индекс (5)"},
|
||||
"value": {},
|
||||
},
|
||||
"required": ["row", "col"],
|
||||
},
|
||||
"description": "Список {row, col, value} для записи",
|
||||
},
|
||||
"out_filename": {"type": "string", "description": "Имя выходного файла (default <stem>_updated.xlsx)"},
|
||||
},
|
||||
"required": ["filename", "sheet", "updates"],
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _tools_list_payload() -> list[dict]:
|
||||
return [
|
||||
{
|
||||
"name": name,
|
||||
"description": meta["description"],
|
||||
"inputSchema": meta["inputSchema"],
|
||||
}
|
||||
for name, meta in TOOLS.items()
|
||||
]
|
||||
|
||||
|
||||
# ---------- JSON-RPC 2.0 ----------
|
||||
|
||||
def _rpc_result(rpc_id, result: dict) -> dict:
|
||||
return {"jsonrpc": "2.0", "id": rpc_id, "result": result}
|
||||
|
||||
|
||||
def _rpc_error(rpc_id, code: int, message: str) -> dict:
|
||||
return {"jsonrpc": "2.0", "id": rpc_id, "error": {"code": code, "message": message}}
|
||||
|
||||
|
||||
def handle(msg: dict) -> dict | None:
|
||||
method = msg.get("method")
|
||||
rpc_id = msg.get("id")
|
||||
|
||||
if method == "initialize":
|
||||
return _rpc_result(rpc_id, {
|
||||
"protocolVersion": PROTOCOL_VERSION,
|
||||
"capabilities": {"tools": {"listChanged": False}},
|
||||
"serverInfo": {"name": "smeta", "version": "0.1.0"},
|
||||
})
|
||||
|
||||
if method in ("notifications/initialized", "notifications/cancelled"):
|
||||
return None # notification — без ответа
|
||||
|
||||
if method == "tools/list":
|
||||
return _rpc_result(rpc_id, {"tools": _tools_list_payload()})
|
||||
|
||||
if method == "tools/call":
|
||||
params = msg.get("params") or {}
|
||||
name = params.get("name")
|
||||
args = params.get("arguments") or {}
|
||||
if name not in TOOLS:
|
||||
return _rpc_error(rpc_id, -32601, f"Unknown tool: {name}")
|
||||
try:
|
||||
result = TOOLS[name]["fn"](**args)
|
||||
except TypeError as e:
|
||||
return _rpc_error(rpc_id, -32602, f"Bad arguments: {e}")
|
||||
except Exception as e:
|
||||
return _rpc_error(rpc_id, -32000, f"{type(e).__name__}: {e}")
|
||||
is_error = isinstance(result, dict) and "error" in result
|
||||
text = json.dumps(result, ensure_ascii=False, indent=2)
|
||||
return _rpc_result(rpc_id, {
|
||||
"content": [{"type": "text", "text": text}],
|
||||
"isError": is_error,
|
||||
})
|
||||
|
||||
if rpc_id is not None:
|
||||
return _rpc_error(rpc_id, -32601, f"Method not found: {method}")
|
||||
return None
|
||||
|
||||
|
||||
def main() -> None:
|
||||
for line in sys.stdin:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
msg = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
try:
|
||||
resp = handle(msg)
|
||||
except Exception:
|
||||
traceback.print_exc(file=sys.stderr)
|
||||
resp = _rpc_error(msg.get("id"), -32000, "Internal server error")
|
||||
if resp is not None:
|
||||
sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+46
-16
@@ -41,13 +41,14 @@ a { color: var(--accent); text-decoration: none; }
|
||||
|
||||
<nav class="sidebar">
|
||||
<h1>Админ-панель</h1>
|
||||
<a href="#dashboard" class="active" onclick="showPage('dashboard')">Dashboard</a>
|
||||
<a href="#users" onclick="showPage('users')">Пользователи</a>
|
||||
<a href="#invites" onclick="showPage('invites')">Приглашения</a>
|
||||
<a href="#sessions" onclick="showPage('sessions')">Сессии</a>
|
||||
<a href="#audit" onclick="showPage('audit')">Журнал</a>
|
||||
<a href="#files" onclick="showPage('files')">Файлы</a>
|
||||
<a href="#dashboard" class="active" onclick="return showPage('dashboard')">Dashboard</a>
|
||||
<a href="#users" onclick="return showPage('users')">Пользователи</a>
|
||||
<a href="#invites" onclick="return showPage('invites')">Приглашения</a>
|
||||
<a href="#sessions" onclick="return showPage('sessions')">Сессии</a>
|
||||
<a href="#audit" onclick="return showPage('audit')">Журнал</a>
|
||||
<a href="#files" onclick="return showPage('files')">Файлы</a>
|
||||
<a href="/" class="back">← Вернуться в чат</a>
|
||||
<div style="position:absolute;bottom:.5rem;left:1rem;font-size:.65rem;color:#999">v.2026-05-06g</div>
|
||||
</nav>
|
||||
|
||||
<div class="main">
|
||||
@@ -107,15 +108,13 @@ a { color: var(--accent); text-decoration: none; }
|
||||
<div class="page" id="page-files">
|
||||
<h2>Файлы пользователей</h2>
|
||||
<div style="display:flex;gap:.5rem;margin-bottom:1rem;align-items:center;flex-wrap:wrap">
|
||||
<select id="files-user" style="padding:4px 8px;border:1px solid var(--border);border-radius:4px;font-size:.85rem;min-width:240px">
|
||||
<select id="files-user" onchange="onFilesUserChange()" style="padding:4px 8px;border:1px solid var(--border);border-radius:4px;font-size:.85rem;min-width:240px">
|
||||
<option value="">— выберите пользователя —</option>
|
||||
</select>
|
||||
<button class="btn" onclick="loadFiles()" style="padding:4px 10px;font-size:.8rem">Показать файлы</button>
|
||||
<button class="btn" onclick="loadFiles()" style="padding:4px 10px;font-size:.8rem">Обновить</button>
|
||||
<span id="files-count" style="font-size:.8rem;color:var(--text-muted, #666)"></span>
|
||||
</div>
|
||||
<table id="files">
|
||||
<tr><th>Tab ID</th><th>Файл</th><th>Размер</th><th>Загружен</th><th>Действие</th></tr>
|
||||
</table>
|
||||
<table id="files"></table>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
@@ -154,6 +153,14 @@ function showPage(name) {
|
||||
document.querySelectorAll('.sidebar a').forEach(a => a.classList.remove('active'));
|
||||
document.getElementById('page-' + name).classList.add('active');
|
||||
document.querySelector('.sidebar a[href="#' + name + '"]').classList.add('active');
|
||||
// Обновляем hash без default-скролла браузера и без записи в history
|
||||
// (default <a href="#x"> делает window.scrollTo + history.pushState —
|
||||
// это и есть «дёрганье». Возвращаем false из onclick, default отменяется,
|
||||
// мы сами тихо ставим hash через replaceState).
|
||||
if (location.hash !== '#' + name) {
|
||||
history.replaceState(null, '', '#' + name);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
// Handle hash on load
|
||||
if (location.hash) showPage(location.hash.slice(1));
|
||||
@@ -217,20 +224,38 @@ async function loadFileUsers() {
|
||||
const r = await fetch('/api/admin/file_users', {headers: H});
|
||||
if (!r.ok) return;
|
||||
const d = await r.json();
|
||||
sel.innerHTML = '<option value="">— выберите пользователя —</option>';
|
||||
const total = d.users.reduce((acc, u) => acc + u.file_count, 0);
|
||||
sel.innerHTML = '<option value="__all__">Все (' + total + ')</option>';
|
||||
for (const u of d.users) {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = u.username;
|
||||
opt.textContent = u.username + ' (' + u.file_count + ')';
|
||||
sel.appendChild(opt);
|
||||
}
|
||||
// По умолчанию — «Все»; localStorage только если ранее юзер
|
||||
// явно выбирал не-«все»
|
||||
const saved = localStorage.getItem('admin_files_user');
|
||||
sel.value = (saved && Array.from(sel.options).some(o => o.value === saved))
|
||||
? saved
|
||||
: '__all__';
|
||||
loadFiles();
|
||||
}
|
||||
function onFilesUserChange() {
|
||||
const v = document.getElementById('files-user').value;
|
||||
if (v) localStorage.setItem('admin_files_user', v);
|
||||
else localStorage.removeItem('admin_files_user');
|
||||
loadFiles();
|
||||
}
|
||||
loadFileUsers();
|
||||
async function loadFiles() {
|
||||
const u = document.getElementById('files-user').value;
|
||||
const tbl = document.getElementById('files');
|
||||
const cnt = document.getElementById('files-count');
|
||||
tbl.innerHTML = '<tr><th>Tab ID</th><th>Файл</th><th>Размер</th><th>Загружен</th><th>Действие</th></tr>';
|
||||
const isAll = (u === '__all__');
|
||||
// header
|
||||
tbl.innerHTML = isAll
|
||||
? '<tr><th>Пользователь</th><th>Tab ID</th><th>Файл</th><th>Размер</th><th>Загружен</th><th>Действие</th></tr>'
|
||||
: '<tr><th>Tab ID</th><th>Файл</th><th>Размер</th><th>Загружен</th><th>Действие</th></tr>';
|
||||
cnt.textContent = '';
|
||||
if (!u) return;
|
||||
cnt.textContent = 'Загрузка…';
|
||||
@@ -238,13 +263,18 @@ async function loadFiles() {
|
||||
if (!r.ok) { cnt.textContent = 'Ошибка: ' + r.status; return; }
|
||||
const d = await r.json();
|
||||
cnt.textContent = 'Файлов: ' + d.count;
|
||||
for (const f of d.files) {
|
||||
// Сортировка: новые сверху
|
||||
const rows = d.files.slice().sort((a, b) => b.mtime - a.mtime);
|
||||
for (const f of rows) {
|
||||
const ts = new Date(f.mtime * 1000).toLocaleString('ru-RU', {day:'2-digit', month:'2-digit', year:'2-digit', hour:'2-digit', minute:'2-digit'});
|
||||
const tr = document.createElement('tr');
|
||||
const dlUrl = '/api/admin/file_download?username=' + encodeURIComponent(u)
|
||||
const owner = f.username || u;
|
||||
const dlUrl = '/api/admin/file_download?username=' + encodeURIComponent(owner)
|
||||
+ '&tab_id=' + encodeURIComponent(f.tab_id)
|
||||
+ '&filename=' + encodeURIComponent(f.filename);
|
||||
tr.innerHTML = '<td style="font-family:monospace;font-size:.8rem">' + f.tab_id + '</td>'
|
||||
const userCol = isAll ? '<td style="font-size:.8rem">' + owner + '</td>' : '';
|
||||
tr.innerHTML = userCol
|
||||
+ '<td style="font-family:monospace;font-size:.8rem">' + f.tab_id + '</td>'
|
||||
+ '<td>' + f.filename.replace(/</g,'<') + '</td>'
|
||||
+ '<td>' + fmtSize(f.size) + '</td>'
|
||||
+ '<td class="time">' + ts + '</td>'
|
||||
|
||||
+11
-2
@@ -167,10 +167,19 @@ const API = '';
|
||||
let token = localStorage.getItem('token');
|
||||
let pendingFiles = [];
|
||||
let streaming = false;
|
||||
// crypto.randomUUID работает только в secure context (HTTPS / localhost),
|
||||
// под голым HTTP по IP его нет — используем fallback
|
||||
function genUUID() {
|
||||
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') return crypto.randomUUID();
|
||||
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
|
||||
const r = Math.random() * 16 | 0;
|
||||
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
|
||||
});
|
||||
}
|
||||
// Session continuity: reuse last tabId from localStorage
|
||||
// New session only via "Новый чат" button or ?tab=UUID
|
||||
const urlTab = new URLSearchParams(window.location.search).get('tab');
|
||||
let tabId = urlTab || localStorage.getItem('tabId') || crypto.randomUUID();
|
||||
let tabId = urlTab || localStorage.getItem('tabId') || genUUID();
|
||||
localStorage.setItem('tabId', tabId);
|
||||
|
||||
function checkAdmin() {
|
||||
@@ -470,7 +479,7 @@ async function sendMessage() {
|
||||
// --- Session ---
|
||||
async function resetSession() {
|
||||
// Create new tab = new session, old one stays in DB
|
||||
tabId = crypto.randomUUID();
|
||||
tabId = genUUID();
|
||||
localStorage.setItem('tabId', tabId);
|
||||
msgs.innerHTML = '';
|
||||
addMsg('system', 'Новый диалог начат.');
|
||||
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
"""DeepSeek function-calling tools.
|
||||
|
||||
Каждый tool — это пара (callable, JSON-Schema). callable принимает
|
||||
(user, tab_id, **args) и возвращает dict, сериализуемый в JSON;
|
||||
ошибки возвращаются как `{"error": "..."}`, чтобы модель могла на них
|
||||
отреагировать в следующем шаге диалога.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import openpyxl
|
||||
|
||||
|
||||
def read_xlsx_sheet(
|
||||
user: str,
|
||||
tab_id: str,
|
||||
*,
|
||||
filename: str,
|
||||
sheet: str | None = None,
|
||||
max_rows: int = 50,
|
||||
) -> dict:
|
||||
"""Прочитать первые непустые строки конкретного листа xlsx."""
|
||||
from claude_bridge_glm import get_work_dir
|
||||
|
||||
work_dir = get_work_dir(user, tab_id)
|
||||
safe_name = Path(filename).name
|
||||
fpath = work_dir / safe_name
|
||||
if not fpath.exists():
|
||||
return {"error": f"Файл «{safe_name}» не найден в рабочей директории"}
|
||||
if fpath.suffix.lower() not in {".xlsx", ".xlsm", ".xls"}:
|
||||
return {"error": f"Неподдерживаемый формат: {fpath.suffix}"}
|
||||
try:
|
||||
wb = openpyxl.load_workbook(str(fpath), data_only=True)
|
||||
except Exception as e:
|
||||
return {"error": f"Не удалось открыть файл: {e}"}
|
||||
|
||||
if sheet is None:
|
||||
ws = wb.worksheets[0]
|
||||
sheet_name = ws.title
|
||||
elif sheet in wb.sheetnames:
|
||||
ws = wb[sheet]
|
||||
sheet_name = sheet
|
||||
else:
|
||||
return {
|
||||
"error": f"Лист «{sheet}» не найден",
|
||||
"available_sheets": wb.sheetnames,
|
||||
}
|
||||
|
||||
rows = []
|
||||
real_count = 0
|
||||
empty_streak = 0
|
||||
for r_idx, row in enumerate(ws.iter_rows(), 1):
|
||||
cells = {
|
||||
c.column_letter: str(c.value)[:300]
|
||||
for c in row
|
||||
if c.value is not None and str(c.value).strip()
|
||||
}
|
||||
if not cells:
|
||||
empty_streak += 1
|
||||
if empty_streak >= 30:
|
||||
break
|
||||
continue
|
||||
empty_streak = 0
|
||||
real_count += 1
|
||||
if len(rows) < max_rows:
|
||||
rows.append({"row": r_idx, "cells": cells})
|
||||
|
||||
return {
|
||||
"filename": safe_name,
|
||||
"sheet": sheet_name,
|
||||
"all_sheets": wb.sheetnames,
|
||||
"rows_with_data_total": real_count,
|
||||
"rows_returned": len(rows),
|
||||
"rows": rows,
|
||||
}
|
||||
|
||||
|
||||
def find_in_normative(
|
||||
user: str,
|
||||
tab_id: str,
|
||||
*,
|
||||
query: str,
|
||||
top_k: int = 3,
|
||||
) -> dict:
|
||||
"""Семантический поиск по нормативной базе.
|
||||
|
||||
Импорт claude_bridge_glm/sentence_transformers вынесен в try-блок:
|
||||
в minimal-окружениях (например, Claude-sandbox Docker без RAG-стека)
|
||||
отсутствие зависимостей не должно ронять весь MCP.
|
||||
"""
|
||||
try:
|
||||
from claude_bridge_glm import _search_normative
|
||||
except Exception as e:
|
||||
return {"query": query, "error": f"RAG недоступен: {type(e).__name__}: {e}"}
|
||||
|
||||
try:
|
||||
text = _search_normative(query, top_k=top_k)
|
||||
except Exception as e:
|
||||
return {"query": query, "error": f"Ошибка поиска: {type(e).__name__}: {e}"}
|
||||
|
||||
return {
|
||||
"query": query,
|
||||
"result": text or "(нет совпадений)",
|
||||
}
|
||||
|
||||
|
||||
def list_files(user: str, tab_id: str) -> dict:
|
||||
"""Список загруженных файлов в текущей вкладке."""
|
||||
from claude_bridge_glm import list_user_files
|
||||
|
||||
files = list_user_files(user, tab_id)
|
||||
return {"tab_id": tab_id, "files": files}
|
||||
|
||||
|
||||
# ---------- Registry + JSON-Schema for the API ----------
|
||||
|
||||
TOOL_REGISTRY = {
|
||||
"read_xlsx_sheet": read_xlsx_sheet,
|
||||
"find_in_normative": find_in_normative,
|
||||
"list_files": list_files,
|
||||
}
|
||||
|
||||
TOOLS_SCHEMA = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "read_xlsx_sheet",
|
||||
"description": (
|
||||
"Прочитать первые непустые строки конкретного листа xlsx-файла из "
|
||||
"рабочей директории пользователя. Используй когда нужно понять "
|
||||
"структуру файла или процитировать ячейки по точным координатам."
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"filename": {
|
||||
"type": "string",
|
||||
"description": "Имя файла, например 'РеестрСМ.xlsm'",
|
||||
},
|
||||
"sheet": {
|
||||
"type": "string",
|
||||
"description": "Имя листа. Если не указано — первый лист",
|
||||
},
|
||||
"max_rows": {
|
||||
"type": "integer",
|
||||
"description": "Сколько строк вернуть максимум (default 50)",
|
||||
},
|
||||
},
|
||||
"required": ["filename"],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "find_in_normative",
|
||||
"description": (
|
||||
"Семантический поиск по нормативной базе (ГЭСН, ФСНБ, приказы "
|
||||
"Минстроя, методики). Используй для конкретных нормативных ссылок."
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": {"type": "string", "description": "Поисковый запрос"},
|
||||
"top_k": {"type": "integer", "description": "Кол-во совпадений (default 3)"},
|
||||
},
|
||||
"required": ["query"],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "list_files",
|
||||
"description": "Список файлов, загруженных пользователем в текущей вкладке.",
|
||||
"parameters": {"type": "object", "properties": {}},
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def summarize_result(name: str, result: dict) -> str:
|
||||
"""Короткий человекочитаемый summary для UI."""
|
||||
if "error" in result:
|
||||
return f"❌ {name}: {result['error']}"
|
||||
if name == "read_xlsx_sheet":
|
||||
return (
|
||||
f"✓ {name}: лист «{result.get('sheet')}» из «{result.get('filename')}» "
|
||||
f"({result.get('rows_with_data_total')} строк с данными, "
|
||||
f"показано {result.get('rows_returned')})"
|
||||
)
|
||||
if name == "find_in_normative":
|
||||
return f"✓ {name}: запрос «{result.get('query')}»"
|
||||
if name == "list_files":
|
||||
n = len(result.get("files", []))
|
||||
return f"✓ {name}: {n} файлов"
|
||||
return f"✓ {name}"
|
||||
Reference in New Issue
Block a user