ts-82-author-overview-and-description #103

Merged
tischer merged 25 commits from ts-82-author-overview-and-description into dev 2026-06-02 10:58:00 +02:00
21 changed files with 1062 additions and 79 deletions
+2 -1
View File
@@ -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" ]
+1
View File
@@ -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()
+165 -4
View File
@@ -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)
+64 -2
View File
@@ -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)
+104 -2
View File
@@ -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
+21 -1
View File
@@ -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
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
+205 -4
View File
@@ -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<PersonBio>;
public generatePersonBio(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PersonBio>>;
public generatePersonBio(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PersonBio>>;
public generatePersonBio(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
public generatePersonBio(authorId: string, include?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<PersonBio>;
public generatePersonBio(authorId: string, include?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PersonBio>>;
public generatePersonBio(authorId: string, include?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PersonBio>>;
public generatePersonBio(authorId: string, include?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
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,
<any>authorId, 'author_id');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>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<AuthorsListResponse>;
public getPersonByID(authorId: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AuthorsListResponse>>;
public getPersonByID(authorId: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AuthorsListResponse>>;
public getPersonByID(authorId: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
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,
<any>authorId, 'author_id');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>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<AuthorsListResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>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<AuthorsListResponse>;
public searchPersonsByInstitution(institutionName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AuthorsListResponse>>;
public searchPersonsByInstitution(institutionName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AuthorsListResponse>>;
public searchPersonsByInstitution(institutionName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
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,
<any>institutionName, 'institution_name');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>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<AuthorsListResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>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<AuthorsListResponse>;
public searchPersonsByName(authorName: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AuthorsListResponse>>;
public searchPersonsByName(authorName: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AuthorsListResponse>>;
public searchPersonsByName(authorName: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
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,
<any>authorName, 'author_name');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>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<AuthorsListResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
}
@@ -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<PersonBio>;
generatePersonBio(authorId: string, include?: string, extraHttpRequestParams?: any): Observable<PersonBio>;
/**
* 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<AuthorsListResponse>;
/**
* Searches for persons by ID or name.
@@ -42,4 +52,22 @@ export interface PersonsOpenApiServiceInterface {
*/
searchPersons(authorId?: string, query?: string, include?: string, extraHttpRequestParams?: any): Observable<AuthorsListResponse>;
/**
* 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<AuthorsListResponse>;
/**
* 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<AuthorsListResponse>;
}
+10 -2
View File
@@ -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: '**',
@@ -0,0 +1,65 @@
@let persons = state.persons();
@let results = persons.results ?? [];
@if (!isPersonsLoading()) {
<mat-grid-list cols="1" rowHeight="65px" gutterSize="16px">
<mat-grid-tile>
<p class="result-count">{{ results.length }} Ergebnisse</p>
</mat-grid-tile>
</mat-grid-list>
<mat-grid-list cols="1" rowHeight="220px" gutterSize="16px">
@for (person of results; track person.id) {
<mat-grid-tile>
@if (person.id){
<mat-card (click)="navigateID(person.id)" class="person-card">
<div class="card-content">
<div class="avatar">
<mat-icon class="avatar-icon">person</mat-icon>
</div>
<div class="info">
<h3 class="name">{{ person.display_name }}</h3>
<p class="person-id">{{ getDistinguishingId(person) }}</p>
@if (person.affiliations!=undefined){
<p class="affiliation">
{{ person.affiliations[0]?.institution?.display_name }}
</p>
}
<p class="stats">
Works: {{ person.works_count }} ·
Citations: {{ person.cited_by_count }}
</p>
<div class="topics">
@for (t of person.topics; track t) {
<mat-chip class="topic-chip">{{ t.display_name }}</mat-chip>
}
</div>
</div>
</div>
</mat-card>
}
</mat-grid-tile>
}
</mat-grid-list>
} @else {
<mat-grid-list cols="1" rowHeight="220px" gutterSize="16px">
<mat-grid-tile>
<div class="loading">
<mat-spinner diameter="40"></mat-spinner>
</div>
</mat-grid-tile>
</mat-grid-list>
}
@@ -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;
}
@@ -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<boolean>(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;
}
}
@@ -1 +1 @@
<p>person-overview works!</p>
Dummy
@@ -1,5 +1,5 @@
import { Component } from '@angular/core';
import { MatProgressSpinner } from '@angular/material/progress-spinner';
@Component({
selector: 'app-person-overview',
imports: [],
@@ -1,3 +1,6 @@
@if (isPersonLoading()){
<section class="person-hero">
<div class="profile-card">
<div class="profile-avatar">{{ initials() }}</div>
@@ -8,26 +11,26 @@
</div>
<p>{{ institution() }}</p>
@if (countryCode()) {
<span>{{ countryCode() }}</span>
<span>{{ countryCode() }}</span>
}
@if (worksCount() !== null || citedByCount() !== null) {
<span>
@if (worksCount() !== null) {
{{ worksCount() }} Publikationen
}
@if (worksCount() !== null && citedByCount() !== null) {
·
}
@if (citedByCount() !== null) {
{{ citedByCount() }} Zitationen
}
</span>
<span>
@if (worksCount() !== null) {
{{ worksCount() }} Publikationen
}
@if (worksCount() !== null && citedByCount() !== null) {
·
}
@if (citedByCount() !== null) {
{{ citedByCount() }} Zitationen
}
</span>
}
</div>
<div class="profile-contact">
<div>
<mat-icon>mail</mat-icon>
<span>anna.becker@uni-due.de</span>
<span>uni-email@uni-due.de</span>
</div>
<!-->
@if (openAlexId()) {
@@ -38,10 +41,10 @@
}
<!-->
@if (orcid()) {
<div>
<mat-icon class="orcid">verified</mat-icon>
<a [href]="orcidUrl()" target="_blank" rel="noopener">{{ orcid() }}</a>
</div>
<div>
<mat-icon class="orcid">verified</mat-icon>
<a [href]="orcidUrl()" target="_blank" rel="noopener">{{ orcid() }}</a>
</div>
}
<div>
<mat-icon>language</mat-icon>
@@ -51,24 +54,31 @@
</div>
</div>
</div>
<aside class="sidebar">
<div class="bio-card">
<h3>Biografie</h3>
@if (isBioLoading()) {
<mat-progress-spinner mode="indeterminate"></mat-progress-spinner>
} @else if (personBio()!=null) {
<p>{{ personBio() }}</p>
}
</div>
</aside>
<app-person-interesting [topics]="topicsFull()"></app-person-interesting>
</section>
<nav class="person-tabs" mat-tab-nav-bar [tabPanel]="tabPanel">
@for (link of links; track link.path) {
<a
mat-tab-link
[routerLink]="link.path"
routerLinkActive
#rla="routerLinkActive"
[active]="rla.isActive"
[disabled]="link.disabled"
>
{{ link.label }}
</a>
<a mat-tab-link [routerLink]="link.path" routerLinkActive #rla="routerLinkActive" [active]="rla.isActive"
[disabled]="link.disabled">
{{ link.label }}
</a>
}
</nav>
} @else {
<div class="loading">
<mat-progress-spinner diameter="40"></mat-progress-spinner>
</div>
}
<mat-tab-nav-panel #tabPanel class="person-panel">
<router-outlet></router-outlet>
</mat-tab-nav-panel>
</mat-tab-nav-panel>
@@ -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) {
@@ -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<string | null>(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<string, string> | undefined;
if (!ids) {
@@ -0,0 +1,21 @@
import { Injectable, signal } from '@angular/core';
import { AuthorsListResponse } from '../../api';
@Injectable({ providedIn: 'root' })
export class SharedStateService {
searchValue = signal<string | null>(null);
persons = signal<AuthorsListResponse>({
meta: null,
results: [],
group_by: []
});
hasSearched = signal<boolean>(false);
destroyPersons(): void {
this.persons.set({
meta: null,
results: [],
group_by: []
});
}
}
@@ -29,7 +29,7 @@
<mat-icon>menu</mat-icon>
</button>
}
<button class="back-link" type="button">
<button (click)="navigateBack()"class="back-link" type="button">
<mat-icon>arrow_back</mat-icon>
<span>Zurück zur Suche</span>
</button>
@@ -38,8 +38,10 @@
<label class="search-box">
<mat-icon>search</mat-icon>
<input
[formControl]="searchValue"
type="search"
placeholder="Suchen nach Personen, Themen, Projekten..."
(keyup.enter)="startSearch()"
/>
</label>
@@ -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()
}
}
@@ -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) {}