Compare commits

..
Author SHA1 Message Date
spsaefan 1e8e82f1d9 Support multiple roles in account UI
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-13 11:03:57 +02:00
spsaefan 13507c2ae8 Support multiple roles in account services 2026-07-13 11:03:57 +02:00
spsaefan 1c535a872f Add multi-role account 2026-07-13 11:03:57 +02:00
Mats Paul Tončik baf5b17239 Merge remote-tracking branch 'origin/dev' into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-12 23:47:09 +02:00
Mats Paul Tončik fa5e42a5eb fix(person/publications): made URL stateful and moved retrieval logic to resolvers 2026-07-12 23:39:25 +02:00
farajollahi 304ce0f1ab Merge pull request 'remove dfg projects analyse' (#211) from dfg-projects-analyse into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #211
2026-07-12 21:04:45 +02:00
farajollahi 92e32cd79e Merge branch 'dev' into dfg-projects-analyse
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-12 20:59:36 +02:00
farajollahi acad12bf27 remove dfg projects analyse
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-07-12 20:32:01 +02:00
farajollahi 3fa6f1dd6e Merge pull request 'fix dfg projects analyse' (#210) from dfg-projects-analyse into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #210
2026-07-12 20:20:07 +02:00
farajollahi f20be8aa63 fix dfg projects analyse
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-07-12 18:32:04 +02:00
genja 0f3388d290 Merge pull request 'feature/keywords-analysis' (#209) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #209
2026-07-12 16:32:28 +02:00
genja 2e855dcf7b removed commented sections, cleaned log outputs
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-12 16:30:44 +02:00
genja 680d2924ee Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keyword-analysis
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-12 16:25:12 +02:00
genja ace2a6bba3 added tooltips, snackbar messages 2026-07-12 16:23:19 +02:00
genja 6dfec1cfd4 updated keywords extraction logic for accepting pdfs 2026-07-12 16:22:43 +02:00
farajollahi 4568669d53 Merge pull request 'bookmark-Authors' (#208) from bookmark-Authors into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #208
2026-07-12 13:42:42 +02:00
farajollahi e162ec1cac Merge branch 'dev' into bookmark-Authors
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-07-12 13:35:35 +02:00
farajollahi 4027728626 Merge pull request 'dashboard-statics' (#207) from dashboard-statics into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #207
2026-07-12 13:33:11 +02:00
farajollahi c12393a906 bookmark authors
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-12 13:12:57 +02:00
genja e5cf17620a fixed layout for fileupload, added snackbars on errors 2026-07-09 23:29:06 +02:00
genja ea3ddabac0 file upload integration fixes 2026-07-09 23:28:40 +02:00
genja 233a2d2fca file upload component added (version 1) 2026-07-09 11:37:12 +02:00
genja b12e254cae added file upload component to keywords extraction UI 2026-07-09 11:36:30 +02:00
genja 40610c94c5 regenerated services 2026-07-09 11:34:56 +02:00
genja 2b1aa8d9e3 added file upload backend logic + content extraction from pdf files 2026-07-09 11:34:43 +02:00
75 changed files with 3549 additions and 955 deletions
+2 -1
View File
@@ -18,7 +18,8 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c
"websockets==12.0" \
"partial-json-parser==0.2.1.1.post7" \
"sqlmodel~=0.0.33" \
"argon2-cffi~=25.1.0"
"argon2-cffi~=25.1.0" \
"pypdf==6.14.2"
COPY [ "src/main", "/home" ]
COPY [ "src/data", "/data" ]
+1
View File
@@ -10,6 +10,7 @@ dependencies = [
"fastapi~=0.115.0",
"httpx~=0.27.0",
"openai~=2.41.0",
"pypdf==6.14.2",
"pydantic~=2.7.1",
"pydantic-settings~=2.2.1",
"pyjwt~=2.8.0",
@@ -1,9 +1,9 @@
import uuid
from typing import List, Optional
from pydantic import BaseModel, Field
from pydantic import BaseModel, Field, model_validator
from inse.auth.model import UserRole
from inse.auth.model import UserRole, normalize_roles
class OrganizationProfile(BaseModel):
@@ -16,7 +16,7 @@ class AccountProfile(BaseModel):
id: uuid.UUID
email: str
name: str
role: UserRole
roles: List[UserRole]
organization_id: uuid.UUID
organization_name: str
deleted: bool
@@ -34,20 +34,45 @@ class AccountPage(BaseModel):
class CreateAccountRequest(BaseModel):
@model_validator(mode="before")
@classmethod
def _role_to_roles(cls, values):
if isinstance(values, dict) and "roles" not in values and "role" in values:
values = {**values, "roles": [values["role"]]}
return values
email: str = Field(min_length=3)
name: str = Field(min_length=1)
role: UserRole = UserRole.USER
roles: List[UserRole] = Field(default_factory=lambda: [UserRole.USER])
organization_id: uuid.UUID
password: str = Field(min_length=8)
openalex_person_id: Optional[str] = None
@model_validator(mode="after")
def _normalize_roles(self):
self.roles = normalize_roles(self.roles)
return self
class UpdateAccountRequest(BaseModel):
@model_validator(mode="before")
@classmethod
def _role_to_roles(cls, values):
if isinstance(values, dict) and "roles" not in values and "role" in values:
values = {**values, "roles": [values["role"]]}
return values
email: Optional[str] = Field(default=None, min_length=3)
name: Optional[str] = Field(default=None, min_length=1)
role: Optional[UserRole] = None
roles: Optional[List[UserRole]] = None
organization_id: Optional[uuid.UUID] = None
password: Optional[str] = Field(default=None, min_length=8)
openalex_person_id: Optional[str] = None
deleted: Optional[bool] = None
activated: Optional[bool] = None
@model_validator(mode="after")
def _normalize_roles(self):
if self.roles is not None:
self.roles = normalize_roles(self.roles)
return self
@@ -5,7 +5,13 @@ from fastapi import HTTPException, status
from sqlmodel import Session, func, or_, select
from inse.auth import service as auth_service
from inse.auth.model import AccessTokenMetadata, Account, Organization, UserRole
from inse.auth.model import (
AccessTokenMetadata,
Account,
Organization,
UserRole,
normalize_roles,
)
from .model import (
AccountPage,
@@ -28,13 +34,17 @@ def _role_allowed_for_editor(editor_role: UserRole, role: UserRole) -> bool:
return False
def _roles_allowed_for_editor(editor_role: UserRole, roles: list[UserRole]) -> bool:
return all(_role_allowed_for_editor(editor_role, role) for role in roles)
def _account_to_profile(account: Account, token: AccessTokenMetadata) -> AccountProfile:
organization_name = account.organization.name if account.organization else ""
return AccountProfile(
id=account.id,
email=account.email,
name=account.name,
role=account.role,
roles=normalize_roles(account.roles),
organization_id=account.organization_id,
organization_name=organization_name,
deleted=account.deleted,
@@ -175,7 +185,7 @@ def create_account(
detail="Admins can only create accounts in their own organization.",
)
if not _role_allowed_for_editor(access_token.effective_role, payload.role):
if not _roles_allowed_for_editor(access_token.effective_role, payload.roles):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You cannot assign this role.",
@@ -194,7 +204,7 @@ def create_account(
account = Account(
email=email,
name=payload.name.strip(),
role=payload.role,
roles=payload.roles,
organization_id=payload.organization_id,
password_hash=auth_service._hash_password(payload.password),
openalex_person_id=payload.openalex_person_id,
@@ -261,15 +271,15 @@ def update_account(
if payload.openalex_person_id is not None:
account.openalex_person_id = payload.openalex_person_id
if payload.role is not None:
if payload.roles is not None:
if not can_admin_update:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
if not _role_allowed_for_editor(access_token.effective_role, payload.role):
if not _roles_allowed_for_editor(access_token.effective_role, payload.roles):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You cannot assign this role.",
)
account.role = payload.role
account.roles = payload.roles
account.epoch += 1
if payload.organization_id is not None:
+80 -7
View File
@@ -3,8 +3,8 @@ from datetime import datetime
from enum import StrEnum
from typing import List
from pydantic import BaseModel
from sqlalchemy import UniqueConstraint
from pydantic import BaseModel, model_validator
from sqlalchemy import JSON, Column, UniqueConstraint
from sqlmodel import Field, Relationship, SQLModel
@@ -15,6 +15,35 @@ class UserRole(StrEnum):
USER = "USER"
ROLE_PRIORITY = {
UserRole.SUPER_ADMIN: 0,
UserRole.ADMIN: 1,
UserRole.MANAGER: 2,
UserRole.USER: 3,
}
def normalize_roles(roles: List[UserRole] | List[str] | UserRole | str | None) -> List[UserRole]:
if roles is None:
return [UserRole.USER]
if isinstance(roles, (str, UserRole)):
roles = [roles]
normalized = []
seen = set()
for role in roles:
user_role = role if isinstance(role, UserRole) else UserRole(role)
if user_role not in seen:
normalized.append(user_role)
seen.add(user_role)
return sorted(normalized or [UserRole.USER], key=lambda role: ROLE_PRIORITY[role])
def effective_role_for_roles(roles: List[UserRole] | List[str] | UserRole | str | None) -> UserRole:
return normalize_roles(roles)[0]
class TokenType(StrEnum):
ID_TOKEN = "ID_TOKEN"
REFRESH_TOKEN = "REFRESH_TOKEN"
@@ -57,6 +86,13 @@ class Organization(Durable, table=True):
class Account(Durable, table=True):
@model_validator(mode="before")
@classmethod
def _role_to_roles(cls, values):
if isinstance(values, dict) and "roles" not in values and "role" in values:
values = {**values, "roles": [values["role"]]}
return values
id: uuid.UUID | None = Field(
default_factory=uuid.uuid4,
primary_key=True,
@@ -101,15 +137,22 @@ class Account(Durable, table=True):
nullable=False,
description="The unique identifier of the organization strictly associated with this account.",
)
role: UserRole = Field(
default=UserRole.USER,
index=True,
nullable=False,
description="The specific role this account holds within its organization.",
roles: List[UserRole] = Field(
default_factory=lambda: [UserRole.USER],
sa_column=Column(JSON, nullable=False, default=lambda: [UserRole.USER.value]),
description="The roles this account holds within its organization.",
)
organization: Organization = Relationship(back_populates="accounts")
@property
def role(self) -> UserRole:
return effective_role_for_roles(self.roles)
@role.setter
def role(self, value: UserRole) -> None:
self.roles = normalize_roles(value)
class Secret(SQLModel, table=True):
__table_args__ = (
@@ -176,6 +219,17 @@ class IdTokenMetadata(BaseTokenData):
class AccessTokenMetadata(BaseTokenData):
@model_validator(mode="before")
@classmethod
def _effective_role_to_roles(cls, values):
if (
isinstance(values, dict)
and "effective_roles" not in values
and "effective_role" in values
):
values = {**values, "effective_roles": [values["effective_role"]]}
return values
token_type: TokenType = Field(
default=TokenType.ACCESS_TOKEN,
const=True,
@@ -191,6 +245,10 @@ class AccessTokenMetadata(BaseTokenData):
default=UserRole.USER,
description="The specific role this access token grants within its organization.",
)
effective_roles: List[UserRole] = Field(
default_factory=lambda: [UserRole.USER],
description="The roles this access token grants within its organization.",
)
effective_organization_id: uuid.UUID = Field(
description="The unique identifier of the organization associated with this access token.",
)
@@ -211,6 +269,17 @@ class AccessToken(AccessTokenMetadata):
class RefreshTokenMetadata(BaseTokenData):
@model_validator(mode="before")
@classmethod
def _effective_role_to_roles(cls, values):
if (
isinstance(values, dict)
and "effective_roles" not in values
and "effective_role" in values
):
values = {**values, "effective_roles": [values["effective_role"]]}
return values
token_type: TokenType = Field(
default=TokenType.REFRESH_TOKEN,
const=True,
@@ -223,6 +292,10 @@ class RefreshTokenMetadata(BaseTokenData):
default=UserRole.USER,
description="The specific role this access token grants within its organization.",
)
effective_roles: List[UserRole] = Field(
default_factory=lambda: [UserRole.USER],
description="The roles this access token grants within its organization.",
)
effective_organization_id: uuid.UUID = Field(
description="The unique identifier of the organization associated with this access token.",
)
+36 -8
View File
@@ -28,6 +28,8 @@ from inse.auth.model import (
SecretPurpose,
TokenType,
UserRole,
effective_role_for_roles,
normalize_roles,
)
from inse.config import get_settings
from inse.database import get_session
@@ -44,6 +46,7 @@ PASSWORD_RESET_MAX_REQUESTS_PER_WINDOW = 3 # 3 minutes
REAL_ACCOUNT_ID_KEY = "real_account_id"
EFFECTIVE_ACCOUNT_ID_KEY = "effective_account_id"
EFFECTIVE_ROLE_KEY = "effective_role"
EFFECTIVE_ROLES_KEY = "effective_roles"
EFFECTIVE_ORGANIZATION_ID_KEY = "effective_organization_id"
EPOCH_KEY = "epoch"
USER_FINGERPRINT_HASH_KEY = "user_fingerprint_hash"
@@ -110,14 +113,14 @@ def create_predefined_accounts(session: Session, file_path: str):
session.add(organization)
for account_data in data.get("accounts", []):
organization_id = uuid.UUID(account_data["organization_id"])
role = UserRole(account_data["role"])
roles = normalize_roles(account_data.get("roles", account_data.get("role")))
email = account_data["email"]
password_hash = _hash_password(account_data["password"])
account = Account(
email=email,
name=account_data["name"],
organization_id=organization_id,
role=role,
roles=roles,
password_hash=password_hash,
epoch=0,
)
@@ -609,6 +612,11 @@ def _get_current_user_access_token_payload(
),
epoch=access_token_payload[EPOCH_KEY],
effective_role=UserRole(access_token_payload[EFFECTIVE_ROLE_KEY]),
effective_roles=normalize_roles(
access_token_payload.get(
EFFECTIVE_ROLES_KEY, access_token_payload[EFFECTIVE_ROLE_KEY]
)
),
effective_organization_id=uuid.UUID(
access_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY]
),
@@ -649,6 +657,11 @@ def _get_current_user_refresh_token_payload(
),
epoch=refresh_token_payload[EPOCH_KEY],
effective_role=UserRole(refresh_token_payload[EFFECTIVE_ROLE_KEY]),
effective_roles=normalize_roles(
refresh_token_payload.get(
EFFECTIVE_ROLES_KEY, refresh_token_payload[EFFECTIVE_ROLE_KEY]
)
),
effective_organization_id=uuid.UUID(
refresh_token_payload[EFFECTIVE_ORGANIZATION_ID_KEY]
),
@@ -728,7 +741,7 @@ def _get_account_epoch(
return account.epoch
def _get_account_role(session: Session, account_id: uuid.UUID) -> UserRole:
def _get_account_roles(session: Session, account_id: uuid.UUID) -> list[UserRole]:
"""Retrieves the role for the given account ID.
Args:
@@ -736,14 +749,14 @@ def _get_account_role(session: Session, account_id: uuid.UUID) -> UserRole:
account_id (uuid.UUID): The unique identifier of the account for which to retrieve the role.
Returns:
UserRole: The role associated with the given account ID.
list[UserRole]: The roles associated with the given account ID.
"""
account = session.get(Account, account_id)
if not account or account.deleted or not account.activated or account.id is None:
raise AccountNotFoundException
return account.role
return normalize_roles(account.roles)
def _get_account_organization(session: Session, account_id: uuid.UUID) -> uuid.UUID:
@@ -794,13 +807,16 @@ def _is_valid_impersonation(
):
raise AccountNotFoundException
if real_account.role == UserRole.SUPER_ADMIN:
real_account_role = effective_role_for_roles(real_account.roles)
effective_account_role = effective_role_for_roles(effective_account.roles)
if real_account_role == UserRole.SUPER_ADMIN:
return True # Super admins can impersonate any account
if real_account.organization_id != effective_account.organization_id:
return False # Cannot impersonate accounts from different organizations
if real_account.role == UserRole.ADMIN and effective_account.role in [
if real_account_role == UserRole.ADMIN and effective_account_role in [
UserRole.MANAGER,
UserRole.USER,
]:
@@ -847,7 +863,8 @@ def get_access_token(
detail="Impersonation not allowed",
)
role = _get_account_role(session=session, account_id=effective_account_id)
roles = _get_account_roles(session=session, account_id=effective_account_id)
role = effective_role_for_roles(roles)
epoch = _get_account_epoch(account_id=effective_account_id, session=session)
organization_id = _get_account_organization(
session=session, account_id=effective_account_id
@@ -862,6 +879,7 @@ def get_access_token(
effective_organization_id=organization_id,
epoch=epoch,
user_fingerprint_hash=user_fingerprint_hash,
effective_roles=roles,
)
_set_refresh_token(
response=response,
@@ -870,6 +888,7 @@ def get_access_token(
effective_role=role,
effective_organization_id=organization_id,
epoch=epoch,
effective_roles=roles,
)
return AccessResponse(
access_token=access_token,
@@ -974,6 +993,7 @@ def refresh_access_token(
effective_organization_id=refresh_token.effective_organization_id,
epoch=refresh_token.epoch,
user_fingerprint_hash=user_fingerprint_hash,
effective_roles=refresh_token.effective_roles,
)
@@ -1020,6 +1040,7 @@ def _set_refresh_token(
effective_role: UserRole,
effective_organization_id: uuid.UUID,
epoch: int,
effective_roles: list[UserRole] | None = None,
) -> RefreshTokenMetadata:
"""Builds a refresh token for the specified account IDs, role, organization ID, epoch, and fingerprint hash.
@@ -1038,10 +1059,12 @@ def _set_refresh_token(
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
minutes=REFRESH_TOKEN_EXPIRATION_MINUTES
)
effective_roles = normalize_roles(effective_roles or effective_role)
payload = {
REAL_ACCOUNT_ID_KEY: str(real_account_id),
EFFECTIVE_ACCOUNT_ID_KEY: str(effective_account_id),
EFFECTIVE_ROLE_KEY: effective_role.value,
EFFECTIVE_ROLES_KEY: [role.value for role in effective_roles],
EFFECTIVE_ORGANIZATION_ID_KEY: str(effective_organization_id),
EPOCH_KEY: epoch,
}
@@ -1058,6 +1081,7 @@ def _set_refresh_token(
expires_at=expires_at,
epoch=epoch,
effective_role=effective_role,
effective_roles=effective_roles,
effective_organization_id=effective_organization_id,
)
@@ -1069,6 +1093,7 @@ def _build_access_token(
effective_organization_id: uuid.UUID,
epoch: int,
user_fingerprint_hash: str,
effective_roles: list[UserRole] | None = None,
) -> AccessToken:
"""Builds an access token for the specified account IDs, role, organization ID, epoch, and fingerprint hash.
@@ -1087,10 +1112,12 @@ def _build_access_token(
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
minutes=ACCESS_TOKEN_EXPIRATION_MINUTES
)
effective_roles = normalize_roles(effective_roles or effective_role)
payload = {
REAL_ACCOUNT_ID_KEY: str(real_account_id),
EFFECTIVE_ACCOUNT_ID_KEY: str(effective_account_id),
EFFECTIVE_ROLE_KEY: effective_role.value,
EFFECTIVE_ROLES_KEY: [role.value for role in effective_roles],
EFFECTIVE_ORGANIZATION_ID_KEY: str(effective_organization_id),
EPOCH_KEY: epoch,
USER_FINGERPRINT_HASH_KEY: user_fingerprint_hash,
@@ -1108,6 +1135,7 @@ def _build_access_token(
expires_at=expires_at,
epoch=epoch,
effective_role=effective_role,
effective_roles=effective_roles,
effective_organization_id=effective_organization_id,
user_fingerprint_hash=user_fingerprint_hash,
raw_token=raw_token,
@@ -0,0 +1 @@
"""User bookmark feature."""
+36
View File
@@ -0,0 +1,36 @@
import uuid
from datetime import datetime, timezone
from pydantic import BaseModel, Field as PydanticField
from sqlalchemy import UniqueConstraint
from sqlmodel import Field, SQLModel
class PersonBookmark(SQLModel, table=True):
__tablename__ = "person_bookmark"
__table_args__ = (
UniqueConstraint(
"account_id", "person_id", name="uq_person_bookmark_account_person"
),
)
id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)
account_id: uuid.UUID = Field(
foreign_key="account.id", nullable=False, index=True
)
person_id: str = Field(nullable=False, index=True)
person_name: str | None = Field(default=None)
created_at: datetime = Field(
default_factory=lambda: datetime.now(timezone.utc), nullable=False, index=True
)
class CreatePersonBookmark(BaseModel):
person_name: str | None = PydanticField(default=None, max_length=500)
class PersonBookmarkResponse(BaseModel):
person_id: str
person_name: str | None
created_at: datetime
+47
View File
@@ -0,0 +1,47 @@
from fastapi import APIRouter, Response, status
from inse.auth import service as auth_service
from inse.auth.model import AccessTokenMetadata
from inse.database import SessionDep
from . import service
from .model import CreatePersonBookmark, PersonBookmarkResponse
router = APIRouter(prefix="/api/bookmarks", tags=["Bookmarks"])
@router.get("/persons", operation_id="listPersonBookmarks")
def list_person_bookmarks(
session: SessionDep,
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> list[PersonBookmarkResponse]:
return service.list_person_bookmarks(session, access_token.effective_account_id)
@router.put("/persons/{person_id}", operation_id="bookmarkPerson")
def bookmark_person(
person_id: str,
payload: CreatePersonBookmark,
session: SessionDep,
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> PersonBookmarkResponse:
return service.create_person_bookmark(
session, access_token.effective_account_id, person_id, payload
)
@router.delete(
"/persons/{person_id}",
operation_id="removePersonBookmark",
status_code=status.HTTP_204_NO_CONTENT,
)
def remove_person_bookmark(
person_id: str,
session: SessionDep,
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> Response:
service.delete_person_bookmark(
session, access_token.effective_account_id, person_id
)
return Response(status_code=status.HTTP_204_NO_CONTENT)
@@ -0,0 +1,81 @@
import uuid
from fastapi import HTTPException, status
from sqlmodel import Session, select
from .model import CreatePersonBookmark, PersonBookmark, PersonBookmarkResponse
def normalize_person_id(person_id: str) -> str:
normalized = person_id.strip().rstrip("/").split("/")[-1]
if not normalized:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="A person ID is required.",
)
return normalized
def list_person_bookmarks(
session: Session, account_id: uuid.UUID
) -> list[PersonBookmarkResponse]:
bookmarks = session.exec(
select(PersonBookmark)
.where(PersonBookmark.account_id == account_id)
.order_by(PersonBookmark.created_at.desc())
).all()
return [
PersonBookmarkResponse(
person_id=bookmark.person_id,
person_name=bookmark.person_name,
created_at=bookmark.created_at,
)
for bookmark in bookmarks
]
def create_person_bookmark(
session: Session,
account_id: uuid.UUID,
person_id: str,
payload: CreatePersonBookmark,
) -> PersonBookmarkResponse:
normalized_id = normalize_person_id(person_id)
bookmark = session.exec(
select(PersonBookmark).where(
PersonBookmark.account_id == account_id,
PersonBookmark.person_id == normalized_id,
)
).first()
if bookmark is None:
bookmark = PersonBookmark(
account_id=account_id,
person_id=normalized_id,
person_name=payload.person_name,
)
session.add(bookmark)
elif payload.person_name:
bookmark.person_name = payload.person_name
session.commit()
session.refresh(bookmark)
return PersonBookmarkResponse(
person_id=bookmark.person_id,
person_name=bookmark.person_name,
created_at=bookmark.created_at,
)
def delete_person_bookmark(
session: Session, account_id: uuid.UUID, person_id: str
) -> None:
normalized_id = normalize_person_id(person_id)
bookmark = session.exec(
select(PersonBookmark).where(
PersonBookmark.account_id == account_id,
PersonBookmark.person_id == normalized_id,
)
).first()
if bookmark is not None:
session.delete(bookmark)
session.commit()
@@ -0,0 +1,71 @@
import uuid
from sqlmodel import Session, SQLModel, create_engine
from inse.auth.model import Account, Organization
from .model import CreatePersonBookmark
from .service import (
create_person_bookmark,
delete_person_bookmark,
list_person_bookmarks,
)
def _session_with_account():
engine = create_engine(
"sqlite:///:memory:", connect_args={"check_same_thread": False}
)
SQLModel.metadata.create_all(engine)
session = Session(engine)
organization = Organization(name="Bookmark Test Org")
session.add(organization)
session.flush()
account = Account(
email="bookmarks@example.org",
name="Bookmark Tester",
password_hash="not-used",
organization_id=organization.id,
)
session.add(account)
session.commit()
return session, account.id
def test_person_bookmarks_are_idempotent_and_normalize_openalex_ids():
session, account_id = _session_with_account()
assert isinstance(account_id, uuid.UUID)
create_person_bookmark(
session,
account_id,
"https://openalex.org/A123",
CreatePersonBookmark(person_name="Ada Example"),
)
create_person_bookmark(
session,
account_id,
"A123",
CreatePersonBookmark(person_name="Ada Updated"),
)
bookmarks = list_person_bookmarks(session, account_id)
assert len(bookmarks) == 1
assert bookmarks[0].person_id == "A123"
assert bookmarks[0].person_name == "Ada Updated"
def test_deleting_a_person_bookmark_is_idempotent():
session, account_id = _session_with_account()
assert isinstance(account_id, uuid.UUID)
create_person_bookmark(
session,
account_id,
"A123",
CreatePersonBookmark(person_name="Ada Example"),
)
delete_person_bookmark(session, account_id, "A123")
delete_person_bookmark(session, account_id, "A123")
assert list_person_bookmarks(session, account_id) == []
+12 -14
View File
@@ -599,7 +599,7 @@ async def _top_project_authors(
return []
counts: dict[str, int] = {}
names: dict[str, str] = {}
for bucket in await _top_bund_project_author_buckets(aliases):
for bucket in await _top_dfg_project_author_buckets(aliases):
key = str(bucket.get("key", "")).strip()
if key:
normalized_key = key.casefold()
@@ -635,20 +635,20 @@ async def _top_project_authors(
]
async def _top_bund_project_author_buckets(
async def _top_dfg_project_author_buckets(
aliases: list[str],
) -> list[dict[str, Any]]:
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_V1,
index=ESIndex.PROJECTS_DFG_ALL,
body={
"size": 0,
"query": _alias_match_query("Zuwendungsempfänger", aliases),
"query": _dfg_institution_query(aliases),
"aggs": {
"people": {
"terms": {
"script": {
"lang": "painless",
"source": _bund_persons_script(),
"source": _dfg_involved_persons_script(),
},
"size": 10000,
}
@@ -662,17 +662,15 @@ async def _top_bund_project_author_buckets(
)
def _bund_persons_script() -> str:
def _dfg_involved_persons_script() -> str:
return (
"def names = new HashSet(); "
"if (params['_source'].containsKey('Arb') && params['_source']['Arb'] != null) { "
" for (entry in params['_source']['Arb'].entrySet()) { "
" def value = entry.getValue(); "
" if (value instanceof String && value.length() > 0) { "
" if (value.contains(';')) { "
" for (name in value.splitOnToken(';')) { names.add(name.trim()); } "
" } else { names.add(value.trim()); } "
" } "
"def value = params['_source'].containsKey('Beteiligte Personen') "
" ? params['_source']['Beteiligte Personen'] : null; "
"if (value instanceof String && value.length() > 0) { "
" for (name in value.splitOnToken(';')) { "
" def trimmed = name.trim(); "
" if (trimmed.length() > 0) { names.add(trimmed); } "
" } "
"} "
"return new ArrayList(names);"
+63 -13
View File
@@ -98,7 +98,7 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
@pytest.mark.anyio
async def test_top_authors_maps_works_and_bund_project_aggregations():
async def test_top_authors_maps_works_and_dfg_project_aggregations():
async def search(**kwargs):
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
return {
@@ -131,7 +131,7 @@ async def test_top_authors_maps_works_and_bund_project_aggregations():
}
}
}
if kwargs["index"] == ESIndex.PROJECTS_BUND_V1:
if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL:
return {
"aggregations": {
"people": {
@@ -184,21 +184,21 @@ async def test_top_authors_maps_works_and_bund_project_aggregations():
in {ESIndex.PROJECTS_DFG_ALL, ESIndex.PROJECTS_BUND_V1}
]
assert len(project_calls) == 1
assert project_calls[0].kwargs["index"] == ESIndex.PROJECTS_BUND_V1
assert project_calls[0].kwargs["body"]["query"]["bool"]["should"][0]["match"] == {
"Zuwendungsempfänger": {
"query": "Example Org",
"operator": "and",
}
}
assert project_calls[0].kwargs["index"] == ESIndex.PROJECTS_DFG_ALL
assert project_calls[0].kwargs["body"]["query"]["bool"][
"minimum_should_match"
] == 1
assert "Beteiligte Personen" in project_calls[0].kwargs["body"]["aggs"][
"people"
]["terms"]["script"]["source"]
@pytest.mark.anyio
async def test_top_authors_keeps_bund_project_authors_without_openalex_match():
async def test_top_authors_keeps_dfg_project_authors_without_openalex_match():
async def search(**kwargs):
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
return {"hits": {"hits": []}}
if kwargs["index"] == ESIndex.PROJECTS_BUND_V1:
if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL:
return {
"aggregations": {
"people": {
@@ -228,11 +228,11 @@ async def test_top_authors_keeps_bund_project_authors_without_openalex_match():
@pytest.mark.anyio
async def test_top_authors_returns_top_ten_bund_project_people_by_project_count():
async def test_top_authors_returns_top_ten_dfg_project_people_by_project_count():
async def search(**kwargs):
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
return {"hits": {"hits": []}}
if kwargs["index"] == ESIndex.PROJECTS_BUND_V1:
if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL:
return {
"aggregations": {
"people": {
@@ -262,6 +262,56 @@ async def test_top_authors_returns_top_ten_bund_project_people_by_project_count(
assert len(result.projects) == 10
@pytest.mark.anyio
async def test_top_authors_combines_dfg_involved_people_case_insensitively():
async def search(**kwargs):
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
return {
"hits": {
"hits": [
{
"_source": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
"works_count": 1,
"counts_by_year": [],
}
}
]
}
}
if kwargs["index"] == ESIndex.PROJECTS_DFG_ALL:
return {
"aggregations": {
"people": {
"buckets": [
{"key": "Ada Example", "doc_count": 2},
{"key": "ada example", "doc_count": 3},
{"key": "DFG Person", "doc_count": 4},
]
}
}
}
return {"aggregations": {"authors": {"buckets": []}}}
with patch(
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(side_effect=search),
), patch(
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
new=AsyncMock(return_value=["Example University"]),
), patch(
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
new=AsyncMock(return_value=[]),
):
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
assert [author.model_dump() for author in result.projects] == [
{"id": "A1", "name": "Ada Example", "count": 5},
{"id": None, "name": "DFG Person", "count": 4},
]
@pytest.mark.anyio
async def test_top_authors_returns_partial_response_when_one_source_fails():
async def search(**kwargs):
+78
View File
@@ -16,9 +16,72 @@ engine = create_engine(
)
def _migrate_secret_table():
"""Upgrade the legacy login-only secret table without losing its data."""
columns = {column["name"] for column in inspect(engine).get_columns("secret")}
required_columns = {
"purpose",
"request_count",
"request_window_started_at",
}
if required_columns.issubset(columns):
return
# SQLite cannot alter a UNIQUE constraint in place. Rebuild the table so an
# account can hold both a login OTK and a password-reset secret.
with engine.begin() as connection:
connection.execute(text("ALTER TABLE secret RENAME TO secret_legacy"))
connection.execute(
text(
"""
CREATE TABLE secret (
id CHAR(32) NOT NULL PRIMARY KEY,
account_id CHAR(32) NOT NULL,
purpose VARCHAR NOT NULL,
secret_value VARCHAR NOT NULL,
expires_at DATETIME NOT NULL,
request_count INTEGER NOT NULL DEFAULT 0,
request_window_started_at DATETIME,
CONSTRAINT uq_secret_account_purpose
UNIQUE (account_id, purpose),
FOREIGN KEY(account_id) REFERENCES account (id)
)
"""
)
)
connection.execute(
text(
"""
INSERT INTO secret (
id, account_id, purpose, secret_value, expires_at,
request_count, request_window_started_at
)
SELECT id, account_id, 'LOGIN_OTK', secret_value, expires_at,
0, NULL
FROM secret_legacy
"""
)
)
connection.execute(text("DROP TABLE secret_legacy"))
connection.execute(
text("CREATE INDEX ix_secret_account_id ON secret (account_id)")
)
connection.execute(text("CREATE INDEX ix_secret_purpose ON secret (purpose)"))
connection.execute(
text("CREATE INDEX ix_secret_expires_at ON secret (expires_at)")
)
connection.execute(
text(
"CREATE INDEX ix_secret_request_window_started_at "
"ON secret (request_window_started_at)"
)
)
def create_db_and_tables():
"""Creates the database and tables based on the SQLModel metadata."""
SQLModel.metadata.create_all(engine)
_migrate_secret_table()
columns = {column["name"] for column in inspect(engine).get_columns("account")}
if "activated" not in columns:
with engine.begin() as connection:
@@ -28,6 +91,21 @@ def create_db_and_tables():
"BOOLEAN NOT NULL DEFAULT TRUE"
)
)
if "roles" not in columns:
with engine.begin() as connection:
connection.execute(
text(
"ALTER TABLE account ADD COLUMN roles "
"JSON NOT NULL DEFAULT '[\"USER\"]'"
)
)
if "role" in columns:
connection.execute(
text(
"UPDATE account SET roles = '[\"' || role || '\"]' "
"WHERE role IS NOT NULL"
)
)
def get_session():
@@ -107,6 +107,7 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
def _wrap_exception(e: Exception) -> Exception:
logger.exception(f"Elasticsearch raised an exception: {e}")
if isinstance(e, httpx.HTTPStatusError):
if e.response.status_code == 404:
return ElasticsearchNotFoundException(
@@ -0,0 +1,58 @@
# inse/keywords/file_extraction.py
import base64
import logging
import httpx
from bs4 import BeautifulSoup
# import fitz
import io
from pypdf import PdfReader
from pypdf.errors import PdfReadError
logger = logging.getLogger(__name__)
def extract_text_from_upload(filename: str, content_base64: str, mime_type: str) -> str:
try:
raw = base64.b64decode(content_base64)
except Exception:
logger.warning("Failed to decode base64 for %s", filename)
return f"[{filename}: could not decode upload]"
if mime_type == "application/pdf" or filename.lower().endswith(".pdf"):
return _extract_pdf_text(filename, raw)
try:
return raw.decode("utf-8", errors="replace")
except Exception:
logger.warning("Failed to decode %s as text", filename)
return f"[{filename}: unsupported or undecodable content]"
def _extract_pdf_text(filename: str, raw: bytes) -> str:
try:
reader = PdfReader(io.BytesIO(raw), strict=False) # non-strict: tolerate minor spec violations
except Exception as e:
logger.warning("Failed to open PDF %s: %s", filename, e)
return f"[{filename}: PDF could not be opened (corrupted or invalid)]"
if reader.is_encrypted:
try:
# Attempt to decrypt with an empty password (common for "owner-locked"
# PDFs that don't require one to read content)
reader.decrypt("")
except Exception as e:
logger.warning("Encrypted PDF %s could not be decrypted: %s", filename, e)
return f"[{filename}: PDF is encrypted and could not be read]"
parts = []
for page_num, page in enumerate(reader.pages):
try:
parts.append(page.extract_text() or "")
except PdfReadError as e:
logger.warning("Failed to extract page %d of %s: %s", page_num, filename, e)
parts.append(f"[Page {page_num + 1} could not be extracted]")
except Exception as e:
logger.warning("Unexpected error extracting page %d of %s: %s", page_num, filename, e)
parts.append(f"[Page {page_num + 1} could not be extracted]")
return "\n".join(parts)
+256 -123
View File
@@ -23,7 +23,9 @@ from inse.keywords.model import (
KeywordEntry,
KeywordEntryWithTopic,
KeywordsWsEvent,
FileUpload,
)
from inse.keywords.extract_text import extract_text_from_upload
from inse.topics.logic import vector_search_topics_batch
logger = logging.getLogger(__name__)
EventCallback = Callable[[dict], Awaitable[None]]
@@ -64,7 +66,7 @@ async def extract_keywords(query: str, mode: str, limit: int) -> ExtractedKeywor
"""
start_time = time.time()
if mode == "url":
text = await _get_text_content(query)
text = await get_text_from_url(query)
system_prompt = KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT
else:
@@ -97,67 +99,18 @@ async def extract_keywords(query: str, mode: str, limit: int) -> ExtractedKeywor
return ExtractedKeywordsResponse(results=enriched, source=mode, source_url=query if mode == "url" else None, source_content=text, duration=elapsed_time)
async def _get_text_content(url: str) -> str:
"""
Fetches the HTML content from the given URL using httpx and extracts visible text.
"""
try:
headers = {
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/91.0.4472.124 Safari/537.36"
)
}
async with httpx.AsyncClient(timeout=30.0) as client:
response = await client.get(url, headers=headers)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
for element in soup(["script", "style"]):
element.decompose()
text = soup.get_text(separator=" ", strip=True)
text = " ".join(text.split())
return text
except httpx.HTTPError as e:
logger.error(f"HTTP error for {url}: {e}")
except Exception as e:
logger.error(f"Error processing {url}: {e}")
async def extract_keywords_stream_enriched(
query: str,
mode: str,
limit: int,
emit: EventCallback,
files: List[FileUpload] | None = None,
) -> ExtractedKeywordsResponse:
start_time = time.time()
timeout_seconds = 120
await emit(KeywordsWsEvent(type="status", step="started", message="Starte Keyword-Extraktion").model_dump())
if mode == "url":
await emit(KeywordsWsEvent(type="status", step="fetching_url", message=f"Extrahiere Inhalt von {query}").model_dump())
text = await _get_text_content(query)
if text:
await emit(KeywordsWsEvent(type="status", step="content_extracted", message=f"Extrahiert {len(text)} Zeichen").model_dump())
else:
await emit(KeywordsWsEvent(type="error", message=f"Fehler beim Abrufen des Inhalts von {query}").model_dump())
raise RuntimeError(f"Failed to fetch content from {query}")
system_prompt = KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT
else:
text = query
await emit(KeywordsWsEvent(type="status", step="text_received", message=f"Empfangen {len(text)} Zeichen").model_dump())
system_prompt = KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT
user_prompt = "\nNow analyze the following text.\n"
if limit:
user_prompt += f"\nExtract exactly {limit} keywords for each level.\n"
user_prompt += f"\nInput:\n{text}"
await emit(KeywordsWsEvent(type="status", step="calling_llm", message="Extrahiere Keywords...").model_dump())
LEVELS = ("broad_keywords", "coarse_grained", "fine_grained")
confirmed: Dict[str, List[KeywordEntryWithTopic]] = {level: [] for level in LEVELS}
enrichment_tasks: List[asyncio.Task] = []
@@ -183,78 +136,224 @@ async def extract_keywords_stream_enriched(
logger.error(f"Error fetching OpenAlex topic for keyword '{item.keyword}': {e}")
await emit_full_results()
async def on_chunk(event: Dict[str, Any]) -> None:
if event["type"] != "llm_chunk":
await emit(event)
return
def make_on_chunk(base_offset: Dict[str, int]):
"""
Builds an on_chunk callback for a single streaming LLM call.
`base_offset` records how many items each level already had in the
shared `confirmed` list *before* this call started, so growth from
this call's own (independent) partial JSON can be tracked correctly
even though `confirmed` keeps accumulating across multiple calls
(one per file).
"""
async def on_chunk(event: Dict[str, Any]) -> None:
if event["type"] != "llm_chunk":
await emit(event)
return
try:
partial = partial_json_parser.loads(event.get("_full_content", ""))
except Exception:
return
if not isinstance(partial, dict):
return
grew = False
for level in LEVELS:
current = partial.get(level) or []
# How many items belonging to *this* call have already been
# appended to the shared `confirmed` list.
local_have = len(confirmed[level]) - base_offset[level]
start_idx = len(confirmed[level])
while local_have < len(current):
raw_item = current[local_have]
try:
validated_item = KeywordEntry.model_validate(raw_item)
except ValidationError:
break
confirmed[level].append(KeywordEntryWithTopic(llm_keyword=validated_item))
local_have += 1
grew = True
for idx in range(start_idx, len(confirmed[level])):
keyword_text = confirmed[level][idx].llm_keyword.keyword
await emit(
KeywordsWsEvent(
type="status",
step="enriching",
message=f"Extracting topic for keyword '{keyword_text}'",
).model_dump()
)
task = asyncio.create_task(get_openalex_topic(level, idx, confirmed[level][idx].llm_keyword))
enrichment_tasks.append(task)
if grew:
await emit_full_results()
return on_chunk
async def run_llm_extraction(text: str, system_prompt: str, label: str | None = None) -> None:
"""
Runs a single independent streaming LLM extraction call over `text`
and folds its results into the shared `confirmed` structure. Used
once for url/text mode, and once *per file* for file mode.
"""
base_offset = {level: len(confirmed[level]) for level in LEVELS}
on_chunk = make_on_chunk(base_offset)
full_content_holder = {"value": ""}
async def emit_wrapper(event: Dict[str, Any]) -> None:
if event["type"] == "llm_chunk":
full_content_holder["value"] += event["content"]
event = {**event, "_full_content": full_content_holder["value"]}
await on_chunk(event)
user_prompt = "\nNow analyze the following text.\n"
if limit:
user_prompt += f"\nExtract exactly {limit} keywords for each level.\n"
user_prompt += f"\nInput:\n{text}"
suffix = f" for {label}" if label else ""
try:
partial = partial_json_parser.loads(event.get("_full_content", ""))
except Exception:
return
if not isinstance(partial, dict):
return
keywords_raw = await asyncio.wait_for(
llm.call_stream(
system_prompt=system_prompt,
user_prompt=user_prompt,
json_schema=ExtractedKeywordsLLM.model_json_schema(),
schema_name="extracted_keywords",
temperature=0.0,
top_p=0.95,
emit=emit_wrapper,
),
timeout=timeout_seconds,
)
except asyncio.TimeoutError:
await emit(KeywordsWsEvent(type="error", message=f"LLM call timed out after {timeout_seconds}s{suffix}").model_dump())
raise RuntimeError(f"LLM streaming call timed out{suffix}")
except asyncio.CancelledError:
await emit(KeywordsWsEvent(type="error", message="Request cancelled").model_dump())
raise
grew = False
if not keywords_raw:
# Empty string covers: real empty completion, APIConnectionError,
# and disconnect-during-emit (call_stream currently swallows all
# three the same way). Treat as a failed extraction.
await emit(KeywordsWsEvent(type="error", message=f"LLM call failed or returned no content{suffix}").model_dump())
raise RuntimeError(f"LLM streaming call returned empty content{suffix}")
for level in LEVELS:
current = partial.get(level) or []
start_idx = len(confirmed[level])
try:
json.loads(keywords_raw)
except json.JSONDecodeError as e:
await emit(KeywordsWsEvent(type="error", message=f"Invalid JSON in LLM response{suffix}: {e}").model_dump())
raise RuntimeError(f"LLM response is not valid JSON{suffix}")
while len(confirmed[level]) < len(current):
raw_item = current[len(confirmed[level])]
try:
validated_item = KeywordEntry.model_validate(raw_item)
except ValidationError:
break
# ---------- Gather input text & run extraction(s) ----------
source_content = ""
try:
if mode == "url":
await emit(KeywordsWsEvent(type="status", step="fetching_url", message=f"Extrahiere Inhalt von {query}").model_dump())
text = await get_text_from_url(query)
if text:
await emit(KeywordsWsEvent(type="status", step="content_extracted", message=f"Extrahiert {len(text)} Zeichen").model_dump())
else:
await emit(KeywordsWsEvent(type="error", message=f"Fehler beim Abrufen des Inhalts von {query}").model_dump())
raise RuntimeError(f"Failed to fetch content from {query}")
confirmed[level].append(KeywordEntryWithTopic(llm_keyword=validated_item))
grew = True
source_content = text
await run_llm_extraction(text, KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT)
elif mode == "files":
provided_files = files or []
total_files = len(provided_files)
await emit(
KeywordsWsEvent(
type="status",
step="extracting_files",
message=f"Extrahiere Inhalt aus {total_files} Datei(en)",
).model_dump()
)
file_texts: List[str] = []
failed_files: List[str] = []
for i, f in enumerate(provided_files, start=1):
text = await asyncio.to_thread(
extract_text_from_upload, f.filename, f.content_base64, f.mime_type
)
if not text or not text.strip():
await emit(
KeywordsWsEvent(
type="status",
step="content_extracted",
message=f"Kein Text in '{f.filename}' gefunden, überspringe",
).model_dump()
)
failed_files.append(f.filename)
continue
for idx in range(start_idx, len(confirmed[level])):
keyword_text = confirmed[level][idx].llm_keyword.keyword
await emit(
KeywordsWsEvent(
type="status",
step="enriching",
message=f"Extracting topic for keyword '{keyword_text}'",
step="content_extracted",
message=f"'{f.filename}': {len(text)} Zeichen extrahiert ({i}/{total_files})",
).model_dump()
)
await emit(
KeywordsWsEvent(
type="status",
step="calling_llm",
message=f"Extrahiere Keywords aus '{f.filename}' ({i}/{total_files})",
).model_dump()
)
task = asyncio.create_task(get_openalex_topic(level, idx, confirmed[level][idx].llm_keyword))
enrichment_tasks.append(task)
if grew:
await emit_full_results()
try:
# Each file gets its own, independent LLM call so
# keywords from one file can't dilute or get mixed up
# with the content of another. Results from every call
# still accumulate into the same shared `confirmed`
# structure, so they keep streaming to the client
# progressively as before.
await run_llm_extraction(
text,
KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT,
label=f"file '{f.filename}'",
)
file_texts.append(f"# {f.filename}\n\n{text}")
except asyncio.CancelledError:
raise
except Exception as e:
# Isolate failures: one broken/unparseable file shouldn't
# abort keyword extraction for the rest of the batch.
logger.error(f"Keyword extraction failed for file '{f.filename}': {e}")
failed_files.append(f.filename)
continue
full_content_holder = {"value": ""}
if not file_texts:
await emit(KeywordsWsEvent(type="error", message="Kein Text konnte aus den Dateien extrahiert werden").model_dump())
raise RuntimeError("Failed to extract text from uploaded files")
async def emit_wrapper(event: Dict[str, Any]) -> None:
if event["type"] == "llm_chunk":
full_content_holder["value"] += event["content"]
event = {**event, "_full_content": full_content_holder["value"]}
await on_chunk(event)
if failed_files:
await emit(
KeywordsWsEvent(
type="status",
step="content_extracted",
message=f"{len(failed_files)} Datei(en) konnten nicht verarbeitet werden: {', '.join(failed_files)}",
).model_dump()
)
# ---------- Call the LLM ----------
keywords = ""
try:
keywords = await asyncio.wait_for(
llm.call_stream(
system_prompt=system_prompt,
user_prompt=user_prompt,
json_schema=ExtractedKeywordsLLM.model_json_schema(),
schema_name="extracted_keywords",
temperature=0.0,
top_p=0.95,
emit=emit_wrapper,
),
timeout=timeout_seconds,
)
except asyncio.TimeoutError:
await emit(KeywordsWsEvent(type="error", message=f"LLM call timed out after {timeout_seconds}s").model_dump())
raise RuntimeError("LLM streaming call timed out")
except asyncio.CancelledError:
await emit(KeywordsWsEvent(type="error", message="Request cancelled").model_dump())
raise
source_content = "\n\n---\n\n".join(file_texts)
else:
text = query
await emit(KeywordsWsEvent(type="status", step="text_received", message=f"Empfangen {len(text)} Zeichen").model_dump())
source_content = text
await run_llm_extraction(text, KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT)
finally:
if enrichment_tasks:
@@ -264,22 +363,8 @@ async def extract_keywords_stream_enriched(
if pending:
await asyncio.gather(*pending, return_exceptions=True)
if not keywords:
# Empty string covers: real empty completion, APIConnectionError,
# and disconnect-during-emit (call_stream currently swallows all
# three the same way). Treat as a failed extraction.
await emit(KeywordsWsEvent(type="error", message="LLM call failed or returned no content").model_dump())
raise RuntimeError("LLM streaming call returned empty content")
# ---------- Finalize ----------
await emit(KeywordsWsEvent(type="status", step="parsing_response", message="Bearbeite Ergebnisse").model_dump())
try:
keywords_json = json.loads(keywords)
except json.JSONDecodeError as e:
await emit(KeywordsWsEvent(type="error", message=f"Invalid JSON in LLM response: {e}").model_dump())
raise RuntimeError("LLM response is not valid JSON")
await emit_full_results()
try:
@@ -294,8 +379,56 @@ async def extract_keywords_stream_enriched(
results=final_validated,
source=mode,
source_url=query if mode == "url" else None,
source_content=text,
source_content=source_content,
duration=elapsed_time,
)
return result
return result
async def get_text_from_url(url: str) -> str:
"""
Fetches the HTML content from the given URL using httpx and extracts visible text.
"""
try:
headers = {
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/91.0.4472.124 Safari/537.36"
)
}
async with httpx.AsyncClient(timeout=30.0) as client:
response = await client.get(url, headers=headers)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
for element in soup(["script", "style"]):
element.decompose()
text = soup.get_text(separator=" ", strip=True)
text = " ".join(text.split())
return text
except httpx.HTTPError as e:
logger.error(f"HTTP error for {url}: {e}")
except Exception as e:
logger.error(f"Error processing {url}: {e}")
async def _get_files_text(files: List[FileUpload]) -> str:
"""
Extracts and joins text from uploaded files. Runs blocking PDF parsing
in a thread so it doesn't stall the event loop.
NOTE: no longer used by extract_keywords_stream_enriched(), which now
extracts and processes each file independently so it can run a
separate LLM call per file. Kept here in case other callers still rely
on a single combined text blob.
"""
parts = []
for f in files:
text = await asyncio.to_thread(
extract_text_from_upload, f.filename, f.content_base64, f.mime_type
)
parts.append(text)
return "\n\n---\n\n".join(parts)
+11
View File
@@ -8,10 +8,21 @@ from typing import List, Literal
from pydantic import BaseModel, Field
from inse.topics.model import KeywordTopicMatch
class FileUpload(BaseModel):
filename: str = Field(description="The name of the uploaded file.")
content_base64: str = Field(description="The base64-encoded content of the uploaded file.")
mime_type: str = Field(description="The MIME type of the uploaded file, e.g., 'application/pdf', 'image/png', etc.")
class KeywordsRequest(BaseModel):
query: str = Field(description="The input text from which to extract keywords.")
files: list[FileUpload] | None = None
mode: str = Field(description="The mode of keyword extraction, e.g., 'url', 'text', or 'keywords'.")
limit: int = Field(default=None, description="The maximum number of keywords to extract.")
# class KeywordsRequest(BaseModel):
# query: str = Field(description="The input text from which to extract keywords.")
# mode: str = Field(description="The mode of keyword extraction, e.g., 'url', 'text', or 'keywords'.")
# limit: int = Field(default=None, description="The maximum number of keywords to extract.")
class KeywordEntry(BaseModel):
keyword: str = Field(description="The extracted keyword.")
+12 -6
View File
@@ -31,9 +31,11 @@ async def extract_keywords_ws(websocket: WebSocket):
disconnected = asyncio.Event()
extraction_task: asyncio.Task | None = None
def _is_socket_open() -> bool:
return not disconnected.is_set() and websocket.application_state.name != "DISCONNECTED"
async def emit(event: dict):
if disconnected.is_set():
if not _is_socket_open():
return
try:
await websocket.send_json(event)
@@ -41,7 +43,7 @@ async def extract_keywords_ws(websocket: WebSocket):
disconnected.set()
async def safe_send(payload: dict):
if disconnected.is_set():
if not _is_socket_open():
return
try:
await websocket.send_json(payload)
@@ -51,12 +53,12 @@ async def extract_keywords_ws(websocket: WebSocket):
try:
raw = await websocket.receive_json()
request = KeywordsRequest(**raw)
extraction_task = asyncio.create_task(
logic.extract_keywords_stream_enriched(
query=request.query,
mode=request.mode,
limit=request.limit,
files=request.files,
emit=emit,
)
)
@@ -71,7 +73,6 @@ async def extract_keywords_ws(websocket: WebSocket):
except (WebSocketDisconnect, ClientDisconnected):
disconnected.set()
logger.info("Client disconnected from keyword extraction ws")
print("Client disconnected from keyword extraction ws")
except Exception as e:
disconnected.set()
@@ -89,8 +90,11 @@ async def extract_keywords_ws(websocket: WebSocket):
except (asyncio.CancelledError, Exception):
pass
if websocket.application_state.name != "DISCONNECTED":
await websocket.close()
if _is_socket_open():
try:
await websocket.close()
except RuntimeError:
logger.debug("WebSocket already closed, skipping close()")
@router.post(
"/keywords/extract",
@@ -107,3 +111,5 @@ async def extract_keywords(
):
return await logic.extract_keywords(query=request.query, mode=request.mode, limit=request.limit)
+5 -1
View File
@@ -38,6 +38,7 @@ from inse.auth.router import router as auth_router
from inse.account_management.router import router as account_management_router
from inse.organization_management.router import router as organization_management_router
from inse.dashboard.router import router as dashboard_router
from inse.bookmarks.router import router as bookmarks_router
from inse.institutions.router import router as institutions_router
from inse.database import create_db_and_tables, get_session
@@ -53,6 +54,7 @@ from inse.patents.service import (
)
from inse.works.purpose_router import router as works_purpose_router
from inse.works.v2.router import router as works_v2_router
logger = logging.getLogger(__name__)
@@ -102,8 +104,10 @@ app.include_router(service_router)
app.include_router(auth_router)
app.include_router(account_management_router)
app.include_router(organization_management_router)
app.include_router(dashboard_router)
app.include_router(works_v2_router)
app.include_router(dashboard_router)
app.include_router(bookmarks_router)
app.add_middleware(
ETagCacheMiddleware,
@@ -25,7 +25,9 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
if request.method != "GET":
return await call_next(request)
if request.url.path.startswith(("/api/auth", "/api/accounts")):
if request.url.path.startswith(
("/api/auth", "/api/accounts", "/api/bookmarks")
):
return await call_next(request)
if request.headers.get("authorization"):
+17 -8
View File
@@ -16,6 +16,7 @@ else:
def __str__(self) -> str:
return self.value
from pydantic import BaseModel
from pydantic import Field
from typing import List
@@ -28,11 +29,16 @@ T = TypeVar("T", bound=BaseModel)
class Page(BaseModel, Generic[T]):
elements: List[T] = Field(default=[], description="The elements of the page.")
offset: int = Field(default=0, description="The page number. (0-based)")
page: int = Field(default=0, description="The page number. (0-based)")
size: int = Field(default=20, description="The page size in elements.")
total: int = Field(default=0, description="The total number of elements.")
class SortDirection(StrEnum):
ASCENDING = "asc"
DESCENDING = "desc"
class ESCluster(StrEnum):
NES = "nes"
INSE = "inse"
@@ -40,6 +46,7 @@ class ESCluster(StrEnum):
class ESIndex(StrEnum):
OPENALEX_WORKS = "openalex-works"
OPENALEX_WORKS_WILDCARD = "openalex-works*"
OPENALEX_AUTHORS = "openalex-authors"
OPENALEX_INSTITUTIONS = "openalex-institutions"
OPENALEX_PUBLICATIONS = "openalex-publications"
@@ -47,17 +54,17 @@ class ESIndex(StrEnum):
OPENALEX_CONTINENTS = "openalex-continents"
OPENALEX_TOPICS = "openalex-topics"
OPENALEX_TOPIC_VECTORS = "topicvectors"
EPO_INDEX = "epo_index_1.0"
USPTO_INDEX = "uspto_patents_3.0"
ORG_PATENTS = "org_patents"
PROJECTS_BUND_V1 = "projects_bund_v1"
PROJECTS_DFG_ALL = "projects_dfg_all"
CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects"
CORDIS_EU_PUBLICATIONS_WILDCARD = "cordis_eu_*_publications"
CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects"
CORDIS_EU_PUBLICATIONS_WILDCARD = "cordis_eu_*_publications"
CORDIS_EU_FP7_OGANIZATIONS = "cordis_eu_fp7_organizations"
# FP7
CORDIS_EU_FP7_ORGANIZATIONS = "cordis_eu_fp7_organizations"
@@ -84,8 +91,10 @@ class ESIndex(StrEnum):
CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS = "cordis_eu_horizon_europe_organizations"
CORDIS_EU_HORIZON_EUROPE_PUBLICATIONS = "cordis_eu_horizon_europe_publications"
CORDIS_EU_HORIZON_EUROPE_DELIVERABLES = "cordis_eu_horizon_europe_deliverables"
CORDIS_EU_HORIZON_EUROPE_REPORT_SUMMARIES = "cordis_eu_horizon_europe_report_summaries"
CORDIS_EU_HORIZON_EUROPE_REPORT_SUMMARIES = (
"cordis_eu_horizon_europe_report_summaries"
)
CORDIS_EU_HORIZON_EUROPE_TOPICS = "cordis_eu_horizon_europe_topics"
CORDIS_EU_HORIZON_EUROPE_WEB_LINKS = "cordis_eu_horizon_europe_web_links"
CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC = "cordis_eu_horizon_europe_euroscivoc"
CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS = "cordis_eu_horizon_europe_legal_basis"
CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS = "cordis_eu_horizon_europe_legal_basis"
+1
View File
@@ -7,6 +7,7 @@ class Tags(StrEnum):
INSTITUTIONS = "Institutions"
TOPICS = "Topics"
WORKS = "Works"
WORKS_V2 = "Works V2"
NEWS = "News"
PROJECTS = "Projects"
AUTH = "Auth"
@@ -20,7 +20,7 @@ router = APIRouter(prefix=WORKS_PREFIX, tags=[Tags.WORKS])
async def get_work_purpose(
raw_oa_work_id: Annotated[str, Path(description="The raw OpenAlex work id.")],
) -> SpecificWorkPurpose:
return await purpose_service.get_work_purpose(raw_oa_work_id)
return await purpose_service.get_work_purpose(raw_oa_work_id=raw_oa_work_id)
@router.get(
@@ -31,4 +31,6 @@ async def get_work_purpose(
async def get_author_work_purposes(
raw_oa_author_id: Annotated[str, Path(description="The raw OpenAlex author id.")],
) -> AuthorWorkPurposes:
return await purpose_service.get_author_work_purposes(raw_oa_author_id)
return await purpose_service.get_author_work_purposes(
raw_oa_author_id=raw_oa_author_id
)
@@ -2,7 +2,6 @@ import logging
import random
from typing import List
from fastapi import HTTPException, status
from inse.exceptions import NotFoundException
from inse.integrations import elasticsearch
@@ -10,13 +9,14 @@ from inse.model import ESIndex
from inse.works.model import AuthorWorkPurposes, SpecificWorkPurpose, WorkPurpose
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
async def get_work_purpose(raw_oa_work_id: str) -> SpecificWorkPurpose:
raw_oa_work_id = raw_oa_work_id.strip().upper()
response = await elasticsearch.get(
index=ESIndex.OPENALEX_WORKS,
index=ESIndex.OPENALEX_WORKS_WILDCARD,
doc_id=raw_oa_work_id,
source=["title", "abstract"],
)
@@ -41,7 +41,7 @@ async def get_author_work_purposes(raw_oa_author_id: str) -> AuthorWorkPurposes:
raw_oa_author_id = raw_oa_author_id.strip().upper()
response = await elasticsearch.search(
index=ESIndex.OPENALEX_WORKS,
index=ESIndex.OPENALEX_WORKS_WILDCARD,
source=["id", "publication_year"],
query={
"nested": {
+48
View File
@@ -0,0 +1,48 @@
from enum import StrEnum
from typing import List
from pydantic import BaseModel, Field
from inse.model import Page
from inse.models.openalex.work_topic import WorkTopic
class WorkSortBy(StrEnum):
TITLE = "title"
TYPE = "type"
PUBLICATION_YEAR = "publication_year"
LANGUAGE = "language"
CITED_BY_COUNT = "cited_by_count"
class AuthorWorkInstitution(BaseModel):
institution_id: str = Field(
description="The ID of the institution associated with the work"
)
institution_name: str = Field(
description="The name of the institution associated with the work"
)
institution_country_code: str = Field(
description="The country code of the institution associated with the work"
)
class AuthorWork(BaseModel):
id: str = Field(description="The ID of the work")
title: str = Field(description="The title of the work")
type: str = Field(description="The type of the work")
publication_year: int = Field(description="The year the work was published")
language_code: str = Field(description="The language code of the work")
institutions: List[AuthorWorkInstitution] = Field(
description="A list of institutions associated with the work"
)
topics: List[WorkTopic] = Field(
description="A list of topics associated with the work"
)
cited_by_count: int = Field(
description="The number of citations the work has received"
)
class AuthorWorkPage(Page[AuthorWork]):
pass
+101
View File
@@ -0,0 +1,101 @@
from typing import Annotated, List
from fastapi import APIRouter, Path, Query
from inse.tags import Tags
from inse.model import SortDirection
from inse.works.v2.model import AuthorWorkPage, WorkSortBy
from inse.models.openalex.work_topic import WorkTopic
from inse.models.openalex.institution import Institution
router = APIRouter(prefix="/api/v2/works", tags=[Tags.WORKS_V2])
@router.get(
"/{raw_oa_author_id}",
operation_id="getAuthorWorkPage",
summary="Returns a paginated list of works for a given author based on their ID.",
)
async def get_author_works(
raw_oa_author_id: Annotated[str, Path(description="The raw OpenAlex author id.")],
page: Annotated[
int, Query(description="The page number to retrieve. (0-based)", ge=0)
] = 0,
size: Annotated[
int,
Query(description="The number of works to retrieve per page.", ge=1, le=100),
] = 10,
publication_years: Annotated[
list[int],
Query(description="A list of publication years to filter by."),
] = [],
publication_types: Annotated[
list[str],
Query(description="A list of publication types to filter by."),
] = [],
institution_ids: Annotated[
list[str],
Query(description="A list of institution IDs to filter by."),
] = [],
topic_ids: Annotated[
list[str],
Query(description="A list of topic IDs to filter by."),
] = [],
language_codes: Annotated[
list[str],
Query(description="A list of language codes to filter by."),
] = [],
sort_by: Annotated[
WorkSortBy, Query(description="The field to sort by.")
] = WorkSortBy.PUBLICATION_YEAR,
sort_order: Annotated[
SortDirection, Query(description="The order to sort by.")
] = SortDirection.DESCENDING,
) -> AuthorWorkPage:
from inse.works.v2.service import get_author_works
return await get_author_works(
raw_oa_author_id=raw_oa_author_id,
page=page,
size=size,
publication_years=publication_years or [],
publication_types=publication_types or [],
institution_ids=institution_ids or [],
topic_ids=topic_ids or [],
language_codes=language_codes or [],
sort_by=sort_by,
sort_order=sort_order,
)
@router.get(
"/topics/search",
operation_id="getWorkTopicsByIds",
summary="Returns a list of work topics based on their IDs.",
)
async def get_work_topics_by_ids(
topic_ids: Annotated[
list[str],
Query(description="A list of topic IDs to retrieve."),
] = [],
) -> List[WorkTopic]:
from inse.works.v2.service import get_work_topics_by_ids
return await get_work_topics_by_ids(topic_ids=topic_ids or [])
@router.get(
"/institutions/search",
operation_id="getInstitutionsByIds",
summary="Returns a list of institutions based on their IDs.",
)
async def get_institutions_by_ids(
institution_ids: Annotated[
list[str],
Query(description="A list of institution IDs to retrieve."),
] = [],
) -> List[Institution]:
from inse.works.v2.service import get_work_institutions_by_ids
return await get_work_institutions_by_ids(institution_ids=institution_ids or [])
+188
View File
@@ -0,0 +1,188 @@
import logging
from typing import List, Optional, Dict
from inse.integrations import elasticsearch
from inse.model import ESIndex, SortDirection
from inse.works.v2.model import (
AuthorWork,
AuthorWorkInstitution,
AuthorWorkPage,
WorkSortBy,
)
from inse.models.openalex.work_topic import WorkTopic
from inse.models.openalex.institution import Institution
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
async def get_author_works(
raw_oa_author_id: str,
page: int,
size: int,
publication_years: Optional[List[int]] = None,
publication_types: Optional[List[str]] = None,
institution_ids: Optional[List[str]] = None,
topic_ids: Optional[List[str]] = None,
language_codes: Optional[List[str]] = None,
sort_by: WorkSortBy = WorkSortBy.PUBLICATION_YEAR,
sort_order: SortDirection = SortDirection.DESCENDING,
) -> AuthorWorkPage:
must = [
{
"nested": {
"path": "authorships",
"query": {
"term": {
"authorships.author.id": f"https://openalex.org/{raw_oa_author_id}"
}
},
}
}
]
if publication_years:
must.append({"terms": {"publication_year": publication_years}})
if publication_types:
must.append({"terms": {"type": publication_types}})
if language_codes:
must.append({"terms": {"language": language_codes}})
if institution_ids:
must.append(
{
"nested": {
"path": "authorships",
"query": {
"nested": {
"path": "authorships.institutions",
"query": {
"terms": {
"authorships.institutions.id": institution_ids
}
},
}
},
}
}
)
if topic_ids:
must.append(
{"nested": {"path": "topics", "query": {"terms": {"topics.id": topic_ids}}}}
)
if sort_by == WorkSortBy.TITLE:
sort = [{"title.keyword": sort_order.value}]
else:
sort = [{sort_by.value: sort_order.value}]
response = await elasticsearch.search(
ESIndex.OPENALEX_WORKS_WILDCARD,
source=[
"id",
"title",
"type",
"publication_year",
"language",
"cited_by_count",
"authorships.institutions.id",
"authorships.institutions.display_name",
"authorships.institutions.country_code",
"topics",
],
query={"bool": {"must": must}},
size=size,
offset=page * size,
sort=sort,
)
logger.debug(f"Elasticsearch response for author {raw_oa_author_id} v2: {response}")
hits_block = response.get("hits", {})
total = hits_block.get("total", {}).get("value", 0)
hits = hits_block.get("hits", [])
elements: List[AuthorWork] = []
for hit in hits:
source = hit.get("_source", {})
logger.debug(f"Hit source for author {raw_oa_author_id} v2: {source}")
institutions: Dict[str, AuthorWorkInstitution] = {}
for authorship in source.get("authorships", []):
for institution in authorship.get("institutions", []):
institution_id = institution.get("id", "")
if institution_id not in institutions:
institutions[institution_id] = AuthorWorkInstitution(
institution_id=institution.get("id", ""),
institution_name=institution.get("display_name", ""),
institution_country_code=institution.get("country_code", ""),
)
topics: List[WorkTopic] = [
WorkTopic.from_dict(topic) for topic in source.get("topics", [])
] # type: ignore
elements.append(
AuthorWork(
id=source.get("id", ""),
title=source.get("title", ""),
type=source.get("type", ""),
publication_year=source.get("publication_year", 0),
language_code=source.get("language") or "",
institutions=list(institutions.values()),
topics=topics,
cited_by_count=source.get("cited_by_count", 0),
)
)
return AuthorWorkPage(
elements=elements,
total=total,
page=page,
size=size,
)
async def get_work_topics_by_ids(topic_ids: List[str]) -> List[WorkTopic]:
logger.debug(f"Fetching work topics for IDs: {topic_ids}")
if not topic_ids:
return []
must = [{"terms": {"id": topic_ids}}]
response = await elasticsearch.search(
ESIndex.OPENALEX_TOPICS,
source=["id", "display_name", "field", "domain"],
query={"bool": {"must": must}},
size=len(topic_ids),
)
logger.debug(f"Elasticsearch response for work topics {topic_ids}: {response}")
hits_block = response.get("hits", {})
hits = hits_block.get("hits", [])
topics: List[WorkTopic] = []
for hit in hits:
source = hit.get("_source", {})
logger.debug(f"Hit source for work topic {source.get('id', '')}: {source}")
topics.append(WorkTopic.from_dict(source)) # type: ignore
return topics
async def get_work_institutions_by_ids(institution_ids: List[str]) -> List[Institution]:
logger.debug(f"Fetching institutions for IDs: {institution_ids}")
if not institution_ids:
return []
must = [{"terms": {"id": institution_ids}}]
response = await elasticsearch.search(
ESIndex.OPENALEX_INSTITUTIONS,
source=["id", "display_name", "country_code"],
query={"bool": {"must": must}},
size=len(institution_ids),
)
logger.debug(
f"Elasticsearch response for institutions {institution_ids}: {response}"
)
hits_block = response.get("hits", {})
hits = hits_block.get("hits", [])
institutions: List[Institution] = []
for hit in hits:
source = hit.get("_source", {})
logger.debug(f"Hit source for institution {source.get('id', '')}: {source}")
institutions.append(Institution.from_dict(source)) # type: ignore
return institutions
+11
View File
@@ -799,6 +799,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/2b/4f/e04a8067c7c96c364cef7ef73906504e2f40d690811c021e1a1901473a19/PyJWT-2.8.0-py3-none-any.whl", hash = "sha256:59127c392cc44c2da5bb3192169a91f429924e17aff6534d70fdc02ab3e04320", size = 22591, upload-time = "2023-07-18T20:02:21.561Z" },
]
[[package]]
name = "pypdf"
version = "6.14.2"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/03/72/7dfd5ff1c9c37de97a731701f51af091325f123d9d4270361c9c69e4431f/pypdf-6.14.2.tar.gz", hash = "sha256:7873f502fe4385e79539b21d872392dc0c4e3714327c15881cbc7fbfd1f95b25", size = 6491182, upload-time = "2026-06-23T14:18:30.859Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/49/e6/136aa8993a2ae7214e0b0ef2edaa0d2e08d1d4e4982635b08a835ff31ec8/pypdf-6.14.2-py3-none-any.whl", hash = "sha256:3f07891af76dc002657e04993ab9b4de81de29f9013b9761d0b7968bff12e946", size = 349514, upload-time = "2026-06-23T14:18:28.867Z" },
]
[[package]]
name = "pytest"
version = "8.1.2"
@@ -1137,6 +1146,7 @@ dependencies = [
{ name = "pydantic" },
{ name = "pydantic-settings" },
{ name = "pyjwt" },
{ name = "pypdf" },
{ name = "pytest" },
{ name = "python-multipart" },
{ name = "pyyaml" },
@@ -1158,6 +1168,7 @@ requires-dist = [
{ name = "pydantic", specifier = "~=2.7.1" },
{ name = "pydantic-settings", specifier = "~=2.2.1" },
{ name = "pyjwt", specifier = "~=2.8.0" },
{ name = "pypdf", specifier = "==6.14.2" },
{ name = "pytest", specifier = "~=8.1.0" },
{ name = "python-multipart", specifier = "~=0.0.19" },
{ name = "pyyaml", specifier = "~=6.0.1" },
+6
View File
@@ -1147,6 +1147,12 @@ Content-Type: application/json
###
GET https://project.nes.uni-due.de/elastic/openalex-topics/_search
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
Content-Type: application/json
###
GET https://project.nes.uni-due.de/elastic/openalex-authors/_search
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
Content-Type: application/json
@@ -19,6 +19,7 @@ api/projects.service.ts
api/topics.service.ts
api/universityRankings.service.ts
api/works.service.ts
api/worksV2.service.ts
configuration.ts
encoder.ts
git_push.sh
@@ -36,6 +37,9 @@ model/authorNetworkNode.ts
model/authorParsedLongestName.ts
model/authorPositionCount.ts
model/authorSummaryStats.ts
model/authorWork.ts
model/authorWorkInstitution.ts
model/authorWorkPage.ts
model/authorWorkPurposes.ts
model/authorsFilterProperties.ts
model/authorsListResponse.ts
@@ -81,6 +85,7 @@ model/euProjectData.ts
model/extractedKeywords.ts
model/extractedKeywordsLLM.ts
model/extractedKeywordsResponse.ts
model/fileUpload.ts
model/filterInformation.ts
model/filterProperties.ts
model/fp7EurosciVoc.ts
@@ -211,6 +216,7 @@ model/workMeshInner.ts
model/workNetworkNode.ts
model/workPage.ts
model/workPurpose.ts
model/workSortBy.ts
model/workSustainableDevelopmentGoalsInner.ts
model/workTopic.ts
model/workTopicDomain.ts
+3 -1
View File
@@ -28,4 +28,6 @@ export * from './universityRankings.service';
import { UniversityRankingsService } from './universityRankings.service';
export * from './works.service';
import { WorksService } from './works.service';
export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEServiceService, InstitutionsService, KeywordsService, NewsService, OrganizationService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, UniversityRankingsService, WorksService];
export * from './worksV2.service';
import { WorksV2Service } from './worksV2.service';
export const APIS = [AuthService, CompanyConnectionsService, FundingService, INSEServiceService, InstitutionsService, KeywordsService, NewsService, OrganizationService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, UniversityRankingsService, WorksService, WorksV2Service];
+275
View File
@@ -0,0 +1,275 @@
/**
* 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.
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams,
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore
import { AuthorWorkPage } from '../model/authorWorkPage';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
import { Institution } from '../model/institution';
// @ts-ignore
import { SortDirection } from '../model/sortDirection';
// @ts-ignore
import { WorkSortBy } from '../model/workSortBy';
// @ts-ignore
import { WorkTopic } from '../model/workTopic';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
@Injectable({
providedIn: 'root'
})
export class WorksV2Service extends BaseService {
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
super(basePath, configuration);
}
/**
* Returns a paginated list of works for a given author based on their ID.
* @endpoint get /api/v2/works/{raw_oa_author_id}
* @param rawOaAuthorId The raw OpenAlex author id.
* @param page The page number to retrieve. (0-based)
* @param size The number of works to retrieve per page.
* @param publicationYears A list of publication years to filter by.
* @param publicationTypes A list of publication types to filter by.
* @param institutionIds A list of institution IDs to filter by.
* @param topicIds A list of topic IDs to filter by.
* @param languageCodes A list of language codes to filter by.
* @param sortBy The field to sort by.
* @param sortOrder The order to sort by.
* @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 getAuthorWorkPage(rawOaAuthorId: string, page?: number, size?: number, publicationYears?: Array<number>, publicationTypes?: Array<string>, institutionIds?: Array<string>, topicIds?: Array<string>, languageCodes?: Array<string>, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AuthorWorkPage>;
public getAuthorWorkPage(rawOaAuthorId: string, page?: number, size?: number, publicationYears?: Array<number>, publicationTypes?: Array<string>, institutionIds?: Array<string>, topicIds?: Array<string>, languageCodes?: Array<string>, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AuthorWorkPage>>;
public getAuthorWorkPage(rawOaAuthorId: string, page?: number, size?: number, publicationYears?: Array<number>, publicationTypes?: Array<string>, institutionIds?: Array<string>, topicIds?: Array<string>, languageCodes?: Array<string>, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AuthorWorkPage>>;
public getAuthorWorkPage(rawOaAuthorId: string, page?: number, size?: number, publicationYears?: Array<number>, publicationTypes?: Array<string>, institutionIds?: Array<string>, topicIds?: Array<string>, languageCodes?: Array<string>, sortBy?: WorkSortBy, sortOrder?: SortDirection, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (rawOaAuthorId === null || rawOaAuthorId === undefined) {
throw new Error('Required parameter rawOaAuthorId was null or undefined when calling getAuthorWorkPage.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>page, 'page');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>size, 'size');
if (publicationYears) {
publicationYears.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'publication_years');
})
}
if (publicationTypes) {
publicationTypes.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'publication_types');
})
}
if (institutionIds) {
institutionIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'institution_ids');
})
}
if (topicIds) {
topicIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'topic_ids');
})
}
if (languageCodes) {
languageCodes.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'language_codes');
})
}
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>sortBy, 'sort_by');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>sortOrder, 'sort_order');
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/v2/works/${this.configuration.encodeParam({name: "rawOaAuthorId", value: rawOaAuthorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<AuthorWorkPage>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Returns a list of institutions based on their IDs.
* @endpoint get /api/v2/works/institutions/search
* @param institutionIds A list of institution IDs to retrieve.
* @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 getInstitutionsByIds(institutionIds?: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<Institution>>;
public getInstitutionsByIds(institutionIds?: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<Institution>>>;
public getInstitutionsByIds(institutionIds?: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<Institution>>>;
public getInstitutionsByIds(institutionIds?: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
if (institutionIds) {
institutionIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'institution_ids');
})
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/v2/works/institutions/search`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<Institution>>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Returns a list of work topics based on their IDs.
* @endpoint get /api/v2/works/topics/search
* @param topicIds A list of topic IDs to retrieve.
* @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 getWorkTopicsByIds(topicIds?: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<WorkTopic>>;
public getWorkTopicsByIds(topicIds?: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<WorkTopic>>>;
public getWorkTopicsByIds(topicIds?: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<WorkTopic>>>;
public getWorkTopicsByIds(topicIds?: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
if (topicIds) {
topicIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>element, 'topic_ids');
})
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/v2/works/topics/search`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<WorkTopic>>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
}
+1
View File
@@ -40,6 +40,7 @@ export interface AccessToken {
* The specific role this access token grants within its organization.
*/
effective_role?: UserRole;
effective_roles?: Array<UserRole>;
/**
* The unique identifier of the organization associated with this access token.
*/
+1 -1
View File
@@ -14,7 +14,7 @@ export interface AccountProfile {
id: string;
email: string;
name: string;
role: UserRole;
roles: Array<UserRole>;
organization_id: string;
organization_name: string;
deleted: boolean;
+48
View File
@@ -0,0 +1,48 @@
/**
* 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 { AuthorWorkInstitution } from './authorWorkInstitution';
import { WorkTopic } from './workTopic';
export interface AuthorWork {
/**
* The ID of the work
*/
id: string;
/**
* The title of the work
*/
title: string;
/**
* The type of the work
*/
type: string;
/**
* The year the work was published
*/
publication_year: number;
/**
* The language code of the work
*/
language_code: string;
/**
* A list of institutions associated with the work
*/
institutions: Array<AuthorWorkInstitution>;
/**
* A list of topics associated with the work
*/
topics: Array<WorkTopic>;
/**
* The number of citations the work has received
*/
cited_by_count: number;
}
@@ -0,0 +1,26 @@
/**
* 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 interface AuthorWorkInstitution {
/**
* The ID of the institution associated with the work
*/
institution_id: string;
/**
* The name of the institution associated with the work
*/
institution_name: string;
/**
* The country code of the institution associated with the work
*/
institution_country_code: string;
}
@@ -0,0 +1,31 @@
/**
* 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 { AuthorWork } from './authorWork';
export interface AuthorWorkPage {
/**
* The elements of the page.
*/
elements?: Array<AuthorWork>;
/**
* The page number. (0-based)
*/
page?: number;
/**
* The page size in elements.
*/
size?: number;
/**
* The total number of elements.
*/
total?: number;
}
@@ -13,7 +13,7 @@ import { UserRole } from './userRole';
export interface CreateAccountRequest {
email: string;
name: string;
role?: UserRole;
roles?: Array<UserRole>;
organization_id: string;
password: string;
openalex_person_id?: string | null;
+26
View File
@@ -0,0 +1,26 @@
/**
* 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 interface FileUpload {
/**
* The name of the uploaded file.
*/
filename: string;
/**
* The base64-encoded content of the uploaded file.
*/
content_base64: string;
/**
* The MIME type of the uploaded file, e.g., \'application/pdf\', \'image/png\', etc.
*/
mime_type: string;
}
+16 -16
View File
@@ -1,26 +1,26 @@
/**
* 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 { FileUpload } from './fileUpload';
export interface KeywordsRequest {
/**
* The input text from which to extract keywords.
*/
query: string;
/**
* The mode of keyword extraction, e.g., \'url\', \'text\', or \'keywords\'.
*/
mode: string;
/**
* The maximum number of keywords to extract.
*/
limit?: number;
export interface KeywordsRequest {
/**
* The input text from which to extract keywords.
*/
query: string;
files?: Array<FileUpload> | null;
/**
* The mode of keyword extraction, e.g., \'url\', \'text\', or \'keywords\'.
*/
mode: string;
/**
* The maximum number of keywords to extract.
*/
limit?: number;
}
+4
View File
@@ -11,6 +11,9 @@ export * from './authorNetworkNode';
export * from './authorParsedLongestName';
export * from './authorPositionCount';
export * from './authorSummaryStats';
export * from './authorWork';
export * from './authorWorkInstitution';
export * from './authorWorkPage';
export * from './authorWorkPurposes';
export * from './authorsFilterProperties';
export * from './authorsListResponse';
@@ -185,6 +188,7 @@ export * from './workMeshInner';
export * from './workNetworkNode';
export * from './workPage';
export * from './workPurpose';
export * from './workSortBy';
export * from './workSustainableDevelopmentGoalsInner';
export * from './workTopic';
export * from './workTopicDomain';
@@ -13,7 +13,7 @@ import { UserRole } from './userRole';
export interface UpdateAccountRequest {
email?: string | null;
name?: string | null;
role?: UserRole | null;
roles?: Array<UserRole> | null;
organization_id?: string | null;
password?: string | null;
openalex_person_id?: string | null;
+20
View File
@@ -0,0 +1,20 @@
/**
* 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 WorkSortBy = {
Title: 'title',
Type: 'type',
PublicationYear: 'publication_year',
Language: 'language',
CitedByCount: 'cited_by_count'
} as const;
export type WorkSortBy = typeof WorkSortBy[keyof typeof WorkSortBy];
+15
View File
@@ -31,6 +31,9 @@ import { KeywordsToPatentsResultsComponent } from './modules/keywords-search/sea
import { KeywordsToNewsResultsComponent } from './modules/keywords-search/search-results/news-results/news-results.component';
import { KeywordsToWorksResultsComponent } from './modules/keywords-search/search-results/works-results/works-results.component';
import { authorWorkPurposesResolver } from './resolvers/author-work-purposes.resolver';
import { workPageResolver } from './resolvers/work-page.resolver';
import { selectedTopicsResolver } from './resolvers/selected-topics.resolver';
import { selectedInstitutionsResolver } from './resolvers/selected-institutions.resolver';
export const routes: Routes = [
{
path: '',
@@ -68,6 +71,14 @@ export const routes: Routes = [
(mod) => mod.DashboardComponent,
),
},
{
path: 'bookmarks',
canActivate: [userGuard],
loadComponent: () =>
import('./modules/bookmarks/bookmarks.component').then(
(mod) => mod.BookmarksComponent,
),
},
{
path: 'persons',
canActivate: [userGuard],
@@ -271,7 +282,11 @@ export const routes: Routes = [
import('./modules/person-publications/person-publications.component').then(
(mod) => mod.PersonPublicationsComponent,
),
runGuardsAndResolvers: 'always',
resolve: {
selectedTopics: selectedTopicsResolver,
selectedInstitutions: selectedInstitutionsResolver,
authorWorkPage: workPageResolver,
authorWorkPurposes: authorWorkPurposesResolver,
},
},
@@ -186,7 +186,7 @@ export class AccountComponent {
constructor() {
effect(() => {
this.roles = [this.accountProfile().role];
this.roles = this.accountProfile().roles;
});
}
}
@@ -24,7 +24,7 @@
<mat-form-field appearance="outline">
<mat-label>Rolle</mat-label>
<mat-select formControlName="role">
<mat-select formControlName="roles" multiple>
@for (role of data.roles; track role) {
<mat-option [value]="role">{{ role }}</mat-option>
}
@@ -35,7 +35,7 @@ export interface AccountDialogData {
export interface AccountPayload {
email?: string;
name?: string;
role?: UserRole;
roles?: UserRole[];
organization_id?: string;
password?: string;
deleted?: boolean;
@@ -45,7 +45,7 @@ export interface AccountPayload {
export interface CreateAccountPayload {
email: string;
name: string;
role: UserRole;
roles: UserRole[];
organization_id: string;
password: string;
}
@@ -85,7 +85,7 @@ export class AccountDialogComponent {
name: new FormControl<string>(this.data.account?.name ?? '', [
Validators.required,
]),
role: new FormControl<UserRole>(this.data.account?.role ?? 'USER', [
roles: new FormControl<UserRole[]>(this.data.account?.roles ?? ['USER'], [
Validators.required,
]),
organizationId: new FormControl<string>(
@@ -115,7 +115,7 @@ export class AccountDialogComponent {
payload: {
email: value.email ?? '',
name: value.name ?? '',
role: value.role ?? 'USER',
roles: value.roles ?? ['USER'],
organization_id: value.organizationId ?? '',
password: value.password ?? '',
},
@@ -128,7 +128,7 @@ export class AccountDialogComponent {
const email = (value.email ?? '').trim();
const name = (value.name ?? '').trim();
const role = value.role ?? account.role;
const roles = value.roles ?? account.roles;
const organizationId = value.organizationId ?? account.organization_id;
const password = value.password?.trim() ?? '';
@@ -140,8 +140,8 @@ export class AccountDialogComponent {
payload.name = name;
}
if (role !== account.role) {
payload.role = role;
if (!this.sameRoles(roles, account.roles)) {
payload.roles = roles;
}
if (password) {
@@ -166,4 +166,10 @@ export class AccountDialogComponent {
protected close(): void {
this.dialogRef.close();
}
private sameRoles(left: UserRole[], right: UserRole[]): boolean {
return (
left.length === right.length && left.every((role) => right.includes(role))
);
}
}
@@ -44,7 +44,9 @@
</section>
<ng-template #accountRoleTmp let-row>
<span class="role">{{ row.role | role }}</span>
@for (role of row.roles; track role) {
<span class="role">{{ role | role }}</span>
}
</ng-template>
<ng-template #accountStatusTmp let-row>
@@ -126,10 +126,10 @@ export class AccountsComponent implements OnInit {
accessorKey: 'organization_name',
},
{
id: 'role',
id: 'roles',
header: 'Rolle',
type: 'accessor',
accessorKey: 'role',
accessorKey: 'roles',
cellTemplate: this.accountRoleTmp(),
},
{
@@ -325,7 +325,22 @@ export class AccountsComponent implements OnInit {
return (
this.credentialService.isEffectiveAdmin() &&
(account.role === 'MANAGER' || account.role === 'USER')
(this.effectiveRole(account) === 'MANAGER' ||
this.effectiveRole(account) === 'USER')
);
}
protected effectiveRole(account: AccountProfile): UserRole {
const roles = account.roles;
if (roles.includes('SUPER_ADMIN')) {
return 'SUPER_ADMIN';
}
if (roles.includes('ADMIN')) {
return 'ADMIN';
}
if (roles.includes('MANAGER')) {
return 'MANAGER';
}
return 'USER';
}
}
@@ -0,0 +1,39 @@
<main class="bookmarks-page">
<header class="page-header">
<div>
<p class="eyebrow">Meine Sammlung</p>
<h1>Bookmarks</h1>
<p>Gespeicherte Personen für den schnellen Zugriff.</p>
</div>
<div class="bookmark-count">
<mat-icon>bookmarks</mat-icon>
<strong>{{ persons().length }}</strong>
<span>Personen</span>
</div>
</header>
@if (loading()) {
<div class="loading-state">
<mat-spinner diameter="42"></mat-spinner>
<p>Bookmarks werden geladen …</p>
</div>
} @else if (persons().length) {
<section class="person-grid" aria-label="Gespeicherte Personen">
@for (person of persons(); track person.id) {
<app-person-card
[person]="person"
[isBookmarked]="bookmarkService.isBookmarked(person.id)"
(bookmarkToggle)="toggleBookmark($event)">
</app-person-card>
}
</section>
} @else {
<section class="empty-state">
<mat-icon>bookmark_border</mat-icon>
<h2>Noch keine Bookmarks</h2>
<p>
Speichere Personen über das Bookmark-Symbol auf einer Personenkarte.
</p>
</section>
}
</main>
@@ -0,0 +1,98 @@
:host {
display: block;
}
.bookmarks-page {
padding: 32px;
}
.page-header {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 24px;
margin-bottom: 30px;
h1 {
margin: 2px 0 6px;
font-size: 2rem;
}
p {
margin: 0;
color: #667085;
}
.eyebrow {
color: #3f51b5;
font-size: 0.75rem;
font-weight: 700;
letter-spacing: 0.12em;
text-transform: uppercase;
}
}
.bookmark-count {
display: grid;
grid-template-columns: auto auto;
align-items: center;
gap: 0 10px;
padding: 14px 18px;
border: 1px solid #e4e7ec;
border-radius: 14px;
background: white;
mat-icon {
grid-row: 1 / 3;
color: #3f51b5;
}
strong {
font-size: 1.25rem;
}
span {
color: #667085;
font-size: 0.75rem;
}
}
.person-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
gap: 20px;
}
.loading-state,
.empty-state {
display: flex;
min-height: 320px;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
color: #667085;
}
.empty-state mat-icon {
width: 54px;
height: 54px;
font-size: 54px;
color: #98a2b3;
}
.empty-state h2 {
margin: 16px 0 6px;
color: #1d2939;
}
@media (max-width: 700px) {
.bookmarks-page {
padding: 20px;
}
.page-header {
align-items: flex-start;
flex-direction: column;
}
}
@@ -0,0 +1,99 @@
import { CommonModule } from '@angular/common';
import { Component, DestroyRef, inject, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { catchError, forkJoin, map, of, switchMap } from 'rxjs';
import { CustomAuthor, PersonsService } from '../../api';
import { BookmarkService } from '../../shared/services/bookmark.service';
import { PersonCardComponent } from '../person-card/person-card.component';
const PERSON_INCLUDE_TAGS =
'display_name,works_count,cited_by_count,summary_stats,ids,' +
'last_known_institutions,affiliations,topics,orcid,topics_full,' +
'topic_share,career_metrics';
@Component({
selector: 'app-bookmarks',
standalone: true,
imports: [
CommonModule,
MatIconModule,
MatProgressSpinnerModule,
PersonCardComponent,
],
templateUrl: './bookmarks.component.html',
styleUrl: './bookmarks.component.scss',
})
export class BookmarksComponent {
readonly bookmarkService = inject(BookmarkService);
private readonly personsService = inject(PersonsService);
private readonly destroyRef = inject(DestroyRef);
readonly persons = signal<CustomAuthor[]>([]);
readonly loading = signal(true);
constructor() {
this.loadBookmarks();
}
toggleBookmark(person: CustomAuthor): void {
this.bookmarkService
.confirmToggle(person)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe({
next: (bookmarked) => {
if (!bookmarked) {
const id = this.personId(person);
this.persons.update((persons) =>
persons.filter((item) => this.personId(item) !== id),
);
}
},
});
}
private loadBookmarks(): void {
this.bookmarkService
.load(true)
.pipe(
switchMap((bookmarks) => {
if (!bookmarks.length) return of([] as CustomAuthor[]);
return forkJoin(
bookmarks.map((bookmark) =>
this.personsService
.getPersonByID(bookmark.person_id, PERSON_INCLUDE_TAGS)
.pipe(
map(
(response) =>
response.results?.[0] ?? {
id: bookmark.person_id,
display_name: bookmark.person_name,
},
),
catchError(() =>
of({
id: bookmark.person_id,
display_name: bookmark.person_name,
} as CustomAuthor),
),
),
),
);
}),
takeUntilDestroyed(this.destroyRef),
)
.subscribe({
next: (persons) => {
this.persons.set(persons);
this.loading.set(false);
},
error: () => this.loading.set(false),
});
}
private personId(person: CustomAuthor): string {
return person.id?.replace(/\/$/, '').split('/').pop() ?? '';
}
}
@@ -174,7 +174,7 @@
<header class="top-authors-header">
<div>
<h2>Top 10 Personen aller Zeiten</h2>
<p>Nach Anzahl der Works und Projekte Ihrer Organisation.</p>
<p>Nach Anzahl der Works, Patente und News Ihrer Organisation.</p>
</div>
<div class="top-authors-period-toggle" aria-label="Works-Zeitraum">
<button
@@ -105,11 +105,6 @@ export class DashboardComponent implements OnInit {
icon: 'menu_book',
entries: this.topAuthors?.works ?? [],
},
{
title: 'Projekte',
icon: 'work',
entries: this.topAuthors?.projects ?? [],
},
{
title: 'Patente',
icon: 'description',
@@ -19,6 +19,7 @@
mat-flat-button
type="button"
class="extract-btn"
[disabled]="!form.controls.urlInput.value"
[color]="isExtracting() ? 'warn' : 'primary'"
(click)="onExtractKeywordsClick()">
<mat-icon>
@@ -43,6 +44,7 @@
<button
mat-flat-button
type="button"
[disabled]="!form.controls.textInput.value"
[color]="isExtracting() ? 'warn' : 'primary'"
class="extract-btn"
(click)="onExtractKeywordsClick()">
@@ -54,6 +56,32 @@
</div>
</div>
</mat-tab>
<mat-tab label="Datei">
<div class="tab-content">
<app-file-upload
[requiredFileType]="'text/plain,application/pdf'"
[maxFileSize]="5 * 1024 * 1024"
[maxFiles]="3"
[uploadedFiles]="uploadedFiles()"
(filesChange)="onFilesSelected($event)">
</app-file-upload>
<div class="actions">
<button
mat-flat-button
type="button"
[color]="isExtracting() ? 'warn' : 'primary'"
[disabled]="uploadedFiles().length === 0"
class="extract-btn"
(click)="onExtractKeywordsClick()">
<mat-icon>
{{ isExtracting() ? 'close' : 'troubleshoot' }}
</mat-icon>
{{ isExtracting() ? 'Abbrechen' : 'Keywords extrahieren' }}
</button>
<!-- Add this inside your form or section -->
</div>
</div>
</mat-tab>
</mat-tab-group>
<!-- Extraction Table -->
<mat-card
@@ -110,37 +138,40 @@
</button>
</div>
<div class="toolbar-divider"></div>
<mat-button-toggle-group
[value]="keywordView()"
(change)="onViewToggleChange($event.value)"
aria-label="Keyword Ansicht wählen">
<mat-button-toggle
[disabled]="isExtracting()"
value="llm"
matTooltip="Extrahierte Keywords">
<mat-icon>text_fields</mat-icon>
<span>Extrahierte Keywords</span>
</mat-button-toggle>
@if (topicMappingSearch()) {
<div class="toolbar-group toolbar-group--view">
<mat-button-toggle-group
[value]="keywordView()"
(change)="onViewToggleChange($event.value)"
aria-label="Keyword Ansicht wählen">
<mat-button-toggle
[disabled]="isExtracting()"
value="topic"
matTooltip="Topic Mapping">
<mat-icon>account_tree</mat-icon>
<span>Topic Mapping</span>
value="llm"
matTooltip="Extrahierte Keywords">
<mat-icon>text_fields</mat-icon>
<span>Extrahierte Keywords</span>
</mat-button-toggle>
}
</mat-button-toggle-group>
@if (topicMappingSearch()) {
<mat-button-toggle
[disabled]="isExtracting()"
value="topic"
matTooltip="Die Abbildung der extrahierten Keywords auf die bekannten Themenbereiche">
<mat-icon>account_tree</mat-icon>
<span>Topic Mapping</span>
</mat-button-toggle>
}
</mat-button-toggle-group>
</div>
<div class="toolbar-divider"></div>
<div class="toolbar-group toolbar-group--view">
<mat-slide-toggle
(change)="onToggleTopicMappingSearch($event)"
labelPosition="before"
[checked]="topicMappingSearch()"
class="mapping-toggle">
Topic Mapping
</mat-slide-toggle>
<div class="toggle-container">
<mat-slide-toggle
(change)="onToggleTopicMappingSearch($event)"
[checked]="topicMappingSearch()"
matTooltip="Wenn aktiviert, werden die extrahierten Keywords auf bekannte Themenbereiche abgebildet, was die Suchergebnisse verbessert.">
Topic Mapping
</mat-slide-toggle>
</div>
</div>
</div>
@@ -243,36 +274,48 @@
<div class="table-body">
<div class="table-col broad-col">
<ng-container
*ngTemplateOutlet="
keywordChipStack;
context: {
keywords: broadKeywords(),
emptyText: 'Nichts extrahiert',
}
"></ng-container>
@if (isExtracting() && broadKeywords().length === 0) {
<app-loading icon="manage_search" [size]="60" [diameter]="60" />
} @else {
<ng-container
*ngTemplateOutlet="
keywordChipStack;
context: {
keywords: broadKeywords(),
emptyText: 'Nichts extrahiert',
}
"></ng-container>
}
</div>
<div class="table-col coarse-col">
<ng-container
*ngTemplateOutlet="
keywordChipStack;
context: {
keywords: coarseKeywords(),
emptyText: 'Nichts extrahiert',
}
"></ng-container>
@if (isExtracting() && coarseKeywords().length === 0) {
<app-loading icon="manage_search" [size]="60" [diameter]="60" />
} @else {
<ng-container
*ngTemplateOutlet="
keywordChipStack;
context: {
keywords: coarseKeywords(),
emptyText: 'Nichts extrahiert',
}
"></ng-container>
}
</div>
<div class="table-col fine-col thick-border">
<ng-container
*ngTemplateOutlet="
keywordChipStack;
context: {
keywords: fineKeywords(),
emptyText: 'Nichts extrahiert',
}
"></ng-container>
@if (isExtracting() && fineKeywords().length === 0) {
<app-loading icon="manage_search" [size]="60" [diameter]="60" />
} @else {
<ng-container
*ngTemplateOutlet="
keywordChipStack;
context: {
keywords: fineKeywords(),
emptyText: 'Nichts extrahiert',
}
"></ng-container>
}
</div>
<div class="table-col own-col">
@@ -289,14 +332,18 @@
<span class="tab-count">{{ broadKeywords().length }}</span>
</ng-template>
<div class="mobile-tab-panel">
<ng-container
*ngTemplateOutlet="
keywordChipStack;
context: {
keywords: broadKeywords(),
emptyText: 'Nichts extrahiert',
}
"></ng-container>
@if (isExtracting() && broadKeywords().length === 0) {
<app-loading icon="manage_search" [size]="60" [diameter]="60" />
} @else {
<ng-container
*ngTemplateOutlet="
keywordChipStack;
context: {
keywords: broadKeywords(),
emptyText: 'Nichts extrahiert',
}
"></ng-container>
}
</div>
</mat-tab>
@@ -306,14 +353,18 @@
<span class="tab-count">{{ coarseKeywords().length }}</span>
</ng-template>
<div class="mobile-tab-panel">
<ng-container
*ngTemplateOutlet="
keywordChipStack;
context: {
keywords: coarseKeywords(),
emptyText: 'Nichts extrahiert',
}
"></ng-container>
@if (isExtracting() && coarseKeywords().length === 0) {
<app-loading icon="manage_search" [size]="60" [diameter]="60" />
} @else {
<ng-container
*ngTemplateOutlet="
keywordChipStack;
context: {
keywords: coarseKeywords(),
emptyText: 'Nichts extrahiert',
}
"></ng-container>
}
</div>
</mat-tab>
@@ -323,14 +374,18 @@
<span class="tab-count">{{ fineKeywords().length }}</span>
</ng-template>
<div class="mobile-tab-panel">
<ng-container
*ngTemplateOutlet="
keywordChipStack;
context: {
keywords: fineKeywords(),
emptyText: 'Nichts extrahiert',
}
"></ng-container>
@if (isExtracting() && fineKeywords().length === 0) {
<app-loading icon="manage_search" [size]="60" [diameter]="60" />
} @else {
<ng-container
*ngTemplateOutlet="
keywordChipStack;
context: {
keywords: fineKeywords(),
emptyText: 'Nichts extrahiert',
}
"></ng-container>
}
</div>
</mat-tab>
@@ -345,30 +400,27 @@
</mat-tab>
</mat-tab-group>
}
<!-- Source content display -->
@if (sourceContent().length > 0) {
<mat-divider></mat-divider>
<mat-expansion-panel class="source-expansion">
<mat-expansion-panel-header>
<mat-panel-title>Quellentext: {{ sourceUrl() }}</mat-panel-title>
</mat-expansion-panel-header>
<div
class="source-text"
[innerHTML]="highlightedSourceContent()"></div>
</mat-expansion-panel>
}
</mat-card-content>
@if (isExtracting() && !keywordsExist()) {
<!-- @if (isExtracting() && !keywordsExist()) {
<app-loading
text="{{ statusMessage() }}"
icon="manage_search"
[size]="200"
[diameter]="200" />
} -->
<!-- Source content display -->
@if (sourceContent().length > 0) {
<mat-divider></mat-divider>
<mat-expansion-panel class="source-expansion">
<mat-expansion-panel-header>
<mat-panel-title>Quellentext: {{ sourceUrl() }}</mat-panel-title>
</mat-expansion-panel-header>
<div class="source-text" [innerHTML]="highlightedSourceContent()"></div>
</mat-expansion-panel>
}
</mat-card>
@if (isExtracting() && keywordsExist()) {
@if (isExtracting()) {
<div class="status-message">{{ statusMessage() }}</div>
}
</div>
@@ -19,10 +19,12 @@ $touch-target: 44px;
.tab-content {
display: flex;
flex-direction: column;
margin-top: 0.5rem;
gap: 0.5rem;
align-items: center;
align-items: top;
app-file-upload {
width: 100%;
}
}
.full-width {
@@ -87,7 +89,6 @@ $touch-target: 44px;
gap: auto;
::ng-deep .mdc-switch {
position: relative;
width: 100%;
}
::ng-deep .mdc-form-field {
@@ -573,7 +574,7 @@ mat-button-toggle-group {
SOURCE EXPANSION PANEL
============================================================ */
.source-expansion {
margin: 0.75rem 0;
margin: 0.5rem 1rem;
background: var(--sg-background-muted, #f5f5f5);
border-radius: 4px;
//border-left: 4px solid var(--sg-primary, #1976d2);
@@ -1,4 +1,4 @@
import { Component, computed, signal, inject } from '@angular/core';
import { Component, computed, signal, inject, effect } from '@angular/core';
import { BreakpointObserver } from '@angular/cdk/layout';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormBuilder, ReactiveFormsModule } from '@angular/forms';
@@ -32,6 +32,12 @@ import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { map } from 'rxjs/operators';
import { toSignal } from '@angular/core/rxjs-interop';
import { MatSliderModule } from '@angular/material/slider';
import { FileUpload } from '../../api/model/fileUpload';
import { MatSnackBar } from '@angular/material/snack-bar';
import {
FileUploadComponent,
FileUploadItem,
} from '../../shared/ui/file-upload/file-upload.component';
import {
MatButtonToggleModule,
MatButtonToggleGroup,
@@ -51,8 +57,12 @@ import { PatentsService } from '../../api/api/patents.service';
import { KeywordsPatentsComponent } from './keywords-patents/keywords-patents.component';
import { DomSanitizer } from '@angular/platform-browser';
import { SearchResultsPayload } from './search-results/search-results-state.service';
import { KeywordPatentMatch, KeywordPatentSearchItem, KeywordsService } from '../../api';
type InputMode = 'url' | 'text';
import {
KeywordPatentMatch,
KeywordPatentSearchItem,
KeywordsService,
} from '../../api';
type InputMode = 'url' | 'text' | 'file';
type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual';
type KeywordView = 'llm' | 'topic';
type KeywordPatentLevel = 'broad' | 'coarse' | 'fine' | 'custom';
@@ -82,6 +92,7 @@ type KeywordPatentLevel = 'broad' | 'coarse' | 'fine' | 'custom';
LoadingComponent,
MatSlideToggleModule,
MatSliderModule,
FileUploadComponent,
],
templateUrl: './keywords-search.component.html',
styleUrl: './keywords-search.component.scss',
@@ -91,24 +102,23 @@ export class KeywordsSearchComponent {
private readonly sanitizer = inject(DomSanitizer);
private readonly route = inject(ActivatedRoute);
private readonly router = inject(Router);
private readonly _snackBar = inject(MatSnackBar);
private readonly destroyRef = inject(DestroyRef);
private readonly websocketService = inject(KeywordWebSocketService);
private readonly topicsService = inject(TopicsService);
private readonly patentsService = inject(PatentsService);
private readonly breakpointObserver = inject(BreakpointObserver);
private readonly keywordsService = inject(KeywordsService);
readonly form = this.formBuilder.nonNullable.group({
selectedInputType: 'url' as InputMode,
urlInput: '',
textInput: '',
fileInput: '',
});
private readonly SESSION_KEY = 'keywords-search-source';
private readonly SEARCH_RESULTS_HANDOFF_KEY = 'search-results-handoff';
// in component class:
private breakpointObserver = inject(BreakpointObserver);
isMobile = toSignal(
this.breakpointObserver
.observe('(max-width: 768px)')
@@ -139,6 +149,7 @@ export class KeywordsSearchComponent {
readonly patentsLoaded = signal(false);
readonly topicMappingSearch = signal<boolean>(false);
readonly uploadedFiles = signal<FileUploadItem[]>([]);
readonly keywordsExist = computed(
() =>
this.broadKeywords().length > 0 ||
@@ -159,43 +170,58 @@ export class KeywordsSearchComponent {
let highlightedContent = content;
// replace the keyword with highlighted spans
const normalizeText = (text: string): string => {
return text
.trim()
.toLowerCase()
.replace(/[\u2010-\u2015\u2026—–]/g, '-')
.replace(/[\u2018\u2019\u201b\u201c\u201d\u201f]/g, "'")
.replace(/[\s\n\r\t]+/g, ' ')
.replace(/[^a-zA-Z0-9\s\-]/g, '');
};
// Normalize keyword for matching
const normalizeKeyword = (keyword: string): string => {
return keyword
.trim()
.toLowerCase()
.replace(/[\s\-]+/g, '')
.replace(/[^a-zA-Z0-9]/g, '');
};
for (const keyword of selectedKeywords) {
const normalizedKeyword = this.normalizeKeyword(keyword);
const normalizedKeyword = normalizeKeyword(keyword);
// Find the first keyword entry that matches this normalized keyword
const entry = this.allKeywordEntries().find(
(e) =>
this.normalizeKeyword(this.getKeywordLabel(e)) === normalizedKeyword,
);
const entry = this.allKeywordEntries().find((e) => {
const label = this.getKeywordLabel(e);
return normalizeKeyword(label) === normalizedKeyword;
});
if (entry) {
const topic = this.getTopic(entry);
if (topic) {
const color = this.getTopicColor(topic);
// Escape HTML special characters in the keyword before using it in HTML
const escapedKeyword = keyword
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
if (!entry) continue;
// Create the replacement span HTML
const replacement = `<span style="text-decoration: underline; background-color: color-mix(in srgb, ${color} 27%, #ffffff); 100%); font-weight: bold;" title="Keyword: ${keyword}">${escapedKeyword}</span>`;
const topic = this.getTopic(entry);
if (!topic) continue;
const escapedRegexKeyword = keyword.replace(
/[.*+?^${}()|[\]\\]/g,
'\\$&',
);
const regex = new RegExp(escapedRegexKeyword, 'g');
const color = this.getTopicColor(topic);
highlightedContent = highlightedContent.replace(regex, replacement);
}
}
const escapedKeyword = keyword
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
const escapedRegexKeyword = keyword
.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
.replace(/\s+/g, '\\s*');
const regex = new RegExp(escapedRegexKeyword, 'gi');
const replacement = `<span style="text-decoration: underline; background-color: color-mix(in srgb, ${color} 27%, #ffffff); font-weight: bold;" title="Keyword: ${escapedKeyword}">${escapedKeyword}</span>`;
highlightedContent = highlightedContent.replace(regex, replacement);
}
console.log(
'Highlighted content:',
this.sanitizer.bypassSecurityTrustHtml(highlightedContent),
);
return this.sanitizer.bypassSecurityTrustHtml(highlightedContent);
});
@@ -211,6 +237,7 @@ export class KeywordsSearchComponent {
readonly progress = signal(0);
readonly statusMessage = signal('');
readonly errorMessage = signal('');
readonly keywordView = signal<KeywordView>('llm');
readonly subfieldLegendVisible = signal(true);
readonly subfieldLegendExpanded = signal(false);
@@ -254,6 +281,14 @@ export class KeywordsSearchComponent {
.getMessages()
.subscribe((event: WsEvent) => this.handleWsEvent(event));
effect(() => {
const message = this.errorMessage();
if (message) {
this._snackBar.open(message, 'Schließen', {
duration: 5000,
});
}
});
// this.destroyRef.onDestroy(() => {
// this.websocketService.close();
// const isReload = this.router.lastSuccessfulNavigation === null;
@@ -293,11 +328,15 @@ export class KeywordsSearchComponent {
this.statusMessage.set('Fertig!');
this.websocketService.close();
this.isExtracting.set(false);
if (!this.keywordsExist()) {
this.errorMessage.set('Keine Keywords extrahiert');
}
}
private handleErrorEvent(event: WsEvent): void {
this.progress.set(0);
this.statusMessage.set('Fehler: ' + event.message);
this.errorMessage.set(event.message || 'Unbekannter Fehler');
//this.statusMessage.set('Fehler: ' + event.message);
this.broadKeywordEntries.set([]);
this.coarseKeywordEntries.set([]);
this.fineKeywordEntries.set([]);
@@ -372,14 +411,49 @@ export class KeywordsSearchComponent {
// --- Tabs ---------------------------------------------------------------
selectedTabIndex(): number {
return this.form.controls.selectedInputType.value === 'text' ? 1 : 0;
if (this.form.controls.selectedInputType.value === 'url') return 0;
if (this.form.controls.selectedInputType.value === 'text') return 1;
return 2;
}
onTabChange(index: number): void {
const nextMode: InputMode = index === 1 ? 'text' : 'url';
let nextMode: InputMode;
if (index === 0) {
nextMode = 'url';
} else if (index === 1) {
nextMode = 'text';
} else {
nextMode = 'file';
}
this.form.controls.selectedInputType.setValue(nextMode);
}
// fileupload
onFilesSelected(files: FileUploadItem[]): void {
this.uploadedFiles.set(files);
}
// Helper: Send files to WebSocket for server-side extraction
private sendFilesToWebSocket(files: FileUpload[]) {
const keywordsRequest: KeywordsRequest = {
query: '',
files,
mode: 'files',
limit: undefined,
};
this.statusMessage.set('Files uploaded. Extracting keywords...');
this.websocketService
.sendRequest(keywordsRequest)
.then(() => {
this.statusMessage.set('Extracting keywords...');
})
.catch((err) => {
console.error('WebSocket error: OPA', err);
this.errorMessage.set('Failed to send content');
this.isExtracting.set(false);
});
}
// --- Keyword selection & manual entry ------------------------------------
private keywordExists(keyword: string): boolean {
@@ -396,7 +470,7 @@ export class KeywordsSearchComponent {
if (!normalizedKeyword) return;
if (this.keywordExists(normalizedKeyword)) {
this.statusMessage.set(`"${normalizedKeyword}" ist bereits vorhanden.`);
this.errorMessage.set(`"${normalizedKeyword}" ist bereits vorhanden.`);
return;
}
@@ -427,7 +501,7 @@ export class KeywordsSearchComponent {
error: (err) => {
console.error('vectorSearchTopics failed', err);
this.loadingNewKeyword.set(false);
this.statusMessage.set(
this.errorMessage.set(
`Fehler beim Hinzufügen von "${normalizedKeyword}".`,
);
},
@@ -555,10 +629,72 @@ export class KeywordsSearchComponent {
}
onExtractKeywordsClick(): void {
this.clearKeywords();
if (this.isExtracting()) {
this.cancelKeywordExtraction();
return;
}
const mode = this.form.controls.selectedInputType.value;
if (mode === 'file') {
const files = this.uploadedFiles();
if (!files || files.length === 0) {
this.errorMessage.set('Bitte Datei hochladen.');
return;
}
this.isExtracting.set(true);
this.progress.set(0);
this.statusMessage.set('Dateien werden verarbeitet...');
const totalFiles = files.length;
let processedFiles = 0;
const fileUploads: FileUpload[] = new Array(totalFiles);
files.forEach((fileItem, index) => {
const file = fileItem.file;
const reader = new FileReader();
reader.onload = (e) => {
const dataUrl = e.target?.result as string;
const base64 = dataUrl.split(',')[1] ?? '';
fileUploads[index] = {
filename: file.name,
content_base64: base64,
mime_type: file.type || 'application/octet-stream',
};
processedFiles++;
if (processedFiles === totalFiles) {
this.sendFilesToWebSocket(fileUploads);
}
};
reader.onerror = () => {
console.error('Error reading file:', file.name);
fileUploads[index] = {
filename: file.name,
content_base64: '',
mime_type: file.type || 'application/octet-stream',
};
processedFiles++;
if (processedFiles === totalFiles) {
this.sendFilesToWebSocket(fileUploads);
}
};
reader.readAsDataURL(file);
});
return;
}
// For URL and text, fall back to original behavior
void this.extractKeywords();
}
@@ -615,7 +751,7 @@ export class KeywordsSearchComponent {
} catch (error) {
console.error('WebSocket send error:', error);
this.isExtracting.set(false);
this.statusMessage.set('Fehler beim Senden der Anfrage');
this.errorMessage.set('Fehler beim Senden der Anfrage');
}
}
@@ -623,7 +759,7 @@ export class KeywordsSearchComponent {
this.websocketService.close();
this.isExtracting.set(false);
this.progress.set(0);
this.statusMessage.set('Extraktion abgebrochen');
this.errorMessage.set('Extraktion abgebrochen');
}
search(): void {
@@ -864,7 +1000,6 @@ export class KeywordsSearchComponent {
const legendExpanded = queryParams.get('legendExpanded') ?? 'off';
const softSearch = queryParams.get('softSearch') === 'true';
this.isRestoringState = true;
this.form.patchValue(
{
selectedInputType: mode,
@@ -889,12 +1024,6 @@ export class KeywordsSearchComponent {
// enrich only newly added keywords that have no topic yet
this.enrichManualKeywordsWithTopics(manual);
// User intent (the current selection): the URL is always authoritative
// here, deliberately overriding whatever the session cache had. This
// is what makes a deep link like ?selected=foo&manual=bar from another
// page reliably preselect keywords, instead of getting merged with (or
// hidden behind) leftover state from a previous visit in the same tab.
// clean up the selection to only include keywords that actually exist in
const manualKeywordSet = new Set(
this.getKeywordLabels(this.manualKeywords()).map((k) =>
@@ -1048,7 +1177,10 @@ export class KeywordsSearchComponent {
}
private parseMode(mode: string | null): InputMode {
return mode === 'text' ? 'text' : 'url';
if (mode === 'url') return 'url';
if (mode === 'text') return 'text';
if (mode === 'file') return 'file';
return 'url';
}
private parseKeywordList(rawValue: string | null): string[] {
@@ -5,25 +5,31 @@
{{ initials() }}
</div>
<div class="header-main">
<div class="bookmark">
<div class="name-row">
<h2
[skText]="loading()"
class="person-name"
[title]="person().display_name ?? ''">
{{ person().display_name ?? '' }}
</h2>
<button
type="button"
class="bookmark-btn"
(click)="
toggleBookmark(); $event.stopPropagation(); $event.preventDefault()
"
[class.bookmarked]="isBookmarked()"
aria-label="Bookmark person">
[attr.aria-label]="
isBookmarked() ? 'Bookmark entfernen' : 'Person speichern'
"
[matTooltip]="
isBookmarked() ? 'Bookmark entfernen' : 'Person speichern'
">
<mat-icon>{{
isBookmarked() ? 'bookmark' : 'bookmark_border'
}}</mat-icon>
</button>
</div>
<h2
[skText]="loading()"
class="person-name"
[title]="person().display_name ?? ''">
{{ person().display_name ?? '' }}
</h2>
<p [skText]="loading()" class="person-id">
{{ distinguishingId() }}
</p>
@@ -25,6 +25,7 @@
.card-header {
padding: 16px;
display: flex;
align-items: flex-start;
gap: 12px;
border-bottom: 1px solid var(--sg-surface-soft);
text-decoration: none;
@@ -52,6 +53,14 @@
}
}
.name-row {
display: flex;
min-width: 0;
min-height: 40px;
align-items: center;
gap: 8px;
}
.rating-and-bookmark {
display: flex;
justify-content: space-between;
@@ -82,18 +91,30 @@
}
.bookmark-btn {
display: grid;
place-items: center;
flex: 0 0 32px;
width: 32px;
height: 32px;
border: none;
border-radius: 50%;
background: transparent;
cursor: pointer;
padding: 2px;
padding: 0;
color: var(--sg-text-soft);
transition:
color 0.15s ease,
background-color 0.15s ease;
&:hover {
&:hover,
&:focus-visible {
background: var(--sg-primary-soft);
color: var(--sg-primary);
outline: none;
}
&.bookmarked {
color: #e53935;
color: var(--sg-success);
}
mat-icon {
@@ -104,11 +125,12 @@
}
.person-name {
margin: 6px 0 2px;
flex: 1 1 auto;
min-width: 0;
margin: 0;
font-size: 16px;
font-weight: 600;
color: var(--sg-text);
min-height: 24px;
line-height: 24px;
white-space: nowrap;
overflow: hidden;
@@ -42,6 +42,7 @@ import {
MatAutocompleteSelectedEvent,
} from '@angular/material/autocomplete';
import { SkTextDirective } from '../../custom-directives/sk-text.directive';
import { BookmarkService } from '../../shared/services/bookmark.service';
@Component({
selector: 'app-person-list',
@@ -73,6 +74,7 @@ export class PersonListComponent {
private readonly topicsService = inject(TopicsService);
private readonly institutionsService = inject(InstitutionsService);
private readonly destroyRef = inject(DestroyRef);
private readonly bookmarkService = inject(BookmarkService);
public readonly state = inject(SharedStateService);
public readonly paginationService = inject(PaginationService);
public readonly resolverStateService = inject(ResolverStateService);
@@ -120,9 +122,12 @@ export class PersonListComponent {
],
});
// Bookmarking
bookmarkedIds = new Set<string>();
constructor() {
this.bookmarkService
.load()
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe();
if (!this.institutionControl.value) {
this.yearFilterEnabledControl.disable();
}
@@ -510,12 +515,10 @@ export class PersonListComponent {
// Bookmarks
toggleBookmark(person: CustomAuthor): void {
if (!person.id) return;
if (this.bookmarkedIds.has(person.id)) {
this.bookmarkedIds.delete(person.id);
} else {
this.bookmarkedIds.add(person.id);
}
this.bookmarkService
.confirmToggle(person)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe();
}
onTopicSelectionChange(newSelection: Set<string>): void {
@@ -540,7 +543,7 @@ export class PersonListComponent {
}
isBookmarked(person: CustomAuthor): boolean {
return !!person.id && this.bookmarkedIds.has(person.id);
return this.bookmarkService.isBookmarked(person.id);
}
clearSearch(): void {
@@ -21,22 +21,23 @@
<mat-expansion-panel class="mat-elevation-z1" [expanded]="true">
<mat-expansion-panel-header>
<mat-panel-title>Publikationsliste</mat-panel-title>
<mat-panel-description>{{ total }} Publikationen</mat-panel-description>
<mat-panel-description
>{{ totalElements() }} Publikationen</mat-panel-description
>
</mat-expansion-panel-header>
<div class="publication-filter-stack">
<form class="publication-filters" [formGroup]="filterForm">
<form class="publication-filters">
<mat-form-field>
<mat-icon matPrefix class="filter-prefix-icon"
>calendar_today</mat-icon
>
<mat-select
placeholder="Jahr"
formControlName="publicationYears"
multiple
[panelWidth]="null"
(selectionChange)="applyFilters()"
(selectionChange)="handleYearSelectionChange($event)"
(opened)="focusSelectSearch(yearSearchInput)"
(closed)="yearSearchControl.setValue('')">
[value]="this.selectedYearsQueryParams()">
<mat-select-trigger>{{
yearSelectionSummary()
}}</mat-select-trigger>
@@ -46,7 +47,6 @@
#yearSearchInput
type="text"
class="select-search__input"
[formControl]="yearSearchControl"
placeholder="Jahr suchen…"
(keydown)="$event.stopPropagation()" />
</div>
@@ -62,12 +62,11 @@
<mat-icon matPrefix class="filter-prefix-icon">category</mat-icon>
<mat-select
placeholder="Typ"
formControlName="types"
multiple
[panelWidth]="null"
(selectionChange)="applyFilters()"
(selectionChange)="handleTypeSelectionChange($event)"
(opened)="focusSelectSearch(typeSearchInput)"
(closed)="typeSearchControl.setValue('')">
[value]="this.selectedTypesQueryParams()">
<mat-select-trigger>{{
typeSelectionSummary()
}}</mat-select-trigger>
@@ -93,12 +92,11 @@
<mat-icon matPrefix class="filter-prefix-icon">translate</mat-icon>
<mat-select
placeholder="Sprache"
formControlName="languages"
multiple
[panelWidth]="null"
(selectionChange)="applyFilters()"
(selectionChange)="handleLanguageSelectionChange($event)"
(opened)="focusSelectSearch(languageSearchInput)"
(closed)="languageSearchControl.setValue('')">
[value]="this.selectedLanguagesQueryParams()">
<mat-select-trigger>{{
languageSelectionSummary()
}}</mat-select-trigger>
@@ -185,21 +183,6 @@
</mat-autocomplete>
</mat-form-field>
<mat-form-field class="sort-field">
<mat-icon matPrefix class="filter-prefix-icon">sort</mat-icon>
<mat-select
[formControl]="sortControl"
[panelWidth]="null"
aria-label="Sortierung"
(selectionChange)="onSortChange()">
@for (option of sortOptions; track option.value) {
<mat-option [value]="option.value">{{
option.label
}}</mat-option>
}
</mat-select>
</mat-form-field>
<button
class="reset-filter-btn"
mat-stroked-button
@@ -211,20 +194,17 @@
</button>
</form>
@let selectedYears = filterForm.controls.publicationYears.value;
@let selectedTypes = filterForm.controls.types.value;
@let selectedLanguages = filterForm.controls.languages.value;
@if (
selectedInstitutions.length ||
selectedTopics.length ||
selectedYears.length ||
selectedTypes.length ||
selectedLanguages.length
selectedInstitutionIdsQueryParams().length ||
selectedTopicIdsQueryParams().length ||
selectedYearsQueryParams().length ||
selectedTypesQueryParams().length ||
selectedLanguagesQueryParams().length
) {
<div class="active-filters-row" aria-label="Aktive Filter">
<span class="active-filters-label">Aktive Filter:</span>
<div class="chips-container">
@for (year of selectedYears; track year) {
@for (year of selectedYearsQueryParams(); track year) {
<span class="active-meta-filter">
<span class="filter-meta-chip">
<mat-icon class="filter-meta-chip__icon"
@@ -241,7 +221,7 @@
</button>
</span>
}
@for (type of selectedTypes; track type) {
@for (type of selectedTypesQueryParams(); track type) {
<span class="active-meta-filter">
<span class="filter-meta-chip">
<mat-icon class="filter-meta-chip__icon">category</mat-icon>
@@ -256,14 +236,17 @@
</button>
</span>
}
@for (language of selectedLanguages; track language) {
@for (
language of selectedLanguagesQueryParams();
track language
) {
<span class="active-meta-filter">
<span class="filter-meta-chip">
<mat-icon class="filter-meta-chip__icon"
>translate</mat-icon
>
<span class="filter-meta-chip__label">{{
languageLabel(language)
language | languageCode
}}</span>
</span>
<button
@@ -271,20 +254,20 @@
class="remove-chip-btn"
(click)="toggleLanguageFilter(language)"
[attr.aria-label]="
'Sprachfilter ' + languageLabel(language) + ' entfernen'
'Sprachfilter ' + (language | languageCode) + ' entfernen'
">
<mat-icon>close</mat-icon>
</button>
</span>
}
@for (topic of selectedTopics; track topic.id) {
@for (topic of selectedTopics(); track topic.id) {
<span class="active-meta-filter">
<span
class="filter-topic-chip"
[style.--topic-color]="getSelectedTopicColor(topic)"
[matTooltip]="getSelectedTopicTooltip(topic)"
[style.--topic-color]="getWorkTopicColor(topic)"
[matTooltip]="getSelectedWorkTopicTooltip(topic)"
matTooltipClass="topic-chip-tooltip"
[matTooltipDisabled]="!getSelectedTopicTooltip(topic)">
[matTooltipDisabled]="!getSelectedWorkTopicTooltip(topic)">
<mat-icon class="filter-topic-chip__icon">label</mat-icon>
<span class="filter-topic-chip__label">{{
topic.display_name
@@ -301,7 +284,10 @@
</button>
</span>
}
@for (institution of selectedInstitutions; track institution.id) {
@for (
institution of selectedInstitutions();
track institution.id
) {
@let instCountry = selectedInstitutionCountry(institution);
<span class="active-institution-filter">
<span class="filter-institution-chip">
@@ -325,7 +311,10 @@
}
<mat-icon
class="institution-open-icon"
(click)="openInstitutionPage(institution.id, $event)"
[routerLink]="[
'/institution',
extractRawId(institution.id),
]"
aria-label="Institutionsseite öffnen"
>open_in_new</mat-icon
>
@@ -344,13 +333,16 @@
}
</div>
<app-data-table [columns]="workColumns" [data]="publications" />
<app-data-table
[columns]="workColumns"
[data]="elements()"
queryParamSortKey="sort_by"
queryParamSortDirectionKey="sort_direction" />
<app-query-param-paginator
[total]="total"
queryParamPageKey="publicationPage"
queryParamSizeKey="publicationPageSize"
[pageSizeOptions]="paginationService.options"
(handlePageChange)="onPage($event)" />
[total]="totalElements()"
queryParamPageKey="page"
queryParamSizeKey="size"
[pageSizeOptions]="paginationService.options" />
</mat-expansion-panel>
</mat-accordion>
</div>
@@ -398,11 +390,11 @@
<button
type="button"
class="cell-filter-pill"
[class.active]="isLanguageActive(work.language)"
[class.active]="isLanguageActive(work.language_code)"
matTooltip="Nach Sprache filtern"
matTooltipPosition="above"
(click)="toggleLanguageFilter(work.language)">
{{ work.language | languageCode }}
(click)="toggleLanguageFilter(work.language_code)">
{{ work.language_code | languageCode }}
</button>
} @else {
<span class="empty-text">-</span>
@@ -410,43 +402,49 @@
</ng-template>
<ng-template #institutionsTmp let-work>
@let publicationInstitutions = getInstitutions(work);
@let publicationInstitutions = work.institutions ?? [];
@let institutionsExpanded = true;
@let visibleInstitutions =
institutionsExpanded
? publicationInstitutions
: publicationInstitutions.slice(0, 3);
<div class="institution-tags" aria-label="Institutionen">
@for (institution of visibleInstitutions; track institution.id) {
<div
class="institution-tags"
aria-label="Institutionen"
style="padding: 0.5rem 0">
@for (
institution of visibleInstitutions;
track institution.institution_id
) {
<button
type="button"
class="publication-institution-tag"
[class.active]="isInstitutionActive(institution.id!)"
[matTooltip]="institution.display_name"
[class.active]="isInstitutionActive(institution.institution_id!)"
[matTooltip]="institution.institution_name"
matTooltipPosition="above"
[attr.aria-label]="
'Nach Institution ' + institution.display_name + ' filtern'
'Nach Institution ' + institution.institution_name + ' filtern'
"
(click)="
filterByInstitution({
id: institution.id!,
name: institution.display_name || '',
id: institution.institution_id!,
name: institution.institution_name || '',
})
">
<mat-icon class="institution-icon">apartment</mat-icon>
<span class="institution-name">{{ institution.display_name }}</span>
@if (institution.country_code) {
<span class="institution-name">{{ institution.institution_name }}</span>
@if (institution.institution_country_code) {
<img
alt=""
class="flag-img"
[src]="
'https://flagcdn.io/' +
institution.country_code.toLowerCase() +
institution.institution_country_code.toLowerCase() +
'.svg'
"
height="10" />
<span class="country-code">{{
institution.country_code.toUpperCase()
institution.institution_country_code.toUpperCase()
}}</span>
}
</button>
@@ -483,7 +481,7 @@
[subfieldName]="topic.subfield?.display_name"
[fieldName]="topic.field?.display_name"
[domainName]="topic.domain?.display_name"
[color]="getTopicColor(topic)"
[color]="getWorkTopicColor(topic)"
[disabled]="!topic.id"
[active]="isTopicActive(topic)"
(chipClick)="filterByTopic(topic)">
@@ -511,7 +509,7 @@
<a
mat-icon-button
color="primary"
[routerLink]="['/publication', publicationKey(work)]"
[routerLink]="['/publication', extractRawId(work.id)]"
matTooltip="Details anzeigen">
<mat-icon>open_in_new</mat-icon>
</a>
File diff suppressed because it is too large Load Diff
@@ -6,6 +6,27 @@
<div class="name-line">
<span>Person</span>
<h1>{{ displayName() }}</h1>
<button
type="button"
class="profile-bookmark-button"
[class.bookmarked]="bookmarkService.isBookmarked(person()?.id)"
[attr.aria-label]="
bookmarkService.isBookmarked(person()?.id)
? 'Bookmark entfernen'
: 'Person bookmarken'
"
[matTooltip]="
bookmarkService.isBookmarked(person()?.id)
? 'Bookmark entfernen'
: 'Person bookmarken'
"
(click)="toggleBookmark()">
<mat-icon>{{
bookmarkService.isBookmarked(person()?.id)
? 'bookmark'
: 'bookmark_border'
}}</mat-icon>
</button>
</div>
<div class="institution-line">
<mat-icon class="institution-icon">apartment</mat-icon>
@@ -76,6 +76,32 @@
font-weight: 700;
}
.profile-bookmark-button {
display: grid;
place-items: center;
width: 36px;
height: 36px;
margin-left: 4px;
padding: 0;
border: 1px solid var(--sg-border);
border-radius: 50%;
background: white;
color: var(--sg-text-muted);
cursor: pointer;
&:hover,
&.bookmarked {
border-color: var(--sg-primary);
color: var(--sg-primary);
}
mat-icon {
width: 21px;
height: 21px;
font-size: 21px;
}
}
.institution-line {
display: flex;
align-items: center;
@@ -24,6 +24,7 @@ import { PersonInterestingComponent } from '../person-interesting/person-interes
import { WorksService } from '../../api';
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
import { PersonBioResolved } from '../../resolvers/person-bio.resolver';
import { BookmarkService } from '../../shared/services/bookmark.service';
@Component({
selector: 'app-person',
@@ -47,6 +48,14 @@ export class PersonComponent {
private readonly worksApi = inject(WorksService);
private readonly destroyRef = inject(DestroyRef);
readonly bookmarkService = inject(BookmarkService);
constructor() {
this.bookmarkService
.load()
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe();
}
readonly params = toSignal(this.activatedRoute.paramMap);
readonly routerEvents = toSignal(this.router.events);
@@ -99,6 +108,15 @@ export class PersonComponent {
{ initialValue: null },
);
toggleBookmark(): void {
const person = this.person();
if (!person) return;
this.bookmarkService
.confirmToggle(person)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe();
}
readonly personBio = toSignal(
this.activatedRoute.data.pipe(
switchMap((data) => {
@@ -0,0 +1,18 @@
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { Institution, WorksV2Service } from '../api';
export const selectedInstitutionsResolver: ResolveFn<Array<Institution>> = (
route,
state,
) => {
const institutionIds = route.queryParamMap.getAll('publicationInstitutionId');
if (institutionIds.length === 0) {
return [];
}
console.log('Resolving selected institutions for IDs:', institutionIds);
return inject(WorksV2Service).getInstitutionsByIds(
institutionIds.map((id) => id.trim()).filter((id) => id.length > 0),
);
};
@@ -0,0 +1,18 @@
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { WorksV2Service, WorkTopic } from '../api';
export const selectedTopicsResolver: ResolveFn<Array<WorkTopic>> = (
route,
state,
) => {
const topicIds = route.queryParamMap.getAll('publicationTopicId');
if (topicIds.length === 0) {
return [];
}
console.log('Resolving selected topics for IDs:', topicIds);
return inject(WorksV2Service).getWorkTopicsByIds(
topicIds.map((id) => id.trim()).filter((id) => id.length > 0),
);
};
+35 -18
View File
@@ -1,27 +1,44 @@
import { ResolveFn } from '@angular/router';
import { WorkPage, WorksService } from '../api';
import {
AuthorWorkPage,
SortDirection,
WorkSortBy,
WorksV2Service,
} from '../api';
import { inject } from '@angular/core';
export const workPageResolver: ResolveFn<WorkPage> = (route, state) => {
const authorId = route.paramMap.get('authorId');
const page = Number(route.queryParamMap.get('page') || 0);
const pageSize = Number(route.queryParamMap.get('pageSize') || 10);
const publicationYears = route.queryParamMap
.getAll('publicationYears')
.map(Number);
const type = route.queryParamMap.getAll('types');
const languages = route.queryParamMap.getAll('languages');
const institutionIds = route.queryParamMap.getAll('institutionIds');
const topicsIds = route.queryParamMap.getAll('topicsIds');
export const workPageResolver: ResolveFn<AuthorWorkPage> = (route, state) => {
const rawOaAuthorId =
route.parent?.paramMap.get('id') || route.paramMap.get('id');
if (!rawOaAuthorId) {
throw new Error('Author ID is required to resolve author work purposes.');
}
return inject(WorksService).getAuthorWorks(
authorId!,
const page = Number(route.queryParamMap.get('page')) || 0;
const size = Number(route.queryParamMap.get('size')) || 10;
const publicationYears = route.queryParamMap
.getAll('publicationYear')
.map(Number);
const publicationTypes = route.queryParamMap.getAll('publicationType');
const institutionIds = route.queryParamMap.getAll('publicationInstitutionId');
const topicIds = route.queryParamMap.getAll('publicationTopicId');
const sortBy: WorkSortBy = (route.queryParamMap.get('sort_by') ||
'publication_year') as WorkSortBy;
const sortDirection: SortDirection = (route.queryParamMap.get(
'sort_direction',
) || 'desc') as SortDirection;
return inject(WorksV2Service).getAuthorWorkPage(
rawOaAuthorId,
page,
pageSize,
size,
publicationYears,
type,
languages,
publicationTypes,
institutionIds,
topicsIds,
topicIds,
undefined,
sortBy,
sortDirection,
);
};
@@ -0,0 +1,105 @@
import { HttpClient } from '@angular/common/http';
import { Injectable, inject, signal } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { EMPTY, Observable, finalize, map, of, switchMap, tap } from 'rxjs';
import { Configuration, CustomAuthor } from '../../api';
import { ConfirmationDialogComponent } from '../ui/confirmation-dialog/confirmation-dialog.component';
export interface PersonBookmark {
person_id: string;
person_name: string | null;
created_at: string;
}
@Injectable({ providedIn: 'root' })
export class BookmarkService {
private readonly http = inject(HttpClient);
private readonly configuration = inject(Configuration, { optional: true });
private readonly dialog = inject(MatDialog);
private readonly bookmarkState = signal<PersonBookmark[]>([]);
private loading = false;
private loaded = false;
readonly bookmarks = this.bookmarkState.asReadonly();
load(force = false): Observable<PersonBookmark[]> {
if (this.loaded && !force) return of(this.bookmarkState());
if (this.loading) return of(this.bookmarkState());
this.loading = true;
return this.http
.get<PersonBookmark[]>(`${this.basePath}/api/bookmarks/persons`)
.pipe(
tap((bookmarks) => {
this.bookmarkState.set(bookmarks);
this.loaded = true;
}),
finalize(() => (this.loading = false)),
);
}
isBookmarked(personId: string | null | undefined): boolean {
const id = this.normalizeId(personId);
return !!id && this.bookmarkState().some((item) => item.person_id === id);
}
toggle(person: CustomAuthor): Observable<boolean> {
const personId = this.normalizeId(person.id);
if (!personId) return of(false);
if (this.isBookmarked(personId)) {
return this.http
.delete<void>(`${this.basePath}/api/bookmarks/persons/${personId}`)
.pipe(
tap(() =>
this.bookmarkState.update((items) =>
items.filter((item) => item.person_id !== personId),
),
),
map(() => false),
);
}
return this.http
.put<PersonBookmark>(`${this.basePath}/api/bookmarks/persons/${personId}`, {
person_name: person.display_name ?? null,
})
.pipe(
tap((bookmark) =>
this.bookmarkState.update((items) => [
bookmark,
...items.filter((item) => item.person_id !== bookmark.person_id),
]),
),
map(() => true),
);
}
confirmToggle(person: CustomAuthor): Observable<boolean> {
const removing = this.isBookmarked(person.id);
const personName = person.display_name?.trim() || 'diese Person';
const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
data: {
title: removing ? 'Bookmark entfernen' : 'Person speichern',
message: removing
? `Möchtest Du „${personName}“ wirklich aus Deinen Bookmarks entfernen?`
: `Möchtest Du „${personName}“ in Deinen Bookmarks speichern?`,
confirmText: removing ? 'Entfernen' : 'Speichern',
cancelText: 'Abbrechen',
},
});
return dialogRef.afterClosed().pipe(
switchMap((confirmed) => (confirmed ? this.toggle(person) : EMPTY)),
);
}
private normalizeId(personId: string | null | undefined): string {
return personId?.trim().replace(/\/$/, '').split('/').pop() ?? '';
}
private get basePath(): string {
return this.configuration?.basePath ?? '';
}
}
@@ -74,6 +74,12 @@ export class AppMenuComponent {
},
disabled: false,
},
{
label: 'Bookmarks',
icon: 'bookmarks',
route: '/bookmarks',
disabled: false,
},
{
label: 'News',
icon: 'newspaper',
@@ -51,11 +51,11 @@ export class ConfirmationDialogComponent {
}
onCancelClick(): void {
this.dialogRef.close();
this.dialogRef.close(false);
}
onConfirmClick(): void {
this.confirmDelete.emit();
this.dialogRef.close();
this.dialogRef.close(true);
}
}
@@ -0,0 +1,84 @@
<div
#uploadContainer
class="file-upload-container"
[class.compact]="files.length > 0">
<!-- Drop Zone (shrinks when files are present) -->
<div class="drop-zone-wrapper">
<div
#dropZone
class="drop-zone"
[class.drag-over]="isDragging"
(click)="fileInput.click()">
<mat-icon class="upload-icon">attach_file</mat-icon>
<p class="drop-text">Drag & Drop Dateien hier oder klicken</p>
<small class="file-info">
Unterstützt: {{ requiredFileType }} (Max:
{{ maxFileSize / 1024 / 1024 }}MB, {{ maxFiles }} Dateien)
</small>
</div>
<!-- File Strip (compact row, appears above the drop zone) -->
@if (files.length > 0) {
<mat-divider></mat-divider>
<div class="file-strip">
@for (file of files; track file.id) {
<div class="file-chip" [matTooltip]="file.file.name">
<div class="chip-thumb">
@if (file.file.type.startsWith('image/')) {
<img [src]="file.previewUrl" alt="Preview" />
} @else {
<mat-icon>{{ getIcon(file.file.type) }}</mat-icon>
}
<div class="chip-overlay">
<button
type="button"
class="chip-btn"
(click)="downloadFile(file.id)"
matTooltip="Download">
<mat-icon>download</mat-icon>
</button>
<button
type="button"
class="chip-btn"
(click)="cancelUpload(file.id)"
matTooltip="Cancel">
<mat-icon>cancel</mat-icon>
</button>
<button
type="button"
class="chip-btn"
(click)="removeFile(file.id)"
matTooltip="Remove">
<mat-icon>close</mat-icon>
</button>
</div>
</div>
@if (file.progress > 0 && file.progress < 100) {
<div class="chip-progress">
<div
class="chip-progress-fill"
[style.width.%]="file.progress"></div>
</div>
}
<div class="chip-name">{{ file.file.name }}</div>
</div>
}
</div>
}
</div>
<!-- Hidden File Input -->
<input
#fileInput
type="file"
[accept]="
typeof requiredFileType === 'string'
? requiredFileType
: requiredFileType.join(',')
"
multiple
(change)="onFileChange($event)"
style="display: none" />
</div>
@@ -0,0 +1,223 @@
.file-upload-container {
margin: 0 auto;
display: flex;
width: 100%;
flex-direction: column;
gap: 12px;
position: relative;
.drop-zone-wrapper {
border: 2px dashed #ccc;
border-radius: 12px;
background-color: #f9f9f9;
height: 100%;
}
.drop-zone {
max-width: 100%;
flex: 1;
min-height: 0;
padding: 40px 20px;
text-align: center;
cursor: pointer;
transition: all 0.3s ease;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
.upload-icon {
font-size: 48px;
height: 48px;
width: 48px;
color: #1976d2;
margin-bottom: 12px;
transition: all 0.3s ease;
}
.drop-text {
font-size: 16px;
color: #555;
margin-bottom: 8px;
transition: all 0.3s ease;
}
.file-info {
font-size: 12px;
color: #888;
}
&.drag-over {
border-color: #1976d2;
background-color: #e3f2fd;
}
}
&.compact .drop-zone {
padding: 16px 20px;
.upload-icon {
font-size: 28px;
height: 28px;
width: 28px;
margin-bottom: 6px;
}
.drop-text {
font-size: 13px;
margin-bottom: 4px;
}
.file-info {
font-size: 11px;
}
}
// Compact horizontal file strip
.file-strip {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(90px, 2fr));
align-items: center;
justify-content: center;
overflow-x: auto;
overflow-y: hidden;
padding: 2px 2px 8px;
&::-webkit-scrollbar {
height: 6px;
}
&::-webkit-scrollbar-thumb {
background: #ccc;
border-radius: 3px;
}
&::-webkit-scrollbar-track {
background: transparent;
}
}
// Individual compact file chip
.file-chip {
flex: 0 0 auto;
width: 90px;
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
.chip-thumb {
position: relative;
width: 60px;
height: 60px;
border-radius: 10px;
overflow: hidden;
background-color: #eef1f4;
border: 1px solid #e0e0e0;
display: flex;
align-items: center;
justify-content: center;
img {
width: 100%;
height: 100%;
object-fit: cover;
}
mat-icon {
font-size: 28px;
height: 28px;
width: 28px;
color: #1976d2;
}
.chip-overlay {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
gap: 2px;
background: rgba(0, 0, 0, 0.55);
opacity: 0;
transition: opacity 0.2s ease;
.chip-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
padding: 0;
border: none;
background: transparent;
color: #fff;
cursor: pointer;
border-radius: 4px;
&:hover {
background: rgba(255, 255, 255, 0.2);
}
mat-icon {
font-size: 15px;
height: 15px;
width: 15px;
color: #fff;
}
}
}
&:hover .chip-overlay,
&:focus-within .chip-overlay {
opacity: 1;
}
}
.chip-progress {
width: 100%;
height: 3px;
border-radius: 2px;
background-color: #e0e0e0;
overflow: hidden;
.chip-progress-fill {
height: 100%;
background-color: #1976d2;
transition: width 0.2s ease;
}
}
.chip-name {
width: 100%;
font-size: 11px;
line-height: 1.3;
color: #333;
text-align: center;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
}
/* Responsive */
@media (max-width: 600px) {
.file-upload-container {
gap: 10px;
height: 280px;
}
.drop-zone {
padding: 24px 16px;
}
.file-chip {
width: 64px;
.chip-thumb {
width: 50px;
height: 50px;
}
}
}
@@ -0,0 +1,234 @@
import {
Component,
Input,
Output,
EventEmitter,
ViewChild,
ElementRef,
OnDestroy,
OnInit,
inject,
effect,
} from '@angular/core';
import { HttpClient, HttpEventType } from '@angular/common/http';
import { Subscription } from 'rxjs';
import { finalize } from 'rxjs/operators';
import { MatIconModule } from '@angular/material/icon';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MatDividerModule } from '@angular/material/divider';
export interface FileUploadItem {
file: File;
id: string;
previewUrl?: string;
progress: number;
error?: string;
}
@Component({
selector: 'app-file-upload',
imports: [MatIconModule, MatTooltipModule, MatDividerModule],
templateUrl: 'file-upload.component.html',
styleUrls: ['file-upload.component.scss'],
})
export class FileUploadComponent implements OnInit, OnDestroy {
private snackBar = inject(MatSnackBar);
private http = inject(HttpClient);
@Input() uploadUrl: string = '';
@Input() uploadedFiles: FileUploadItem[] = [];
@Input() requiredFileType: string | string[] = 'application/pdf';
@Input() maxFileSize: number = 10 * 1024 * 1024; // 10MB
@Input() maxFiles: number = 5;
@Output() filesChange = new EventEmitter<FileUploadItem[]>();
@Output() filesSelected = new EventEmitter<FileUploadItem[]>();
@Output() uploadProgressChange = new EventEmitter<{
id: string;
progress: number;
}>();
@ViewChild('fileInput', { static: true })
fileInput!: ElementRef<HTMLInputElement>;
@ViewChild('dropZone', { static: true })
dropZone!: ElementRef<HTMLDivElement>;
@ViewChild('uploadContainer', { static: true })
uploadContainer!: ElementRef<HTMLDivElement>;
files: FileUploadItem[] = [];
private uploadSub: Subscription = new Subscription();
isDragging = false;
private dragCounter = 0;
ngOnInit() {
this.files = [...this.uploadedFiles]; // bind the input files to the internal state
this.setupDragAndDrop();
}
ngOnDestroy() {
this.uploadSub.unsubscribe();
}
private setupDragAndDrop() {
const zone = this.uploadContainer.nativeElement;
zone.addEventListener('dragenter', (e) => {
e.preventDefault();
this.dragCounter++;
this.isDragging = this.dragCounter > 0;
});
zone.addEventListener('dragover', (e) => {
e.preventDefault();
});
zone.addEventListener('dragleave', (e) => {
e.preventDefault();
this.dragCounter--;
this.isDragging = this.dragCounter > 0;
});
zone.addEventListener('drop', (e) => {
e.preventDefault();
this.dragCounter = 0;
this.isDragging = false;
const files = e.dataTransfer?.files;
if (files) {
this.handleFiles(files);
}
});
}
onFileChange(event: Event) {
const input = event.target as HTMLInputElement;
if (input.files) {
this.handleFiles(input.files);
}
}
private handleFiles(fileList: FileList) {
const validFiles: File[] = [];
const newFiles: FileUploadItem[] = [];
Array.from(fileList).forEach((file) => {
if (!this.isValidFile(file)) return;
validFiles.push(file);
});
console.log('Valid files:', validFiles);
if (validFiles.length === 0) return;
const remainingSlots = this.maxFiles - this.files.length;
const filesToAdd = validFiles.slice(0, remainingSlots);
filesToAdd.forEach((file) => {
newFiles.push({
file,
id: this.generateId(),
progress: 0,
previewUrl: this.getPreviewUrl(file),
});
});
this.files = [...this.files, ...newFiles];
this.emitFilesChange();
this.filesSelected.emit(this.files);
}
private isValidFile(file: File): boolean {
const type = file.type;
const size = file.size;
const allowedTypes = Array.isArray(this.requiredFileType)
? this.requiredFileType
: this.requiredFileType.split(',');
const isValidType = allowedTypes.some((t) => {
if (t.includes('/')) return type.startsWith(t);
if (t === 'image') return type.startsWith('image/');
if (t === 'pdf') return type === 'application/pdf';
if (t === 'text') return type.startsWith('text/');
return false;
});
if (!isValidType) {
this.showError(`Dateityp nicht erlaubt: ${file.name}`);
return false;
}
if (size > this.maxFileSize) {
this.showError(
`File zu groß: ${file.name} (${(size / 1024 / 1024).toFixed(2)}MB)`,
);
return false;
}
if (this.files.length + 1 > this.maxFiles) {
this.showError(
`Maximal ${this.maxFiles} Dateien erlaubt. Datei ${file.name} wurde nicht hinzugefügt.`,
);
return false;
}
return true;
}
private getPreviewUrl(file: File): string | undefined {
if (file.type.startsWith('image/')) {
return URL.createObjectURL(file);
}
return undefined;
}
private generateId(): string {
return Math.random().toString(36).substr(2, 9);
}
getIcon(fileType: string): string {
if (fileType.startsWith('image/')) return 'image';
if (fileType === 'application/pdf') return 'picture_as_pdf';
if (fileType.startsWith('text/')) return 'description';
return 'insert_drive_file';
}
cancelUpload(id: string) {
const file = this.files.find((f) => f.id === id);
if (file) {
this.files = this.files.filter((f) => f.id !== id);
this.emitFilesChange();
this.showError('Upload cancelled');
}
}
removeFile(id: string) {
this.files = this.files.filter((f) => f.id !== id);
this.emitFilesChange();
}
downloadFile(id: string) {
const file = this.files.find((f) => f.id === id);
if (file) {
const url = URL.createObjectURL(file.file);
const a = document.createElement('a');
a.href = url;
a.download = file.file.name;
a.click();
URL.revokeObjectURL(url);
}
}
private emitFilesChange() {
this.filesChange.emit(this.files);
}
private reset() {
this.uploadSub.unsubscribe();
this.uploadSub = new Subscription();
}
private showError(message: string) {
this.snackBar.open(message, 'OK', { duration: 3000 });
}
}