Upload 5 files
Browse files- src/api/admin.py +0 -0
- src/api/agent.py +76 -76
- src/api/search.py +373 -373
src/api/admin.py
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
src/api/agent.py
CHANGED
|
@@ -1,76 +1,76 @@
|
|
| 1 |
-
"""Authenticated agent endpoint; Cloudflare is the only intended caller."""
|
| 2 |
-
|
| 3 |
-
import asyncio
|
| 4 |
-
import html
|
| 5 |
-
import re
|
| 6 |
-
import time
|
| 7 |
-
import uuid
|
| 8 |
-
|
| 9 |
-
from fastapi import APIRouter, HTTPException, Request
|
| 10 |
-
|
| 11 |
-
from src.agentcore.models import AgentRequest, AgentResponse
|
| 12 |
-
from src.agentcore.moderation import BLOCKED_ANSWER, SUPPORT_ANSWER, screen_input
|
| 13 |
-
from src.agentcore.orchestrator import _agent_query_inner, _log_agent_query
|
| 14 |
-
from src.agentcore.utils import _get_runtime_config, _normalize_whitespace, _safe_metrics_increment, _sanitize_llm_response
|
| 15 |
-
from src.services.html_sanitizer import sanitize_answer_html
|
| 16 |
-
from src.config import get_settings
|
| 17 |
-
|
| 18 |
-
router = APIRouter()
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
@router.post("", response_model=AgentResponse)
|
| 22 |
-
async def agent_query(request: Request, req: AgentRequest):
|
| 23 |
-
start_time = time.time()
|
| 24 |
-
settings = get_settings()
|
| 25 |
-
if (len(req.question) > settings.max_question_chars or
|
| 26 |
-
len(req.history) > settings.max_history_messages or
|
| 27 |
-
any(len(message.content) > settings.max_message_chars for message in req.history)):
|
| 28 |
-
raise HTTPException(status_code=422, detail="Question or history exceeds the configured text limit.")
|
| 29 |
-
supplied_id = request.headers.get("x-request-id", "")
|
| 30 |
-
request_id = supplied_id if re.fullmatch(r"[A-Za-z0-9_-]{8,80}", supplied_id) else str(uuid.uuid4())
|
| 31 |
-
question = _normalize_whitespace(req.question)
|
| 32 |
-
if not question:
|
| 33 |
-
raise HTTPException(status_code=422, detail="Question must contain text.")
|
| 34 |
-
history = list(req.history)
|
| 35 |
-
if history and history[-1].role == "user" and _normalize_whitespace(history[-1].content) == question:
|
| 36 |
-
history.pop()
|
| 37 |
-
is_canary = request.headers.get("x-libbee-canary") == "1"
|
| 38 |
-
if not is_canary:
|
| 39 |
-
_safe_metrics_increment("agent_requests")
|
| 40 |
-
verdict, response = await asyncio.gather(
|
| 41 |
-
screen_input(question),
|
| 42 |
-
_agent_query_inner(question, history, req.model, req.client_state, start_time),
|
| 43 |
-
)
|
| 44 |
-
# Deterministic refusals (injection gate) stand as they are.
|
| 45 |
-
if verdict and response.intent != "blocked":
|
| 46 |
-
response = AgentResponse(
|
| 47 |
-
answer=SUPPORT_ANSWER if verdict == "support" else BLOCKED_ANSWER,
|
| 48 |
-
intent="social" if verdict == "support" else "sensitive_blocked",
|
| 49 |
-
tools_used=["moderation_guard"],
|
| 50 |
-
model_used=response.model_used,
|
| 51 |
-
response_time=time.time() - start_time,
|
| 52 |
-
)
|
| 53 |
-
response.request_id = request_id
|
| 54 |
-
response.answer = _sanitize_llm_response(response.answer)
|
| 55 |
-
runtime_config = _get_runtime_config()
|
| 56 |
-
announcement = str(runtime_config.get("announcement", "")).strip()
|
| 57 |
-
if announcement and response.intent not in {"social_greeting", "social"}:
|
| 58 |
-
response.answer += '<div class="libbee-announcement" role="note"><strong>Announcement:</strong> ' + html.escape(announcement) + "</div>"
|
| 59 |
-
response.answer = sanitize_answer_html(response.answer)
|
| 60 |
-
if not is_canary:
|
| 61 |
-
_log_agent_query(question, response, start_time)
|
| 62 |
-
return response
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
@router.get("/test")
|
| 66 |
-
async def test():
|
| 67 |
-
return {"status": "ok"}
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
@router.get("/rag-status")
|
| 71 |
-
async def rag_status():
|
| 72 |
-
try:
|
| 73 |
-
from app import get_rag_service
|
| 74 |
-
return get_rag_service().get_stats()
|
| 75 |
-
except Exception:
|
| 76 |
-
return {"ready": False}
|
|
|
|
| 1 |
+
"""Authenticated agent endpoint; Cloudflare is the only intended caller."""
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import html
|
| 5 |
+
import re
|
| 6 |
+
import time
|
| 7 |
+
import uuid
|
| 8 |
+
|
| 9 |
+
from fastapi import APIRouter, HTTPException, Request
|
| 10 |
+
|
| 11 |
+
from src.agentcore.models import AgentRequest, AgentResponse
|
| 12 |
+
from src.agentcore.moderation import BLOCKED_ANSWER, SUPPORT_ANSWER, screen_input
|
| 13 |
+
from src.agentcore.orchestrator import _agent_query_inner, _log_agent_query
|
| 14 |
+
from src.agentcore.utils import _get_runtime_config, _normalize_whitespace, _safe_metrics_increment, _sanitize_llm_response
|
| 15 |
+
from src.services.html_sanitizer import sanitize_answer_html
|
| 16 |
+
from src.config import get_settings
|
| 17 |
+
|
| 18 |
+
router = APIRouter()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@router.post("", response_model=AgentResponse)
|
| 22 |
+
async def agent_query(request: Request, req: AgentRequest):
|
| 23 |
+
start_time = time.time()
|
| 24 |
+
settings = get_settings()
|
| 25 |
+
if (len(req.question) > settings.max_question_chars or
|
| 26 |
+
len(req.history) > settings.max_history_messages or
|
| 27 |
+
any(len(message.content) > settings.max_message_chars for message in req.history)):
|
| 28 |
+
raise HTTPException(status_code=422, detail="Question or history exceeds the configured text limit.")
|
| 29 |
+
supplied_id = request.headers.get("x-request-id", "")
|
| 30 |
+
request_id = supplied_id if re.fullmatch(r"[A-Za-z0-9_-]{8,80}", supplied_id) else str(uuid.uuid4())
|
| 31 |
+
question = _normalize_whitespace(req.question)
|
| 32 |
+
if not question:
|
| 33 |
+
raise HTTPException(status_code=422, detail="Question must contain text.")
|
| 34 |
+
history = list(req.history)
|
| 35 |
+
if history and history[-1].role == "user" and _normalize_whitespace(history[-1].content) == question:
|
| 36 |
+
history.pop()
|
| 37 |
+
is_canary = request.headers.get("x-libbee-canary") == "1"
|
| 38 |
+
if not is_canary:
|
| 39 |
+
_safe_metrics_increment("agent_requests")
|
| 40 |
+
verdict, response = await asyncio.gather(
|
| 41 |
+
screen_input(question),
|
| 42 |
+
_agent_query_inner(question, history, req.model, req.client_state, start_time),
|
| 43 |
+
)
|
| 44 |
+
# Deterministic refusals (injection gate) stand as they are.
|
| 45 |
+
if verdict and response.intent != "blocked":
|
| 46 |
+
response = AgentResponse(
|
| 47 |
+
answer=SUPPORT_ANSWER if verdict == "support" else BLOCKED_ANSWER,
|
| 48 |
+
intent="social" if verdict == "support" else "sensitive_blocked",
|
| 49 |
+
tools_used=["moderation_guard"],
|
| 50 |
+
model_used=response.model_used,
|
| 51 |
+
response_time=time.time() - start_time,
|
| 52 |
+
)
|
| 53 |
+
response.request_id = request_id
|
| 54 |
+
response.answer = _sanitize_llm_response(response.answer)
|
| 55 |
+
runtime_config = _get_runtime_config()
|
| 56 |
+
announcement = str(runtime_config.get("announcement", "")).strip()
|
| 57 |
+
if announcement and response.intent not in {"social_greeting", "social", "clarification"}:
|
| 58 |
+
response.answer += '<div class="libbee-announcement" role="note"><strong>Announcement:</strong> ' + html.escape(announcement) + "</div>"
|
| 59 |
+
response.answer = sanitize_answer_html(response.answer)
|
| 60 |
+
if not is_canary:
|
| 61 |
+
_log_agent_query(question, response, start_time)
|
| 62 |
+
return response
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@router.get("/test")
|
| 66 |
+
async def test():
|
| 67 |
+
return {"status": "ok"}
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@router.get("/rag-status")
|
| 71 |
+
async def rag_status():
|
| 72 |
+
try:
|
| 73 |
+
from app import get_rag_service
|
| 74 |
+
return get_rag_service().get_stats()
|
| 75 |
+
except Exception:
|
| 76 |
+
return {"ready": False}
|
src/api/search.py
CHANGED
|
@@ -1,373 +1,373 @@
|
|
| 1 |
-
"""PRIMO and PubMed search, with explicit filters and bounded upstream waits."""
|
| 2 |
-
import asyncio
|
| 3 |
-
import logging
|
| 4 |
-
import re
|
| 5 |
-
from typing import Optional
|
| 6 |
-
from urllib.parse import quote, urlsplit
|
| 7 |
-
|
| 8 |
-
from fastapi import APIRouter
|
| 9 |
-
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
| 10 |
-
|
| 11 |
-
logger = logging.getLogger(__name__)
|
| 12 |
-
router = APIRouter()
|
| 13 |
-
# One deadline covers all gateways, rather than one wait per region. A region
|
| 14 |
-
# selected in HF's PRIMO_API_REGION avoids even the fast discovery attempts.
|
| 15 |
-
PRIMO_REQUEST_TIMEOUT = 6.0
|
| 16 |
-
PUBMED_REQUEST_TIMEOUT = 8.0
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
class SearchRequest(BaseModel):
|
| 20 |
-
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
| 21 |
-
query: str = Field(min_length=1, max_length=1000)
|
| 22 |
-
boolean_query: Optional[str] = Field(default=None, max_length=1500)
|
| 23 |
-
source: str = Field(default="primo", pattern=r"^(primo|pubmed)$")
|
| 24 |
-
limit: int = Field(default=10, ge=1, le=20)
|
| 25 |
-
sort: str = Field(default="rank", pattern=r"^(rank|date_d|date_a)$")
|
| 26 |
-
query_field: str = Field(default="any", pattern=r"^(any|title|creator|sub)$")
|
| 27 |
-
peer_reviewed: bool = False
|
| 28 |
-
open_access: bool = False
|
| 29 |
-
year_from: Optional[str] = Field(default=None, pattern=r"^[0-9]{4}$")
|
| 30 |
-
year_to: Optional[str] = Field(default=None, pattern=r"^[0-9]{4}$")
|
| 31 |
-
resource_type: str = Field(default="articles", pattern=r"^(articles|books|both)$")
|
| 32 |
-
|
| 33 |
-
@model_validator(mode="after")
|
| 34 |
-
def validate_search(self):
|
| 35 |
-
self.boolean_query = self.boolean_query or None
|
| 36 |
-
for year in (self.year_from, self.year_to):
|
| 37 |
-
if year == "0000":
|
| 38 |
-
raise ValueError("Publication years must be between 0001 and 9999")
|
| 39 |
-
if self.year_from and self.year_to and self.year_from > self.year_to:
|
| 40 |
-
raise ValueError("year_from must not be later than year_to")
|
| 41 |
-
# Primo reserves semicolons for additional field clauses, even when
|
| 42 |
-
# percent-encoded; accepting one here changes the meaning of a query.
|
| 43 |
-
if self.source == "primo" and ";" in (self.boolean_query or self.query):
|
| 44 |
-
raise ValueError("PRIMO search terms cannot contain semicolons")
|
| 45 |
-
return self
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
def _boolean_to_primo_params(boolean_query: str, query_field: str = "any") -> str:
|
| 49 |
-
"""Preserve exact phrases and all Boolean operators in one Primo q value."""
|
| 50 |
-
if query_field not in {"any", "title", "creator", "sub"}:
|
| 51 |
-
raise ValueError("Unsupported PRIMO search field")
|
| 52 |
-
return f"q={query_field},contains,{quote(boolean_query.strip(), safe='')}"
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
def _year_bounds(req: SearchRequest) -> tuple[str, str]:
|
| 56 |
-
"""Represent an omitted bound without silently excluding older/future works."""
|
| 57 |
-
return req.year_from or "0001", req.year_to or "9999"
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
def _build_primo_search_link(title: str, record_id: Optional[str] = None,
|
| 61 |
-
context: Optional[str] = None) -> Optional[str]:
|
| 62 |
-
base = "https://khalifa.primo.exlibrisgroup.com/discovery"
|
| 63 |
-
if record_id:
|
| 64 |
-
context_param = f"&context={context}" if isinstance(context, str) and context in {"L", "PC"} else ""
|
| 65 |
-
return (
|
| 66 |
-
f"{base}/fulldisplay?docid={quote(str(record_id), safe='')}&vid=971KUOSTAR_INST:KU"
|
| 67 |
-
f"{context_param}&lang=en&tab=Everything&search_scope=MyInst_and_CI"
|
| 68 |
-
)
|
| 69 |
-
clean_title = (title or "").strip()
|
| 70 |
-
if not clean_title:
|
| 71 |
-
return None
|
| 72 |
-
return (
|
| 73 |
-
f"{base}/search?query=any,contains,{quote(clean_title, safe='')}"
|
| 74 |
-
"&tab=Everything&search_scope=MyInst_and_CI&vid=971KUOSTAR_INST:KU&lang=en"
|
| 75 |
-
)
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
def _first(value, default=""):
|
| 79 |
-
"""PNX values are normally arrays; tolerate scalar/missing metadata."""
|
| 80 |
-
if isinstance(value, list):
|
| 81 |
-
value = value[0] if value else default
|
| 82 |
-
return value if isinstance(value, str) else default
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
def _result_link(raw_link: str, fallback: Optional[str]) -> Optional[str]:
|
| 86 |
-
# PNX link fields can contain $$U<url>$$D<label>, rather than a bare URL.
|
| 87 |
-
match = re.match(r"(?:\$\$U)?(https?://[^\s]+?)(?:\$\$|$)", raw_link)
|
| 88 |
-
if not match:
|
| 89 |
-
return fallback
|
| 90 |
-
candidate = match.group(1)
|
| 91 |
-
try:
|
| 92 |
-
parsed = urlsplit(candidate)
|
| 93 |
-
if parsed.hostname and not parsed.username and not parsed.password:
|
| 94 |
-
return candidate
|
| 95 |
-
except ValueError:
|
| 96 |
-
pass
|
| 97 |
-
return fallback
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
def _pnx_section(pnx: dict, section: str) -> dict:
|
| 101 |
-
value = pnx.get(section)
|
| 102 |
-
return value if isinstance(value, dict) else {}
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
def _primo_records(data: dict, limit: int) -> list[dict]:
|
| 106 |
-
"""Normalize returned PNX metadata; never infer circulation availability."""
|
| 107 |
-
results = []
|
| 108 |
-
seen = set()
|
| 109 |
-
for doc in data.get("docs", []):
|
| 110 |
-
if not isinstance(doc, dict) or not isinstance(doc.get("pnx"), dict):
|
| 111 |
-
continue
|
| 112 |
-
pnx = doc["pnx"]
|
| 113 |
-
display = _pnx_section(pnx, "display")
|
| 114 |
-
addata = _pnx_section(pnx, "addata")
|
| 115 |
-
search = _pnx_section(pnx, "search")
|
| 116 |
-
sort = _pnx_section(pnx, "sort")
|
| 117 |
-
control = _pnx_section(pnx, "control")
|
| 118 |
-
links = _pnx_section(pnx, "links")
|
| 119 |
-
record_id = _first(control.get("recordid"), None) or _first(doc.get("id"), None)
|
| 120 |
-
title = _first(display.get("title")) or _first(addata.get("btitle") or addata.get("atitle"))
|
| 121 |
-
# A corrupt/empty item is not a real result to pad the requested count.
|
| 122 |
-
if not title:
|
| 123 |
-
continue
|
| 124 |
-
if record_id and record_id in seen:
|
| 125 |
-
continue
|
| 126 |
-
if record_id:
|
| 127 |
-
seen.add(record_id)
|
| 128 |
-
primo_url = _build_primo_search_link(title, record_id, _first(doc.get("context")))
|
| 129 |
-
creators = display.get("creator") or display.get("contributor") or addata.get("au") or []
|
| 130 |
-
if isinstance(creators, str):
|
| 131 |
-
creators = [creators]
|
| 132 |
-
if not isinstance(creators, list):
|
| 133 |
-
creators = []
|
| 134 |
-
raw_link = _first(links.get("openurl") or links.get("linktorsrc"))
|
| 135 |
-
results.append({
|
| 136 |
-
"record_id": record_id,
|
| 137 |
-
"title": title,
|
| 138 |
-
"creator": "; ".join(creator for creator in creators if isinstance(creator, str)),
|
| 139 |
-
"date": (_first(search.get("creationdate")) or _first(addata.get("risdate"))
|
| 140 |
-
or _first(addata.get("date")) or _first(sort.get("creationdate"))),
|
| 141 |
-
"type": _first(display.get("type") or addata.get("ristype")),
|
| 142 |
-
"source": _first(display.get("source") or addata.get("jtitle")),
|
| 143 |
-
"description": _first(display.get("description"))[:400],
|
| 144 |
-
"doi": _first(addata.get("doi"), None),
|
| 145 |
-
"primo_url": primo_url,
|
| 146 |
-
"link": _result_link(raw_link, primo_url),
|
| 147 |
-
"open_access": True if _first(display.get("oa")) == "free_for_read" else None,
|
| 148 |
-
"_source": "PRIMO",
|
| 149 |
-
})
|
| 150 |
-
if len(results) >= limit:
|
| 151 |
-
break
|
| 152 |
-
return results
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
def _primo_failure(message: str, code: str, status: str = "unavailable") -> dict:
|
| 156 |
-
return {"error": message, "error_code": code, "status": status,
|
| 157 |
-
"results": [], "total": 0, "source": "PRIMO"}
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
def _primo_gateways(region: str) -> tuple[str, ...]:
|
| 161 |
-
"""Allow only Ex Libris's documented gateway hosts; no custom secret target."""
|
| 162 |
-
hosts = {
|
| 163 |
-
"eu": "api-eu.hosted.exlibrisgroup.com",
|
| 164 |
-
"na": "api-na.hosted.exlibrisgroup.com",
|
| 165 |
-
"ap": "api-ap.hosted.exlibrisgroup.com",
|
| 166 |
-
"ca": "api-ca.hosted.exlibrisgroup.com",
|
| 167 |
-
"aps": "api-aps.hosted.exlibrisgroup.com",
|
| 168 |
-
"cn": "api-cn.hosted.exlibrisgroup.com.cn",
|
| 169 |
-
}
|
| 170 |
-
if region == "auto":
|
| 171 |
-
return tuple(hosts[name] for name in ("eu", "na", "ap"))
|
| 172 |
-
return (hosts[region],) if region in hosts else ()
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
async def search_primo(req: SearchRequest, api_key: str, region: str = "auto") -> dict:
|
| 176 |
-
"""Search Primo using the full preferred query and documented facet syntax."""
|
| 177 |
-
import httpx
|
| 178 |
-
|
| 179 |
-
if not api_key:
|
| 180 |
-
return _primo_failure("PRIMO results are not configured", "not_configured", "not_configured")
|
| 181 |
-
|
| 182 |
-
gateways = _primo_gateways(region)
|
| 183 |
-
if not gateways:
|
| 184 |
-
return _primo_failure("PRIMO API region is not configured correctly", "invalid_region", "not_configured")
|
| 185 |
-
|
| 186 |
-
query_params = _boolean_to_primo_params(req.boolean_query or req.query, req.query_field)
|
| 187 |
-
facets = []
|
| 188 |
-
if req.peer_reviewed:
|
| 189 |
-
facets.append("facet_tlevel,exact,peer_reviewed")
|
| 190 |
-
if req.open_access:
|
| 191 |
-
facets.append("facet_tlevel,exact,open_access")
|
| 192 |
-
if req.year_from or req.year_to:
|
| 193 |
-
year_from, year_to = _year_bounds(req)
|
| 194 |
-
facets.append(f"facet_searchcreationdate,exact,[{year_from} TO {year_to}]")
|
| 195 |
-
if req.resource_type != "both":
|
| 196 |
-
facets.append(f"facet_rtype,exact,{req.resource_type}")
|
| 197 |
-
|
| 198 |
-
# Multiple qInclude values in the same category are ANDed, so an explicit
|
| 199 |
-
# Books OR Articles request must use multiFacets for that category.
|
| 200 |
-
mixed_types = "facet_rtype,include,books|,|facet_rtype,include,articles"
|
| 201 |
-
mixed_params = f"&multiFacets={quote(mixed_types, safe='')}" if req.resource_type == "both" else ""
|
| 202 |
-
compact_query = re.sub(r'["\s-]', "", (req.boolean_query or req.query)).upper()
|
| 203 |
-
exact_identifier = bool(re.fullmatch(r"(?:[0-9]{9}[0-9X]|[0-9]{13})", compact_query))
|
| 204 |
-
controlled_vocabulary = "false" if req.query_field == "title" or exact_identifier else "true"
|
| 205 |
-
|
| 206 |
-
# qInclude accepts one value, joining ANDed facets with |,|. Repeated
|
| 207 |
-
# qInclude keys are not its documented API contract.
|
| 208 |
-
facet_params = f"&qInclude={quote('|,|'.join(facets), safe='')}" if facets else ""
|
| 209 |
-
qs = (
|
| 210 |
-
"?vid=971KUOSTAR_INST:KU&tab=Everything&scope=MyInst_and_CI"
|
| 211 |
-
f"&{query_params}&lang=en&sort={req.sort}&limit={req.limit}&offset=0"
|
| 212 |
-
f"&conVoc={controlled_vocabulary}&skipDelivery=true"
|
| 213 |
-
f"{facet_params}{mixed_params}"
|
| 214 |
-
)
|
| 215 |
-
|
| 216 |
-
deadline = asyncio.get_running_loop().time() + PRIMO_REQUEST_TIMEOUT
|
| 217 |
-
last_status = None
|
| 218 |
-
async with httpx.AsyncClient(timeout=PRIMO_REQUEST_TIMEOUT) as client:
|
| 219 |
-
for gateway in gateways:
|
| 220 |
-
remaining = deadline - asyncio.get_running_loop().time()
|
| 221 |
-
if remaining <= 0:
|
| 222 |
-
return _primo_failure("PRIMO took too long to respond; use the search link", "timeout")
|
| 223 |
-
url = f"https://{gateway}/primo/v1/search{qs}"
|
| 224 |
-
try:
|
| 225 |
-
# httpx read timeouts reset per chunk. wait_for additionally
|
| 226 |
-
# bounds the complete request, including a slowly streamed body.
|
| 227 |
-
response = await asyncio.wait_for(
|
| 228 |
-
client.get(url, headers={"Accept": "application/json", "Authorization": f"apikey {api_key}"}),
|
| 229 |
-
timeout=remaining,
|
| 230 |
-
)
|
| 231 |
-
if response.status_code != 200:
|
| 232 |
-
last_status = response.status_code
|
| 233 |
-
logger.warning("PRIMO gateway %s returned HTTP %s", gateway, response.status_code)
|
| 234 |
-
if response.status_code == 429:
|
| 235 |
-
return _primo_failure("PRIMO request limit reached; try again later", "rate_limited", "rate_limited")
|
| 236 |
-
if response.status_code == 400:
|
| 237 |
-
return _primo_failure("PRIMO could not process this search; check the search terms", "invalid_query", "error")
|
| 238 |
-
if response.status_code in (401, 403, 404):
|
| 239 |
-
continue
|
| 240 |
-
return _primo_failure("PRIMO API unavailable", "upstream_error")
|
| 241 |
-
data = response.json()
|
| 242 |
-
if not isinstance(data, dict) or not isinstance(data.get("docs"), list):
|
| 243 |
-
raise ValueError("Invalid PRIMO response")
|
| 244 |
-
results = _primo_records(data, req.limit)
|
| 245 |
-
info = data.get("info") if isinstance(data.get("info"), dict) else {}
|
| 246 |
-
raw_total = info.get("total")
|
| 247 |
-
total = None
|
| 248 |
-
# Unknown totals must stay unknown: a short page is not evidence
|
| 249 |
-
# that those records exhaust all matches in the catalogue.
|
| 250 |
-
if ((type(raw_total) is int) or
|
| 251 |
-
(isinstance(raw_total, str) and re.fullmatch(r"[0-9]+", raw_total.strip()))):
|
| 252 |
-
parsed_total = int(raw_total)
|
| 253 |
-
if parsed_total >= len(results):
|
| 254 |
-
total = parsed_total
|
| 255 |
-
if data["docs"] and not results:
|
| 256 |
-
return _primo_failure("PRIMO returned unreadable record details; use the search link", "invalid_response")
|
| 257 |
-
return {"total": total, "results": results, "source": "PRIMO", "status": "ok"}
|
| 258 |
-
except (TimeoutError, httpx.TimeoutException):
|
| 259 |
-
logger.warning("PRIMO search exceeded the total request deadline")
|
| 260 |
-
return _primo_failure("PRIMO took too long to respond; use the search link", "timeout")
|
| 261 |
-
except (httpx.HTTPError, ValueError, TypeError, AttributeError) as exc:
|
| 262 |
-
# Exception strings from HTTP clients can include the full URL,
|
| 263 |
-
# including the API key. Never put them in logs or responses.
|
| 264 |
-
logger.warning("PRIMO gateway %s failed (%s)", gateway, type(exc).__name__)
|
| 265 |
-
|
| 266 |
-
if last_status in (401, 403):
|
| 267 |
-
return _primo_failure("PRIMO access could not be verified; use the search link", "unauthorized")
|
| 268 |
-
return _primo_failure("PRIMO API unavailable", "upstream_error")
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
def _pubmed_query(req: SearchRequest) -> str:
|
| 272 |
-
query = req.boolean_query or req.query
|
| 273 |
-
if req.year_from or req.year_to:
|
| 274 |
-
year_from, year_to = _year_bounds(req)
|
| 275 |
-
query = f"({query}) AND ({year_from}:{year_to}[dp])"
|
| 276 |
-
if req.open_access:
|
| 277 |
-
query = f"({query}) AND free full text[sb]"
|
| 278 |
-
if req.resource_type == "books":
|
| 279 |
-
query = f'({query}) AND "pubmed books"[sb]'
|
| 280 |
-
elif req.resource_type == "articles":
|
| 281 |
-
query = f'({query}) NOT "pubmed books"[sb]'
|
| 282 |
-
return query
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
async def search_pubmed(req: SearchRequest) -> dict:
|
| 286 |
-
"""Search PubMed; free availability does not establish an open-access licence."""
|
| 287 |
-
import httpx
|
| 288 |
-
|
| 289 |
-
base = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils"
|
| 290 |
-
warnings = []
|
| 291 |
-
if req.peer_reviewed:
|
| 292 |
-
warnings.append("PubMed has no general peer-reviewed-only filter; peer review must be checked for each record.")
|
| 293 |
-
if req.open_access:
|
| 294 |
-
warnings.append("The PubMed access filter finds free full text; it does not verify an open-access licence.")
|
| 295 |
-
common = {"source": "PubMed", "warnings": warnings}
|
| 296 |
-
|
| 297 |
-
def failed(message):
|
| 298 |
-
return {**common, "error": message, "results": [], "total": 0}
|
| 299 |
-
|
| 300 |
-
try:
|
| 301 |
-
async with httpx.AsyncClient(timeout=PUBMED_REQUEST_TIMEOUT) as client:
|
| 302 |
-
response = await asyncio.wait_for(client.get(
|
| 303 |
-
f"{base}/esearch.fcgi",
|
| 304 |
-
params={"db": "pubmed", "term": _pubmed_query(req), "retmax": req.limit,
|
| 305 |
-
"retmode": "json", "sort": "relevance"},
|
| 306 |
-
), timeout=PUBMED_REQUEST_TIMEOUT)
|
| 307 |
-
if response.status_code != 200:
|
| 308 |
-
return failed("PubMed search failed")
|
| 309 |
-
payload = response.json()
|
| 310 |
-
esearch = payload.get("esearchresult", {})
|
| 311 |
-
if payload.get("error") or esearch.get("ERROR") or esearch.get("errorlist"):
|
| 312 |
-
return failed("PubMed could not process this search; check the search terms")
|
| 313 |
-
ids = esearch.get("idlist")
|
| 314 |
-
if not isinstance(ids, list):
|
| 315 |
-
return failed("PubMed returned an unreadable search response; try again")
|
| 316 |
-
query_translation = esearch.get("querytranslation", "")
|
| 317 |
-
count = int(esearch.get("count", 0))
|
| 318 |
-
if not ids:
|
| 319 |
-
return {**common, "total": count, "results": [], "query_translation": query_translation}
|
| 320 |
-
|
| 321 |
-
summary = await asyncio.wait_for(client.get(
|
| 322 |
-
f"{base}/esummary.fcgi",
|
| 323 |
-
params={"db": "pubmed", "id": ",".join(ids), "retmode": "json"},
|
| 324 |
-
), timeout=PUBMED_REQUEST_TIMEOUT)
|
| 325 |
-
if summary.status_code != 200:
|
| 326 |
-
return failed("PubMed fetch failed")
|
| 327 |
-
summary_payload = summary.json()
|
| 328 |
-
if summary_payload.get("error"):
|
| 329 |
-
return failed("PubMed fetch failed")
|
| 330 |
-
data = summary_payload.get("result", {})
|
| 331 |
-
results = []
|
| 332 |
-
for pid in ids:
|
| 333 |
-
record = data.get(pid)
|
| 334 |
-
if not isinstance(record, dict) or record.get("error"):
|
| 335 |
-
continue
|
| 336 |
-
authors_list = record.get("authors") or []
|
| 337 |
-
authors = ", ".join(author.get("name", "") for author in authors_list[:3])
|
| 338 |
-
if len(authors_list) > 3:
|
| 339 |
-
authors += " et al."
|
| 340 |
-
doi = next((article.get("value") for article in record.get("articleids", [])
|
| 341 |
-
if article.get("idtype") == "doi"), None)
|
| 342 |
-
if not doi:
|
| 343 |
-
match = re.search(r"\bdoi:\s*(\S+)", record.get("elocationid", ""), re.IGNORECASE)
|
| 344 |
-
doi = match.group(1) if match else None
|
| 345 |
-
results.append({
|
| 346 |
-
"title": record.get("title", ""),
|
| 347 |
-
"creator": authors,
|
| 348 |
-
"date": record.get("pubdate", ""),
|
| 349 |
-
"source": record.get("fulljournalname", record.get("source", "")),
|
| 350 |
-
"doi": doi,
|
| 351 |
-
"pmid": pid,
|
| 352 |
-
"link": f"https://pubmed.ncbi.nlm.nih.gov/{pid}/",
|
| 353 |
-
"type": "; ".join(record.get("pubtype") or []) or "PubMed record",
|
| 354 |
-
"free_full_text": True if req.open_access else None,
|
| 355 |
-
"_source": "PubMed",
|
| 356 |
-
})
|
| 357 |
-
if ids and not results:
|
| 358 |
-
return failed("PubMed returned no readable record details; try again")
|
| 359 |
-
return {**common, "total": count, "results": results, "query_translation": query_translation}
|
| 360 |
-
except (httpx.HTTPError, TimeoutError, ValueError, TypeError, AttributeError) as exc:
|
| 361 |
-
logger.warning("PubMed search failed (%s)", type(exc).__name__)
|
| 362 |
-
return failed("PubMed is temporarily unavailable; try again")
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
@router.post("")
|
| 366 |
-
async def search_endpoint(req: SearchRequest):
|
| 367 |
-
"""Search PRIMO or PubMed, preferring boolean_query when supplied."""
|
| 368 |
-
from src.config import get_settings
|
| 369 |
-
|
| 370 |
-
if req.source == "pubmed":
|
| 371 |
-
return await search_pubmed(req)
|
| 372 |
-
settings = get_settings()
|
| 373 |
-
return await search_primo(req, settings.primo_api_key, settings.primo_api_region)
|
|
|
|
| 1 |
+
"""PRIMO and PubMed search, with explicit filters and bounded upstream waits."""
|
| 2 |
+
import asyncio
|
| 3 |
+
import logging
|
| 4 |
+
import re
|
| 5 |
+
from typing import Optional
|
| 6 |
+
from urllib.parse import quote, urlsplit
|
| 7 |
+
|
| 8 |
+
from fastapi import APIRouter
|
| 9 |
+
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
router = APIRouter()
|
| 13 |
+
# One deadline covers all gateways, rather than one wait per region. A region
|
| 14 |
+
# selected in HF's PRIMO_API_REGION avoids even the fast discovery attempts.
|
| 15 |
+
PRIMO_REQUEST_TIMEOUT = 6.0
|
| 16 |
+
PUBMED_REQUEST_TIMEOUT = 8.0
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class SearchRequest(BaseModel):
|
| 20 |
+
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
| 21 |
+
query: str = Field(min_length=1, max_length=1000)
|
| 22 |
+
boolean_query: Optional[str] = Field(default=None, max_length=1500)
|
| 23 |
+
source: str = Field(default="primo", pattern=r"^(primo|pubmed)$")
|
| 24 |
+
limit: int = Field(default=10, ge=1, le=20)
|
| 25 |
+
sort: str = Field(default="rank", pattern=r"^(rank|date_d|date_a)$")
|
| 26 |
+
query_field: str = Field(default="any", pattern=r"^(any|title|creator|sub)$")
|
| 27 |
+
peer_reviewed: bool = False
|
| 28 |
+
open_access: bool = False
|
| 29 |
+
year_from: Optional[str] = Field(default=None, pattern=r"^[0-9]{4}$")
|
| 30 |
+
year_to: Optional[str] = Field(default=None, pattern=r"^[0-9]{4}$")
|
| 31 |
+
resource_type: str = Field(default="articles", pattern=r"^(articles|books|both)$")
|
| 32 |
+
|
| 33 |
+
@model_validator(mode="after")
|
| 34 |
+
def validate_search(self):
|
| 35 |
+
self.boolean_query = self.boolean_query or None
|
| 36 |
+
for year in (self.year_from, self.year_to):
|
| 37 |
+
if year == "0000":
|
| 38 |
+
raise ValueError("Publication years must be between 0001 and 9999")
|
| 39 |
+
if self.year_from and self.year_to and self.year_from > self.year_to:
|
| 40 |
+
raise ValueError("year_from must not be later than year_to")
|
| 41 |
+
# Primo reserves semicolons for additional field clauses, even when
|
| 42 |
+
# percent-encoded; accepting one here changes the meaning of a query.
|
| 43 |
+
if self.source == "primo" and ";" in (self.boolean_query or self.query):
|
| 44 |
+
raise ValueError("PRIMO search terms cannot contain semicolons")
|
| 45 |
+
return self
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _boolean_to_primo_params(boolean_query: str, query_field: str = "any") -> str:
|
| 49 |
+
"""Preserve exact phrases and all Boolean operators in one Primo q value."""
|
| 50 |
+
if query_field not in {"any", "title", "creator", "sub"}:
|
| 51 |
+
raise ValueError("Unsupported PRIMO search field")
|
| 52 |
+
return f"q={query_field},contains,{quote(boolean_query.strip(), safe='')}"
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _year_bounds(req: SearchRequest) -> tuple[str, str]:
|
| 56 |
+
"""Represent an omitted bound without silently excluding older/future works."""
|
| 57 |
+
return req.year_from or "0001", req.year_to or "9999"
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _build_primo_search_link(title: str, record_id: Optional[str] = None,
|
| 61 |
+
context: Optional[str] = None) -> Optional[str]:
|
| 62 |
+
base = "https://khalifa.primo.exlibrisgroup.com/discovery"
|
| 63 |
+
if record_id:
|
| 64 |
+
context_param = f"&context={context}" if isinstance(context, str) and context in {"L", "PC"} else ""
|
| 65 |
+
return (
|
| 66 |
+
f"{base}/fulldisplay?docid={quote(str(record_id), safe='')}&vid=971KUOSTAR_INST:KU"
|
| 67 |
+
f"{context_param}&lang=en&tab=Everything&search_scope=MyInst_and_CI"
|
| 68 |
+
)
|
| 69 |
+
clean_title = (title or "").strip()
|
| 70 |
+
if not clean_title:
|
| 71 |
+
return None
|
| 72 |
+
return (
|
| 73 |
+
f"{base}/search?query=any,contains,{quote(clean_title, safe='')}"
|
| 74 |
+
"&tab=Everything&search_scope=MyInst_and_CI&vid=971KUOSTAR_INST:KU&lang=en"
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _first(value, default=""):
|
| 79 |
+
"""PNX values are normally arrays; tolerate scalar/missing metadata."""
|
| 80 |
+
if isinstance(value, list):
|
| 81 |
+
value = value[0] if value else default
|
| 82 |
+
return value if isinstance(value, str) else default
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _result_link(raw_link: str, fallback: Optional[str]) -> Optional[str]:
|
| 86 |
+
# PNX link fields can contain $$U<url>$$D<label>, rather than a bare URL.
|
| 87 |
+
match = re.match(r"(?:\$\$U)?(https?://[^\s]+?)(?:\$\$|$)", raw_link)
|
| 88 |
+
if not match:
|
| 89 |
+
return fallback
|
| 90 |
+
candidate = match.group(1)
|
| 91 |
+
try:
|
| 92 |
+
parsed = urlsplit(candidate)
|
| 93 |
+
if parsed.hostname and not parsed.username and not parsed.password:
|
| 94 |
+
return candidate
|
| 95 |
+
except ValueError:
|
| 96 |
+
pass
|
| 97 |
+
return fallback
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def _pnx_section(pnx: dict, section: str) -> dict:
|
| 101 |
+
value = pnx.get(section)
|
| 102 |
+
return value if isinstance(value, dict) else {}
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _primo_records(data: dict, limit: int) -> list[dict]:
|
| 106 |
+
"""Normalize returned PNX metadata; never infer circulation availability."""
|
| 107 |
+
results = []
|
| 108 |
+
seen = set()
|
| 109 |
+
for doc in data.get("docs", []):
|
| 110 |
+
if not isinstance(doc, dict) or not isinstance(doc.get("pnx"), dict):
|
| 111 |
+
continue
|
| 112 |
+
pnx = doc["pnx"]
|
| 113 |
+
display = _pnx_section(pnx, "display")
|
| 114 |
+
addata = _pnx_section(pnx, "addata")
|
| 115 |
+
search = _pnx_section(pnx, "search")
|
| 116 |
+
sort = _pnx_section(pnx, "sort")
|
| 117 |
+
control = _pnx_section(pnx, "control")
|
| 118 |
+
links = _pnx_section(pnx, "links")
|
| 119 |
+
record_id = _first(control.get("recordid"), None) or _first(doc.get("id"), None)
|
| 120 |
+
title = _first(display.get("title")) or _first(addata.get("btitle") or addata.get("atitle"))
|
| 121 |
+
# A corrupt/empty item is not a real result to pad the requested count.
|
| 122 |
+
if not title:
|
| 123 |
+
continue
|
| 124 |
+
if record_id and record_id in seen:
|
| 125 |
+
continue
|
| 126 |
+
if record_id:
|
| 127 |
+
seen.add(record_id)
|
| 128 |
+
primo_url = _build_primo_search_link(title, record_id, _first(doc.get("context")))
|
| 129 |
+
creators = display.get("creator") or display.get("contributor") or addata.get("au") or []
|
| 130 |
+
if isinstance(creators, str):
|
| 131 |
+
creators = [creators]
|
| 132 |
+
if not isinstance(creators, list):
|
| 133 |
+
creators = []
|
| 134 |
+
raw_link = _first(links.get("openurl") or links.get("linktorsrc"))
|
| 135 |
+
results.append({
|
| 136 |
+
"record_id": record_id,
|
| 137 |
+
"title": title,
|
| 138 |
+
"creator": "; ".join(creator for creator in creators if isinstance(creator, str)),
|
| 139 |
+
"date": (_first(search.get("creationdate")) or _first(addata.get("risdate"))
|
| 140 |
+
or _first(addata.get("date")) or _first(sort.get("creationdate"))),
|
| 141 |
+
"type": _first(display.get("type") or addata.get("ristype")),
|
| 142 |
+
"source": _first(display.get("source") or addata.get("jtitle")),
|
| 143 |
+
"description": _first(display.get("description"))[:400],
|
| 144 |
+
"doi": _first(addata.get("doi"), None),
|
| 145 |
+
"primo_url": primo_url,
|
| 146 |
+
"link": _result_link(raw_link, primo_url),
|
| 147 |
+
"open_access": True if _first(display.get("oa")) == "free_for_read" else None,
|
| 148 |
+
"_source": "PRIMO",
|
| 149 |
+
})
|
| 150 |
+
if len(results) >= limit:
|
| 151 |
+
break
|
| 152 |
+
return results
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def _primo_failure(message: str, code: str, status: str = "unavailable") -> dict:
|
| 156 |
+
return {"error": message, "error_code": code, "status": status,
|
| 157 |
+
"results": [], "total": 0, "source": "PRIMO"}
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def _primo_gateways(region: str) -> tuple[str, ...]:
|
| 161 |
+
"""Allow only Ex Libris's documented gateway hosts; no custom secret target."""
|
| 162 |
+
hosts = {
|
| 163 |
+
"eu": "api-eu.hosted.exlibrisgroup.com",
|
| 164 |
+
"na": "api-na.hosted.exlibrisgroup.com",
|
| 165 |
+
"ap": "api-ap.hosted.exlibrisgroup.com",
|
| 166 |
+
"ca": "api-ca.hosted.exlibrisgroup.com",
|
| 167 |
+
"aps": "api-aps.hosted.exlibrisgroup.com",
|
| 168 |
+
"cn": "api-cn.hosted.exlibrisgroup.com.cn",
|
| 169 |
+
}
|
| 170 |
+
if region == "auto":
|
| 171 |
+
return tuple(hosts[name] for name in ("eu", "na", "ap"))
|
| 172 |
+
return (hosts[region],) if region in hosts else ()
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
async def search_primo(req: SearchRequest, api_key: str, region: str = "auto") -> dict:
|
| 176 |
+
"""Search Primo using the full preferred query and documented facet syntax."""
|
| 177 |
+
import httpx
|
| 178 |
+
|
| 179 |
+
if not api_key:
|
| 180 |
+
return _primo_failure("PRIMO results are not configured", "not_configured", "not_configured")
|
| 181 |
+
|
| 182 |
+
gateways = _primo_gateways(region)
|
| 183 |
+
if not gateways:
|
| 184 |
+
return _primo_failure("PRIMO API region is not configured correctly", "invalid_region", "not_configured")
|
| 185 |
+
|
| 186 |
+
query_params = _boolean_to_primo_params(req.boolean_query or req.query, req.query_field)
|
| 187 |
+
facets = []
|
| 188 |
+
if req.peer_reviewed:
|
| 189 |
+
facets.append("facet_tlevel,exact,peer_reviewed")
|
| 190 |
+
if req.open_access:
|
| 191 |
+
facets.append("facet_tlevel,exact,open_access")
|
| 192 |
+
if req.year_from or req.year_to:
|
| 193 |
+
year_from, year_to = _year_bounds(req)
|
| 194 |
+
facets.append(f"facet_searchcreationdate,exact,[{year_from} TO {year_to}]")
|
| 195 |
+
if req.resource_type != "both":
|
| 196 |
+
facets.append(f"facet_rtype,exact,{req.resource_type}")
|
| 197 |
+
|
| 198 |
+
# Multiple qInclude values in the same category are ANDed, so an explicit
|
| 199 |
+
# Books OR Articles request must use multiFacets for that category.
|
| 200 |
+
mixed_types = "facet_rtype,include,books|,|facet_rtype,include,articles"
|
| 201 |
+
mixed_params = f"&multiFacets={quote(mixed_types, safe='')}" if req.resource_type == "both" else ""
|
| 202 |
+
compact_query = re.sub(r'["\s-]', "", (req.boolean_query or req.query)).upper()
|
| 203 |
+
exact_identifier = bool(re.fullmatch(r"(?:[0-9]{9}[0-9X]|[0-9]{13})", compact_query))
|
| 204 |
+
controlled_vocabulary = "false" if req.query_field == "title" or exact_identifier else "true"
|
| 205 |
+
|
| 206 |
+
# qInclude accepts one value, joining ANDed facets with |,|. Repeated
|
| 207 |
+
# qInclude keys are not its documented API contract.
|
| 208 |
+
facet_params = f"&qInclude={quote('|,|'.join(facets), safe='')}" if facets else ""
|
| 209 |
+
qs = (
|
| 210 |
+
"?vid=971KUOSTAR_INST:KU&tab=Everything&scope=MyInst_and_CI"
|
| 211 |
+
f"&{query_params}&lang=en&sort={req.sort}&limit={req.limit}&offset=0"
|
| 212 |
+
f"&conVoc={controlled_vocabulary}&skipDelivery=true"
|
| 213 |
+
f"{facet_params}{mixed_params}"
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
deadline = asyncio.get_running_loop().time() + PRIMO_REQUEST_TIMEOUT
|
| 217 |
+
last_status = None
|
| 218 |
+
async with httpx.AsyncClient(timeout=PRIMO_REQUEST_TIMEOUT) as client:
|
| 219 |
+
for gateway in gateways:
|
| 220 |
+
remaining = deadline - asyncio.get_running_loop().time()
|
| 221 |
+
if remaining <= 0:
|
| 222 |
+
return _primo_failure("PRIMO took too long to respond; use the search link", "timeout")
|
| 223 |
+
url = f"https://{gateway}/primo/v1/search{qs}"
|
| 224 |
+
try:
|
| 225 |
+
# httpx read timeouts reset per chunk. wait_for additionally
|
| 226 |
+
# bounds the complete request, including a slowly streamed body.
|
| 227 |
+
response = await asyncio.wait_for(
|
| 228 |
+
client.get(url, headers={"Accept": "application/json", "Authorization": f"apikey {api_key}"}),
|
| 229 |
+
timeout=remaining,
|
| 230 |
+
)
|
| 231 |
+
if response.status_code != 200:
|
| 232 |
+
last_status = response.status_code
|
| 233 |
+
logger.warning("PRIMO gateway %s returned HTTP %s", gateway, response.status_code)
|
| 234 |
+
if response.status_code == 429:
|
| 235 |
+
return _primo_failure("PRIMO request limit reached; try again later", "rate_limited", "rate_limited")
|
| 236 |
+
if response.status_code == 400:
|
| 237 |
+
return _primo_failure("PRIMO could not process this search; check the search terms", "invalid_query", "error")
|
| 238 |
+
if response.status_code in (401, 403, 404):
|
| 239 |
+
continue
|
| 240 |
+
return _primo_failure("PRIMO API unavailable", "upstream_error")
|
| 241 |
+
data = response.json()
|
| 242 |
+
if not isinstance(data, dict) or not isinstance(data.get("docs"), list):
|
| 243 |
+
raise ValueError("Invalid PRIMO response")
|
| 244 |
+
results = _primo_records(data, req.limit)
|
| 245 |
+
info = data.get("info") if isinstance(data.get("info"), dict) else {}
|
| 246 |
+
raw_total = info.get("total")
|
| 247 |
+
total = None
|
| 248 |
+
# Unknown totals must stay unknown: a short page is not evidence
|
| 249 |
+
# that those records exhaust all matches in the catalogue.
|
| 250 |
+
if ((type(raw_total) is int) or
|
| 251 |
+
(isinstance(raw_total, str) and re.fullmatch(r"[0-9]+", raw_total.strip()))):
|
| 252 |
+
parsed_total = int(raw_total)
|
| 253 |
+
if parsed_total >= len(results):
|
| 254 |
+
total = parsed_total
|
| 255 |
+
if data["docs"] and not results:
|
| 256 |
+
return _primo_failure("PRIMO returned unreadable record details; use the search link", "invalid_response")
|
| 257 |
+
return {"total": total, "results": results, "source": "PRIMO", "status": "ok"}
|
| 258 |
+
except (TimeoutError, httpx.TimeoutException):
|
| 259 |
+
logger.warning("PRIMO search exceeded the total request deadline")
|
| 260 |
+
return _primo_failure("PRIMO took too long to respond; use the search link", "timeout")
|
| 261 |
+
except (httpx.HTTPError, ValueError, TypeError, AttributeError) as exc:
|
| 262 |
+
# Exception strings from HTTP clients can include the full URL,
|
| 263 |
+
# including the API key. Never put them in logs or responses.
|
| 264 |
+
logger.warning("PRIMO gateway %s failed (%s)", gateway, type(exc).__name__)
|
| 265 |
+
|
| 266 |
+
if last_status in (401, 403):
|
| 267 |
+
return _primo_failure("PRIMO access could not be verified; use the search link", "unauthorized")
|
| 268 |
+
return _primo_failure("PRIMO API unavailable", "upstream_error")
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def _pubmed_query(req: SearchRequest) -> str:
|
| 272 |
+
query = req.boolean_query or req.query
|
| 273 |
+
if req.year_from or req.year_to:
|
| 274 |
+
year_from, year_to = _year_bounds(req)
|
| 275 |
+
query = f"({query}) AND ({year_from}:{year_to}[dp])"
|
| 276 |
+
if req.open_access:
|
| 277 |
+
query = f"({query}) AND free full text[sb]"
|
| 278 |
+
if req.resource_type == "books":
|
| 279 |
+
query = f'({query}) AND "pubmed books"[sb]'
|
| 280 |
+
elif req.resource_type == "articles":
|
| 281 |
+
query = f'({query}) NOT "pubmed books"[sb]'
|
| 282 |
+
return query
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
async def search_pubmed(req: SearchRequest) -> dict:
|
| 286 |
+
"""Search PubMed; free availability does not establish an open-access licence."""
|
| 287 |
+
import httpx
|
| 288 |
+
|
| 289 |
+
base = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils"
|
| 290 |
+
warnings = []
|
| 291 |
+
if req.peer_reviewed:
|
| 292 |
+
warnings.append("PubMed has no general peer-reviewed-only filter; peer review must be checked for each record.")
|
| 293 |
+
if req.open_access:
|
| 294 |
+
warnings.append("The PubMed access filter finds free full text; it does not verify an open-access licence.")
|
| 295 |
+
common = {"source": "PubMed", "warnings": warnings}
|
| 296 |
+
|
| 297 |
+
def failed(message):
|
| 298 |
+
return {**common, "error": message, "results": [], "total": 0}
|
| 299 |
+
|
| 300 |
+
try:
|
| 301 |
+
async with httpx.AsyncClient(timeout=PUBMED_REQUEST_TIMEOUT) as client:
|
| 302 |
+
response = await asyncio.wait_for(client.get(
|
| 303 |
+
f"{base}/esearch.fcgi",
|
| 304 |
+
params={"db": "pubmed", "term": _pubmed_query(req), "retmax": req.limit,
|
| 305 |
+
"retmode": "json", "sort": "relevance"},
|
| 306 |
+
), timeout=PUBMED_REQUEST_TIMEOUT)
|
| 307 |
+
if response.status_code != 200:
|
| 308 |
+
return failed("PubMed search failed")
|
| 309 |
+
payload = response.json()
|
| 310 |
+
esearch = payload.get("esearchresult", {})
|
| 311 |
+
if payload.get("error") or esearch.get("ERROR") or esearch.get("errorlist"):
|
| 312 |
+
return failed("PubMed could not process this search; check the search terms")
|
| 313 |
+
ids = esearch.get("idlist")
|
| 314 |
+
if not isinstance(ids, list):
|
| 315 |
+
return failed("PubMed returned an unreadable search response; try again")
|
| 316 |
+
query_translation = esearch.get("querytranslation", "")
|
| 317 |
+
count = int(esearch.get("count", 0))
|
| 318 |
+
if not ids:
|
| 319 |
+
return {**common, "total": count, "results": [], "query_translation": query_translation}
|
| 320 |
+
|
| 321 |
+
summary = await asyncio.wait_for(client.get(
|
| 322 |
+
f"{base}/esummary.fcgi",
|
| 323 |
+
params={"db": "pubmed", "id": ",".join(ids), "retmode": "json"},
|
| 324 |
+
), timeout=PUBMED_REQUEST_TIMEOUT)
|
| 325 |
+
if summary.status_code != 200:
|
| 326 |
+
return failed("PubMed fetch failed")
|
| 327 |
+
summary_payload = summary.json()
|
| 328 |
+
if summary_payload.get("error"):
|
| 329 |
+
return failed("PubMed fetch failed")
|
| 330 |
+
data = summary_payload.get("result", {})
|
| 331 |
+
results = []
|
| 332 |
+
for pid in ids:
|
| 333 |
+
record = data.get(pid)
|
| 334 |
+
if not isinstance(record, dict) or record.get("error"):
|
| 335 |
+
continue
|
| 336 |
+
authors_list = record.get("authors") or []
|
| 337 |
+
authors = ", ".join(author.get("name", "") for author in authors_list[:3])
|
| 338 |
+
if len(authors_list) > 3:
|
| 339 |
+
authors += " et al."
|
| 340 |
+
doi = next((article.get("value") for article in record.get("articleids", [])
|
| 341 |
+
if article.get("idtype") == "doi"), None)
|
| 342 |
+
if not doi:
|
| 343 |
+
match = re.search(r"\bdoi:\s*(\S+)", record.get("elocationid", ""), re.IGNORECASE)
|
| 344 |
+
doi = match.group(1) if match else None
|
| 345 |
+
results.append({
|
| 346 |
+
"title": record.get("title", ""),
|
| 347 |
+
"creator": authors,
|
| 348 |
+
"date": record.get("pubdate", ""),
|
| 349 |
+
"source": record.get("fulljournalname", record.get("source", "")),
|
| 350 |
+
"doi": doi,
|
| 351 |
+
"pmid": pid,
|
| 352 |
+
"link": f"https://pubmed.ncbi.nlm.nih.gov/{pid}/",
|
| 353 |
+
"type": "; ".join(record.get("pubtype") or []) or "PubMed record",
|
| 354 |
+
"free_full_text": True if req.open_access else None,
|
| 355 |
+
"_source": "PubMed",
|
| 356 |
+
})
|
| 357 |
+
if ids and not results:
|
| 358 |
+
return failed("PubMed returned no readable record details; try again")
|
| 359 |
+
return {**common, "total": count, "results": results, "query_translation": query_translation}
|
| 360 |
+
except (httpx.HTTPError, TimeoutError, ValueError, TypeError, AttributeError) as exc:
|
| 361 |
+
logger.warning("PubMed search failed (%s)", type(exc).__name__)
|
| 362 |
+
return failed("PubMed is temporarily unavailable; try again")
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
@router.post("")
|
| 366 |
+
async def search_endpoint(req: SearchRequest):
|
| 367 |
+
"""Search PRIMO or PubMed, preferring boolean_query when supplied."""
|
| 368 |
+
from src.config import get_settings
|
| 369 |
+
|
| 370 |
+
if req.source == "pubmed":
|
| 371 |
+
return await search_pubmed(req)
|
| 372 |
+
settings = get_settings()
|
| 373 |
+
return await search_primo(req, settings.primo_api_key, settings.primo_api_region)
|