859596b030
wiki-sync / Publish docs/wiki to Gitea wiki (push) Failing after 28s
- .gitea/workflows/wiki.yml: на push в docs/wiki/** (и правки скриптов) запускается scripts/wiki_publish.py с секретом WIKI_TOKEN (runs-on ubuntu-24.04) - scripts/wiki_ingest_qdrant.py: страницы docs/wiki → коллекция knowledge_base (dense bge-m3 1024, payload как у индексатора vault + source для очистки), режим --search для проверки - scripts/wiki_publish.py: токен берётся также из WIKI_TOKEN (для CI)
162 lines
6.0 KiB
Python
162 lines
6.0 KiB
Python
#!/usr/bin/env python3
|
||
"""
|
||
wiki_ingest_qdrant.py — индексация docs/wiki проекта в Qdrant (knowledge_base).
|
||
|
||
Страницы вики проекта попадают в ту же коллекцию, что использует memory-os
|
||
search_api, поэтому агент находит их обычным recall-ом (контекст
|
||
«[qdrant] knowledge base»).
|
||
|
||
Схема payload — как у индексатора vault: filename, path, content, length, title,
|
||
chunk_index, chunk_total, indexed_at + source (по нему чистим старые точки).
|
||
|
||
Запуск:
|
||
python3 scripts/wiki_ingest_qdrant.py --dry-run
|
||
python3 scripts/wiki_ingest_qdrant.py
|
||
python3 scripts/wiki_ingest_qdrant.py --search "fail2ban Connect" # проверка
|
||
|
||
Окружение: OLLAMA_URL (default http://127.0.0.1:11434),
|
||
WIKI_EMBED_MODEL (default bge-m3:latest), QDRANT_URL (default http://127.0.0.1:6333),
|
||
QDRANT_COLLECTION (default knowledge_base).
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import json
|
||
import os
|
||
import re
|
||
import sys
|
||
import urllib.error
|
||
import urllib.parse
|
||
import urllib.request
|
||
import uuid
|
||
from datetime import datetime, timezone
|
||
from pathlib import Path
|
||
|
||
BASE_DIR = Path(__file__).resolve().parents[1]
|
||
WIKI_DIR = BASE_DIR / "docs" / "wiki"
|
||
SOURCE = "email-assistant/docs/wiki"
|
||
NAMESPACE = uuid.UUID("6f9619ff-8b86-d011-b42d-00cf4fc964ff")
|
||
|
||
OLLAMA_URL = os.environ.get("OLLAMA_URL", "http://127.0.0.1:11434").rstrip("/")
|
||
EMBED_MODEL = os.environ.get("WIKI_EMBED_MODEL", "bge-m3:latest")
|
||
QDRANT_URL = os.environ.get("QDRANT_URL", "http://127.0.0.1:6333").rstrip("/")
|
||
COLLECTION = os.environ.get("QDRANT_COLLECTION", "knowledge_base")
|
||
|
||
CHUNK_CHARS = int(os.environ.get("WIKI_CHUNK_CHARS", "1800"))
|
||
|
||
|
||
def _request(method: str, url: str, payload: dict | None = None) -> dict:
|
||
data = json.dumps(payload).encode("utf-8") if payload is not None else None
|
||
request = urllib.request.Request(url, data=data, method=method,
|
||
headers={"Content-Type": "application/json"})
|
||
with urllib.request.urlopen(request, timeout=120) as response:
|
||
body = response.read().decode("utf-8") or "{}"
|
||
return json.loads(body)
|
||
|
||
|
||
def embed(text: str) -> list[float]:
|
||
data = _request("POST", f"{OLLAMA_URL}/api/embeddings",
|
||
{"model": EMBED_MODEL, "prompt": text})
|
||
vector = data.get("embedding") or []
|
||
if not vector:
|
||
raise RuntimeError(f"пустой эмбеддинг от {EMBED_MODEL}")
|
||
return vector
|
||
|
||
|
||
def split_chunks(text: str) -> list[str]:
|
||
"""Резать по абзацам, склеивая до CHUNK_CHARS."""
|
||
paragraphs = [p.strip() for p in re.split(r"\n{2,}", text) if p.strip()]
|
||
chunks: list[str] = []
|
||
current = ""
|
||
for paragraph in paragraphs:
|
||
if current and len(current) + len(paragraph) + 2 > CHUNK_CHARS:
|
||
chunks.append(current)
|
||
current = paragraph
|
||
else:
|
||
current = f"{current}\n\n{paragraph}" if current else paragraph
|
||
if current:
|
||
chunks.append(current)
|
||
return chunks or [text]
|
||
|
||
|
||
def title_of(path: Path, text: str) -> str:
|
||
match = re.search(r"^title:\s*(.+)$", text, re.M)
|
||
if match:
|
||
return match.group(1).strip().strip('"')
|
||
for line in text.splitlines():
|
||
if line.startswith("# "):
|
||
return line[2:].strip()
|
||
return path.stem
|
||
|
||
|
||
def delete_old() -> int:
|
||
_request("POST", f"{QDRANT_URL}/collections/{COLLECTION}/points/delete?wait=true",
|
||
{"filter": {"must": [{"key": "source", "match": {"value": SOURCE}}]}})
|
||
return 0
|
||
|
||
|
||
def search(query: str, limit: int = 5) -> None:
|
||
vector = embed(query)
|
||
data = _request("POST", f"{QDRANT_URL}/collections/{COLLECTION}/points/search",
|
||
{"vector": {"name": "dense", "vector": vector},
|
||
"limit": limit, "with_payload": True, "with_vector": False})
|
||
for point in data.get("result", []):
|
||
payload = point.get("payload") or {}
|
||
print(f"{point.get('score', 0):.3f} {payload.get('title', '?')} "
|
||
f"[{payload.get('source', 'vault')}] {payload.get('path', '')}")
|
||
|
||
|
||
def main() -> int:
|
||
parser = argparse.ArgumentParser(description="Индексация docs/wiki в Qdrant")
|
||
parser.add_argument("--dry-run", action="store_true")
|
||
parser.add_argument("--search", default="", help="Проверочный поиск по коллекции")
|
||
args = parser.parse_args()
|
||
|
||
if args.search:
|
||
search(args.search)
|
||
return 0
|
||
|
||
files = sorted(WIKI_DIR.rglob("*.md"))
|
||
if not files:
|
||
print(f"В {WIKI_DIR} нет .md", file=sys.stderr)
|
||
return 1
|
||
|
||
points: list[dict] = []
|
||
for path in files:
|
||
text = path.read_text(encoding="utf-8")
|
||
chunks = split_chunks(text)
|
||
title = title_of(path, text)
|
||
for index, chunk in enumerate(chunks):
|
||
points.append({
|
||
"id": str(uuid.uuid5(NAMESPACE, f"{path.relative_to(BASE_DIR)}#{index}")),
|
||
"vector": {"dense": embed(chunk)},
|
||
"payload": {
|
||
"filename": path.name,
|
||
"path": str(path),
|
||
"content": chunk,
|
||
"length": str(len(chunk)),
|
||
"title": title,
|
||
"chunk_index": str(index),
|
||
"chunk_total": str(len(chunks)),
|
||
"indexed_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
||
"source": SOURCE,
|
||
},
|
||
})
|
||
|
||
if args.dry_run:
|
||
print(f"[dry] файлов={len(files)}, чанков={len(points)}")
|
||
for path in files:
|
||
print(f" • {path.relative_to(WIKI_DIR)}")
|
||
return 0
|
||
|
||
delete_old()
|
||
_request("PUT", f"{QDRANT_URL}/collections/{COLLECTION}/points?wait=true",
|
||
{"points": points})
|
||
print(f"Проиндексировано: файлов={len(files)}, чанков={len(points)} "
|
||
f"(коллекция {COLLECTION}, модель {EMBED_MODEL})")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|