From a9822ca5ff0701e5513f1d7e6e539c9353b99843 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Thu, 4 Jun 2026 10:29:41 +0200 Subject: [PATCH 1/4] refactor(backend/persons): move person logic from logic.py to seperate folder --- service/src/main/inse/logic.py | 209 +-------------------- service/src/main/inse/persons/__init__.py | 0 service/src/main/inse/persons/logic.py | 216 ++++++++++++++++++++++ 3 files changed, 217 insertions(+), 208 deletions(-) create mode 100644 service/src/main/inse/persons/__init__.py create mode 100644 service/src/main/inse/persons/logic.py diff --git a/service/src/main/inse/logic.py b/service/src/main/inse/logic.py index 688c81d9..22723fa2 100644 --- a/service/src/main/inse/logic.py +++ b/service/src/main/inse/logic.py @@ -12,23 +12,16 @@ from typing import Type from sqlalchemy.orm import Session from sqlalchemy import select from sqlalchemy import func -from fastapi import HTTPException import logging import httpx import json -import time from . import schema from . import model from . import config -from .integrations import elasticsearch from .integrations import llm -from . import util -from elasticsearch import Elasticsearch, helpers, NotFoundError, ApiError +from elasticsearch import Elasticsearch -from inse.models.author import Author -from inse.models.authors_list_response import AuthorsListResponse -from inse.models.meta import Meta from inse.models.topic import Topic from inse.models.topic_subfield import TopicSubfield from inse.models.topic_field import TopicField @@ -249,203 +242,3 @@ def count_topic_hierarchy(topic_names: List[str]) -> dict: counts["domains"][domain] = counts["domains"].get(domain, 0) + 1 return counts - - -### persons - - -def search_persons( - author_id: Optional[str] = None, - query: Optional[str] = None, - include: Optional[set[str]] = None, -) -> AuthorsListResponse: - if author_id: - query_field = "_id" - query_value = author_id - elif query: - query_field = "display_name" - query_value = query - else: - return AuthorsListResponse(results=[], meta=Meta(count=0)) - - data = elasticsearch.search( - index="openalex-authors", query_field=query_field, query_value=query_value - ) - - authors = [] - for hit in data.get("hits", {}).get("hits", []): - source = hit.get("_source", {}) - source_copy = dict(source) - source_copy["id"] = source_copy.get("id") or hit.get("_id", "") - - # Resilient sanitization of IDs to protect against model regeneration type conflicts (#Generated) - ids = source_copy.get("ids") - if isinstance(ids, dict): - ids_copy = dict(ids) - for str_field in ["openalex", "orcid", "scopus"]: - val = ids_copy.get(str_field) - if val is not None and not isinstance(val, str): - ids_copy[str_field] = str(val) - source_copy["ids"] = ids_copy - - author = Author.from_dict(source_copy) - if author: - authors.append(author) - - return AuthorsListResponse(results=authors, meta=Meta(count=len(authors))) - - -def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> str: - start_time = time.time() - search_result = search_persons(author_id=author_id) - if not search_result.results: - return "No person found." - if len(search_result.results) > 1: - return "Multiple persons found, cannot generate bio." - - person = search_result.results[0] - person_json = json.dumps(person.model_dump_json()) - - system_prompt = """\ - Erstelle auf Basis der bereitgestellten OpenAlex-Daten ein kurzes Porträt der Person in 3-5 Sätzen. Die Person selbst ist das Subjekt: Beginne mit ihrem Namen und beschreibe sie als Forschende:n (z. B. „{name} ist ein:e Forscher:in im Bereich …"). Schreibe nicht über „die Forschung" oder „die Arbeit" im Abstrakten, sondern durchgehend über die Person. - - Gehe dabei auf folgende drei Punkte ein: - - 1. Besonderheiten: Was hebt die Person im Vergleich zu anderen Forschenden ähnlicher Karrierephase und ähnlichen Feldes hervor? (z. B. überdurchschnittlicher Impact gemessen an der aktiven Zeit, hoher Erst-/Korrespondenzautor-Anteil, einzelnes Breakout-Paper, frühe Positionierung in einem später gewachsenen Thema) - 2. Wirtschaftliche Relevanz: Arbeitet die Person in einem grundsätzlich anwendungsnahen/kommerziell interessanten Themenfeld oder eher in der Grundlagenforschung? - 3. Dynamik: Entwickelt sich ihr Publikations-/Zitationsverlauf zuletzt steigend, konstant oder abflachend? - - Stütze jede Aussage auf konkrete Werte aus den Daten und formuliere nichts, was sich nicht belegen lässt. Wenn die Daten für einen Punkt keine klare Aussage zulassen, formuliere ihn entsprechend zurückhaltend oder lasse ihn weg, statt zu spekulieren. Gib nur das Porträt zurück, ohne Einleitung oder Schluss.\ - """ - - user_prompt = f"Daten zur Person:\n{person_json}" - - headers = { - "Authorization": f"Bearer {config.settings.llm_api_key}", - "Content-Type": "application/json", - } - payload = { - "model": config.settings.llm_model, - "prompt": f"{system_prompt}\n{user_prompt}", - "stream": False, - } - - with httpx.Client(timeout=30.0) as client: - response = client.post( - config.settings.llm_api_url, json=payload, headers=headers - ) - response.raise_for_status() - data = response.json() - bio = data.get("response", "") - - elapsed_time = time.time() - start_time - logger.info( - f"Bio generation for author {author_id} took {elapsed_time:.2f} seconds" - ) - - return bio - -def get_person_by_id(author_id: str, include: Optional[str] = None) -> AuthorsListResponse: - body = { - "_source":include.split(",") if include else True, - } - - try: - 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) - - -def search_persons_by_name( - author_name: str, limit: Optional[int] = 10, include: Optional[str] = None -) -> AuthorsListResponse: - if not author_name: - raise HTTPException(status_code=400, detail="name must be provided") - - search_query = { - "bool": { - "should": [ - {"match_phrase": {"display_name": {"query": author_name, "boost": 5}}}, - { - "match_phrase_prefix": { - "display_name": {"query": author_name, "boost": 3} - } - }, - # { - # "match": { - # "display_name": { - # "query": author_name, - # "fuzziness": 1 - # } - # } - # } - ], - "minimum_should_match": 1, - } - } - try: - response = elasticsearch.search( - index="openalex-authors", - query=search_query, - source=include.split(",") if include else True, - size=limit, - ) - - except Exception as e: - raise HTTPException( - status_code=500, detail=f"Elasticsearch search failed: {str(e)}" - ) - - hits = response.get("hits", {}).get("hits", []) - - persons = [util.get_persons_data(hit) for hit in hits] - - return AuthorsListResponse(results=persons) - - -def search_persons_by_institution( - institution_name: str, limit: Optional[int] = 10, include: Optional[str] = None -) -> AuthorsListResponse: - - if not institution_name: - raise HTTPException(status_code=400, detail="institution_name must be provided") - - search_query = { - "nested": { - "path": "affiliations", - "query": { - "match_phrase": { - "affiliations.institution.display_name": institution_name - } - }, - } - } - try: - response = elasticsearch.search( - index="openalex-authors", - query=search_query, - source=include.split(",") if include else True, - size=limit, - sort=[{"works_count": {"order": "desc"}}], - ) - - except Exception as e: - raise HTTPException( - status_code=500, detail=f"Elasticsearch search failed: {str(e)}" - ) - - hits = response.get("hits", {}).get("hits", []) - persons = [util.get_persons_data(hit) for hit in hits] - return AuthorsListResponse(results=persons) diff --git a/service/src/main/inse/persons/__init__.py b/service/src/main/inse/persons/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py new file mode 100644 index 00000000..a93eb1bb --- /dev/null +++ b/service/src/main/inse/persons/logic.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +Business logic for persons / authors. +""" + +import json +import logging +import time +from typing import Optional + +import httpx +from fastapi import HTTPException + +from .. import config +from .. import util +from ..integrations import elasticsearch + +from inse.models.author import Author +from inse.models.authors_list_response import AuthorsListResponse +from inse.models.meta import Meta + +logger = logging.getLogger(__name__) + + +def search_persons( + author_id: Optional[str] = None, + query: Optional[str] = None, + include: Optional[set[str]] = None, +) -> AuthorsListResponse: + if author_id: + query_field = "_id" + query_value = author_id + elif query: + query_field = "display_name" + query_value = query + else: + return AuthorsListResponse(results=[], meta=Meta(count=0)) + + data = elasticsearch.search( + index="openalex-authors", query_field=query_field, query_value=query_value + ) + + authors = [] + for hit in data.get("hits", {}).get("hits", []): + source = hit.get("_source", {}) + source_copy = dict(source) + source_copy["id"] = source_copy.get("id") or hit.get("_id", "") + + # Resilient sanitization of IDs to protect against model regeneration type conflicts (#Generated) + ids = source_copy.get("ids") + if isinstance(ids, dict): + ids_copy = dict(ids) + for str_field in ["openalex", "orcid", "scopus"]: + val = ids_copy.get(str_field) + if val is not None and not isinstance(val, str): + ids_copy[str_field] = str(val) + source_copy["ids"] = ids_copy + + author = Author.from_dict(source_copy) + if author: + authors.append(author) + + return AuthorsListResponse(results=authors, meta=Meta(count=len(authors))) + + +def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> str: + start_time = time.time() + search_result = search_persons(author_id=author_id) + if not search_result.results: + return "No person found." + if len(search_result.results) > 1: + return "Multiple persons found, cannot generate bio." + + person = search_result.results[0] + person_json = json.dumps(person.model_dump_json()) + + system_prompt = """\ + Erstelle auf Basis der bereitgestellten OpenAlex-Daten ein kurzes Porträt der Person in 3-5 Sätzen. Die Person selbst ist das Subjekt: Beginne mit ihrem Namen und beschreibe sie als Forschende:n (z. B. „{name} ist ein:e Forscher:in im Bereich …"). Schreibe nicht über „die Forschung" oder „die Arbeit" im Abstrakten, sondern durchgehend über die Person. + + Gehe dabei auf folgende drei Punkte ein: + + 1. Besonderheiten: Was hebt die Person im Vergleich zu anderen Forschenden ähnlicher Karrierephase und ähnlichen Feldes hervor? (z. B. überdurchschnittlicher Impact gemessen an der aktiven Zeit, hoher Erst-/Korrespondenzautor-Anteil, einzelnes Breakout-Paper, frühe Positionierung in einem später gewachsenen Thema) + 2. Wirtschaftliche Relevanz: Arbeitet die Person in einem grundsätzlich anwendungsnahen/kommerziell interessanten Themenfeld oder eher in der Grundlagenforschung? + 3. Dynamik: Entwickelt sich ihr Publikations-/Zitationsverlauf zuletzt steigend, konstant oder abflachend? + + Stütze jede Aussage auf konkrete Werte aus den Daten und formuliere nichts, was sich nicht belegen lässt. Wenn die Daten für einen Punkt keine klare Aussage zulassen, formuliere ihn entsprechend zurückhaltend oder lasse ihn weg, statt zu spekulieren. Gib nur das Porträt zurück, ohne Einleitung oder Schluss.\ + """ + + user_prompt = f"Daten zur Person:\n{person_json}" + + headers = { + "Authorization": f"Bearer {config.settings.llm_api_key}", + "Content-Type": "application/json", + } + payload = { + "model": config.settings.llm_model, + "prompt": f"{system_prompt}\n{user_prompt}", + "stream": False, + } + + with httpx.Client(timeout=30.0) as client: + response = client.post( + config.settings.llm_api_url, json=payload, headers=headers + ) + response.raise_for_status() + data = response.json() + bio = data.get("response", "") + + elapsed_time = time.time() - start_time + logger.info( + f"Bio generation for author {author_id} took {elapsed_time:.2f} seconds" + ) + + return bio + + +def get_person_by_id(author_id: str, include: Optional[str] = None) -> AuthorsListResponse: + try: + hit = elasticsearch.get( + index="openalex-authors", + doc_id=author_id, + source=include.split(",") if include else None, + ) + except httpx.HTTPStatusError as e: + if e.response.status_code == 404: + raise HTTPException( + status_code=404, detail=f"Person with id {author_id} not found" + ) + raise HTTPException(status_code=500, detail=f"Elasticsearch error: {str(e)}") + persons = [util.get_persons_data(hit)] + + return AuthorsListResponse(results=persons) + + +def search_persons_by_name( + author_name: str, limit: Optional[int] = 10, include: Optional[str] = None +) -> AuthorsListResponse: + if not author_name: + raise HTTPException(status_code=400, detail="name must be provided") + + search_query = { + "bool": { + "should": [ + {"match_phrase": {"display_name": {"query": author_name, "boost": 5}}}, + { + "match_phrase_prefix": { + "display_name": {"query": author_name, "boost": 3} + } + }, + # { + # "match": { + # "display_name": { + # "query": author_name, + # "fuzziness": 1 + # } + # } + # } + ], + "minimum_should_match": 1, + } + } + try: + response = elasticsearch.search( + index="openalex-authors", + query=search_query, + source=include.split(",") if include else True, + size=limit, + ) + + except Exception as e: + raise HTTPException( + status_code=500, detail=f"Elasticsearch search failed: {str(e)}" + ) + + hits = response.get("hits", {}).get("hits", []) + + persons = [util.get_persons_data(hit) for hit in hits] + + return AuthorsListResponse(results=persons) + + +def search_persons_by_institution( + institution_name: str, limit: Optional[int] = 10, include: Optional[str] = None +) -> AuthorsListResponse: + + if not institution_name: + raise HTTPException(status_code=400, detail="institution_name must be provided") + + search_query = { + "nested": { + "path": "affiliations", + "query": { + "match_phrase": { + "affiliations.institution.display_name": institution_name + } + }, + } + } + try: + response = elasticsearch.search( + index="openalex-authors", + query=search_query, + source=include.split(",") if include else True, + size=limit, + sort=[{"works_count": {"order": "desc"}}], + ) + + except Exception as e: + raise HTTPException( + status_code=500, detail=f"Elasticsearch search failed: {str(e)}" + ) + + hits = response.get("hits", {}).get("hits", []) + persons = [util.get_persons_data(hit) for hit in hits] + return AuthorsListResponse(results=persons) From 9f5835a5d30bad668ddcdd23a892d078ee1713d7 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Thu, 4 Jun 2026 10:31:21 +0200 Subject: [PATCH 2/4] refactor(backend/persons): update person logic references to use persons_logic module --- service/src/main/inse/service.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/service/src/main/inse/service.py b/service/src/main/inse/service.py index 76f59946..c3ec0329 100644 --- a/service/src/main/inse/service.py +++ b/service/src/main/inse/service.py @@ -23,6 +23,7 @@ from fastapi import APIRouter from . import model from . import logic +from .persons import logic as persons_logic from . import schema from . import database from . import security @@ -248,7 +249,7 @@ def search_persons( if include else None ) - return logic.search_persons(author_id, query, include_set) + return persons_logic.search_persons(author_id, query, include_set) @router.get( @@ -275,7 +276,7 @@ def generate_person_bio( if include else None ) - bio = logic.generate_person_bio(author_id, include_set) + bio = persons_logic.generate_person_bio(author_id, include_set) return model.PersonBio(bio=bio) @@ -301,7 +302,7 @@ def get_person_by_id( ), ], ): - return logic.get_person_by_id(author_id=id, include=include) + return persons_logic.get_person_by_id(author_id=id, include=include) @router.get( @@ -324,7 +325,7 @@ def search_persons_by_name( ), ], ): - return logic.search_persons_by_name(author_name=author_name, include=include) + return persons_logic.search_persons_by_name(author_name=author_name, include=include) @router.get( @@ -349,4 +350,4 @@ def search_persons_by_institution( ), ], ): - return logic.search_persons_by_institution(institution_name, include=include) + return persons_logic.search_persons_by_institution(institution_name, include=include) From 75514b7f5781b35266aabe970c67575e654d8462 Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Thu, 4 Jun 2026 10:32:47 +0200 Subject: [PATCH 3/4] fix(backend/elasticsearch): update get function to use query parameters instead of body --- .../src/main/inse/integrations/elasticsearch.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/service/src/main/inse/integrations/elasticsearch.py b/service/src/main/inse/integrations/elasticsearch.py index 3d744ad9..e045987c 100644 --- a/service/src/main/inse/integrations/elasticsearch.py +++ b/service/src/main/inse/integrations/elasticsearch.py @@ -49,22 +49,23 @@ def search( return response.json() def get( index: str, - doc_id:str, - body: dict = None, - + doc_id: str, + source: list = None, ) -> dict[str, Any]: headers = { "Authorization": f"ApiKey {config.settings.elasticsearch_api_key}", "Content-Type": "application/json" } - payload = body - - # get document directly + + params = {} + if source is not None: + params["_source_includes"] = ",".join(source) + with httpx.Client() as client: response = client.get( f"{config.settings.elasticsearch_url}/{index}/_doc/{doc_id}", - json=payload, + params=params, headers=headers ) response.raise_for_status() From ec2899fad96c88a15761f90294fc8a50549b51fd Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Thu, 4 Jun 2026 11:07:19 +0200 Subject: [PATCH 4/4] refactor(backend/persons): move person logic and endpoints to own package --- service/src/main/inse/main.py | 2 + service/src/main/inse/model.py | 3 - service/src/main/inse/persons/model.py | 12 ++ service/src/main/inse/persons/service.py | 153 +++++++++++++++++++++++ service/src/main/inse/service.py | 141 --------------------- 5 files changed, 167 insertions(+), 144 deletions(-) create mode 100644 service/src/main/inse/persons/model.py create mode 100644 service/src/main/inse/persons/service.py diff --git a/service/src/main/inse/main.py b/service/src/main/inse/main.py index 41d776c2..2b018c5d 100644 --- a/service/src/main/inse/main.py +++ b/service/src/main/inse/main.py @@ -12,6 +12,7 @@ from fastapi.responses import RedirectResponse from fastapi.middleware.cors import CORSMiddleware from inse.collaboration_network.router import router as collaboration_network_router from inse.works.service import router as works_service_router +from inse.persons.service import router as persons_service_router from . import config from .service import router as service_router @@ -32,6 +33,7 @@ app = FastAPI( ) app.include_router(collaboration_network_router) app.include_router(works_service_router) +app.include_router(persons_service_router) app.include_router(service_router) app.include_router(account_router) diff --git a/service/src/main/inse/model.py b/service/src/main/inse/model.py index aaac61b1..669f049f 100644 --- a/service/src/main/inse/model.py +++ b/service/src/main/inse/model.py @@ -36,8 +36,5 @@ class Page(BaseModel, Generic[T]): class ItemPage(Page[Item]): pass -class PersonBio(BaseModel): - bio: str = Field(description="The generated biography.") - diff --git a/service/src/main/inse/persons/model.py b/service/src/main/inse/persons/model.py new file mode 100644 index 00000000..4da3f5fe --- /dev/null +++ b/service/src/main/inse/persons/model.py @@ -0,0 +1,12 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +Data models for persons / authors. +""" + +from pydantic import BaseModel +from pydantic import Field + + +class PersonBio(BaseModel): + bio: str = Field(description="The generated biography.") diff --git a/service/src/main/inse/persons/service.py b/service/src/main/inse/persons/service.py new file mode 100644 index 00000000..94fca980 --- /dev/null +++ b/service/src/main/inse/persons/service.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +REST API for persons / authors. +""" + +from typing import Annotated, Optional + +from fastapi import APIRouter +from fastapi import Path +from fastapi import Query + +from . import logic +from . import model +from inse.models.authors_list_response import AuthorsListResponse + + +router = APIRouter( + prefix="/api/inse-service", + tags=["Persons"], + responses={404: {"description": "Not found"}}, +) + + +@router.get( + "/persons/search", + operation_id="searchPersons", + response_model=AuthorsListResponse, + summary="Searches for persons by ID or name.", + response_model_exclude_none=True, +) +def search_persons( + author_id: Annotated[ + str, Query(description="OpenAlex author ID (e.g., A5093075883)") + ] = None, + query: Annotated[ + str, Query(description="Search query (e.g., Arman AND Arzani)") + ] = None, + include: Annotated[ + Optional[str], + Query( + description=( + "Comma-separated include tags: topics_full, topic_share, summary_stats, ids, " + "last_known_institutions, sources, counts_by_year, works_api_url, dates, " + "cited_by_count_boost" + ), + example="topics_full,topic_share", + ), + ] = None, +): + include_set = ( + {tag.strip().lower() for tag in include.split(",") if tag.strip()} + if include + else None + ) + return logic.search_persons(author_id, query, include_set) + + +@router.get( + "/persons/bio", + operation_id="generatePersonBio", + response_model=model.PersonBio, + summary="Generates a bio for a person by author ID.", +) +def generate_person_bio( + author_id: Annotated[ + str, Query(description="OpenAlex author ID (e.g., A5093075883)") + ], + include: Annotated[ + Optional[str], + Query( + description=("Comma-separated list to include tags"), + example="topics_full,topic_share", + ), + ] = None, +): + include_set = ( + {tag.strip().lower() for tag in include.split(",") if tag.strip()} + if include + else None + ) + bio = logic.generate_person_bio(author_id, include_set) + return model.PersonBio(bio=bio) + + +@router.get( + "/person/{id}", + operation_id="getPersonByID", + response_model=AuthorsListResponse, + summary="Searches for person by ID.", +) +def get_person_by_id( + id: Annotated[ + str, Path(description="OpenAlex author ID", examples=["A5093075883"]) + ], + include: Annotated[ + Optional[str], + Query( + description=( + "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, " + "last_known_institutions, ..." + ), + example="topics_full,topic_share", + ), + ], +): + return logic.get_person_by_id(author_id=id, include=include) + + +@router.get( + "/persons/searchByName", + operation_id="searchPersonsByName", + response_model=AuthorsListResponse, + summary="Searches for person by name.", +) +def search_persons_by_name( + author_name: Annotated[str, Query(description="Authors name (e.g., Arman Arzani)")], + include: Annotated[ + Optional[str], + Query( + description=( + "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, " + "last_known_institutions, ..." + ), + example="topics_full,topic_share", + ), + ], +): + return logic.search_persons_by_name(author_name=author_name, include=include) + + +@router.get( + "/persons/searchByInstitution", + operation_id="searchPersonsByInstitution", + response_model=AuthorsListResponse, + summary="Searches for persons by institution name.", +) +def search_persons_by_institution( + institution_name: Annotated[ + str, Query(description="Institution name (e.g., MIT, Oxford University)") + ], + include: Annotated[ + Optional[str], + Query( + description=( + "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, " + "last_known_institutions, ..." + ), + example="topics_full,topic_share", + ), + ], +): + return logic.search_persons_by_institution(institution_name, include=include) diff --git a/service/src/main/inse/service.py b/service/src/main/inse/service.py index c3ec0329..92ac3e42 100644 --- a/service/src/main/inse/service.py +++ b/service/src/main/inse/service.py @@ -23,15 +23,12 @@ from fastapi import APIRouter from . import model from . import logic -from .persons import logic as persons_logic from . import schema from . import database from . import security from . import util from .works import service as works_service -from inse.models.authors_list_response import AuthorsListResponse - logger = logging.getLogger(__name__) @@ -213,141 +210,3 @@ def count_topic_hierarchy( ): return logic.count_topic_hierarchy(topic_names) - -### persons - - -@router.get( - "/persons/search", - operation_id="searchPersons", - response_model=AuthorsListResponse, - summary="Searches for persons by ID or name.", - response_model_exclude_none=True, - tags=["Persons"], -) -def search_persons( - author_id: Annotated[ - str, Query(description="OpenAlex author ID (e.g., A5093075883)") - ] = None, - query: Annotated[ - str, Query(description="Search query (e.g., Arman AND Arzani)") - ] = None, - include: Annotated[ - Optional[str], - Query( - description=( - "Comma-separated include tags: topics_full, topic_share, summary_stats, ids, " - "last_known_institutions, sources, counts_by_year, works_api_url, dates, " - "cited_by_count_boost" - ), - example="topics_full,topic_share", - ), - ] = None, -): - include_set = ( - {tag.strip().lower() for tag in include.split(",") if tag.strip()} - if include - else None - ) - return persons_logic.search_persons(author_id, query, include_set) - - -@router.get( - "/persons/bio", - operation_id="generatePersonBio", - response_model=model.PersonBio, - summary="Generates a bio for a person by author ID.", - tags=["Persons"], -) -def generate_person_bio( - author_id: Annotated[ - str, Query(description="OpenAlex author ID (e.g., A5093075883)") - ], - include: Annotated[ - Optional[str], - Query( - description=("Comma-separated list to include tags"), - example="topics_full,topic_share", - ), - ] = None, -): - include_set = ( - {tag.strip().lower() for tag in include.split(",") if tag.strip()} - if include - else None - ) - bio = persons_logic.generate_person_bio(author_id, include_set) - return model.PersonBio(bio=bio) - - -@router.get( - "/person/{id}", - operation_id="getPersonByID", - response_model=AuthorsListResponse, - summary="Searches for person by ID.", - tags=["Persons"], -) -def get_person_by_id( - id: Annotated[ - str, Path(description="OpenAlex author ID", examples=["A5093075883"]) - ], - include: Annotated[ - Optional[str], - Query( - description=( - "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, " - "last_known_institutions, ..." - ), - example="topics_full,topic_share", - ), - ], -): - return persons_logic.get_person_by_id(author_id=id, include=include) - - -@router.get( - "/persons/searchByName", - operation_id="searchPersonsByName", - response_model=AuthorsListResponse, - summary="Searches for person by name.", - tags=["Persons"], -) -def search_persons_by_name( - author_name: Annotated[str, Query(description="Authors name (e.g., Arman Arzani)")], - include: Annotated[ - Optional[str], - Query( - description=( - "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, " - "last_known_institutions, ..." - ), - example="topics_full,topic_share", - ), - ], -): - return persons_logic.search_persons_by_name(author_name=author_name, include=include) - - -@router.get( - "/persons/searchByInstitution", - operation_id="searchPersonsByInstitution", - response_model=AuthorsListResponse, - summary="Searches for persons by institution name.", - tags=["Persons"], -) -def search_persons_by_institution( - institution_name: Annotated[ - str, Query(description="Institution name (e.g., MIT, Oxford University)") - ], - include: Annotated[ - Optional[str], - Query( - description=( - "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, " - "last_known_institutions, ..." - ), - example="topics_full,topic_share", - ), - ], -): - return persons_logic.search_persons_by_institution(institution_name, include=include)