acupedia-api/app/features/search/service.py

147 lines
5.2 KiB
Python

from __future__ import annotations
from .repository import SearchRepository
from .schema import (
FacetBucket,
FacetDefinitionResponse,
FacetedSearchRequest,
FacetedSearchResponse,
FacetValueResponse,
FacetValuesRequest,
FacetValuesResponse,
SearchCapabilitiesResponse,
SearchResultItem,
SearchScope,
)
_DISPLAY_ACRONYMS = {
"tcm": "TCM",
"lu": "LU", "li": "LI", "st": "ST", "sp": "SP",
"ht": "HT", "si": "SI", "bl": "BL", "ki": "KI",
"pc": "PC", "sj": "SJ", "gb": "GB", "lr": "LR",
"cv": "CV", "gv": "GV",
}
_DISPLAY_MINOR_WORDS = {"a", "an", "and", "as", "at", "by", "for", "from", "in", "of", "on", "or", "the", "to", "with"}
def _facet_display_label(value: str) -> str:
"""Return a consistent UI label without changing the canonical value_key."""
text = " ".join(value.strip().split())
if not text:
return text
def format_token(token: str, index: int) -> str:
# Preserve punctuation around a word while normalizing its casing.
start = 0
end = len(token)
while start < end and not token[start].isalnum():
start += 1
while end > start and not token[end - 1].isalnum():
end -= 1
prefix, core, suffix = token[:start], token[start:end], token[end:]
if not core:
return token
lower = core.lower()
if lower in _DISPLAY_ACRONYMS:
display = _DISPLAY_ACRONYMS[lower]
elif index > 0 and lower in _DISPLAY_MINOR_WORDS:
display = lower
else:
display = lower[:1].upper() + lower[1:]
return f"{prefix}{display}{suffix}"
return " ".join(format_token(token, index) for index, token in enumerate(text.split(" ")))
class SearchService:
def __init__(self, repository: SearchRepository) -> None:
self.repository = repository
async def capabilities(
self,
scope: SearchScope | None = None,
) -> SearchCapabilitiesResponse:
effective_scope = scope or SearchScope()
facets, modules, content_kinds = await self._capability_parts(effective_scope)
return SearchCapabilitiesResponse(
modules=modules,
content_kinds=content_kinds,
facets=[
FacetDefinitionResponse(
code=item.code,
label=item.label,
category=item.category,
description=item.description,
control_type=item.control_type,
allow_multiple_values=item.allow_multiple_values,
value_source=item.value_source,
sort_order=item.sort_order,
)
for item in facets
],
)
async def _capability_parts(self, scope: SearchScope):
facets = await self.repository.list_facets(scope)
modules = await self.repository.list_modules(scope)
content_kinds = await self.repository.list_content_kinds(scope)
return facets, modules, content_kinds
async def facet_values(self, request: FacetValuesRequest) -> FacetValuesResponse:
rows = await self.repository.facet_values(
facet_code=request.facet_code,
scope=request.scope,
query=request.query,
active_filters=request.active_filters,
filter_logic=request.filter_logic,
limit=request.limit,
)
return FacetValuesResponse(
facet_code=request.facet_code,
items=[
FacetValueResponse(
value_key=row["value_key"],
label=_facet_display_label(row["label"]),
result_count=row["result_count"],
)
for row in rows
],
)
async def search(self, request: FacetedSearchRequest) -> FacetedSearchResponse:
total, rows = await self.repository.search(
scope=request.scope,
query=request.query,
filters=request.filters,
filter_logic=request.filter_logic,
sort_field=request.sort.field,
sort_direction=request.sort.direction,
page=request.page,
page_size=request.page_size,
)
return FacetedSearchResponse(
page=request.page,
page_size=request.page_size,
total=total,
items=[
SearchResultItem(
content_id=row["id"],
module_code=row["module_code"],
module_name=row["module_name"],
template_code=row["template_code"],
template_name=row["template_name"],
content_kind=row["content_kind"],
title=row["title"],
summary=row["summary"],
score=float(row["score"] or 0.0),
)
for row in rows
],
buckets=[],
)
async def reindex(self, module_codes: list[str] | None = None) -> dict[str, int]:
contents, facet_rows = await self.repository.rebuild_all(module_codes)
return {"contents_indexed": contents, "facet_rows_indexed": facet_rows}