File size: 8,120 Bytes
9c940cd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 | #!/usr/bin/env python3
"""
Load CVE-KGRAG chunks into Qdrant with dense (transformer) + sparse (BM25) vectors.
Standalone — does not require the upstream CVE-KGRAG codebase. Creates four
collections: cve_chunks, mitre_techniques, capec_patterns, cwe_entries.
Each point carries a named "dense" vector (640-dim by default, microsoft/harrier-oss-v1-270m)
and a named "sparse" vector encoded from bm25/vocab.json.
Resumes from checkpoint at <kb-dir>/bm25/qdrant_checkpoint.json so you can re-run
after an interruption without re-encoding everything.
Usage:
python load_qdrant.py --kb-dir ./data/knowledge_base \
--qdrant-url http://localhost:6333 \
--model microsoft/harrier-oss-v1-270m
"""
from __future__ import annotations
import argparse
import json
import logging
import math
import re
import sys
import uuid
from collections import Counter
from pathlib import Path
from typing import Any, Dict, Iterable, List, Tuple
from qdrant_client import QdrantClient
from qdrant_client.models import (
Distance, PointStruct, SparseIndexParams, SparseVector,
SparseVectorParams, VectorParams,
)
from sentence_transformers import SentenceTransformer
from tqdm import tqdm
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
log = logging.getLogger("load_qdrant")
COLLECTIONS = {
"cve": "cve_chunks",
"mitre": "mitre_techniques",
"capec": "capec_patterns",
"cwe": "cwe_entries",
}
CHUNK_FILES = {
"cve": "rag_exports/cve_chunks.json",
"mitre": "rag_exports/mitre_chunks.json",
"capec": "rag_exports/capec_chunks.json",
"cwe": "rag_exports/cwe_chunks.json",
}
DENSE = "dense"
SPARSE = "sparse"
TOKEN_RE = re.compile(r"[a-z0-9][a-z0-9_-]*", re.IGNORECASE)
K1 = 1.5
B = 0.75
def tokenize(text: str) -> List[str]:
return [t.lower() for t in TOKEN_RE.findall(text or "")]
def point_uuid(chunk_id: str) -> str:
return str(uuid.uuid5(uuid.NAMESPACE_URL, chunk_id))
class SparseEncoder:
"""BM25-weighted sparse vectors using the prebuilt vocab.json."""
def __init__(self, vocab_path: Path, avgdl: float = 200.0) -> None:
with vocab_path.open("r", encoding="utf-8") as f:
raw = json.load(f)
self.token_to_id = {t: int(v["id"]) for t, v in raw.items()}
self.idf = {int(v["id"]): float(v["idf"]) for v in raw.values()}
self.avgdl = avgdl
def encode(self, text: str) -> SparseVector:
tokens = tokenize(text)
dl = len(tokens) or 1
tf = Counter(tokens)
indices: List[int] = []
values: List[float] = []
for tok, count in tf.items():
tid = self.token_to_id.get(tok)
if tid is None:
continue
num = count * (K1 + 1)
den = count + K1 * (1 - B + B * dl / self.avgdl)
indices.append(tid)
values.append(self.idf[tid] * num / den)
return SparseVector(indices=indices, values=values)
def ensure_collections(client: QdrantClient, dense_dim: int) -> None:
existing = {c.name for c in client.get_collections().collections}
for name in COLLECTIONS.values():
if name in existing:
log.info(f" {name} already exists")
continue
client.create_collection(
collection_name=name,
vectors_config={DENSE: VectorParams(size=dense_dim, distance=Distance.COSINE)},
sparse_vectors_config={SPARSE: SparseVectorParams(index=SparseIndexParams())},
)
log.info(f" created {name}")
def sanitize_payload(p: Dict[str, Any]) -> Dict[str, Any]:
"""Qdrant indexes scalars and flat lists fine; nested dicts become JSON strings."""
out: Dict[str, Any] = {}
for k, v in p.items():
if isinstance(v, (str, int, float, bool)) or v is None:
out[k] = v
elif isinstance(v, list) and all(isinstance(x, (str, int, float, bool)) for x in v):
out[k] = v
else:
out[k] = json.dumps(v, ensure_ascii=False)
return out
def upsert_collection(
client: QdrantClient,
collection: str,
chunks: List[Dict[str, Any]],
dense_model: SentenceTransformer,
sparse: SparseEncoder,
*,
batch: int = 2000,
resume_from: int = 0,
) -> int:
total = len(chunks)
log.info(f" → {collection}: {total - resume_from:,} / {total:,} chunks to encode")
for start in tqdm(range(resume_from, total, batch), desc=collection):
end = min(start + batch, total)
slab = chunks[start:end]
texts = [c["text"] for c in slab]
dense = dense_model.encode(texts, batch_size=128, show_progress_bar=False,
convert_to_numpy=True, normalize_embeddings=True)
points = []
for c, d in zip(slab, dense):
points.append(PointStruct(
id=point_uuid(c["id"]),
vector={
DENSE: d.tolist(),
SPARSE: sparse.encode(c["text"]),
},
payload={**sanitize_payload(c.get("payload") or {}), "chunk_id": c["id"]},
))
client.upsert(collection_name=collection, points=points)
yield end
def load_chunks(path: Path) -> List[Dict[str, Any]]:
with path.open("r", encoding="utf-8") as f:
return json.load(f)
def main() -> int:
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--kb-dir", required=True, type=Path,
help="Knowledge-base root (containing rag_exports/ and bm25/)")
p.add_argument("--qdrant-url", default="http://localhost:6333")
p.add_argument("--qdrant-api-key", default=None)
p.add_argument("--model", default="microsoft/harrier-oss-v1-270m",
help="HF sentence-transformers model for dense vectors")
p.add_argument("--device", default=None, help="cuda|cpu (auto if omitted)")
p.add_argument("--batch", type=int, default=2000)
p.add_argument("--recreate", action="store_true",
help="Drop and recreate collections before loading")
args = p.parse_args()
if not (args.kb_dir / "rag_exports").is_dir():
log.error(f"--kb-dir missing rag_exports/: {args.kb_dir}")
return 2
log.info(f"Loading dense model: {args.model}")
dense_model = SentenceTransformer(args.model, device=args.device)
dense_dim = dense_model.get_sentence_embedding_dimension()
log.info(f" dim={dense_dim}")
log.info("Loading sparse encoder")
sparse = SparseEncoder(args.kb_dir / "bm25" / "vocab.json")
client = QdrantClient(url=args.qdrant_url, api_key=args.qdrant_api_key, timeout=60)
if args.recreate:
log.info("Recreating collections")
for name in COLLECTIONS.values():
try:
client.delete_collection(name)
except Exception:
pass
ensure_collections(client, dense_dim)
ckpt_path = args.kb_dir / "bm25" / "qdrant_checkpoint.json"
ckpt: Dict[str, int] = {}
if ckpt_path.exists():
ckpt = json.loads(ckpt_path.read_text())
log.info(f"Resuming from checkpoint: {ckpt}")
for key, rel in CHUNK_FILES.items():
path = args.kb_dir / rel
if not path.exists():
log.warning(f" {path} missing, skipping {key}")
continue
chunks = load_chunks(path)
col = COLLECTIONS[key]
resume = ckpt.get(col, 0) if not args.recreate else 0
if resume >= len(chunks):
log.info(f" {col}: already complete ({resume:,}/{len(chunks):,})")
continue
for done in upsert_collection(
client, col, chunks, dense_model, sparse,
batch=args.batch, resume_from=resume,
):
ckpt[col] = done
ckpt_path.write_text(json.dumps(ckpt))
log.info(f" {col}: complete")
log.info("Done. Counts:")
for name in COLLECTIONS.values():
info = client.get_collection(name)
log.info(f" {name}: {info.points_count:,} points")
return 0
if __name__ == "__main__":
sys.exit(main())
|