feat(work-classifications): made publication table work classifications optional based on using page
This commit is contained in:
@@ -5,4 +5,3 @@ from inse.models.openalex.author import Author
|
||||
class AuthorPage(Page[Author]):
|
||||
"""A paginated response containing a list of authors."""
|
||||
|
||||
pass
|
||||
|
||||
@@ -1,20 +1,16 @@
|
||||
import logging
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
|
||||
from inse.tags import Tags
|
||||
from inse.authors.v2.model import AuthorPage
|
||||
|
||||
import inse.authors.v2.service as authors_service
|
||||
|
||||
|
||||
AUTHORS_V2_PREFIX = "/api/v2/authors"
|
||||
from fastapi import APIRouter, Query
|
||||
from inse.authors.v2.model import AuthorPage
|
||||
from inse.router_prefixes import RouterPrefixes
|
||||
from inse.tags import Tags
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
router = APIRouter(prefix=AUTHORS_V2_PREFIX, tags=[Tags.AUTHORS_V2])
|
||||
router = APIRouter(prefix=RouterPrefixes.AUTHORS_V2, tags=[Tags.AUTHORS_V2])
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -24,9 +20,9 @@ router = APIRouter(prefix=AUTHORS_V2_PREFIX, tags=[Tags.AUTHORS_V2])
|
||||
)
|
||||
async def get_authors_by_ids(
|
||||
author_ids: Annotated[
|
||||
list[str],
|
||||
list[str] | None,
|
||||
Query(description="A list of author IDs to retrieve."),
|
||||
] = [],
|
||||
] = None,
|
||||
) -> AuthorPage:
|
||||
return await authors_service.get_authors_by_ids(author_ids=author_ids or [])
|
||||
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
from typing import Dict, List, Optional, Set
|
||||
|
||||
from inse.authors.v2.model import AuthorPage
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.institutions.v2 import service as institution_service
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESIndex
|
||||
from inse.models.openalex.author import Author
|
||||
from inse.models.openalex.institution import Institution
|
||||
@@ -11,10 +9,10 @@ from inse.models.openalex.institution import Institution
|
||||
async def search_authors(
|
||||
page: int = 0,
|
||||
size: int = 10,
|
||||
query: Optional[Dict] = None,
|
||||
source: Optional[List[str]] = None,
|
||||
sort: Optional[List[dict]] = None,
|
||||
body: Optional[dict] = None,
|
||||
query: dict | None = None,
|
||||
source: list[str] | None = None,
|
||||
sort: list[dict] | None = None,
|
||||
body: dict | None = None,
|
||||
) -> AuthorPage:
|
||||
"""Searches for authors in the OpenAlex Elasticsearch index based on the provided parameters.
|
||||
|
||||
@@ -42,14 +40,14 @@ async def search_authors(
|
||||
|
||||
hits_block = response.get("hits", {})
|
||||
hits = hits_block.get("hits", [])
|
||||
authors: List[Author] = []
|
||||
authors: list[Author] = []
|
||||
for hit in hits:
|
||||
_source = hit.get("_source", {})
|
||||
authors.append(Author.from_dict(_source)) # type: ignore
|
||||
return AuthorPage(elements=authors, total=len(authors), page=page, size=size)
|
||||
|
||||
|
||||
async def get_author_by_id(author_id: str) -> Optional[Author]:
|
||||
async def get_author_by_id(author_id: str) -> Author | None:
|
||||
"""Retrieves an author from the OpenAlex Elasticsearch index based on the provided author ID.
|
||||
|
||||
Args:
|
||||
@@ -88,7 +86,7 @@ async def autocomplete_authors_for_selector(query: str) -> AuthorPage:
|
||||
)
|
||||
|
||||
|
||||
async def get_authors_by_ids(author_ids: List[str]) -> AuthorPage:
|
||||
async def get_authors_by_ids(author_ids: list[str]) -> AuthorPage:
|
||||
"""Retrieves authors based on a list of author IDs.
|
||||
|
||||
Args:
|
||||
@@ -117,7 +115,7 @@ async def get_authors_by_ids(author_ids: List[str]) -> AuthorPage:
|
||||
async def author_currently_belongs_to_institution(
|
||||
raw_oa_author_id: str,
|
||||
raw_oa_institution_id: str,
|
||||
current_years: List[int] = [2025, 2026],
|
||||
current_years: list[int] = [2025, 2026], # noqa: B006
|
||||
) -> bool:
|
||||
"""Checks if an author currently belongs to a specific institution based on their affiliations and the provided years.
|
||||
|
||||
@@ -149,7 +147,7 @@ def _prefix_openalex_id(raw_id: str) -> str:
|
||||
|
||||
async def _get_institution_identity(
|
||||
raw_oa_institution_id: str,
|
||||
) -> Optional[Institution]:
|
||||
) -> Institution | None:
|
||||
page = await institution_service.get_institutions_by_ids(
|
||||
[_prefix_openalex_id(raw_oa_institution_id)]
|
||||
)
|
||||
@@ -157,12 +155,12 @@ async def _get_institution_identity(
|
||||
|
||||
|
||||
def _current_institution_cohort_query(
|
||||
author_ids: List[str],
|
||||
author_ids: list[str],
|
||||
institution_id: str,
|
||||
institution_ror: Optional[str],
|
||||
institution_ror: str | None,
|
||||
institution_display_name: str,
|
||||
affiliation_year_filter: Dict,
|
||||
) -> Dict:
|
||||
affiliation_year_filter: dict,
|
||||
) -> dict:
|
||||
"""Build the author cohort query used by work classification access."""
|
||||
|
||||
affiliation_identifiers = [
|
||||
@@ -215,9 +213,7 @@ def _current_institution_cohort_query(
|
||||
"nested": {
|
||||
"path": "last_known_institutions",
|
||||
"query": {
|
||||
"exists": {
|
||||
"field": "last_known_institutions.display_name"
|
||||
}
|
||||
"exists": {"field": "last_known_institutions.display_name"}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -230,7 +226,9 @@ def _current_institution_cohort_query(
|
||||
"filter": [
|
||||
{
|
||||
"terms": {
|
||||
"id": [_prefix_openalex_id(author_id) for author_id in author_ids]
|
||||
"id": [
|
||||
_prefix_openalex_id(author_id) for author_id in author_ids
|
||||
]
|
||||
}
|
||||
},
|
||||
recent_affiliation,
|
||||
@@ -249,25 +247,23 @@ def _current_institution_cohort_query(
|
||||
|
||||
|
||||
async def authors_currently_belong_to_institution(
|
||||
raw_oa_author_ids: List[str],
|
||||
raw_oa_author_ids: list[str],
|
||||
raw_oa_institution_id: str,
|
||||
) -> Set[str]:
|
||||
) -> set[str]:
|
||||
"""Return current cohort members using one query for all author IDs."""
|
||||
|
||||
return await _authors_belong_to_institution(
|
||||
raw_oa_author_ids,
|
||||
raw_oa_institution_id,
|
||||
affiliation_year_filter={
|
||||
"range": {"affiliations.years": {"gte": 2025}}
|
||||
},
|
||||
affiliation_year_filter={"range": {"affiliations.years": {"gte": 2025}}},
|
||||
)
|
||||
|
||||
|
||||
async def _authors_belong_to_institution(
|
||||
raw_oa_author_ids: List[str],
|
||||
raw_oa_author_ids: list[str],
|
||||
raw_oa_institution_id: str,
|
||||
affiliation_year_filter: Dict,
|
||||
) -> Set[str]:
|
||||
affiliation_year_filter: dict,
|
||||
) -> set[str]:
|
||||
"""Return matching author IDs for the supplied affiliation-year filter."""
|
||||
|
||||
author_ids = list(dict.fromkeys(filter(None, raw_oa_author_ids)))
|
||||
@@ -283,8 +279,7 @@ async def _authors_belong_to_institution(
|
||||
size=len(author_ids),
|
||||
query=_current_institution_cohort_query(
|
||||
author_ids=author_ids,
|
||||
institution_id=institution.id
|
||||
or _prefix_openalex_id(raw_oa_institution_id),
|
||||
institution_id=institution.id or _prefix_openalex_id(raw_oa_institution_id),
|
||||
institution_ror=institution.ror,
|
||||
institution_display_name=institution.display_name,
|
||||
affiliation_year_filter=affiliation_year_filter,
|
||||
|
||||
@@ -5,4 +5,3 @@ from inse.models.openalex.institution import Institution
|
||||
class InstitutionPageV2(Page[Institution]):
|
||||
"""A paginated response containing a list of institutions."""
|
||||
|
||||
pass
|
||||
|
||||
@@ -2,17 +2,14 @@ import logging
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
|
||||
from inse.institutions.v2.model import InstitutionPageV2
|
||||
from inse.router_prefixes import RouterPrefixes
|
||||
from inse.tags import Tags
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
INSTITUTIONS_v2_PREFIX = "/api/v2/institutions"
|
||||
|
||||
router = APIRouter(prefix=INSTITUTIONS_v2_PREFIX, tags=[Tags.INSTITUTIONS_V2])
|
||||
router = APIRouter(prefix=RouterPrefixes.INSTITUTIONS_V2, tags=[Tags.INSTITUTIONS_V2])
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -22,9 +19,9 @@ router = APIRouter(prefix=INSTITUTIONS_v2_PREFIX, tags=[Tags.INSTITUTIONS_V2])
|
||||
)
|
||||
async def get_institutions_by_ids(
|
||||
institution_ids: Annotated[
|
||||
list[str],
|
||||
list[str] | None,
|
||||
Query(description="A list of institution IDs to retrieve."),
|
||||
] = [],
|
||||
] = None,
|
||||
) -> InstitutionPageV2:
|
||||
from inse.institutions.v2.service import get_institutions_by_ids
|
||||
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import logging
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from inse.institutions.v2.model import InstitutionPageV2
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESIndex
|
||||
from inse.models.openalex.institution import Institution
|
||||
from inse.institutions.v2.model import InstitutionPageV2
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -13,10 +11,10 @@ logger = logging.getLogger(__name__)
|
||||
async def search_institutions(
|
||||
page: int = 0,
|
||||
size: int = 10,
|
||||
query: Optional[Dict] = None,
|
||||
source: Optional[List[str]] = None,
|
||||
sort: Optional[List[Dict]] = None,
|
||||
body: Optional[Dict] = None,
|
||||
query: dict | None = None,
|
||||
source: list[str] | None = None,
|
||||
sort: list[dict] | None = None,
|
||||
body: dict | None = None,
|
||||
) -> InstitutionPageV2:
|
||||
"""Searches for institutions in the OpenAlex Elasticsearch index based on the provided parameters.
|
||||
|
||||
@@ -43,7 +41,7 @@ async def search_institutions(
|
||||
|
||||
hits_block = response.get("hits", {})
|
||||
hits = hits_block.get("hits", [])
|
||||
institutions: List[Institution] = []
|
||||
institutions: list[Institution] = []
|
||||
for hit in hits:
|
||||
_source = hit.get("_source", {})
|
||||
institutions.append(Institution.from_dict(_source)) # type: ignore
|
||||
@@ -52,7 +50,7 @@ async def search_institutions(
|
||||
)
|
||||
|
||||
|
||||
async def get_institutions_by_ids(institution_ids: List[str]) -> InstitutionPageV2:
|
||||
async def get_institutions_by_ids(institution_ids: list[str]) -> InstitutionPageV2:
|
||||
"""Retrieves institutions based on a list of institution IDs.
|
||||
|
||||
Args:
|
||||
@@ -81,7 +79,7 @@ async def get_institutions_by_ids(institution_ids: List[str]) -> InstitutionPage
|
||||
|
||||
|
||||
async def autocomplete_institutions(
|
||||
query: str, page: int = 0, size: int = 10, source: Optional[List[str]] = None
|
||||
query: str, page: int = 0, size: int = 10, source: list[str] | None = None
|
||||
) -> InstitutionPageV2:
|
||||
"""Autocompletes institutions based on a search term.
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
from enum import StrEnum
|
||||
|
||||
|
||||
class RouterPrefixes(StrEnum):
|
||||
"""Router prefixes for different API endpoints."""
|
||||
|
||||
INSTITUTIONS_V2 = "/api/institutions/v2"
|
||||
TOPICS_V2 = "/api/topics/v2"
|
||||
AUTHORS_V2 = "/api/authors/v2"
|
||||
WORKS_V2 = "/api/works/v2"
|
||||
@@ -1,20 +1,16 @@
|
||||
import logging
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
|
||||
from inse.tags import Tags
|
||||
|
||||
import inse.topics.v2.service as topics_service
|
||||
from fastapi import APIRouter, Query
|
||||
from inse.router_prefixes import RouterPrefixes
|
||||
from inse.tags import Tags
|
||||
from inse.topics.v2.model import TopicPageV2
|
||||
|
||||
|
||||
TOPICS_V2_PREFIX = "/api/v2/topics"
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
router = APIRouter(prefix=TOPICS_V2_PREFIX, tags=[Tags.TOPICS_V2])
|
||||
router = APIRouter(prefix=RouterPrefixes.TOPICS_V2, tags=[Tags.TOPICS_V2])
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -24,9 +20,9 @@ router = APIRouter(prefix=TOPICS_V2_PREFIX, tags=[Tags.TOPICS_V2])
|
||||
)
|
||||
async def get_topics_by_ids(
|
||||
topic_ids: Annotated[
|
||||
list[str],
|
||||
list[str] | None,
|
||||
Query(description="A list of topic IDs to retrieve."),
|
||||
] = [],
|
||||
] = None,
|
||||
) -> TopicPageV2:
|
||||
return await topics_service.get_topics_by_ids(topic_ids=topic_ids or [])
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESIndex
|
||||
@@ -9,10 +8,10 @@ from inse.topics.v2.model import TopicPageV2
|
||||
async def search_topics(
|
||||
page: int = 0,
|
||||
size: int = 10,
|
||||
query: Optional[Dict] = None,
|
||||
source: Optional[List[str]] = None,
|
||||
sort: Optional[List[Dict]] = None,
|
||||
body: Optional[Dict] = None,
|
||||
query: dict | None = None,
|
||||
source: list[str] | None = None,
|
||||
sort: list[dict] | None = None,
|
||||
body: dict | None = None,
|
||||
) -> TopicPageV2:
|
||||
"""Searches for topics based on the provided criteria.
|
||||
|
||||
@@ -39,7 +38,7 @@ async def search_topics(
|
||||
|
||||
hits_block = response.get("hits", {})
|
||||
hits = hits_block.get("hits", [])
|
||||
topics: List[Topic] = []
|
||||
topics: list[Topic] = []
|
||||
for hit in hits:
|
||||
_source = hit.get("_source", {})
|
||||
topics.append(Topic.from_dict(_source)) # type: ignore
|
||||
@@ -69,7 +68,7 @@ async def autocomplete_topics_for_selector(query: str) -> TopicPageV2:
|
||||
)
|
||||
|
||||
|
||||
async def get_topics_by_ids(topic_ids: List[str]) -> TopicPageV2:
|
||||
async def get_topics_by_ids(topic_ids: list[str]) -> TopicPageV2:
|
||||
"""Retrieves topics based on a list of topic IDs.
|
||||
|
||||
Args:
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from typing import Dict, Optional, List
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from inse.model import Page
|
||||
from inse.models.openalex.work import Work
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class WorkSortBy(StrEnum):
|
||||
@@ -34,28 +32,28 @@ class WorkPrimaryCategory(StrEnum):
|
||||
class WorkClassificationAuthor(BaseModel):
|
||||
"""An author entry within a work classification document."""
|
||||
|
||||
id: Optional[str] = Field(default=None, description="The OpenAlex author id.")
|
||||
display_name: Optional[str] = Field(
|
||||
id: str | None = Field(default=None, description="The OpenAlex author id.")
|
||||
display_name: str | None = Field(
|
||||
default=None, description="The author's display name."
|
||||
)
|
||||
orcid: Optional[str] = Field(default=None, description="The author's ORCID id.")
|
||||
orcid: str | None = Field(default=None, description="The author's ORCID id.")
|
||||
|
||||
|
||||
class WorkClassificationInstitution(BaseModel):
|
||||
"""An institution entry within a work classification document."""
|
||||
|
||||
id: Optional[str] = Field(default=None, description="The OpenAlex institution id.")
|
||||
display_name: Optional[str] = Field(
|
||||
id: str | None = Field(default=None, description="The OpenAlex institution id.")
|
||||
display_name: str | None = Field(
|
||||
default=None, description="The institution's display name."
|
||||
)
|
||||
ror: Optional[str] = Field(default=None, description="The institution's ROR id.")
|
||||
ror: str | None = Field(default=None, description="The institution's ROR id.")
|
||||
|
||||
|
||||
class WorkClassificationTopicGroup(BaseModel):
|
||||
"""A domain/field/subfield group referenced within a classification topic."""
|
||||
|
||||
id: Optional[str] = Field(default=None, description="The id of the group.")
|
||||
display_name: Optional[str] = Field(
|
||||
id: str | None = Field(default=None, description="The id of the group.")
|
||||
display_name: str | None = Field(
|
||||
default=None, description="The display name of the group."
|
||||
)
|
||||
|
||||
@@ -63,20 +61,20 @@ class WorkClassificationTopicGroup(BaseModel):
|
||||
class WorkClassificationTopic(BaseModel):
|
||||
"""A topic entry within a work classification document."""
|
||||
|
||||
id: Optional[str] = Field(default=None, description="The OpenAlex topic id.")
|
||||
display_name: Optional[str] = Field(
|
||||
id: str | None = Field(default=None, description="The OpenAlex topic id.")
|
||||
display_name: str | None = Field(
|
||||
default=None, description="The topic's display name."
|
||||
)
|
||||
score: Optional[float] = Field(
|
||||
score: float | None = Field(
|
||||
default=None, description="The relevance score of the topic."
|
||||
)
|
||||
domain: Optional[WorkClassificationTopicGroup] = Field(
|
||||
domain: WorkClassificationTopicGroup | None = Field(
|
||||
default=None, description="The topic's domain."
|
||||
)
|
||||
field: Optional[WorkClassificationTopicGroup] = Field(
|
||||
field: WorkClassificationTopicGroup | None = Field(
|
||||
default=None, description="The topic's field."
|
||||
)
|
||||
subfield: Optional[WorkClassificationTopicGroup] = Field(
|
||||
subfield: WorkClassificationTopicGroup | None = Field(
|
||||
default=None, description="The topic's subfield."
|
||||
)
|
||||
|
||||
@@ -84,28 +82,28 @@ class WorkClassificationTopic(BaseModel):
|
||||
class WorkClassificationDetails(BaseModel):
|
||||
"""The core classification result for a work."""
|
||||
|
||||
primary_category: Optional[WorkPrimaryCategory] = Field(
|
||||
primary_category: WorkPrimaryCategory | None = Field(
|
||||
default=None,
|
||||
description="The primary classification category assigned to the work.",
|
||||
)
|
||||
confidence: Optional[str] = Field(
|
||||
confidence: str | None = Field(
|
||||
default=None, description="The confidence level of the classification."
|
||||
)
|
||||
pasteur_quadrant: Optional[str] = Field(
|
||||
pasteur_quadrant: str | None = Field(
|
||||
default=None, description="The Pasteur quadrant classification, if applicable."
|
||||
)
|
||||
applied_orientation_score: Optional[int] = Field(
|
||||
applied_orientation_score: int | None = Field(
|
||||
default=None,
|
||||
description="The applied orientation score for the classification.",
|
||||
)
|
||||
insufficient_context: Optional[bool] = Field(
|
||||
insufficient_context: bool | None = Field(
|
||||
default=None,
|
||||
description="Whether there was insufficient context to classify confidently.",
|
||||
)
|
||||
signals_used: Optional[List[str]] = Field(
|
||||
signals_used: list[str] | None = Field(
|
||||
default=None, description="The signals used to arrive at the classification."
|
||||
)
|
||||
classification_reason: Optional[str] = Field(
|
||||
classification_reason: str | None = Field(
|
||||
default=None, description="The reasoning behind the classification."
|
||||
)
|
||||
|
||||
@@ -113,14 +111,14 @@ class WorkClassificationDetails(BaseModel):
|
||||
class WorkClassificationMeta(BaseModel):
|
||||
"""Metadata about how and when a classification was produced."""
|
||||
|
||||
model: Optional[str] = Field(
|
||||
model: str | None = Field(
|
||||
default=None, description="The model used to produce the classification."
|
||||
)
|
||||
prompt_version: Optional[str] = Field(
|
||||
prompt_version: str | None = Field(
|
||||
default=None,
|
||||
description="The version of the prompt used to produce the classification.",
|
||||
)
|
||||
classified_at: Optional[datetime] = Field(
|
||||
classified_at: datetime | None = Field(
|
||||
default=None,
|
||||
description="The timestamp at which the classification was produced.",
|
||||
)
|
||||
@@ -129,13 +127,13 @@ class WorkClassificationMeta(BaseModel):
|
||||
class WorkClassificationValidation(BaseModel):
|
||||
"""Validation results for a classification."""
|
||||
|
||||
valid: Optional[bool] = Field(
|
||||
valid: bool | None = Field(
|
||||
default=None, description="Whether the classification passed validation."
|
||||
)
|
||||
errors: Optional[List[str]] = Field(
|
||||
errors: list[str] | None = Field(
|
||||
default=None, description="Validation errors, if any."
|
||||
)
|
||||
corrections: Optional[List[str]] = Field(
|
||||
corrections: list[str] | None = Field(
|
||||
default=None, description="Corrections applied, if any."
|
||||
)
|
||||
|
||||
@@ -144,27 +142,27 @@ class WorkClassification(BaseModel):
|
||||
"""Represents a full work-classification document."""
|
||||
|
||||
work_id: str = Field(description="The full OpenAlex work id/URL.")
|
||||
doi: Optional[str] = Field(default=None, description="The DOI of the work.")
|
||||
title: Optional[str] = Field(default=None, description="The title of the work.")
|
||||
publication_year: Optional[int] = Field(
|
||||
doi: str | None = Field(default=None, description="The DOI of the work.")
|
||||
title: str | None = Field(default=None, description="The title of the work.")
|
||||
publication_year: int | None = Field(
|
||||
default=None, description="The publication year of the work."
|
||||
)
|
||||
authors: List[WorkClassificationAuthor] = Field(
|
||||
authors: list[WorkClassificationAuthor] = Field(
|
||||
default_factory=list, description="The authors of the work."
|
||||
)
|
||||
institutions: List[WorkClassificationInstitution] = Field(
|
||||
institutions: list[WorkClassificationInstitution] = Field(
|
||||
default_factory=list, description="The institutions associated with the work."
|
||||
)
|
||||
topics: List[WorkClassificationTopic] = Field(
|
||||
topics: list[WorkClassificationTopic] = Field(
|
||||
default_factory=list, description="The topics associated with the work."
|
||||
)
|
||||
classification: Optional[WorkClassificationDetails] = Field(
|
||||
classification: WorkClassificationDetails | None = Field(
|
||||
default=None, description="The classification result for the work."
|
||||
)
|
||||
classification_meta: Optional[WorkClassificationMeta] = Field(
|
||||
classification_meta: WorkClassificationMeta | None = Field(
|
||||
default=None, description="Metadata about the classification."
|
||||
)
|
||||
validation: Optional[WorkClassificationValidation] = Field(
|
||||
validation: WorkClassificationValidation | None = Field(
|
||||
default=None, description="Validation results for the classification."
|
||||
)
|
||||
|
||||
@@ -181,7 +179,7 @@ class WorkClassificationPage(Page[WorkClassification]):
|
||||
|
||||
class PrimaryCategoryYearAggregation(BaseModel):
|
||||
publication_year: int = Field(description="The publication year.")
|
||||
categories: Dict[WorkPrimaryCategory, int] = Field(
|
||||
categories: dict[WorkPrimaryCategory, int] = Field(
|
||||
default_factory=dict,
|
||||
description="A mapping of primary categories to their counts for the given year.",
|
||||
)
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import logging
|
||||
from typing import Annotated
|
||||
|
||||
import inse.works.v2.service as works_service
|
||||
from fastapi import APIRouter, Path, Query
|
||||
|
||||
from inse.tags import Tags
|
||||
from inse.auth.model import AccessTokenMetadata
|
||||
from inse.auth.service import CurrentUserAccessTokenPayloadDep
|
||||
from inse.model import SortDirection
|
||||
from inse.router_prefixes import RouterPrefixes
|
||||
from inse.tags import Tags
|
||||
from inse.works.v2.model import (
|
||||
PrimaryCategoryYearAggregationPage,
|
||||
WorkClassification,
|
||||
@@ -12,16 +15,11 @@ from inse.works.v2.model import (
|
||||
WorkPageV2,
|
||||
WorkSortBy,
|
||||
)
|
||||
from inse.auth.model import AccessTokenMetadata
|
||||
from inse.auth.service import CurrentUserAccessTokenPayloadDep
|
||||
import inse.works.v2.service as works_service
|
||||
|
||||
WORKS_v2_PREFIX = "/api/v2/works"
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
router = APIRouter(prefix=WORKS_v2_PREFIX, tags=[Tags.WORKS_V2])
|
||||
router = APIRouter(prefix=RouterPrefixes.WORKS_V2, tags=[Tags.WORKS_V2])
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -42,25 +40,25 @@ async def get_author_works(
|
||||
str, Query(description="A title to filter by (partial matches allowed).")
|
||||
] = "",
|
||||
publication_years: Annotated[
|
||||
list[int],
|
||||
list[int] | None,
|
||||
Query(description="A list of publication years to filter by."),
|
||||
] = [],
|
||||
] = None,
|
||||
publication_types: Annotated[
|
||||
list[str],
|
||||
list[str] | None,
|
||||
Query(description="A list of publication types to filter by."),
|
||||
] = [],
|
||||
] = None,
|
||||
institution_ids: Annotated[
|
||||
list[str],
|
||||
list[str] | None,
|
||||
Query(description="A list of institution IDs to filter by."),
|
||||
] = [],
|
||||
] = None,
|
||||
topic_ids: Annotated[
|
||||
list[str],
|
||||
list[str] | None,
|
||||
Query(description="A list of topic IDs to filter by."),
|
||||
] = [],
|
||||
] = None,
|
||||
language_codes: Annotated[
|
||||
list[str],
|
||||
list[str] | None,
|
||||
Query(description="A list of language codes to filter by."),
|
||||
] = [],
|
||||
] = None,
|
||||
sort_by: Annotated[
|
||||
WorkSortBy, Query(description="The field to sort by.")
|
||||
] = WorkSortBy.PUBLICATION_YEAR,
|
||||
@@ -179,25 +177,25 @@ async def get_institution_works(
|
||||
Query(description="The number of works to retrieve per page.", ge=1, le=100),
|
||||
] = 10,
|
||||
publication_years: Annotated[
|
||||
list[int],
|
||||
list[int] | None,
|
||||
Query(description="A list of publication years to filter by."),
|
||||
] = [],
|
||||
] = None,
|
||||
publication_types: Annotated[
|
||||
list[str],
|
||||
list[str] | None,
|
||||
Query(description="A list of publication types to filter by."),
|
||||
] = [],
|
||||
] = None,
|
||||
author_ids: Annotated[
|
||||
list[str],
|
||||
list[str] | None,
|
||||
Query(description="A list of author IDs to filter by."),
|
||||
] = [],
|
||||
] = None,
|
||||
topic_ids: Annotated[
|
||||
list[str],
|
||||
list[str] | None,
|
||||
Query(description="A list of topic IDs to filter by."),
|
||||
] = [],
|
||||
] = None,
|
||||
language_codes: Annotated[
|
||||
list[str],
|
||||
list[str] | None,
|
||||
Query(description="A list of language codes to filter by."),
|
||||
] = [],
|
||||
] = None,
|
||||
sort_by: Annotated[
|
||||
WorkSortBy, Query(description="The field to sort by.")
|
||||
] = WorkSortBy.PUBLICATION_YEAR,
|
||||
@@ -246,11 +244,17 @@ async def get_work_classifications_by_work_ids(
|
||||
AccessTokenMetadata, CurrentUserAccessTokenPayloadDep
|
||||
],
|
||||
work_ids: Annotated[
|
||||
list[str],
|
||||
list[str] | None,
|
||||
Query(
|
||||
description="A list of OpenAlex work IDs to retrieve classifications for."
|
||||
),
|
||||
] = [],
|
||||
] = None,
|
||||
raw_oa_author_id: Annotated[
|
||||
str | None, Query(description="The raw OpenAlex author id to filter by.")
|
||||
] = None,
|
||||
raw_oa_institution_id: Annotated[
|
||||
str | None, Query(description="The raw OpenAlex institution id to filter by.")
|
||||
] = None,
|
||||
page: Annotated[
|
||||
int, Query(description="The page number to retrieve. (0-based)", ge=0)
|
||||
] = 0,
|
||||
@@ -266,6 +270,8 @@ async def get_work_classifications_by_work_ids(
|
||||
return await works_service.get_work_classifications_by_work_ids(
|
||||
access_token_metadata=access_token_metadata,
|
||||
work_ids=work_ids or [],
|
||||
raw_oa_author_id=raw_oa_author_id,
|
||||
raw_oa_institution_id=raw_oa_institution_id,
|
||||
page=page,
|
||||
size=size,
|
||||
)
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import logging
|
||||
from typing import Dict, List, Optional
|
||||
from fastapi import Query
|
||||
|
||||
import inse.authors.v2.service as author_service
|
||||
from inse.auth.model import AccessTokenMetadata
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESIndex, SortDirection, ESCluster
|
||||
from inse.model import ESCluster, ESIndex, SortDirection
|
||||
from inse.models.openalex.work import Work
|
||||
from inse.works.v2.model import (
|
||||
PrimaryCategoryYearAggregation,
|
||||
PrimaryCategoryYearAggregationPage,
|
||||
@@ -11,16 +13,12 @@ from inse.works.v2.model import (
|
||||
WorkPageV2,
|
||||
WorkSortBy,
|
||||
)
|
||||
from inse.models.openalex.work import Work
|
||||
from inse.auth.model import AccessTokenMetadata
|
||||
import inse.authors.v2.service as author_service
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.setLevel(logging.DEBUG)
|
||||
|
||||
|
||||
def _authors_nested_query(author_ids: List[str]) -> Dict:
|
||||
def _authors_nested_query(author_ids: list[str]) -> dict:
|
||||
"""Returns a nested query for filtering works by a list of author IDs.
|
||||
|
||||
Args:
|
||||
@@ -38,7 +36,7 @@ def _authors_nested_query(author_ids: List[str]) -> Dict:
|
||||
}
|
||||
|
||||
|
||||
def _institutions_nested_query(institution_ids: List[str]) -> Dict:
|
||||
def _institutions_nested_query(institution_ids: list[str]) -> dict:
|
||||
"""Returns a nested query for filtering works by a list of institution IDs.
|
||||
|
||||
Args:
|
||||
@@ -61,7 +59,7 @@ def _institutions_nested_query(institution_ids: List[str]) -> Dict:
|
||||
}
|
||||
|
||||
|
||||
def _title_query(title: str) -> Dict:
|
||||
def _title_query(title: str) -> dict:
|
||||
"""Returns a query for filtering works by title using a multi-match query.
|
||||
|
||||
Args:
|
||||
@@ -84,12 +82,12 @@ def _title_query(title: str) -> Dict:
|
||||
|
||||
|
||||
def _apply_common_filters(
|
||||
must: List,
|
||||
publication_years: Optional[List[int]],
|
||||
publication_types: Optional[List[str]],
|
||||
language_codes: Optional[List[str]],
|
||||
topic_ids: Optional[List[str]],
|
||||
title: Optional[str] = None,
|
||||
must: list,
|
||||
publication_years: list[int] | None,
|
||||
publication_types: list[str] | None,
|
||||
language_codes: list[str] | None,
|
||||
topic_ids: list[str] | None,
|
||||
title: str | None = None,
|
||||
) -> None:
|
||||
"""Applies common filters to the provided list of must conditions for filtering works.
|
||||
|
||||
@@ -115,7 +113,7 @@ def _apply_common_filters(
|
||||
must.append(_title_query(title))
|
||||
|
||||
|
||||
def _build_sort(sort_by: WorkSortBy, sort_order: SortDirection) -> List[Dict]:
|
||||
def _build_sort(sort_by: WorkSortBy, sort_order: SortDirection) -> list[dict]:
|
||||
"""Builds a sort criteria list for sorting works based on the specified sort_by and sort_order.
|
||||
|
||||
Args:
|
||||
@@ -131,7 +129,7 @@ def _build_sort(sort_by: WorkSortBy, sort_order: SortDirection) -> List[Dict]:
|
||||
|
||||
|
||||
async def _execute_works_search(
|
||||
must: List[Dict],
|
||||
must: list[dict],
|
||||
page: int,
|
||||
size: int,
|
||||
sort_by: WorkSortBy,
|
||||
@@ -173,15 +171,15 @@ async def _execute_works_search(
|
||||
async def get_works(
|
||||
page: int,
|
||||
size: int,
|
||||
raw_oa_author_id: Optional[str] = None,
|
||||
raw_oa_institution_id: Optional[str] = None,
|
||||
title: Optional[str] = None,
|
||||
author_ids: Optional[List[str]] = None,
|
||||
institution_ids: Optional[List[str]] = None,
|
||||
publication_years: Optional[List[int]] = None,
|
||||
publication_types: Optional[List[str]] = None,
|
||||
topic_ids: Optional[List[str]] = None,
|
||||
language_codes: Optional[List[str]] = None,
|
||||
raw_oa_author_id: str | None = None,
|
||||
raw_oa_institution_id: str | None = None,
|
||||
title: str | None = None,
|
||||
author_ids: list[str] | None = None,
|
||||
institution_ids: list[str] | None = None,
|
||||
publication_years: list[int] | None = None,
|
||||
publication_types: list[str] | None = None,
|
||||
topic_ids: list[str] | None = None,
|
||||
language_codes: list[str] | None = None,
|
||||
sort_by: WorkSortBy = WorkSortBy.PUBLICATION_YEAR,
|
||||
sort_order: SortDirection = SortDirection.DESCENDING,
|
||||
) -> WorkPageV2:
|
||||
@@ -213,7 +211,7 @@ async def get_works(
|
||||
"get_works requires at least one of raw_oa_author_id or raw_oa_institution_id"
|
||||
)
|
||||
|
||||
must: List = []
|
||||
must: list = []
|
||||
|
||||
if raw_oa_author_id:
|
||||
must.append(_authors_nested_query([raw_oa_author_id]))
|
||||
@@ -233,34 +231,24 @@ async def get_works(
|
||||
|
||||
|
||||
async def get_works_by_keywords(
|
||||
topics: Optional[List[str]] = Query(None, description="List of topics to match."),
|
||||
topic_ids: Optional[List[str]] = Query(
|
||||
None, description="List of topic IDs to match."
|
||||
),
|
||||
filter_topic_ids: Optional[List[str]] = Query(
|
||||
None,
|
||||
description="Additional topic IDs to filter results by (OR semantics), "
|
||||
"applied independently of the fuzzy/keyword search mode.",
|
||||
),
|
||||
keywords: Optional[List[str]] = Query(
|
||||
None, description="Raw keywords to search in title/abstract."
|
||||
),
|
||||
title: Optional[str] = None,
|
||||
fuzzy: bool = Query(
|
||||
True, description="Use topic resolution if True, otherwise use raw keywords."
|
||||
),
|
||||
publication_year: Optional[List[int]] = Query(None),
|
||||
publication_type: Optional[List[str]] = Query(None, alias="type"),
|
||||
language: Optional[List[str]] = Query(None),
|
||||
institution_ids: Optional[List[str]] = Query(None),
|
||||
author_ids: Optional[List[str]] = Query(None),
|
||||
topics: list[str] | None = None,
|
||||
topic_ids: list[str] | None = None,
|
||||
filter_topic_ids: list[str] | None = None,
|
||||
keywords: list[str] | None = None,
|
||||
title: str | None = None,
|
||||
fuzzy: bool = True,
|
||||
publication_year: list[int] | None = None,
|
||||
publication_type: list[str] | None = None,
|
||||
language: list[str] | None = None,
|
||||
institution_ids: list[str] | None = None,
|
||||
author_ids: list[str] | None = None,
|
||||
page: int = 0,
|
||||
size: int = 10,
|
||||
sort_by: WorkSortBy = Query(WorkSortBy.PUBLICATION_YEAR),
|
||||
sort_order: SortDirection = Query(SortDirection.DESCENDING),
|
||||
sort_by: WorkSortBy = WorkSortBy.PUBLICATION_YEAR,
|
||||
sort_order: SortDirection = SortDirection.DESCENDING,
|
||||
) -> WorkPageV2:
|
||||
# print(f"get_works_by_keywords called with topics={topics}, topic_ids={topic_ids}, filter_topic_ids={filter_topic_ids}, keywords={keywords}, fuzzy={fuzzy}, publication_year={publication_year}, publication_type={publication_type}, language={language},title={title}, institution_ids={institution_ids}, page={page}, size={size}, sort_by={sort_by}, sort_order={sort_order}")
|
||||
def _topics_nested_clause(should_clauses: List[Dict]) -> Dict:
|
||||
def _topics_nested_clause(should_clauses: list[dict]) -> dict:
|
||||
return {
|
||||
"nested": {
|
||||
"path": "topics",
|
||||
@@ -274,7 +262,7 @@ async def get_works_by_keywords(
|
||||
}
|
||||
}
|
||||
|
||||
def _single_topic_id_match(topic_id: str) -> Dict:
|
||||
def _single_topic_id_match(topic_id: str) -> dict:
|
||||
return {
|
||||
"bool": {
|
||||
"should": [
|
||||
@@ -357,7 +345,7 @@ async def get_works_by_keywords(
|
||||
sort = [{"title.keyword": sort_order.value}]
|
||||
else:
|
||||
sort = [{sort_by.value: sort_order.value}]
|
||||
print(f"Final query:", must)
|
||||
print("Final query:", must)
|
||||
# search
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.OPENALEX_WORKS_WILDCARD,
|
||||
@@ -391,7 +379,7 @@ async def get_works_by_keywords(
|
||||
total = hits_block.get("total", {}).get("value", 0)
|
||||
hits = hits_block.get("hits", [])
|
||||
|
||||
elements: List[Work] = []
|
||||
elements: list[Work] = []
|
||||
for hit in hits:
|
||||
source = hit.get("_source", {})
|
||||
logger.debug(f"Hit source for keyword search: {source}")
|
||||
@@ -408,11 +396,11 @@ async def get_author_works(
|
||||
page: int,
|
||||
size: int,
|
||||
title: str = "",
|
||||
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,
|
||||
publication_years: list[int] | None = None,
|
||||
publication_types: list[str] | None = None,
|
||||
institution_ids: list[str] | None = None,
|
||||
topic_ids: list[str] | None = None,
|
||||
language_codes: list[str] | None = None,
|
||||
sort_by: WorkSortBy = WorkSortBy.PUBLICATION_YEAR,
|
||||
sort_order: SortDirection = SortDirection.DESCENDING,
|
||||
) -> WorkPageV2:
|
||||
@@ -455,11 +443,11 @@ async def get_institution_works(
|
||||
page: int,
|
||||
size: int,
|
||||
title: str = "",
|
||||
publication_years: Optional[List[int]] = None,
|
||||
publication_types: Optional[List[str]] = None,
|
||||
author_ids: Optional[List[str]] = None,
|
||||
topic_ids: Optional[List[str]] = None,
|
||||
language_codes: Optional[List[str]] = None,
|
||||
publication_years: list[int] | None = None,
|
||||
publication_types: list[str] | None = None,
|
||||
author_ids: list[str] | None = None,
|
||||
topic_ids: list[str] | None = None,
|
||||
language_codes: list[str] | None = None,
|
||||
sort_by: WorkSortBy = WorkSortBy.PUBLICATION_YEAR,
|
||||
sort_order: SortDirection = SortDirection.DESCENDING,
|
||||
) -> WorkPageV2:
|
||||
@@ -497,9 +485,7 @@ async def get_institution_works(
|
||||
)
|
||||
|
||||
|
||||
async def get_work(
|
||||
raw_oa_work_id: str, source: Optional[List[str]] = None
|
||||
) -> Work | None:
|
||||
async def get_work(raw_oa_work_id: str, source: list[str] | None = None) -> Work | None:
|
||||
"""Retrieves a work based on its OpenAlex ID.
|
||||
|
||||
Args:
|
||||
@@ -524,11 +510,11 @@ async def get_work(
|
||||
|
||||
|
||||
async def search_works(
|
||||
query: Optional[Dict] = None,
|
||||
source: Optional[List[str]] = None,
|
||||
query: dict | None = None,
|
||||
source: list[str] | None = None,
|
||||
page: int = 0,
|
||||
size: int = 10,
|
||||
sort: Optional[List[Dict]] = None,
|
||||
sort: list[dict] | None = None,
|
||||
) -> WorkPageV2:
|
||||
"""Searches for works based on the provided criteria.
|
||||
|
||||
@@ -553,7 +539,7 @@ async def search_works(
|
||||
|
||||
hits_block = response.get("hits", {})
|
||||
total = hits_block.get("total", {}).get("value", 0)
|
||||
works: List[Work] = []
|
||||
works: list[Work] = []
|
||||
for hit in hits_block.get("hits", []):
|
||||
work = Work.from_dict(hit.get("_source", {})) # type: ignore
|
||||
if work is not None:
|
||||
@@ -563,7 +549,7 @@ async def search_works(
|
||||
|
||||
|
||||
async def _get_works_by_work_ids_and_institution_id(
|
||||
work_ids: List[str], raw_oa_institution_id: str | None
|
||||
work_ids: list[str], raw_oa_institution_id: str | None
|
||||
) -> WorkPageV2:
|
||||
"""Retrieves works based on a list of work IDs and filters them by the specified institution ID.
|
||||
|
||||
@@ -636,8 +622,8 @@ def _work_has_authorship_with_institution_id(
|
||||
|
||||
|
||||
async def search_work_classifications(
|
||||
query: Optional[Dict] = None,
|
||||
source: Optional[List[str]] = None,
|
||||
query: dict | None = None,
|
||||
source: list[str] | None = None,
|
||||
page: int = 0,
|
||||
size: int = 10,
|
||||
) -> WorkClassificationPage:
|
||||
@@ -662,7 +648,7 @@ async def search_work_classifications(
|
||||
|
||||
hits_block = response.get("hits", {})
|
||||
total = hits_block.get("total", {}).get("value", 0)
|
||||
classifications: List[WorkClassification] = []
|
||||
classifications: list[WorkClassification] = []
|
||||
for hit in hits_block.get("hits", []):
|
||||
classification = WorkClassification.from_dict(hit.get("_source", {})) # type: ignore
|
||||
if classification is not None:
|
||||
@@ -674,7 +660,7 @@ async def search_work_classifications(
|
||||
|
||||
|
||||
async def _get_work_classifications_by_work_ids(
|
||||
work_ids: List[str],
|
||||
work_ids: list[str],
|
||||
page: int = 0,
|
||||
size: int = 10000,
|
||||
) -> WorkClassificationPage:
|
||||
@@ -712,7 +698,9 @@ async def _get_work_classifications_by_work_ids(
|
||||
|
||||
async def get_work_classifications_by_work_ids(
|
||||
access_token_metadata: AccessTokenMetadata,
|
||||
work_ids: List[str],
|
||||
work_ids: list[str],
|
||||
raw_oa_author_id: str | None = None,
|
||||
raw_oa_institution_id: str | None = None,
|
||||
page: int = 0,
|
||||
size: int = 10000,
|
||||
) -> WorkClassificationPage:
|
||||
@@ -721,30 +709,102 @@ async def get_work_classifications_by_work_ids(
|
||||
Args:
|
||||
access_token_metadata (AccessTokenMetadata): The access token metadata containing the effective institution ID.
|
||||
work_ids (List[str]): The list of work IDs to retrieve classifications for.
|
||||
raw_oa_author_id (Optional[str], optional): The ID of the author to filter by. Defaults to None.
|
||||
raw_oa_institution_id (Optional[str], optional): The ID of the institution to filter by. Defaults to None.
|
||||
page (int, optional): The page number. Defaults to 0.
|
||||
size (int, optional): The number of results per page. Defaults to 10000.
|
||||
|
||||
Returns:
|
||||
WorkClassificationPage: The page of work classifications matching the criteria.
|
||||
"""
|
||||
raw_account_institution_id = access_token_metadata.effective_institution_id
|
||||
if raw_oa_author_id:
|
||||
return await _get_author_work_classifications_by_work_ids(
|
||||
access_token_metadata=access_token_metadata,
|
||||
work_ids=work_ids,
|
||||
raw_oa_author_id=raw_oa_author_id,
|
||||
page=page,
|
||||
size=size,
|
||||
)
|
||||
elif raw_oa_institution_id:
|
||||
return await _get_institution_work_classifications_by_work_ids(
|
||||
access_token_metadata=access_token_metadata,
|
||||
work_ids=work_ids,
|
||||
raw_oa_institution_id=raw_oa_institution_id,
|
||||
page=page,
|
||||
size=size,
|
||||
)
|
||||
else:
|
||||
raise ValueError(
|
||||
"get_work_classifications_by_work_ids requires at least one of raw_oa_author_id or raw_oa_institution_id"
|
||||
)
|
||||
|
||||
work_page = await _get_works_by_work_ids_and_institution_id(
|
||||
work_ids=work_ids, raw_oa_institution_id=raw_account_institution_id
|
||||
)
|
||||
|
||||
allowed_work_ids: List[str] = [
|
||||
work.id for work in work_page.elements if work.id is not None
|
||||
]
|
||||
async def _get_author_work_classifications_by_work_ids(
|
||||
access_token_metadata: AccessTokenMetadata,
|
||||
work_ids: list[str],
|
||||
raw_oa_author_id: str,
|
||||
page: int = 0,
|
||||
size: int = 10000,
|
||||
) -> WorkClassificationPage:
|
||||
"""Retrieves work classifications for a list of work IDs, filtered by the effective institution ID from the access token metadata and the specified author ID.
|
||||
|
||||
Args:
|
||||
access_token_metadata (AccessTokenMetadata): The access token metadata containing the effective institution ID.
|
||||
work_ids (list[str]): The list of work IDs to retrieve classifications for.
|
||||
raw_oa_author_id (str): The ID of the author to filter by.
|
||||
page (int, optional): The page number. Defaults to 0.
|
||||
size (int, optional): The number of results per page. Defaults to 10000.
|
||||
|
||||
Returns:
|
||||
WorkClassificationPage: The page of work classifications matching the criteria.
|
||||
"""
|
||||
|
||||
account_institution_id = access_token_metadata.effective_institution_id
|
||||
if not account_institution_id:
|
||||
return WorkClassificationPage(elements=[], total=0, page=page, size=size)
|
||||
if not await author_service.author_currently_belongs_to_institution(
|
||||
raw_oa_author_id=raw_oa_author_id, raw_oa_institution_id=account_institution_id
|
||||
):
|
||||
return WorkClassificationPage(elements=[], total=0, page=page, size=size)
|
||||
|
||||
return await _get_work_classifications_by_work_ids(
|
||||
work_ids=allowed_work_ids, page=page, size=size
|
||||
work_ids=work_ids, page=page, size=size
|
||||
)
|
||||
|
||||
|
||||
async def _get_institution_work_classifications_by_work_ids(
|
||||
access_token_metadata: AccessTokenMetadata,
|
||||
work_ids: list[str],
|
||||
raw_oa_institution_id: str,
|
||||
page: int = 0,
|
||||
size: int = 10000,
|
||||
) -> WorkClassificationPage:
|
||||
"""Retrieves work classifications for a list of work IDs, filtered by the effective institution ID from the access token metadata.
|
||||
|
||||
Args:
|
||||
access_token_metadata (AccessTokenMetadata): The access token metadata containing the effective institution ID.
|
||||
work_ids (list[str]): The list of work IDs to retrieve classifications for.
|
||||
raw_oa_institution_id (str): The ID of the institution to filter by.
|
||||
page (int, optional): The page number. Defaults to 0.
|
||||
size (int, optional): The number of results per page. Defaults to 10000.
|
||||
|
||||
Returns:
|
||||
WorkClassificationPage: The page of work classifications matching the criteria.
|
||||
"""
|
||||
account_institution_id = access_token_metadata.effective_institution_id
|
||||
if not account_institution_id:
|
||||
return WorkClassificationPage(elements=[], total=0, page=page, size=size)
|
||||
if account_institution_id != raw_oa_institution_id:
|
||||
return WorkClassificationPage(elements=[], total=0, page=page, size=size)
|
||||
|
||||
return await _get_work_classifications_by_work_ids(
|
||||
work_ids=work_ids, page=page, size=size
|
||||
)
|
||||
|
||||
|
||||
async def _get_work_classification_by_work_id(
|
||||
raw_oa_work_id: str, source: Optional[List[str]] = None
|
||||
) -> Optional[WorkClassification]:
|
||||
raw_oa_work_id: str, source: list[str] | None = None
|
||||
) -> WorkClassification | None:
|
||||
"""Retrieves a work classification for a specific work ID.
|
||||
|
||||
Args:
|
||||
@@ -771,7 +831,7 @@ async def _get_work_classification_by_work_id(
|
||||
async def get_work_classification_by_work_id(
|
||||
access_token_metadata: AccessTokenMetadata,
|
||||
raw_oa_work_id: str,
|
||||
) -> Optional[WorkClassification]:
|
||||
) -> WorkClassification | None:
|
||||
"""Retrieves a work classification for a specific work ID, filtered by the effective institution ID from the access token metadata.
|
||||
|
||||
Args:
|
||||
@@ -881,7 +941,7 @@ async def _get_primary_category_year_aggregations(
|
||||
response.get("aggregations", {}).get("by_year", {}).get("buckets", [])
|
||||
)
|
||||
|
||||
results: List[PrimaryCategoryYearAggregation] = []
|
||||
results: list[PrimaryCategoryYearAggregation] = []
|
||||
for year_bucket in year_buckets:
|
||||
category_buckets = year_bucket.get("by_category", {}).get("buckets", [])
|
||||
categories = {cb["key"]: cb["doc_count"] for cb in category_buckets}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -462,16 +462,18 @@ export class WorksV2Service extends BaseService {
|
||||
* Returns the classifications of works based on their IDs.
|
||||
* @endpoint get /api/v2/works/classification/works/search
|
||||
* @param workIds A list of OpenAlex work IDs to retrieve classifications for.
|
||||
* @param rawOaAuthorId The raw OpenAlex author id to filter by.
|
||||
* @param rawOaInstitutionId The raw OpenAlex institution id to filter by.
|
||||
* @param page The page number to retrieve. (0-based)
|
||||
* @param size The number of classifications to retrieve per page.
|
||||
* @param secureFgpAcc
|
||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
||||
* @param reportProgress flag to report request and response progress.
|
||||
*/
|
||||
public getWorkClassificationsByWorkIds(workIds?: Array<string>, page?: number, size?: number, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<WorkClassificationPage>;
|
||||
public getWorkClassificationsByWorkIds(workIds?: Array<string>, page?: number, size?: number, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<WorkClassificationPage>>;
|
||||
public getWorkClassificationsByWorkIds(workIds?: Array<string>, page?: number, size?: number, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<WorkClassificationPage>>;
|
||||
public getWorkClassificationsByWorkIds(workIds?: Array<string>, page?: number, size?: number, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
public getWorkClassificationsByWorkIds(workIds?: Array<string>, rawOaAuthorId?: string, rawOaInstitutionId?: string, page?: number, size?: number, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<WorkClassificationPage>;
|
||||
public getWorkClassificationsByWorkIds(workIds?: Array<string>, rawOaAuthorId?: string, rawOaInstitutionId?: string, page?: number, size?: number, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<WorkClassificationPage>>;
|
||||
public getWorkClassificationsByWorkIds(workIds?: Array<string>, rawOaAuthorId?: string, rawOaInstitutionId?: string, page?: number, size?: number, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<WorkClassificationPage>>;
|
||||
public getWorkClassificationsByWorkIds(workIds?: Array<string>, rawOaAuthorId?: string, rawOaInstitutionId?: string, page?: number, size?: number, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
if (workIds) {
|
||||
@@ -480,6 +482,10 @@ export class WorksV2Service extends BaseService {
|
||||
<any>element, 'work_ids');
|
||||
})
|
||||
}
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>rawOaAuthorId, 'raw_oa_author_id');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>rawOaInstitutionId, 'raw_oa_institution_id');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>page, 'page');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -12,28 +12,30 @@ import { DFGProjectFachgebieteInner } from './dFGProjectFachgebieteInner';
|
||||
import { Topic } from './topic';
|
||||
import { DfgPersonSummary } from './dfgPersonSummary';
|
||||
|
||||
export interface DfgProjectSummary {
|
||||
/**
|
||||
* The unique identifier of the DFG project.
|
||||
*/
|
||||
id: string;
|
||||
link?: string | null;
|
||||
title?: string | null;
|
||||
professional_classification?: string | null;
|
||||
funding_start?: string | null;
|
||||
funding_end?: string | null;
|
||||
/**
|
||||
* Institutions associated with the project.
|
||||
*/
|
||||
institutions?: Array<DfgInstitutionSummary>;
|
||||
/**
|
||||
* The names of the persons involved in the DFG project.
|
||||
*/
|
||||
names?: Array<string>;
|
||||
/**
|
||||
* The persons involved in the DFG project.
|
||||
*/
|
||||
persons?: Array<DfgPersonSummary>;
|
||||
subject_classifications?: Array<DFGProjectFachgebieteInner> | null;
|
||||
topics?: Array<Topic> | null;
|
||||
|
||||
export interface DfgProjectSummary {
|
||||
/**
|
||||
* The unique identifier of the DFG project.
|
||||
*/
|
||||
id: string;
|
||||
link?: string | null;
|
||||
title?: string | null;
|
||||
professional_classification?: string | null;
|
||||
funding_start?: string | null;
|
||||
funding_end?: string | null;
|
||||
/**
|
||||
* Institutions associated with the project.
|
||||
*/
|
||||
institutions?: Array<DfgInstitutionSummary>;
|
||||
/**
|
||||
* The names of the persons involved in the DFG project.
|
||||
*/
|
||||
names?: Array<string>;
|
||||
/**
|
||||
* The persons involved in the DFG project.
|
||||
*/
|
||||
persons?: Array<DfgPersonSummary>;
|
||||
subject_classifications?: Array<DFGProjectFachgebieteInner> | null;
|
||||
topics?: Array<Topic> | null;
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -37,7 +37,8 @@
|
||||
|
||||
<app-publication-table
|
||||
[page]="institutionWorkPage()"
|
||||
[authorFilterEnabled]="true" />
|
||||
[authorFilterEnabled]="true"
|
||||
[rawOaInstitutionId]="rawOaInstitutionId()" />
|
||||
|
||||
<app-query-param-paginator
|
||||
[total]="total()"
|
||||
|
||||
+9
-1
@@ -1,4 +1,4 @@
|
||||
import { Component, computed, input } from '@angular/core';
|
||||
import { Component, computed, inject, input } from '@angular/core';
|
||||
import { PublicationTableComponent } from '../../shared/ui/publication-table/publication-table.component';
|
||||
import {
|
||||
AuthorPage,
|
||||
@@ -11,6 +11,7 @@ import { PublicationFilterComponent } from '../../shared/ui/publication-filters/
|
||||
import { PrimaryCategoryYearAggregationChartComponent } from '../../shared/ui/primary-category-year-aggregation-chart/primary-category-year-aggregation-chart.component';
|
||||
import { MatExpansionModule } from '@angular/material/expansion';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { ActivatedRoute } from '@angular/router';
|
||||
|
||||
@Component({
|
||||
selector: 'app-institution-publications',
|
||||
@@ -26,6 +27,8 @@ import { CommonModule } from '@angular/common';
|
||||
styleUrl: './institution-publications.component.scss',
|
||||
})
|
||||
export class InstitutionPublicationsComponent {
|
||||
private readonly activatedRoute = inject(ActivatedRoute);
|
||||
|
||||
institutionWorkPage = input.required<WorkPageV2>();
|
||||
selectedAuthorsPage = input.required<AuthorPage>();
|
||||
selectedTopicsPage = input.required<TopicPageV2>();
|
||||
@@ -38,4 +41,9 @@ export class InstitutionPublicationsComponent {
|
||||
const page = this.primaryCategoryYearAggregationPage();
|
||||
return (page?.elements?.length ?? 0) > 0;
|
||||
});
|
||||
|
||||
rawOaInstitutionId = computed(() => {
|
||||
const params = this.activatedRoute.parent?.snapshot.paramMap;
|
||||
return params?.get('institutionId') ?? undefined;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -37,7 +37,8 @@
|
||||
|
||||
<app-publication-table
|
||||
[page]="authorWorkPage()"
|
||||
[institutionFilterEnabled]="true" />
|
||||
[institutionFilterEnabled]="true"
|
||||
[rawOaAuthorId]="rawOaAuthorId()" />
|
||||
|
||||
<app-query-param-paginator
|
||||
[total]="total()"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, computed, input } from '@angular/core';
|
||||
import { Component, computed, inject, input, OnInit } from '@angular/core';
|
||||
|
||||
import {
|
||||
WorkPageV2,
|
||||
@@ -12,6 +12,7 @@ import { PublicationTableComponent } from '../../shared/ui/publication-table/pub
|
||||
import { PublicationFilterComponent } from '../../shared/ui/publication-filters/publication-filters.component';
|
||||
import { PrimaryCategoryYearAggregationChartComponent } from '../../shared/ui/primary-category-year-aggregation-chart/primary-category-year-aggregation-chart.component';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { ActivatedRoute } from '@angular/router';
|
||||
|
||||
@Component({
|
||||
selector: 'app-person-publications',
|
||||
@@ -27,6 +28,8 @@ import { CommonModule } from '@angular/common';
|
||||
styleUrl: './person-publications.component.scss',
|
||||
})
|
||||
export class PersonPublicationsComponent {
|
||||
private readonly activatedRoute = inject(ActivatedRoute);
|
||||
|
||||
authorWorkPage = input.required<WorkPageV2>();
|
||||
total = computed(() => this.authorWorkPage().total ?? 0);
|
||||
elements = computed(() => this.authorWorkPage().elements ?? []);
|
||||
@@ -41,4 +44,9 @@ export class PersonPublicationsComponent {
|
||||
const page = this.primaryCategoryYearAggregationPage();
|
||||
return (page?.elements?.length ?? 0) > 0;
|
||||
});
|
||||
|
||||
rawOaAuthorId = computed(() => {
|
||||
const params = this.activatedRoute.parent?.snapshot.paramMap;
|
||||
return params?.get('id') ?? undefined;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<app-data-table
|
||||
[columns]="columns"
|
||||
[columns]="columns()"
|
||||
[data]="elements()"
|
||||
queryParamSortKey="sort_by"
|
||||
queryParamSortDirectionKey="sort_direction" />
|
||||
|
||||
@@ -52,15 +52,29 @@ import { WorkPrimaryCategoryPipe } from '../../pipes/work-primary-category.pipe'
|
||||
templateUrl: './publication-table.component.html',
|
||||
styleUrl: './publication-table.component.scss',
|
||||
})
|
||||
export class PublicationTableComponent implements OnInit {
|
||||
export class PublicationTableComponent {
|
||||
page = input.required<WorkPageV2>();
|
||||
authorFilterEnabled = input<boolean>(false);
|
||||
institutionFilterEnabled = input<boolean>(false);
|
||||
topicFilterEnabled = input<boolean>(false);
|
||||
rawOaAuthorId = input<string | undefined>(undefined);
|
||||
rawOaInstitutionId = input<string | undefined>(undefined);
|
||||
|
||||
shouldFetchClassifications = computed(() => {
|
||||
return (
|
||||
this.rawOaAuthorId() !== undefined ||
|
||||
this.rawOaInstitutionId() !== undefined
|
||||
);
|
||||
});
|
||||
|
||||
showClassificationColumn = computed(() => {
|
||||
return (
|
||||
this.shouldFetchClassifications() && this.workClassifications().length > 0
|
||||
);
|
||||
});
|
||||
|
||||
elements = computed(() => this.page().elements ?? []);
|
||||
|
||||
columns: GenericColumn<Work>[] = [];
|
||||
titleTmp = viewChild.required<TemplateRef<any>>('titleTmp');
|
||||
typeTmp = viewChild.required<TemplateRef<any>>('typeTmp');
|
||||
yearTmp = viewChild.required<TemplateRef<any>>('yearTmp');
|
||||
@@ -103,8 +117,8 @@ export class PublicationTableComponent implements OnInit {
|
||||
return this.queryParamMap().getAll(workQueryParamKeys.topicId);
|
||||
});
|
||||
|
||||
ngOnInit(): void {
|
||||
this.columns = [
|
||||
columns = computed<GenericColumn<Work>[]>(() => {
|
||||
const baseColumns: GenericColumn<Work>[] = [
|
||||
{
|
||||
id: 'title',
|
||||
header: 'Titel',
|
||||
@@ -133,26 +147,30 @@ export class PublicationTableComponent implements OnInit {
|
||||
accessorKey: 'language',
|
||||
cellTemplate: this.languageTmp(),
|
||||
},
|
||||
{
|
||||
];
|
||||
|
||||
if (this.showClassificationColumn()) {
|
||||
baseColumns.push({
|
||||
id: 'classification',
|
||||
header: 'Klassifikation',
|
||||
type: 'display',
|
||||
cellTemplate: this.classificationTmp(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
baseColumns.push(
|
||||
{
|
||||
id: 'authors',
|
||||
header: 'Autoren',
|
||||
type: 'display',
|
||||
cellTemplate: this.authorsTmp(),
|
||||
},
|
||||
|
||||
{
|
||||
id: 'institutions',
|
||||
header: 'Institutionen',
|
||||
type: 'display',
|
||||
cellTemplate: this.institutionsTmp(),
|
||||
},
|
||||
|
||||
{
|
||||
id: 'topics',
|
||||
header: 'Themen',
|
||||
@@ -172,8 +190,10 @@ export class PublicationTableComponent implements OnInit {
|
||||
type: 'display',
|
||||
cellTemplate: this.actionsTmp(),
|
||||
},
|
||||
];
|
||||
}
|
||||
);
|
||||
|
||||
return baseColumns;
|
||||
});
|
||||
|
||||
workIds = computed(
|
||||
() =>
|
||||
@@ -193,9 +213,13 @@ export class PublicationTableComponent implements OnInit {
|
||||
constructor(private readonly worksV2Service: WorksV2Service) {
|
||||
effect(() => {
|
||||
const ids = this.workIds();
|
||||
if (ids.length > 0) {
|
||||
if (ids.length > 0 && this.shouldFetchClassifications()) {
|
||||
this.worksV2Service
|
||||
.getWorkClassificationsByWorkIds(ids)
|
||||
.getWorkClassificationsByWorkIds(
|
||||
ids,
|
||||
this.rawOaAuthorId(),
|
||||
this.rawOaInstitutionId(),
|
||||
)
|
||||
.subscribe((classificationPage) => {
|
||||
this.workClassifications.set(classificationPage.elements ?? []);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user