diff --git a/service/Dockerfile b/service/Dockerfile index c7207d73..403e56c1 100644 --- a/service/Dockerfile +++ b/service/Dockerfile @@ -14,7 +14,8 @@ RUN mkdir /test && \ "uvicorn~=0.29.0" \ "pytest~=8.1.0" \ "httpx~=0.27.0" \ - "python-multipart~=0.0.19" + "python-multipart~=0.0.19"\ + "elasticsearch~=9.4.0" COPY [ "src/main", "/home" ] COPY [ "src/data", "/data" ] diff --git a/service/src/main/inse/config.py b/service/src/main/inse/config.py index 3f1e92e9..330c1d4b 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -28,6 +28,7 @@ class Settings(BaseSettings): llm_api_token: str = 'c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212' llm_model: str = 'gemma4:e4b' elasticsearch_url: str = 'https://project.nes.uni-due.de/elastic/' + elasticsearch_instance: str = 'https://project.nes.uni-due.de/elastic' elasticsearch_api_key: str = 'am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==' settings = Settings() diff --git a/service/src/main/inse/logic.py b/service/src/main/inse/logic.py index e93966f6..69cfe1ef 100644 --- a/service/src/main/inse/logic.py +++ b/service/src/main/inse/logic.py @@ -14,14 +14,19 @@ from sqlalchemy import delete from sqlalchemy import insert from sqlalchemy import update from sqlalchemy import func +from fastapi import HTTPException import logging import httpx import json +import time +from elasticsearch import Elasticsearch, helpers, NotFoundError, ApiError from . import schema from . import model from . import config from .integrations import elasticsearch from .integrations import llm +from . import util + from inse.models.author import Author from inse.models.authors_list_response import AuthorsListResponse @@ -35,6 +40,10 @@ from inse.models.topic_domain import TopicDomain logger = logging.getLogger(__name__) topic_cache_filename: str = "topic_hierarchy_cache.json" +es_client = Elasticsearch( + hosts=[config.settings.elasticsearch_url], + api_key=config.settings.elasticsearch_api_key, +) S = TypeVar('S', bound=schema.Base) M = TypeVar('M', bound=model.BaseModel) @@ -252,7 +261,8 @@ def search_persons(author_id: Optional[str] = None, query: Optional[str] = None, return AuthorsListResponse(results=authors, meta=Meta(count=len(authors))) -def generate_person_bio(author_id: str) -> str: +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." @@ -260,12 +270,163 @@ def generate_person_bio(author_id: str) -> str: return "Multiple persons found, cannot generate bio." person = search_result.results[0] - person_json = json.dumps(person.model_dump()) + 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.\ + """ - system_prompt = "Erstelle eine Beschreibung der Person in 3-5 Sätzen. Gebe nur die Beschreibung zurück, ohne Einleitung oder Schluss." user_prompt = f"Daten zur Person:\n{person_json}" - return llm.call(system_prompt=system_prompt, user_prompt=user_prompt) + headers = { + "Authorization": f"Bearer {config.settings.llm_api_token}", + "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 = es_client.get( + index="openalex-authors", + id=author_id, + source=include.split(",") if include else True, + ) + 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 = es_client.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 + } + } + } + } + print (include,institution_name) + try: + response = es_client.search( + index="openalex-authors", + source=include.split(",") if include else True, + query=search_query, + 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) \ No newline at end of file diff --git a/service/src/main/inse/service.py b/service/src/main/inse/service.py index 96225866..73c0fc65 100644 --- a/service/src/main/inse/service.py +++ b/service/src/main/inse/service.py @@ -155,6 +155,7 @@ def count_topic_hierarchy( ### persons + @app.get('/persons/search', operation_id='searchPersons', response_model=AuthorsListResponse, @@ -179,6 +180,67 @@ def search_persons(author_id: Annotated[str, Query(description="OpenAlex author 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)")]): - bio = logic.generate_person_bio(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) + +@app.get('/persons/id', + operation_id='getPersonByID', + response_model=AuthorsListResponse, + summary='Searches for person by ID.', + tags=[ 'Persons' ] +) +def get_person_by_id( + author_id: Annotated[str, Query(description="OpenAlex author ID (e.g., 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=author_id,include=include) + +@app.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 logic.search_persons_by_name(author_name=author_name,include=include) + +@app.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 logic.search_persons_by_institution(institution_name,include=include) diff --git a/service/src/main/inse/test_service.py b/service/src/main/inse/test_service.py index f04314e9..30c00152 100644 --- a/service/src/main/inse/test_service.py +++ b/service/src/main/inse/test_service.py @@ -1,9 +1,111 @@ from fastapi.testclient import TestClient +from fastapi import HTTPException from inse.main import app - +from . import model +from unittest.mock import patch client = TestClient(app) - +URL_SERVICE_PREFIX="/inse-service" def test_redirect_root(): response = client.get("/", follow_redirects=False) assert response.status_code == 307 + + + +# def test_get_person_by_id_success(): + +# mock_person = model.Person( +# id="A5093075883", +# name="Arman Arzani", +# works_count=6, +# cited_by_count=4, +# affiliations=[], +# topics=[] +# ) + +# with patch("inse.logic.get_person_by_id", return_value=mock_person): + +# response = client.get( +# URL_SERVICE_PREFIX + "/persons/id", +# params={"author_id": "A5093075883"} +# ) + +# assert response.status_code == 200 + +# data = response.json() + +# assert data["id"] == "A5093075883" +# assert data["name"] == "Arman Arzani" +# assert data["works_count"] == 6 +# assert data["cited_by_count"] == 4 + +# def test_get_person_by_id_not_found(): +# invalid_id = "INVALID" +# with patch( +# "inse.logic.get_person_by_id", +# side_effect=HTTPException( +# status_code=404, +# detail="Person with id INVALID not found" +# ) +# ): + +# response = client.get( +# URL_SERVICE_PREFIX + "/persons/id", +# params={"author_id": invalid_id} +# ) +# assert response.status_code == 404 + +# def test_get_person_by_id_missing_query_param(): + +# response = client.get(URL_SERVICE_PREFIX + "/persons/id") + +# assert response.status_code == 422 + +# def test_search_persons_by_name_success(): + +# mock_result = model.PersonSearchResult( +# persons=[ +# model.Person( +# id="A5047117780", +# name="Pedro José Marrón", +# works_count=285, +# cited_by_count=2638, +# ) +# ] +# ) + +# with patch( +# "inse.logic.search_persons_by_name", +# return_value=mock_result +# ): + +# response = client.get( +# URL_SERVICE_PREFIX + "/persons/searchByName", +# params={"author_name": "Pedro José Marrón"} +# ) + +# assert response.status_code == 200 + +# data = response.json() + +# assert "persons" in data +# assert data["persons"][0]["name"] == "Pedro José Marrón" + +# def test_search_persons_by_name_empty_result(): + +# response = client.get( +# URL_SERVICE_PREFIX + "/persons/searchByName", +# params={"author_name": "zzzz_nonexistent_name_123"} +# ) + +# assert response.status_code == 200 + +# data = response.json() + +# assert data["persons"] == [] + +# def test_search_persons_by_name_missing_query_param(): + +# response = client.get(URL_SERVICE_PREFIX + "/persons/searchByName") + +# assert response.status_code == 422 \ No newline at end of file diff --git a/service/src/main/inse/util.py b/service/src/main/inse/util.py index 26d916f3..da4fc410 100644 --- a/service/src/main/inse/util.py +++ b/service/src/main/inse/util.py @@ -6,6 +6,8 @@ """ from typing import Optional from typing import TypeVar +from inse.models import Author +from . import model from fastapi import HTTPException from starlette.status import HTTP_404_NOT_FOUND @@ -16,4 +18,22 @@ def raise_not_found_if_none(value: Optional[T]) -> T: if value == None: raise HTTPException(HTTP_404_NOT_FOUND) else: - return value \ No newline at end of file + return value + +def get_persons_data(hit:dict): + source = hit.get("_source", {}) + source_copy = dict(source) + source_copy["id"] = hit.get("_id", "") or source_copy.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) + return author \ No newline at end of file diff --git a/webapp/src/app/api/api/persons.service.ts b/webapp/src/app/api/api/persons.service.ts index 92865f67..aa9747cb 100644 --- a/webapp/src/app/api/api/persons.service.ts +++ b/webapp/src/app/api/api/persons.service.ts @@ -46,13 +46,14 @@ export class PersonsOpenApiService extends BaseService implements PersonsOpenApi * Generates a bio for a person by author ID. * @endpoint get /persons/bio * @param authorId OpenAlex author ID (e.g., A5093075883) + * @param include Comma-separated list to include tags * @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 generatePersonBio(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public generatePersonBio(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public generatePersonBio(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public generatePersonBio(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + public generatePersonBio(authorId: string, include?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public generatePersonBio(authorId: string, include?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public generatePersonBio(authorId: string, include?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public generatePersonBio(authorId: string, include?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { if (authorId === null || authorId === undefined) { throw new Error('Required parameter authorId was null or undefined when calling generatePersonBio.'); } @@ -60,6 +61,8 @@ export class PersonsOpenApiService extends BaseService implements PersonsOpenApi let localVarQueryParameters = new HttpParams({encoder: this.encoder}); localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, authorId, 'author_id'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); let localVarHeaders = this.defaultHeaders; @@ -102,6 +105,72 @@ export class PersonsOpenApiService extends BaseService implements PersonsOpenApi ); } + /** + * Searches for person by ID. + * @endpoint get /persons/id + * @param authorId OpenAlex author ID (e.g., A5093075883) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @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 getPersonByID(authorId: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public getPersonByID(authorId: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPersonByID(authorId: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public getPersonByID(authorId: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorId === null || authorId === undefined) { + throw new Error('Required parameter authorId was null or undefined when calling getPersonByID.'); + } + if (include === null || include === undefined) { + throw new Error('Required parameter include was null or undefined when calling getPersonByID.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + authorId, 'author_id'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/persons/id`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + /** * Searches for persons by ID or name. * @endpoint get /persons/search @@ -165,4 +234,136 @@ export class PersonsOpenApiService extends BaseService implements PersonsOpenApi ); } + /** + * Searches for persons by institution name. + * @endpoint get /persons/searchByInstitution + * @param institutionName Institution name (e.g., MIT, Oxford University) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @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 searchPersonsByInstitution(institutionName: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchPersonsByInstitution(institutionName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsByInstitution(institutionName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsByInstitution(institutionName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (institutionName === null || institutionName === undefined) { + throw new Error('Required parameter institutionName was null or undefined when calling searchPersonsByInstitution.'); + } + if (include === null || include === undefined) { + throw new Error('Required parameter include was null or undefined when calling searchPersonsByInstitution.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + institutionName, 'institution_name'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/persons/searchByInstitution`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + + /** + * Searches for person by name. + * @endpoint get /persons/searchByName + * @param authorName Authors name (e.g., Arman Arzani) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + * @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 searchPersonsByName(authorName: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; + public searchPersonsByName(authorName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsByName(authorName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; + public searchPersonsByName(authorName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + if (authorName === null || authorName === undefined) { + throw new Error('Required parameter authorName was null or undefined when calling searchPersonsByName.'); + } + if (include === null || include === undefined) { + throw new Error('Required parameter include was null or undefined when calling searchPersonsByName.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + authorName, 'author_name'); + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + include, 'include'); + + let localVarHeaders = this.defaultHeaders; + + const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ + 'application/json' + ]); + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); + + const localVarTransferCache: boolean = options?.transferCache ?? true; + + + let responseType_: 'text' | 'json' | 'blob' = 'json'; + if (localVarHttpHeaderAcceptSelected) { + if (localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { + responseType_ = 'json'; + } else { + responseType_ = 'blob'; + } + } + + let localVarPath = `/persons/searchByName`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request('get', `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), + reportProgress: reportProgress + } + ); + } + } diff --git a/webapp/src/app/api/api/persons.serviceInterface.ts b/webapp/src/app/api/api/persons.serviceInterface.ts index 3a899295..67b9a127 100644 --- a/webapp/src/app/api/api/persons.serviceInterface.ts +++ b/webapp/src/app/api/api/persons.serviceInterface.ts @@ -29,8 +29,18 @@ export interface PersonsOpenApiServiceInterface { * * @endpoint get /persons/bio * @param authorId OpenAlex author ID (e.g., A5093075883) + * @param include Comma-separated list to include tags */ - generatePersonBio(authorId: string, extraHttpRequestParams?: any): Observable; + generatePersonBio(authorId: string, include?: string, extraHttpRequestParams?: any): Observable; + + /** + * Searches for person by ID. + * + * @endpoint get /persons/id + * @param authorId OpenAlex author ID (e.g., A5093075883) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + */ + getPersonByID(authorId: string, include: string, extraHttpRequestParams?: any): Observable; /** * Searches for persons by ID or name. @@ -42,4 +52,22 @@ export interface PersonsOpenApiServiceInterface { */ searchPersons(authorId?: string, query?: string, include?: string, extraHttpRequestParams?: any): Observable; + /** + * Searches for persons by institution name. + * + * @endpoint get /persons/searchByInstitution + * @param institutionName Institution name (e.g., MIT, Oxford University) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + */ + searchPersonsByInstitution(institutionName: string, include: string, extraHttpRequestParams?: any): Observable; + + /** + * Searches for person by name. + * + * @endpoint get /persons/searchByName + * @param authorName Authors name (e.g., Arman Arzani) + * @param include Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, ... + */ + searchPersonsByName(authorName: string, include: string, extraHttpRequestParams?: any): Observable; + } diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index a257d1fc..1c7661a2 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -18,7 +18,15 @@ export const routes: Routes = [ ), }, { - path: 'person/:id', + path: 'persons', + canActivate: [userGuard], + loadComponent: () => + import('./modules/person-list/person-list.component').then( + (mod) => mod.PersonListComponent, + ), + }, + { + path: 'persons/:id', canActivate: [userGuard], loadComponent: () => import('./modules/person/person.component').then( @@ -51,7 +59,7 @@ export const routes: Routes = [ (mod) => mod.PersonPublicationsComponent, ), }, - ], + ] }, { path: '**', diff --git a/webapp/src/app/modules/person-list/person-list.component.html b/webapp/src/app/modules/person-list/person-list.component.html new file mode 100644 index 00000000..0b3fdf33 --- /dev/null +++ b/webapp/src/app/modules/person-list/person-list.component.html @@ -0,0 +1,65 @@ +@let persons = state.persons(); +@let results = persons.results ?? []; +@if (!isPersonsLoading()) { + + +

{{ results.length }} Ergebnisse

+
+
+ + + + @for (person of results; track person.id) { + + + @if (person.id){ + + +
+ +
+ person +
+ +
+

{{ person.display_name }}

+

{{ getDistinguishingId(person) }}

+ @if (person.affiliations!=undefined){ +

+ {{ person.affiliations[0]?.institution?.display_name }} +

+ } + + +

+ Works: {{ person.works_count }} · + Citations: {{ person.cited_by_count }} +

+ +
+ @for (t of person.topics; track t) { + {{ t.display_name }} + } +
+ +
+ +
+ + +
+ } +
+ + } + +
+} @else { + + +
+ +
+
+
+} \ No newline at end of file diff --git a/webapp/src/app/modules/person-list/person-list.component.scss b/webapp/src/app/modules/person-list/person-list.component.scss new file mode 100644 index 00000000..10174b2e --- /dev/null +++ b/webapp/src/app/modules/person-list/person-list.component.scss @@ -0,0 +1,78 @@ +.result-count { + margin: 0 0 12px; + font-size: 14px; + color: #666; +} + +.person-card { + width: 100%; + height: 100%; + padding: 12px; + border-radius: 16px; +} + +.card-content { + display: flex; + align-items: center; + gap: 16px; + height: 100%; +} + +.avatar { + display: flex; + justify-content: center; + align-items: center; +} + +.avatar-icon { + font-size: 48px; + width: 48px; + height: 48px; + color: #9e9e9e; +} + +.info { + display: flex; + flex-direction: column; + gap: 4px; +} + +.name { + margin: 0; +} + +.person-id { + font-size: 11px; + color: #aaa; + margin: 0; +} + +.affiliation { + color: #666; + margin: 0; +} + +.stats { + font-size: 12px; + color: #888; +} + +.topics { + display: flex; + gap: 6px; + flex-wrap: wrap; +} + +.topic-chip { + font-size: 12px; +} +.loading { + display: flex; + justify-content: center; + align-items: center; + + width: 100%; + min-height: 300px; + + padding: 2rem; +} \ No newline at end of file diff --git a/webapp/src/app/modules/person-list/person-list.component.ts b/webapp/src/app/modules/person-list/person-list.component.ts new file mode 100644 index 00000000..bd63e6c1 --- /dev/null +++ b/webapp/src/app/modules/person-list/person-list.component.ts @@ -0,0 +1,121 @@ +import { Component, computed, inject, signal, DestroyRef } from '@angular/core'; +import { Router } from '@angular/router'; +import { toObservable } from '@angular/core/rxjs-interop'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { MatGridListModule } from '@angular/material/grid-list'; +import { MatCardModule } from '@angular/material/card'; +import { MatIconModule } from '@angular/material/icon'; +import { MatChipsModule } from '@angular/material/chips'; +import { MatProgressSpinner } from '@angular/material/progress-spinner'; +import { Author, AuthorsListResponse, PersonsOpenApiService } from '../../api'; +import { SharedStateService } from '../../shared/services/shared-state.service'; +import { distinctUntilChanged, switchMap, tap, finalize } from 'rxjs'; + +@Component({ + selector: 'app-person-list', + imports: [MatCardModule, MatChipsModule, MatGridListModule, MatIconModule, MatProgressSpinner], + templateUrl: './person-list.component.html', + styleUrl: './person-list.component.scss', +}) +export class PersonListComponent { + private router = inject(Router); + private personsService = inject(PersonsOpenApiService); + private destroyRef = inject(DestroyRef); + public state = inject(SharedStateService); + + private defaultIncludes = "display_name,works_count,cited_by_count,topics,orcid" + private defaultInstitutionName = 'University of Duisburg-Essen'; + + readonly isPersonsLoading = signal(false); + constructor() { + toObservable(this.state.searchValue) + .pipe( + distinctUntilChanged(), + tap(() => { + this.state.hasSearched.set(false); + this.isPersonsLoading.set(true); + }), + switchMap((value) => + value + ? this.personsService.searchPersonsByName(value,this.defaultIncludes).pipe( + tap((result) => { + this.state.persons.set(this.sortByRanking(result)); + this.state.hasSearched.set(true); + }) + ) + : this.personsService.searchPersonsByInstitution(this.defaultInstitutionName,this.defaultIncludes).pipe( + tap((result) => { + this.state.persons.set(this.sortByRanking(result)); + }) + ) + ), + finalize(() => this.isPersonsLoading.set(false)), + takeUntilDestroyed(this.destroyRef) + ) + .subscribe({ + next: () => this.isPersonsLoading.set(false), + error: (err) => { + console.error('Error loading persons:', err); + this.isPersonsLoading.set(false); + }, + }); + } + + // navigation + navigateID(id: string): void { + this.router.navigate(['/persons', id]); + } + + // sorting logic + sortByRanking(response: AuthorsListResponse): AuthorsListResponse { + if (!response.results) return response; + + return { + ...response, + results: [...response.results].sort((personA, personB) => { + const rankDiff = this.getSortRank(personA) - this.getSortRank(personB); + if (rankDiff !== 0) { + return rankDiff; + } + return this.getWorksCount(personB) - this.getWorksCount(personA); + }), + }; + } + + getWorksCount(person: Author): number { + return person.works_count ?? 0; + } + + getSortRank(person: Author): number { + if (this.hasInstitution(person) && this.hasOrcid(person)) return 0; + if (this.hasInstitution(person)) return 1; + if (this.hasOrcid(person)) return 2; + return 3; + } + + hasInstitution(person: Author): boolean { + if (!person.affiliations) { + return false; + } + for (const affiliation of person.affiliations) { + if (affiliation.institution) { + return true; + } + } + return false; + } + + hasOrcid(person: Author): boolean { + const ids = person.ids as { orcid?: string } | null | undefined; + return !!ids?.orcid; + } + + getDistinguishingId(person: Author): string { + const ids = person.ids as { orcid?: string } | null | undefined; + const orcid = ids?.orcid; + + return orcid + ? 'ORCID: ' + orcid.replace('https://orcid.org/', '') + : 'OpenAlexID: ' + person.id; + } +} \ No newline at end of file diff --git a/webapp/src/app/modules/person-overview/person-overview.component.html b/webapp/src/app/modules/person-overview/person-overview.component.html index bc281a0c..938179bf 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.html +++ b/webapp/src/app/modules/person-overview/person-overview.component.html @@ -1 +1 @@ -

person-overview works!

+Dummy \ No newline at end of file diff --git a/webapp/src/app/modules/person-overview/person-overview.component.ts b/webapp/src/app/modules/person-overview/person-overview.component.ts index 37c8461e..a7f7ae5d 100644 --- a/webapp/src/app/modules/person-overview/person-overview.component.ts +++ b/webapp/src/app/modules/person-overview/person-overview.component.ts @@ -1,5 +1,5 @@ import { Component } from '@angular/core'; - +import { MatProgressSpinner } from '@angular/material/progress-spinner'; @Component({ selector: 'app-person-overview', imports: [], diff --git a/webapp/src/app/modules/person/person.component.html b/webapp/src/app/modules/person/person.component.html index 310a0fe8..04a4c7a9 100644 --- a/webapp/src/app/modules/person/person.component.html +++ b/webapp/src/app/modules/person/person.component.html @@ -1,3 +1,6 @@ +@if (isPersonLoading()){ + +
{{ initials() }}
@@ -8,26 +11,26 @@

{{ institution() }}

@if (countryCode()) { - {{ countryCode() }} + {{ countryCode() }} } @if (worksCount() !== null || citedByCount() !== null) { - - @if (worksCount() !== null) { - {{ worksCount() }} Publikationen - } - @if (worksCount() !== null && citedByCount() !== null) { - · - } - @if (citedByCount() !== null) { - {{ citedByCount() }} Zitationen - } - + + @if (worksCount() !== null) { + {{ worksCount() }} Publikationen + } + @if (worksCount() !== null && citedByCount() !== null) { + · + } + @if (citedByCount() !== null) { + {{ citedByCount() }} Zitationen + } + }
mail - anna.becker@uni-due.de + uni-email@uni-due.de
@if (openAlexId()) { @@ -38,10 +41,10 @@ } @if (orcid()) { -
- verified - {{ orcid() }} -
+
+ verified + {{ orcid() }} +
}
language @@ -51,24 +54,31 @@
- +
- +} @else { +
+ +
+} - + \ No newline at end of file diff --git a/webapp/src/app/modules/person/person.component.scss b/webapp/src/app/modules/person/person.component.scss index 4192c28c..fe73494e 100644 --- a/webapp/src/app/modules/person/person.component.scss +++ b/webapp/src/app/modules/person/person.component.scss @@ -97,6 +97,54 @@ font-weight: 600; } +.sidebar { + display: flex; + flex-direction: column; + gap: 24px; +} + +.interest-card, +.bio-card { + padding: 24px 28px; + border-radius: var(--sg-radius-sm); + background: var(--sg-surface-muted); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.8); +} + +.interest-card h3, +.bio-card h3 { + margin: 0 0 18px; + font-size: 14px; + font-weight: 700; +} + +.bio-card p { + margin: 0; + color: var(--sg-text); + font-size: 14px; + line-height: 1.5; +} + +.bio-card mat-progress-bar { + margin: -24px -28px 18px -28px; + border-radius: var(--sg-radius-sm) var(--sg-radius-sm) 0 0; +} + +.interest-tags { + display: flex; + flex-wrap: wrap; + gap: 12px; +} + +.interest-tags span { + padding: 9px 16px; + border: 1px solid #a8c0ff; + border-radius: 7px; + background: #ffffff; + color: var(--sg-primary); + font-size: 13px; + font-weight: 600; +} .person-tabs { padding: 0 32px; @@ -139,6 +187,16 @@ .profile-contact { grid-column: 2; } + + .sidebar { + flex-direction: row; + gap: 20px; + } + + .interest-card, + .bio-card { + flex: 1; + } } @media (max-width: 720px) { diff --git a/webapp/src/app/modules/person/person.component.ts b/webapp/src/app/modules/person/person.component.ts index f69f429f..06674875 100644 --- a/webapp/src/app/modules/person/person.component.ts +++ b/webapp/src/app/modules/person/person.component.ts @@ -1,11 +1,13 @@ -import { Component, OnDestroy, OnInit, computed, inject, signal } from '@angular/core'; +import { Component, computed, inject, signal, DestroyRef } from '@angular/core'; import { toSignal, toObservable } from '@angular/core/rxjs-interop'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { MatIconModule } from '@angular/material/icon'; +import { MatProgressSpinner } from '@angular/material/progress-spinner'; import { MatTabsModule } from '@angular/material/tabs'; import { ActivatedRoute, RouterModule, RouterOutlet } from '@angular/router'; -import { Subscription, map, of, switchMap } from 'rxjs'; +import { of, switchMap, finalize, map, catchError } from 'rxjs'; -import { Author, PersonsOpenApiService, WorkTopic } from '../../api'; +import { Author, PersonsOpenApiService } from '../../api'; import { PersonInterestingComponent } from '../person-interesting/person-interesting.component'; const PERSON_INCLUDE_TAGS = @@ -20,31 +22,70 @@ const PERSON_INCLUDE_TAGS = PersonInterestingComponent, RouterOutlet, RouterModule, + MatProgressSpinner, ], templateUrl: './person.component.html', styleUrl: './person.component.scss', }) -export class PersonComponent implements OnInit, OnDestroy { +export class PersonComponent { private route = inject(ActivatedRoute); private readonly personsApi = inject(PersonsOpenApiService); - private routeSub?: Subscription; + private readonly destroyRef = inject(DestroyRef); - private readonly authorId = signal(null); + + // derive authorID directly from route + private readonly authorId = toSignal( + this.route.paramMap.pipe( + map((params) => params.get('id') ?? null), + takeUntilDestroyed(this.destroyRef) + ) + ); + + // loading states + readonly isPersonLoading = signal(false); + readonly isBioLoading = signal(false); readonly person = toSignal( toObservable(this.authorId).pipe( switchMap((id) => { - if (!id) { - return of(null); - } - - return this.personsApi.searchPersons(id, undefined, PERSON_INCLUDE_TAGS).pipe( + if (!id) return of(null); + this.isPersonLoading.set(true); + return this.personsApi.searchPersons(id, PERSON_INCLUDE_TAGS).pipe( map((result) => result.results?.[0] ?? null), + catchError((err) => { + console.error('Failed to load person:', err); + return of(null); + }), + finalize(() => this.isPersonLoading.set(false)) ); - }), + }) ), - { initialValue: null }, + { initialValue: null } ); + // bio data +readonly personBio = toSignal( + toObservable(this.authorId).pipe( + switchMap((id) => { + if (!id) { + this.isBioLoading.set(false); + return of(null); + } + this.isBioLoading.set(true); + return this.personsApi.generatePersonBio(id).pipe( + map((result) => { + this.isBioLoading.set(false); + return result.bio ?? null; + }), + catchError((err) => { + console.error('Failed to load bio:', err); + this.isBioLoading.set(false); + return of(null); + }) + ); + }) + ), + { initialValue: null } +); readonly displayName = computed( () => this.person()?.display_name ?? 'Unbekannte Person', ); @@ -70,7 +111,6 @@ export class PersonComponent implements OnInit, OnDestroy { readonly topicsFull = computed( () => this.person()?.topics ?? [], ); - links = [ { label: 'Übersicht', path: 'overview', disabled: false }, { label: 'Projekte', path: 'projects', disabled: true }, @@ -79,17 +119,6 @@ export class PersonComponent implements OnInit, OnDestroy { { label: 'Gründungen', path: 'foundings', disabled: true }, ]; - ngOnInit(): void { - this.routeSub = this.route.paramMap.subscribe((params) => { - const authorId = params.get('id') ?? ''; - this.authorId.set(authorId ? authorId : null); - }); - } - - ngOnDestroy(): void { - this.routeSub?.unsubscribe(); - } - private getId(key: string): string | null { const ids = this.person()?.ids as Record | undefined; if (!ids) { diff --git a/webapp/src/app/shared/services/shared-state.service.ts b/webapp/src/app/shared/services/shared-state.service.ts new file mode 100644 index 00000000..e03428ba --- /dev/null +++ b/webapp/src/app/shared/services/shared-state.service.ts @@ -0,0 +1,21 @@ +import { Injectable, signal } from '@angular/core'; +import { AuthorsListResponse } from '../../api'; +@Injectable({ providedIn: 'root' }) +export class SharedStateService { + + searchValue = signal(null); + persons = signal({ + meta: null, + results: [], + group_by: [] + }); + hasSearched = signal(false); + + destroyPersons(): void { + this.persons.set({ + meta: null, + results: [], + group_by: [] + }); + } +} \ No newline at end of file diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.html b/webapp/src/app/shared/ui/app-layout/app-layout.component.html index 8f21ec4a..b2fe1274 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.html +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.html @@ -29,7 +29,7 @@ menu } - @@ -38,8 +38,10 @@ diff --git a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts index 54911500..e246822d 100644 --- a/webapp/src/app/shared/ui/app-layout/app-layout.component.ts +++ b/webapp/src/app/shared/ui/app-layout/app-layout.component.ts @@ -4,15 +4,18 @@ import { MatToolbarModule } from '@angular/material/toolbar'; import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; import { MatDrawer, MatSidenavModule } from '@angular/material/sidenav'; -import { Router, RouterLink } from '@angular/router'; +import { Router} from '@angular/router'; import { MediaMatcher } from '@angular/cdk/layout'; import { AppMenuComponent } from '../app-menu/app-menu.component'; import { MatTooltipModule } from '@angular/material/tooltip'; import { CredentialService } from '../../services/credential.service'; +import { FormControl,ReactiveFormsModule } from '@angular/forms'; +import { SharedStateService } from '../../services/shared-state.service'; +import { Location } from '@angular/common'; @Component({ selector: 'app-layout', - imports: [CommonModule, MatToolbarModule, MatSidenavModule, MatButtonModule, MatIconModule, RouterLink, AppMenuComponent, MatTooltipModule], + imports: [CommonModule, MatToolbarModule, MatSidenavModule, MatButtonModule, MatIconModule, AppMenuComponent, MatTooltipModule,ReactiveFormsModule], templateUrl: './app-layout.component.html', styleUrl: './app-layout.component.scss', standalone: true, @@ -27,8 +30,10 @@ export class AppLayoutComponent implements OnInit, OnDestroy { mediaQueryListener: () => void; sideNavOpen = false; - + searchValue = new FormControl(''); constructor(public credentialService: CredentialService, public router: Router, + private location:Location, + private state: SharedStateService, public changeDetector: ChangeDetectorRef, media: MediaMatcher) { this.mediaQuery = media.matchMedia('(max-width: 600px)'); this.mediaQueryListener = () => { @@ -56,5 +61,15 @@ export class AppLayoutComponent implements OnInit, OnDestroy { this.credentialService.logoutAcount(); this.router.navigate(['/']) } + startSearch(){ + console.log("updated to", this.searchValue.value,this.router.url) + if (this.router.url.startsWith('/persons')) { + this.router.navigate(['/persons']); + } + this.state.searchValue.set(this.searchValue.value); + } + navigateBack(){ + this.location.back() + } } diff --git a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts index f74d3a11..70c0ba5e 100644 --- a/webapp/src/app/shared/ui/app-menu/app-menu.component.ts +++ b/webapp/src/app/shared/ui/app-menu/app-menu.component.ts @@ -21,7 +21,7 @@ import { CredentialService } from '../../services/credential.service'; export class AppMenuComponent { navItems = [ { label: 'Dashboard', icon: 'dashboard', route: '/items', disabled: false }, - { label: 'Personen', icon: 'groups', route: '/person/0', disabled: false }, + { label: 'Personen', icon: 'groups', route: '/persons', disabled: false }, ]; constructor(public credentialService: CredentialService) {}