fix(person/publications): made URL stateful and moved retrieval logic to resolvers

This commit is contained in:
Mats Paul Tončik
2026-07-12 23:39:25 +02:00
parent 9cf6348f55
commit fa5e42a5eb
24 changed files with 1211 additions and 563 deletions
@@ -107,6 +107,7 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
def _wrap_exception(e: Exception) -> Exception:
logger.exception(f"Elasticsearch raised an exception: {e}")
if isinstance(e, httpx.HTTPStatusError):
if e.response.status_code == 404:
return ElasticsearchNotFoundException(
+2
View File
@@ -52,6 +52,7 @@ from inse.patents.service import (
)
from inse.works.purpose_router import router as works_purpose_router
from inse.works.v2.router import router as works_v2_router
logger = logging.getLogger(__name__)
@@ -101,6 +102,7 @@ app.include_router(service_router)
app.include_router(auth_router)
app.include_router(account_management_router)
app.include_router(organization_management_router)
app.include_router(works_v2_router)
app.add_middleware(
+17 -8
View File
@@ -16,6 +16,7 @@ else:
def __str__(self) -> str:
return self.value
from pydantic import BaseModel
from pydantic import Field
from typing import List
@@ -28,11 +29,16 @@ T = TypeVar("T", bound=BaseModel)
class Page(BaseModel, Generic[T]):
elements: List[T] = Field(default=[], description="The elements of the page.")
offset: int = Field(default=0, description="The page number. (0-based)")
page: int = Field(default=0, description="The page number. (0-based)")
size: int = Field(default=20, description="The page size in elements.")
total: int = Field(default=0, description="The total number of elements.")
class SortDirection(StrEnum):
ASCENDING = "asc"
DESCENDING = "desc"
class ESCluster(StrEnum):
NES = "nes"
INSE = "inse"
@@ -40,6 +46,7 @@ class ESCluster(StrEnum):
class ESIndex(StrEnum):
OPENALEX_WORKS = "openalex-works"
OPENALEX_WORKS_WILDCARD = "openalex-works*"
OPENALEX_AUTHORS = "openalex-authors"
OPENALEX_INSTITUTIONS = "openalex-institutions"
OPENALEX_PUBLICATIONS = "openalex-publications"
@@ -47,17 +54,17 @@ class ESIndex(StrEnum):
OPENALEX_CONTINENTS = "openalex-continents"
OPENALEX_TOPICS = "openalex-topics"
OPENALEX_TOPIC_VECTORS = "topicvectors"
EPO_INDEX = "epo_index_1.0"
USPTO_INDEX = "uspto_patents_3.0"
ORG_PATENTS = "org_patents"
PROJECTS_BUND_V1 = "projects_bund_v1"
PROJECTS_DFG_ALL = "projects_dfg_all"
CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects"
CORDIS_EU_PUBLICATIONS_WILDCARD = "cordis_eu_*_publications"
CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects"
CORDIS_EU_PUBLICATIONS_WILDCARD = "cordis_eu_*_publications"
CORDIS_EU_FP7_OGANIZATIONS = "cordis_eu_fp7_organizations"
# FP7
CORDIS_EU_FP7_ORGANIZATIONS = "cordis_eu_fp7_organizations"
@@ -84,8 +91,10 @@ class ESIndex(StrEnum):
CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS = "cordis_eu_horizon_europe_organizations"
CORDIS_EU_HORIZON_EUROPE_PUBLICATIONS = "cordis_eu_horizon_europe_publications"
CORDIS_EU_HORIZON_EUROPE_DELIVERABLES = "cordis_eu_horizon_europe_deliverables"
CORDIS_EU_HORIZON_EUROPE_REPORT_SUMMARIES = "cordis_eu_horizon_europe_report_summaries"
CORDIS_EU_HORIZON_EUROPE_REPORT_SUMMARIES = (
"cordis_eu_horizon_europe_report_summaries"
)
CORDIS_EU_HORIZON_EUROPE_TOPICS = "cordis_eu_horizon_europe_topics"
CORDIS_EU_HORIZON_EUROPE_WEB_LINKS = "cordis_eu_horizon_europe_web_links"
CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC = "cordis_eu_horizon_europe_euroscivoc"
CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS = "cordis_eu_horizon_europe_legal_basis"
CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS = "cordis_eu_horizon_europe_legal_basis"
+1
View File
@@ -7,6 +7,7 @@ class Tags(StrEnum):
INSTITUTIONS = "Institutions"
TOPICS = "Topics"
WORKS = "Works"
WORKS_V2 = "Works V2"
NEWS = "News"
PROJECTS = "Projects"
AUTH = "Auth"
@@ -20,7 +20,7 @@ router = APIRouter(prefix=WORKS_PREFIX, tags=[Tags.WORKS])
async def get_work_purpose(
raw_oa_work_id: Annotated[str, Path(description="The raw OpenAlex work id.")],
) -> SpecificWorkPurpose:
return await purpose_service.get_work_purpose(raw_oa_work_id)
return await purpose_service.get_work_purpose(raw_oa_work_id=raw_oa_work_id)
@router.get(
@@ -31,4 +31,6 @@ async def get_work_purpose(
async def get_author_work_purposes(
raw_oa_author_id: Annotated[str, Path(description="The raw OpenAlex author id.")],
) -> AuthorWorkPurposes:
return await purpose_service.get_author_work_purposes(raw_oa_author_id)
return await purpose_service.get_author_work_purposes(
raw_oa_author_id=raw_oa_author_id
)
@@ -2,7 +2,6 @@ import logging
import random
from typing import List
from fastapi import HTTPException, status
from inse.exceptions import NotFoundException
from inse.integrations import elasticsearch
@@ -10,13 +9,14 @@ from inse.model import ESIndex
from inse.works.model import AuthorWorkPurposes, SpecificWorkPurpose, WorkPurpose
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
async def get_work_purpose(raw_oa_work_id: str) -> SpecificWorkPurpose:
raw_oa_work_id = raw_oa_work_id.strip().upper()
response = await elasticsearch.get(
index=ESIndex.OPENALEX_WORKS,
index=ESIndex.OPENALEX_WORKS_WILDCARD,
doc_id=raw_oa_work_id,
source=["title", "abstract"],
)
@@ -41,7 +41,7 @@ async def get_author_work_purposes(raw_oa_author_id: str) -> AuthorWorkPurposes:
raw_oa_author_id = raw_oa_author_id.strip().upper()
response = await elasticsearch.search(
index=ESIndex.OPENALEX_WORKS,
index=ESIndex.OPENALEX_WORKS_WILDCARD,
source=["id", "publication_year"],
query={
"nested": {
+48
View File
@@ -0,0 +1,48 @@
from enum import StrEnum
from typing import List
from pydantic import BaseModel, Field
from inse.model import Page
from inse.models.openalex.work_topic import WorkTopic
class WorkSortBy(StrEnum):
TITLE = "title"
TYPE = "type"
PUBLICATION_YEAR = "publication_year"
LANGUAGE = "language"
CITED_BY_COUNT = "cited_by_count"
class AuthorWorkInstitution(BaseModel):
institution_id: str = Field(
description="The ID of the institution associated with the work"
)
institution_name: str = Field(
description="The name of the institution associated with the work"
)
institution_country_code: str = Field(
description="The country code of the institution associated with the work"
)
class AuthorWork(BaseModel):
id: str = Field(description="The ID of the work")
title: str = Field(description="The title of the work")
type: str = Field(description="The type of the work")
publication_year: int = Field(description="The year the work was published")
language_code: str = Field(description="The language code of the work")
institutions: List[AuthorWorkInstitution] = Field(
description="A list of institutions associated with the work"
)
topics: List[WorkTopic] = Field(
description="A list of topics associated with the work"
)
cited_by_count: int = Field(
description="The number of citations the work has received"
)
class AuthorWorkPage(Page[AuthorWork]):
pass
+101
View File
@@ -0,0 +1,101 @@
from typing import Annotated, List
from fastapi import APIRouter, Path, Query
from inse.tags import Tags
from inse.model import SortDirection
from inse.works.v2.model import AuthorWorkPage, WorkSortBy
from inse.models.openalex.work_topic import WorkTopic
from inse.models.openalex.institution import Institution
router = APIRouter(prefix="/api/v2/works", tags=[Tags.WORKS_V2])
@router.get(
"/{raw_oa_author_id}",
operation_id="getAuthorWorkPage",
summary="Returns a paginated list of works for a given author based on their ID.",
)
async def get_author_works(
raw_oa_author_id: Annotated[str, Path(description="The raw OpenAlex author id.")],
page: Annotated[
int, Query(description="The page number to retrieve. (0-based)", ge=0)
] = 0,
size: Annotated[
int,
Query(description="The number of works to retrieve per page.", ge=1, le=100),
] = 10,
publication_years: Annotated[
list[int],
Query(description="A list of publication years to filter by."),
] = [],
publication_types: Annotated[
list[str],
Query(description="A list of publication types to filter by."),
] = [],
institution_ids: Annotated[
list[str],
Query(description="A list of institution IDs to filter by."),
] = [],
topic_ids: Annotated[
list[str],
Query(description="A list of topic IDs to filter by."),
] = [],
language_codes: Annotated[
list[str],
Query(description="A list of language codes to filter by."),
] = [],
sort_by: Annotated[
WorkSortBy, Query(description="The field to sort by.")
] = WorkSortBy.PUBLICATION_YEAR,
sort_order: Annotated[
SortDirection, Query(description="The order to sort by.")
] = SortDirection.DESCENDING,
) -> AuthorWorkPage:
from inse.works.v2.service import get_author_works
return await get_author_works(
raw_oa_author_id=raw_oa_author_id,
page=page,
size=size,
publication_years=publication_years or [],
publication_types=publication_types or [],
institution_ids=institution_ids or [],
topic_ids=topic_ids or [],
language_codes=language_codes or [],
sort_by=sort_by,
sort_order=sort_order,
)
@router.get(
"/topics/search",
operation_id="getWorkTopicsByIds",
summary="Returns a list of work topics based on their IDs.",
)
async def get_work_topics_by_ids(
topic_ids: Annotated[
list[str],
Query(description="A list of topic IDs to retrieve."),
] = [],
) -> List[WorkTopic]:
from inse.works.v2.service import get_work_topics_by_ids
return await get_work_topics_by_ids(topic_ids=topic_ids or [])
@router.get(
"/institutions/search",
operation_id="getInstitutionsByIds",
summary="Returns a list of institutions based on their IDs.",
)
async def get_institutions_by_ids(
institution_ids: Annotated[
list[str],
Query(description="A list of institution IDs to retrieve."),
] = [],
) -> List[Institution]:
from inse.works.v2.service import get_work_institutions_by_ids
return await get_work_institutions_by_ids(institution_ids=institution_ids or [])
+188
View File
@@ -0,0 +1,188 @@
import logging
from typing import List, Optional, Dict
from inse.integrations import elasticsearch
from inse.model import ESIndex, SortDirection
from inse.works.v2.model import (
AuthorWork,
AuthorWorkInstitution,
AuthorWorkPage,
WorkSortBy,
)
from inse.models.openalex.work_topic import WorkTopic
from inse.models.openalex.institution import Institution
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
async def get_author_works(
raw_oa_author_id: str,
page: int,
size: int,
publication_years: Optional[List[int]] = None,
publication_types: Optional[List[str]] = None,
institution_ids: Optional[List[str]] = None,
topic_ids: Optional[List[str]] = None,
language_codes: Optional[List[str]] = None,
sort_by: WorkSortBy = WorkSortBy.PUBLICATION_YEAR,
sort_order: SortDirection = SortDirection.DESCENDING,
) -> AuthorWorkPage:
must = [
{
"nested": {
"path": "authorships",
"query": {
"term": {
"authorships.author.id": f"https://openalex.org/{raw_oa_author_id}"
}
},
}
}
]
if publication_years:
must.append({"terms": {"publication_year": publication_years}})
if publication_types:
must.append({"terms": {"type": publication_types}})
if language_codes:
must.append({"terms": {"language": language_codes}})
if institution_ids:
must.append(
{
"nested": {
"path": "authorships",
"query": {
"nested": {
"path": "authorships.institutions",
"query": {
"terms": {
"authorships.institutions.id": institution_ids
}
},
}
},
}
}
)
if topic_ids:
must.append(
{"nested": {"path": "topics", "query": {"terms": {"topics.id": topic_ids}}}}
)
if sort_by == WorkSortBy.TITLE:
sort = [{"title.keyword": sort_order.value}]
else:
sort = [{sort_by.value: sort_order.value}]
response = await elasticsearch.search(
ESIndex.OPENALEX_WORKS_WILDCARD,
source=[
"id",
"title",
"type",
"publication_year",
"language",
"cited_by_count",
"authorships.institutions.id",
"authorships.institutions.display_name",
"authorships.institutions.country_code",
"topics",
],
query={"bool": {"must": must}},
size=size,
offset=page * size,
sort=sort,
)
logger.debug(f"Elasticsearch response for author {raw_oa_author_id} v2: {response}")
hits_block = response.get("hits", {})
total = hits_block.get("total", {}).get("value", 0)
hits = hits_block.get("hits", [])
elements: List[AuthorWork] = []
for hit in hits:
source = hit.get("_source", {})
logger.debug(f"Hit source for author {raw_oa_author_id} v2: {source}")
institutions: Dict[str, AuthorWorkInstitution] = {}
for authorship in source.get("authorships", []):
for institution in authorship.get("institutions", []):
institution_id = institution.get("id", "")
if institution_id not in institutions:
institutions[institution_id] = AuthorWorkInstitution(
institution_id=institution.get("id", ""),
institution_name=institution.get("display_name", ""),
institution_country_code=institution.get("country_code", ""),
)
topics: List[WorkTopic] = [
WorkTopic.from_dict(topic) for topic in source.get("topics", [])
] # type: ignore
elements.append(
AuthorWork(
id=source.get("id", ""),
title=source.get("title", ""),
type=source.get("type", ""),
publication_year=source.get("publication_year", 0),
language_code=source.get("language") or "",
institutions=list(institutions.values()),
topics=topics,
cited_by_count=source.get("cited_by_count", 0),
)
)
return AuthorWorkPage(
elements=elements,
total=total,
page=page,
size=size,
)
async def get_work_topics_by_ids(topic_ids: List[str]) -> List[WorkTopic]:
logger.debug(f"Fetching work topics for IDs: {topic_ids}")
if not topic_ids:
return []
must = [{"terms": {"id": topic_ids}}]
response = await elasticsearch.search(
ESIndex.OPENALEX_TOPICS,
source=["id", "display_name", "field", "domain"],
query={"bool": {"must": must}},
size=len(topic_ids),
)
logger.debug(f"Elasticsearch response for work topics {topic_ids}: {response}")
hits_block = response.get("hits", {})
hits = hits_block.get("hits", [])
topics: List[WorkTopic] = []
for hit in hits:
source = hit.get("_source", {})
logger.debug(f"Hit source for work topic {source.get('id', '')}: {source}")
topics.append(WorkTopic.from_dict(source)) # type: ignore
return topics
async def get_work_institutions_by_ids(institution_ids: List[str]) -> List[Institution]:
logger.debug(f"Fetching institutions for IDs: {institution_ids}")
if not institution_ids:
return []
must = [{"terms": {"id": institution_ids}}]
response = await elasticsearch.search(
ESIndex.OPENALEX_INSTITUTIONS,
source=["id", "display_name", "country_code"],
query={"bool": {"must": must}},
size=len(institution_ids),
)
logger.debug(
f"Elasticsearch response for institutions {institution_ids}: {response}"
)
hits_block = response.get("hits", {})
hits = hits_block.get("hits", [])
institutions: List[Institution] = []
for hit in hits:
source = hit.get("_source", {})
logger.debug(f"Hit source for institution {source.get('id', '')}: {source}")
institutions.append(Institution.from_dict(source)) # type: ignore
return institutions