feat: семантический поиск расценок ГЭСН (Уровень 1)
- ai/embeddings.py: генерация embedding через OpenAI API, FAISS индекс - ai/search.py: GESNSearch — cosine similarity, фильтр по сборнику - CLI: smeta build-index, smeta search "описание работ" - pyproject.toml: optional deps [ai] = faiss-cpu + openai Для работы нужен OPENAI_API_KEY (embedding text-embedding-3-small) Индекс строится один раз, поиск — локальный через FAISS Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -16,6 +16,7 @@ dependencies = [
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = ["pytest>=8.0"]
|
||||
ai = ["faiss-cpu>=1.7", "openai>=1.0"]
|
||||
|
||||
[project.scripts]
|
||||
smeta = "smeta_railway.cli:app"
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
"""
|
||||
Embedding generation and FAISS index for semantic search over GESN norms.
|
||||
|
||||
Supports two backends:
|
||||
- OpenAI API (text-embedding-3-small) — requires OPENAI_API_KEY
|
||||
- Z.AI proxy (Anthropic-compatible) — requires SMETA_LLM_TOKEN
|
||||
- sentence-transformers (local, no API) — fallback
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import pickle
|
||||
from pathlib import Path
|
||||
|
||||
import faiss
|
||||
import numpy as np
|
||||
|
||||
|
||||
# Default embedding dimension for text-embedding-3-small
|
||||
EMBEDDING_DIM = 1536
|
||||
|
||||
INDEX_DIR = Path(__file__).parent / "index"
|
||||
|
||||
|
||||
def _get_openai_client():
|
||||
"""Get OpenAI client (or compatible proxy)."""
|
||||
from openai import OpenAI
|
||||
|
||||
api_key = os.environ.get("OPENAI_API_KEY") or os.environ.get("SMETA_LLM_TOKEN")
|
||||
base_url = os.environ.get("OPENAI_BASE_URL")
|
||||
|
||||
if not api_key:
|
||||
raise RuntimeError(
|
||||
"Set OPENAI_API_KEY or SMETA_LLM_TOKEN environment variable"
|
||||
)
|
||||
|
||||
return OpenAI(api_key=api_key, base_url=base_url)
|
||||
|
||||
|
||||
def extract_norm_texts(resources_path: str | Path) -> list[dict]:
|
||||
"""Extract (code, text) pairs from resources.json for embedding."""
|
||||
with open(resources_path, encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
|
||||
norms = []
|
||||
for code, info in data.items():
|
||||
if "error" in info:
|
||||
continue
|
||||
|
||||
name = info.get("norm_name", "")
|
||||
unit = info.get("unit", "")
|
||||
if not name:
|
||||
continue
|
||||
|
||||
# Build rich text for embedding
|
||||
parts = [f"ГЭСН {code}", name]
|
||||
if unit:
|
||||
parts.append(f"Единица: {unit}")
|
||||
|
||||
# Add machine names for context
|
||||
machines = info.get("machines", [])
|
||||
if machines:
|
||||
m_names = [m["name"] for m in machines[:5]]
|
||||
parts.append(f"Машины: {', '.join(m_names)}")
|
||||
|
||||
# Add material names
|
||||
materials = info.get("materials", [])
|
||||
if materials:
|
||||
mat_names = [m["name"] for m in materials[:5]]
|
||||
parts.append(f"Материалы: {', '.join(mat_names)}")
|
||||
|
||||
norms.append({
|
||||
"code": code,
|
||||
"name": name,
|
||||
"unit": unit or "",
|
||||
"text": ". ".join(parts),
|
||||
"collection": code.split("-")[0],
|
||||
})
|
||||
|
||||
return norms
|
||||
|
||||
|
||||
def generate_embeddings_openai(
|
||||
texts: list[str],
|
||||
model: str = "text-embedding-3-small",
|
||||
batch_size: int = 100,
|
||||
) -> np.ndarray:
|
||||
"""Generate embeddings via OpenAI API."""
|
||||
client = _get_openai_client()
|
||||
all_embeddings = []
|
||||
|
||||
for i in range(0, len(texts), batch_size):
|
||||
batch = texts[i:i + batch_size]
|
||||
response = client.embeddings.create(input=batch, model=model)
|
||||
batch_embs = [item.embedding for item in response.data]
|
||||
all_embeddings.extend(batch_embs)
|
||||
|
||||
if (i // batch_size) % 10 == 0:
|
||||
print(f" Embedded {i + len(batch)}/{len(texts)}")
|
||||
|
||||
return np.array(all_embeddings, dtype=np.float32)
|
||||
|
||||
|
||||
def build_index(
|
||||
resources_path: str | Path,
|
||||
output_dir: str | Path | None = None,
|
||||
model: str = "text-embedding-3-small",
|
||||
) -> tuple[faiss.IndexFlatIP, list[dict]]:
|
||||
"""Build FAISS index from resources.json."""
|
||||
output_dir = Path(output_dir or INDEX_DIR)
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
print("Extracting norm texts...")
|
||||
norms = extract_norm_texts(resources_path)
|
||||
print(f" {len(norms)} norms extracted")
|
||||
|
||||
texts = [n["text"] for n in norms]
|
||||
|
||||
print(f"Generating embeddings ({model})...")
|
||||
embeddings = generate_embeddings_openai(texts, model=model)
|
||||
|
||||
# Normalize for cosine similarity (IP = cosine on normalized vectors)
|
||||
faiss.normalize_L2(embeddings)
|
||||
|
||||
# Build FAISS index
|
||||
dim = embeddings.shape[1]
|
||||
index = faiss.IndexFlatIP(dim)
|
||||
index.add(embeddings)
|
||||
|
||||
# Save
|
||||
faiss.write_index(index, str(output_dir / "gesn.faiss"))
|
||||
with open(output_dir / "norms.pkl", "wb") as f:
|
||||
pickle.dump(norms, f)
|
||||
|
||||
print(f"Index saved: {output_dir}/gesn.faiss ({len(norms)} norms, dim={dim})")
|
||||
return index, norms
|
||||
|
||||
|
||||
def load_index(
|
||||
index_dir: str | Path | None = None,
|
||||
) -> tuple[faiss.IndexFlatIP, list[dict]]:
|
||||
"""Load existing FAISS index."""
|
||||
index_dir = Path(index_dir or INDEX_DIR)
|
||||
|
||||
index = faiss.read_index(str(index_dir / "gesn.faiss"))
|
||||
with open(index_dir / "norms.pkl", "rb") as f:
|
||||
norms = pickle.load(f)
|
||||
|
||||
return index, norms
|
||||
@@ -0,0 +1,118 @@
|
||||
"""
|
||||
Semantic search over GESN norms using FAISS index.
|
||||
|
||||
Usage:
|
||||
from smeta_railway.ai.search import GESNSearch
|
||||
|
||||
search = GESNSearch("resources.json")
|
||||
results = search.find("очистка щебня машинами", top_k=5)
|
||||
for r in results:
|
||||
print(f"{r['code']}: {r['name']} (score={r['score']:.3f})")
|
||||
"""
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
import faiss
|
||||
import numpy as np
|
||||
|
||||
from smeta_railway.ai.embeddings import (
|
||||
build_index,
|
||||
generate_embeddings_openai,
|
||||
load_index,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class SearchResult:
|
||||
code: str
|
||||
name: str
|
||||
unit: str
|
||||
score: float
|
||||
collection: str
|
||||
|
||||
|
||||
class GESNSearch:
|
||||
"""Semantic search over GESN norms."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
resources_path: str | Path | None = None,
|
||||
index_dir: str | Path | None = None,
|
||||
):
|
||||
self.index_dir = Path(index_dir) if index_dir else None
|
||||
|
||||
# Try loading existing index
|
||||
try:
|
||||
idx_dir = self.index_dir or Path(__file__).parent / "index"
|
||||
self.index, self.norms = load_index(idx_dir)
|
||||
except FileNotFoundError:
|
||||
if resources_path:
|
||||
print("Index not found, building...")
|
||||
self.index, self.norms = build_index(
|
||||
resources_path, self.index_dir
|
||||
)
|
||||
else:
|
||||
raise FileNotFoundError(
|
||||
"No FAISS index found. Run: smeta build-index"
|
||||
)
|
||||
|
||||
def find(
|
||||
self,
|
||||
query: str,
|
||||
top_k: int = 5,
|
||||
collection: str | None = None,
|
||||
min_score: float = 0.0,
|
||||
) -> list[SearchResult]:
|
||||
"""
|
||||
Search for GESN norms matching the query.
|
||||
|
||||
Args:
|
||||
query: natural language description of work
|
||||
top_k: number of results to return
|
||||
collection: filter by collection number (e.g. "28")
|
||||
min_score: minimum similarity score (0-1)
|
||||
|
||||
Returns:
|
||||
list of SearchResult sorted by score descending
|
||||
"""
|
||||
# Embed query
|
||||
query_emb = generate_embeddings_openai([query])
|
||||
faiss.normalize_L2(query_emb)
|
||||
|
||||
# Search (get more results if filtering)
|
||||
search_k = top_k * 5 if collection else top_k * 2
|
||||
scores, indices = self.index.search(query_emb, min(search_k, len(self.norms)))
|
||||
|
||||
results = []
|
||||
for score, idx in zip(scores[0], indices[0]):
|
||||
if idx < 0 or score < min_score:
|
||||
continue
|
||||
|
||||
norm = self.norms[idx]
|
||||
|
||||
# Filter by collection
|
||||
if collection and norm["collection"] != collection:
|
||||
continue
|
||||
|
||||
results.append(SearchResult(
|
||||
code=norm["code"],
|
||||
name=norm["name"],
|
||||
unit=norm["unit"],
|
||||
score=float(score),
|
||||
collection=norm["collection"],
|
||||
))
|
||||
|
||||
if len(results) >= top_k:
|
||||
break
|
||||
|
||||
return results
|
||||
|
||||
def find_by_code(self, code: str) -> dict | None:
|
||||
"""Find norm by exact code."""
|
||||
code = code.replace("ГЭСН ", "").strip()
|
||||
for norm in self.norms:
|
||||
if norm["code"] == code:
|
||||
return norm
|
||||
return None
|
||||
@@ -232,6 +232,50 @@ def ks3(
|
||||
typer.echo(f"КС-3 saved: {out}")
|
||||
|
||||
|
||||
@app.command("build-index")
|
||||
def build_index_cmd(
|
||||
resources_json: Path = typer.Argument(
|
||||
"resources.json", help="Path to resources.json"
|
||||
),
|
||||
output_dir: str | None = typer.Option(None, "--output-dir", "-o"),
|
||||
):
|
||||
"""Build FAISS search index from resources.json."""
|
||||
from smeta_railway.ai.embeddings import build_index
|
||||
|
||||
if not resources_json.exists():
|
||||
typer.echo(f"Error: {resources_json} not found", err=True)
|
||||
raise typer.Exit(1)
|
||||
|
||||
_, norms = build_index(resources_json, output_dir)
|
||||
typer.echo(f"Index built: {len(norms)} norms")
|
||||
|
||||
|
||||
@app.command()
|
||||
def search(
|
||||
query: str = typer.Argument(..., help="Work description to search for"),
|
||||
top_k: int = typer.Option(5, "--top", "-k"),
|
||||
collection: str | None = typer.Option(None, "--collection", "-c",
|
||||
help="Filter by collection (e.g. '28')"),
|
||||
resources_json: str = typer.Option("resources.json", "--resources"),
|
||||
):
|
||||
"""Search GESN norms by work description."""
|
||||
from smeta_railway.ai.search import GESNSearch
|
||||
|
||||
s = GESNSearch(resources_path=resources_json)
|
||||
results = s.find(query, top_k=top_k, collection=collection)
|
||||
|
||||
if not results:
|
||||
typer.echo("Ничего не найдено")
|
||||
return
|
||||
|
||||
for i, r in enumerate(results, 1):
|
||||
typer.echo(
|
||||
f" {i}. ГЭСН {r.code}: {r.name[:70]}"
|
||||
f"{'...' if len(r.name) > 70 else ''}"
|
||||
f" [{r.unit}] (score={r.score:.3f})"
|
||||
)
|
||||
|
||||
|
||||
def _resolve_path(path_str: str, base_dir: Path) -> Path:
|
||||
"""Resolve path relative to base_dir if not absolute."""
|
||||
p = Path(path_str)
|
||||
|
||||
Reference in New Issue
Block a user