Merged with dev + optimized persons data loading for persons dashboard
LocationBasedServices/smartguide/pipeline/head This commit looks good

This commit is contained in:
2026-05-31 22:56:20 +02:00
parent adbd741268
commit fc356401e4
10 changed files with 299 additions and 261 deletions
+20 -25
View File
@@ -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)
+34 -10
View File
@@ -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)
+15 -36
View File
@@ -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)
author = Author.from_dict(source_copy)
return author
+40 -19
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;
@@ -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<PersonSearchResult>;
public getPersonByID(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PersonSearchResult>>;
public getPersonByID(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PersonSearchResult>>;
public getPersonByID(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
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;
@@ -148,7 +157,7 @@ export class PersonsOpenApiService extends BaseService implements PersonsOpenApi
let localVarPath = `/persons/id`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<PersonSearchResult>('get', `${basePath}${localVarPath}`,
return this.httpClient.request<AuthorsListResponse>('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<PersonSearchResult>;
public searchPersonsByInstitution(institutionName: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PersonSearchResult>>;
public searchPersonsByInstitution(institutionName: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PersonSearchResult>>;
public searchPersonsByInstitution(institutionName: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
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;
@@ -271,7 +286,7 @@ export class PersonsOpenApiService extends BaseService implements PersonsOpenApi
let localVarPath = `/persons/searchByInstitution`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<PersonSearchResult>('get', `${basePath}${localVarPath}`,
return this.httpClient.request<AuthorsListResponse>('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<PersonSearchResult>;
public searchPersonsByName(authorName: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PersonSearchResult>>;
public searchPersonsByName(authorName: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PersonSearchResult>>;
public searchPersonsByName(authorName: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
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;
@@ -331,7 +352,7 @@ export class PersonsOpenApiService extends BaseService implements PersonsOpenApi
let localVarPath = `/persons/searchByName`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<PersonSearchResult>('get', `${basePath}${localVarPath}`,
return this.httpClient.request<AuthorsListResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
@@ -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<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, extraHttpRequestParams?: any): Observable<PersonSearchResult>;
getPersonByID(authorId: string, include: string, extraHttpRequestParams?: any): Observable<AuthorsListResponse>;
/**
* 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<PersonSearchResult>;
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, extraHttpRequestParams?: any): Observable<PersonSearchResult>;
searchPersonsByName(authorName: string, include: string, extraHttpRequestParams?: any): Observable<AuthorsListResponse>;
}
@@ -1,13 +1,18 @@
@if (!isPersonsLoading && state.persons().length > 0) {
<p class="result-count">{{ state.persons().length }} Ergebnisse</p>
}
@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">
@if (!isPersonsLoading){
@for (person of state.persons(); track person.id) {
@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">
@@ -17,11 +22,11 @@
</div>
<div class="info">
<h3 class="name">{{ person.name }}</h3>
<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 }}
{{ person.affiliations[0]?.institution?.display_name }}
</p>
}
@@ -33,7 +38,7 @@
<div class="topics">
@for (t of person.topics; track t) {
<mat-chip class="topic-chip">{{ t }}</mat-chip>
<mat-chip class="topic-chip">{{ t.display_name }}</mat-chip>
}
</div>
@@ -41,16 +46,20 @@
</div>
</mat-card>
</mat-card>
}
</mat-grid-tile>
}
} @else {
</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>
</mat-grid-list>
}
@@ -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<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);
},
});
}
sortByRanking(persons: Person[]): Person[] {
const personsByRank = new Map<number, Person[]>();
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;
}
}
}
@@ -1,4 +1,4 @@
@if (person(); as p){
@if (isPersonLoading()){
<section class="person-hero">
@@ -11,20 +11,20 @@
</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">
@@ -41,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>
@@ -52,32 +52,20 @@
ude.de/anna-becker
</a>
</div>
}
</div>
</div>
<aside class="sidebar">
<div class="bio-card">
<h3>Biografie</h3>
@if (isBioLoading) {
@if (isBioLoading()) {
<mat-progress-spinner mode="indeterminate"></mat-progress-spinner>
} @else {
} @else if (personBio()!=null) {
<p>{{ personBio() }}</p>
}
</div>
<div class="interest-card">
<h3>Interessant für</h3>
<div class="interest-tags">
@for (t of p.topics; track t) {
<mat-chip class="topic-chip">{{ t }}</mat-chip>
}
</div>
</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"
@@ -1,12 +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 =
@@ -21,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',
);
@@ -71,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 },
@@ -80,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) {
@@ -1,9 +1,21 @@
import { Injectable, signal } from '@angular/core';
import { Person } from '../../api';
import { AuthorsListResponse } from '../../api';
@Injectable({ providedIn: 'root' })
export class SharedStateService {
searchValue = signal<string | null>(null);
persons = signal<Person[]>([]);
persons = signal<AuthorsListResponse>({
meta: null,
results: [],
group_by: []
});
hasSearched = signal<boolean>(false);
destroyPersons(): void {
this.persons.set({
meta: null,
results: [],
group_by: []
});
}
}