diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index 88b36788..76db43c7 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -7,7 +7,9 @@ Business logic for persons / authors. import json import logging import time +from datetime import datetime from typing import Optional, Callable, Any, List +from elasticsearch import ApiError, NotFoundError import hashlib import httpx from fastapi import HTTPException @@ -24,8 +26,8 @@ from inse.persons.model import ( CustomAuthor, CustomAuthorsListResponse, PersonSearchRequest, + CareerMetrics, ) - logger = logging.getLogger(__name__) INDEX_NAME = "openalex-authors" @@ -186,6 +188,120 @@ def _fetch_works_and_topics(author_id: str) -> tuple[list, list]: return works, topics +def _get_publication_years_for_author(author_id: str) -> list[int]: + author_url = f"https://openalex.org/{author_id.strip()}" + + body = { + "size": 0, + "query": { + "nested": { + "path": "authorships", + "query": { + "bool": { + "filter": [ + {"term": {"authorships.author.id": author_url}}, + ], + }, + }, + }, + }, + "aggs": { + "publication_years": { + "terms": { + "field": "publication_year", + "size": 1000, + }, + }, + }, + } + + response = elasticsearch.search( + index=config.settings.openalex_works_search_index, + body=body, + ) + + buckets = ( + response.get("aggregations", {}) + .get("publication_years", {}) + .get("buckets", []) + ) + + publication_years: list[int] = [] + + for bucket in buckets: + year = bucket.get("key") + count = bucket.get("doc_count", 0) + + if isinstance(year, int): + publication_years.extend([year] * count) + + return publication_years + +def _classify_career_stage(active_years: int) -> str: + if active_years <= 0: + return "unknown" + + if active_years <= 4: + return "Early Researcher" + + if active_years <= 10: + return "Emerging Researcher" + + if active_years <= 20: + return "Established Researcher" + + return "Senior Researcher" + + +def _compute_career_metrics(publication_years: list[int]) -> CareerMetrics: + current_year = datetime.now().year + + if not publication_years: + return CareerMetrics() + + sorted_years = sorted(publication_years) + unique_years = sorted(set(publication_years)) + + first_year = sorted_years[0] + last_year = sorted_years[-1] + + publication_count = len(sorted_years) + active_years = len(unique_years) + career_stage = _classify_career_stage(active_years) + career_age = last_year - first_year + career_span = last_year - first_year + 1 + + publications_per_active_year = ( + publication_count / active_years if active_years > 0 else None + ) + + publications_per_career_year = ( + publication_count / career_span if career_span > 0 else None + ) + + years_since_last_publication = current_year - last_year + has_suspicious_publication_years = first_year < 1970 or career_span > 60 + + return CareerMetrics( + first_publication_year=first_year, + last_publication_year=last_year, + career_age=career_age, + career_span=career_span, + career_stage=career_stage, + active_years=active_years, + publication_count=publication_count, + publications_per_active_year=publications_per_active_year, + publications_per_career_year=publications_per_career_year, + years_since_last_publication=years_since_last_publication, + has_suspicious_publication_years=has_suspicious_publication_years, + ) + + +def get_career_metrics_for_author(author_id: str) -> CareerMetrics: + publication_years = _get_publication_years_for_author(author_id) + return _compute_career_metrics(publication_years) + + def _build_papers(works: list) -> list: papers = [] @@ -254,23 +370,34 @@ def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> s def get_person_by_id( author_id: str, include: Optional[str] = None -) -> AuthorsListResponse: +) -> CustomAuthorsListResponse: body = { "_source": include.split(",") if include else True, } try: - hit = elasticsearch.get(index="openalex-authors", body=body, doc_id=author_id) + hit = elasticsearch.get( + index="openalex-authors", + body=body, + doc_id=author_id, + ) except NotFoundError: raise HTTPException( status_code=404, detail=f"Person with id {author_id} not found" ) - except ApiError as e: raise HTTPException(status_code=500, detail=f"Elasticsearch error: {str(e)}") - persons = [util.get_persons_data(hit)] - return AuthorsListResponse(results=persons) + author = util.get_persons_data(hit) + career_metrics = get_career_metrics_for_author(author_id) + + custom_author = CustomAuthor( + **author.model_dump(), + career_metrics=career_metrics, + ) + + return CustomAuthorsListResponse(results=[custom_author]) + def search_persons_by_name( diff --git a/service/src/main/inse/persons/model.py b/service/src/main/inse/persons/model.py index 1973c763..300ec2d9 100644 --- a/service/src/main/inse/persons/model.py +++ b/service/src/main/inse/persons/model.py @@ -13,20 +13,59 @@ from inse.models.openalex.authors_list_response import AuthorsListResponse from inse.models.openalex.group_by_result import GroupByResult +class CareerMetrics(BaseModel): + first_publication_year: Optional[int] = Field( + default=None, description="First publication year of the author." + ) + last_publication_year: Optional[int] = Field( + default=None, description="Last publication year of the author." + ) + career_age: Optional[int] = Field( + default=None, description="Difference between last and first publication year." + ) + career_span: Optional[int] = Field( + default=None, description="Inclusive span from first to last publication year." + ) + career_stage: Optional[str] = Field( + default=None, + description="Threshold-based career stage derived from active publication years.", + ) + active_years: int = Field( + default=0, description="Number of distinct years with at least one publication." + ) + publication_count: int = Field( + default=0, description="Number of publications used for career metrics." + ) + publications_per_active_year: Optional[float] = Field( + default=None, description="Average publications per active publication year." + ) + publications_per_career_year: Optional[float] = Field( + default=None, description="Average publications per year over the full career span." + ) + years_since_last_publication: Optional[int] = Field( + default=None, description="Years since the last publication." + ) + has_suspicious_publication_years: bool = Field( + default=False, description="True if publication years look suspicious." + ) + class CustomAuthor(Author): relevance_rating: Optional[str] = Field( default=None, description="The relevance suitability rating." ) + career_metrics: Optional[CareerMetrics] = Field( + default=None, description="Publication-history-based career metrics." + ) class CustomAuthorsListResponse(AuthorsListResponse): placeholder: Optional[CustomAuthor] = Field( default=None, description="A placeholder field for generation." ) - # meta: Optional[Meta] = None - # results: Optional[List[CustomAuthor]] = None - # group_by: Optional[List[GroupByResult]] = None + results: Optional[List[CustomAuthor]] = None + meta: Optional[Meta] = None + group_by: Optional[List[GroupByResult]] = None class PersonBio(BaseModel): diff --git a/service/src/main/inse/persons/service.py b/service/src/main/inse/persons/service.py index 35034d82..c6cae176 100644 --- a/service/src/main/inse/persons/service.py +++ b/service/src/main/inse/persons/service.py @@ -85,7 +85,7 @@ def generate_person_bio( @router.get( "/person/{id}", operation_id="getPersonByID", - response_model=AuthorsListResponse, + response_model=model.CustomAuthorsListResponse, summary="Searches for person by ID.", tags=["Persons"], ) @@ -102,7 +102,7 @@ def get_person_by_id( ), example="topics_full,topic_share", ), - ], + ] = None, ): return logic.get_person_by_id(author_id=id, include=include)