Files
netbox/vinogorod/scripts/3_ingest_qdrant.py
T
hermes bbf8b20802 vinogorod: проект СКС «Винный город» — скрипты, документация, снимки справочников NetBox
- скрипты: экспорт справочников (export_netbox_refs) и портовой модели
  (export_netbox_inventory) для составления CSV-импорта устройств/соединений
- docs: CSV-снимки справочников + inventory JSON (2026-10-12, сайт «Винный город»)
- статус/план/конспекты проекта; .gitignore исключает .venv, skc_pdfs, skc_texts
2026-10-12 05:41:30 +00:00

132 lines
5.0 KiB
Python
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
Шаг 3: Инжект чанков СКС в Qdrant (коллекция skc_vinny_gorod).
Вход : каталог с <name>.json чанками (по умолчанию skc_chunks/)
Действия:
1. Создаёт Qdrant-коллекцию `skc_vinny_gorod` (dense 1024d COSINE + sparse BM25),
если её нет (или с --recreate пересоздаёт).
2. Для каждого чанка получает dense-эмбеддинг (bge-m3 через Ollama).
3. Пишет point в Qdrant с payload.
Управление:
--recreate пересоздать коллекцию (удалить все точки)
--model embedding-модель Ollama (по умолчанию bge-m3)
--ollama-url (по умолчанию http://localhost:11434/api/embeddings)
Замечание: sparse (BM25) рассчитывается на этапе поиска search-api/icarus,
поэтому здесь пишем только dense + payload. Если обнаружите, что search-api
ждёт sparse при write — переключиться на bulk_wiki_ingest_ollama.py схему.
"""
import sys, json, time, re, hashlib, pathlib
import requests
from qdrant_client import QdrantClient, models
QDRANT_URL = "http://localhost:6333"
COLLECTION = "skc_vinny_gorod"
OLLAMA_URL = "http://localhost:11434/api/embeddings"
OLLAMA_MODEL = "bge-m3"
DENSE = "dense"
SPARSE = "sparse"
def sanitize_text(text: str) -> str:
text = re.sub(r'data:image/[a-zA-Z]+;base64,[A-Za-z0-9+/=]+', '[base64-data]', text)
text = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]', '', text)
text = re.sub(r' +', ' ', text)
text = re.sub(r'\n{4,}', '\n\n\n', text)
return text.strip()
def get_embedding(text: str):
clean = sanitize_text(text)
if not clean:
return None
r = requests.post(OLLAMA_URL, json={"model": OLLAMA_MODEL, "prompt": clean}, timeout=90)
if r.status_code == 200:
return r.json().get("embedding")
print(f" ❌ Ollama {r.status_code}: {r.text[:200]}")
return None
def ensure_collection(client, recreate: bool):
if recreate:
client.delete_collection(COLLECTION)
print(f"[i] коллекция {COLLECTION} удалена (recreate)")
if COLLECTION not in [c.name for c in client.get_collections().collections]:
client.create_collection(
collection_name=COLLECTION,
vectors_config={DENSE: models.VectorParams(
size=1024, distance=models.Distance.COSINE,
)},
sparse_vectors_config={SPARSE: models.SparseVectorParams(
index=models.SparseIndexParams(on_disk=True),
)},
)
print(f"[+] коллекция {COLLECTION} создана (dense 1024d COSINE + sparse BM25)")
return COLLECTION
def main() -> int:
args = sys.argv[1:]
chunk_dir = pathlib.Path(args[0] if args else "skc_chunks")
recreate = "--recreate" in args
if "--model" in args:
global OLLAMA_MODEL
OLLAMA_MODEL = args[args.index("--model") + 1]
client = QdrantClient(QDRANT_URL)
ensure_collection(client, recreate)
existing = set()
try:
existing = {p.payload.get("doc_id") for p in
client.scroll(COLLECTION, with_payload=["doc_id"], limit=100000)[0]}
except Exception:
pass
jsons = sorted(chunk_dir.glob("*.json"))
jsons = [j for j in jsons if j.name != "manifest.json"]
if not jsons:
print(f"[!] Нет чанков в {chunk_dir}")
return 1
total, skipped, failed = 0, 0, 0
for jp in jsons:
recs = json.loads(jp.read_text(encoding="utf-8"))
doc_id = jp.stem
points = []
for rec in recs:
text = rec.get("text", "")
if not text.strip():
continue
meta = rec.get("meta", {})
did = f"{doc_id}::c{meta.get('chunk_index', 0)}"
if did in existing:
skipped += 1
continue
emb = get_embedding(text)
if emb is None:
failed += 1
continue
points.append(models.PointStruct(
id=hashlib.sha256(did.encode()).hexdigest()[:32],
vector={DENSE: emb},
payload={"doc_id": did, "text": text, "source": meta.get("source", f"{doc_id}.md"),
"collection": COLLECTION, **meta},
))
if points:
client.upsert(COLLECTION, points)
total += len(points)
print(f"[OK] {doc_id}: {len(points)} точек")
else:
print(f"[i] {doc_id}: нечего добавлять ({skipped} пропущено)")
time.sleep(0.2)
print(f"\nИтого: {total} новых точек, {skipped} уже были, {failed} ошибок эмбеддинга.")
print(f"Коллекция: {QDRANT_URL} / {COLLECTION}")
return 0 if failed == 0 else 2
if __name__ == "__main__":
sys.exit(main())