Merge branch 'dev' into network
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
This commit is contained in:
@@ -34,6 +34,10 @@ class Settings(BaseSettings):
|
||||
"am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ=="
|
||||
)
|
||||
openalex_works_search_timeout_seconds: float = 30.0
|
||||
# OpenAlex public API config
|
||||
openalex_api_base_url: str = "https://api.openalex.org"
|
||||
openalex_api_key: Optional[str] = None
|
||||
openalex_api_timeout_seconds: float = 30.0
|
||||
|
||||
# LLM config
|
||||
llm_api_url: Optional[str] = None
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Institution lookup module."""
|
||||
@@ -0,0 +1,309 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Business logic for OpenAlex institutions.
|
||||
"""
|
||||
import logging
|
||||
from copy import deepcopy
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from pydantic import ValidationError
|
||||
from starlette.status import HTTP_400_BAD_REQUEST
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||
|
||||
from inse.models.autocomplete_response import AutocompleteResponse
|
||||
from inse.models.autocomplete_response_meta import AutocompleteResponseMeta
|
||||
from inse.models.autocomplete_response_results_inner import AutocompleteResponseResultsInner
|
||||
from inse.models.institutions_list_response import InstitutionsListResponse
|
||||
from .search_client import OpenAlexInstitutionsClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_VALID_INSTITUTION_TYPES = {
|
||||
"education",
|
||||
"healthcare",
|
||||
"company",
|
||||
"archive",
|
||||
"nonprofit",
|
||||
"government",
|
||||
"facility",
|
||||
"other",
|
||||
}
|
||||
|
||||
|
||||
async def list_institutions(
|
||||
*,
|
||||
search: str | None = None,
|
||||
filter: str | None = None,
|
||||
sort: str | None = None,
|
||||
group_by: str | None = None,
|
||||
per_page: int = 25,
|
||||
page: int | None = 1,
|
||||
cursor: str | None = None,
|
||||
sample: int | None = None,
|
||||
select: str | None = None,
|
||||
client: OpenAlexInstitutionsClient | None = None,
|
||||
) -> InstitutionsListResponse:
|
||||
if sample is not None and (sort or page not in (None, 1)):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST,
|
||||
detail="sample cannot be combined with sort or page.",
|
||||
)
|
||||
|
||||
openalex_client = client or OpenAlexInstitutionsClient()
|
||||
|
||||
try:
|
||||
data = await openalex_client.list_institutions(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
group_by=group_by,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
sample=sample,
|
||||
select=select,
|
||||
)
|
||||
except httpx.HTTPStatusError as exc:
|
||||
status_code = exc.response.status_code
|
||||
detail = "OpenAlex institutions request failed."
|
||||
try:
|
||||
error_body = exc.response.json()
|
||||
detail = error_body.get("message") or error_body.get("error") or detail
|
||||
except ValueError:
|
||||
if exc.response.text:
|
||||
detail = exc.response.text
|
||||
raise HTTPException(status_code=status_code, detail=detail) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex institutions request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex institutions request failed.",
|
||||
) from exc
|
||||
|
||||
try:
|
||||
normalized_data = _normalize_institutions_response(data)
|
||||
return InstitutionsListResponse.from_dict(normalized_data) or InstitutionsListResponse()
|
||||
except ValidationError as exc:
|
||||
logger.exception("OpenAlex institutions response could not be parsed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex institutions response could not be parsed.",
|
||||
) from exc
|
||||
|
||||
|
||||
async def autocomplete_institutions(
|
||||
*,
|
||||
query: str,
|
||||
country_code: str | None = None,
|
||||
institution_type: str | None = None,
|
||||
limit: int = 10,
|
||||
client: OpenAlexInstitutionsClient | None = None,
|
||||
) -> AutocompleteResponse:
|
||||
filters = []
|
||||
if country_code:
|
||||
filters.append(f"country_code:{country_code}")
|
||||
if institution_type:
|
||||
filters.append(f"type:{institution_type}")
|
||||
|
||||
response = await list_institutions(
|
||||
search=query,
|
||||
filter=",".join(filters) if filters else None,
|
||||
sort="works_count:desc",
|
||||
per_page=limit,
|
||||
page=1,
|
||||
select=(
|
||||
"id,ror,display_name,country_code,type,works_count,"
|
||||
"cited_by_count,geo"
|
||||
),
|
||||
client=client,
|
||||
)
|
||||
|
||||
results = []
|
||||
for institution in response.results or []:
|
||||
if not institution.id or not institution.display_name:
|
||||
continue
|
||||
|
||||
hint_parts = []
|
||||
if institution.geo:
|
||||
if institution.geo.city:
|
||||
hint_parts.append(institution.geo.city)
|
||||
if institution.geo.country:
|
||||
hint_parts.append(institution.geo.country)
|
||||
elif institution.country_code:
|
||||
hint_parts.append(institution.country_code)
|
||||
if institution.type:
|
||||
hint_parts.append(institution.type)
|
||||
|
||||
results.append(
|
||||
AutocompleteResponseResultsInner(
|
||||
id=institution.id,
|
||||
display_name=institution.display_name,
|
||||
hint=" · ".join(hint_parts) if hint_parts else None,
|
||||
cited_by_count=institution.cited_by_count,
|
||||
works_count=institution.works_count,
|
||||
entity_type="institution",
|
||||
external_id=institution.ror,
|
||||
)
|
||||
)
|
||||
|
||||
return AutocompleteResponse(
|
||||
meta=AutocompleteResponseMeta(
|
||||
count=response.meta.count if response.meta else len(results),
|
||||
db_response_time_ms=(
|
||||
response.meta.db_response_time_ms if response.meta else None
|
||||
),
|
||||
),
|
||||
results=results,
|
||||
)
|
||||
|
||||
|
||||
def _normalize_institutions_response(data: dict[str, Any]) -> dict[str, Any]:
|
||||
normalized = deepcopy(data)
|
||||
|
||||
meta = normalized.get("meta")
|
||||
if isinstance(meta, dict):
|
||||
for field in ["count", "db_response_time_ms", "page", "per_page", "groups_count"]:
|
||||
meta[field] = _int_or_none(meta.get(field))
|
||||
meta["next_cursor"] = _str_or_none(meta.get("next_cursor"))
|
||||
meta["cost_usd"] = _number_or_none(meta.get("cost_usd"))
|
||||
|
||||
for institution in normalized.get("results") or []:
|
||||
if not isinstance(institution, dict):
|
||||
continue
|
||||
|
||||
for field in [
|
||||
"id",
|
||||
"ror",
|
||||
"display_name",
|
||||
"country_code",
|
||||
"homepage_url",
|
||||
"image_url",
|
||||
"image_thumbnail_url",
|
||||
"works_api_url",
|
||||
]:
|
||||
institution[field] = _str_or_none(institution.get(field))
|
||||
|
||||
institution_type = institution.get("type")
|
||||
if institution_type is not None and institution_type not in _VALID_INSTITUTION_TYPES:
|
||||
institution["type"] = None
|
||||
else:
|
||||
institution["type"] = _str_or_none(institution_type)
|
||||
|
||||
institution["display_name_acronyms"] = _str_list_or_none(
|
||||
institution.get("display_name_acronyms")
|
||||
)
|
||||
institution["display_name_alternatives"] = _str_list_or_none(
|
||||
institution.get("display_name_alternatives")
|
||||
)
|
||||
institution["lineage"] = _str_list_or_none(institution.get("lineage"))
|
||||
institution["works_count"] = _int_or_none(institution.get("works_count"))
|
||||
institution["cited_by_count"] = _int_or_none(institution.get("cited_by_count"))
|
||||
institution["created_date"] = _date_str_or_none(institution.get("created_date"))
|
||||
institution["updated_date"] = _datetime_str_or_none(institution.get("updated_date"))
|
||||
|
||||
summary_stats = institution.get("summary_stats")
|
||||
if isinstance(summary_stats, dict):
|
||||
summary_stats["2yr_mean_citedness"] = _number_or_none(
|
||||
summary_stats.get("2yr_mean_citedness")
|
||||
)
|
||||
summary_stats["h_index"] = _int_or_none(summary_stats.get("h_index"))
|
||||
summary_stats["i10_index"] = _int_or_none(summary_stats.get("i10_index"))
|
||||
|
||||
geo = institution.get("geo")
|
||||
if isinstance(geo, dict):
|
||||
for field in [
|
||||
"city",
|
||||
"geonames_city_id",
|
||||
"region",
|
||||
"country_code",
|
||||
"country",
|
||||
]:
|
||||
geo[field] = _str_or_none(geo.get(field))
|
||||
geo["latitude"] = _number_or_none(geo.get("latitude"))
|
||||
geo["longitude"] = _number_or_none(geo.get("longitude"))
|
||||
|
||||
ids = institution.get("ids")
|
||||
if isinstance(ids, dict):
|
||||
for field in ["openalex", "ror", "grid", "wikipedia", "wikidata"]:
|
||||
ids[field] = _str_or_none(ids.get(field))
|
||||
ids["mag"] = _int_or_none(ids.get("mag"))
|
||||
|
||||
for counts_by_year in institution.get("counts_by_year") or []:
|
||||
if not isinstance(counts_by_year, dict):
|
||||
continue
|
||||
for field in ["year", "works_count", "cited_by_count"]:
|
||||
counts_by_year[field] = _int_or_none(counts_by_year.get(field))
|
||||
|
||||
for group in normalized.get("group_by") or []:
|
||||
if not isinstance(group, dict):
|
||||
continue
|
||||
|
||||
group["key"] = _str_or_none(group.get("key"))
|
||||
group["key_display_name"] = _str_or_none(group.get("key_display_name"))
|
||||
group["count"] = _int_or_none(group.get("count"))
|
||||
|
||||
return normalized
|
||||
|
||||
|
||||
def _str_or_none(value: Any) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, bool):
|
||||
return str(value).lower()
|
||||
return str(value)
|
||||
|
||||
|
||||
def _str_list_or_none(value: Any) -> list[str] | None:
|
||||
if value is None:
|
||||
return None
|
||||
if not isinstance(value, list):
|
||||
return None
|
||||
return [_str_or_none(item) for item in value if item is not None]
|
||||
|
||||
|
||||
def _int_or_none(value: Any) -> int | None:
|
||||
if value is None or isinstance(value, bool):
|
||||
return None
|
||||
if isinstance(value, int):
|
||||
return value
|
||||
if isinstance(value, float):
|
||||
return int(value)
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
return int(float(value))
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _number_or_none(value: Any) -> int | float | None:
|
||||
if value is None or isinstance(value, bool):
|
||||
return None
|
||||
if isinstance(value, (int, float)):
|
||||
return value
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
number = float(value)
|
||||
except ValueError:
|
||||
return None
|
||||
return int(number) if number.is_integer() else number
|
||||
return None
|
||||
|
||||
|
||||
def _date_str_or_none(value: Any) -> str | None:
|
||||
text = _str_or_none(value)
|
||||
if not text:
|
||||
return None
|
||||
return text[:10]
|
||||
|
||||
|
||||
def _datetime_str_or_none(value: Any) -> str | None:
|
||||
text = _str_or_none(value)
|
||||
if not text:
|
||||
return None
|
||||
if len(text) == 10:
|
||||
return f"{text}T00:00:00Z"
|
||||
return text
|
||||
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
HTTP client for OpenAlex institutions.
|
||||
"""
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
class OpenAlexInstitutionsClient:
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
api_key: str | None = None,
|
||||
timeout: float | None = None,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
):
|
||||
self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/")
|
||||
self.api_key = api_key if api_key is not None else config.settings.openalex_api_key
|
||||
self.timeout = timeout if timeout is not None else config.settings.openalex_api_timeout_seconds
|
||||
self.transport = transport
|
||||
|
||||
def list_institutions_params(
|
||||
self,
|
||||
*,
|
||||
search: str | None = None,
|
||||
filter: str | None = None,
|
||||
sort: str | None = None,
|
||||
group_by: str | None = None,
|
||||
per_page: int = 25,
|
||||
page: int | None = 1,
|
||||
cursor: str | None = None,
|
||||
sample: int | None = None,
|
||||
select: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
params: dict[str, Any] = {"per_page": per_page}
|
||||
|
||||
if search:
|
||||
params["search"] = search
|
||||
if filter:
|
||||
params["filter"] = filter
|
||||
if sort:
|
||||
params["sort"] = sort
|
||||
if group_by:
|
||||
params["group_by"] = group_by
|
||||
if cursor:
|
||||
params["cursor"] = cursor
|
||||
elif page is not None:
|
||||
params["page"] = page
|
||||
if sample is not None:
|
||||
params["sample"] = sample
|
||||
if select:
|
||||
params["select"] = select
|
||||
if self.api_key:
|
||||
params["api_key"] = self.api_key
|
||||
|
||||
return params
|
||||
|
||||
async def list_institutions(
|
||||
self,
|
||||
*,
|
||||
search: str | None = None,
|
||||
filter: str | None = None,
|
||||
sort: str | None = None,
|
||||
group_by: str | None = None,
|
||||
per_page: int = 25,
|
||||
page: int | None = 1,
|
||||
cursor: str | None = None,
|
||||
sample: int | None = None,
|
||||
select: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.get(
|
||||
"/institutions",
|
||||
params=self.list_institutions_params(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
group_by=group_by,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
sample=sample,
|
||||
select=select,
|
||||
),
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
REST API for OpenAlex institutions.
|
||||
"""
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter
|
||||
from fastapi import Query
|
||||
|
||||
from inse.models.autocomplete_response import AutocompleteResponse
|
||||
from inse.models.institutions_list_response import InstitutionsListResponse
|
||||
from inse.tags import Tags
|
||||
from . import logic
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/institutions", tags=[Tags.INSTITUTIONS])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/autocomplete",
|
||||
operation_id="autocompleteInstitutions",
|
||||
response_model=AutocompleteResponse,
|
||||
response_model_exclude_none=True,
|
||||
summary="Returns institution options for autocomplete inputs.",
|
||||
)
|
||||
async def autocomplete_institutions(
|
||||
query: Annotated[
|
||||
str,
|
||||
Query(description="Institution search text, for example 'Duisburg Essen'.", min_length=1),
|
||||
],
|
||||
country_code: Annotated[
|
||||
str | None,
|
||||
Query(alias="countryCode", description="Optional ISO country code filter."),
|
||||
] = None,
|
||||
institution_type: Annotated[
|
||||
str | None,
|
||||
Query(alias="type", description="Optional institution type filter."),
|
||||
] = None,
|
||||
limit: Annotated[
|
||||
int,
|
||||
Query(description="Maximum number of autocomplete options.", ge=1, le=25),
|
||||
] = 10,
|
||||
):
|
||||
return await logic.autocomplete_institutions(
|
||||
query=query,
|
||||
country_code=country_code,
|
||||
institution_type=institution_type,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
operation_id="listInstitutions",
|
||||
response_model=InstitutionsListResponse,
|
||||
response_model_exclude_none=True,
|
||||
summary="Returns a list of OpenAlex institutions.",
|
||||
)
|
||||
async def list_institutions(
|
||||
search: Annotated[
|
||||
str | None,
|
||||
Query(description="Full-text search, for example 'Duisburg Essen'."),
|
||||
] = None,
|
||||
filter: Annotated[
|
||||
str | None,
|
||||
Query(description="OpenAlex filter, for example 'country_code:DE,type:education'."),
|
||||
] = None,
|
||||
sort: Annotated[
|
||||
str | None,
|
||||
Query(description="Sort field, for example 'works_count:desc'."),
|
||||
] = "works_count:desc",
|
||||
group_by: Annotated[
|
||||
str | None,
|
||||
Query(description="OpenAlex group_by field, for example 'country_code'."),
|
||||
] = None,
|
||||
per_page: Annotated[
|
||||
int,
|
||||
Query(description="Results per page.", ge=1, le=100),
|
||||
] = 25,
|
||||
page: Annotated[
|
||||
int | None,
|
||||
Query(description="Page number. Use cursor for deep pagination.", ge=1),
|
||||
] = 1,
|
||||
cursor: Annotated[
|
||||
str | None,
|
||||
Query(description="Cursor pagination token. Use '*' to start."),
|
||||
] = None,
|
||||
sample: Annotated[
|
||||
int | None,
|
||||
Query(description="Random sample size. Cannot be combined with sort or page.", ge=1, le=10000),
|
||||
] = None,
|
||||
select: Annotated[
|
||||
str | None,
|
||||
Query(description="Comma-separated fields to return."),
|
||||
] = None,
|
||||
):
|
||||
return await logic.list_institutions(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
group_by=group_by,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
sample=sample,
|
||||
select=select,
|
||||
)
|
||||
@@ -0,0 +1,236 @@
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from inse.institutions import logic
|
||||
from inse.institutions.search_client import OpenAlexInstitutionsClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_institutions_maps_openalex_response_to_model():
|
||||
def handler(_: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||
"results": [
|
||||
{
|
||||
"id": "https://openalex.org/I123",
|
||||
"ror": "https://ror.org/04mz5ra38",
|
||||
"display_name": "University of Duisburg-Essen",
|
||||
"country_code": "DE",
|
||||
"type": "education",
|
||||
"homepage_url": "https://www.uni-due.de",
|
||||
"image_url": "https://example.org/image.jpg",
|
||||
"image_thumbnail_url": "https://example.org/thumb.jpg",
|
||||
"display_name_acronyms": ["UDE"],
|
||||
"display_name_alternatives": ["Universitaet Duisburg-Essen"],
|
||||
"works_count": 123,
|
||||
"cited_by_count": 456,
|
||||
"summary_stats": {
|
||||
"2yr_mean_citedness": 1.5,
|
||||
"h_index": 42,
|
||||
"i10_index": 99,
|
||||
},
|
||||
"geo": {
|
||||
"city": "Duisburg",
|
||||
"geonames_city_id": "2934691",
|
||||
"region": "North Rhine-Westphalia",
|
||||
"country_code": "DE",
|
||||
"country": "Germany",
|
||||
"latitude": 51.4344,
|
||||
"longitude": 6.7623,
|
||||
},
|
||||
"lineage": ["https://openalex.org/I123"],
|
||||
"ids": {
|
||||
"openalex": "https://openalex.org/I123",
|
||||
"ror": "https://ror.org/04mz5ra38",
|
||||
"mag": 123,
|
||||
"grid": "grid.12345.6",
|
||||
"wikipedia": "https://en.wikipedia.org/wiki/University_of_Duisburg-Essen",
|
||||
"wikidata": "https://www.wikidata.org/wiki/Q317070",
|
||||
},
|
||||
"counts_by_year": [
|
||||
{
|
||||
"year": 2024,
|
||||
"works_count": 12,
|
||||
"cited_by_count": 34,
|
||||
}
|
||||
],
|
||||
"works_api_url": "https://api.openalex.org/works?filter=institutions.id:I123",
|
||||
"created_date": "2023-12-25",
|
||||
"updated_date": "2023-11-07T05:31:56Z",
|
||||
}
|
||||
],
|
||||
"group_by": [
|
||||
{
|
||||
"key": "DE",
|
||||
"key_display_name": "Germany",
|
||||
"count": 1,
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexInstitutionsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
result = await logic.list_institutions(search="Duisburg Essen", client=client)
|
||||
|
||||
assert result.meta.count == 1
|
||||
institution = result.results[0]
|
||||
assert institution.display_name == "University of Duisburg-Essen"
|
||||
assert institution.summary_stats.h_index == 42
|
||||
assert institution.geo.country == "Germany"
|
||||
assert institution.ids.mag == 123
|
||||
assert institution.counts_by_year[0].year == 2024
|
||||
assert result.group_by[0].key_display_name == "Germany"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_institutions_rejects_sample_with_sort():
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await logic.list_institutions(sample=10, sort="works_count:desc")
|
||||
|
||||
assert exc_info.value.status_code == 400
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_institutions_accepts_practical_openalex_type_variants():
|
||||
def handler(_: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||
"results": [
|
||||
{
|
||||
"id": 123,
|
||||
"ror": 456,
|
||||
"display_name": "Example Institute",
|
||||
"country_code": 789,
|
||||
"type": "unknown-openalex-type",
|
||||
"display_name_acronyms": ["EI", 123],
|
||||
"display_name_alternatives": "not-a-list",
|
||||
"works_count": "12",
|
||||
"cited_by_count": "34.0",
|
||||
"summary_stats": {
|
||||
"2yr_mean_citedness": "1.25",
|
||||
"h_index": "10.0",
|
||||
"i10_index": True,
|
||||
},
|
||||
"geo": {
|
||||
"city": 123,
|
||||
"geonames_city_id": 12345,
|
||||
"latitude": "51.4",
|
||||
"longitude": "6",
|
||||
},
|
||||
"ids": {"openalex": 123, "mag": "123"},
|
||||
"counts_by_year": [
|
||||
{
|
||||
"year": "2024",
|
||||
"works_count": "12.0",
|
||||
"cited_by_count": False,
|
||||
}
|
||||
],
|
||||
"created_date": "2023-12-25T10:11:12Z",
|
||||
"updated_date": "2023-12-25",
|
||||
}
|
||||
],
|
||||
"group_by": [{"key": True, "count": 1}],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexInstitutionsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
result = await logic.list_institutions(client=client)
|
||||
|
||||
assert result.results[0].id == "123"
|
||||
assert result.results[0].ror == "456"
|
||||
assert result.results[0].country_code == "789"
|
||||
assert result.results[0].type is None
|
||||
assert result.results[0].display_name_acronyms == ["EI", "123"]
|
||||
assert result.results[0].display_name_alternatives is None
|
||||
assert result.results[0].works_count == 12
|
||||
assert result.results[0].cited_by_count == 34
|
||||
assert result.results[0].summary_stats.var_2yr_mean_citedness == 1.25
|
||||
assert result.results[0].summary_stats.h_index == 10
|
||||
assert result.results[0].summary_stats.i10_index is None
|
||||
assert result.results[0].geo.city == "123"
|
||||
assert result.results[0].geo.geonames_city_id == "12345"
|
||||
assert result.results[0].geo.latitude == 51.4
|
||||
assert result.results[0].geo.longitude == 6
|
||||
assert result.results[0].ids.openalex == "123"
|
||||
assert result.results[0].ids.mag == 123
|
||||
assert result.results[0].counts_by_year[0].year == 2024
|
||||
assert result.results[0].counts_by_year[0].works_count == 12
|
||||
assert result.results[0].counts_by_year[0].cited_by_count is None
|
||||
assert result.group_by[0].key == "true"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_autocomplete_institutions_returns_frontend_options():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
assert request.url.params["search"] == "Duisburg Essen"
|
||||
assert request.url.params["filter"] == "country_code:DE,type:education"
|
||||
assert request.url.params["sort"] == "works_count:desc"
|
||||
assert request.url.params["per_page"] == "5"
|
||||
assert request.url.params["select"] == (
|
||||
"id,ror,display_name,country_code,type,works_count,"
|
||||
"cited_by_count,geo"
|
||||
)
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "db_response_time_ms": 12},
|
||||
"results": [
|
||||
{
|
||||
"id": "https://openalex.org/I123",
|
||||
"ror": "https://ror.org/04mz5ra38",
|
||||
"display_name": "University of Duisburg-Essen",
|
||||
"country_code": "DE",
|
||||
"type": "education",
|
||||
"works_count": 123,
|
||||
"cited_by_count": 456,
|
||||
"geo": {
|
||||
"city": "Duisburg",
|
||||
"country": "Germany",
|
||||
},
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexInstitutionsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
result = await logic.autocomplete_institutions(
|
||||
query="Duisburg Essen",
|
||||
country_code="DE",
|
||||
institution_type="education",
|
||||
limit=5,
|
||||
client=client,
|
||||
)
|
||||
|
||||
assert result.meta.count == 1
|
||||
assert result.meta.db_response_time_ms == 12
|
||||
assert len(result.results) == 1
|
||||
option = result.results[0]
|
||||
assert option.id == "https://openalex.org/I123"
|
||||
assert option.display_name == "University of Duisburg-Essen"
|
||||
assert option.hint == "Duisburg · Germany · education"
|
||||
assert option.works_count == 123
|
||||
assert option.cited_by_count == 456
|
||||
assert option.entity_type == "institution"
|
||||
assert option.external_id == "https://ror.org/04mz5ra38"
|
||||
@@ -0,0 +1,77 @@
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from inse.institutions.search_client import OpenAlexInstitutionsClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
def test_list_institutions_params_include_openalex_query_parameters():
|
||||
client = OpenAlexInstitutionsClient(api_key="test-key")
|
||||
|
||||
params = client.list_institutions_params(
|
||||
search="Duisburg Essen",
|
||||
filter="country_code:DE,type:education",
|
||||
sort="works_count:desc",
|
||||
group_by="country_code",
|
||||
per_page=10,
|
||||
page=2,
|
||||
select="id,display_name",
|
||||
)
|
||||
|
||||
assert params == {
|
||||
"search": "Duisburg Essen",
|
||||
"filter": "country_code:DE,type:education",
|
||||
"sort": "works_count:desc",
|
||||
"group_by": "country_code",
|
||||
"per_page": 10,
|
||||
"page": 2,
|
||||
"select": "id,display_name",
|
||||
"api_key": "test-key",
|
||||
}
|
||||
|
||||
|
||||
def test_list_institutions_params_prefers_cursor_over_page():
|
||||
client = OpenAlexInstitutionsClient(api_key="test-key")
|
||||
|
||||
params = client.list_institutions_params(cursor="*", page=3)
|
||||
|
||||
assert params["cursor"] == "*"
|
||||
assert "page" not in params
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_institutions_calls_openalex_institutions_endpoint():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
assert request.method == "GET"
|
||||
assert request.url.path == "/institutions"
|
||||
assert request.url.params["search"] == "Duisburg Essen"
|
||||
assert request.url.params["api_key"] == "test-key"
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||
"results": [
|
||||
{
|
||||
"id": "https://openalex.org/I123",
|
||||
"display_name": "University of Duisburg-Essen",
|
||||
"country_code": "DE",
|
||||
"type": "education",
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexInstitutionsClient(
|
||||
base_url="https://api.openalex.org",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
result = await client.list_institutions(search="Duisburg Essen")
|
||||
|
||||
assert result["meta"]["count"] == 1
|
||||
assert result["results"][0]["display_name"] == "University of Duisburg-Essen"
|
||||
@@ -11,6 +11,8 @@ from fastapi import FastAPI
|
||||
from fastapi.responses import RedirectResponse
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from inse.collaboration_network.router import router as collaboration_network_router
|
||||
from inse.institutions.service import router as institutions_service_router
|
||||
from inse.topics.service import router as topics_service_router
|
||||
from inse.works.service import router as works_service_router
|
||||
from inse.persons.service import router as persons_service_router
|
||||
from inse.funders.service import router as funders_service_router
|
||||
@@ -33,6 +35,8 @@ app = FastAPI(
|
||||
servers=settings.servers,
|
||||
)
|
||||
app.include_router(collaboration_network_router)
|
||||
app.include_router(institutions_service_router)
|
||||
app.include_router(topics_service_router)
|
||||
app.include_router(works_service_router)
|
||||
app.include_router(persons_service_router)
|
||||
app.include_router(funders_service_router)
|
||||
|
||||
@@ -4,4 +4,6 @@ from enum import Enum
|
||||
class Tags(Enum):
|
||||
PERSON = "Person"
|
||||
PERSON_NETWORK = "Person Network"
|
||||
WORKS = "Works"
|
||||
INSTITUTIONS = "Institutions"
|
||||
TOPICS = "Topics"
|
||||
WORKS = "Works"
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
OpenAlex topics module.
|
||||
"""
|
||||
@@ -0,0 +1,257 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Business logic for OpenAlex topics.
|
||||
"""
|
||||
import logging
|
||||
from copy import deepcopy
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from pydantic import ValidationError
|
||||
from starlette.status import HTTP_400_BAD_REQUEST
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||
|
||||
from inse.models.autocomplete_response import AutocompleteResponse
|
||||
from inse.models.autocomplete_response_meta import AutocompleteResponseMeta
|
||||
from inse.models.autocomplete_response_results_inner import (
|
||||
AutocompleteResponseResultsInner,
|
||||
)
|
||||
from inse.models.topics_list_response import TopicsListResponse
|
||||
from .search_client import OpenAlexTopicsClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def list_topics(
|
||||
*,
|
||||
search: str | None = None,
|
||||
filter: str | None = None,
|
||||
sort: str | None = None,
|
||||
group_by: str | None = None,
|
||||
per_page: int = 25,
|
||||
page: int | None = 1,
|
||||
cursor: str | None = None,
|
||||
sample: int | None = None,
|
||||
select: str | None = None,
|
||||
client: OpenAlexTopicsClient | None = None,
|
||||
) -> TopicsListResponse:
|
||||
if sample is not None and (sort or page not in (None, 1)):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST,
|
||||
detail="sample cannot be combined with sort or page.",
|
||||
)
|
||||
|
||||
openalex_client = client or OpenAlexTopicsClient()
|
||||
|
||||
try:
|
||||
data = await openalex_client.list_topics(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
group_by=group_by,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
sample=sample,
|
||||
select=select,
|
||||
)
|
||||
except httpx.HTTPStatusError as exc:
|
||||
status_code = exc.response.status_code
|
||||
detail = "OpenAlex topics request failed."
|
||||
try:
|
||||
error_body = exc.response.json()
|
||||
detail = error_body.get("message") or error_body.get("error") or detail
|
||||
except ValueError:
|
||||
if exc.response.text:
|
||||
detail = exc.response.text
|
||||
raise HTTPException(status_code=status_code, detail=detail) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex topics request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex topics request failed.",
|
||||
) from exc
|
||||
|
||||
try:
|
||||
normalized_data = _normalize_topics_response(data)
|
||||
return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse()
|
||||
except ValidationError as exc:
|
||||
logger.exception("OpenAlex topics response could not be parsed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex topics response could not be parsed.",
|
||||
) from exc
|
||||
|
||||
|
||||
async def autocomplete_topics(
|
||||
*,
|
||||
query: str,
|
||||
domain_id: str | None = None,
|
||||
field_id: str | None = None,
|
||||
subfield_id: str | None = None,
|
||||
limit: int = 10,
|
||||
client: OpenAlexTopicsClient | None = None,
|
||||
) -> AutocompleteResponse:
|
||||
filters = []
|
||||
if domain_id:
|
||||
filters.append(f"domain.id:{domain_id}")
|
||||
if field_id:
|
||||
filters.append(f"field.id:{field_id}")
|
||||
if subfield_id:
|
||||
filters.append(f"subfield.id:{subfield_id}")
|
||||
|
||||
response = await list_topics(
|
||||
search=query,
|
||||
filter=",".join(filters) if filters else None,
|
||||
sort="works_count:desc",
|
||||
per_page=limit,
|
||||
page=1,
|
||||
select=(
|
||||
"id,display_name,description,keywords,subfield,field,domain,"
|
||||
"works_count,cited_by_count,ids"
|
||||
),
|
||||
client=client,
|
||||
)
|
||||
|
||||
results = []
|
||||
for topic in response.results or []:
|
||||
if not topic.id or not topic.display_name:
|
||||
continue
|
||||
|
||||
hint_parts = []
|
||||
if topic.var_field and topic.var_field.display_name:
|
||||
hint_parts.append(topic.var_field.display_name)
|
||||
if topic.subfield and topic.subfield.display_name:
|
||||
hint_parts.append(topic.subfield.display_name)
|
||||
if topic.domain and topic.domain.display_name:
|
||||
hint_parts.append(topic.domain.display_name)
|
||||
|
||||
results.append(
|
||||
AutocompleteResponseResultsInner(
|
||||
id=topic.id,
|
||||
display_name=topic.display_name,
|
||||
hint=" · ".join(hint_parts) if hint_parts else topic.description,
|
||||
cited_by_count=topic.cited_by_count,
|
||||
works_count=topic.works_count,
|
||||
entity_type="topic",
|
||||
external_id=topic.ids.openalex if topic.ids else None,
|
||||
)
|
||||
)
|
||||
|
||||
return AutocompleteResponse(
|
||||
meta=AutocompleteResponseMeta(
|
||||
count=response.meta.count if response.meta else len(results),
|
||||
db_response_time_ms=(
|
||||
response.meta.db_response_time_ms if response.meta else None
|
||||
),
|
||||
),
|
||||
results=results,
|
||||
)
|
||||
|
||||
|
||||
def _normalize_topics_response(data: dict[str, Any]) -> dict[str, Any]:
|
||||
normalized = deepcopy(data)
|
||||
|
||||
meta = normalized.get("meta")
|
||||
if isinstance(meta, dict):
|
||||
for field in ["count", "db_response_time_ms", "page", "per_page", "groups_count"]:
|
||||
meta[field] = _int_or_none(meta.get(field))
|
||||
meta["next_cursor"] = _str_or_none(meta.get("next_cursor"))
|
||||
meta["cost_usd"] = _number_or_none(meta.get("cost_usd"))
|
||||
|
||||
for topic in normalized.get("results") or []:
|
||||
if not isinstance(topic, dict):
|
||||
continue
|
||||
|
||||
for field in ["id", "display_name", "description", "works_api_url"]:
|
||||
topic[field] = _str_or_none(topic.get(field))
|
||||
topic["keywords"] = _str_list_or_none(topic.get("keywords"))
|
||||
topic["works_count"] = _int_or_none(topic.get("works_count"))
|
||||
topic["cited_by_count"] = _int_or_none(topic.get("cited_by_count"))
|
||||
topic["created_date"] = _date_str_or_none(topic.get("created_date"))
|
||||
topic["updated_date"] = _datetime_str_or_none(topic.get("updated_date"))
|
||||
|
||||
for relation_field in ["subfield", "field", "domain"]:
|
||||
relation = topic.get(relation_field)
|
||||
if not isinstance(relation, dict):
|
||||
continue
|
||||
relation["id"] = _str_or_none(relation.get("id"))
|
||||
relation["display_name"] = _str_or_none(relation.get("display_name"))
|
||||
|
||||
ids = topic.get("ids")
|
||||
if isinstance(ids, dict):
|
||||
for field in ["openalex", "wikipedia"]:
|
||||
ids[field] = _str_or_none(ids.get(field))
|
||||
|
||||
for group in normalized.get("group_by") or []:
|
||||
if not isinstance(group, dict):
|
||||
continue
|
||||
|
||||
group["key"] = _str_or_none(group.get("key"))
|
||||
group["key_display_name"] = _str_or_none(group.get("key_display_name"))
|
||||
group["count"] = _int_or_none(group.get("count"))
|
||||
|
||||
return normalized
|
||||
|
||||
|
||||
def _str_or_none(value: Any) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, bool):
|
||||
return str(value).lower()
|
||||
return str(value)
|
||||
|
||||
|
||||
def _str_list_or_none(value: Any) -> list[str] | None:
|
||||
if value is None:
|
||||
return None
|
||||
if not isinstance(value, list):
|
||||
return None
|
||||
return [_str_or_none(item) for item in value if item is not None]
|
||||
|
||||
|
||||
def _int_or_none(value: Any) -> int | None:
|
||||
if value is None or isinstance(value, bool):
|
||||
return None
|
||||
if isinstance(value, int):
|
||||
return value
|
||||
if isinstance(value, float):
|
||||
return int(value)
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
return int(float(value))
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _number_or_none(value: Any) -> int | float | None:
|
||||
if value is None or isinstance(value, bool):
|
||||
return None
|
||||
if isinstance(value, (int, float)):
|
||||
return value
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
number = float(value)
|
||||
except ValueError:
|
||||
return None
|
||||
return int(number) if number.is_integer() else number
|
||||
return None
|
||||
|
||||
|
||||
def _date_str_or_none(value: Any) -> str | None:
|
||||
text = _str_or_none(value)
|
||||
if not text:
|
||||
return None
|
||||
return text[:10]
|
||||
|
||||
|
||||
def _datetime_str_or_none(value: Any) -> str | None:
|
||||
text = _str_or_none(value)
|
||||
if not text:
|
||||
return None
|
||||
if len(text) == 10:
|
||||
return f"{text}T00:00:00Z"
|
||||
return text
|
||||
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
HTTP client for OpenAlex topics.
|
||||
"""
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
class OpenAlexTopicsClient:
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
api_key: str | None = None,
|
||||
timeout: float | None = None,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
):
|
||||
self.base_url = (base_url or config.settings.openalex_api_base_url).rstrip("/")
|
||||
self.api_key = api_key if api_key is not None else config.settings.openalex_api_key
|
||||
self.timeout = (
|
||||
timeout
|
||||
if timeout is not None
|
||||
else config.settings.openalex_api_timeout_seconds
|
||||
)
|
||||
self.transport = transport
|
||||
|
||||
def list_topics_params(
|
||||
self,
|
||||
*,
|
||||
search: str | None = None,
|
||||
filter: str | None = None,
|
||||
sort: str | None = None,
|
||||
group_by: str | None = None,
|
||||
per_page: int = 25,
|
||||
page: int | None = 1,
|
||||
cursor: str | None = None,
|
||||
sample: int | None = None,
|
||||
select: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
params: dict[str, Any] = {"per_page": per_page}
|
||||
|
||||
if search:
|
||||
params["search"] = search
|
||||
if filter:
|
||||
params["filter"] = filter
|
||||
if sort:
|
||||
params["sort"] = sort
|
||||
if group_by:
|
||||
params["group_by"] = group_by
|
||||
if cursor:
|
||||
params["cursor"] = cursor
|
||||
elif page is not None:
|
||||
params["page"] = page
|
||||
if sample is not None:
|
||||
params["sample"] = sample
|
||||
if select:
|
||||
params["select"] = select
|
||||
if self.api_key:
|
||||
params["api_key"] = self.api_key
|
||||
|
||||
return params
|
||||
|
||||
async def list_topics(
|
||||
self,
|
||||
*,
|
||||
search: str | None = None,
|
||||
filter: str | None = None,
|
||||
sort: str | None = None,
|
||||
group_by: str | None = None,
|
||||
per_page: int = 25,
|
||||
page: int | None = 1,
|
||||
cursor: str | None = None,
|
||||
sample: int | None = None,
|
||||
select: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.get(
|
||||
"/topics",
|
||||
params=self.list_topics_params(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
group_by=group_by,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
sample=sample,
|
||||
select=select,
|
||||
),
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
@@ -0,0 +1,113 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
REST API for OpenAlex topics.
|
||||
"""
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter
|
||||
from fastapi import Query
|
||||
|
||||
from inse.models.autocomplete_response import AutocompleteResponse
|
||||
from inse.models.topics_list_response import TopicsListResponse
|
||||
from inse.tags import Tags
|
||||
from . import logic
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/topics", tags=[Tags.TOPICS])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/autocomplete",
|
||||
operation_id="autocompleteTopics",
|
||||
response_model=AutocompleteResponse,
|
||||
response_model_exclude_none=True,
|
||||
summary="Returns topic options for autocomplete inputs.",
|
||||
)
|
||||
async def autocomplete_topics(
|
||||
query: Annotated[
|
||||
str,
|
||||
Query(description="Topic search text, for example 'machine learning'.", min_length=1),
|
||||
],
|
||||
domain_id: Annotated[
|
||||
str | None,
|
||||
Query(alias="domainId", description="Optional OpenAlex domain id filter."),
|
||||
] = None,
|
||||
field_id: Annotated[
|
||||
str | None,
|
||||
Query(alias="fieldId", description="Optional OpenAlex field id filter."),
|
||||
] = None,
|
||||
subfield_id: Annotated[
|
||||
str | None,
|
||||
Query(alias="subfieldId", description="Optional OpenAlex subfield id filter."),
|
||||
] = None,
|
||||
limit: Annotated[
|
||||
int,
|
||||
Query(description="Maximum number of autocomplete options.", ge=1, le=25),
|
||||
] = 10,
|
||||
):
|
||||
return await logic.autocomplete_topics(
|
||||
query=query,
|
||||
domain_id=domain_id,
|
||||
field_id=field_id,
|
||||
subfield_id=subfield_id,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
operation_id="listTopics",
|
||||
response_model=TopicsListResponse,
|
||||
response_model_exclude_none=True,
|
||||
summary="Returns a list of OpenAlex topics.",
|
||||
)
|
||||
async def list_topics(
|
||||
search: Annotated[
|
||||
str | None,
|
||||
Query(description="Full-text search, for example 'machine learning'."),
|
||||
] = None,
|
||||
filter: Annotated[
|
||||
str | None,
|
||||
Query(description="OpenAlex filter, for example 'domain.id:1,works_count:>1000'."),
|
||||
] = None,
|
||||
sort: Annotated[
|
||||
str | None,
|
||||
Query(description="Sort field, for example 'works_count:desc'."),
|
||||
] = "works_count:desc",
|
||||
group_by: Annotated[
|
||||
str | None,
|
||||
Query(description="OpenAlex group_by field, for example 'domain.id'."),
|
||||
] = None,
|
||||
per_page: Annotated[
|
||||
int,
|
||||
Query(description="Results per page.", ge=1, le=100),
|
||||
] = 25,
|
||||
page: Annotated[
|
||||
int | None,
|
||||
Query(description="Page number. Use cursor for deep pagination.", ge=1),
|
||||
] = 1,
|
||||
cursor: Annotated[
|
||||
str | None,
|
||||
Query(description="Cursor pagination token. Use '*' to start."),
|
||||
] = None,
|
||||
sample: Annotated[
|
||||
int | None,
|
||||
Query(description="Random sample size. Cannot be combined with sort or page.", ge=1, le=10000),
|
||||
] = None,
|
||||
select: Annotated[
|
||||
str | None,
|
||||
Query(description="Comma-separated fields to return."),
|
||||
] = None,
|
||||
):
|
||||
return await logic.list_topics(
|
||||
search=search,
|
||||
filter=filter,
|
||||
sort=sort,
|
||||
group_by=group_by,
|
||||
per_page=per_page,
|
||||
page=page,
|
||||
cursor=cursor,
|
||||
sample=sample,
|
||||
select=select,
|
||||
)
|
||||
@@ -0,0 +1,195 @@
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from inse.topics import logic
|
||||
from inse.topics.search_client import OpenAlexTopicsClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_maps_openalex_response_to_model():
|
||||
def handler(_: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||
"results": [
|
||||
{
|
||||
"id": "https://openalex.org/T12419",
|
||||
"display_name": "Machine learning",
|
||||
"description": "Methods that learn from data.",
|
||||
"keywords": ["machine learning", "classification"],
|
||||
"subfield": {
|
||||
"id": "https://openalex.org/subfields/1702",
|
||||
"display_name": "Artificial Intelligence",
|
||||
},
|
||||
"field": {
|
||||
"id": "https://openalex.org/fields/17",
|
||||
"display_name": "Computer Science",
|
||||
},
|
||||
"domain": {
|
||||
"id": "https://openalex.org/domains/4",
|
||||
"display_name": "Physical Sciences",
|
||||
},
|
||||
"works_count": 123,
|
||||
"cited_by_count": 456,
|
||||
"ids": {
|
||||
"openalex": "https://openalex.org/T12419",
|
||||
"wikipedia": "https://en.wikipedia.org/wiki/Machine_learning",
|
||||
},
|
||||
"works_api_url": "https://api.openalex.org/works?filter=topics.id:T12419",
|
||||
"created_date": "2023-12-25",
|
||||
"updated_date": "2023-11-07T05:31:56Z",
|
||||
}
|
||||
],
|
||||
"group_by": [
|
||||
{
|
||||
"key": "https://openalex.org/domains/4",
|
||||
"key_display_name": "Physical Sciences",
|
||||
"count": 1,
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexTopicsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
result = await logic.list_topics(search="machine learning", client=client)
|
||||
|
||||
assert result.meta.count == 1
|
||||
topic = result.results[0]
|
||||
assert topic.display_name == "Machine learning"
|
||||
assert topic.var_field.display_name == "Computer Science"
|
||||
assert topic.subfield.display_name == "Artificial Intelligence"
|
||||
assert topic.domain.display_name == "Physical Sciences"
|
||||
assert topic.ids.openalex == "https://openalex.org/T12419"
|
||||
assert result.group_by[0].key_display_name == "Physical Sciences"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_rejects_sample_with_sort():
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await logic.list_topics(sample=10, sort="works_count:desc")
|
||||
|
||||
assert exc_info.value.status_code == 400
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_accepts_practical_openalex_type_variants():
|
||||
def handler(_: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": "1", "page": "1", "per_page": "25"},
|
||||
"results": [
|
||||
{
|
||||
"id": 123,
|
||||
"display_name": 456,
|
||||
"description": True,
|
||||
"keywords": ["topic", 123],
|
||||
"subfield": {"id": 1, "display_name": 2},
|
||||
"field": {"id": 3, "display_name": 4},
|
||||
"domain": {"id": 5, "display_name": 6},
|
||||
"works_count": "12.0",
|
||||
"cited_by_count": False,
|
||||
"ids": {"openalex": 123, "wikipedia": 456},
|
||||
"created_date": "2023-12-25T10:11:12Z",
|
||||
"updated_date": "2023-12-25",
|
||||
}
|
||||
],
|
||||
"group_by": [{"key": True, "count": "1"}],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexTopicsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
result = await logic.list_topics(client=client)
|
||||
|
||||
topic = result.results[0]
|
||||
assert topic.id == "123"
|
||||
assert topic.display_name == "456"
|
||||
assert topic.description == "true"
|
||||
assert topic.keywords == ["topic", "123"]
|
||||
assert topic.works_count == 12
|
||||
assert topic.cited_by_count is None
|
||||
assert topic.var_field.id == "3"
|
||||
assert topic.domain.display_name == "6"
|
||||
assert topic.ids.wikipedia == "456"
|
||||
assert topic.created_date.isoformat() == "2023-12-25"
|
||||
assert topic.updated_date.isoformat() == "2023-12-25T00:00:00+00:00"
|
||||
assert result.group_by[0].key == "true"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_autocomplete_topics_returns_frontend_options():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
assert request.url.params["search"] == "machine learning"
|
||||
assert request.url.params["filter"] == (
|
||||
"domain.id:https://openalex.org/domains/4,"
|
||||
"field.id:https://openalex.org/fields/17,"
|
||||
"subfield.id:https://openalex.org/subfields/1702"
|
||||
)
|
||||
assert request.url.params["sort"] == "works_count:desc"
|
||||
assert request.url.params["per_page"] == "5"
|
||||
assert request.url.params["select"] == (
|
||||
"id,display_name,description,keywords,subfield,field,domain,"
|
||||
"works_count,cited_by_count,ids"
|
||||
)
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "db_response_time_ms": 12},
|
||||
"results": [
|
||||
{
|
||||
"id": "https://openalex.org/T12419",
|
||||
"display_name": "Machine learning",
|
||||
"description": "Methods that learn from data.",
|
||||
"field": {"display_name": "Computer Science"},
|
||||
"subfield": {"display_name": "Artificial Intelligence"},
|
||||
"domain": {"display_name": "Physical Sciences"},
|
||||
"works_count": 123,
|
||||
"cited_by_count": 456,
|
||||
"ids": {"openalex": "https://openalex.org/T12419"},
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexTopicsClient(
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
result = await logic.autocomplete_topics(
|
||||
query="machine learning",
|
||||
domain_id="https://openalex.org/domains/4",
|
||||
field_id="https://openalex.org/fields/17",
|
||||
subfield_id="https://openalex.org/subfields/1702",
|
||||
limit=5,
|
||||
client=client,
|
||||
)
|
||||
|
||||
assert result.meta.count == 1
|
||||
assert result.meta.db_response_time_ms == 12
|
||||
assert len(result.results) == 1
|
||||
option = result.results[0]
|
||||
assert option.id == "https://openalex.org/T12419"
|
||||
assert option.display_name == "Machine learning"
|
||||
assert option.hint == (
|
||||
"Computer Science · Artificial Intelligence · Physical Sciences"
|
||||
)
|
||||
assert option.works_count == 123
|
||||
assert option.cited_by_count == 456
|
||||
assert option.entity_type == "topic"
|
||||
assert option.external_id == "https://openalex.org/T12419"
|
||||
@@ -0,0 +1,75 @@
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from inse.topics.search_client import OpenAlexTopicsClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
def test_list_topics_params_include_openalex_query_parameters():
|
||||
client = OpenAlexTopicsClient(api_key="test-key")
|
||||
|
||||
params = client.list_topics_params(
|
||||
search="machine learning",
|
||||
filter="domain.id:4,works_count:>1000",
|
||||
sort="works_count:desc",
|
||||
group_by="domain.id",
|
||||
per_page=10,
|
||||
page=2,
|
||||
select="id,display_name",
|
||||
)
|
||||
|
||||
assert params == {
|
||||
"search": "machine learning",
|
||||
"filter": "domain.id:4,works_count:>1000",
|
||||
"sort": "works_count:desc",
|
||||
"group_by": "domain.id",
|
||||
"per_page": 10,
|
||||
"page": 2,
|
||||
"select": "id,display_name",
|
||||
"api_key": "test-key",
|
||||
}
|
||||
|
||||
|
||||
def test_list_topics_params_prefers_cursor_over_page():
|
||||
client = OpenAlexTopicsClient(api_key="test-key")
|
||||
|
||||
params = client.list_topics_params(cursor="*", page=3)
|
||||
|
||||
assert params["cursor"] == "*"
|
||||
assert "page" not in params
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_calls_openalex_topics_endpoint():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
assert request.method == "GET"
|
||||
assert request.url.path == "/topics"
|
||||
assert request.url.params["search"] == "machine learning"
|
||||
assert request.url.params["api_key"] == "test-key"
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||
"results": [
|
||||
{
|
||||
"id": "https://openalex.org/T12419",
|
||||
"display_name": "Machine learning",
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexTopicsClient(
|
||||
base_url="https://api.openalex.org",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
result = await client.list_topics(search="machine learning")
|
||||
|
||||
assert result["meta"]["count"] == 1
|
||||
assert result["results"][0]["display_name"] == "Machine learning"
|
||||
@@ -11,6 +11,7 @@ import httpx
|
||||
from fastapi import HTTPException
|
||||
from pydantic import ValidationError
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||
from starlette.status import HTTP_404_NOT_FOUND
|
||||
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
|
||||
|
||||
from inse.models.work import Work
|
||||
@@ -33,6 +34,8 @@ async def get_author_works(
|
||||
publication_year: list[int] | None = None,
|
||||
work_type: list[str] | None = None,
|
||||
language: list[str] | None = None,
|
||||
institution_id: list[str] | None = None,
|
||||
topic_id: list[str] | None = None,
|
||||
client: OpenAlexWorksSearchClient | None = None,
|
||||
) -> WorkPage:
|
||||
search_client = client or OpenAlexWorksSearchClient()
|
||||
@@ -44,6 +47,8 @@ async def get_author_works(
|
||||
publication_year=publication_year,
|
||||
work_type=work_type,
|
||||
language=language,
|
||||
institution_id=institution_id,
|
||||
topic_id=topic_id,
|
||||
)
|
||||
|
||||
elements, total = _parse_full_work_search_response(data)
|
||||
@@ -116,6 +121,32 @@ async def get_primary_topic_counts(
|
||||
]
|
||||
|
||||
|
||||
async def get_work(
|
||||
work_id: str,
|
||||
client: OpenAlexWorksSearchClient | None = None,
|
||||
) -> Work:
|
||||
search_client = client or OpenAlexWorksSearchClient()
|
||||
try:
|
||||
data = await search_client.search_work(work_id)
|
||||
except MissingApiKeyError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="OpenAlex works search is not configured.",
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex works search request failed.",
|
||||
) from exc
|
||||
elements, _ = _parse_full_work_search_response(data)
|
||||
if not elements:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_404_NOT_FOUND,
|
||||
detail="Publication not found.",
|
||||
)
|
||||
return elements[0]
|
||||
|
||||
|
||||
async def get_topics_by_time_by_author(
|
||||
author_id: str,
|
||||
max_topics_per_year: int = 3,
|
||||
@@ -217,6 +248,8 @@ async def _search_author_works_data(
|
||||
publication_year: list[int] | None = None,
|
||||
work_type: list[str] | None = None,
|
||||
language: list[str] | None = None,
|
||||
institution_id: list[str] | None = None,
|
||||
topic_id: list[str] | None = None,
|
||||
) -> dict:
|
||||
try:
|
||||
return await search_client.search_author_works(
|
||||
@@ -226,6 +259,8 @@ async def _search_author_works_data(
|
||||
publication_year=publication_year,
|
||||
work_type=work_type,
|
||||
language=language,
|
||||
institution_id=institution_id,
|
||||
topic_id=topic_id,
|
||||
)
|
||||
except MissingApiKeyError as exc:
|
||||
logger.error("OpenAlex works Elasticsearch API key is not configured.")
|
||||
|
||||
@@ -40,26 +40,52 @@ class OpenAlexWorksSearchClient:
|
||||
publication_year: list[int] | None = None,
|
||||
work_type: list[str] | None = None,
|
||||
language: list[str] | None = None,
|
||||
institution_id: list[str] | None = None,
|
||||
topic_id: list[str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
indexed_author_id = f"https://openalex.org/{author_id.strip()}"
|
||||
filters = self._work_filters(publication_year, work_type, language)
|
||||
filters = self._work_filters(
|
||||
publication_year,
|
||||
work_type,
|
||||
language,
|
||||
topic_id,
|
||||
)
|
||||
author_filters: list[dict[str, Any]] = [
|
||||
{
|
||||
"term": {
|
||||
"authorships.author.id": indexed_author_id,
|
||||
},
|
||||
},
|
||||
]
|
||||
must_clauses: list[dict[str, Any]] = [
|
||||
{
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": author_filters,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
]
|
||||
if institution_id:
|
||||
must_clauses.append({
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {
|
||||
"terms": {
|
||||
"authorships.institutions.id": institution_id,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
return {
|
||||
"from": (page - 1) * size,
|
||||
"size": size,
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [
|
||||
{
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {
|
||||
"term": {
|
||||
"authorships.author.id": indexed_author_id,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
"must": must_clauses,
|
||||
"filter": filters,
|
||||
},
|
||||
},
|
||||
@@ -74,6 +100,7 @@ class OpenAlexWorksSearchClient:
|
||||
publication_year: list[int] | None = None,
|
||||
work_type: list[str] | None = None,
|
||||
language: list[str] | None = None,
|
||||
topic_id: list[str] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
filters: list[dict[str, Any]] = []
|
||||
if publication_year:
|
||||
@@ -82,6 +109,21 @@ class OpenAlexWorksSearchClient:
|
||||
filters.append({"terms": {"type": work_type}})
|
||||
if language:
|
||||
filters.append({"terms": {"language": language}})
|
||||
if topic_id:
|
||||
filters.append({
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"nested": {
|
||||
"path": "topics",
|
||||
"query": {"terms": {"topics.id": topic_id}},
|
||||
},
|
||||
},
|
||||
{"terms": {"primary_topic.id": topic_id}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
},
|
||||
})
|
||||
return filters
|
||||
|
||||
async def search_author_works(
|
||||
@@ -92,6 +134,8 @@ class OpenAlexWorksSearchClient:
|
||||
publication_year: list[int] | None = None,
|
||||
work_type: list[str] | None = None,
|
||||
language: list[str] | None = None,
|
||||
institution_id: list[str] | None = None,
|
||||
topic_id: list[str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
|
||||
@@ -111,8 +155,31 @@ class OpenAlexWorksSearchClient:
|
||||
publication_year=publication_year,
|
||||
work_type=work_type,
|
||||
language=language,
|
||||
institution_id=institution_id,
|
||||
topic_id=topic_id,
|
||||
),
|
||||
)
|
||||
# logging.debug(f"Response: {response.text}")
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
async def search_work(self, work_id: str) -> dict[str, Any]:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
|
||||
|
||||
indexed_work_id = f"https://openalex.org/{work_id.strip().split('/')[-1]}"
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"/{self.index}/_search",
|
||||
headers={"Authorization": f"ApiKey {self.api_key}"},
|
||||
json={
|
||||
"size": 1,
|
||||
"query": {"term": {"id": indexed_work_id}},
|
||||
},
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
@@ -16,6 +16,7 @@ from inse.tags import Tags
|
||||
from .. import security
|
||||
from . import logic
|
||||
from inse.models.work_page import WorkPage
|
||||
from inse.models.work import Work
|
||||
from inse.models.works_list_response import WorksListResponse
|
||||
from inse.models.topic_count import TopicCount
|
||||
from inse.models.topics_by_time import TopicsByTime
|
||||
@@ -47,6 +48,14 @@ async def get_author_works(
|
||||
language: Annotated[
|
||||
list[str] | None, Query(description="Filter by language code. Can be repeated.")
|
||||
] = None,
|
||||
institution_id: Annotated[
|
||||
list[str] | None,
|
||||
Query(description="Filter by OpenAlex institution id. Can be repeated."),
|
||||
] = None,
|
||||
topic_id: Annotated[
|
||||
list[str] | None,
|
||||
Query(description="Filter by OpenAlex topic id. Can be repeated."),
|
||||
] = None,
|
||||
principal: security.Principal = Depends(
|
||||
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
|
||||
),
|
||||
@@ -58,6 +67,8 @@ async def get_author_works(
|
||||
publication_year=publication_year,
|
||||
work_type=work_type,
|
||||
language=language,
|
||||
institution_id=institution_id,
|
||||
topic_id=topic_id,
|
||||
)
|
||||
|
||||
|
||||
@@ -96,3 +107,20 @@ async def get_topics_by_time_by_author(
|
||||
author_id,
|
||||
max_topics_per_year=max_topics_per_year,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/detail/{work_id}",
|
||||
operation_id="getWork",
|
||||
response_model=Work,
|
||||
summary="Returns one publication.",
|
||||
)
|
||||
async def get_work(
|
||||
work_id: Annotated[
|
||||
str, Path(description="The OpenAlex work id, for example W2741809807.")
|
||||
],
|
||||
principal: security.Principal = Depends(
|
||||
security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])
|
||||
),
|
||||
):
|
||||
return await logic.get_work(work_id)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
@@ -19,7 +21,9 @@ def test_author_works_query_searches_authorship_author_id():
|
||||
assert query["size"] == 25
|
||||
author_query = query["query"]["bool"]["must"][0]["nested"]
|
||||
assert author_query["path"] == "authorships"
|
||||
assert author_query["query"]["term"]["authorships.author.id"] == "https://openalex.org/A5023888391"
|
||||
assert author_query["query"]["bool"]["filter"] == [
|
||||
{"term": {"authorships.author.id": "https://openalex.org/A5023888391"}},
|
||||
]
|
||||
assert query["query"]["bool"]["filter"] == []
|
||||
|
||||
|
||||
@@ -33,13 +37,191 @@ def test_author_works_query_adds_publication_filters():
|
||||
publication_year=[2023, 2024],
|
||||
work_type=["article", "book-chapter"],
|
||||
language=["en", "de"],
|
||||
institution_id=["https://openalex.org/I123"],
|
||||
topic_id=["https://openalex.org/T12419"],
|
||||
)
|
||||
|
||||
assert query["query"]["bool"]["filter"] == [
|
||||
{"terms": {"publication_year": [2023, 2024]}},
|
||||
{"terms": {"type": ["article", "book-chapter"]}},
|
||||
{"terms": {"language": ["en", "de"]}},
|
||||
{
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"nested": {
|
||||
"path": "topics",
|
||||
"query": {
|
||||
"terms": {
|
||||
"topics.id": ["https://openalex.org/T12419"],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{"terms": {"primary_topic.id": ["https://openalex.org/T12419"]}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
},
|
||||
},
|
||||
]
|
||||
assert query["query"]["bool"]["must"] == [
|
||||
{
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{
|
||||
"term": {
|
||||
"authorships.author.id": "https://openalex.org/A5023888391"
|
||||
}
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {
|
||||
"terms": {
|
||||
"authorships.institutions.id": [
|
||||
"https://openalex.org/I123",
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def test_author_works_query_uses_nested_institution_path():
|
||||
client = OpenAlexWorksSearchClient(api_key="test-key")
|
||||
|
||||
query = client.author_works_query(
|
||||
"A5023888391",
|
||||
page=1,
|
||||
size=20,
|
||||
institution_id=["https://openalex.org/I205640436"],
|
||||
)
|
||||
|
||||
assert query["query"]["bool"]["must"][1] == {
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {
|
||||
"terms": {
|
||||
"authorships.institutions.id": [
|
||||
"https://openalex.org/I205640436",
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_author_works_query_adds_topic_filter():
|
||||
client = OpenAlexWorksSearchClient(api_key="test-key")
|
||||
|
||||
query = client.author_works_query(
|
||||
"A5023888391",
|
||||
page=1,
|
||||
size=20,
|
||||
topic_id=["https://openalex.org/T12419"],
|
||||
)
|
||||
|
||||
assert query["query"]["bool"]["filter"] == [
|
||||
{
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"nested": {
|
||||
"path": "topics",
|
||||
"query": {
|
||||
"terms": {
|
||||
"topics.id": ["https://openalex.org/T12419"],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{"terms": {"primary_topic.id": ["https://openalex.org/T12419"]}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_search_author_works_passes_institution_filter_to_query():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
body = json.loads(request.content)
|
||||
assert body["query"]["bool"]["must"][1]["nested"]["path"] == (
|
||||
"authorships.institutions"
|
||||
)
|
||||
assert body["query"]["bool"]["must"][1]["nested"]["query"]["terms"] == {
|
||||
"authorships.institutions.id": ["https://openalex.org/I205640436"],
|
||||
}
|
||||
return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}})
|
||||
|
||||
client = OpenAlexWorksSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
index="openalex-works",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
await client.search_author_works(
|
||||
"A5023888391",
|
||||
page=1,
|
||||
size=20,
|
||||
institution_id=["https://openalex.org/I205640436"],
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_search_author_works_passes_topic_filter_to_query():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
body = json.loads(request.content)
|
||||
assert body["query"]["bool"]["filter"] == [
|
||||
{
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"nested": {
|
||||
"path": "topics",
|
||||
"query": {
|
||||
"terms": {
|
||||
"topics.id": ["https://openalex.org/T12419"],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"terms": {
|
||||
"primary_topic.id": ["https://openalex.org/T12419"],
|
||||
},
|
||||
},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
},
|
||||
},
|
||||
]
|
||||
return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}})
|
||||
|
||||
client = OpenAlexWorksSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
index="openalex-works",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
await client.search_author_works(
|
||||
"A5023888391",
|
||||
page=1,
|
||||
size=20,
|
||||
topic_id=["https://openalex.org/T12419"],
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -62,6 +244,26 @@ async def test_search_author_works_calls_elasticsearch_index_with_api_key():
|
||||
assert result == {"hits": {"total": {"value": 0}, "hits": []}}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_search_work_filters_by_work_id():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
body = json.loads(request.content)
|
||||
assert body == {
|
||||
"size": 1,
|
||||
"query": {"term": {"id": "https://openalex.org/W2741809807"}},
|
||||
}
|
||||
return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}})
|
||||
|
||||
client = OpenAlexWorksSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
index="openalex-works",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
await client.search_work("W2741809807")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_search_author_works_requires_api_key():
|
||||
client = OpenAlexWorksSearchClient(api_key="")
|
||||
|
||||
Reference in New Issue
Block a user