Spaces:
Sleeping
Sleeping
Download metadata_search/qdrant_metadata.py from EnvironmentalAI/WaterScopeAI-Search: direct link, hf CLI and curl.
- Browser
- Download file 9.26 kB
-
https://huggingface.co/spaces/EnvironmentalAI/WaterScopeAI-Search/resolve/main/metadata_search/qdrant_metadata.py
- Command line
-
hf download hf://spaces/EnvironmentalAI/WaterScopeAI-Search/metadata_search/qdrant_metadata.py
-
curl -L -o qdrant_metadata.py https://huggingface.co/spaces/EnvironmentalAI/WaterScopeAI-Search/resolve/main/metadata_search/qdrant_metadata.py
9.26 kB
| """Qdrant vector index for paper metadata (title / abstract / keywords).""" | |
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import Any | |
| import numpy as np | |
| from qdrant_client import QdrantClient | |
| from qdrant_client.http import models as qmodels | |
| from metadata_search.config import ( | |
| ABSTRACT_COL, | |
| EMBEDDING_MODEL, | |
| KEYWORD_COL, | |
| METADATA_QDRANT_COLLECTION, | |
| METADATA_QDRANT_MANIFEST, | |
| METADATA_QDRANT_PATH, | |
| PAPER_CSV, | |
| TITLE_COL, | |
| ) | |
| from metadata_search.corpus import load_rows, paper_text | |
| from metadata_search.embedder import MetadataEmbedder | |
| class MetadataSearchHit: | |
| row_index: int | |
| score: float | |
| class MetadataVectorStore: | |
| """One Qdrant point per papers.csv row.""" | |
| def __init__( | |
| self, | |
| *, | |
| qdrant_path: Path = METADATA_QDRANT_PATH, | |
| collection_name: str = METADATA_QDRANT_COLLECTION, | |
| model_name: str = EMBEDDING_MODEL, | |
| title_weight: float = 2.0, | |
| abstract_weight: float = 1.0, | |
| keyword_weight: float = 1.5, | |
| batch_size: int = 64, | |
| ) -> None: | |
| self.qdrant_path = qdrant_path | |
| self.collection_name = collection_name | |
| self.model_name = model_name | |
| self.title_weight = title_weight | |
| self.abstract_weight = abstract_weight | |
| self.keyword_weight = keyword_weight | |
| self.batch_size = batch_size | |
| self.qdrant_path.mkdir(parents=True, exist_ok=True) | |
| self.client = QdrantClient(path=str(self.qdrant_path)) | |
| self.manifest_path = METADATA_QDRANT_MANIFEST | |
| def points_count(self) -> int: | |
| if not self.client.collection_exists(self.collection_name): | |
| return 0 | |
| info = self.client.get_collection(self.collection_name) | |
| return int(info.points_count or 0) | |
| def _content_hash(self, rows: list[dict[str, str]]) -> str: | |
| digest = hashlib.sha256() | |
| for row in rows: | |
| digest.update(paper_text(row).encode("utf-8")) | |
| digest.update(b"\0") | |
| digest.update(self.model_name.encode("utf-8")) | |
| digest.update( | |
| f"{self.title_weight}:{self.abstract_weight}:{self.keyword_weight}".encode("utf-8") | |
| ) | |
| return digest.hexdigest() | |
| def _load_manifest(self) -> dict[str, Any]: | |
| if not self.manifest_path.exists(): | |
| return {} | |
| return json.loads(self.manifest_path.read_text(encoding="utf-8")) | |
| def _write_manifest(self, payload: dict[str, Any]) -> None: | |
| self.manifest_path.parent.mkdir(parents=True, exist_ok=True) | |
| self.manifest_path.write_text(json.dumps(payload, indent=2), encoding="utf-8") | |
| def is_current(self, rows: list[dict[str, str]]) -> bool: | |
| manifest = self._load_manifest() | |
| if not manifest: | |
| return False | |
| if manifest.get("row_count") != len(rows): | |
| return False | |
| if manifest.get("content_hash") != self._content_hash(rows): | |
| return False | |
| if manifest.get("model_name") != self.model_name: | |
| return False | |
| return self.points_count() == len(rows) | |
| def build_weighted_vectors(self, rows: list[dict[str, str]]) -> list[list[float]]: | |
| embedder = MetadataEmbedder(self.model_name, batch_size=self.batch_size) | |
| title_texts = [str(row.get(TITLE_COL) or "") for row in rows] | |
| abstract_texts = [str(row.get(ABSTRACT_COL) or "") for row in rows] | |
| keyword_texts = [str(row.get(KEYWORD_COL) or "") for row in rows] | |
| field_texts = title_texts + abstract_texts + keyword_texts | |
| field_embeddings = np.asarray( | |
| embedder.embed_documents(field_texts), | |
| dtype=float, | |
| ) | |
| count = len(rows) | |
| title_embeddings = field_embeddings[:count] | |
| abstract_embeddings = field_embeddings[count : 2 * count] | |
| keyword_embeddings = field_embeddings[2 * count :] | |
| title_mask = np.asarray([bool(text.strip()) for text in title_texts], dtype=float)[:, None] | |
| abstract_mask = np.asarray([bool(text.strip()) for text in abstract_texts], dtype=float)[:, None] | |
| keyword_mask = np.asarray([bool(text.strip()) for text in keyword_texts], dtype=float)[:, None] | |
| combined = ( | |
| self.title_weight * title_embeddings * title_mask | |
| + self.abstract_weight * abstract_embeddings * abstract_mask | |
| + self.keyword_weight * keyword_embeddings * keyword_mask | |
| ) | |
| norms = np.linalg.norm(combined, axis=1, keepdims=True) | |
| combined = np.divide(combined, norms, out=np.zeros_like(combined), where=norms != 0) | |
| return combined.tolist() | |
| def reset_collection(self, vector_size: int) -> None: | |
| if self.client.collection_exists(self.collection_name): | |
| self.client.delete_collection(self.collection_name) | |
| self.client.create_collection( | |
| collection_name=self.collection_name, | |
| vectors_config=qmodels.VectorParams( | |
| size=vector_size, | |
| distance=qmodels.Distance.COSINE, | |
| ), | |
| ) | |
| def upsert_rows(self, rows: list[dict[str, str]], vectors: list[list[float]]) -> None: | |
| if len(rows) != len(vectors): | |
| raise ValueError("rows and vectors length mismatch") | |
| if not rows: | |
| raise ValueError("No rows to index") | |
| vector_size = len(vectors[0]) | |
| self.reset_collection(vector_size) | |
| points: list[qmodels.PointStruct] = [] | |
| for row_index, (row, vector) in enumerate(zip(rows, vectors, strict=True)): | |
| points.append( | |
| qmodels.PointStruct( | |
| id=row_index, | |
| vector=vector, | |
| payload={ | |
| "row_index": row_index, | |
| "title": (row.get(TITLE_COL) or "").strip(), | |
| "year": (row.get("PY") or "").strip(), | |
| "txt_file": (row.get("TXT_file") or row.get("txt_file") or "").strip(), | |
| }, | |
| ) | |
| ) | |
| batch = 1000 | |
| for start in range(0, len(points), batch): | |
| end = min(start + batch, len(points)) | |
| self.client.upsert( | |
| collection_name=self.collection_name, | |
| points=points[start:end], | |
| ) | |
| print(f"Qdrant indexing: {end}/{len(points)} points") | |
| self._write_manifest( | |
| { | |
| "csv_path": str(Path(PAPER_CSV).resolve()), | |
| "model_name": self.model_name, | |
| "row_count": len(rows), | |
| "content_hash": self._content_hash(rows), | |
| "title_weight": self.title_weight, | |
| "abstract_weight": self.abstract_weight, | |
| "keyword_weight": self.keyword_weight, | |
| "collection_name": self.collection_name, | |
| "qdrant_path": str(self.qdrant_path.resolve()), | |
| } | |
| ) | |
| def rebuild(self, rows: list[dict[str, str]] | None = None, *, force: bool = False) -> dict[str, Any]: | |
| rows = rows if rows is not None else load_rows(PAPER_CSV) | |
| if not force and self.is_current(rows): | |
| return { | |
| "rebuilt": False, | |
| "row_count": len(rows), | |
| "points_count": self.points_count(), | |
| "message": "Metadata vector index is already up to date.", | |
| } | |
| vectors = self.build_weighted_vectors(rows) | |
| self.upsert_rows(rows, vectors) | |
| return { | |
| "rebuilt": True, | |
| "row_count": len(rows), | |
| "points_count": self.points_count(), | |
| "model_name": self.model_name, | |
| "qdrant_path": str(self.qdrant_path.resolve()), | |
| } | |
| def search(self, query_vector: list[float], *, limit: int) -> list[MetadataSearchHit]: | |
| if not self.client.collection_exists(self.collection_name): | |
| return [] | |
| response = self.client.query_points( | |
| collection_name=self.collection_name, | |
| query=query_vector, | |
| limit=limit, | |
| with_payload=True, | |
| ) | |
| hits: list[MetadataSearchHit] = [] | |
| for point in response.points: | |
| payload = point.payload or {} | |
| row_index = int(payload.get("row_index", point.id)) | |
| hits.append( | |
| MetadataSearchHit( | |
| row_index=row_index, | |
| score=float(point.score or 0.0), | |
| ) | |
| ) | |
| return hits | |
| def semantic_scores(self, query_vector: list[float], row_count: int) -> list[float]: | |
| """Cosine similarity for every row (via Qdrant top-N over full collection).""" | |
| scores = [0.0] * row_count | |
| if row_count <= 0: | |
| return scores | |
| for hit in self.search(query_vector, limit=row_count): | |
| if 0 <= hit.row_index < row_count: | |
| scores[hit.row_index] = hit.score | |
| return scores | |