From 4c244f4e6c214288ba974c076aacd0467d90fef5 Mon Sep 17 00:00:00 2001 From: anor Date: Sun, 22 Mar 2026 15:54:02 +1000 Subject: [PATCH] =?UTF-8?q?feat:=20=D1=81=D0=B5=D0=BC=D0=B0=D0=BD=D1=82?= =?UTF-8?q?=D0=B8=D1=87=D0=B5=D1=81=D0=BA=D0=B8=D0=B9=20=D0=BF=D0=BE=D0=B8?= =?UTF-8?q?=D1=81=D0=BA=20=D1=80=D0=B0=D1=81=D1=86=D0=B5=D0=BD=D0=BE=D0=BA?= =?UTF-8?q?=20=D0=93=D0=AD=D0=A1=D0=9D=20(=D0=A3=D1=80=D0=BE=D0=B2=D0=B5?= =?UTF-8?q?=D0=BD=D1=8C=201)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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) --- pyproject.toml | 1 + src/smeta_railway/ai/__init__.py | 0 src/smeta_railway/ai/embeddings.py | 149 +++++++++++++++++++++++++++++ src/smeta_railway/ai/search.py | 118 +++++++++++++++++++++++ src/smeta_railway/cli.py | 44 +++++++++ 5 files changed, 312 insertions(+) create mode 100644 src/smeta_railway/ai/__init__.py create mode 100644 src/smeta_railway/ai/embeddings.py create mode 100644 src/smeta_railway/ai/search.py diff --git a/pyproject.toml b/pyproject.toml index 4c11bff..2d861f8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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" diff --git a/src/smeta_railway/ai/__init__.py b/src/smeta_railway/ai/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/smeta_railway/ai/embeddings.py b/src/smeta_railway/ai/embeddings.py new file mode 100644 index 0000000..dc725f3 --- /dev/null +++ b/src/smeta_railway/ai/embeddings.py @@ -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 diff --git a/src/smeta_railway/ai/search.py b/src/smeta_railway/ai/search.py new file mode 100644 index 0000000..aff09df --- /dev/null +++ b/src/smeta_railway/ai/search.py @@ -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 diff --git a/src/smeta_railway/cli.py b/src/smeta_railway/cli.py index 57fc563..81be882 100644 --- a/src/smeta_railway/cli.py +++ b/src/smeta_railway/cli.py @@ -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)