Refactor funders logic into separate module and add tests
LocationBasedServices/smartguide/pipeline/head This commit looks good

This commit is contained in:
2026-06-01 22:21:50 +02:00
parent fac08044a8
commit 5294d26552
8 changed files with 580 additions and 203 deletions
@@ -0,0 +1,5 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Funders domain package.
"""
@@ -0,0 +1,123 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
HTTP client for funded-publication searches in the OpenAlex works index.
"""
from typing import Any
import httpx
from .. import config
class MissingApiKeyError(Exception):
pass
class FundedPublicationsSearchClient:
def __init__(
self,
base_url: str | None = None,
index: 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_works_search_base_url).rstrip("/")
self.index = index or config.settings.openalex_works_search_index
self.api_key = api_key if api_key is not None else config.settings.openalex_works_api_key
self.timeout = timeout if timeout is not None else config.settings.openalex_works_search_timeout_seconds
self.transport = transport
@staticmethod
def indexed_author_id(author_id: str) -> str:
short_id = author_id.strip().removeprefix("https://openalex.org/")
return f"https://openalex.org/{short_id}"
def funded_publications_by_author_query(
self,
author_id: str,
page: int,
size: int,
) -> dict[str, Any]:
indexed_author_id = self.indexed_author_id(author_id)
return {
"from": (page - 1) * size,
"size": size,
"_source": [
"id",
"title",
"display_name",
"publication_year",
"authorships.author.id",
"authorships.author.display_name",
"authorships.author_position",
"funders.id",
"funders.display_name",
"funders.ror",
"awards.id",
"awards.funder_id",
"awards.funder_display_name",
"awards.funder_award_id",
],
"query": {
"bool": {
"must": [
{
"nested": {
"path": "authorships",
"query": {
"term": {
"authorships.author.id": indexed_author_id,
},
},
},
},
{
"bool": {
"should": [
{
"nested": {
"path": "funders",
"query": {
"exists": {
"field": "funders.id",
},
},
},
},
{
"nested": {
"path": "awards",
"query": {
"exists": {
"field": "awards.funder_id",
},
},
},
},
],
"minimum_should_match": 1,
},
},
],
},
},
}
async def search(self, payload: dict[str, Any]) -> dict[str, Any]:
if not self.api_key:
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
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=payload,
)
response.raise_for_status()
return response.json()
+203
View File
@@ -0,0 +1,203 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Business logic for author funding based on publication works.
"""
import logging
from typing import Any
import httpx
from fastapi import HTTPException
from starlette.status import HTTP_502_BAD_GATEWAY
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
from .. import logic as person_logic
from . import model
from .elastic_search_client import FundedPublicationsSearchClient
from .elastic_search_client import MissingApiKeyError
logger = logging.getLogger(__name__)
_VALID_AUTHOR_POSITIONS = frozenset({"first", "middle", "last"})
async def get_publications_by_author_id(
author_id: str,
page: int = 1,
page_size: int = 20,
client: FundedPublicationsSearchClient | None = None,
) -> model.PublicationsByAuthorResponse:
search_client = client or FundedPublicationsSearchClient()
data = await _search_funded_publications(
search_client,
author_id,
page,
page_size,
)
total, hits = _parse_publication_search_response(data)
return model.PublicationsByAuthorResponse(
author_id=FundedPublicationsSearchClient.indexed_author_id(author_id),
page=page,
page_size=page_size,
total=total,
results_count=len(hits),
results=hits,
)
async def get_funders_by_author_id(
author_id: str,
client: FundedPublicationsSearchClient | None = None,
) -> model.FundersByAuthorResponse:
search_client = client or FundedPublicationsSearchClient()
page = 1
page_size = 100
funder_counts: dict[str, dict[str, Any]] = {}
normalized_author_id = FundedPublicationsSearchClient.indexed_author_id(author_id)
author_name = _get_author_name(author_id)
while True:
data = await _search_funded_publications(
search_client,
author_id,
page,
page_size,
)
total, results = _parse_publication_search_response(data)
if not results:
break
_collect_funders_from_publications(results, author_id, funder_counts)
if page * page_size >= total:
break
page += 1
funders = sorted(
funder_counts.values(),
key=lambda entry: entry["publication_count"],
reverse=True,
)
return model.FundersByAuthorResponse(
author_id=normalized_author_id,
author_name=author_name,
funder_count=len(funders),
funders=[model.FunderByAuthor.model_validate(entry) for entry in funders],
)
async def _search_funded_publications(
search_client: FundedPublicationsSearchClient,
author_id: str,
page: int,
page_size: int,
) -> dict:
try:
payload = search_client.funded_publications_by_author_query(
author_id,
page,
page_size,
)
return await search_client.search(payload)
except MissingApiKeyError as exc:
logger.error("OpenAlex works Elasticsearch API key is not configured.")
raise HTTPException(
status_code=HTTP_503_SERVICE_UNAVAILABLE,
detail="OpenAlex works search is not configured.",
) from exc
except httpx.HTTPError as exc:
logger.exception("OpenAlex works search request failed.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex works search request failed.",
) from exc
def _parse_publication_search_response(data: dict) -> tuple[int, list[dict]]:
hits = data.get("hits", {})
total = hits.get("total", 0)
if isinstance(total, dict):
total = total.get("value", 0)
return total, hits.get("hits", [])
def _get_author_name(author_id: str) -> str | None:
short_author_id = author_id.replace("https://openalex.org/", "")
search_result = person_logic.search_persons(author_id=short_author_id)
if not search_result.persons:
return None
return search_result.persons[0].name
def _get_author_position_in_publication(publication: dict, author_id: str) -> str:
normalized_author_id = FundedPublicationsSearchClient.indexed_author_id(author_id)
for authorship in publication.get("authorships", []):
author = authorship.get("author", {})
if author.get("id") == normalized_author_id:
position = authorship.get("author_position", "unknown")
if position in _VALID_AUTHOR_POSITIONS:
return position
return "unknown"
return "unknown"
def _collect_funders_from_publications(
results: list[dict],
author_id: str,
funder_counts: dict[str, dict[str, Any]],
) -> None:
for hit in results:
publication = hit.get("_source", {})
publication_id = publication.get("id")
author_position = _get_author_position_in_publication(publication, author_id)
publication_funders: set[tuple[str, str | None, str | None]] = set()
for funder in publication.get("funders", []):
funder_id = funder.get("id")
funder_name = funder.get("display_name")
if funder_id or funder_name:
key = funder_id or funder_name
publication_funders.add((key, funder_id, funder_name))
for award in publication.get("awards", []):
funder_id = award.get("funder_id")
funder_name = award.get("funder_display_name")
if funder_id or funder_name:
key = funder_id or funder_name
publication_funders.add((key, funder_id, funder_name))
for key, funder_id, funder_name in publication_funders:
if key not in funder_counts:
funder_counts[key] = {
"funder_id": funder_id,
"funder_name": funder_name,
"publication_count": 0,
"author_position_count": {
"first": 0,
"middle": 0,
"last": 0,
"unknown": 0,
},
"publication_ids": {
"first": [],
"middle": [],
"last": [],
"unknown": [],
},
}
entry = funder_counts[key]
entry["publication_count"] += 1
entry["author_position_count"][author_position] += 1
entry["publication_ids"][author_position].append(publication_id)
+41
View File
@@ -0,0 +1,41 @@
from typing import Any
from pydantic import BaseModel
class PublicationsByAuthorResponse(BaseModel):
author_id: str
page: int
page_size: int
total: int
results_count: int
results: list[dict[str, Any]]
class PublicationIdsByAuthorPosition(BaseModel):
first: list[str] = []
middle: list[str] = []
last: list[str] = []
unknown: list[str] = []
class AuthorPositionCount(BaseModel):
first: int = 0
middle: int = 0
last: int = 0
unknown: int = 0
class FunderByAuthor(BaseModel):
funder_id: str | None = None
funder_name: str | None = None
publication_count: int
author_position_count: AuthorPositionCount
publication_ids: PublicationIdsByAuthorPosition
class FundersByAuthorResponse(BaseModel):
author_id: str
author_name: str | None = None
funder_count: int
funders: list[FunderByAuthor]
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
REST API for author publications and funding.
"""
from typing import Annotated
from fastapi import APIRouter
from fastapi import Query
from . import logic
from . import model
router = APIRouter(prefix="/authors", tags=["Funding"])
@router.get(
"/{author_id}/publications",
operation_id="getPublicationsByAuthor",
response_model=model.PublicationsByAuthorResponse,
summary="Get funded publications by author.",
)
async def get_publications_by_author(
author_id: str,
page: Annotated[int, Query(ge=1)] = 1,
page_size: Annotated[int, Query(ge=1, le=1000)] = 20,
):
return await logic.get_publications_by_author_id(author_id, page, page_size)
@router.get(
"/{author_id}/funders",
operation_id="getFundersByAuthor",
response_model=model.FundersByAuthorResponse,
summary="Get funding organizations by author.",
)
async def get_funders_by_author(author_id: str):
return await logic.get_funders_by_author_id(author_id)
+166
View File
@@ -0,0 +1,166 @@
import json
import httpx
import pytest
from fastapi import HTTPException
from inse.funders import logic
from inse.funders.elastic_search_client import FundedPublicationsSearchClient
@pytest.fixture
def anyio_backend():
return "asyncio"
def _funded_publication_hit(
work_id: str,
*,
funder_id: str | None = "https://openalex.org/F123",
funder_name: str | None = "Example Funder",
author_position: str = "first",
award_funder_id: str | None = None,
award_funder_name: str | None = None,
) -> dict:
source: dict = {
"id": work_id,
"authorships": [
{
"author": {
"id": "https://openalex.org/A5023888391",
"display_name": "Example Author",
},
"author_position": author_position,
}
],
"funders": [],
"awards": [],
}
if funder_id or funder_name:
source["funders"].append(
{
"id": funder_id,
"display_name": funder_name,
}
)
if award_funder_id or award_funder_name:
source["awards"].append(
{
"funder_id": award_funder_id,
"funder_display_name": award_funder_name,
}
)
return {"_source": source}
@pytest.mark.anyio
async def test_get_funders_by_author_id_aggregates_funders_and_awards(monkeypatch):
def handler(request: httpx.Request) -> httpx.Response:
payload = json.loads(request.content.decode("utf-8"))
assert payload["from"] == 0
return httpx.Response(
200,
json={
"hits": {
"total": {"value": 2},
"hits": [
_funded_publication_hit(
"https://openalex.org/W1",
funder_id="https://openalex.org/F123",
funder_name="Funder A",
author_position="first",
),
_funded_publication_hit(
"https://openalex.org/W2",
funder_id=None,
funder_name=None,
award_funder_id="https://openalex.org/F123",
award_funder_name="Funder A",
author_position="last",
),
],
},
},
)
monkeypatch.setattr(
logic.person_logic,
"search_persons",
lambda author_id: type(
"Result",
(),
{"persons": [type("Person", (), {"name": "Example Author"})()]},
)(),
)
client = FundedPublicationsSearchClient(
base_url="https://project.nes.uni-due.de/elastic",
api_key="test-key",
transport=httpx.MockTransport(handler),
)
response = await logic.get_funders_by_author_id("A5023888391", client=client)
assert response.author_id == "https://openalex.org/A5023888391"
assert response.author_name == "Example Author"
assert response.funder_count == 1
assert response.funders[0].funder_id == "https://openalex.org/F123"
assert response.funders[0].funder_name == "Funder A"
assert response.funders[0].publication_count == 2
assert response.funders[0].author_position_count.first == 1
assert response.funders[0].author_position_count.last == 1
assert response.funders[0].publication_ids.first == ["https://openalex.org/W1"]
assert response.funders[0].publication_ids.last == ["https://openalex.org/W2"]
@pytest.mark.anyio
async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded(monkeypatch):
requested_pages: list[int] = []
def handler(request: httpx.Request) -> httpx.Response:
payload = json.loads(request.content.decode("utf-8"))
page = payload["from"] // payload["size"] + 1
requested_pages.append(page)
return httpx.Response(
200,
json={
"hits": {
"total": {"value": 101},
"hits": [
_funded_publication_hit(
f"https://openalex.org/W{page}",
funder_id=f"https://openalex.org/F{page}",
funder_name=f"Funder {page}",
)
],
},
},
)
monkeypatch.setattr(
logic.person_logic,
"search_persons",
lambda author_id: type("Result", (), {"persons": []})(),
)
client = FundedPublicationsSearchClient(
base_url="https://project.nes.uni-due.de/elastic",
api_key="test-key",
transport=httpx.MockTransport(handler),
)
response = await logic.get_funders_by_author_id("A5023888391", client=client)
assert requested_pages == [1, 2]
assert response.funder_count == 2
assert {funder.funder_name for funder in response.funders} == {"Funder 1", "Funder 2"}
@pytest.mark.anyio
async def test_get_funders_by_author_id_maps_missing_api_key_to_service_unavailable():
client = FundedPublicationsSearchClient(api_key="")
with pytest.raises(HTTPException) as exc:
await logic.get_funders_by_author_id("A5023888391", client=client)
assert exc.value.status_code == 503
+1 -185
View File
@@ -284,188 +284,4 @@ def generate_person_bio(author_id: str) -> str:
system_prompt = "Erstelle eine Beschreibung der Person in 3-5 Sätzen. Gebe nur die Beschreibung zurück, ohne Einleitung oder Schluss."
user_prompt = f"Daten zur Person:\n{person_json}"
return llm.call(system_prompt=system_prompt, user_prompt=user_prompt)
def create_publications_by_author_query(
author_id: str,
page: int = 1,
page_size: int = 20
) -> dict:
if not author_id.startswith("https://openalex.org/"):
author_id = f"https://openalex.org/{author_id}"
from_value = (page - 1) * page_size
return {
"from": from_value,
"size": page_size,
"_source": [
"id",
"title",
"display_name",
"publication_year",
"authorships.author.id",
"authorships.author.display_name",
"authorships.author_position",
"funders.id",
"funders.display_name",
"funders.ror"
],
"query": {
"bool": {
"must": [
{
"nested": {
"path": "authorships",
"query": {
"term": {
"authorships.author.id": author_id
}
}
}
},
{
"nested": {
"path": "funders",
"query": {
"exists": {
"field": "funders.id"
}
}
}
}
]
}
}
}
def get_publications_by_author_id(
author_id: str,
page: int = 1,
page_size: int = 20
) -> dict:
headers = {
"Authorization": f"ApiKey {config.settings.elasticsearch_api_key}",
"Content-Type": "application/json"
}
payload = create_publications_by_author_query(author_id, page, page_size)
with httpx.Client() as client:
response = client.post(
config.settings.elasticsearch_works_url,
json=payload,
headers=headers
)
response.raise_for_status()
data = response.json()
total = data.get("hits", {}).get("total", {}).get("value", 0)
hits = data.get("hits", {}).get("hits", [])
return {
"author_id": author_id if author_id.startswith("https://openalex.org/") else f"https://openalex.org/{author_id}",
"page": page,
"page_size": page_size,
"total": total,
"results_count": len(hits),
"results": hits
}
def get_author_name(author_id: str) -> str | None:
short_author_id = author_id.replace("https://openalex.org/", "")
search_result = search_persons(author_id=short_author_id)
if not search_result.persons:
return None
return search_result.persons[0].name
def get_author_position_in_publication(publication: dict, author_id: str) -> str:
normalized_author_id = (
author_id if author_id.startswith("https://openalex.org/")
else f"https://openalex.org/{author_id}"
)
for authorship in publication.get("authorships", []):
author = authorship.get("author", {})
if author.get("id") == normalized_author_id:
return authorship.get("author_position", "unknown")
return "unknown"
def get_funders_by_author_id(author_id: str) -> dict:
page = 1
page_size = 100
funder_counts = {}
normalized_author_id = (
author_id if author_id.startswith("https://openalex.org/")
else f"https://openalex.org/{author_id}"
)
author_name = get_author_name(author_id)
while True:
data = get_publications_by_author_id(author_id, page, page_size)
results = data.get("results", [])
if not results:
break
for hit in results:
publication = hit.get("_source", {})
publication_id = publication.get("id")
author_position = get_author_position_in_publication(publication, author_id)
publication_funders = set()
# Funders field
for funder in publication.get("funders", []):
funder_id = funder.get("id")
funder_name = funder.get("display_name")
if funder_id or funder_name:
key = funder_id or funder_name
publication_funders.add((key, funder_id, funder_name))
# Count each funder only once per publication
for key, funder_id, funder_name in publication_funders:
if key not in funder_counts:
funder_counts[key] = {
"funder_id": funder_id,
"funder_name": funder_name,
"publication_count": 0,
"author_position_count": {
"first": 0,
"middle": 0,
"last": 0,
"unknown": 0
},
"publication_ids": {
"first": [],
"middle": [],
"last": [],
"unknown": []
}
}
funder_counts[key]["publication_count"] += 1
if author_position not in funder_counts[key]["author_position_count"]:
author_position = "unknown"
funder_counts[key]["author_position_count"][author_position] += 1
funder_counts[key]["publication_ids"][author_position].append(publication_id)
if len(results) < page_size:
break
page += 1
return {
"author_id": normalized_author_id,
"author_name": author_name,
"funder_count": len(funder_counts),
"funders": list(funder_counts.values())
}
return llm.call(system_prompt=system_prompt, user_prompt=user_prompt)
+2 -18
View File
@@ -23,6 +23,7 @@ from . import database
from . import security
from . import util
from .works import service as works_service
from .funders import service as funders_service
logger = logging.getLogger(__name__)
@@ -34,6 +35,7 @@ app = FastAPI(redoc_url=None,
summary='My App Service API',
version='1.0.0')
app.include_router(works_service.router)
app.include_router(funders_service.router)
@app.get("/", include_in_schema=False)
async def show_api():
@@ -180,21 +182,3 @@ def generate_person_bio(author_id: Annotated[str, Query(description="OpenAlex au
bio = logic.generate_person_bio(author_id)
return model.PersonBio(bio=bio)
@app.get('/authors/{author_id}/publications',
operation_id='getPublicationsByAuthor',
summary='Get publications by author.',
tags=['Publications'])
def get_publications_by_author(
author_id: str,
page: int = 1,
page_size: int = 20
):
return logic.get_publications_by_author_id(author_id, page, page_size)
@app.get('/authors/{author_id}/funders',
operation_id='getFundersByAuthor',
summary='Get funding organizations by author.',
tags=['Funding'])
def get_funders_by_author(author_id: str):
return logic.get_funders_by_author_id(author_id)