- OpenAI text-embedding-3-small (1536 dim) - FAISS индекс: 6094 нормы, ~10 MB - smeta build-index — построение индекса (разовое, ~$0.01) - smeta search "описание работ" — поиск top-5 ГЭСН (~$0.00002/запрос) - Точность top-1: 80%+ на тестовых запросах ж/д тематики - .env для API ключей (OpenAI + Z.AI) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
117 lines
3.8 KiB
Python
117 lines
3.8 KiB
Python
"""
|
|
Embedding generation and FAISS index for semantic search over GESN norms.
|
|
|
|
Backend: OpenAI API (text-embedding-3-small, 1536 dim).
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import pickle
|
|
from pathlib import Path
|
|
|
|
import faiss
|
|
import numpy as np
|
|
|
|
INDEX_DIR = Path(__file__).parent / "index"
|
|
DEFAULT_MODEL = "text-embedding-3-small"
|
|
EMBEDDING_DIM = 1536
|
|
|
|
|
|
def _get_client():
|
|
from openai import OpenAI
|
|
api_key = os.environ.get("OPENAI_API_KEY")
|
|
if not api_key:
|
|
raise RuntimeError("Set OPENAI_API_KEY environment variable")
|
|
return OpenAI(api_key=api_key)
|
|
|
|
|
|
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
|
|
|
|
parts = [f"ГЭСН {code}", name]
|
|
if unit:
|
|
parts.append(f"Единица: {unit}")
|
|
machines = info.get("machines", [])
|
|
if machines:
|
|
parts.append(f"Машины: {', '.join(m['name'] for m in machines[:5])}")
|
|
materials = info.get("materials", [])
|
|
if materials:
|
|
parts.append(f"Материалы: {', '.join(m['name'] for m in materials[:5])}")
|
|
|
|
norms.append({
|
|
"code": code, "name": name, "unit": unit or "",
|
|
"text": ". ".join(parts), "collection": code.split("-")[0],
|
|
})
|
|
return norms
|
|
|
|
|
|
def generate_embeddings(texts: list[str], model: str = DEFAULT_MODEL, batch_size: int = 200) -> np.ndarray:
|
|
"""Generate embeddings via OpenAI API."""
|
|
client = _get_client()
|
|
all_embs = []
|
|
for i in range(0, len(texts), batch_size):
|
|
batch = texts[i:i + batch_size]
|
|
resp = client.embeddings.create(input=batch, model=model)
|
|
all_embs.extend([item.embedding for item in resp.data])
|
|
if (i // batch_size) % 5 == 0:
|
|
print(f" Embedded {i + len(batch)}/{len(texts)}")
|
|
return np.array(all_embs, dtype=np.float32)
|
|
|
|
|
|
def embed_query(query: str, model: str = DEFAULT_MODEL) -> np.ndarray:
|
|
"""Embed a single query."""
|
|
client = _get_client()
|
|
resp = client.embeddings.create(input=[query], model=model)
|
|
return np.array([resp.data[0].embedding], dtype=np.float32)
|
|
|
|
|
|
def build_index(
|
|
resources_path: str | Path,
|
|
output_dir: str | Path | None = None,
|
|
model: str = DEFAULT_MODEL,
|
|
) -> 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")
|
|
|
|
print(f"Generating embeddings ({model})...")
|
|
embeddings = generate_embeddings([n["text"] for n in norms], model=model)
|
|
faiss.normalize_L2(embeddings)
|
|
|
|
dim = embeddings.shape[1]
|
|
index = faiss.IndexFlatIP(dim)
|
|
index.add(embeddings)
|
|
|
|
faiss.write_index(index, str(output_dir / "gesn.faiss"))
|
|
with open(output_dir / "norms.pkl", "wb") as f:
|
|
pickle.dump(norms, f)
|
|
with open(output_dir / "config.json", "w") as f:
|
|
json.dump({"model": model, "dim": dim, "count": len(norms)}, f)
|
|
|
|
print(f"Index saved: {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
|