chore: универсализация, скрипты fetch/verify, python>=3.10

- CAG: коэффициенты 421/пр (Прил.10, таблицы 1-5)
- Checker: универсальный lookup НР/СП по сборнику
- Chunker: рефакторинг для всех видов строительства
- RAG: batch embeddings
- python>=3.10 (совместимость с сервером)
- Скрипты: fetch ГЭСН/ФССЦ, verify_knowledge_base

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-29 23:27:55 +10:00
co-authored by Claude Opus 4.6
parent e45a0734d8
commit 45f9d423d9
12 changed files with 1414 additions and 47 deletions
+34 -5
View File
@@ -3,12 +3,32 @@ CAG (Cache-Augmented Generation) — structured data always in context.
All tables that fit in LLM context window (~15K tokens):
- НР/СП tables (274 rows)
- Coefficients (Приложение 28.1, 20 items)
- FGIS groups mapping
- Coefficients 421/пр Приложение 10 (условия производства работ)
- Coefficients Приложение 28.1 (железные дороги)
- Key normative rules
"""
from smeta_railway.data.nr_sp_tables import NR_TABLE, SP_TABLE
from smeta_railway.data.coefficients_421pr import (
TABLE_1_PRODUCTIVITY, TABLE_2_WAGES,
TABLE_3_RECONSTRUCTION_PRODUCTIVITY,
TABLE_5_CAPREPAIR_PRODUCTIVITY,
)
def _format_421_table(table: dict, table_num: int) -> list[str]:
"""Format a 421/pr coefficient table for CAG context."""
lines = [f"### Таблица {table_num}. {table['title']}"]
for key, row in table["rows"].items():
desc = row["description"]
if len(desc) > 80:
desc = desc[:77] + "..."
coeffs = []
for col in ("gesn", "gesnm", "gesnr", "coeff"):
if col in row and row[col] is not None:
coeffs.append(str(row[col]))
lines.append(f" п.{key}: {desc} — К={'/'.join(coeffs)}")
return lines
def build_cag_context() -> str:
@@ -31,7 +51,17 @@ def build_cag_context() -> str:
parts.append("")
# Coefficients from Приложение 28.1
# Coefficients 421/пр Приложение 10 (universal)
parts.append("## Коэффициенты условий производства работ (Приказ 421/пр, Прил.10)")
parts.append("(в ред. 557/пр от 07.07.2022, 55/пр от 30.01.2024)")
parts.extend(_format_421_table(TABLE_1_PRODUCTIVITY, 1))
parts.extend(_format_421_table(TABLE_2_WAGES, 2))
parts.extend(_format_421_table(TABLE_3_RECONSTRUCTION_PRODUCTIVITY, 3))
parts.extend(_format_421_table(TABLE_5_CAPREPAIR_PRODUCTIVITY, 5))
parts.append("")
# Coefficients from Приложение 28.1 (railway-specific, kept for backwards compat)
parts.append("## Коэффициенты ГЭСН-28 (Приложение 28.1, Железные дороги)")
parts.append("п.1.1 К_движение (скорость до 140 км/ч):")
for trains, k in [("14-18", 1.05), ("19-36", 1.10), ("37-54", 1.15),
@@ -57,11 +87,10 @@ def build_cag_context() -> str:
parts.append("- НР и СП считаются от ФОТ (ОТ + ЗП маш.), НЕ от ПЗ")
parts.append("- Коэффициенты перемножаются, НЕ складываются")
parts.append("- Лимитированные: временные здания + зимнее + резерв на непредвиденные")
parts.append("- Нормы 28-01-043 (резка плетей) и 28-01-044 (изол. стыки) — добавлены в дополнениях к ФСНБ-2022")
parts.append("- Резерв на непредвиденные: максимум 2% для соцобъектов, максимум 3% для производственных")
parts.append("- Врем. здания для капремонта: норма × 0.8")
parts.append("- Изолирующие стыки = 28-03-035 (раздел СЦБ)")
parts.append("- ФСНБ-2022: базовый приказ 1046/пр + 17 дополнений (И1-И17)")
parts.append("- База расценок: 47 сборников ГЭСН, 181 000+ расценок")
return "\n".join(parts)
+13 -9
View File
@@ -126,20 +126,24 @@ def check_yaml_config(yaml_path: str | Path) -> CheckReport:
if result:
report.add(result.level, result.code, result.message)
# 2. Check overhead
# 2. Check overhead — lookup by collection
overhead = config.get("overhead", {})
nr = overhead.get("nr_railway", 0)
sp = overhead.get("sp_railway", 0)
nr = overhead.get("nr_pct", overhead.get("nr_railway", 0))
sp = overhead.get("sp_pct", overhead.get("sp_railway", 0))
collection = config.get("collection", "28")
nr_entry = NR_TABLE.get("22") # ж/д
if nr_entry and nr != nr_entry[1]:
from smeta_railway.calc.overhead import GESN_TO_NR_SP_ITEM
item_key = GESN_TO_NR_SP_ITEM.get(f"{collection}-", "22")
nr_entry = NR_TABLE.get(item_key)
if nr_entry and nr and nr != nr_entry[1]:
report.add("error", "NR_WRONG",
f"НР для ж/д = {nr}%, должно быть {nr_entry[1]}% (812/пр, п.22)")
f"НР = {nr}%, должно быть {nr_entry[1]}% (812/пр, п.{item_key} — {nr_entry[0]})")
sp_entry = SP_TABLE.get("22")
if sp_entry and sp != sp_entry[1]:
sp_entry = SP_TABLE.get(item_key)
if sp_entry and sp and sp != sp_entry[1]:
report.add("error", "SP_WRONG",
f"СП для ж/д = {sp}%, должно быть {sp_entry[1]}% (774/пр, п.22)")
f"СП = {sp}%, должно быть {sp_entry[1]}% (774/пр, п.{item_key} — {sp_entry[0]})")
# 3. Check limited costs
limited = config.get("limited_costs", {})
+157 -16
View File
@@ -1,11 +1,13 @@
"""
PDF → text chunks for RAG retrieval.
Uses pymupdf (fitz) for text extraction.
PDF/HTM → text chunks for RAG retrieval.
Uses pymupdf (fitz) for PDF, html.parser for HTM.
"""
import html.parser
import json
import os
import pickle
import re
from pathlib import Path
import fitz # pymupdf
@@ -33,6 +35,56 @@ def extract_text_from_pdf(pdf_path: str | Path) -> list[dict]:
return pages
class _HTMLTextExtractor(html.parser.HTMLParser):
"""Simple HTML to text converter."""
def __init__(self):
super().__init__()
self._text = []
self._skip = False
def handle_starttag(self, tag, attrs):
self._skip = tag in ("script", "style", "img")
if tag in ("br", "p", "div", "tr", "li"):
self._text.append("\n")
def handle_endtag(self, tag):
self._skip = False
def handle_data(self, data):
if not self._skip:
self._text.append(data)
def get_text(self):
return "".join(self._text)
def extract_text_from_htm(htm_path: str | Path) -> list[dict]:
"""Extract text from HTM file (windows-1251 or utf-8)."""
path = Path(htm_path)
raw = path.read_bytes()
# Detect encoding from meta tag or try windows-1251
for enc in ("windows-1251", "cp1251", "utf-8"):
try:
text = raw.decode(enc)
if "�" not in text[:200]:
break
except UnicodeDecodeError:
continue
else:
text = raw.decode("utf-8", errors="replace")
parser = _HTMLTextExtractor()
parser.feed(text)
clean = parser.get_text()
# Collapse whitespace
clean = re.sub(r"\n{3,}", "\n\n", clean).strip()
if not clean:
return []
return [{"source": path.name, "page": 1, "text": clean}]
def chunk_text(text: str, source: str, page: int,
chunk_size: int = CHUNK_SIZE,
overlap: int = CHUNK_OVERLAP) -> list[dict]:
@@ -73,10 +125,11 @@ def chunk_text(text: str, source: str, page: int,
def process_pdf_directory(pdf_dir: str | Path) -> list[dict]:
"""Process all PDFs in directory into chunks."""
"""Process all PDFs and HTM files in directory into chunks."""
pdf_dir = Path(pdf_dir)
all_chunks = []
# PDF files
for pdf_path in sorted(pdf_dir.glob("*.pdf")):
print(f" Processing {pdf_path.name}...")
pages = extract_text_from_pdf(pdf_path)
@@ -88,15 +141,32 @@ def process_pdf_directory(pdf_dir: str | Path) -> list[dict]:
)
all_chunks.extend(chunks)
# HTM files
for htm_path in sorted(pdf_dir.glob("*.htm")):
print(f" Processing {htm_path.name}...")
pages = extract_text_from_htm(htm_path)
for page_data in pages:
chunks = chunk_text(
page_data["text"],
page_data["source"],
page_data["page"],
)
all_chunks.extend(chunks)
return all_chunks
def build_rag_index(
pdf_dirs: list[str | Path],
output_dir: str | Path,
embed_batch: int = 500,
) -> tuple[faiss.IndexFlatIP, list[dict]]:
"""Build RAG FAISS index from PDF directories."""
from smeta_railway.ai.embeddings import embed_query
"""Build RAG FAISS index from PDF directories.
Memory-optimized: processes embeddings in batches of `embed_batch`
and adds them to FAISS incrementally instead of holding all in RAM.
"""
from smeta_railway.ai.embeddings import EMBEDDING_DIM
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
@@ -106,32 +176,42 @@ def build_rag_index(
for pdf_dir in pdf_dirs:
pdf_dir = Path(pdf_dir)
if pdf_dir.is_file():
pages = extract_text_from_pdf(pdf_dir)
if str(pdf_dir).endswith((".htm", ".html")):
pages = extract_text_from_htm(pdf_dir)
else:
pages = extract_text_from_pdf(pdf_dir)
for p in pages:
all_chunks.extend(chunk_text(p["text"], p["source"], p["page"]))
elif pdf_dir.is_dir():
print(f"Processing directory: {pdf_dir}")
all_chunks.extend(process_pdf_directory(pdf_dir))
print(f"Total chunks: {len(all_chunks)}")
total = len(all_chunks)
print(f"Total chunks: {total}")
# Generate embeddings
# Build FAISS index incrementally — batch embeddings to save RAM
from smeta_railway.ai.embeddings import generate_embeddings
texts = [c["text"][:500] for c in all_chunks] # truncate for embedding
import gc
print("Generating embeddings for RAG chunks...")
embeddings = generate_embeddings(texts, batch_size=200)
faiss.normalize_L2(embeddings)
index = faiss.IndexFlatIP(EMBEDDING_DIM)
dim = embeddings.shape[1]
index = faiss.IndexFlatIP(dim)
index.add(embeddings)
for start in range(0, total, embed_batch):
end = min(start + embed_batch, total)
batch_texts = [c["text"][:500] for c in all_chunks[start:end]]
print(f" Embedding batch {start}-{end} / {total}...")
embs = generate_embeddings(batch_texts, batch_size=64)
faiss.normalize_L2(embs)
index.add(embs)
del embs, batch_texts
gc.collect()
faiss.write_index(index, str(output_dir / "rag.faiss"))
with open(output_dir / "rag_chunks.pkl", "wb") as f:
pickle.dump(all_chunks, f)
print(f"RAG index saved: {len(all_chunks)} chunks, dim={dim}")
print(f"RAG index saved: {total} chunks, dim={EMBEDDING_DIM}")
return index, all_chunks
@@ -144,3 +224,64 @@ def load_rag_index(
with open(index_dir / "rag_chunks.pkl", "rb") as f:
chunks = pickle.load(f)
return index, chunks
def add_to_rag_index(
doc_path: str | Path,
index_dir: str | Path,
embed_batch: int = 500,
) -> int:
"""Add a single PDF/HTM document to existing RAG index incrementally.
Returns number of new chunks added.
"""
from smeta_railway.ai.embeddings import generate_embeddings, EMBEDDING_DIM
import gc
doc_path = Path(doc_path)
index_dir = Path(index_dir)
# Extract chunks from new document
if doc_path.suffix.lower() in (".htm", ".html"):
pages = extract_text_from_htm(doc_path)
else:
pages = extract_text_from_pdf(doc_path)
new_chunks = []
for p in pages:
new_chunks.extend(chunk_text(p["text"], p["source"], p["page"]))
if not new_chunks:
print(f"No chunks extracted from {doc_path.name}")
return 0
# Load existing index
index = faiss.read_index(str(index_dir / "rag.faiss"))
with open(index_dir / "rag_chunks.pkl", "rb") as f:
existing_chunks = pickle.load(f)
# Check if already indexed (by source name)
existing_sources = {c.get("source") for c in existing_chunks}
if doc_path.name in existing_sources:
print(f"{doc_path.name} already in index, skipping")
return 0
# Generate embeddings in batches and add to index
total_new = len(new_chunks)
for start in range(0, total_new, embed_batch):
end = min(start + embed_batch, total_new)
batch_texts = [c["text"][:500] for c in new_chunks[start:end]]
embs = generate_embeddings(batch_texts, batch_size=64)
faiss.normalize_L2(embs)
index.add(embs)
del embs, batch_texts
gc.collect()
# Save updated index
existing_chunks.extend(new_chunks)
faiss.write_index(index, str(index_dir / "rag.faiss"))
with open(index_dir / "rag_chunks.pkl", "wb") as f:
pickle.dump(existing_chunks, f)
print(f"Added {total_new} chunks from {doc_path.name} (total: {len(existing_chunks)})")
return total_new
+4 -4
View File
@@ -16,7 +16,7 @@ from smeta_railway.ai.cag_context import CAG_CONTEXT
from smeta_railway.ai.embeddings import embed_query
SYSTEM_PROMPT = """Ты — инженер-сметчик, 20 лет опыта, ГЭСН/ФЕР.
SYSTEM_PROMPT = """Ты — инженер-сметчик, 20 лет опыта, все сборники ГЭСН/ФЕР (1-47).
ПРАВИЛА:
1. Отвечай ТОЛЬКО по предоставленным документам и таблицам.
@@ -24,13 +24,13 @@ SYSTEM_PROMPT = """Ты — инженер-сметчик, 20 лет опыта,
3. Числа — дословно из таблиц, без округления.
4. Если в НАЙДЕННЫХ НОРМАХ ГЭСН есть подходящие — используй их, даже при низком score.
5. "Не найдено" — только если вопрос вообще не покрыт ни таблицами, ни нормами, ни документами.
6. Приоритет: ФСНБ-2022 > приказы Минстроя > МДС > учебники.
6. Приоритет: ФСНБ-2022 > приказы Минстроя (421/пр, 812/пр, 774/пр) > МДС.
ПРИМЕРЫ:
✓ "НР = 109% от ФОТ [Приказ 812/пр, Прил.1, п.22, гр.3]"
✓ "НР = 102% от ФОТ [Приказ 812/пр, Прил.1, п.6, гр.3]" (бетонные работы)
✗ "НР обычно 100-120%" (нет ссылки, нет точного значения)
✓ "Коэффициент не применяется [ГЭСН-28, Прил.28.1, п.1.3 — нормы 28-01-155 не указаны]"
✓ "К=1.15 [Приказ 421/пр, Прил.10, Табл.1, п.5 — стеснённые условия населённых пунктов]"
✗ "Можно применить по аналогии" (домысливание)
## СПРАВОЧНЫЕ ДАННЫЕ (всегда актуальны):
+3 -2
View File
@@ -128,8 +128,9 @@ def get_coefficients(
code = gesn_code.replace("ГЭСН ", "").strip()
# Only apply coefficients to collection 28 norms
if not code.startswith("28-01-"):
# Приложение 28.1 coefficients only apply to collection 28
# For other collections, return empty (421/пр coefficients handled via CAG/RAG)
if not code.startswith("28-"):
return Coefficients(
formulas={"zt": "", "em": "", "ztm": ""},
)
+18 -10
View File
@@ -284,6 +284,7 @@ def build_rag_cmd(
pdf_dirs = [
"literature/gesn",
"literature/GESN-28_full.pdf",
"literature/supplements",
]
existing = [p for p in pdf_dirs if Path(p).exists()]
if not existing:
@@ -294,6 +295,23 @@ def build_rag_cmd(
build_rag_index(existing, out)
@app.command("add-doc")
def add_doc_cmd(
doc_path: Path = typer.Argument(..., help="Path to PDF or HTM file to add"),
index_dir: str = typer.Option(None, "--index-dir", "-i"),
):
"""Add a single document to RAG index without full rebuild."""
from smeta_railway.ai.chunker import add_to_rag_index
if not doc_path.exists():
typer.echo(f"File not found: {doc_path}", err=True)
raise typer.Exit(1)
idx_dir = index_dir or str(Path(__file__).parent / "ai/index")
added = add_to_rag_index(doc_path, idx_dir)
typer.echo(f"Added {added} chunks from {doc_path.name}")
@app.command()
def search(
query: str = typer.Argument(..., help="Work description to search for"),
@@ -320,16 +338,6 @@ def search(
)
@app.command("build-rag")
def build_rag_cmd(
pdf_dirs: list[str] = typer.Argument(..., help="PDF directories to index"),
):
"""Build RAG index from PDF documents."""
from smeta_railway.ai.rag import build_rag_index
_, chunks = build_rag_index([Path(d) for d in pdf_dirs])
typer.echo(f"RAG index built: {len(chunks)} chunks")
@app.command()
def auto(
description: str = typer.Argument(..., help="Work description in natural language"),