From 78e6b371e5e9615bf13e72feba40674b8df437fd Mon Sep 17 00:00:00 2001 From: genja Date: Wed, 27 May 2026 18:40:38 +0200 Subject: [PATCH 01/19] added get_person_by_id and search_person_by_name endpoints + pytests --- service/Dockerfile | 3 +- service/src/main/inse/config.py | 1 + service/src/main/inse/logic.py | 126 ++++++++++++++++++++++++++ service/src/main/inse/service.py | 17 ++++ service/src/main/inse/test_service.py | 106 +++++++++++++++++++++- 5 files changed, 250 insertions(+), 3 deletions(-) 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 c5255a5d..ffc4694f 100644 --- a/service/src/main/inse/config.py +++ b/service/src/main/inse/config.py @@ -23,6 +23,7 @@ class Settings(BaseSettings): llm_api_token: str = 'c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212' llm_model: str = 'gemma4:e4b' elasticsearch_url: str = 'https://project.nes.uni-due.de/elastic/openalex-authors/_search' + 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 e7e9c7b6..ae73af7b 100644 --- a/service/src/main/inse/logic.py +++ b/service/src/main/inse/logic.py @@ -14,15 +14,21 @@ 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 +from elasticsearch import Elasticsearch, helpers, NotFoundError, ApiError from . import schema from . import model from . import config logger = logging.getLogger(__name__) +es_client = Elasticsearch( + hosts=[config.settings.elasticsearch_instance], + api_key=config.settings.elasticsearch_api_key, +) S = TypeVar('S', bound=schema.Base) M = TypeVar('M', bound=model.BaseModel) @@ -141,3 +147,123 @@ def generate_person_bio(author_id: str) -> str: response.raise_for_status() data = response.json() return data.get("response", "") + + +def get_person_by_id(author_id: str) -> model.Person: + try: + hit = es_client.get( + index="openalex-authors", + 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)}" + ) + + source = hit.get("_source", {}) or {} + + affiliations = [ + model.Affiliation( + institution=aff.get("institution", {}).get("display_name", ""), + country_code=aff.get("institution", {}).get("country_code", "") + ) + for aff in source.get("affiliations") or [] + ] + + topics = [ + t.get("display_name", "") + for t in source.get("topics") or [] + ] + + return model.Person( + id=author_id, + name=source.get("display_name", ""), + works_count=source.get("works_count", 0), + cited_by_count=source.get("cited_by_count", 0), + affiliations=affiliations, + topics=topics + ) + +def search_persons_by_name(author_name: str, limit: Optional[int] = 10) -> model.PersonSearchResult: + 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": { + "display_name": { + "query": author_name, + "fuzziness": 1 + } + } + } + ], + "minimum_should_match": 1 + } + } + try: + response = es_client.search( + index="openalex-authors", + query=search_query, + 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 = [] + + for hit in hits: + source = hit.get("_source", {}) or {} + + affiliations = [ + model.Affiliation( + institution=aff.get("institution", {}).get("display_name", ""), + country_code=aff.get("institution", {}).get("country_code", "") + ) + for aff in source.get("affiliations") or [] + ] + + topics = [ + t.get("display_name", "") + for t in source.get("topics") or [] + ] + + persons.append( + model.Person( + id=hit.get("_id", ""), + name=source.get("display_name", ""), + works_count=source.get("works_count", 0), + cited_by_count=source.get("cited_by_count", 0), + affiliations=affiliations, + topics=topics + ) + ) + + return model.PersonSearchResult(persons=persons) \ No newline at end of file diff --git a/service/src/main/inse/service.py b/service/src/main/inse/service.py index dca6915e..9fae7e7b 100644 --- a/service/src/main/inse/service.py +++ b/service/src/main/inse/service.py @@ -113,6 +113,23 @@ def delete_item(id: Annotated[int, Path(description='The item id.', ge=0)], finally: db.commit() +@app.get('/persons/id', + operation_id='getPersonByID', + response_model=model.Person, + 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)")]): + return logic.get_person_by_id(author_id) + +@app.get('/persons/searchByName', + operation_id='searchPersonsByName', + response_model=model.PersonSearchResult, + 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)")]): + return logic.search_persons_by_name(author_name) + + @app.get('/persons/search', operation_id='searchPersons', response_model=model.PersonSearchResult, diff --git a/service/src/main/inse/test_service.py b/service/src/main/inse/test_service.py index f04314e9..1df8ff10 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 -- 2.56.1 From 45e02a72b429ee1f729a60fe5160ca43a78dc8ce Mon Sep 17 00:00:00 2001 From: Steven Tischer Date: Thu, 28 May 2026 14:23:08 +0200 Subject: [PATCH 02/19] feat(frontend): add static llm generated bio to profile --- .../app/modules/person/person.component.html | 27 +++++++++----- .../app/modules/person/person.component.scss | 35 +++++++++++++++++-- .../app/modules/person/person.component.ts | 30 ++++++++++++++-- 3 files changed, 78 insertions(+), 14 deletions(-) diff --git a/webapp/src/app/modules/person/person.component.html b/webapp/src/app/modules/person/person.component.html index a937e2a5..1325b376 100644 --- a/webapp/src/app/modules/person/person.component.html +++ b/webapp/src/app/modules/person/person.component.html @@ -26,14 +26,25 @@ - diff --git a/webapp/src/app/modules/person/person.component.ts b/webapp/src/app/modules/person/person.component.ts index a7edeb6d..cabf8b05 100644 --- a/webapp/src/app/modules/person/person.component.ts +++ b/webapp/src/app/modules/person/person.component.ts @@ -6,10 +6,11 @@ import { MatProgressSpinner } from '@angular/material/progress-spinner'; import { MatTabsModule } from '@angular/material/tabs'; import { RouterModule, RouterOutlet, ActivatedRoute } from '@angular/router'; import { Person, PersonsOpenApiService } from '../../api'; +import { MatChip } from '@angular/material/chips'; @Component({ selector: 'app-person', - imports: [MatIconModule, MatTabsModule, RouterOutlet, RouterModule, MatProgressSpinner], + imports: [MatIconModule, MatTabsModule, RouterOutlet, RouterModule, MatProgressSpinner,MatChip], templateUrl: './person.component.html', styleUrl: './person.component.scss', }) -- 2.56.1 From fc356401e4d8d0b0555bb40ca0c89f76f67ca5e4 Mon Sep 17 00:00:00 2001 From: genja Date: Sun, 31 May 2026 22:56:20 +0200 Subject: [PATCH 17/19] Merged with dev + optimized persons data loading for persons dashboard --- service/src/main/inse/logic.py | 45 +++-- service/src/main/inse/service.py | 44 +++-- service/src/main/inse/util.py | 51 ++---- webapp/src/app/api/api/persons.service.ts | 59 ++++-- .../app/api/api/persons.serviceInterface.ts | 12 +- .../person-list/person-list.component.html | 37 ++-- .../person-list/person-list.component.ts | 168 ++++++++---------- .../app/modules/person/person.component.html | 50 ++---- .../app/modules/person/person.component.ts | 78 +++++--- .../shared/services/shared-state.service.ts | 16 +- 10 files changed, 299 insertions(+), 261 deletions(-) diff --git a/service/src/main/inse/logic.py b/service/src/main/inse/logic.py index 07c83da1..69cfe1ef 100644 --- a/service/src/main/inse/logic.py +++ b/service/src/main/inse/logic.py @@ -263,14 +263,14 @@ def search_persons(author_id: Optional[str] = None, query: Optional[str] = None, 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, include=include) - if not search_result.persons: + 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()) + 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. @@ -308,11 +308,12 @@ def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> s return bio -def get_person_by_id(author_id: str) -> model.Person: +def get_person_by_id(author_id: str, include: Optional[str] = None) -> AuthorsListResponse: try: hit = es_client.get( index="openalex-authors", - id=author_id + id=author_id, + source=include.split(",") if include else True, ) except NotFoundError: @@ -328,9 +329,9 @@ def get_person_by_id(author_id: str) -> model.Person: ) persons = [util.get_persons_data(hit)] - return model.PersonSearchResult(persons=persons) + return AuthorsListResponse(results=persons) -def search_persons_by_name(author_name: str, limit: Optional[int] = 10) -> model.PersonSearchResult: +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, @@ -372,6 +373,7 @@ def search_persons_by_name(author_name: str, limit: Optional[int] = 10) -> model response = es_client.search( index="openalex-authors", query=search_query, + source=include.split(",") if include else True, size=limit ) @@ -385,12 +387,13 @@ def search_persons_by_name(author_name: str, limit: Optional[int] = 10) -> model persons = [util.get_persons_data(hit) for hit in hits] - return model.PersonSearchResult(persons=persons) + return AuthorsListResponse(results=persons) def search_persons_by_institution( institution_name: str, - limit: Optional[int] = 10 -) -> model.PersonSearchResult: + limit: Optional[int] = 10, + include: Optional[str] = None +) -> AuthorsListResponse: if not institution_name: raise HTTPException( @@ -399,29 +402,23 @@ def search_persons_by_institution( ) search_query = { - "nested": { + "nested": { "path": "affiliations", "query": { "match_phrase": { - "affiliations.institution.display_name":institution_name + "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" - } - } - ] + sort=[{"works_count": {"order": "desc"}}] ) except Exception as e: @@ -431,7 +428,5 @@ def search_persons_by_institution( ) hits = response.get("hits", {}).get("hits", []) - persons = [util.get_persons_data(hit) for hit in hits] - - return model.PersonSearchResult(persons=persons) + 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 980d4809..73c0fc65 100644 --- a/service/src/main/inse/service.py +++ b/service/src/main/inse/service.py @@ -193,23 +193,40 @@ def generate_person_bio(author_id: Annotated[str, Query(description="OpenAlex au @app.get('/persons/id', operation_id='getPersonByID', - response_model=model.PersonSearchResult, + 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)")]): - return logic.get_person_by_id(author_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=model.PersonSearchResult, + 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)")]): - return logic.search_persons_by_name(author_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) @app.get('/persons/searchByInstitution', operation_id='searchPersonsByInstitution', - response_model=model.PersonSearchResult, + response_model=AuthorsListResponse, summary='Searches for persons by institution name.', tags=['Persons'] ) @@ -217,6 +234,13 @@ 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) + return logic.search_persons_by_institution(institution_name,include=include) diff --git a/service/src/main/inse/util.py b/service/src/main/inse/util.py index e0a03c96..da4fc410 100644 --- a/service/src/main/inse/util.py +++ b/service/src/main/inse/util.py @@ -6,6 +6,7 @@ """ 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 @@ -20,41 +21,19 @@ def raise_not_found_if_none(value: Optional[T]) -> T: return value def get_persons_data(hit:dict): - source = hit.get("_source", {}) or {} + source = hit.get("_source", {}) + source_copy = dict(source) + source_copy["id"] = hit.get("_id", "") or source_copy.get("id") - affiliations = [ - model.Affiliation( - institution=aff.get("institution", {}).get("display_name", ""), - country_code=aff.get("institution", {}).get("country_code", "") - ) - for aff in source.get("affiliations") or [] - ] + # 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 - topics = [ - t.get("display_name", "") - for t in source.get("topics") or [] - ] - - person_data = { - "id": hit.get("_id", ""), - "name": source.get("display_name", ""), - "works_count": source.get("works_count", 0), - "cited_by_count": source.get("cited_by_count", 0), - "affiliations": affiliations, - "topics": topics - } - - person_data["topics_full"] = source.get("topics", []) - person_data["topic_share"] = source.get("topic_share", []) - person_data["summary_stats"] = source.get("summary_stats") - person_data["ids"] = source.get("ids") - person_data["last_known_institutions"] = source.get("last_known_institutions", []) - person_data["sources"] = source.get("sources", []) - person_data["counts_by_year"] = source.get("counts_by_year", []) - person_data["works_api_url"] = source.get("works_api_url") - person_data["dates"] = { - "created_date": source.get("created_date"), - "updated_date": source.get("updated_date") - } - person_data["cited_by_count_boost"] = source.get("cited_by_count_boost") - return model.Person(**person_data) \ No newline at end of file + 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 d58428ee..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; @@ -106,20 +109,26 @@ 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, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public getPersonByID(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getPersonByID(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public getPersonByID(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + 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; @@ -148,7 +157,7 @@ export class PersonsOpenApiService extends BaseService implements PersonsOpenApi let localVarPath = `/persons/id`; const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, + return this.httpClient.request('get', `${basePath}${localVarPath}`, { context: localVarHttpContext, params: localVarQueryParameters, @@ -229,20 +238,26 @@ 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, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsByInstitution(institutionName: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByInstitution(institutionName: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByInstitution(institutionName: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + 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; @@ -271,7 +286,7 @@ export class PersonsOpenApiService extends BaseService implements PersonsOpenApi let localVarPath = `/persons/searchByInstitution`; const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, + return this.httpClient.request('get', `${basePath}${localVarPath}`, { context: localVarHttpContext, params: localVarQueryParameters, @@ -289,20 +304,26 @@ export class PersonsOpenApiService extends BaseService implements PersonsOpenApi * 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, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable; - public searchPersonsByName(authorName: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByName(authorName: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable>; - public searchPersonsByName(authorName: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable { + 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; @@ -331,7 +352,7 @@ export class PersonsOpenApiService extends BaseService implements PersonsOpenApi let localVarPath = `/persons/searchByName`; const { basePath, withCredentials } = this.configuration; - return this.httpClient.request('get', `${basePath}${localVarPath}`, + return this.httpClient.request('get', `${basePath}${localVarPath}`, { context: localVarHttpContext, params: localVarQueryParameters, diff --git a/webapp/src/app/api/api/persons.serviceInterface.ts b/webapp/src/app/api/api/persons.serviceInterface.ts index 3e9acb7e..67b9a127 100644 --- a/webapp/src/app/api/api/persons.serviceInterface.ts +++ b/webapp/src/app/api/api/persons.serviceInterface.ts @@ -29,16 +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, extraHttpRequestParams?: any): Observable; + getPersonByID(authorId: string, include: string, extraHttpRequestParams?: any): Observable; /** * Searches for persons by ID or name. @@ -55,15 +57,17 @@ export interface PersonsOpenApiServiceInterface { * * @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, extraHttpRequestParams?: any): Observable; + 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, extraHttpRequestParams?: any): Observable; + searchPersonsByName(authorName: string, include: string, extraHttpRequestParams?: any): Observable; } diff --git a/webapp/src/app/modules/person-list/person-list.component.html b/webapp/src/app/modules/person-list/person-list.component.html index 820c062b..0b3fdf33 100644 --- a/webapp/src/app/modules/person-list/person-list.component.html +++ b/webapp/src/app/modules/person-list/person-list.component.html @@ -1,13 +1,18 @@ -@if (!isPersonsLoading && state.persons().length > 0) { -

{{ state.persons().length }} Ergebnisse

-} - +@let persons = state.persons(); +@let results = persons.results ?? []; +@if (!isPersonsLoading()) { + + +

{{ results.length }} Ergebnisse

+
+
- @if (!isPersonsLoading){ - @for (person of state.persons(); track person.id) { + + + @for (person of results; track person.id) { - + @if (person.id){
@@ -17,11 +22,11 @@
-

{{ person.name }}

+

{{ person.display_name }}

{{ getDistinguishingId(person) }}

@if (person.affiliations!=undefined){

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

} @@ -33,7 +38,7 @@
@for (t of person.topics; track t) { - {{ t }} + {{ t.display_name }} }
@@ -41,16 +46,20 @@
-
+ + }
} - } @else { + +
+} @else { +
- } -
\ No newline at end of file + +} \ 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 index 38469f7a..3321e61a 100644 --- a/webapp/src/app/modules/person-list/person-list.component.ts +++ b/webapp/src/app/modules/person-list/person-list.component.ts @@ -1,112 +1,91 @@ -import { Component, inject, signal, effect, OnInit } from '@angular/core'; +import { Component, computed, inject, signal, DestroyRef } from '@angular/core'; import { Router } from '@angular/router'; -import { tap } from 'rxjs'; -import { toSignal } from '@angular/core/rxjs-interop'; +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 { PersonSearchResult,Person, PersonsOpenApiService } from '../../api'; +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], + imports: [MatCardModule, MatChipsModule, MatGridListModule, MatIconModule, MatProgressSpinner], templateUrl: './person-list.component.html', styleUrl: './person-list.component.scss', }) -export class PersonListComponent implements OnInit{ - - constructor(private router:Router, private personsService:PersonsOpenApiService){ - effect(() => { - const value = this.state.searchValue(); - - if (value) { - this.loadPersonsByName(value); - } else{ - this.loadPersonsByInstitution("Duisburg-Essen") //default search - } - }); - } - ngOnInit(): void { - if (!this.state.hasSearched){ - this.loadPersonsByInstitution("Duisburg-Essen") //default search - }; - - } +export class PersonListComponent { + private router = inject(Router); + private personsService = inject(PersonsOpenApiService); + private destroyRef = inject(DestroyRef); public state = inject(SharedStateService); - isPersonsLoading = false; + private defaultIncludes = "display_name,works_count,cited_by_count,topics" + private defaultInstitutionName = 'University of Duisburg-Essen'; - loadPersonsByName(author_name: string): void { - this.isPersonsLoading = true - - this.personsService.searchPersonsByName(author_name).subscribe({ - next: (result) => { - this.state.persons.set(this.sortByRanking(result.persons ?? [])); - this.state.hasSearched.set(true); - this.isPersonsLoading = false - }, - error: (error) => { - console.error('Error loading person list:', error); - this.isPersonsLoading = false - } - }); - } - loadPersonsByInstitution(institution_name: string): void { - this.isPersonsLoading = true - - this.personsService.searchPersonsByInstitution(institution_name).subscribe({ - next: (result) => { - this.state.persons.set(result.persons ?? []); - this.isPersonsLoading = false - }, - error: (error) => { - console.error('Error loading person list:', error); - this.isPersonsLoading = false - } - }); - } - navigateID(id:string){ - console.log(id) - this.router.navigate(['/persons',id]); + 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); + }, + }); } - sortByRanking(persons: Person[]): Person[] { - const personsByRank = new Map(); - - for (const person of persons) { - const rank = this.getSortRank(person); - if (!personsByRank.has(rank)) { - personsByRank.set(rank, []); - } - personsByRank.get(rank)!.push(person); - } - - const sortedRanks = Array.from(personsByRank.keys()).sort((a, b) => a - b); - const sortedPersons: Person[] = []; - - for (const rank of sortedRanks) { - sortedPersons.push(...personsByRank.get(rank)!); - } - - return sortedPersons; + // navigation + navigateID(id: string): void { + this.router.navigate(['/persons', id]); } - getSortRank(person: Person): number { - if (this.hasInstitution(person) && this.hasOrcid(person)) { - return 0; - } - if (this.hasInstitution(person)) { - return 1; - } - if (this.hasOrcid(person)) { - return 2; - } + // sorting logic + sortByRanking(response: AuthorsListResponse): AuthorsListResponse { + if (!response.results) return response; + + return { + ...response, + results: [...response.results].sort( + (a, b) => this.getSortRank(a) - this.getSortRank(b) + ), + }; + } + + 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: Person): boolean { + hasInstitution(person: Author): boolean { if (!person.affiliations) { return false; } @@ -118,18 +97,17 @@ export class PersonListComponent implements OnInit{ return false; } - hasOrcid(person: Person): boolean { + hasOrcid(person: Author): boolean { const ids = person.ids as { orcid?: string } | null | undefined; return !!ids?.orcid; } - // if a person has an ORCID, use it as the distinguishing ID, otherwise use the regular ID - getDistinguishingId(person: Person): string { + getDistinguishingId(person: Author): string { const ids = person.ids as { orcid?: string } | null | undefined; const orcid = ids?.orcid; - if (orcid) { - return 'ORCID: ' + orcid.replace('https://orcid.org/', ''); - } - return 'OpenAlexID: ' + person.id; + + 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/person.component.html b/webapp/src/app/modules/person/person.component.html index f064c32a..04a4c7a9 100644 --- a/webapp/src/app/modules/person/person.component.html +++ b/webapp/src/app/modules/person/person.component.html @@ -1,4 +1,4 @@ -@if (person(); as p){ +@if (isPersonLoading()){
@@ -11,20 +11,20 @@

{{ 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 + } + }
@@ -41,10 +41,10 @@ } @if (orcid()) { -
- verified - {{ orcid() }} -
+
+ verified + {{ orcid() }} +
}
language @@ -52,32 +52,20 @@ ude.de/anna-becker
- } -
-
-