diff --git a/service/src/main/inse/auth/router.py b/service/src/main/inse/auth/router.py index 4bb2ab31..c23d69d0 100644 --- a/service/src/main/inse/auth/router.py +++ b/service/src/main/inse/auth/router.py @@ -61,6 +61,25 @@ async def request_password_reset( return auth_service.request_password_reset(session=session, email=email) +@router.post( + "/validate-password-reset-token", + summary="Validate Password Reset Token", + description="Validate a password reset token without consuming it.", + operation_id="validatePasswordResetToken", + responses={status.HTTP_200_OK: {"description": "Password reset token is valid."}}, +) +async def validate_password_reset_token( + session: SessionDep, + reset_token: Annotated[ + str, Body(embed=True, description="Password reset token from the reset link") + ], +) -> dict[str, bool]: + return auth_service.validate_password_reset_token( + session=session, + reset_token=reset_token, + ) + + @router.post( "/reset-password", summary="Reset Password", @@ -213,6 +232,7 @@ async def change_password( operation_id="canFetchGdprRelevantData", ) async def can_fetch_gdpr_relevant_data( + session: SessionDep, access_token: Annotated[ AccessTokenMetadata, auth_service.CurrentUserAccessTokenPayloadDep, @@ -227,6 +247,7 @@ async def can_fetch_gdpr_relevant_data( ] = None, ) -> bool: return await auth_service.can_fetch_gdpr_relevant_data( + session=session, access_token=access_token, raw_oa_author_id=raw_oa_author_id, raw_oa_institution_id=raw_oa_institution_id, diff --git a/service/src/main/inse/auth/service.py b/service/src/main/inse/auth/service.py index 1b271e67..8418b33f 100644 --- a/service/src/main/inse/auth/service.py +++ b/service/src/main/inse/auth/service.py @@ -442,24 +442,8 @@ def request_password_reset(session: Session, email: str) -> dict[str, Any]: } -def reset_password( - session: Session, - reset_token: str, - new_password: str, -) -> dict[str, str]: - """Resets an account password using a one-time password reset token. - - Args: - session (Session): The database session used to query the account and secret. - reset_token (str): The raw reset token from the password reset link. - new_password (str): The new password to store for the account. - - Raises: - HTTPException: If the reset token is invalid or expired. - - Returns: - Dict[str, str]: A status response. - """ +def _valid_password_reset_secret(session: Session, reset_token: str) -> Secret: + """Return the valid password-reset secret without consuming it.""" now = datetime.datetime.now(datetime.UTC) reset_token_hash = _hash_reset_token(reset_token.strip()) @@ -498,6 +482,47 @@ def reset_password( detail="Invalid or expired password reset token", ) + return secret + + +def validate_password_reset_token( + session: Session, + reset_token: str, +) -> dict[str, bool]: + """Validate a password-reset token without consuming it.""" + _valid_password_reset_secret(session, reset_token) + return {"valid": True} + + +def reset_password( + session: Session, + reset_token: str, + new_password: str, +) -> dict[str, str]: + """Resets an account password using a one-time password reset token. + + Args: + session (Session): The database session used to query the account and secret. + reset_token (str): The raw reset token from the password reset link. + new_password (str): The new password to store for the account. + + Raises: + HTTPException: If the reset token is invalid or expired. + + Returns: + Dict[str, str]: A status response. + """ + secret = _valid_password_reset_secret(session, reset_token) + account = session.get(Account, secret.account_id) + + # _valid_password_reset_secret already checked the account. Keep the guard + # for type narrowing and to avoid relying on an assertion in production. + if account is None: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid or expired password reset token", + ) + account.password_hash = _hash_password(new_password) account.epoch += 1 @@ -1467,6 +1492,7 @@ def change_password( async def can_fetch_gdpr_relevant_data( + session: Session, access_token: AccessTokenMetadata, raw_oa_author_id: str | None = None, raw_oa_institution_id: str | None = None, @@ -1493,40 +1519,71 @@ async def can_fetch_gdpr_relevant_data( logger.debug("No OpenAlex author ID or institution ID provided") return False - effective_institution_id = access_token.effective_institution_id - # Current user does not belong to any institution - if not effective_institution_id: + institution_ids = list( + session.exec( + select(OrganizationInstitution.openalex_institution_id) + .where( + OrganizationInstitution.organization_id + == access_token.effective_organization_id + ) + .order_by(OrganizationInstitution.position) + ).all() + ) + if not institution_ids and access_token.effective_institution_id: + institution_ids = [access_token.effective_institution_id] + + if not institution_ids: logger.debug( "Current user does not belong to any institution, cannot fetch GDPR-relevant data" ) return False - # Current user belongs to an institution, but the request is for a different institution + from inse.organization_management import service as organization_service + + association_groups = await organization_service.resolve_institution_associations( + institution_ids + ) + organization_institution_ids = set(institution_ids) + for group in association_groups: + organization_institution_ids.add(group.id.rstrip("/").split("/")[-1]) + organization_institution_ids.update( + association.id.rstrip("/").split("/")[-1] + for association in group.associated_institutions + ) + + requested_institution_id = ( + raw_oa_institution_id.rstrip("/").split("/")[-1] + if raw_oa_institution_id + else None + ) if ( - raw_oa_institution_id - and effective_institution_id - and raw_oa_institution_id != effective_institution_id + requested_institution_id + and requested_institution_id not in organization_institution_ids ): logger.debug( "Current user belongs to institution %s, but request is for institution %s, cannot fetch GDPR-relevant data", - effective_institution_id, - raw_oa_institution_id, + organization_institution_ids, + requested_institution_id, ) return False # Current user belongs to an institution, but request is for author not belonging to that institution if raw_oa_author_id: - author_belongs_to_institution = ( - await authors_service.author_currently_belongs_to_institution( - raw_oa_author_id or "", effective_institution_id - ) - ) + for institution_id in organization_institution_ids: + if await authors_service.author_currently_belongs_to_institution( + raw_oa_author_id, institution_id + ): + logger.debug( + "Author %s belongs to organization institution %s", + raw_oa_author_id, + institution_id, + ) + return True logger.debug( - "Author %s belongs to institution %s: %s", + "Author %s does not belong to any organization institution %s", raw_oa_author_id, - effective_institution_id, - author_belongs_to_institution, + organization_institution_ids, ) - return author_belongs_to_institution + return False return True diff --git a/service/src/main/inse/auth/test_auth_service.py b/service/src/main/inse/auth/test_auth_service.py index 1b5c92cb..db35c6ce 100644 --- a/service/src/main/inse/auth/test_auth_service.py +++ b/service/src/main/inse/auth/test_auth_service.py @@ -1,6 +1,7 @@ import datetime as _dt import uuid from datetime import timedelta +from unittest.mock import AsyncMock, patch import pytest from fastapi import HTTPException, Response @@ -14,11 +15,16 @@ from inse.auth.model import ( Account, IdTokenMetadata, Organization, + OrganizationInstitution, RefreshTokenMetadata, Secret, SecretPurpose, UserRole, ) +from inse.organization_management.model import ( + InstitutionAssociation, + InstitutionAssociationsResponse, +) @pytest.fixture() @@ -81,6 +87,74 @@ def test_hash_and_verify_password(): assert auth_service._verify_password("wrong", h) is False +@pytest.mark.anyio +async def test_gdpr_access_allows_every_organization_institution(in_memory_session): + org, account = create_org_and_account( + in_memory_session, "multi-institution@example.com", "pw" + ) + in_memory_session.add_all( + [ + OrganizationInstitution( + organization_id=org.id, + openalex_institution_id="I111", + position=0, + ), + OrganizationInstitution( + organization_id=org.id, + openalex_institution_id="I222", + position=1, + ), + ] + ) + in_memory_session.commit() + token = AccessTokenMetadata( + real_account_id=account.id, + expires_at=_dt.datetime.now(_dt.UTC) + timedelta(hours=1), + user_fingerprint_hash="fingerprint", + effective_account_id=account.id, + effective_organization_id=org.id, + effective_institution_id="I111", + ) + + associations = [ + InstitutionAssociationsResponse( + id="I111", + display_name="Root institution", + associated_institutions=[ + InstitutionAssociation( + id="I333", + display_name="Child institution", + relationship="child", + ) + ], + ), + InstitutionAssociationsResponse( + id="I222", + display_name="Second institution", + associated_institutions=[], + ), + ] + with patch( + "inse.organization_management.service.resolve_institution_associations", + new=AsyncMock(return_value=associations), + ): + assert await auth_service.can_fetch_gdpr_relevant_data( + session=in_memory_session, + access_token=token, + raw_oa_institution_id="https://openalex.org/I222", + ) + assert await auth_service.can_fetch_gdpr_relevant_data( + session=in_memory_session, + access_token=token, + raw_oa_institution_id="I333", + ) + assert not await auth_service.can_fetch_gdpr_relevant_data( + session=in_memory_session, + access_token=token, + raw_oa_institution_id="I444", + ) + + def test_request_otk_and_login_flow(in_memory_session, settings_backup): config_module.settings.token_hmac_key = "test-hmac-key" config_module.settings.token_issuer_id = "test-issuer" @@ -113,7 +187,9 @@ def test_request_otk_and_login_flow(in_memory_session, settings_backup): assert login_result.id_token.real_account_id == acc.id raw_id_token = _get_cookie_value(response, auth_service.ID_TOKEN_COOKIE_KEY) - payload = auth_service._verify_id_token(raw_id_token=raw_id_token, session=in_memory_session) + payload = auth_service._verify_id_token( + raw_id_token=raw_id_token, session=in_memory_session + ) assert payload[auth_service.REAL_ACCOUNT_ID_KEY] == str(acc.id) @@ -175,7 +251,9 @@ def test_access_and_refresh_token_flow(in_memory_session, settings_backup): ) assert isinstance(access_response.access_token, AccessTokenMetadata) - raw_refresh_token = _get_cookie_value(response, auth_service.REFRESH_TOKEN_COOKIE_KEY) + raw_refresh_token = _get_cookie_value( + response, auth_service.REFRESH_TOKEN_COOKIE_KEY + ) refresh_payload = auth_service._verify_refresh_token( raw_refresh_token=raw_refresh_token, session=in_memory_session, @@ -185,9 +263,7 @@ def test_access_and_refresh_token_flow(in_memory_session, settings_backup): effective_account_id=uuid.UUID( refresh_payload[auth_service.EFFECTIVE_ACCOUNT_ID_KEY] ), - expires_at=_dt.datetime.fromtimestamp( - refresh_payload["exp"], tz=_dt.UTC - ), + expires_at=_dt.datetime.fromtimestamp(refresh_payload["exp"], tz=_dt.UTC), epoch=refresh_payload[auth_service.EPOCH_KEY], effective_role=UserRole(refresh_payload[auth_service.EFFECTIVE_ROLE_KEY]), effective_organization_id=uuid.UUID( @@ -240,7 +316,9 @@ def test_access_and_refresh_token_preserve_multiple_roles( UserRole.USER.value, ] - raw_refresh_token = _get_cookie_value(response, auth_service.REFRESH_TOKEN_COOKIE_KEY) + raw_refresh_token = _get_cookie_value( + response, auth_service.REFRESH_TOKEN_COOKIE_KEY + ) refresh_payload = auth_service._verify_refresh_token( raw_refresh_token=raw_refresh_token, session=in_memory_session, @@ -634,7 +712,6 @@ def test_get_account_epoch_not_found(in_memory_session): auth_service._get_account_epoch(in_memory_session, random_id) - def test_request_password_reset_creates_secret(in_memory_session, settings_backup): email = "reset@example.com" password = "oldpw123" @@ -740,6 +817,68 @@ def test_reset_password_changes_password_and_increments_epoch(in_memory_session) assert deleted_secret is None +def test_validate_password_reset_token_does_not_consume_token(in_memory_session): + email = "validate-reset@example.com" + password = "oldpw123" + _, acc = create_org_and_account(in_memory_session, email, password) + assert acc.id is not None + + reset_token = "valid-token-to-check" + secret = Secret( + account_id=acc.id, + purpose=SecretPurpose.PASSWORD_RESET, + secret_value=auth_service._hash_reset_token(reset_token), + expires_at=_dt.datetime.now(_dt.UTC) + timedelta(minutes=5), + ) + in_memory_session.add(secret) + in_memory_session.commit() + + assert auth_service.validate_password_reset_token( + in_memory_session, reset_token + ) == {"valid": True} + + result = auth_service.reset_password( + in_memory_session, + reset_token=reset_token, + new_password="NewPassword123", + ) + assert result == {"status": "ok"} + + +def test_validate_password_reset_token_rejects_invalid_token(in_memory_session): + with pytest.raises(HTTPException) as exc_info: + auth_service.validate_password_reset_token( + in_memory_session, "invalid-token" + ) + + assert exc_info.value.status_code == 401 + + +def test_validate_password_reset_token_rejects_and_deletes_expired_token( + in_memory_session, +): + email = "validate-expired-reset@example.com" + password = "oldpw123" + _, acc = create_org_and_account(in_memory_session, email, password) + assert acc.id is not None + + reset_token = "expired-token-to-check" + secret = Secret( + account_id=acc.id, + purpose=SecretPurpose.PASSWORD_RESET, + secret_value=auth_service._hash_reset_token(reset_token), + expires_at=_dt.datetime.now(_dt.UTC) - timedelta(minutes=1), + ) + in_memory_session.add(secret) + in_memory_session.commit() + + with pytest.raises(HTTPException) as exc_info: + auth_service.validate_password_reset_token(in_memory_session, reset_token) + + assert exc_info.value.status_code == 401 + assert in_memory_session.get(Secret, secret.id) is None + + def test_reset_password_rejects_reused_token(in_memory_session): email = "reuse-reset@example.com" password = "oldpw123" diff --git a/service/src/main/inse/dashboard/model.py b/service/src/main/inse/dashboard/model.py index bbc047db..d4871d2b 100644 --- a/service/src/main/inse/dashboard/model.py +++ b/service/src/main/inse/dashboard/model.py @@ -1,6 +1,11 @@ from pydantic import BaseModel +class DashboardInstitution(BaseModel): + id: str + display_name: str + + class DashboardStatistics(BaseModel): institution_id: str organization_name: str diff --git a/service/src/main/inse/dashboard/project_statistics_service.py b/service/src/main/inse/dashboard/project_statistics_service.py index 10f68bde..86915d86 100644 --- a/service/src/main/inse/dashboard/project_statistics_service.py +++ b/service/src/main/inse/dashboard/project_statistics_service.py @@ -1,3 +1,5 @@ +import asyncio + from inse.institutions.institutions_search_client import InstitutionsSearchClient from inse.projects import service as projects_service from inse.projects.model import EuCordisProjectType @@ -10,21 +12,53 @@ from .common import ( from .model import DashboardStatisticValue +def _institution_ids(value: str | list[str]) -> list[str]: + return value if isinstance(value, list) else [value] + + +def _scope_id(institution_ids: list[str]) -> str: + return ( + _normalize_institution_id(institution_ids[0]) + if len(institution_ids) == 1 + else "all" + ) + + +async def _institution_aliases(institution_ids: list[str]) -> list[str]: + client = InstitutionsSearchClient() + aliases = await asyncio.gather( + *( + client.get_institution_aliases_by_oa_institution_id( + _raw_institution_id(institution_id) + ) + for institution_id in institution_ids + ) + ) + return list(dict.fromkeys(alias for group in aliases for alias in group)) + + async def get_dashboard_eu_projects( - institution_id: str, + institution_id: str | list[str], organization_name: str, from_year: int | None = None, to_year: int | None = None, ) -> DashboardStatisticValue: - normalized_id = _normalize_institution_id(institution_id) + institution_ids = _institution_ids(institution_id) period = _dashboard_period(from_year, to_year) + multiple_institutions = len(institution_ids) > 1 projects = await projects_service.search_eu_cordis_projects( institutions_search_client=InstitutionsSearchClient(), - raw_oa_institution_id=_raw_institution_id(normalized_id), + raw_oa_institution_id=( + None if multiple_institutions else _raw_institution_id(institution_ids[0]) + ), author_id=None, author_ids=None, organization_ids=None, - organization_names=None, + organization_names=( + await _institution_aliases(institution_ids) + if multiple_institutions + else None + ), project_types=list(EuCordisProjectType), keywords=None, topic_ids=None, @@ -45,24 +79,27 @@ async def get_dashboard_eu_projects( fuzzy=False, ) return DashboardStatisticValue( - institution_id=normalized_id, + institution_id=_scope_id(institution_ids), organization_name=organization_name, value=projects.total, ) async def get_dashboard_bmbf_projects( - institution_id: str, + institution_id: str | list[str], organization_name: str, from_year: int | None = None, to_year: int | None = None, ) -> DashboardStatisticValue: - normalized_id = _normalize_institution_id(institution_id) + institution_ids = _institution_ids(institution_id) period = _dashboard_period(from_year, to_year) + multiple_institutions = len(institution_ids) > 1 projects = await projects_service.search_bund_projects_with_filters( institutions_search_client=InstitutionsSearchClient(), executing_agency=None, - raw_oa_institution_id=_raw_institution_id(normalized_id), + raw_oa_institution_id=( + None if multiple_institutions else _raw_institution_id(institution_ids[0]) + ), title=None, keywords=None, funding_arts=None, @@ -78,25 +115,33 @@ async def get_dashboard_bmbf_projects( sort_by="id", sort_direction="asc", fuzzy=False, + oa_institution_aliases=( + await _institution_aliases(institution_ids) + if multiple_institutions + else None + ), ) return DashboardStatisticValue( - institution_id=normalized_id, + institution_id=_scope_id(institution_ids), organization_name=organization_name, value=projects.total, ) async def get_dashboard_dfg_projects( - institution_id: str, + institution_id: str | list[str], organization_name: str, from_year: int | None = None, to_year: int | None = None, ) -> DashboardStatisticValue: - normalized_id = _normalize_institution_id(institution_id) + institution_ids = _institution_ids(institution_id) period = _dashboard_period(from_year, to_year) + multiple_institutions = len(institution_ids) > 1 projects = await projects_service.get_dfg_projects( institutions_search_client=InstitutionsSearchClient(), - raw_oa_institution_id=_raw_institution_id(normalized_id), + raw_oa_institution_id=( + None if multiple_institutions else _raw_institution_id(institution_ids[0]) + ), author_id=None, author_filter_ids=None, institution_ids=None, @@ -114,9 +159,14 @@ async def get_dashboard_dfg_projects( sort_direction="asc", fuzzy=False, skip_enrichment=True, + institution_aliases=( + await _institution_aliases(institution_ids) + if multiple_institutions + else None + ), ) return DashboardStatisticValue( - institution_id=normalized_id, + institution_id=_scope_id(institution_ids), organization_name=organization_name, value=projects.total, ) diff --git a/service/src/main/inse/dashboard/project_status_service.py b/service/src/main/inse/dashboard/project_status_service.py index 4c32b94b..803cb3ed 100644 --- a/service/src/main/inse/dashboard/project_status_service.py +++ b/service/src/main/inse/dashboard/project_status_service.py @@ -25,6 +25,7 @@ from .project_statistics_service import ( get_dashboard_dfg_projects, get_dashboard_eu_projects, ) +from .project_ids_service import _get_dfg_project_ids_from_projects_service def _status_count(aggregations: dict[str, Any], status_name: str) -> int: @@ -77,13 +78,22 @@ async def get_dashboard_eu_project_statuses( to_year: int | None = None, ) -> EuProjectStatusStatistics: normalized_id = _normalize_institution_id(institution_id) - aliases = await _institution_aliases(normalized_id, organization_name) - project_ids = await _eu_project_ids_for_aliases(aliases) total = ( await get_dashboard_eu_projects( normalized_id, organization_name, from_year=from_year, to_year=to_year ) ).value + if total == 0: + return EuProjectStatusStatistics( + institution_id=normalized_id, + organization_name=organization_name, + ongoing=0, + upcoming=0, + completed=0, + ) + + aliases = await _institution_aliases(normalized_id, organization_name) + project_ids = await _eu_project_ids_for_aliases(aliases) if not project_ids: return EuProjectStatusStatistics( institution_id=normalized_id, @@ -152,6 +162,20 @@ async def get_dashboard_bmbf_project_statuses( to_year: int | None = None, ) -> BmbfProjectStatusStatistics: normalized_id = _normalize_institution_id(institution_id) + total = ( + await get_dashboard_bmbf_projects( + normalized_id, organization_name, from_year=from_year, to_year=to_year + ) + ).value + if total == 0: + return BmbfProjectStatusStatistics( + institution_id=normalized_id, + organization_name=organization_name, + ongoing=0, + upcoming=0, + completed=0, + ) + aliases = await _institution_aliases(normalized_id, organization_name) period = _dashboard_period(from_year, to_year) filters = [_alias_match_query("Zuwendungsempfänger", aliases)] @@ -171,11 +195,6 @@ async def get_dashboard_bmbf_project_statuses( cluster=ESCluster.INSE, ) aggregations = response.get("aggregations", {}) - total = ( - await get_dashboard_bmbf_projects( - normalized_id, organization_name, from_year=from_year, to_year=to_year - ) - ).value ongoing, upcoming, completed = reconcile_status_counts( total, int(aggregations.get("ongoing", {}).get("doc_count", 0)), @@ -199,12 +218,25 @@ async def get_dashboard_dfg_project_statuses( ) -> DfgProjectStatusStatistics: normalized_id = _normalize_institution_id(institution_id) period = _dashboard_period(from_year, to_year) - project_ids = await _get_dfg_project_ids_for_institution(normalized_id) total = ( await get_dashboard_dfg_projects( normalized_id, organization_name, from_year=from_year, to_year=to_year ) ).value + if total == 0: + return DfgProjectStatusStatistics( + institution_id=normalized_id, + organization_name=organization_name, + ongoing=0, + upcoming=0, + completed=0, + ) + + project_ids = await _get_dfg_project_ids_from_projects_service( + normalized_id, + from_year=from_year, + to_year=to_year, + ) if not project_ids: return DfgProjectStatusStatistics( institution_id=normalized_id, diff --git a/service/src/main/inse/dashboard/router.py b/service/src/main/inse/dashboard/router.py index a0d0de82..96b1dbe0 100644 --- a/service/src/main/inse/dashboard/router.py +++ b/service/src/main/inse/dashboard/router.py @@ -11,6 +11,7 @@ from inse.tags import Tags from .model import ( BmbfProjectStatusStatistics, BundProjectTopics, + DashboardInstitution, DashboardStatistics, DashboardStatisticValue, DfgProjectStatusStatistics, @@ -23,10 +24,13 @@ from .model import ( TopicWordCloud, ) from .service import ( + get_dashboard_analytical_institution, + get_dashboard_institutions, get_dashboard_organization, get_dashboard_patents, get_dashboard_persons, get_dashboard_publications, + get_dashboard_statistic_institution_ids, get_dashboard_statistics, get_topic_heatmap, get_topic_word_cloud, @@ -56,6 +60,19 @@ from .top_authors_service import ( router = APIRouter(prefix="/api/dashboard", tags=[Tags.DASHBOARD]) +@router.get( + "/institutions", + operation_id="getDashboardInstitutions", + response_model=list[DashboardInstitution], +) +async def dashboard_institutions( + session: Session = Depends(get_session), + access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, +) -> list[DashboardInstitution]: + organization = get_dashboard_organization(session, access_token) + return await get_dashboard_institutions(session, organization) + + @router.get( "/statistics", operation_id="getDashboardStatistics", @@ -78,14 +95,18 @@ async def dashboard_statistics( response_model=DashboardStatisticValue, ) async def dashboard_publications( + institution_id: str | None = Query(default=None), from_year: int | None = Query(default=None, ge=1900, le=2100), to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> DashboardStatisticValue: organization = get_dashboard_organization(session, access_token) + institution_ids = await get_dashboard_statistic_institution_ids( + session, organization, institution_id + ) return await get_dashboard_publications( - organization.openalex_institution_id, + institution_ids, organization.name, from_year=from_year, to_year=to_year, @@ -98,14 +119,18 @@ async def dashboard_publications( response_model=DashboardStatisticValue, ) async def dashboard_persons( + institution_id: str | None = Query(default=None), from_year: int | None = Query(default=None, ge=1900, le=2100), to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> DashboardStatisticValue: organization = get_dashboard_organization(session, access_token) + institution_ids = await get_dashboard_statistic_institution_ids( + session, organization, institution_id + ) return await get_dashboard_persons( - organization.openalex_institution_id, + institution_ids, organization.name, from_year=from_year, to_year=to_year, @@ -118,14 +143,18 @@ async def dashboard_persons( response_model=DashboardStatisticValue, ) async def dashboard_patents( + institution_id: str | None = Query(default=None), from_year: int | None = Query(default=None, ge=1900, le=2100), to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> DashboardStatisticValue: organization = get_dashboard_organization(session, access_token) + institution_ids = await get_dashboard_statistic_institution_ids( + session, organization, institution_id + ) return await get_dashboard_patents( - organization.openalex_institution_id, + institution_ids, organization.name, from_year=from_year, to_year=to_year, @@ -138,14 +167,18 @@ async def dashboard_patents( response_model=DashboardStatisticValue, ) async def dashboard_eu_projects( + institution_id: str | None = Query(default=None), from_year: int | None = Query(default=None, ge=1900, le=2100), to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> DashboardStatisticValue: organization = get_dashboard_organization(session, access_token) + institution_ids = await get_dashboard_statistic_institution_ids( + session, organization, institution_id + ) return await get_dashboard_eu_projects( - organization.openalex_institution_id, + institution_ids, organization.name, from_year=from_year, to_year=to_year, @@ -158,15 +191,21 @@ async def dashboard_eu_projects( response_model=EuProjectStatusStatistics, ) async def dashboard_eu_project_statuses( + institution_id: str | None = Query(default=None), from_year: int | None = Query(default=None, ge=1900, le=2100), to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> EuProjectStatusStatistics: organization = get_dashboard_organization(session, access_token) + selected_institution_id, selected_institution_name = ( + await get_dashboard_analytical_institution( + session, organization, institution_id + ) + ) return await get_dashboard_eu_project_statuses( - organization.openalex_institution_id, - organization.name, + selected_institution_id, + selected_institution_name, from_year=from_year, to_year=to_year, ) @@ -178,14 +217,18 @@ async def dashboard_eu_project_statuses( response_model=DashboardStatisticValue, ) async def dashboard_bmbf_projects( + institution_id: str | None = Query(default=None), from_year: int | None = Query(default=None, ge=1900, le=2100), to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> DashboardStatisticValue: organization = get_dashboard_organization(session, access_token) + institution_ids = await get_dashboard_statistic_institution_ids( + session, organization, institution_id + ) return await get_dashboard_bmbf_projects( - organization.openalex_institution_id, + institution_ids, organization.name, from_year=from_year, to_year=to_year, @@ -198,15 +241,21 @@ async def dashboard_bmbf_projects( response_model=BmbfProjectStatusStatistics, ) async def dashboard_bmbf_project_statuses( + institution_id: str | None = Query(default=None), from_year: int | None = Query(default=None, ge=1900, le=2100), to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> BmbfProjectStatusStatistics: organization = get_dashboard_organization(session, access_token) + selected_institution_id, selected_institution_name = ( + await get_dashboard_analytical_institution( + session, organization, institution_id + ) + ) return await get_dashboard_bmbf_project_statuses( - organization.openalex_institution_id, - organization.name, + selected_institution_id, + selected_institution_name, from_year=from_year, to_year=to_year, ) @@ -218,14 +267,18 @@ async def dashboard_bmbf_project_statuses( response_model=DashboardStatisticValue, ) async def dashboard_dfg_projects( + institution_id: str | None = Query(default=None), from_year: int | None = Query(default=None, ge=1900, le=2100), to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> DashboardStatisticValue: organization = get_dashboard_organization(session, access_token) + institution_ids = await get_dashboard_statistic_institution_ids( + session, organization, institution_id + ) return await get_dashboard_dfg_projects( - organization.openalex_institution_id, + institution_ids, organization.name, from_year=from_year, to_year=to_year, @@ -238,15 +291,21 @@ async def dashboard_dfg_projects( response_model=DfgProjectStatusStatistics, ) async def dashboard_dfg_project_statuses( + institution_id: str | None = Query(default=None), from_year: int | None = Query(default=None, ge=1900, le=2100), to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> DfgProjectStatusStatistics: organization = get_dashboard_organization(session, access_token) + selected_institution_id, selected_institution_name = ( + await get_dashboard_analytical_institution( + session, organization, institution_id + ) + ) return await get_dashboard_dfg_project_statuses( - organization.openalex_institution_id, - organization.name, + selected_institution_id, + selected_institution_name, from_year=from_year, to_year=to_year, ) @@ -258,15 +317,21 @@ async def dashboard_dfg_project_statuses( response_model=DfgProjectTopics, ) async def dashboard_dfg_project_topics( + institution_id: str | None = Query(default=None), from_year: int | None = Query(default=None, ge=1900, le=2100), to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> DfgProjectTopics: organization = get_dashboard_organization(session, access_token) + selected_institution_id, selected_institution_name = ( + await get_dashboard_analytical_institution( + session, organization, institution_id + ) + ) return await get_dashboard_dfg_topics( - organization.openalex_institution_id, - organization.name, + selected_institution_id, + selected_institution_name, from_year=from_year, to_year=to_year, ) @@ -278,15 +343,21 @@ async def dashboard_dfg_project_topics( response_model=EuProjectTopics, ) async def dashboard_eu_project_topics( + institution_id: str | None = Query(default=None), from_year: int | None = Query(default=None, ge=1900, le=2100), to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> EuProjectTopics: organization = get_dashboard_organization(session, access_token) + selected_institution_id, selected_institution_name = ( + await get_dashboard_analytical_institution( + session, organization, institution_id + ) + ) return await get_dashboard_eu_topics( - organization.openalex_institution_id, - organization.name, + selected_institution_id, + selected_institution_name, from_year=from_year, to_year=to_year, ) @@ -298,15 +369,21 @@ async def dashboard_eu_project_topics( response_model=BundProjectTopics, ) async def dashboard_bund_project_topics( + institution_id: str | None = Query(default=None), from_year: int | None = Query(default=None, ge=1900, le=2100), to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> BundProjectTopics: organization = get_dashboard_organization(session, access_token) + selected_institution_id, selected_institution_name = ( + await get_dashboard_analytical_institution( + session, organization, institution_id + ) + ) return await get_dashboard_bund_topics( - organization.openalex_institution_id, - organization.name, + selected_institution_id, + selected_institution_name, from_year=from_year, to_year=to_year, ) @@ -322,15 +399,21 @@ async def dashboard_top_authors( default="all_time", pattern="^(all_time|last_5_years)$", ), + institution_id: str | None = Query(default=None), from_year: int | None = Query(default=None, ge=1900, le=2100), to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> TopAuthorStatistics: organization = get_dashboard_organization(session, access_token) + selected_institution_id, selected_institution_name = ( + await get_dashboard_analytical_institution( + session, organization, institution_id + ) + ) return await get_top_authors( - organization.openalex_institution_id, - organization.name, + selected_institution_id, + selected_institution_name, works_period=works_period, from_year=from_year, to_year=to_year, @@ -346,14 +429,18 @@ async def dashboard_top_work_authors( works_period: Literal["all_time", "last_5_years"] = Query( default="all_time", pattern="^(all_time|last_5_years)$" ), + institution_id: str | None = Query(default=None), from_year: int | None = Query(default=None, ge=1900, le=2100), to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> TopAuthorAnalysis: organization = get_dashboard_organization(session, access_token) + selected_institution_id, _ = await get_dashboard_analytical_institution( + session, organization, institution_id + ) return await get_top_work_authors( - organization.openalex_institution_id, works_period, from_year, to_year + selected_institution_id, works_period, from_year, to_year ) @@ -363,14 +450,20 @@ async def dashboard_top_work_authors( response_model=TopAuthorAnalysis, ) async def dashboard_top_project_authors( + institution_id: str | None = Query(default=None), from_year: int | None = Query(default=None, ge=1900, le=2100), to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> TopAuthorAnalysis: organization = get_dashboard_organization(session, access_token) + selected_institution_id, selected_institution_name = ( + await get_dashboard_analytical_institution( + session, organization, institution_id + ) + ) return await get_top_project_authors( - organization.openalex_institution_id, organization.name, from_year, to_year + selected_institution_id, selected_institution_name, from_year, to_year ) @@ -380,14 +473,18 @@ async def dashboard_top_project_authors( response_model=TopAuthorAnalysis, ) async def dashboard_top_eu_project_authors( + institution_id: str | None = Query(default=None), from_year: int | None = Query(default=None, ge=1900, le=2100), to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> TopAuthorAnalysis: organization = get_dashboard_organization(session, access_token) + selected_institution_id, _ = await get_dashboard_analytical_institution( + session, organization, institution_id + ) return await get_top_eu_project_authors( - organization.openalex_institution_id, from_year, to_year + selected_institution_id, from_year, to_year ) @@ -397,14 +494,18 @@ async def dashboard_top_eu_project_authors( response_model=TopAuthorAnalysis, ) async def dashboard_top_patent_authors( + institution_id: str | None = Query(default=None), from_year: int | None = Query(default=None, ge=1900, le=2100), to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> TopAuthorAnalysis: organization = get_dashboard_organization(session, access_token) + selected_institution_id, _ = await get_dashboard_analytical_institution( + session, organization, institution_id + ) return await get_top_patent_authors( - organization.openalex_institution_id, from_year, to_year + selected_institution_id, from_year, to_year ) @@ -414,14 +515,18 @@ async def dashboard_top_patent_authors( response_model=TopAuthorAnalysis, ) async def dashboard_top_news_authors( + institution_id: str | None = Query(default=None), from_year: int | None = Query(default=None, ge=1900, le=2100), to_year: int | None = Query(default=None, ge=1900, le=2100), session: Session = Depends(get_session), access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> TopAuthorAnalysis: organization = get_dashboard_organization(session, access_token) + selected_institution_id, _ = await get_dashboard_analytical_institution( + session, organization, institution_id + ) return await get_top_news_authors( - organization.openalex_institution_id, from_year, to_year + selected_institution_id, from_year, to_year ) @@ -431,6 +536,7 @@ async def dashboard_top_news_authors( response_model=TopicHeatmap, ) async def dashboard_topic_heatmap( + institution_id: str | None = Query(default=None), from_year: int | None = Query(default=None, ge=1900, le=2100), to_year: int | None = Query(default=None, ge=1900, le=2100), limit: int = Query(default=25, ge=1, le=50), @@ -438,9 +544,14 @@ async def dashboard_topic_heatmap( access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> TopicHeatmap: organization = get_dashboard_organization(session, access_token) + selected_institution_id, selected_institution_name = ( + await get_dashboard_analytical_institution( + session, organization, institution_id + ) + ) return await get_topic_heatmap( - institution_id=organization.openalex_institution_id, - organization_name=organization.name, + institution_id=selected_institution_id, + organization_name=selected_institution_name, from_year=from_year, to_year=to_year, limit=limit, @@ -454,6 +565,7 @@ async def dashboard_topic_heatmap( ) async def dashboard_topic_word_cloud( topic_id: str = Query(alias="topicId", min_length=1), + institution_id: str | None = Query(default=None), from_year: int | None = Query(default=None, ge=1900, le=2100), to_year: int | None = Query(default=None, ge=1900, le=2100), limit: int = Query(default=30, ge=1, le=100), @@ -461,8 +573,11 @@ async def dashboard_topic_word_cloud( access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep, ) -> TopicWordCloud: organization = get_dashboard_organization(session, access_token) + selected_institution_id, _ = await get_dashboard_analytical_institution( + session, organization, institution_id + ) return await get_topic_word_cloud( - institution_id=organization.openalex_institution_id, + institution_id=selected_institution_id, topic_id=topic_id, from_year=from_year, to_year=to_year, diff --git a/service/src/main/inse/dashboard/service.py b/service/src/main/inse/dashboard/service.py index 873c55f0..21a7351d 100644 --- a/service/src/main/inse/dashboard/service.py +++ b/service/src/main/inse/dashboard/service.py @@ -3,13 +3,17 @@ import logging from typing import Any from fastapi import HTTPException, status -from sqlmodel import Session +from sqlmodel import Session, select from inse import config -from inse.auth.model import AccessToken, Organization +from inse.auth.model import AccessToken, Organization, OrganizationInstitution +from inse.authors.institution_membership_query import ( + build_institution_membership_query, +) from inse.institutions.v2 import service as institutions_v2_service from inse.integrations import elasticsearch from inse.model import ESCluster, ESIndex +from inse.organization_management import service as organization_management_service from inse.patents.org.elastic_search_client import OrgPatentsSearchClient from inse.persons import service as persons_service from inse.works.v2 import service as works_v2_service @@ -22,6 +26,7 @@ from .common import ( raw_institution_id as _raw_institution_id, ) from .model import ( + DashboardInstitution, DashboardStatistics, DashboardStatisticValue, TopicHeatmap, @@ -45,6 +50,92 @@ TOPIC_WORD_CLOUD_LIMIT = 30 logger = logging.getLogger(__name__) +async def get_dashboard_institutions( + session: Session, + organization: Organization, +) -> list[DashboardInstitution]: + rows = session.exec( + select(OrganizationInstitution) + .where(OrganizationInstitution.organization_id == organization.id) + .order_by(OrganizationInstitution.position) + ).all() + institution_ids = [row.openalex_institution_id for row in rows] + if not institution_ids and organization.openalex_institution_id: + institution_ids = [_raw_institution_id(organization.openalex_institution_id)] + if not institution_ids: + return [] + + association_groups = ( + await organization_management_service.resolve_institution_associations( + institution_ids + ) + ) + institutions: dict[str, DashboardInstitution] = {} + for group in association_groups: + root_id = _raw_institution_id(group.id) + institutions[root_id] = DashboardInstitution( + id=root_id, + display_name=group.display_name, + ) + for association in group.associated_institutions: + association_id = _raw_institution_id(association.id) + institutions.setdefault( + association_id, + DashboardInstitution( + id=association_id, + display_name=association.display_name, + ), + ) + return list(institutions.values()) + + +async def get_dashboard_statistic_institution_ids( + session: Session, + organization: Organization, + selected_institution_id: str | None, +) -> list[str]: + institutions = await get_dashboard_institutions(session, organization) + institution_ids = [institution.id for institution in institutions] + if selected_institution_id in (None, "all"): + return institution_ids + + selected_id = _raw_institution_id(selected_institution_id) + if selected_id not in institution_ids: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Institution is not associated with this organization.", + ) + return [selected_id] + + +async def get_dashboard_analytical_institution( + session: Session, + organization: Organization, + selected_institution_id: str | None, +) -> tuple[str, str]: + if selected_institution_id in (None, "all"): + return organization.openalex_institution_id, organization.name + + selected_id = _raw_institution_id(selected_institution_id) + institutions = await get_dashboard_institutions(session, organization) + for institution in institutions: + if institution.id == selected_id: + return selected_id, institution.display_name + + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Institution is not associated with this organization.", + ) + + +def _statistic_scope_id(institution_ids: list[str]) -> str: + return ( + _normalize_institution_id(institution_ids[0]) + if len(institution_ids) == 1 + else "all" + ) + + def _publication_year_filter(period: DashboardPeriod) -> dict[str, Any] | None: from_year, to_year = period year_range: dict[str, int] = {} @@ -104,12 +195,15 @@ async def get_dashboard_statistics( async def get_dashboard_publications( - institution_id: str, + institution_id: str | list[str], organization_name: str, from_year: int | None = None, to_year: int | None = None, ) -> DashboardStatisticValue: - normalized_id = _normalize_institution_id(institution_id) + institution_ids = ( + institution_id if isinstance(institution_id, list) else [institution_id] + ) + normalized_ids = [_normalize_institution_id(value) for value in institution_ids] period = _dashboard_period(from_year, to_year) publication_years: list[int] = [] if period != (None, None): @@ -120,67 +214,94 @@ async def get_dashboard_publications( works = await works_v2_service.get_works( page=0, size=1, - institution_ids=[normalized_id], + institution_ids=normalized_ids, publication_years=publication_years, ) return DashboardStatisticValue( - institution_id=normalized_id, + institution_id=_statistic_scope_id(institution_ids), organization_name=organization_name, value=works.total, ) async def get_dashboard_persons( - institution_id: str, + institution_id: str | list[str], organization_name: str, from_year: int | None = None, to_year: int | None = None, ) -> DashboardStatisticValue: - normalized_id = _normalize_institution_id(institution_id) + institution_ids = institution_id if isinstance(institution_id, list) else [institution_id] + normalized_ids = [_normalize_institution_id(value) for value in institution_ids] period = _dashboard_period(from_year, to_year) if (period[0] is None) != (period[1] is None): raise HTTPException( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="from_year and to_year must either both be provided or both omitted.", ) - persons = await persons_service.search_persons_list( - query=None, - institution_id=normalized_id, - sort_by=None, - sort_order=None, - topic=None, - page=1, - page_size=1, - include="", - year_filter_enabled=period[0] is not None, - filter_mode="between" if period[0] is not None else None, - filter_year=period[0], - filter_year_to=period[1], + if len(normalized_ids) == 1: + persons = await persons_service.search_persons_list( + query=None, + institution_id=normalized_ids[0], + sort_by=None, + sort_order=None, + topic=None, + page=1, + page_size=1, + include="", + year_filter_enabled=period[0] is not None, + filter_mode="between" if period[0] is not None else None, + filter_year=period[0], + filter_year_to=period[1], + ) + return DashboardStatisticValue( + institution_id=normalized_ids[0], + organization_name=organization_name, + value=int(persons.meta.count or 0) if persons.meta else 0, + ) + + membership_queries = [ + build_institution_membership_query( + institution_id=value, + year_mode="between" if period[0] is not None else "all", + year=period[0], + year_to=period[1], + ) + for value in normalized_ids + ] + value = await elasticsearch.count( + index="openalex-authors", + query={ + "bool": { + "should": membership_queries, + "minimum_should_match": 1, + } + }, ) return DashboardStatisticValue( - institution_id=normalized_id, + institution_id=_statistic_scope_id(institution_ids), organization_name=organization_name, - value=int(persons.meta.count or 0) if persons.meta else 0, + value=value, ) async def get_dashboard_patents( - institution_id: str, + institution_id: str | list[str], organization_name: str, from_year: int | None = None, to_year: int | None = None, ) -> DashboardStatisticValue: - normalized_id = _normalize_institution_id(institution_id) + institution_ids = institution_id if isinstance(institution_id, list) else [institution_id] + normalized_ids = [_normalize_institution_id(value) for value in institution_ids] period = _dashboard_period(from_year, to_year) _, total = await OrgPatentsSearchClient().search_by_institution( - normalized_id, + normalized_ids, page=0, size=0, from_year=period[0], to_year=period[1], ) return DashboardStatisticValue( - institution_id=normalized_id, + institution_id=_statistic_scope_id(institution_ids), organization_name=organization_name, value=total, ) diff --git a/service/src/main/inse/dashboard/test_service.py b/service/src/main/inse/dashboard/test_service.py index 4445262a..8f21c89b 100644 --- a/service/src/main/inse/dashboard/test_service.py +++ b/service/src/main/inse/dashboard/test_service.py @@ -8,8 +8,15 @@ from fastapi import HTTPException from sqlmodel import Session, SQLModel, create_engine from inse import config -from inse.auth.model import AccessToken, Organization, UserRole +from inse.auth.model import ( + AccessToken, + Organization, + OrganizationInstitution, + UserRole, +) from inse.dashboard.service import ( + get_dashboard_analytical_institution, + get_dashboard_institutions, get_dashboard_organization, get_dashboard_persons, get_dashboard_publications, @@ -22,8 +29,13 @@ from inse.dashboard.common import ( ) from inse.dashboard.bund_topics_service import get_dashboard_bund_topics from inse.dashboard.eu_topics_service import get_dashboard_eu_topics -from inse.dashboard.model import TopAuthor -from inse.dashboard.project_status_service import reconcile_status_counts +from inse.dashboard.model import DashboardStatisticValue, TopAuthor +from inse.dashboard.project_status_service import ( + get_dashboard_bmbf_project_statuses, + get_dashboard_dfg_project_statuses, + get_dashboard_eu_project_statuses, + reconcile_status_counts, +) from inse.dashboard.project_ids_service import ( _get_dfg_project_ids_from_projects_service, ) @@ -42,6 +54,10 @@ from inse.exceptions import ElasticsearchException from inse.model import ESIndex from inse.models.openalex.institution import Institution from inse.models.openalex.meta import Meta +from inse.organization_management.model import ( + InstitutionAssociation, + InstitutionAssociationsResponse, +) from inse.persons.model import CustomAuthorsListResponse from inse.projects.model import ( BundProjectPage, @@ -116,6 +132,100 @@ def test_project_status_counts_match_authoritative_total(): assert reconcile_status_counts(7, 4, 2, 3) == (2, 2, 3) +@pytest.mark.anyio +@pytest.mark.parametrize( + ("status_loader", "count_loader", "extra_dependency"), + [ + ( + get_dashboard_eu_project_statuses, + "get_dashboard_eu_projects", + "_institution_aliases", + ), + ( + get_dashboard_bmbf_project_statuses, + "get_dashboard_bmbf_projects", + "_institution_aliases", + ), + ( + get_dashboard_dfg_project_statuses, + "get_dashboard_dfg_projects", + "_get_dfg_project_ids_from_projects_service", + ), + ], +) +async def test_project_status_zero_count_is_not_an_error( + status_loader, count_loader, extra_dependency +): + zero_count = DashboardStatisticValue( + institution_id=ORG_INSTITUTION_ID, + organization_name="Example University", + value=0, + ) + with ( + patch( + f"inse.dashboard.project_status_service.{count_loader}", + new=AsyncMock(return_value=zero_count), + ), + patch( + f"inse.dashboard.project_status_service.{extra_dependency}", + new=AsyncMock(side_effect=AssertionError("must not be called")), + ), + ): + result = await status_loader(ORG_INSTITUTION_ID, "Example University") + + assert result.ongoing == 0 + assert result.upcoming == 0 + assert result.completed == 0 + + +@pytest.mark.anyio +async def test_dfg_project_status_uses_card_project_ids_and_total(): + card_total = DashboardStatisticValue( + institution_id=ORG_INSTITUTION_ID, + organization_name="University Hospital Essen", + value=24, + ) + status_aggregations = { + "aggregations": { + "projects_nested": { + "selected_projects": { + "ongoing": {"projects": {"value": 7}}, + "completed": {"projects": {"value": 17}}, + } + } + } + } + with ( + patch( + "inse.dashboard.project_status_service.get_dashboard_dfg_projects", + new=AsyncMock(return_value=card_total), + ), + patch( + "inse.dashboard.project_status_service._get_dfg_project_ids_from_projects_service", + new=AsyncMock( + return_value=[str(project_id) for project_id in range(1, 25)] + ), + ) as project_ids_loader, + patch( + "inse.dashboard.project_status_service.elasticsearch.search", + new=AsyncMock(return_value=status_aggregations), + ), + ): + result = await get_dashboard_dfg_project_statuses( + ORG_INSTITUTION_ID, + "University Hospital Essen", + ) + + project_ids_loader.assert_awaited_once_with( + ORG_INSTITUTION_ID, + from_year=None, + to_year=None, + ) + assert result.ongoing == 7 + assert result.completed == 17 + assert result.ongoing + result.upcoming + result.completed == 24 + + def test_project_status_period_uses_interval_overlap(): assert _project_boundary_year_filter( "startDate", "endDate", (2022, 2026), "iso" @@ -971,11 +1081,11 @@ def test_eu_author_count_groups_multiple_publications_by_project_id(): works_response, doi_project_ids, ORG_INSTITUTION_ID, - {"https://openalex.org/A5007170803"}, ) assert [author.model_dump() for author in result] == [ - {"id": "A5007170803", "name": "Marcus Example", "count": 1} + {"id": "A999", "name": "External Example", "count": 1}, + {"id": "A5007170803", "name": "Marcus Example", "count": 1}, ] @@ -1618,6 +1728,161 @@ def test_get_dashboard_organization_uses_effective_organization(): assert result.openalex_institution_id == "I456" +@pytest.mark.anyio +async def test_dashboard_institutions_include_openalex_associations(): + engine = create_engine("sqlite://", connect_args={"check_same_thread": False}) + SQLModel.metadata.create_all(engine) + + with Session(engine) as session: + organization = Organization( + name="Example University", + openalex_institution_id="I123", + ) + session.add(organization) + session.commit() + session.refresh(organization) + session.add( + OrganizationInstitution( + organization_id=organization.id, + openalex_institution_id="I123", + position=0, + ) + ) + session.commit() + + associations = [ + InstitutionAssociationsResponse( + id="I123", + display_name="Main institution", + associated_institutions=[ + InstitutionAssociation( + id="I456", + display_name="Child institution", + relationship="child", + ), + InstitutionAssociation( + id="I789", + display_name="Related institution", + relationship="related", + ), + ], + ) + ] + with patch( + "inse.dashboard.service.organization_management_service." + "resolve_institution_associations", + new=AsyncMock(return_value=associations), + ): + result = await get_dashboard_institutions(session, organization) + + assert [institution.model_dump() for institution in result] == [ + {"id": "I123", "display_name": "Main institution"}, + {"id": "I456", "display_name": "Child institution"}, + {"id": "I789", "display_name": "Related institution"}, + ] + + +@pytest.mark.anyio +async def test_dashboard_analytical_institution_all_uses_root_organization(): + engine = create_engine("sqlite://", connect_args={"check_same_thread": False}) + SQLModel.metadata.create_all(engine) + + with Session(engine) as session: + organization = Organization( + name="Example University", + openalex_institution_id="I123", + ) + session.add(organization) + session.commit() + session.refresh(organization) + + result = await get_dashboard_analytical_institution( + session, + organization, + "all", + ) + + assert result == ("I123", "Example University") + + +@pytest.mark.anyio +async def test_dashboard_analytical_institution_uses_selected_tab_institution(): + engine = create_engine("sqlite://", connect_args={"check_same_thread": False}) + SQLModel.metadata.create_all(engine) + + with Session(engine) as session: + organization = Organization( + name="Example University", + openalex_institution_id="I123", + ) + session.add(organization) + session.commit() + session.refresh(organization) + session.add( + OrganizationInstitution( + organization_id=organization.id, + openalex_institution_id="I123", + position=0, + ) + ) + session.commit() + + associations = [ + InstitutionAssociationsResponse( + id="I123", + display_name="Main institution", + associated_institutions=[ + InstitutionAssociation( + id="I456", + display_name="Child institution", + relationship="child", + ), + ], + ) + ] + with patch( + "inse.dashboard.service.organization_management_service." + "resolve_institution_associations", + new=AsyncMock(return_value=associations), + ): + result = await get_dashboard_analytical_institution( + session, + organization, + "https://openalex.org/I456", + ) + + assert result == ("I456", "Child institution") + + +@pytest.mark.anyio +async def test_dashboard_analytical_institution_rejects_unassociated_selection(): + engine = create_engine("sqlite://", connect_args={"check_same_thread": False}) + SQLModel.metadata.create_all(engine) + + with Session(engine) as session: + organization = Organization( + name="Example University", + openalex_institution_id="I123", + ) + session.add(organization) + session.commit() + session.refresh(organization) + + with patch( + "inse.dashboard.service.organization_management_service." + "resolve_institution_associations", + new=AsyncMock(return_value=[]), + ): + with pytest.raises(HTTPException) as exc_info: + await get_dashboard_analytical_institution( + session, + organization, + "I999", + ) + + assert exc_info.value.status_code == 422 + + def test_get_dashboard_organization_rejects_missing_openalex_id(): engine = create_engine("sqlite://", connect_args={"check_same_thread": False}) SQLModel.metadata.create_all(engine) diff --git a/service/src/main/inse/dashboard/top_authors_service.py b/service/src/main/inse/dashboard/top_authors_service.py index 72a8c1e2..79d63846 100644 --- a/service/src/main/inse/dashboard/top_authors_service.py +++ b/service/src/main/inse/dashboard/top_authors_service.py @@ -79,7 +79,6 @@ async def get_top_authors( "eu_projects", _top_eu_project_publication_authors( normalized_id, - authors, from_year=period[0], to_year=period[1], ), @@ -152,12 +151,10 @@ async def get_top_eu_project_authors( ) -> TopAuthorAnalysis: normalized_id = _normalize_institution_id(institution_id) period = _period(from_year=from_year, to_year=to_year) - authors = await _safe_institution_authors(normalized_id) return TopAuthorAnalysis( institution_id=normalized_id, authors=await _top_eu_project_publication_authors( normalized_id, - authors, from_year=period[0], to_year=period[1], ), @@ -825,18 +822,9 @@ async def _top_patent_authors( async def _top_eu_project_publication_authors( institution_id: str, - institution_authors: list[dict[str, Any]], from_year: int | None = None, to_year: int | None = None, ) -> list[TopAuthor]: - institution_author_ids = { - author_id - for author in institution_authors - if (author_id := _normalize_author_id(author.get("id"))) - } - if not institution_author_ids: - return [] - # Candidate discovery is deliberately all-time. The selected period is # applied to each person's authoritative project count below. Otherwise a # person can disappear merely because their recent projects have no linked @@ -889,7 +877,6 @@ async def _top_eu_project_publication_authors( works_response, doi_project_ids, institution_id, - institution_author_ids, limit=None, ) ranked = await _count_eu_projects_for_candidates( @@ -976,7 +963,6 @@ def _openalex_work_authors_by_eu_projects( response: dict[str, Any], doi_project_ids: dict[str, set[str]], institution_id: str, - institution_author_ids: set[str], limit: int | None = TOP_AUTHOR_LIMIT, ) -> list[TopAuthor]: # Count unique CORDIS projects per author, not publications. Multiple works @@ -999,11 +985,7 @@ def _openalex_work_authors_by_eu_projects( author = authorship.get("author") or {} author_id = _normalize_author_id(author.get("id")) author_name = str(author.get("display_name") or "").strip() - if ( - not author_id - or author_id not in institution_author_ids - or not author_name - ): + if not author_id or not author_name: continue author_project_ids[author_id].update(project_ids) author_names.setdefault(author_id, author_name) diff --git a/service/src/main/inse/institutions/v2/router.py b/service/src/main/inse/institutions/v2/router.py index 6cd9ad36..26928f27 100644 --- a/service/src/main/inse/institutions/v2/router.py +++ b/service/src/main/inse/institutions/v2/router.py @@ -29,12 +29,17 @@ async def get_institution_by_id( raw_oa_institution_id=institution_id, source=[ "id", + "ror", "display_name", + "country_code", + "type", + "homepage_url", "display_name_alternatives", "works_count", "cited_by_count", "geo", "summary_stats", + "associated_institutions", ], ) diff --git a/service/src/main/inse/integrations/llm.py b/service/src/main/inse/integrations/llm.py index 7860ad8a..55c7b92c 100644 --- a/service/src/main/inse/integrations/llm.py +++ b/service/src/main/inse/integrations/llm.py @@ -43,6 +43,8 @@ async def call( ) except APIConnectionError: return "Etwas ist schiefgelaufen. Bitte versuche es später erneut." + finally: + await client.close() return response.choices[0].message.content or ( "Etwas ist schiefgelaufen. Bitte versuche es erneut." @@ -126,5 +128,7 @@ async def call_stream( print(f"LLM streaming failed: {type(e).__name__}: {e}") traceback.print_exc() return "" + finally: + await client.close() return full_content \ No newline at end of file diff --git a/service/src/main/inse/middleware/etag_cache.py b/service/src/main/inse/middleware/etag_cache.py index c19403b5..30581bd9 100644 --- a/service/src/main/inse/middleware/etag_cache.py +++ b/service/src/main/inse/middleware/etag_cache.py @@ -12,19 +12,29 @@ from starlette.responses import Response # organization must never be reused by the browser. NO_STORE_PATH_PREFIXES = ( "/api/auth/v2", - "/api/accounts", - "/api/background-jobs", - "/api/bookmarks", - "/api/organizations", - "/api/rank/orientation-profiles", - "/api/works/v2/classification/", -) - -NO_STORE_PATH_FRAGMENTS = ( - "/company-connections", - "/primary-category-aggregations", - "/collaboration-graph/", -) + "/api/accounts", + "/api/background-jobs", + "/api/bookmarks", + "/api/organizations", +) + +# Keep these responses in the server-side ETag cache, but require the browser +# to revalidate them. A new access token (for example after impersonation) +# automatically produces a different cache key. +REVALIDATE_PATH_PREFIXES = ( + "/api/dashboard", + "/api/rank/orientation-profiles", + "/api/works/v2/classification/", +) + +REVALIDATE_PATH_FRAGMENTS = ( + "/company-connections", + "/primary-category-aggregations", +) + +NO_STORE_PATH_FRAGMENTS = ( + "/collaboration-graph/", +) # POST is opt-out. Add any endpoint here that MUTATES state (create/update/delete/ # trigger side effects), even if it "usually" returns 200. EXCLUDED_POST_PATHS = ( @@ -94,11 +104,17 @@ class ETagCacheMiddleware(BaseHTTPMiddleware): def _content_type(self, response: Response) -> str | None: return response.headers.get("content-type") - def _requires_no_store(self, request: Request) -> bool: - path = request.url.path - return path.startswith(NO_STORE_PATH_PREFIXES) or any( - fragment in path for fragment in NO_STORE_PATH_FRAGMENTS - ) + def _requires_no_store(self, request: Request) -> bool: + path = request.url.path + return path.startswith(NO_STORE_PATH_PREFIXES) or any( + fragment in path for fragment in NO_STORE_PATH_FRAGMENTS + ) + + def _requires_revalidation(self, request: Request) -> bool: + path = request.url.path + return path.startswith(REVALIDATE_PATH_PREFIXES) or any( + fragment in path for fragment in REVALIDATE_PATH_FRAGMENTS + ) def _set_no_store_headers(self, response: Response) -> None: response.headers["Cache-Control"] = "private, no-store, max-age=0" @@ -117,10 +133,14 @@ class ETagCacheMiddleware(BaseHTTPMiddleware): vary_values.append("Authorization") headers["Vary"] = ", ".join(vary_values) - def _cache_response_headers( - self, request: Request, etag: str, content_type: str | None - ) -> dict[str, str]: - cache_control = f"max-age={self.ttl}" + def _cache_response_headers( + self, request: Request, etag: str, content_type: str | None + ) -> dict[str, str]: + cache_control = ( + "no-cache, max-age=0" + if self._requires_revalidation(request) + else f"max-age={self.ttl}" + ) headers = {"ETag": etag, "Cache-Control": cache_control} if request.headers.get("authorization"): headers["Cache-Control"] = f"private, {cache_control}" diff --git a/service/src/main/inse/middleware/test_etag_cache.py b/service/src/main/inse/middleware/test_etag_cache.py index 2ae09207..2a7dbe86 100644 --- a/service/src/main/inse/middleware/test_etag_cache.py +++ b/service/src/main/inse/middleware/test_etag_cache.py @@ -1,11 +1,13 @@ +import pytest from fastapi import FastAPI from fastapi.testclient import TestClient + from inse.middleware.etag_cache import ETagCacheMiddleware def _app_with_counter(): app = FastAPI() - calls = {"get": 0, "post": 0} + calls = {"get": 0, "post": 0, "dashboard": 0, "read_only": 0} @app.get("/api/background-jobs/tasks") def get_tasks(): @@ -17,6 +19,36 @@ def _app_with_counter(): calls["post"] += 1 return {"call": calls["post"]} + @app.get("/api/dashboard/statistics") + def get_dashboard_statistics(): + calls["dashboard"] += 1 + return {"call": calls["dashboard"]} + + def read_only_response(): + calls["read_only"] += 1 + return {"call": calls["read_only"]} + + app.add_api_route( + "/api/inse-service/authors/A1/company-connections", + read_only_response, + methods=["GET"], + ) + app.add_api_route( + "/api/works/v2/classification/work/W1", + read_only_response, + methods=["GET"], + ) + app.add_api_route( + "/api/works/v2/author/A1/primary-category-aggregations", + read_only_response, + methods=["GET"], + ) + app.add_api_route( + "/api/rank/orientation-profiles", + read_only_response, + methods=["POST"], + ) + app.add_middleware(ETagCacheMiddleware, ttl=120) return app, calls @@ -50,3 +82,70 @@ def test_background_job_post_side_effects_are_never_replayed_from_cache(): assert first.json() == {"call": 1} assert second.json() == {"call": 2} assert calls["post"] == 2 + + +def test_dashboard_revalidates_and_uses_a_separate_cache_for_a_new_token(): + app, calls = _app_with_counter() + + with TestClient(app) as client: + first = client.get( + "/api/dashboard/statistics", + headers={"Authorization": "Bearer real-account"}, + ) + revalidated = client.get( + "/api/dashboard/statistics", + headers={ + "Authorization": "Bearer real-account", + "If-None-Match": first.headers["etag"], + }, + ) + impersonated = client.get( + "/api/dashboard/statistics", + headers={ + "Authorization": "Bearer impersonated-account", + "If-None-Match": first.headers["etag"], + }, + ) + + assert first.status_code == 200 + assert first.headers["cache-control"] == "private, no-cache, max-age=0" + assert revalidated.status_code == 304 + assert impersonated.status_code == 200 + assert impersonated.json() == {"call": 2} + assert calls["dashboard"] == 2 + + +@pytest.mark.parametrize( + ("method", "path"), + [ + ("GET", "/api/inse-service/authors/A1/company-connections"), + ("GET", "/api/works/v2/classification/work/W1"), + ( + "GET", + "/api/works/v2/author/A1/primary-category-aggregations", + ), + ("POST", "/api/rank/orientation-profiles"), + ], +) +def test_read_only_personalized_endpoints_require_revalidation(method, path): + app, calls = _app_with_counter() + + with TestClient(app) as client: + first = client.request( + method, + path, + headers={"Authorization": "Bearer account"}, + ) + revalidated = client.request( + method, + path, + headers={ + "Authorization": "Bearer account", + "If-None-Match": first.headers["etag"], + }, + ) + + assert first.status_code == 200 + assert first.headers["cache-control"] == "private, no-cache, max-age=0" + assert revalidated.status_code == 304 + assert calls["read_only"] == 1 diff --git a/service/src/main/inse/models/openalex/institution.py b/service/src/main/inse/models/openalex/institution.py index 089013ba..1be99706 100644 --- a/service/src/main/inse/models/openalex/institution.py +++ b/service/src/main/inse/models/openalex/institution.py @@ -25,6 +25,7 @@ from pydantic_core import to_jsonable_python from inse.models.openalex.author_counts_by_year_inner import AuthorCountsByYearInner from inse.models.openalex.author_summary_stats import AuthorSummaryStats +from inse.models.openalex.dehydrated_institution import DehydratedInstitution from inse.models.openalex.institution_geo import InstitutionGeo from inse.models.openalex.institution_ids import InstitutionIds @@ -51,9 +52,10 @@ class Institution(BaseModel): ids: InstitutionIds | None = None counts_by_year: list[AuthorCountsByYearInner] | None = Field(default=None, description="`works_count` and `cited_by_count` for each of the last ten years.") works_api_url: StrictStr | None = Field(default=None, description="A URL that will get you a list of all works affiliated with this institution.") + associated_institutions: list[DehydratedInstitution] | None = Field(default=None, description="Associated institutions list.") created_date: date | None = Field(default=None, description="When this institution was added to OpenAlex (ISO 8601 date).") updated_date: datetime | None = Field(default=None, description="When this institution was last updated (ISO 8601 datetime).") - __properties: ClassVar[list[str]] = ["id", "ror", "display_name", "country_code", "type", "homepage_url", "image_url", "image_thumbnail_url", "display_name_acronyms", "display_name_alternatives", "works_count", "cited_by_count", "summary_stats", "geo", "lineage", "ids", "counts_by_year", "works_api_url", "created_date", "updated_date"] + __properties: ClassVar[list[str]] = ["id", "ror", "display_name", "country_code", "type", "homepage_url", "image_url", "image_thumbnail_url", "display_name_acronyms", "display_name_alternatives", "works_count", "cited_by_count", "summary_stats", "geo", "lineage", "ids", "counts_by_year", "works_api_url", "associated_institutions", "created_date", "updated_date"] @field_validator('type') def type_validate_enum(cls, value): @@ -151,6 +153,7 @@ class Institution(BaseModel): "ids": InstitutionIds.from_dict(obj["ids"]) if obj.get("ids") is not None else None, "counts_by_year": [AuthorCountsByYearInner.from_dict(_item) for _item in obj["counts_by_year"]] if obj.get("counts_by_year") is not None else None, "works_api_url": obj.get("works_api_url"), + "associated_institutions": [DehydratedInstitution.from_dict(_item) for _item in obj["associated_institutions"]] if obj.get("associated_institutions") is not None else None, "created_date": obj.get("created_date"), "updated_date": obj.get("updated_date") }) diff --git a/service/src/main/inse/models/openalex/work.py b/service/src/main/inse/models/openalex/work.py index 31934220..3ad6f785 100644 --- a/service/src/main/inse/models/openalex/work.py +++ b/service/src/main/inse/models/openalex/work.py @@ -94,7 +94,10 @@ class Work(BaseModel): content_url: StrictStr | None = Field(default=None, description="URL for downloading full-text content. Only present when `has_content.pdf` or `has_content.grobid_xml` is true.") created_date: date | None = Field(default=None, description="When this work was added to OpenAlex (ISO 8601 date).") updated_date: datetime | None = Field(default=None, description="When this work was last updated (ISO 8601 datetime).") - __properties: ClassVar[list[str]] = ["id", "doi", "title", "display_name", "publication_year", "publication_date", "type", "language", "cited_by_count", "is_retracted", "is_paratext", "primary_location", "locations", "best_oa_location", "open_access", "authorships", "ids", "biblio", "abstract_inverted_index", "referenced_works", "referenced_works_count", "related_works", "topics", "primary_topic", "keywords", "funders", "awards", "fwci", "citation_normalized_percentile", "cited_by_percentile_year", "counts_by_year", "sustainable_development_goals", "mesh", "indexed_in", "has_content", "content_url", "created_date", "updated_date"] + snippet: StrictStr | None = Field(default=None, description="Passage of the title or abstract containing the searched keyword, with the matches wrapped in ``. Only set by the keyword search, and only when the keyword actually occurs in the text.") + snippet_field: StrictStr | None = Field(default=None, description="Which field `snippet` was taken from: `title` or `abstract`.") + matched_via: list[StrictStr] | None = Field(default=None, description="Names of the topics and OpenAlex keywords that matched the searched keywords. Set by the keyword search so a work matched purely on metadata can explain itself when there is no `snippet`.") + __properties: ClassVar[list[str]] = ["id", "doi", "title", "display_name", "publication_year", "publication_date", "type", "language", "cited_by_count", "is_retracted", "is_paratext", "primary_location", "locations", "best_oa_location", "open_access", "authorships", "ids", "biblio", "abstract_inverted_index", "referenced_works", "referenced_works_count", "related_works", "topics", "primary_topic", "keywords", "funders", "awards", "fwci", "citation_normalized_percentile", "cited_by_percentile_year", "counts_by_year", "sustainable_development_goals", "mesh", "indexed_in", "has_content", "content_url", "created_date", "updated_date", "snippet", "snippet_field", "matched_via"] model_config = ConfigDict( validate_by_name=True, @@ -273,7 +276,10 @@ class Work(BaseModel): "has_content": WorkHasContent.from_dict(obj["has_content"]) if obj.get("has_content") is not None else None, "content_url": obj.get("content_url"), "created_date": obj.get("created_date"), - "updated_date": obj.get("updated_date") + "updated_date": obj.get("updated_date"), + "snippet": obj.get("snippet"), + "snippet_field": obj.get("snippet_field"), + "matched_via": obj.get("matched_via") }) return _obj diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index da4ca3eb..453323bb 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -11,6 +11,12 @@ from inse.exceptions import ElasticsearchException from ..integrations import elasticsearch, llm from ..persons.logic import find_ude_author_by_name, get_author_name_by_id +from ..snippets import ( + FRAGMENT_FIELD, + HIGHLIGHT_TAGS, + SNIPPET_FRAGMENT_CHARS, + snippet_with_context, +) from ..topics.logic import vector_search_topics_batch from .model import ( MatchedTopic, @@ -30,6 +36,19 @@ TOPICS_INDEX = "aktuell_openalex_topics" _SESSION_TOPIC_CACHE: dict[str, list] = {} +PREVIEW_WORD_COUNT = 80 + +CONTENT_HIGHLIGHT = { + "fields": { + "full_content": { + **FRAGMENT_FIELD, + "no_match_size": SNIPPET_FRAGMENT_CHARS, + } + }, + **HIGHLIGHT_TAGS, + "require_field_match": False, +} + KEYWORD_LIMIT = 6 KEYWORD_CONTENT_CHARS = 4000 KEYWORD_SYSTEM_PROMPT = """\ @@ -87,13 +106,6 @@ async def search_news( ) -> NewsPage: offset = (page - 1) * page_size - highlight = { - "fields": {"full_content": {"fragment_size": 200, "number_of_fragments": 1}}, - "pre_tags": [""], - "post_tags": [""], - "encoder": "html", - } - # Filter einmal berechnen (der Relevanz-Filter macht eine ES-Abfrage). clauses = await _filter_clauses(year_from, year_to, relevance_values) exact_query = { @@ -115,7 +127,7 @@ async def search_news( size=page_size, offset=offset, sort=None, - highlight=highlight, + highlight=CONTENT_HIGHLIGHT, ) news_page = await _build_page(response, page, page_size) @@ -142,6 +154,7 @@ async def search_news_by_keywords( year_to: int | None = None, relevance_values: list | None = None, sort_order: str | None = None, + title: str | None = None, ) -> NewsPage: """Searches the news for the keywords of a keywords-search run. @@ -177,6 +190,9 @@ async def search_news_by_keywords( return _empty_page(page, page_size) clauses = await _filter_clauses(year_from, year_to, relevance_values) + if title and title.strip(): + clauses.append({"match_phrase_prefix": {"maintitle": title.strip()}}) + query = { "bool": { "should": should, @@ -185,13 +201,6 @@ async def search_news_by_keywords( } } - highlight = { - "fields": {"full_content": {"fragment_size": 200, "number_of_fragments": 1}}, - "pre_tags": [""], - "post_tags": [""], - "encoder": "html", - } - sort = [{"date_full": sort_order}] if sort_order in ("asc", "desc") else None response = await _run_search( @@ -200,7 +209,7 @@ async def search_news_by_keywords( size=page_size, offset=(page - 1) * page_size, sort=sort, - highlight=None if wanted_topic_ids else highlight, + highlight=None if wanted_topic_ids else CONTENT_HIGHLIGHT, ) news_page = await _build_page(response, page, page_size) @@ -761,7 +770,7 @@ def _parse_hit(hit: dict) -> NewsArticle: fragments = hit.get("highlight", {}).get("full_content") if fragments: - snippet = fragments[0] + snippet = snippet_with_context(source.get("full_content"), fragments) else: snippet = _make_preview(source) @@ -776,14 +785,13 @@ def _parse_hit(hit: dict) -> NewsArticle: def _make_preview(source: dict) -> str | None: - text = source.get("intro_content") or source.get("full_content") + text = source.get("full_content") or source.get("intro_content") if not text: return None words = text.split() - PREVIEW_WORD_COUNT = 10 preview = " ".join(words[:PREVIEW_WORD_COUNT]) if len(words) > PREVIEW_WORD_COUNT: preview = preview + " …" @@ -874,3 +882,4 @@ async def _related_search_terms(query_text: str) -> list: terms.append(term) return terms + diff --git a/service/src/main/inse/news/service.py b/service/src/main/inse/news/service.py index eeeeb564..bfc6d105 100644 --- a/service/src/main/inse/news/service.py +++ b/service/src/main/inse/news/service.py @@ -147,6 +147,10 @@ async def search_news_by_keywords( pattern="^(asc|desc)$", ), ] = None, + title: Annotated[ + str | None, + Query(description="Narrows the results to articles whose title matches this text."), + ] = None, ): return await logic.search_news_by_keywords( keywords=keywords or [], @@ -159,6 +163,7 @@ async def search_news_by_keywords( year_from=year_from, year_to=year_to, relevance_values=_parse_relevance(relevance), + title=title, ) diff --git a/service/src/main/inse/organization_management/service.py b/service/src/main/inse/organization_management/service.py index 072db92a..6b8b4c10 100644 --- a/service/src/main/inse/organization_management/service.py +++ b/service/src/main/inse/organization_management/service.py @@ -352,6 +352,12 @@ async def get_institution_associations( institution_ids: list[str], ) -> list[InstitutionAssociationsResponse]: _require_super_admin(access_token) + return await resolve_institution_associations(institution_ids) + + +async def resolve_institution_associations( + institution_ids: list[str], +) -> list[InstitutionAssociationsResponse]: clean_ids = _normalize_institution_ids(institution_ids) if not clean_ids: return [] diff --git a/service/src/main/inse/patents/org/elastic_search_client.py b/service/src/main/inse/patents/org/elastic_search_client.py index 0bee7f9e..8d8d6cd2 100644 --- a/service/src/main/inse/patents/org/elastic_search_client.py +++ b/service/src/main/inse/patents/org/elastic_search_client.py @@ -251,7 +251,7 @@ class OrgPatentsSearchClient: async def search_by_institution( self, - institution_id: str, + institution_id: str | list[str], match_type: MatchTypeFilter = "all", page: int = 0, size: int = DEFAULT_PAGE_SIZE, @@ -259,8 +259,16 @@ class OrgPatentsSearchClient: from_year: int | None = None, to_year: int | None = None, ) -> tuple[list[OrgPatentEntry], int]: - short_id = institution_id.replace("https://openalex.org/", "").upper() - filters: list[dict[str, Any]] = [{"term": {"institution_id": short_id}}] + institution_ids = ( + institution_id if isinstance(institution_id, list) else [institution_id] + ) + short_ids = [ + value.replace("https://openalex.org/", "").upper() + for value in institution_ids + ] + filters: list[dict[str, Any]] = [ + {"terms": {"institution_id": short_ids}} + ] if match_type == "institution": filters.append({"terms": {"match_type": ["institution", "both"]}}) diff --git a/service/src/main/inse/persons/bio.py b/service/src/main/inse/persons/bio.py new file mode 100644 index 00000000..28c5d4a4 --- /dev/null +++ b/service/src/main/inse/persons/bio.py @@ -0,0 +1,186 @@ +""" +Bio generation for persons / authors. +""" + +import json +import logging +import time + +from pydantic import ValidationError + +from inse.exceptions import NotFoundException, UpstreamAPIException +from inse.integrations import elasticsearch +from inse.model import ESIndex +from inse.persons.model import PersonBio + +from .. import config +from ..integrations import llm + +logger = logging.getLogger(__name__) + + +async def _fetch_author_display_name(author_id: str) -> str | None: + query = { + "query_string": { + "default_field": "_id", + "query": author_id, + } + } + + response = await elasticsearch.search( + index=ESIndex.OPENALEX_AUTHORS, + query=query, + source=["display_name"], + ) + + hits = response.get("hits", {}).get("hits", []) + + if not hits: + return None + + return hits[0].get("_source", {}).get("display_name") + + +async def _fetch_works_and_topics(author_id: str) -> tuple[list, list]: + WORK_SOURCE_FIELDS = [ + "title", + "display_name", + "abstract", + "cited_by_count", + "primary_topic", + ] + + author_url = f"https://openalex.org/{author_id.strip()}" + + authorship_query = { + "nested": { + "path": "authorships", + "query": { + "bool": { + "filter": [{"term": {"authorships.author.id": author_url}}], + } + }, + } + } + + body = { + "size": 100, + "sort": [{"cited_by_count": {"order": "desc"}}], + "_source": WORK_SOURCE_FIELDS, + "query": authorship_query, + "aggs": { + "primary_topics": { + "terms": {"field": "primary_topic.id", "size": 5}, + "aggs": { + "topic_name": { + "top_hits": { + "size": 1, + "_source": ["primary_topic.display_name"], + } + } + }, + } + }, + } + + response = await elasticsearch.search( + index=config.settings.openalex_works_search_index, + body=body, + ) + + works = [] + for hit in response.get("hits", {}).get("hits", []): + works.append(hit.get("_source", {})) + + topics = [] + buckets = ( + response.get("aggregations", {}).get("primary_topics", {}).get("buckets", []) + ) + for bucket in buckets: + topic_hits = bucket.get("topic_name", {}).get("hits", {}).get("hits", []) + display_name = None + if topic_hits: + primary_topic = topic_hits[0].get("_source", {}).get("primary_topic", {}) + display_name = primary_topic.get("display_name") + topics.append( + { + "id": bucket.get("key"), + "display_name": display_name, + "count": bucket.get("doc_count"), + } + ) + + return works, topics + + +def _build_papers(works: list) -> list: + papers = [] + for work in works: + name = work.get("title") or work.get("display_name") + abstract = work.get("abstract") + papers.append( + { + "name": name, + "abstract": abstract, + "stats": { + "cited_by_count": work.get("cited_by_count"), + }, + } + ) + return papers + + +async def get_data_for_bio(author_id: str) -> dict | None: + display_name = await _fetch_author_display_name(author_id) + if display_name is None: + return None + + works, top_topics = await _fetch_works_and_topics(author_id) + papers = _build_papers(works) + + author_data = { + "display_name": display_name, + "topics": top_topics, + "papers": papers, + } + return author_data + + +async def generate_person_bio(author_id: str) -> str: + start_time = time.time() + author_data = await get_data_for_bio(author_id) + if author_data is None: + raise NotFoundException(f"No person found for author ID {author_id}.") + + person_json = json.dumps(author_data, ensure_ascii=False) + + system_prompt = """\ + Beschreibe in zwei Sätzen das Hauptforschungsfeld des Autors. Formuliere dabei allgemeinverständlich, sodass auch Personen ohne Fachwissen einen Einblick in die Forschung gewinnen. Nenne keine konkreten Publikationen oder Einzelwerke, sondern konzentriere dich auf die übergeordneten Forschungsinteressen und Themen. Verzichte auf bloße Aufzählungen und verbinde die Informationen zu einem flüssigen Text. + Beschreibe anschließend in ein bis zwei Sätzen die wirtschaftliche Relevanz der Forschung anhand von Anwendungen, Technologien oder Branchen, die davon profitieren könnten. + Verwende insgesamt maximal 100 bis 120 Wörter. Formuliere die Antwort so, dass sie ohne weitere Anpassungen direkt als Kurzbiografie verwendet werden kann. Verwende keine Superlative oder übertriebene Formulierungen, sondern bleibe sachlich und informativ. Gebe den Text als One-Liner zurück, ohne Zeilenumbrüche oder Aufzählungen. Verwende keine Gedankenstriche (– oder —) zur Gliederung von Sätzen. Formuliere stattdessen mit Kommas, Klammern oder zwei getrennten Sätzen. + Gib ausschließlich ein JSON-Objekt zurück, das den Text im Feld "bio" enthält. + """ + + user_prompt = f"Daten zur Person:\n{person_json}" + + response = await llm.call( + system_prompt=system_prompt, + user_prompt=user_prompt, + json_schema=PersonBio.model_json_schema(), + schema_name="bio", + temperature=0.8, + top_p=0.95, + ) + + try: + bio = PersonBio.model_validate_json(response).bio + except ValidationError as error: + logger.warning( + f"Bio generation for author {author_id} returned no valid bio: {response}" + ) + raise UpstreamAPIException("Bio generation failed.") from error + + elapsed_time = time.time() - start_time + logger.info(f"Bio generation for author {author_id} took {elapsed_time:.2f} seconds") + + return bio diff --git a/service/src/main/inse/persons/logic.py b/service/src/main/inse/persons/logic.py index a75ae61a..f6355cf8 100644 --- a/service/src/main/inse/persons/logic.py +++ b/service/src/main/inse/persons/logic.py @@ -4,13 +4,10 @@ Business logic for persons / authors. """ import hashlib -import json import logging import time from datetime import datetime -from pydantic import ValidationError - from inse.exceptions import ( BadRequestException, ElasticsearchException, @@ -26,13 +23,11 @@ from inse.persons.model import ( CareerMetrics, CustomAuthor, CustomAuthorsListResponse, - PersonBio, ) from inse.persons.query_builder import build_authors_search_rescored from inse.works.logic import enrich_topic_descriptions from .. import config, util -from ..integrations import llm logger = logging.getLogger(__name__) INDEX_NAME = "openalex-authors" @@ -220,100 +215,6 @@ async def count_authors_by_last_name(last_name: str) -> int: return await _count_authors(query) -async def _fetch_author_display_name(author_id: str) -> str | None: - query = { - "query_string": { - "default_field": "_id", - "query": author_id, - } - } - - response = await elasticsearch.search( - index=INDEX_NAME, - query=query, - source=["display_name"], - ) - - hits = response.get("hits", {}).get("hits", []) - - if not hits: - return None - - return hits[0].get("_source", {}).get("display_name") - - -async def _fetch_works_and_topics(author_id: str) -> tuple[list, list]: - WORK_SOURCE_FIELDS = [ - "title", - "display_name", - "abstract", - "cited_by_count", - "primary_topic", - ] - - author_url = f"https://openalex.org/{author_id.strip()}" - - authorship_query = { - "nested": { - "path": "authorships", - "query": { - "bool": { - "filter": [{"term": {"authorships.author.id": author_url}}], - } - }, - } - } - - body = { - "size": 100, - "sort": [{"cited_by_count": {"order": "desc"}}], - "_source": WORK_SOURCE_FIELDS, - "query": authorship_query, - "aggs": { - "primary_topics": { - "terms": {"field": "primary_topic.id", "size": 5}, - "aggs": { - "topic_name": { - "top_hits": { - "size": 1, - "_source": ["primary_topic.display_name"], - } - } - }, - } - }, - } - - response = await elasticsearch.search( - index=config.settings.openalex_works_search_index, - body=body, - ) - - works = [] - for hit in response.get("hits", {}).get("hits", []): - works.append(hit.get("_source", {})) - - topics = [] - buckets = ( - response.get("aggregations", {}).get("primary_topics", {}).get("buckets", []) - ) - for bucket in buckets: - topic_hits = bucket.get("topic_name", {}).get("hits", {}).get("hits", []) - display_name = None - if topic_hits: - primary_topic = topic_hits[0].get("_source", {}).get("primary_topic", {}) - display_name = primary_topic.get("display_name") - topics.append( - { - "id": bucket.get("key"), - "display_name": display_name, - "count": bucket.get("doc_count"), - } - ) - - return works, topics - - async def _get_publication_years_for_author(author_id: str) -> list[int]: author_url = f"https://openalex.org/{author_id.strip()}" @@ -427,79 +328,6 @@ async def get_career_metrics_for_author(author_id: str) -> CareerMetrics: return _compute_career_metrics(publication_years) -def _build_papers(works: list) -> list: - papers = [] - for work in works: - name = work.get("title") or work.get("display_name") - abstract = work.get("abstract") - papers.append( - { - "name": name, - "abstract": abstract, - "stats": { - "cited_by_count": work.get("cited_by_count"), - }, - } - ) - return papers - - -async def get_data_for_bio(author_id: str) -> dict | None: - display_name = await _fetch_author_display_name(author_id) - if display_name is None: - return None - - works, top_topics = await _fetch_works_and_topics(author_id) - papers = _build_papers(works) - - author_data = { - "display_name": display_name, - "topics": top_topics, - "papers": papers, - } - return author_data - - -async def generate_person_bio( - author_id: str, include: set[str] | None = None -) -> str: - start_time = time.time() - author_data = await get_data_for_bio(author_id) - if author_data is None: - return "No person found." - - person_json = json.dumps(author_data, ensure_ascii=False) - - system_prompt = """\ - Beschreibe in zwei Sätzen das Hauptforschungsfeld des Autors. Formuliere dabei allgemeinverständlich, sodass auch Personen ohne Fachwissen einen Einblick in die Forschung gewinnen. Nenne keine konkreten Publikationen oder Einzelwerke, sondern konzentriere dich auf die übergeordneten Forschungsinteressen und Themen. Verzichte auf bloße Aufzählungen und verbinde die Informationen zu einem flüssigen Text. - Beschreibe anschließend in ein bis zwei Sätzen die wirtschaftliche Relevanz der Forschung anhand von Anwendungen, Technologien oder Branchen, die davon profitieren könnten. - Verwende insgesamt maximal 100 bis 120 Wörter. Formuliere die Antwort so, dass sie ohne weitere Anpassungen direkt als Kurzbiografie verwendet werden kann. Verwende keine Superlative oder übertriebene Formulierungen, sondern bleibe sachlich und informativ. Gebe den Text als One-Liner zurück, ohne Zeilenumbrüche oder Aufzählungen. Verwende keine Gedankenstriche (– oder —) zur Gliederung von Sätzen. Formuliere stattdessen mit Kommas, Klammern oder zwei getrennten Sätzen. - Gib ausschließlich ein JSON-Objekt zurück, das den Text im Feld "bio" enthält. - """ - - user_prompt = f"Daten zur Person:\n{person_json}" - - response = await llm.call( - system_prompt=system_prompt, - user_prompt=user_prompt, - json_schema=PersonBio.model_json_schema(), - schema_name="bio", - temperature=0.8, - top_p=0.95, - ) - - try: - bio = PersonBio.model_validate_json(response).bio - except ValidationError: - logger.warning(f"Bio generation for author {author_id} returned no valid JSON: {response}") - bio = "Etwas ist schiefgelaufen." - - elapsed_time = time.time() - start_time - logger.info(f"Bio generation for author {author_id} took {elapsed_time:.2f} seconds") - - return bio - - async def get_person_by_id( author_id: str, include: str | None = None ) -> CustomAuthorsListResponse: diff --git a/service/src/main/inse/persons/service.py b/service/src/main/inse/persons/service.py index 3f66255c..d95ca046 100644 --- a/service/src/main/inse/persons/service.py +++ b/service/src/main/inse/persons/service.py @@ -9,7 +9,7 @@ from fastapi import APIRouter, HTTPException, Path, Query, status from inse.models.openalex.authors_list_response import AuthorsListResponse -from . import logic, model +from . import bio as bio_logic, logic, model router = APIRouter( prefix="/api/inse-service", @@ -32,23 +32,7 @@ async def search_persons( query: Annotated[ str, Query(description="Search query (e.g., Arman AND Arzani)") ] = None, - include: Annotated[ - str | None, - Query( - description=( - "Comma-separated include tags: topics_full, topic_share, summary_stats, ids, " - "last_known_institutions, sources, counts_by_year, works_api_url, dates, " - "cited_by_count_boost" - ), - example="topics_full,topic_share", - ), - ] = None, ): - include_set = ( - {tag.strip().lower() for tag in include.split(",") if tag.strip()} - if include - else None - ) return await logic.search_persons(author_id, query) @@ -62,20 +46,8 @@ async def generate_person_bio( author_id: Annotated[ str, Query(description="OpenAlex author ID (e.g., A5093075883)") ], - include: Annotated[ - str | None, - 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 = await logic.generate_person_bio(author_id, include_set) + bio = await bio_logic.generate_person_bio(author_id) return model.PersonBio(bio=bio) @router.get( @@ -96,7 +68,7 @@ async def get_person_by_id( "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, " "last_known_institutions, ..." ), - example="topics_full,topic_share", + examples="topics_full,topic_share", ), ] = None, ): @@ -119,11 +91,11 @@ async def search_persons_by_name( "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, " "last_known_institutions, ..." ), - example="topics_full,topic_share", + examples="topics_full,topic_share", ), ], - limit:Annotated[int | None, Query(description=("Limit of search page results"),example ="2")]= None, - page_offset : Annotated[int | None, Query(description=("Offset of the result page"),example="2")] = None, + limit:Annotated[int | None, Query(description=("Limit of search page results"),examples ="2")]= None, + page_offset : Annotated[int | None, Query(description=("Offset of the result page"),examples="2")] = None, ): return await logic.search_persons_by_name(author_name=author_name, include=include, page_offset=page_offset, limit=limit) @@ -141,7 +113,7 @@ async def search_persons_autocomplete( "Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, " "last_known_institutions, ..." ), - example="topics_full,topic_share" + examples="topics_full,topic_share" )]): return await logic.search_persons_autocomplete(author_name=author_name, include=include) @@ -181,7 +153,7 @@ async def search_persons_list( str | None, Query( description="Comma-separated include tags", - example="topics_full,topic_share", + examples="topics_full,topic_share", ), ] = None, year_filter_enabled: Annotated[ diff --git a/service/src/main/inse/persons/test_bio.py b/service/src/main/inse/persons/test_bio.py new file mode 100644 index 00000000..8f575de4 --- /dev/null +++ b/service/src/main/inse/persons/test_bio.py @@ -0,0 +1,48 @@ +import pytest + +from inse import config +from inse.exceptions import NotFoundException +from inse.persons import service + + +@pytest.fixture() +def anyio_backend(): + return "asyncio" + + +def elasticsearch_configured(): + return bool( + config.settings.elasticsearch_url and config.settings.elasticsearch_api_key + ) + + +def llm_configured(): + return bool( + config.settings.llm_api_url + and config.settings.llm_api_key + and config.settings.llm_model + ) + + +requires_elasticsearch = pytest.mark.skipif( + not elasticsearch_configured(), reason="Elasticsearch is not configured" +) +requires_elasticsearch_and_llm = pytest.mark.skipif( + not (elasticsearch_configured() and llm_configured()), + reason="Elasticsearch and/or LLM are not configured", +) + + +@pytest.mark.anyio +@requires_elasticsearch_and_llm +async def test_bio_is_generated_for_person(): + response = await service.generate_person_bio(author_id="A5093075883") + + assert len(response.bio) >= 10, f"bio is too short: {response.bio!r}" + + +@pytest.mark.anyio +@requires_elasticsearch +async def test_bio_generation_fails_for_unknown_author(): + with pytest.raises(NotFoundException): + await service.generate_person_bio(author_id="A000") diff --git a/service/src/main/inse/projects/router.py b/service/src/main/inse/projects/router.py index 69aaae66..963c1f96 100644 --- a/service/src/main/inse/projects/router.py +++ b/service/src/main/inse/projects/router.py @@ -30,6 +30,7 @@ from inse.projects.model import ( SortDirection, ) from inse.tags import Tags +from inse.database import SessionDep from inse.auth.service import can_fetch_gdpr_relevant_data from fastapi import HTTPException as HttpException @@ -78,26 +79,36 @@ async def search_bund_projects( "model": DfgProjectPage, }, status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, - status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"}, + status.HTTP_403_FORBIDDEN: { + "description": "Access denied for the provided institution ID" + }, }, response_model_by_alias=False, ) async def get_dfg_projects( - access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep], + session: SessionDep, + access_token_metadata: Annotated[ + AccessTokenMetadata, CurrentUserAccessTokenPayloadDep + ], institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], raw_oa_institution_id: Annotated[ str | None, Query(description="The openalex institution ID to filter by.") ] = None, - author_id: Annotated[str | None, Query(description="The openalex author ID to filter by.")] = None, - author_filter_ids: Annotated[list[str] | None, Query(description="The dfg author IDs to filter by.")] = None, - institution_ids: Annotated[list[str] | None, Query(description="The institution IDs to filter by.")] = None, - title: Annotated[ - str | None, Query(description="The title to filter by.") + author_id: Annotated[ + str | None, Query(description="The openalex author ID to filter by.") ] = None, + author_filter_ids: Annotated[ + list[str] | None, Query(description="The dfg author IDs to filter by.") + ] = None, + institution_ids: Annotated[ + list[str] | None, Query(description="The institution IDs to filter by.") + ] = None, + title: Annotated[str | None, Query(description="The title to filter by.")] = None, keywords: Annotated[ - list[str] | None, Query(description="Raw keywords to search in title/abstract/subject fields.") + list[str] | None, + Query(description="Raw keywords to search in title/abstract/subject fields."), ] = None, topic_ids: Annotated[ list[str] | None, Query(description="The openalex topic IDs to filter by.") @@ -106,12 +117,15 @@ async def get_dfg_projects( list[str] | None, Query( description="Additional topic IDs to merge into the fuzzy topic-id resolution " - "(union with topic_ids). Only used when fuzzy=True." + "(union with topic_ids). Only used when fuzzy=True." ), ] = None, - funding_start_years: Annotated[list[str] | None, Query(description="The funding start years to filter by.")] = None, - funding_end_years: Annotated[list[str] | None, Query(description="The funding end years to filter by.")] = None, - + funding_start_years: Annotated[ + list[str] | None, Query(description="The funding start years to filter by.") + ] = None, + funding_end_years: Annotated[ + list[str] | None, Query(description="The funding end years to filter by.") + ] = None, page: Annotated[int, Query(description="The page number.", ge=0)] = 0, size: Annotated[int, Query(description="The page size.", ge=1)] = 20, sort_by: Annotated[str, Query(description="The field to sort by.")] = "", @@ -120,9 +134,10 @@ async def get_dfg_projects( ] = "asc", fuzzy: Annotated[ bool, - Query(description="Use topic_id resolution if True, otherwise use raw keyword search."), + Query( + description="Use topic_id resolution if True, otherwise use raw keyword search." + ), ] = False, - ) -> DfgProjectPage: logger.debug( "Received request to get DFG projects for author_id=%s, author_filter_ids=%s, " @@ -144,8 +159,13 @@ async def get_dfg_projects( sort_direction, fuzzy, ) - if (author_id or raw_oa_institution_id): - is_allowed = await can_fetch_gdpr_relevant_data(access_token = access_token_metadata, raw_oa_author_id = author_id, raw_oa_institution_id = raw_oa_institution_id) + if author_id or raw_oa_institution_id: + is_allowed = await can_fetch_gdpr_relevant_data( + session=session, + access_token=access_token_metadata, + raw_oa_author_id=author_id, + raw_oa_institution_id=raw_oa_institution_id, + ) if not is_allowed: raise HttpException( status_code=403, @@ -170,6 +190,7 @@ async def get_dfg_projects( fuzzy=fuzzy, ) + @router.get( "/dfg/{id}", summary="Get a single DFG project.", @@ -204,12 +225,17 @@ async def get_single_dfg_project( "model": BundProjectPage, }, status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, - status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"}, + status.HTTP_403_FORBIDDEN: { + "description": "Access denied for the provided institution ID" + }, }, response_model_by_alias=False, ) async def search_bund_projects( - access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep], + session: SessionDep, + access_token_metadata: Annotated[ + AccessTokenMetadata, CurrentUserAccessTokenPayloadDep + ], institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], @@ -262,11 +288,18 @@ async def search_bund_projects( ] = "asc", fuzzy: Annotated[ bool, - Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."), + Query( + description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search." + ), ] = False, ) -> BundProjectPage: - if (raw_oa_institution_id): - is_allowed = await can_fetch_gdpr_relevant_data(access_token = access_token_metadata, raw_oa_author_id = None, raw_oa_institution_id = raw_oa_institution_id) + if raw_oa_institution_id: + is_allowed = await can_fetch_gdpr_relevant_data( + session=session, + access_token=access_token_metadata, + raw_oa_author_id=None, + raw_oa_institution_id=raw_oa_institution_id, + ) if not is_allowed: raise HttpException( status_code=403, @@ -288,9 +321,10 @@ async def search_bund_projects( size=size, sort_by=sort_by, sort_direction=sort_direction, - fuzzy=fuzzy + fuzzy=fuzzy, ) - + + @router.get( "/bund/{id}", summary="Get a single BUND project.", @@ -313,6 +347,7 @@ async def get_single_bund_project( project_id=id, ) + ######## from inse.projects.model import EuCordisProjectSearchPage, EuCordisProjectType from inse.projects.service import search_eu_cordis_projects @@ -334,12 +369,17 @@ from inse.projects.service import search_eu_cordis_projects "model": EuCordisProjectSearchPage, }, status.HTTP_404_NOT_FOUND: {"description": "Institution not found"}, - status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"}, + status.HTTP_403_FORBIDDEN: { + "description": "Access denied for the provided institution ID" + }, }, response_model_by_alias=False, ) async def search_eu_cordis_projects_endpoint( - access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep], + session: SessionDep, + access_token_metadata: Annotated[ + AccessTokenMetadata, CurrentUserAccessTokenPayloadDep + ], institutions_search_client: Annotated[ InstitutionsSearchClient, Depends(get_institutions_search_client) ], @@ -353,15 +393,21 @@ async def search_eu_cordis_projects_endpoint( ] = None, author_ids: Annotated[ list[str] | None, - Query(description="Additional OpenAlex author IDs to filter by. All selected authors must match."), + Query( + description="Additional OpenAlex author IDs to filter by. All selected authors must match." + ), ] = None, organization_ids: Annotated[ list[str] | None, - Query(description="CORDIS organisation IDs. All selected organizations must match."), + Query( + description="CORDIS organisation IDs. All selected organizations must match." + ), ] = None, organization_names: Annotated[ list[str] | None, - Query(description="CORDIS organization names. All selected organizations must match."), + Query( + description="CORDIS organization names. All selected organizations must match." + ), ] = None, project_types: Annotated[ list[EuCordisProjectType] | None, @@ -416,9 +462,10 @@ async def search_eu_cordis_projects_endpoint( ] = "asc", fuzzy: Annotated[ bool, - Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."), + Query( + description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search." + ), ] = False, - ) -> EuCordisProjectSearchPage: logger.debug( "Received EU CORDIS search request: raw_oa_institution_id=%s, " @@ -450,8 +497,13 @@ async def search_eu_cordis_projects_endpoint( sort_direction, fuzzy, ) - if (author_id or raw_oa_institution_id): - is_allowed = await can_fetch_gdpr_relevant_data(access_token = access_token_metadata, raw_oa_author_id = author_id, raw_oa_institution_id = raw_oa_institution_id) + if author_id or raw_oa_institution_id: + is_allowed = await can_fetch_gdpr_relevant_data( + session=session, + access_token=access_token_metadata, + raw_oa_author_id=author_id, + raw_oa_institution_id=raw_oa_institution_id, + ) if not is_allowed: raise HttpException( status_code=403, @@ -482,6 +534,7 @@ async def search_eu_cordis_projects_endpoint( fuzzy=fuzzy, ) + @router.get( "/eu/{id}", summary="Get a single EU Cordis project.", @@ -494,27 +547,29 @@ async def search_eu_cordis_projects_endpoint( }, status.HTTP_404_NOT_FOUND: { "description": "Project not found", - "model": EuCordisProjectResponse + "model": EuCordisProjectResponse, }, status.HTTP_500_INTERNAL_SERVER_ERROR: { "description": "Internal server error", - "model": EuCordisProjectResponse - } + "model": EuCordisProjectResponse, + }, }, ) async def get_single_eu_cordis_project( - id: Annotated[str, Path(description="The ID of the EU Cordis project to retrieve.")], + id: Annotated[ + str, Path(description="The ID of the EU Cordis project to retrieve.") + ], ) -> EuCordisProjectResponse: """ Get a single EU Cordis project by ID. Returns a wrapper response containing the project data or error information. """ logger.debug(f"Received request to get single EU Cordis project for id={id}") - + try: # Get the project from the service project = await projects_service.get_single_eu_cordis_project(project_id=id) - + # Check if project exists if project is None: logger.warning(f"Project with ID {id} not found") @@ -522,9 +577,9 @@ async def get_single_eu_cordis_project( success=False, project_type=None, eu_project_data=None, - error=f"Project with ID {id} not found" + error=f"Project with ID {id} not found", ) - + # Determine the project type if isinstance(project, Fp7ProjectDetails): project_type = "fp7" @@ -539,24 +594,21 @@ async def get_single_eu_cordis_project( success=False, project_type=None, eu_project_data=None, - error=f"Unknown project type for ID {id}" + error=f"Unknown project type for ID {id}", ) - + # Return success with the project data return EuCordisProjectResponse( - success=True, - project_type=project_type, - eu_project_data=project, - error=None + success=True, project_type=project_type, eu_project_data=project, error=None ) - + except Exception as e: logger.error(f"Error retrieving project with ID {id}: {e!s}", exc_info=True) return EuCordisProjectResponse( success=False, project_type=None, eu_project_data=None, - error=f"Internal server error: {e!s}" + error=f"Internal server error: {e!s}", ) @@ -623,7 +675,9 @@ async def get_institution_bund_projects_funding_over_time( ] = None, fuzzy: Annotated[ bool, - Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."), + Query( + description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search." + ), ] = False, ) -> InstitutionFunderSummary: return await projects_service.get_institution_bund_projects_funding_over_time( @@ -674,15 +728,21 @@ async def get_institution_cordis_eu_projects_funding_over_time( ] = None, author_ids: Annotated[ list[str] | None, - Query(description="Additional OpenAlex author IDs to filter by. All selected authors must match."), + Query( + description="Additional OpenAlex author IDs to filter by. All selected authors must match." + ), ] = None, organization_ids: Annotated[ list[str] | None, - Query(description="CORDIS organisation IDs. All selected organizations must match."), + Query( + description="CORDIS organisation IDs. All selected organizations must match." + ), ] = None, organization_names: Annotated[ list[str] | None, - Query(description="CORDIS organization names. All selected organizations must match."), + Query( + description="CORDIS organization names. All selected organizations must match." + ), ] = None, project_types: Annotated[ list[EuCordisProjectType] | None, @@ -730,7 +790,9 @@ async def get_institution_cordis_eu_projects_funding_over_time( ] = None, fuzzy: Annotated[ bool, - Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."), + Query( + description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search." + ), ] = False, ) -> InstitutionFunderSummary: return await projects_service.get_institution_cordis_eu_projects_funding_over_time( @@ -777,9 +839,7 @@ async def search_projects( description="The set of project types to filter by (e.g., 'bund', 'eu', 'dfg'). If not provided, projects of all types will be included." ), ] = None, - title: Annotated[ - str | None, Query(description="The title to filter by.") - ] = None, + title: Annotated[str | None, Query(description="The title to filter by.")] = None, sort_by: Annotated[ ProjectsSortBy, Query(description="The field to sort by.") ] = ProjectsSortBy.TITLE, @@ -794,4 +854,4 @@ async def search_projects( title=title, sort_by=sort_by, sort_direction=sort_direction, - ) \ No newline at end of file + ) diff --git a/service/src/main/inse/projects/service.py b/service/src/main/inse/projects/service.py index 331cc6c8..f17e6b6b 100644 --- a/service/src/main/inse/projects/service.py +++ b/service/src/main/inse/projects/service.py @@ -190,6 +190,7 @@ async def get_dfg_projects( skip_enrichment: bool = False, active_from_year: int | None = None, active_to_year: int | None = None, + institution_aliases: list[str] | None = None, ) -> DfgProjectPage: logger.debug( "Fetching DFG projects for author_id=%s, author_filter_ids=%s, " @@ -251,18 +252,18 @@ async def get_dfg_projects( "No author names found for author_filter_ids=%s", author_filter_ids_int, ) - institution_aliases = [] + resolved_institution_aliases = list(institution_aliases or []) if raw_oa_institution_id: if institutions_search_client is None: raise ValueError( "institutions_search_client must be provided when raw_oa_institution_id is set" ) - institution_aliases = ( + resolved_institution_aliases.extend( await institutions_search_client.get_institution_aliases_by_oa_institution_id( raw_oa_institution_id ) ) - if not institution_aliases: + if not resolved_institution_aliases: return DfgProjectPage( elements=[], page=page, @@ -272,7 +273,7 @@ async def get_dfg_projects( return await projects_search_client.search_dfg_projects( page=page, size=size, - institution_aliases=institution_aliases, + institution_aliases=resolved_institution_aliases, project_ids=author_project_ids, names=filter_names or [], institution_ids=institution_ids_int, @@ -465,8 +466,9 @@ async def search_bund_projects_with_filters( fuzzy: bool = False, active_from_year: int | None = None, active_to_year: int | None = None, + oa_institution_aliases: list[str] | None = None, ) -> BundProjectPage: - institution_aliases = [] + institution_aliases = list(oa_institution_aliases or []) if raw_oa_institution_id: if institutions_search_client is None: raise ValueError( diff --git a/service/src/main/inse/ranking/logic.py b/service/src/main/inse/ranking/logic.py index 8313217f..1340f2ee 100644 --- a/service/src/main/inse/ranking/logic.py +++ b/service/src/main/inse/ranking/logic.py @@ -2,7 +2,6 @@ import asyncio import logging -from dataclasses import dataclass from math import floor from time import time from typing import Any @@ -21,7 +20,6 @@ from .model import ( AuthorTopicStats, CareerStage, CompanyStatusFilter, - FilterType, KeywordOperator, PublicationType, PublicationTypeCount, @@ -69,59 +67,88 @@ async def _get_author_ids_from_institution(institution_id: str) -> list[str]: -@dataclass(frozen=True) -class MatchConfig: - """Where a topic filter matches on a work: keyword display names or topic ids.""" - - path: str - match_field: str - score_field: str - - -_KEYWORD_MATCH = MatchConfig( - path="keywords", - match_field="keywords.display_name.keyword", - score_field="keywords.score", -) -_TOPIC_MATCH = MatchConfig( - path="topics", - match_field="topics.display_name.keyword", - score_field="topics.score", -) - - -def _match_config(filter_type: FilterType) -> MatchConfig: - """Resolves the request's filter_type into the single set of fields to match on.""" - if filter_type == FilterType.TOPIC: - return _TOPIC_MATCH - return _KEYWORD_MATCH - - -def _keyword_clause(value: str, config: MatchConfig = _KEYWORD_MATCH) -> dict: - """A single nested clause that matches one keyword/topic value on a work.""" +def _topics_nested_clause(should_clauses: list[dict]) -> dict: + """Wraps should-clauses on the nested topics of a work.""" return { "nested": { - "path": config.path, + "path": "topics", "query": { - "term": {config.match_field: value}, + "bool": { + "should": should_clauses, + "minimum_should_match": 1, + }, }, }, } +def _topic_id_clause(topic_id: str) -> dict: + """Matches one OpenAlex topic id against a work (fuzzy mode). + + A work matches when the topic is either its primary topic or one of its + other topics. + """ + return { + "bool": { + "should": [ + _topics_nested_clause([{"term": {"topics.id": topic_id}}]), + {"term": {"primary_topic.id": topic_id}}, + ], + "minimum_should_match": 1, + }, + } + + +def _keyword_clause(keyword: str) -> dict: + """Matches one raw keyword as a phrase against a work (non-fuzzy mode). + + The keyword has to occur as a phrase in at least one of the work's own text + fields or in one of the names of its topic hierarchy. + """ + return { + "bool": { + "should": [ + { + "nested": { + "path": "keywords", + "query": { + "match_phrase": {"keywords.display_name": keyword}, + }, + }, + }, + {"match_phrase": {"primary_topic.display_name": keyword}}, + {"match_phrase": {"title": keyword}}, + {"match_phrase": {"abstract": keyword}}, + _topics_nested_clause( + [ + {"match_phrase": {"topics.display_name": keyword}}, + {"match_phrase": {"topics.field.display_name": keyword}}, + {"match_phrase": {"topics.subfield.display_name": keyword}}, + {"match_phrase": {"topics.domain.display_name": keyword}}, + ] + ), + ], + "minimum_should_match": 1, + }, + } + + def _build_keyword_query( keywords: list[str], operator: KeywordOperator, - config: MatchConfig = _KEYWORD_MATCH, + fuzzy: bool = False, ) -> dict: """Combines the keyword/topic clauses according to the operator. - AND: a work must carry all values (every clause is required). - OR: a work must carry at least one of the values. + AND: a work must match all values (every clause is required). + OR: a work must match at least one of the values. """ clauses = [] for keyword in keywords: - clauses.append(_keyword_clause(keyword, config)) + if fuzzy: + clauses.append(_topic_id_clause(keyword)) + else: + clauses.append(_keyword_clause(keyword)) if operator == KeywordOperator.OR: return { @@ -156,12 +183,12 @@ def _topic_stats_query( operator: KeywordOperator, publication_types: list[PublicationType], timespan: Timespan | None, - config: MatchConfig = _KEYWORD_MATCH, + fuzzy: bool = False, ) -> dict: """Builds a single query with all stats for Section 1""" filters = [ - _build_keyword_query(keywords, operator, config), + _build_keyword_query(keywords, operator, fuzzy), _author_filter(author_ids), ] @@ -283,38 +310,6 @@ def _topic_stats_query( "_source": {"includes": ["cited_by_count"]}, }, }, - # works whose matched keyword/topic scores above 0.8 - "relevance_above_80": { - "filter": { - "nested": { - "path": config.path, - "query": { - "bool": { - "filter": [ - {"terms": {config.match_field: keywords}}, - {"range": {config.score_field: {"gt": 0.8}}}, - ], - }, - }, - }, - }, - }, - # average matched relevance score over the works - "matched_keywords": { - "nested": {"path": config.path}, - "aggs": { - "only_searched": { - "filter": { - "terms": {config.match_field: keywords}, - }, - "aggs": { - "avg_score": { - "avg": {"field": config.score_field}, - }, - }, - }, - }, - }, }, }, }, @@ -347,17 +342,16 @@ async def topic_stats_for_authors( operator: KeywordOperator, publication_types: list[PublicationType], timespan: Timespan | None, - filter_type: FilterType = FilterType.KEYWORD, + fuzzy: bool = False, ) -> list[AuthorTopicStats]: if not author_ids: return [] - match_cfg = _match_config(filter_type) response: dict[str, Any] = await elasticsearch.search( index=config.settings.openalex_works_search_index, body=_topic_stats_query( - author_ids, keywords, operator, publication_types, timespan, match_cfg + author_ids, keywords, operator, publication_types, timespan, fuzzy ), cluster=ESCluster.NES, ) @@ -375,12 +369,6 @@ async def topic_stats_for_authors( for author_bucket in author_buckets: to_work = author_bucket.get("to_work", {}) avg_value = to_work.get("avg_percentile", {}).get("value") - avg_rel = ( - to_work.get("matched_keywords", {}) - .get("only_searched", {}) - .get("avg_score", {}) - .get("value") - ) positions = { bucket.get("key", ""): bucket.get("doc_count", 0) for bucket in author_bucket.get("positions", {}).get("buckets", []) @@ -413,8 +401,6 @@ async def topic_stats_for_authors( industry_works_count=to_work.get("industry_collab", {}).get("doc_count", 0), first_year=int(first_year) if first_year is not None else None, last_year=int(last_year) if last_year is not None else None, - relevance_above_80_count=to_work.get("relevance_above_80", {}).get("doc_count", 0), - avg_relevance=float(avg_rel) if avg_rel is not None else 0.0, first_author_count=positions.get("first", 0), middle_author_count=positions.get("middle", 0), last_author_count=positions.get("last", 0), @@ -424,13 +410,29 @@ async def topic_stats_for_authors( return results +def _primary_topic_match(keywords: list[str], fuzzy: bool) -> dict: + """Matches works whose primary topic is one of the searched topics/keywords.""" + if fuzzy: + return {"terms": {"primary_topic.id": keywords}} + + return { + "bool": { + "should": [ + {"match_phrase": {"primary_topic.display_name": keyword}} + for keyword in keywords + ], + "minimum_should_match": 1, + }, + } + + def _topic_profile_query( author_ids: list[str], keywords: list[str], operator: KeywordOperator, publication_types: list[PublicationType], timespan: Timespan | None, - config: MatchConfig = _KEYWORD_MATCH, + fuzzy: bool = False, ) -> dict: """Builds the Section 3 query""" @@ -474,14 +476,10 @@ def _topic_profile_query( "reverse_nested": {}, "aggs": { "matched": { - "filter": _build_keyword_query(keywords, operator, config), + "filter": _build_keyword_query(keywords, operator, fuzzy), "aggs": { "primary_match": { - "filter": { - "terms": { - "primary_topic.display_name.keyword": keywords, - }, - }, + "filter": _primary_topic_match(keywords, fuzzy), }, }, }, @@ -561,17 +559,16 @@ async def topic_profile_for_authors( operator: KeywordOperator, publication_types: list[PublicationType], timespan: Timespan | None, - filter_type: FilterType = FilterType.KEYWORD, + fuzzy: bool = False, ) -> list[AuthorTopicProfile]: if not author_ids: return [] - match_cfg = _match_config(filter_type) response: dict[str, Any] = await elasticsearch.search( index=config.settings.openalex_works_search_index, body=_topic_profile_query( - author_ids, keywords, operator, publication_types, timespan, match_cfg + author_ids, keywords, operator, publication_types, timespan, fuzzy ), cluster=ESCluster.NES, ) @@ -727,11 +724,11 @@ def _build_query( author_ids: list[str], publication_types: list[PublicationType], timespan: Timespan | None, - config: MatchConfig = _KEYWORD_MATCH, + fuzzy: bool = False, ) -> dict: """Builds the Elasticsearch query that returns the raw stats per author.""" work_filters = [ - _build_keyword_query(keywords, operator, config), + _build_keyword_query(keywords, operator, fuzzy), _author_filter(author_ids), ] if publication_types: @@ -794,7 +791,7 @@ def _build_publication_type_counts_query( operator: KeywordOperator, author_ids: list[str], timespan: Timespan | None, - config: MatchConfig = _KEYWORD_MATCH, + fuzzy: bool = False, ) -> dict: """Builds the query that counts matching works per publication type. @@ -802,7 +799,7 @@ def _build_publication_type_counts_query( filter itself, since it aggregates over all types instead of one score. """ work_filters = [ - _build_keyword_query(keywords, operator, config), + _build_keyword_query(keywords, operator, fuzzy), _author_filter(author_ids), ] if timespan is not None: @@ -832,7 +829,7 @@ async def publication_type_counts_for_keywords( institution_id: str, career_stages: list[CareerStage], timespan: Timespan | None, - filter_type: FilterType = FilterType.KEYWORD, + fuzzy: bool = False, ) -> list[PublicationTypeCount]: """Counts the university's matching works per publication type, largest first.""" author_ids = await _get_author_ids_from_institution(institution_id) @@ -844,7 +841,7 @@ async def publication_type_counts_for_keywords( author_ids = await _filter_author_ids_by_career_stage(author_ids, career_stages) query_body = _build_publication_type_counts_query( - keywords, operator, author_ids, timespan, _match_config(filter_type), + keywords, operator, author_ids, timespan, fuzzy, ) response: dict[str, Any] = await elasticsearch.search( @@ -1175,7 +1172,7 @@ async def rank_authors_by_keywords( publication_types: list[PublicationType], timespan: Timespan | None, company_status: CompanyStatusFilter = CompanyStatusFilter.ALL, - filter_type: FilterType = FilterType.KEYWORD, + fuzzy: bool = False, ) -> list[RankedAuthor]: """Ranks the university's authors by a weighted score over works and citations. @@ -1193,8 +1190,7 @@ async def rank_authors_by_keywords( author_ids = await _filter_author_ids_by_career_stage(author_ids, career_stages) query_body = _build_query( - keywords, operator, author_ids, publication_types, timespan, - _match_config(filter_type), + keywords, operator, author_ids, publication_types, timespan, fuzzy, ) response: dict[str, Any] = await elasticsearch.search( diff --git a/service/src/main/inse/ranking/model.py b/service/src/main/inse/ranking/model.py index f4de7b12..15430231 100644 --- a/service/src/main/inse/ranking/model.py +++ b/service/src/main/inse/ranking/model.py @@ -12,11 +12,6 @@ class KeywordOperator(StrEnum): OR = "or" -class FilterType(StrEnum): - KEYWORD = "keyword" - TOPIC = "topic" - - class CompanyStatusFilter(StrEnum): ALL = "all" ACTIVE = "active" @@ -107,10 +102,12 @@ class KeywordToAuthorRequest(BaseModel): default=KeywordOperator.AND, description="How to combine the keywords: 'and' or 'or'. Defaults to 'and'.", ) - filter_type: FilterType = Field( - default=FilterType.KEYWORD, - description="What the 'keywords' values match against: 'keyword' (OpenAlex " - "keyword display names) or 'topic' (OpenAlex topic display names). Defaults to 'keyword'.", + fuzzy: bool = Field( + default=False, + description="How the 'keywords' values are matched: True means they are " + "OpenAlex topic ids matched against the work's topics, False means they are " + "raw keywords matched as phrases in the work's title, abstract, keywords and " + "topic names. Defaults to False.", ) weights: RankingWeights = Field( description="Weights for the ranking metrics. Required.", @@ -133,7 +130,7 @@ class KeywordToAuthorRequest(BaseModel): "'all', only 'active' (non-deleted), or only 'deleted'.", ) - @field_validator("operator", "filter_type", mode="before") + @field_validator("operator", mode="before") @classmethod def operator_case_insensitive(cls, value): if isinstance(value, str): @@ -154,10 +151,12 @@ class SelectedAuthorsRequest(BaseModel): default=KeywordOperator.AND, description="How to combine the keywords: 'and' or 'or'. Defaults to 'and'.", ) - filter_type: FilterType = Field( - default=FilterType.KEYWORD, - description="What the 'keywords' values match against: 'keyword' (OpenAlex " - "keyword display names) or 'topic' (OpenAlex topic ids). Defaults to 'keyword'.", + fuzzy: bool = Field( + default=False, + description="How the 'keywords' values are matched: True means they are " + "OpenAlex topic ids matched against the work's topics, False means they are " + "raw keywords matched as phrases in the work's title, abstract, keywords and " + "topic names. Defaults to False.", ) publication_types: list[PublicationType] = Field( default_factory=list, @@ -175,13 +174,6 @@ class SelectedAuthorsRequest(BaseModel): return value.lower() return value - @field_validator("filter_type", mode="before") - @classmethod - def filter_type_case_insensitive(cls, value): - if isinstance(value, str): - return value.lower() - return value - class AuthorMetricsRequest(BaseModel): author_ids: list[str] = Field( @@ -204,10 +196,12 @@ class PublicationTypeCountsRequest(BaseModel): default=KeywordOperator.AND, description="How to combine the keywords: 'and' or 'or'. Defaults to 'and'.", ) - filter_type: FilterType = Field( - default=FilterType.KEYWORD, - description="What the 'keywords' values match against: 'keyword' (OpenAlex " - "keyword display names) or 'topic' (OpenAlex topic display names). Defaults to 'keyword'.", + fuzzy: bool = Field( + default=False, + description="How the 'keywords' values are matched: True means they are " + "OpenAlex topic ids matched against the work's topics, False means they are " + "raw keywords matched as phrases in the work's title, abstract, keywords and " + "topic names. Defaults to False.", ) career_stages: list[CareerStage] = Field( default_factory=list, @@ -218,7 +212,7 @@ class PublicationTypeCountsRequest(BaseModel): description="Optional filter: only count works whose publication_year is within [from, to].", ) - @field_validator("operator", "filter_type", mode="before") + @field_validator("operator", mode="before") @classmethod def operator_case_insensitive(cls, value): if isinstance(value, str): @@ -290,15 +284,6 @@ class AuthorTopicStats(BaseModel): default=None, description="Latest publication year among the author's topic works.", ) - relevance_above_80_count: int = Field( - default=0, - description="Number of the author's topic works where the matched keyword's " - "relevance score is above 0.8.", - ) - avg_relevance: float = Field( - default=0.0, - description="Average matched-keyword relevance score (0-1) over the author's topic works.", - ) first_author_count: int = Field( default=0, description="Number of the author's topic works where they are the first author.", @@ -355,7 +340,7 @@ class AuthorTopicProfile(BaseModel): ) primary_topic_matches: int = Field( description="Matched works where one of the searched topics is the work's " - "primary topic (only meaningful for filter_type 'topic').", + "primary topic.", ) distinct_topics: int = Field( description="Number of distinct primary topics across all works.", diff --git a/service/src/main/inse/ranking/router.py b/service/src/main/inse/ranking/router.py index e0f0dd9b..a5fc843f 100644 --- a/service/src/main/inse/ranking/router.py +++ b/service/src/main/inse/ranking/router.py @@ -48,11 +48,11 @@ async def rank_author( ) logger.info( - "rank-author keywords=%s operator=%s filter_type=%s institution_id=%s career_stages=%s " + "rank-author keywords=%s operator=%s fuzzy=%s institution_id=%s career_stages=%s " "publication_types=%s timespan=%s", request.keywords, request.operator, - request.filter_type, + request.fuzzy, institution_id, request.career_stages, request.publication_types, @@ -67,7 +67,7 @@ async def rank_author( publication_types=request.publication_types, timespan=request.timespan, company_status=request.company_status, - filter_type=request.filter_type, + fuzzy=request.fuzzy, ) # Publication-type facet counts for the "Art der Work" filter @@ -86,11 +86,11 @@ async def publication_type_counts( ) logger.info( - "publication-type-counts keywords=%s operator=%s filter_type=%s institution_id=%s " + "publication-type-counts keywords=%s operator=%s fuzzy=%s institution_id=%s " "career_stages=%s timespan=%s", request.keywords, request.operator, - request.filter_type, + request.fuzzy, institution_id, request.career_stages, request.timespan, @@ -101,18 +101,18 @@ async def publication_type_counts( institution_id=institution_id, career_stages=request.career_stages, timespan=request.timespan, - filter_type=request.filter_type, + fuzzy=request.fuzzy, ) # Compare authors table 1 (topic stats) @router.post("/topic-stats", response_model=list[AuthorTopicStats]) async def topic_stats(request: SelectedAuthorsRequest): logger.info( - "topic-stats author_ids=%s keywords=%s operator=%s filter_type=%s publication_types=%s timespan=%s", + "topic-stats author_ids=%s keywords=%s operator=%s fuzzy=%s publication_types=%s timespan=%s", request.author_ids, request.keywords, request.operator, - request.filter_type, + request.fuzzy, request.publication_types, request.timespan, ) @@ -122,19 +122,19 @@ async def topic_stats(request: SelectedAuthorsRequest): request.operator, request.publication_types, request.timespan, - request.filter_type, + request.fuzzy, ) # Compare authors section 3 (topic profile over ALL works of each author) @router.post("/topic-profile", response_model=list[AuthorTopicProfile]) async def topic_profile(request: SelectedAuthorsRequest): logger.info( - "topic-profile author_ids=%s keywords=%s operator=%s filter_type=%s " + "topic-profile author_ids=%s keywords=%s operator=%s fuzzy=%s " "publication_types=%s timespan=%s", request.author_ids, request.keywords, request.operator, - request.filter_type, + request.fuzzy, request.publication_types, request.timespan, ) @@ -144,7 +144,7 @@ async def topic_profile(request: SelectedAuthorsRequest): request.operator, request.publication_types, request.timespan, - request.filter_type, + request.fuzzy, ) # Compare authors table 2 (author-level stats, keyword/time-independent) diff --git a/service/src/main/inse/snippets.py b/service/src/main/inse/snippets.py new file mode 100644 index 00000000..0d8d662a --- /dev/null +++ b/service/src/main/inse/snippets.py @@ -0,0 +1,125 @@ +import re + +SNIPPET_FRAGMENT_CHARS = 500 +SNIPPET_FRAGMENT_COUNT = 3 +SNIPPET_FRAGMENT_SEPARATOR = " … " + +SNIPPET_CONTEXT_BEFORE_CHARS = 400 +SNIPPET_CONTEXT_AFTER_CHARS = 1100 +SNIPPET_BOUNDARY_CHARS = 150 +SNIPPET_ELLIPSIS = "…" + +_EM_TAG = re.compile(r"(.*?)", re.DOTALL) + +_SENTENCE_BREAK = re.compile(r"(?"], "post_tags": [""]} + + +def snippet_with_context(text: str | None, fragments: list) -> str: + joined = SNIPPET_FRAGMENT_SEPARATOR.join(fragments) + terms = marked_terms(joined) + + if not text or not terms: + return joined + + span = _first_term_span(text, terms) + if span is None: + return joined + + start, end = _window_bounds(text, *span) + window = _mark_terms(text[start:end], terms) + + if start > 0: + window = f"{SNIPPET_ELLIPSIS} {window}" + if end < len(text): + window = f"{window} {SNIPPET_ELLIPSIS}" + + return window + + +def marked_terms(fragment_text: str) -> list: + by_key: dict[str, str] = {} + for match in _EM_TAG.finditer(fragment_text): + term = match.group(1).strip() + if term: + by_key.setdefault(term.lower(), term) + return list(by_key.values()) + + +def _first_term_span(text: str, terms: list) -> tuple | None: + lowered = text.lower() + spans = [ + (index, index + len(term)) + for term, index in ((term, lowered.find(term.lower())) for term in terms) + if index >= 0 + ] + return min(spans) if spans else None + + +def _window_bounds(text: str, match_start: int, match_end: int) -> tuple: + start = max(0, match_start - SNIPPET_CONTEXT_BEFORE_CHARS) + end = min(len(text), match_end + SNIPPET_CONTEXT_AFTER_CHARS) + + if start > 0: + start = _forward_to_boundary(text, start, match_start) + if end < len(text): + end = _back_to_boundary(text, end, match_end) + + return start, end + + +def _forward_to_boundary(text: str, start: int, limit: int) -> int: + + ahead = _SENTENCE_BREAK.search(text, start, min(limit, start + SNIPPET_BOUNDARY_CHARS)) + if ahead: + return ahead.end() + + behind_from = max(0, start - SNIPPET_BOUNDARY_CHARS) + behind = list(_SENTENCE_BREAK.finditer(text, behind_from, start)) + if behind: + return behind[-1].end() + + if behind_from == 0: + return 0 + + space = text.find(" ", start, start + SNIPPET_BOUNDARY_CHARS) + return space + 1 if space >= 0 else start + + +def _back_to_boundary(text: str, end: int, floor: int) -> int: + + sentence = _SENTENCE_BREAK.search(text, end, end + SNIPPET_BOUNDARY_CHARS) + if sentence: + return sentence.start() + + space = text.rfind(" ", floor, end) + return space if space > floor else end + + +def _mark_terms(window: str, terms: list) -> str: + lowered = window.lower() + spans = sorted( + (index, index + len(term)) + for term, index in ((term, lowered.find(term.lower())) for term in terms) + if index >= 0 + ) + + marked = [] + cursor = 0 + for start, end in spans: + if start < cursor: + continue + marked.append(window[cursor:start]) + marked.append(f"{window[start:end]}") + cursor = end + marked.append(window[cursor:]) + + return "".join(marked) diff --git a/service/src/main/inse/works/v2/service.py b/service/src/main/inse/works/v2/service.py index 20e139a8..8309edf9 100644 --- a/service/src/main/inse/works/v2/service.py +++ b/service/src/main/inse/works/v2/service.py @@ -6,6 +6,12 @@ from inse.exceptions import ElasticsearchNotFoundException, NotFoundException from inse.integrations import elasticsearch from inse.model import ESCluster, ESIndex, SortDirection from inse.models.openalex.work import Work +from inse.snippets import ( + FRAGMENT_FIELD, + HIGHLIGHT_TAGS, + WHOLE_FIELD, + snippet_with_context, +) from inse.works.v2.model import ( PrimaryCategoryYearAggregation, PrimaryCategoryYearAggregationPage, @@ -372,6 +378,17 @@ async def get_works_by_keywords( track_total_hits=True, offset=page * size, sort=sort, + # A work matches on its topic and keyword metadata as well as on its + # text, so roughly half the hits contain the searched keyword nowhere in + # title or abstract. Highlighting tells the two apart: a fragment comes + # back only for the works that really do carry the phrase. + highlight={ + "fields": { + "title": WHOLE_FIELD, + "abstract": FRAGMENT_FIELD, + }, + **HIGHLIGHT_TAGS, + }, cluster=ESCluster.NES, ) print(f"Elasticsearch response: {response}") @@ -388,11 +405,67 @@ async def get_works_by_keywords( work = Work.from_dict(source) # type: ignore if work is not None: + snippet, snippet_field = _keyword_snippet(hit) + work.snippet = snippet + work.snippet_field = snippet_field + work.matched_via = _matched_via(source, keywords) elements.append(work) return WorkPageV2(elements=elements, total=total, page=page, size=size) +def _keyword_snippet(hit: dict) -> tuple[str | None, str | None]: + """Picks the passage to show for a hit, preferring the title over the abstract.""" + highlight = hit.get("highlight") or {} + + title_fragments = highlight.get("title") + if title_fragments: + return title_fragments[0], "title" + + abstract_fragments = highlight.get("abstract") + if abstract_fragments: + abstract = (hit.get("_source") or {}).get("abstract") + return snippet_with_context(abstract, abstract_fragments), "abstract" + + return None, None + + +def _matched_via(source: dict, keywords: list[str] | None) -> list[str] | None: + """Names the topics and keywords a work was matched through. + + Only needed when there is no snippet: those works carry the searched term in + their metadata rather than in their text, and would otherwise expand into an + empty row. Matching mirrors the `match_phrase` clauses above closely enough + for a label - it is not used for retrieval. + """ + wanted = [kw.strip().lower() for kw in (keywords or []) if kw and kw.strip()] + if not wanted: + return None + + candidates: list[str] = [] + + primary_topic = source.get("primary_topic") or {} + candidates.append(primary_topic.get("display_name")) + + for topic in source.get("topics") or []: + candidates.append(topic.get("display_name")) + for level in ("field", "subfield", "domain"): + candidates.append((topic.get(level) or {}).get("display_name")) + + for keyword in source.get("keywords") or []: + candidates.append(keyword.get("display_name")) + + names: list[str] = [] + for name in candidates: + if not name or name in names: + continue + lowered = name.lower() + if any(kw in lowered for kw in wanted): + names.append(name) + + return names or None + + async def get_author_works( raw_oa_author_id: str, page: int, diff --git a/webapp/angular.json b/webapp/angular.json index dadf2610..4e6e27de 100644 --- a/webapp/angular.json +++ b/webapp/angular.json @@ -34,7 +34,7 @@ { "type": "initial", "maximumWarning": "1500kb", - "maximumError": "2mb" + "maximumError": "3mb" }, { "type": "anyComponentStyle", diff --git a/webapp/src/app/api/.openapi-generator/FILES b/webapp/src/app/api/.openapi-generator/FILES index efd9cee6..3f8e63e4 100644 --- a/webapp/src/app/api/.openapi-generator/FILES +++ b/webapp/src/app/api/.openapi-generator/FILES @@ -69,6 +69,7 @@ model/bodyLogin.ts model/bodyRequestOtk.ts model/bodyRequestPasswordReset.ts model/bodyResetPassword.ts +model/bodyValidatePasswordResetToken.ts model/bundInstitutionSummary.ts model/bundInstitutionSummaryPage.ts model/bundProjectDetails.ts @@ -138,7 +139,6 @@ model/extractedKeywordsLLM.ts model/extractedKeywordsResponse.ts model/fieldNode.ts model/fileUpload.ts -model/filterType.ts model/fp7EurosciVoc.ts model/fp7LegalBasis.ts model/fp7Organization.ts diff --git a/webapp/src/app/api/api/auth.service.ts b/webapp/src/app/api/api/auth.service.ts index 535c7da5..e8a5b735 100644 --- a/webapp/src/app/api/api/auth.service.ts +++ b/webapp/src/app/api/api/auth.service.ts @@ -43,6 +43,8 @@ import { BodyRequestPasswordReset } from '../model/bodyRequestPasswordReset'; // @ts-ignore import { BodyResetPassword } from '../model/bodyResetPassword'; // @ts-ignore +import { BodyValidatePasswordResetToken } from '../model/bodyValidatePasswordResetToken'; +// @ts-ignore import { CreateAccountRequest } from '../model/createAccountRequest'; // @ts-ignore import { HTTPValidationError } from '../model/hTTPValidationError'; @@ -1929,4 +1931,122 @@ export class AuthService extends BaseService { }, ); } + + /** + * Validate Password Reset Token + * Validate a password reset token without consuming it. + * @endpoint post /api/auth/v2/validate-password-reset-token + * @param bodyValidatePasswordResetToken + * @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 validatePasswordResetToken( + bodyValidatePasswordResetToken: BodyValidatePasswordResetToken, + observe?: 'body', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable<{ [key: string]: boolean | null }>; + public validatePasswordResetToken( + bodyValidatePasswordResetToken: BodyValidatePasswordResetToken, + observe?: 'response', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public validatePasswordResetToken( + bodyValidatePasswordResetToken: BodyValidatePasswordResetToken, + observe?: 'events', + reportProgress?: boolean, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable>; + public validatePasswordResetToken( + bodyValidatePasswordResetToken: BodyValidatePasswordResetToken, + observe: any = 'body', + reportProgress: boolean = false, + options?: { + httpHeaderAccept?: 'application/json'; + context?: HttpContext; + transferCache?: boolean; + }, + ): Observable { + if ( + bodyValidatePasswordResetToken === null || + bodyValidatePasswordResetToken === undefined + ) { + throw new Error( + 'Required parameter bodyValidatePasswordResetToken was null or undefined when calling validatePasswordResetToken.', + ); + } + + 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; + + // to determine the Content-Type header + const consumes: string[] = ['application/json']; + const httpContentTypeSelected: string | undefined = + this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set( + 'Content-Type', + httpContentTypeSelected, + ); + } + + 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 = `/api/auth/v2/validate-password-reset-token`; + const { basePath, withCredentials } = this.configuration; + return this.httpClient.request<{ [key: string]: boolean | null }>( + 'post', + `${basePath}${localVarPath}`, + { + context: localVarHttpContext, + body: bodyValidatePasswordResetToken, + responseType: responseType_, + ...(withCredentials ? { withCredentials } : {}), + headers: localVarHeaders, + observe: observe, + ...(localVarTransferCache !== undefined + ? { transferCache: localVarTransferCache } + : {}), + reportProgress: reportProgress, + }, + ); + } } diff --git a/webapp/src/app/api/api/news.service.ts b/webapp/src/app/api/api/news.service.ts index 6d7a4c53..b789f410 100644 --- a/webapp/src/app/api/api/news.service.ts +++ b/webapp/src/app/api/api/news.service.ts @@ -563,6 +563,7 @@ export class NewsService extends BaseService { * @param yearFrom Earliest publication year (inclusive). * @param yearTo Latest publication year (inclusive). * @param sortOrder Overrides relevance ranking with a date sort: \'desc\' (newest first) or \'asc\' (oldest first). + * @param title Narrows the results to articles whose title matches this text. * @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. */ @@ -577,6 +578,7 @@ export class NewsService extends BaseService { yearFrom?: number, yearTo?: number, sortOrder?: string, + title?: string, observe?: 'body', reportProgress?: boolean, options?: { @@ -596,6 +598,7 @@ export class NewsService extends BaseService { yearFrom?: number, yearTo?: number, sortOrder?: string, + title?: string, observe?: 'response', reportProgress?: boolean, options?: { @@ -615,6 +618,7 @@ export class NewsService extends BaseService { yearFrom?: number, yearTo?: number, sortOrder?: string, + title?: string, observe?: 'events', reportProgress?: boolean, options?: { @@ -634,6 +638,7 @@ export class NewsService extends BaseService { yearFrom?: number, yearTo?: number, sortOrder?: string, + title?: string, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -705,6 +710,11 @@ export class NewsService extends BaseService { sortOrder, 'sortOrder', ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + title, + 'title', + ); let localVarHeaders = this.defaultHeaders; @@ -769,6 +779,7 @@ export class NewsService extends BaseService { * @param yearFrom Earliest publication year (inclusive). * @param yearTo Latest publication year (inclusive). * @param sortOrder Overrides relevance ranking with a date sort: \'desc\' (newest first) or \'asc\' (oldest first). + * @param title Narrows the results to articles whose title matches this text. * @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. */ @@ -783,6 +794,7 @@ export class NewsService extends BaseService { yearFrom?: number, yearTo?: number, sortOrder?: string, + title?: string, observe?: 'body', reportProgress?: boolean, options?: { @@ -802,6 +814,7 @@ export class NewsService extends BaseService { yearFrom?: number, yearTo?: number, sortOrder?: string, + title?: string, observe?: 'response', reportProgress?: boolean, options?: { @@ -821,6 +834,7 @@ export class NewsService extends BaseService { yearFrom?: number, yearTo?: number, sortOrder?: string, + title?: string, observe?: 'events', reportProgress?: boolean, options?: { @@ -840,6 +854,7 @@ export class NewsService extends BaseService { yearFrom?: number, yearTo?: number, sortOrder?: string, + title?: string, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -911,6 +926,11 @@ export class NewsService extends BaseService { sortOrder, 'sortOrder', ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + title, + 'title', + ); let localVarHeaders = this.defaultHeaders; diff --git a/webapp/src/app/api/api/persons.service.ts b/webapp/src/app/api/api/persons.service.ts index 8f9ef03d..b8502f7c 100644 --- a/webapp/src/app/api/api/persons.service.ts +++ b/webapp/src/app/api/api/persons.service.ts @@ -52,13 +52,11 @@ export class PersonsService extends BaseService { * Generates a bio for a person by author ID. * @endpoint get /api/inse-service/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, - include?: string, observe?: 'body', reportProgress?: boolean, options?: { @@ -69,7 +67,6 @@ export class PersonsService extends BaseService { ): Observable; public generatePersonBio( authorId: string, - include?: string, observe?: 'response', reportProgress?: boolean, options?: { @@ -80,7 +77,6 @@ export class PersonsService extends BaseService { ): Observable>; public generatePersonBio( authorId: string, - include?: string, observe?: 'events', reportProgress?: boolean, options?: { @@ -91,7 +87,6 @@ export class PersonsService extends BaseService { ): Observable>; public generatePersonBio( authorId: string, - include?: string, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -112,11 +107,6 @@ export class PersonsService extends BaseService { authorId, 'author_id', ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - include, - 'include', - ); let localVarHeaders = this.defaultHeaders; @@ -403,14 +393,12 @@ export class PersonsService extends BaseService { * @endpoint get /api/inse-service/persons/search * @param authorId OpenAlex author ID (e.g., A5093075883) * @param query Search query (e.g., Arman AND Arzani) - * @param include Comma-separated include tags: topics_full, topic_share, summary_stats, ids, last_known_institutions, sources, counts_by_year, works_api_url, dates, cited_by_count_boost * @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 searchPersons( authorId?: string, query?: string, - include?: string, observe?: 'body', reportProgress?: boolean, options?: { @@ -422,7 +410,6 @@ export class PersonsService extends BaseService { public searchPersons( authorId?: string, query?: string, - include?: string, observe?: 'response', reportProgress?: boolean, options?: { @@ -434,7 +421,6 @@ export class PersonsService extends BaseService { public searchPersons( authorId?: string, query?: string, - include?: string, observe?: 'events', reportProgress?: boolean, options?: { @@ -446,7 +432,6 @@ export class PersonsService extends BaseService { public searchPersons( authorId?: string, query?: string, - include?: string, observe: any = 'body', reportProgress: boolean = false, options?: { @@ -466,11 +451,6 @@ export class PersonsService extends BaseService { query, 'query', ); - localVarQueryParameters = this.addToHttpParams( - localVarQueryParameters, - include, - 'include', - ); let localVarHeaders = this.defaultHeaders; diff --git a/webapp/src/app/api/model/authorTopicProfile.ts b/webapp/src/app/api/model/authorTopicProfile.ts index fddb2ed6..075bc8ec 100644 --- a/webapp/src/app/api/model/authorTopicProfile.ts +++ b/webapp/src/app/api/model/authorTopicProfile.ts @@ -28,7 +28,7 @@ export interface AuthorTopicProfile { */ matched_works: number; /** - * Matched works where one of the searched topics is the work\'s primary topic (only meaningful for filter_type \'topic\'). + * Matched works where one of the searched topics is the work\'s primary topic. */ primary_topic_matches: number; /** diff --git a/webapp/src/app/api/model/authorTopicStats.ts b/webapp/src/app/api/model/authorTopicStats.ts index 15fac6d0..67d32eca 100644 --- a/webapp/src/app/api/model/authorTopicStats.ts +++ b/webapp/src/app/api/model/authorTopicStats.ts @@ -70,14 +70,6 @@ export interface AuthorTopicStats { industry_works_count?: number; first_year?: number | null; last_year?: number | null; - /** - * Number of the author\'s topic works where the matched keyword\'s relevance score is above 0.8. - */ - relevance_above_80_count?: number; - /** - * Average matched-keyword relevance score (0-1) over the author\'s topic works. - */ - avg_relevance?: number; /** * Number of the author\'s topic works where they are the first author. */ diff --git a/webapp/src/app/api/model/filterType.ts b/webapp/src/app/api/model/bodyValidatePasswordResetToken.ts similarity index 56% rename from webapp/src/app/api/model/filterType.ts rename to webapp/src/app/api/model/bodyValidatePasswordResetToken.ts index bee9d0d7..a91ed455 100644 --- a/webapp/src/app/api/model/filterType.ts +++ b/webapp/src/app/api/model/bodyValidatePasswordResetToken.ts @@ -1,17 +1,16 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ - -export const FilterType = { - Keyword: 'keyword', - Topic: 'topic' -} as const; -export type FilterType = typeof FilterType[keyof typeof FilterType]; - +export interface BodyValidatePasswordResetToken { + /** + * Password reset token from the reset link + */ + reset_token: string; +} diff --git a/webapp/src/app/api/model/institution.ts b/webapp/src/app/api/model/institution.ts index 6b1a5778..a60acdaa 100644 --- a/webapp/src/app/api/model/institution.ts +++ b/webapp/src/app/api/model/institution.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -11,31 +11,31 @@ import { InstitutionIds } from './institutionIds'; import { AuthorCountsByYearInner } from './authorCountsByYearInner'; import { AuthorSummaryStats } from './authorSummaryStats'; import { InstitutionGeo } from './institutionGeo'; - +import { DehydratedInstitution } from './dehydratedInstitution'; /** * A university, research organization, or other affiliation */ -export interface Institution { - id?: string | null; - ror?: string | null; - display_name?: string | null; - country_code?: string | null; - type?: string | null; - homepage_url?: string | null; - image_url?: string | null; - image_thumbnail_url?: string | null; - display_name_acronyms?: Array | null; - display_name_alternatives?: Array | null; - works_count?: number | null; - cited_by_count?: number | null; - summary_stats?: AuthorSummaryStats | null; - geo?: InstitutionGeo | null; - lineage?: Array | null; - ids?: InstitutionIds | null; - counts_by_year?: Array | null; - works_api_url?: string | null; - created_date?: string | null; - updated_date?: string | null; +export interface Institution { + id?: string | null; + ror?: string | null; + display_name?: string | null; + country_code?: string | null; + type?: string | null; + homepage_url?: string | null; + image_url?: string | null; + image_thumbnail_url?: string | null; + display_name_acronyms?: Array | null; + display_name_alternatives?: Array | null; + works_count?: number | null; + cited_by_count?: number | null; + summary_stats?: AuthorSummaryStats | null; + geo?: InstitutionGeo | null; + lineage?: Array | null; + ids?: InstitutionIds | null; + counts_by_year?: Array | null; + works_api_url?: string | null; + associated_institutions?: Array | null; + created_date?: string | null; + updated_date?: string | null; } - diff --git a/webapp/src/app/api/model/keywordToAuthorRequest.ts b/webapp/src/app/api/model/keywordToAuthorRequest.ts index 9821531e..4f420e16 100644 --- a/webapp/src/app/api/model/keywordToAuthorRequest.ts +++ b/webapp/src/app/api/model/keywordToAuthorRequest.ts @@ -8,7 +8,6 @@ * Do not edit the class manually. */ import { Timespan } from './timespan'; -import { FilterType } from './filterType'; import { CareerStage } from './careerStage'; import { KeywordOperator } from './keywordOperator'; import { PublicationType } from './publicationType'; @@ -25,9 +24,9 @@ export interface KeywordToAuthorRequest { */ operator?: KeywordOperator; /** - * What the \'keywords\' values match against: \'keyword\' (OpenAlex keyword display names) or \'topic\' (OpenAlex topic display names). Defaults to \'keyword\'. + * How the \'keywords\' values are matched: True means they are OpenAlex topic ids matched against the work\'s topics, False means they are raw keywords matched as phrases in the work\'s title, abstract, keywords and topic names. Defaults to False. */ - filter_type?: FilterType; + fuzzy?: boolean; /** * Weights for the ranking metrics. Required. */ diff --git a/webapp/src/app/api/model/models.ts b/webapp/src/app/api/model/models.ts index 9c21b9fb..9929cf3c 100644 --- a/webapp/src/app/api/model/models.ts +++ b/webapp/src/app/api/model/models.ts @@ -35,6 +35,7 @@ export * from './bodyLogin'; export * from './bodyRequestOtk'; export * from './bodyRequestPasswordReset'; export * from './bodyResetPassword'; +export * from './bodyValidatePasswordResetToken'; export * from './bundInstitutionSummary'; export * from './bundInstitutionSummaryPage'; export * from './bundProjectDetails'; @@ -104,7 +105,6 @@ export * from './extractedKeywordsLLM'; export * from './extractedKeywordsResponse'; export * from './fieldNode'; export * from './fileUpload'; -export * from './filterType'; export * from './fp7EurosciVoc'; export * from './fp7LegalBasis'; export * from './fp7Organization'; diff --git a/webapp/src/app/api/model/publicationTypeCountsRequest.ts b/webapp/src/app/api/model/publicationTypeCountsRequest.ts index fe24986b..294ce4c7 100644 --- a/webapp/src/app/api/model/publicationTypeCountsRequest.ts +++ b/webapp/src/app/api/model/publicationTypeCountsRequest.ts @@ -8,7 +8,6 @@ * Do not edit the class manually. */ import { Timespan } from './timespan'; -import { FilterType } from './filterType'; import { CareerStage } from './careerStage'; import { KeywordOperator } from './keywordOperator'; @@ -22,9 +21,9 @@ export interface PublicationTypeCountsRequest { */ operator?: KeywordOperator; /** - * What the \'keywords\' values match against: \'keyword\' (OpenAlex keyword display names) or \'topic\' (OpenAlex topic display names). Defaults to \'keyword\'. + * How the \'keywords\' values are matched: True means they are OpenAlex topic ids matched against the work\'s topics, False means they are raw keywords matched as phrases in the work\'s title, abstract, keywords and topic names. Defaults to False. */ - filter_type?: FilterType; + fuzzy?: boolean; /** * Optional filter: only count works of authors in one of these career stages. Empty = no filter. */ diff --git a/webapp/src/app/api/model/selectedAuthorsRequest.ts b/webapp/src/app/api/model/selectedAuthorsRequest.ts index 79f008fe..9979fb5c 100644 --- a/webapp/src/app/api/model/selectedAuthorsRequest.ts +++ b/webapp/src/app/api/model/selectedAuthorsRequest.ts @@ -1,42 +1,37 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { Timespan } from './timespan'; -import { FilterType } from './filterType'; import { KeywordOperator } from './keywordOperator'; import { PublicationType } from './publicationType'; - -export interface SelectedAuthorsRequest { - /** - * OpenAlex IDs of the authors to rank. - */ - author_ids: Array; - /** - * One or more keywords defining the topic. - */ - keywords: Array; - /** - * How to combine the keywords: \'and\' or \'or\'. Defaults to \'and\'. - */ - operator?: KeywordOperator; - /** - * What the \'keywords\' values match against: \'keyword\' (OpenAlex keyword display names) or \'topic\' (OpenAlex topic ids). Defaults to \'keyword\'. - */ - filter_type?: FilterType; - /** - * Optional filter: only count works of these publication types. Empty = no filter. - */ - publication_types?: Array; - timespan?: Timespan | null; +export interface SelectedAuthorsRequest { + /** + * OpenAlex IDs of the authors to rank. + */ + author_ids: Array; + /** + * One or more keywords defining the topic. + */ + keywords: Array; + /** + * How to combine the keywords: \'and\' or \'or\'. Defaults to \'and\'. + */ + operator?: KeywordOperator; + /** + * How the \'keywords\' values are matched: True means they are OpenAlex topic ids matched against the work\'s topics, False means they are raw keywords matched as phrases in the work\'s title, abstract, keywords and topic names. Defaults to False. + */ + fuzzy?: boolean; + /** + * Optional filter: only count works of these publication types. Empty = no filter. + */ + publication_types?: Array; + timespan?: Timespan | null; } -export namespace SelectedAuthorsRequest { -} - - +export namespace SelectedAuthorsRequest {} diff --git a/webapp/src/app/api/model/work.ts b/webapp/src/app/api/model/work.ts index 07d94a1c..97c4d648 100644 --- a/webapp/src/app/api/model/work.ts +++ b/webapp/src/app/api/model/work.ts @@ -1,7 +1,7 @@ /** * Innovation Search Engine API * - * + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech @@ -24,48 +24,49 @@ import { WorkHasContent } from './workHasContent'; import { Location } from './location'; import { WorkBiblio } from './workBiblio'; - /** * A scholarly document (article, book, dataset, thesis, etc.) */ -export interface Work { - id?: string | null; - doi?: string | null; - title?: string | null; - display_name?: string | null; - publication_year?: number | null; - publication_date?: string | null; - type?: string | null; - language?: string | null; - cited_by_count?: number | null; - is_retracted?: boolean | null; - is_paratext?: boolean | null; - primary_location?: Location | null; - locations?: Array | null; - best_oa_location?: Location | null; - open_access?: OpenAccess | null; - authorships?: Array | null; - ids?: WorkIds | null; - biblio?: WorkBiblio | null; - abstract_inverted_index?: object | null; - referenced_works?: Array | null; - referenced_works_count?: number | null; - related_works?: Array | null; - topics?: Array | null; - primary_topic?: WorkTopic | null; - keywords?: Array | null; - funders?: Array | null; - awards?: Array | null; - fwci?: Fwci | null; - citation_normalized_percentile?: WorkCitationNormalizedPercentile | null; - cited_by_percentile_year?: WorkCitedByPercentileYear | null; - counts_by_year?: Array | null; - sustainable_development_goals?: Array | null; - mesh?: Array | null; - indexed_in?: Array | null; - has_content?: WorkHasContent | null; - content_url?: string | null; - created_date?: string | null; - updated_date?: string | null; +export interface Work { + id?: string | null; + doi?: string | null; + title?: string | null; + display_name?: string | null; + publication_year?: number | null; + publication_date?: string | null; + type?: string | null; + language?: string | null; + cited_by_count?: number | null; + is_retracted?: boolean | null; + is_paratext?: boolean | null; + primary_location?: Location | null; + locations?: Array | null; + best_oa_location?: Location | null; + open_access?: OpenAccess | null; + authorships?: Array | null; + ids?: WorkIds | null; + biblio?: WorkBiblio | null; + abstract_inverted_index?: object | null; + referenced_works?: Array | null; + referenced_works_count?: number | null; + related_works?: Array | null; + topics?: Array | null; + primary_topic?: WorkTopic | null; + keywords?: Array | null; + funders?: Array | null; + awards?: Array | null; + fwci?: Fwci | null; + citation_normalized_percentile?: WorkCitationNormalizedPercentile | null; + cited_by_percentile_year?: WorkCitedByPercentileYear | null; + counts_by_year?: Array | null; + sustainable_development_goals?: Array | null; + mesh?: Array | null; + indexed_in?: Array | null; + has_content?: WorkHasContent | null; + content_url?: string | null; + created_date?: string | null; + updated_date?: string | null; + snippet?: string | null; + snippet_field?: string | null; + matched_via?: Array | null; } - diff --git a/webapp/src/app/app.routes.ts b/webapp/src/app/app.routes.ts index 43d09f3f..44bafe3d 100644 --- a/webapp/src/app/app.routes.ts +++ b/webapp/src/app/app.routes.ts @@ -72,6 +72,13 @@ export const routes: Routes = [ pathMatch: 'full', redirectTo: 'dashboard', }, + { + path: 'icons', + loadComponent: () => + import('./modules/icon-preview/icon-preview.component').then( + (mod) => mod.IconPreviewComponent, + ), + }, { path: 'login', loadComponent: () => diff --git a/webapp/src/app/modules/accounts/account-dialog.component.html b/webapp/src/app/modules/accounts/account-dialog.component.html index a494ff36..807e8da0 100644 --- a/webapp/src/app/modules/accounts/account-dialog.component.html +++ b/webapp/src/app/modules/accounts/account-dialog.component.html @@ -61,7 +61,7 @@ diff --git a/webapp/src/app/modules/accounts/account-dialog.component.ts b/webapp/src/app/modules/accounts/account-dialog.component.ts index 15e312ae..fcd2926b 100644 --- a/webapp/src/app/modules/accounts/account-dialog.component.ts +++ b/webapp/src/app/modules/accounts/account-dialog.component.ts @@ -21,6 +21,7 @@ import { InseAccountManagementModelOrganizationProfile, UserRole, } from '../../api'; +import { SAVE_ICON } from '../../shared/ui/icons'; export type AccountDialogMode = 'create' | 'edit'; @@ -71,6 +72,8 @@ export type AccountDialogResult = standalone: true, }) export class AccountDialogComponent { + readonly SAVE_ICON = SAVE_ICON; + private readonly dialogRef = inject< MatDialogRef diff --git a/webapp/src/app/modules/accounts/accounts.component.html b/webapp/src/app/modules/accounts/accounts.component.html index fbab8c8f..b80f69d4 100644 --- a/webapp/src/app/modules/accounts/accounts.component.html +++ b/webapp/src/app/modules/accounts/accounts.component.html @@ -31,7 +31,7 @@ type="button" matTooltip="Neuen Account anlegen" (click)="startCreate()"> - person_add + {{ PERSON_ADD_ICON }} Neuer Account } @@ -68,7 +68,7 @@ type="button" aria-label="Bearbeiten" (click)="startEdit(row)"> - edit + {{ EDIT_ICON }} diff --git a/webapp/src/app/modules/accounts/accounts.component.ts b/webapp/src/app/modules/accounts/accounts.component.ts index b8ec1d26..5a7643d4 100644 --- a/webapp/src/app/modules/accounts/accounts.component.ts +++ b/webapp/src/app/modules/accounts/accounts.component.ts @@ -44,6 +44,14 @@ import { UserRole, } from '../../api'; import { StatusPipe } from '../../shared/pipes/status.pipe'; +import { + DELETE_ICON, + EDIT_ICON, + PERSON_ADD_ICON, + PERSON_CHECK_ICON, + PERSON_OFF_ICON, + SWITCH_ACCOUNT_ICON, +} from '../../shared/ui/icons'; @Component({ selector: 'app-accounts', @@ -71,6 +79,13 @@ import { StatusPipe } from '../../shared/pipes/status.pipe'; standalone: true, }) export class AccountsComponent implements OnInit { + readonly PERSON_ADD_ICON = PERSON_ADD_ICON; + readonly EDIT_ICON = EDIT_ICON; + readonly SWITCH_ACCOUNT_ICON = SWITCH_ACCOUNT_ICON; + readonly PERSON_CHECK_ICON = PERSON_CHECK_ICON; + readonly PERSON_OFF_ICON = PERSON_OFF_ICON; + readonly DELETE_ICON = DELETE_ICON; + protected readonly credentialService = inject(CredentialService); private readonly snackBar = inject(MatSnackBar); private readonly router = inject(Router); diff --git a/webapp/src/app/modules/app-login/app-login.component.html b/webapp/src/app/modules/app-login/app-login.component.html index 0c3c7754..0cc67570 100644 --- a/webapp/src/app/modules/app-login/app-login.component.html +++ b/webapp/src/app/modules/app-login/app-login.component.html @@ -58,7 +58,7 @@ " (click)="showPassword = !showPassword"> {{ - showPassword ? 'visibility' : 'visibility_off' + showPassword ? VISIBILITY_ICON : VISIBILITY_OFF_ICON }} @if (credentialsForm.controls.password.hasError('required')) { @@ -91,7 +91,7 @@ } @else {