Implemented Sentence-Transformer (Setup, Backend & Frontend) => downloading custom torch wheel to not pull gpu packages

This commit is contained in:
Kazgatari
2026-06-12 12:10:47 +02:00
parent ecc6aabfa3
commit bca5bf74bf
12 changed files with 1250 additions and 27 deletions
+86
View File
@@ -255,3 +255,89 @@ def _datetime_str_or_none(value: Any) -> str | None:
if len(text) == 10:
return f"{text}T00:00:00Z"
return text
async def vector_search_topics(
*,
query: str,
limit: int = 25,
) -> TopicsListResponse:
"""
Perform a semantic similarity search on the topicvectors index.
"""
try:
from inse.integrations import elasticsearch
from inse.util import get_model
except Exception as exc:
logger.exception("Failed to load elasticsearch integration.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail=f"Failed to load elasticsearch integration: {exc}"
)
# 1. Vectorize query
try:
model = get_model()
query_vector = model.encode(query).tolist()
except Exception as exc:
logger.exception("Failed to encode query text.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail=f"Failed to encode query text: {exc}"
)
# 2. Query Elasticsearch
body = {
"knn": {
"field": "vector",
"query_vector": query_vector,
"k": limit,
"num_candidates": 100
}
}
try:
raw_results = elasticsearch.search(
index="topicvectors",
body=body,
cluster="nes"
)
except Exception as exc:
logger.exception("Elasticsearch vector search failed.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail=f"Elasticsearch vector search failed: {exc}"
)
# 3. Format result
hits = raw_results.get("hits", {}).get("hits", [])
total = len(hits)
results = []
for hit in hits:
source = hit.get("_source", {})
# Remove vector field (dont send to frontend)
if "vector" in source:
del source["vector"]
results.append(source)
data = {
"meta": {
"count": total,
"page": 1,
"per_page": limit
},
"results": results
}
try:
normalized_data = _normalize_topics_response(data)
return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse()
except ValidationError as exc:
logger.exception("Vector search response could not be parsed.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="Vector search response could not be parsed.",
) from exc
+24
View File
@@ -111,3 +111,27 @@ async def list_topics(
sample=sample,
select=select,
)
@router.get(
"/vector-search",
operation_id="vectorSearchTopics",
response_model=TopicsListResponse,
response_model_exclude_none=True,
summary="Semantic / vector search for topics using a keyword/sentence.",
)
async def vector_search_topics(
query: Annotated[
str,
Query(description="Word or sentence to search by similarity.", min_length=1),
],
limit: Annotated[
int,
Query(description="Maximum number of topics to return.", ge=1, le=100),
] = 25,
):
return await logic.vector_search_topics(
query=query,
limit=limit,
)
+22 -1
View File
@@ -35,4 +35,25 @@ def get_persons_data(hit:dict):
source_copy["ids"] = ids_copy
author = Author.from_dict(source_copy)
return author
return author
from sentence_transformers import SentenceTransformer
# Sentence Transformer Model
_model: SentenceTransformer | None = None
def get_model():
global _model
if _model is None:
import os
# If SENTENCE_TRANSFORMERS_HOME is not set, check if container-baked /models folder is available
if "SENTENCE_TRANSFORMERS_HOME" not in os.environ:
if os.path.exists("/models"):
os.environ["SENTENCE_TRANSFORMERS_HOME"] = "/models"
os.environ["HF_HUB_OFFLINE"] = "1"
else:
# If it is set to /models, enforce offline mode as it is baked into the image
if os.environ.get("SENTENCE_TRANSFORMERS_HOME") == "/models":
os.environ["HF_HUB_OFFLINE"] = "1"
_model = SentenceTransformer("paraphrase-multilingual-mpnet-base-v2")
return _model