Compare commits
119
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1a6c32e0c | ||
|
|
cf5a3e7d3d | ||
|
|
89f45082fb | ||
|
|
0ad6ac70ff | ||
|
|
e8e0decc6c | ||
|
|
57aaf77162 | ||
|
|
07ce24143b | ||
|
|
bf5e065520 | ||
|
|
08178e74d2 | ||
|
|
c66fcff906 | ||
|
|
b0dd0e509d | ||
|
|
719da6e921 | ||
|
|
e4b3d0a9a9 | ||
|
|
c0e231a32b | ||
|
|
af9f9a25da | ||
|
|
0a465bc7e1 | ||
|
|
aec735e09e | ||
|
|
9ce6d5f26e | ||
|
|
f4b4fb0562 | ||
|
|
aa22fad67d | ||
|
|
548bb4ce70 | ||
|
|
b6871b3618 | ||
|
|
fe5e816551 | ||
|
|
20d2a281b1 | ||
|
|
e2ae0c660a | ||
|
|
9e8ae16597 | ||
|
|
e5284a79c9 | ||
|
|
79dad5dfb0 | ||
|
|
a511c16fb1 | ||
|
|
98a1214a4d | ||
|
|
be459c45cf | ||
|
|
328ef2938c | ||
|
|
21f3f49078 | ||
|
|
882ad3b8cf | ||
|
|
d8b7d8bc2e | ||
|
|
c1692535a5 | ||
|
|
af0e326747 | ||
|
|
6cdaa9738a | ||
|
|
1e5d0c4517 | ||
|
|
127f5ca287 | ||
|
|
f51b775fd9 | ||
|
|
0015b92591 | ||
|
|
37e1f1811f | ||
|
|
daa4f79ea0 | ||
|
|
c70a566514 | ||
|
|
b99d3a7ff1 | ||
|
|
30cbb080b0 | ||
|
|
d8eec59d5d | ||
|
|
be89e2986b | ||
|
|
916af84651 | ||
|
|
4e5ab529de | ||
|
|
3b1ffda3b2 | ||
|
|
cdf58044a8 | ||
|
|
e9fdf7d538 | ||
|
|
57f221868d | ||
|
|
ae7d1a54cb | ||
|
|
71b075b365 | ||
|
|
fb40bc548e | ||
|
|
d06c1954a5 | ||
|
|
545d487fea | ||
|
|
62f0812aae | ||
|
|
e0dda3ea0c | ||
|
|
7628f219e2 | ||
|
|
1d7a54c866 | ||
|
|
6c55493acb | ||
|
|
42bcac251b | ||
|
|
1fc509ea13 | ||
|
|
90a1b930a3 | ||
|
|
9011d58355 | ||
|
|
f2c0f203f6 | ||
|
|
3f5746dd7d | ||
|
|
adce95ead4 | ||
|
|
84d7ca0122 | ||
|
|
053af573fc | ||
|
|
06f34bec45 | ||
|
|
c1641fdb38 | ||
|
|
9115af350e | ||
|
|
77cf3612d9 | ||
|
|
07c7343f94 | ||
|
|
530f751f02 | ||
|
|
9a005cabe9 | ||
|
|
f7eb502d9d | ||
|
|
a407cfb514 | ||
|
|
ff43d07b6d | ||
|
|
340b5f22b7 | ||
|
|
b4a90131bb | ||
|
|
90149ddb4e | ||
|
|
1f09f0cf68 | ||
|
|
8035e7aecb | ||
|
|
cea32deba2 | ||
|
|
b02358e3a0 | ||
|
|
79320f27c9 | ||
|
|
52ca2f7339 | ||
|
|
78e54248e3 | ||
|
|
fc82604947 | ||
|
|
40bb0feaf8 | ||
|
|
0afb6a9481 | ||
|
|
57f72a473f | ||
|
|
876fbb9980 | ||
|
|
bee09f7c29 | ||
|
|
c31aef4131 | ||
|
|
53a36e7974 | ||
|
|
60e74c4916 | ||
|
|
1d24f912ae | ||
|
|
f9591c512c | ||
|
|
f74396e97b | ||
|
|
1127eeebb8 | ||
|
|
e9590e8b04 | ||
|
|
fd0bc89771 | ||
|
|
32a38b46fe | ||
|
|
e5f9d8cfdf | ||
|
|
ecd6b30626 | ||
|
|
31da701fe7 | ||
|
|
9d875b3935 | ||
|
|
8cab4ffb42 | ||
|
|
61aeb5bf86 | ||
|
|
0821008d6e | ||
|
|
a4a24b77b9 | ||
|
|
897edab3cf |
@@ -2,7 +2,7 @@ import logging
|
|||||||
import uuid
|
import uuid
|
||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
from fastapi import APIRouter, Body, Depends, Response, status
|
from fastapi import APIRouter, Body, Depends, Query, Response, status
|
||||||
from sqlmodel import Session
|
from sqlmodel import Session
|
||||||
|
|
||||||
import inse.auth.service as auth_service
|
import inse.auth.service as auth_service
|
||||||
@@ -204,3 +204,30 @@ async def change_password(
|
|||||||
current_password=current_password,
|
current_password=current_password,
|
||||||
new_password=new_password,
|
new_password=new_password,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/can-fetch-gdpr-relevant-data",
|
||||||
|
summary="Check if user can fetch GDPR-relevant data",
|
||||||
|
description="Check if the authenticated user can fetch GDPR-relevant data for a given author and institution.",
|
||||||
|
operation_id="canFetchGdprRelevantData",
|
||||||
|
)
|
||||||
|
async def can_fetch_gdpr_relevant_data(
|
||||||
|
access_token: Annotated[
|
||||||
|
AccessTokenMetadata,
|
||||||
|
auth_service.CurrentUserAccessTokenPayloadDep,
|
||||||
|
],
|
||||||
|
raw_oa_author_id: Annotated[
|
||||||
|
str | None,
|
||||||
|
Query(description="OpenAlex author ID to check access for"),
|
||||||
|
] = None,
|
||||||
|
raw_oa_institution_id: Annotated[
|
||||||
|
str | None,
|
||||||
|
Query(description="OpenAlex institution ID to check access for"),
|
||||||
|
] = None,
|
||||||
|
) -> bool:
|
||||||
|
return await auth_service.can_fetch_gdpr_relevant_data(
|
||||||
|
access_token=access_token,
|
||||||
|
raw_oa_author_id=raw_oa_author_id,
|
||||||
|
raw_oa_institution_id=raw_oa_institution_id,
|
||||||
|
)
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ from inse.auth.model import (
|
|||||||
effective_role_for_roles,
|
effective_role_for_roles,
|
||||||
normalize_roles,
|
normalize_roles,
|
||||||
)
|
)
|
||||||
|
from inse.authors.v2 import service as authors_service
|
||||||
from inse.config import get_settings
|
from inse.config import get_settings
|
||||||
from inse.database import get_session
|
from inse.database import get_session
|
||||||
|
|
||||||
@@ -1451,3 +1452,69 @@ def change_password(
|
|||||||
logger.info("Password changed successfully for account %s", account.id)
|
logger.info("Password changed successfully for account %s", account.id)
|
||||||
|
|
||||||
return {"status": "ok"}
|
return {"status": "ok"}
|
||||||
|
|
||||||
|
|
||||||
|
async def can_fetch_gdpr_relevant_data(
|
||||||
|
access_token: AccessTokenMetadata,
|
||||||
|
raw_oa_author_id: str | None = None,
|
||||||
|
raw_oa_institution_id: str | None = None,
|
||||||
|
) -> bool:
|
||||||
|
"""Returns True if the user associated with the provided access token is allowed to fetch GDPR-relevant data for the specified OpenAlex author ID and institution ID, based on their effective institution ID.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
access_token (AccessTokenMetadata): The access token for the user.
|
||||||
|
raw_oa_author_id (str | None, optional): The OpenAlex author ID for which to check access. Defaults to None.
|
||||||
|
raw_oa_institution_id (str | None, optional): The OpenAlex institution ID for which to check access. Defaults to None.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: True if the user is allowed to fetch GDPR-relevant data for the specified IDs, False otherwise.
|
||||||
|
"""
|
||||||
|
|
||||||
|
logger.debug(
|
||||||
|
"Checking if user with effective institution ID %s can fetch GDPR-relevant data for author ID %s and institution ID %s",
|
||||||
|
access_token.effective_institution_id,
|
||||||
|
raw_oa_author_id,
|
||||||
|
raw_oa_institution_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
if not raw_oa_author_id and not raw_oa_institution_id:
|
||||||
|
logger.debug("No OpenAlex author ID or institution ID provided")
|
||||||
|
return False
|
||||||
|
|
||||||
|
effective_institution_id = access_token.effective_institution_id
|
||||||
|
# Current user does not belong to any institution
|
||||||
|
if not effective_institution_id:
|
||||||
|
logger.debug(
|
||||||
|
"Current user does not belong to any institution, cannot fetch GDPR-relevant data"
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Current user belongs to an institution, but the request is for a different institution
|
||||||
|
if (
|
||||||
|
raw_oa_institution_id
|
||||||
|
and effective_institution_id
|
||||||
|
and raw_oa_institution_id != effective_institution_id
|
||||||
|
):
|
||||||
|
logger.debug(
|
||||||
|
"Current user belongs to institution %s, but request is for institution %s, cannot fetch GDPR-relevant data",
|
||||||
|
effective_institution_id,
|
||||||
|
raw_oa_institution_id,
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Current user belongs to an institution, but request is for author not belonging to that institution
|
||||||
|
if raw_oa_author_id:
|
||||||
|
author_belongs_to_institution = (
|
||||||
|
await authors_service.author_currently_belongs_to_institution(
|
||||||
|
raw_oa_author_id or "", effective_institution_id
|
||||||
|
)
|
||||||
|
)
|
||||||
|
logger.debug(
|
||||||
|
"Author %s belongs to institution %s: %s",
|
||||||
|
raw_oa_author_id,
|
||||||
|
effective_institution_id,
|
||||||
|
author_belongs_to_institution,
|
||||||
|
)
|
||||||
|
return author_belongs_to_institution
|
||||||
|
|
||||||
|
return True
|
||||||
|
|||||||
@@ -11,13 +11,13 @@ from sqlmodel import Session
|
|||||||
|
|
||||||
from inse import config
|
from inse import config
|
||||||
from inse.auth.model import AccessToken, Organization
|
from inse.auth.model import AccessToken, Organization
|
||||||
from inse.authors.institution_membership_query import (
|
|
||||||
build_institution_membership_query,
|
|
||||||
)
|
|
||||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||||
|
from inse.institutions.v2 import service as institutions_v2_service
|
||||||
from inse.integrations import elasticsearch
|
from inse.integrations import elasticsearch
|
||||||
from inse.model import ESCluster, ESIndex
|
from inse.model import ESCluster, ESIndex
|
||||||
from inse.patents.org.elastic_search_client import OrgPatentsSearchClient
|
from inse.patents.org.elastic_search_client import OrgPatentsSearchClient
|
||||||
|
from inse.persons import service as persons_service
|
||||||
|
from inse.projects import service as projects_service
|
||||||
from inse.projects.dfg_institutions.service import (
|
from inse.projects.dfg_institutions.service import (
|
||||||
autocomplete_institutions_for_selector,
|
autocomplete_institutions_for_selector,
|
||||||
)
|
)
|
||||||
@@ -241,20 +241,26 @@ async def get_dashboard_publications(
|
|||||||
) -> DashboardStatisticValue:
|
) -> DashboardStatisticValue:
|
||||||
normalized_id = _normalize_institution_id(institution_id)
|
normalized_id = _normalize_institution_id(institution_id)
|
||||||
period = _dashboard_period(from_year, to_year)
|
period = _dashboard_period(from_year, to_year)
|
||||||
filters = []
|
institution = await institutions_v2_service.get_institution_by_id_or_raise(
|
||||||
if year_filter := _publication_year_filter(period):
|
raw_oa_institution_id=_raw_institution_id(normalized_id),
|
||||||
filters.append(year_filter)
|
source=["id", "works_count", "counts_by_year"],
|
||||||
query = _institution_works_query(normalized_id)
|
)
|
||||||
if filters:
|
if period == (None, None):
|
||||||
query = {"bool": {"must": [query], "filter": filters}}
|
value = int(institution.works_count or 0)
|
||||||
response = await elasticsearch.search(
|
else:
|
||||||
index=config.settings.openalex_works_search_index,
|
value = sum(
|
||||||
query=query,
|
int(entry.works_count or 0)
|
||||||
size=0,
|
for entry in institution.counts_by_year or []
|
||||||
track_total_hits=True,
|
if (
|
||||||
cluster=ESCluster.NES,
|
(period[0] is None or int(entry.year or 0) >= period[0])
|
||||||
|
and (period[1] is None or int(entry.year or 0) <= period[1])
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return DashboardStatisticValue(
|
||||||
|
institution_id=normalized_id,
|
||||||
|
organization_name=organization_name,
|
||||||
|
value=value,
|
||||||
)
|
)
|
||||||
return _dashboard_statistic_value(normalized_id, organization_name, response)
|
|
||||||
|
|
||||||
|
|
||||||
async def get_dashboard_persons(
|
async def get_dashboard_persons(
|
||||||
@@ -270,20 +276,25 @@ async def get_dashboard_persons(
|
|||||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||||
detail="from_year and to_year must either both be provided or both omitted.",
|
detail="from_year and to_year must either both be provided or both omitted.",
|
||||||
)
|
)
|
||||||
membership_query = build_institution_membership_query(
|
persons = await persons_service.search_persons_list(
|
||||||
|
query=None,
|
||||||
institution_id=normalized_id,
|
institution_id=normalized_id,
|
||||||
year_mode="between" if period[0] is not None else "all",
|
sort_by=None,
|
||||||
year=period[0],
|
sort_order=None,
|
||||||
year_to=period[1],
|
topic=None,
|
||||||
|
page=1,
|
||||||
|
page_size=1,
|
||||||
|
include="",
|
||||||
|
year_filter_enabled=period[0] is not None,
|
||||||
|
filter_mode="between" if period[0] is not None else None,
|
||||||
|
filter_year=period[0],
|
||||||
|
filter_year_to=period[1],
|
||||||
)
|
)
|
||||||
response = await elasticsearch.search(
|
return DashboardStatisticValue(
|
||||||
index=ESIndex.OPENALEX_AUTHORS,
|
institution_id=normalized_id,
|
||||||
query=membership_query,
|
organization_name=organization_name,
|
||||||
size=0,
|
value=int(persons.meta.count or 0) if persons.meta else 0,
|
||||||
track_total_hits=True,
|
|
||||||
cluster=ESCluster.NES,
|
|
||||||
)
|
)
|
||||||
return _dashboard_statistic_value(normalized_id, organization_name, response)
|
|
||||||
|
|
||||||
|
|
||||||
async def get_dashboard_patents(
|
async def get_dashboard_patents(
|
||||||
@@ -315,45 +326,43 @@ async def get_dashboard_eu_projects(
|
|||||||
to_year: int | None = None,
|
to_year: int | None = None,
|
||||||
) -> DashboardStatisticValue:
|
) -> DashboardStatisticValue:
|
||||||
normalized_id = _normalize_institution_id(institution_id)
|
normalized_id = _normalize_institution_id(institution_id)
|
||||||
aliases = await _institution_aliases(normalized_id, organization_name)
|
|
||||||
period = _dashboard_period(from_year, to_year)
|
period = _dashboard_period(from_year, to_year)
|
||||||
period_filter = _project_overlap_filter(
|
projects = await projects_service.search_eu_cordis_projects(
|
||||||
"startDate",
|
institutions_search_client=InstitutionsSearchClient(),
|
||||||
"endDate",
|
raw_oa_institution_id=_raw_institution_id(normalized_id),
|
||||||
_date_period(period, "iso"),
|
author_id=None,
|
||||||
)
|
author_ids=None,
|
||||||
if period_filter:
|
organization_ids=None,
|
||||||
project_ids = await _eu_project_ids_for_aliases(aliases)
|
organization_names=None,
|
||||||
value = await _count_eu_projects_in_period(project_ids, period_filter)
|
project_types=list(EuCordisProjectType),
|
||||||
return DashboardStatisticValue(
|
keywords=None,
|
||||||
institution_id=normalized_id,
|
topic_ids=None,
|
||||||
organization_name=organization_name,
|
filter_topic_ids=None,
|
||||||
value=value,
|
title=None,
|
||||||
)
|
funding_start_years=(
|
||||||
|
[str(year) for year in range(1900, period[1] + 1)]
|
||||||
response = await elasticsearch.search(
|
if period[1] is not None
|
||||||
index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
|
else None
|
||||||
body={
|
),
|
||||||
"size": 0,
|
funding_end_years=(
|
||||||
"query": _eu_organization_query(aliases),
|
[str(year) for year in range(period[0], 2101)]
|
||||||
"aggs": {
|
if period[0] is not None
|
||||||
"projects": {
|
else None
|
||||||
"cardinality": {
|
),
|
||||||
"field": "projectID",
|
countries=None,
|
||||||
}
|
framework_programmes=None,
|
||||||
}
|
funding_schemes=None,
|
||||||
},
|
statuses=None,
|
||||||
},
|
page=0,
|
||||||
cluster=ESCluster.INSE,
|
size=1,
|
||||||
|
sort_by="id",
|
||||||
|
sort_direction="asc",
|
||||||
|
fuzzy=False,
|
||||||
)
|
)
|
||||||
return DashboardStatisticValue(
|
return DashboardStatisticValue(
|
||||||
institution_id=normalized_id,
|
institution_id=normalized_id,
|
||||||
organization_name=organization_name,
|
organization_name=organization_name,
|
||||||
value=int(
|
value=projects.total,
|
||||||
response.get("aggregations", {})
|
|
||||||
.get("projects", {})
|
|
||||||
.get("value", 0)
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -368,10 +377,18 @@ async def get_dashboard_eu_project_statuses(
|
|||||||
project_ids = await _eu_project_ids_for_aliases(aliases)
|
project_ids = await _eu_project_ids_for_aliases(aliases)
|
||||||
|
|
||||||
if not project_ids:
|
if not project_ids:
|
||||||
|
total = (
|
||||||
|
await get_dashboard_eu_projects(
|
||||||
|
normalized_id,
|
||||||
|
organization_name,
|
||||||
|
from_year=from_year,
|
||||||
|
to_year=to_year,
|
||||||
|
)
|
||||||
|
).value
|
||||||
return EuProjectStatusStatistics(
|
return EuProjectStatusStatistics(
|
||||||
institution_id=normalized_id,
|
institution_id=normalized_id,
|
||||||
organization_name=organization_name,
|
organization_name=organization_name,
|
||||||
ongoing=0,
|
ongoing=total,
|
||||||
upcoming=0,
|
upcoming=0,
|
||||||
completed=0,
|
completed=0,
|
||||||
)
|
)
|
||||||
@@ -426,12 +443,26 @@ async def get_dashboard_eu_project_statuses(
|
|||||||
cluster=ESCluster.INSE,
|
cluster=ESCluster.INSE,
|
||||||
)
|
)
|
||||||
aggregations = response.get("aggregations", {})
|
aggregations = response.get("aggregations", {})
|
||||||
|
total = (
|
||||||
|
await get_dashboard_eu_projects(
|
||||||
|
normalized_id,
|
||||||
|
organization_name,
|
||||||
|
from_year=from_year,
|
||||||
|
to_year=to_year,
|
||||||
|
)
|
||||||
|
).value
|
||||||
|
ongoing, upcoming, completed = _reconcile_project_status_counts(
|
||||||
|
total,
|
||||||
|
_project_status_count(aggregations, "ongoing"),
|
||||||
|
_project_status_count(aggregations, "upcoming"),
|
||||||
|
_project_status_count(aggregations, "completed"),
|
||||||
|
)
|
||||||
return EuProjectStatusStatistics(
|
return EuProjectStatusStatistics(
|
||||||
institution_id=normalized_id,
|
institution_id=normalized_id,
|
||||||
organization_name=organization_name,
|
organization_name=organization_name,
|
||||||
ongoing=_project_status_count(aggregations, "ongoing"),
|
ongoing=ongoing,
|
||||||
upcoming=_project_status_count(aggregations, "upcoming"),
|
upcoming=upcoming,
|
||||||
completed=_project_status_count(aggregations, "completed"),
|
completed=completed,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -441,6 +472,32 @@ def _project_status_count(aggregations: dict[str, Any], status_name: str) -> int
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _reconcile_project_status_counts(
|
||||||
|
total: int,
|
||||||
|
ongoing: int,
|
||||||
|
upcoming: int,
|
||||||
|
completed: int,
|
||||||
|
) -> tuple[int, int, int]:
|
||||||
|
"""Makes status buckets add up to the authoritative project-service total."""
|
||||||
|
counts = [max(0, ongoing), max(0, upcoming), max(0, completed)]
|
||||||
|
difference = total - sum(counts)
|
||||||
|
if difference >= 0:
|
||||||
|
counts[0] += difference
|
||||||
|
return counts[0], counts[1], counts[2]
|
||||||
|
|
||||||
|
# Defensive fallback for stale/duplicated status documents: reduce buckets
|
||||||
|
# without ever returning negative values, preferring the inferred ongoing
|
||||||
|
# bucket before changing explicit upcoming/completed classifications.
|
||||||
|
excess = -difference
|
||||||
|
for index in (0, 1, 2):
|
||||||
|
reduction = min(counts[index], excess)
|
||||||
|
counts[index] -= reduction
|
||||||
|
excess -= reduction
|
||||||
|
if excess == 0:
|
||||||
|
break
|
||||||
|
return counts[0], counts[1], counts[2]
|
||||||
|
|
||||||
|
|
||||||
async def get_dashboard_bmbf_projects(
|
async def get_dashboard_bmbf_projects(
|
||||||
institution_id: str,
|
institution_id: str,
|
||||||
organization_name: str,
|
organization_name: str,
|
||||||
@@ -448,23 +505,38 @@ async def get_dashboard_bmbf_projects(
|
|||||||
to_year: int | None = None,
|
to_year: int | None = None,
|
||||||
) -> DashboardStatisticValue:
|
) -> DashboardStatisticValue:
|
||||||
normalized_id = _normalize_institution_id(institution_id)
|
normalized_id = _normalize_institution_id(institution_id)
|
||||||
aliases = await _institution_aliases(normalized_id, organization_name)
|
|
||||||
period = _dashboard_period(from_year, to_year)
|
period = _dashboard_period(from_year, to_year)
|
||||||
filters = [_alias_match_query("Zuwendungsempfänger", aliases)]
|
projects = await projects_service.search_bund_projects_with_filters(
|
||||||
if period_filter := _project_overlap_filter(
|
institutions_search_client=InstitutionsSearchClient(),
|
||||||
"funding_start",
|
executing_agency=None,
|
||||||
"funding_end",
|
raw_oa_institution_id=_raw_institution_id(normalized_id),
|
||||||
_date_period(period, "de"),
|
title=None,
|
||||||
):
|
keywords=None,
|
||||||
filters.append(period_filter)
|
funding_arts=None,
|
||||||
response = await elasticsearch.search(
|
topic_ids=None,
|
||||||
index=ESIndex.PROJECTS_BUND_V1,
|
filter_topic_ids=None,
|
||||||
query=filters[0] if len(filters) == 1 else {"bool": {"filter": filters}},
|
funding_start_years=(
|
||||||
size=0,
|
[str(year) for year in range(1900, period[1] + 1)]
|
||||||
track_total_hits=True,
|
if period[1] is not None
|
||||||
cluster=ESCluster.INSE,
|
else None
|
||||||
|
),
|
||||||
|
funding_end_years=(
|
||||||
|
[str(year) for year in range(period[0], 2101)]
|
||||||
|
if period[0] is not None
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
countries=None,
|
||||||
|
page=0,
|
||||||
|
size=1,
|
||||||
|
sort_by="id",
|
||||||
|
sort_direction="asc",
|
||||||
|
fuzzy=False,
|
||||||
|
)
|
||||||
|
return DashboardStatisticValue(
|
||||||
|
institution_id=normalized_id,
|
||||||
|
organization_name=organization_name,
|
||||||
|
value=projects.total,
|
||||||
)
|
)
|
||||||
return _dashboard_statistic_value(normalized_id, organization_name, response)
|
|
||||||
|
|
||||||
|
|
||||||
async def get_dashboard_bmbf_project_statuses(
|
async def get_dashboard_bmbf_project_statuses(
|
||||||
@@ -498,12 +570,26 @@ async def get_dashboard_bmbf_project_statuses(
|
|||||||
cluster=ESCluster.INSE,
|
cluster=ESCluster.INSE,
|
||||||
)
|
)
|
||||||
aggregations = response.get("aggregations", {})
|
aggregations = response.get("aggregations", {})
|
||||||
|
total = (
|
||||||
|
await get_dashboard_bmbf_projects(
|
||||||
|
normalized_id,
|
||||||
|
organization_name,
|
||||||
|
from_year=from_year,
|
||||||
|
to_year=to_year,
|
||||||
|
)
|
||||||
|
).value
|
||||||
|
ongoing, upcoming, completed = _reconcile_project_status_counts(
|
||||||
|
total,
|
||||||
|
int(aggregations.get("ongoing", {}).get("doc_count", 0)),
|
||||||
|
int(aggregations.get("upcoming", {}).get("doc_count", 0)),
|
||||||
|
int(aggregations.get("completed", {}).get("doc_count", 0)),
|
||||||
|
)
|
||||||
return BmbfProjectStatusStatistics(
|
return BmbfProjectStatusStatistics(
|
||||||
institution_id=normalized_id,
|
institution_id=normalized_id,
|
||||||
organization_name=organization_name,
|
organization_name=organization_name,
|
||||||
ongoing=int(aggregations.get("ongoing", {}).get("doc_count", 0)),
|
ongoing=ongoing,
|
||||||
upcoming=int(aggregations.get("upcoming", {}).get("doc_count", 0)),
|
upcoming=upcoming,
|
||||||
completed=int(aggregations.get("completed", {}).get("doc_count", 0)),
|
completed=completed,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -535,15 +621,37 @@ async def get_dashboard_dfg_projects(
|
|||||||
to_year: int | None = None,
|
to_year: int | None = None,
|
||||||
) -> DashboardStatisticValue:
|
) -> DashboardStatisticValue:
|
||||||
normalized_id = _normalize_institution_id(institution_id)
|
normalized_id = _normalize_institution_id(institution_id)
|
||||||
project_ids = await _get_dfg_project_ids_for_institution(
|
period = _dashboard_period(from_year, to_year)
|
||||||
normalized_id,
|
projects = await projects_service.get_dfg_projects(
|
||||||
from_year=from_year,
|
institutions_search_client=InstitutionsSearchClient(),
|
||||||
to_year=to_year,
|
raw_oa_institution_id=_raw_institution_id(normalized_id),
|
||||||
|
author_id=None,
|
||||||
|
author_filter_ids=None,
|
||||||
|
institution_ids=None,
|
||||||
|
keywords=None,
|
||||||
|
topic_ids=None,
|
||||||
|
filter_topic_ids=None,
|
||||||
|
title=None,
|
||||||
|
funding_start_years=(
|
||||||
|
[str(year) for year in range(1900, period[1] + 1)]
|
||||||
|
if period[1] is not None
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
funding_end_years=(
|
||||||
|
[str(year) for year in range(period[0], 2101)]
|
||||||
|
if period[0] is not None
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
page=0,
|
||||||
|
size=1,
|
||||||
|
sort_by="id",
|
||||||
|
sort_direction="asc",
|
||||||
|
fuzzy=False,
|
||||||
)
|
)
|
||||||
return DashboardStatisticValue(
|
return DashboardStatisticValue(
|
||||||
institution_id=normalized_id,
|
institution_id=normalized_id,
|
||||||
organization_name=organization_name,
|
organization_name=organization_name,
|
||||||
value=len(project_ids),
|
value=projects.total,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -559,10 +667,18 @@ async def get_dashboard_dfg_project_statuses(
|
|||||||
normalized_id,
|
normalized_id,
|
||||||
)
|
)
|
||||||
if not project_ids:
|
if not project_ids:
|
||||||
|
total = (
|
||||||
|
await get_dashboard_dfg_projects(
|
||||||
|
normalized_id,
|
||||||
|
organization_name,
|
||||||
|
from_year=from_year,
|
||||||
|
to_year=to_year,
|
||||||
|
)
|
||||||
|
).value
|
||||||
return DfgProjectStatusStatistics(
|
return DfgProjectStatusStatistics(
|
||||||
institution_id=normalized_id,
|
institution_id=normalized_id,
|
||||||
organization_name=organization_name,
|
organization_name=organization_name,
|
||||||
ongoing=0,
|
ongoing=total,
|
||||||
upcoming=0,
|
upcoming=0,
|
||||||
completed=0,
|
completed=0,
|
||||||
)
|
)
|
||||||
@@ -640,12 +756,26 @@ async def get_dashboard_dfg_project_statuses(
|
|||||||
.get("projects_nested", {})
|
.get("projects_nested", {})
|
||||||
.get("selected_projects", {})
|
.get("selected_projects", {})
|
||||||
)
|
)
|
||||||
|
total = (
|
||||||
|
await get_dashboard_dfg_projects(
|
||||||
|
normalized_id,
|
||||||
|
organization_name,
|
||||||
|
from_year=from_year,
|
||||||
|
to_year=to_year,
|
||||||
|
)
|
||||||
|
).value
|
||||||
|
ongoing, upcoming, completed = _reconcile_project_status_counts(
|
||||||
|
total,
|
||||||
|
_project_status_count(aggregations, "ongoing"),
|
||||||
|
0,
|
||||||
|
_project_status_count(aggregations, "completed"),
|
||||||
|
)
|
||||||
return DfgProjectStatusStatistics(
|
return DfgProjectStatusStatistics(
|
||||||
institution_id=normalized_id,
|
institution_id=normalized_id,
|
||||||
organization_name=organization_name,
|
organization_name=organization_name,
|
||||||
ongoing=_project_status_count(aggregations, "ongoing"),
|
ongoing=ongoing,
|
||||||
upcoming=0,
|
upcoming=upcoming,
|
||||||
completed=_project_status_count(aggregations, "completed"),
|
completed=completed,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -656,17 +786,11 @@ async def get_dashboard_dfg_topics(
|
|||||||
to_year: int | None = None,
|
to_year: int | None = None,
|
||||||
) -> DfgProjectTopics:
|
) -> DfgProjectTopics:
|
||||||
normalized_id = _normalize_institution_id(institution_id)
|
normalized_id = _normalize_institution_id(institution_id)
|
||||||
project_ids = await _get_dfg_project_ids_for_institution(
|
project_ids = await _get_dfg_project_ids_from_projects_service(
|
||||||
normalized_id,
|
normalized_id,
|
||||||
from_year=from_year,
|
from_year=from_year,
|
||||||
to_year=to_year,
|
to_year=to_year,
|
||||||
)
|
)
|
||||||
print(
|
|
||||||
"Dashboard DFG project topics "
|
|
||||||
f"for institution {normalized_id}: "
|
|
||||||
f"{len(project_ids)} project IDs={project_ids}",
|
|
||||||
flush=True,
|
|
||||||
)
|
|
||||||
topics: dict[str, dict[str, Any]] = {}
|
topics: dict[str, dict[str, Any]] = {}
|
||||||
matched_project_ids: set[str] = set()
|
matched_project_ids: set[str] = set()
|
||||||
|
|
||||||
@@ -735,6 +859,53 @@ async def get_dashboard_dfg_topics(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def _get_dfg_project_ids_from_projects_service(
|
||||||
|
institution_id: str,
|
||||||
|
from_year: int | None = None,
|
||||||
|
to_year: int | None = None,
|
||||||
|
) -> list[str]:
|
||||||
|
"""Returns every matching DFG project ID through the canonical project service."""
|
||||||
|
period = _dashboard_period(from_year, to_year)
|
||||||
|
page_size = 1000
|
||||||
|
page_number = 0
|
||||||
|
project_ids: set[str] = set()
|
||||||
|
|
||||||
|
while True:
|
||||||
|
projects = await projects_service.get_dfg_projects(
|
||||||
|
institutions_search_client=InstitutionsSearchClient(),
|
||||||
|
raw_oa_institution_id=_raw_institution_id(institution_id),
|
||||||
|
author_id=None,
|
||||||
|
author_filter_ids=None,
|
||||||
|
institution_ids=None,
|
||||||
|
keywords=None,
|
||||||
|
topic_ids=None,
|
||||||
|
filter_topic_ids=None,
|
||||||
|
title=None,
|
||||||
|
funding_start_years=(
|
||||||
|
[str(year) for year in range(1900, period[1] + 1)]
|
||||||
|
if period[1] is not None
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
funding_end_years=(
|
||||||
|
[str(year) for year in range(period[0], 2101)]
|
||||||
|
if period[0] is not None
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
page=page_number,
|
||||||
|
size=page_size,
|
||||||
|
sort_by="id",
|
||||||
|
sort_direction="asc",
|
||||||
|
fuzzy=False,
|
||||||
|
skip_enrichment=True,
|
||||||
|
)
|
||||||
|
project_ids.update(project.id for project in projects.elements if project.id)
|
||||||
|
if len(project_ids) >= projects.total or not projects.elements:
|
||||||
|
break
|
||||||
|
page_number += 1
|
||||||
|
|
||||||
|
return sorted(project_ids)
|
||||||
|
|
||||||
|
|
||||||
async def _get_dfg_project_ids_for_institution(
|
async def _get_dfg_project_ids_for_institution(
|
||||||
institution_id: str,
|
institution_id: str,
|
||||||
from_year: int | None = None,
|
from_year: int | None = None,
|
||||||
@@ -1011,7 +1182,6 @@ async def get_top_authors(
|
|||||||
from_year = datetime.now().year - 4
|
from_year = datetime.now().year - 4
|
||||||
to_year = datetime.now().year
|
to_year = datetime.now().year
|
||||||
period = _dashboard_period(from_year, to_year)
|
period = _dashboard_period(from_year, to_year)
|
||||||
aliases = await _institution_aliases(normalized_id, organization_name)
|
|
||||||
authors = await _safe_institution_authors(normalized_id)
|
authors = await _safe_institution_authors(normalized_id)
|
||||||
works = _top_work_authors(authors, period)
|
works = _top_work_authors(authors, period)
|
||||||
projects = await _safe_top_authors(
|
projects = await _safe_top_authors(
|
||||||
@@ -1025,7 +1195,12 @@ async def get_top_authors(
|
|||||||
)
|
)
|
||||||
eu_projects = await _safe_top_authors(
|
eu_projects = await _safe_top_authors(
|
||||||
"eu_projects",
|
"eu_projects",
|
||||||
_top_eu_project_publication_authors(normalized_id, aliases, authors),
|
_top_eu_project_publication_authors(
|
||||||
|
normalized_id,
|
||||||
|
authors,
|
||||||
|
from_year=period[0],
|
||||||
|
to_year=period[1],
|
||||||
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
patents = await _safe_top_authors(
|
patents = await _safe_top_authors(
|
||||||
@@ -1998,8 +2173,9 @@ async def _top_patent_authors(
|
|||||||
|
|
||||||
async def _top_eu_project_publication_authors(
|
async def _top_eu_project_publication_authors(
|
||||||
institution_id: str,
|
institution_id: str,
|
||||||
organization_names: list[str],
|
|
||||||
institution_authors: list[dict[str, Any]],
|
institution_authors: list[dict[str, Any]],
|
||||||
|
from_year: int | None = None,
|
||||||
|
to_year: int | None = None,
|
||||||
) -> list[TopAuthor]:
|
) -> list[TopAuthor]:
|
||||||
institution_author_ids = {
|
institution_author_ids = {
|
||||||
author_id
|
author_id
|
||||||
@@ -2009,17 +2185,12 @@ async def _top_eu_project_publication_authors(
|
|||||||
if not institution_author_ids:
|
if not institution_author_ids:
|
||||||
return []
|
return []
|
||||||
|
|
||||||
project_page = await get_eu_organization_project_contributions(
|
project_ids = await _get_eu_project_ids_from_projects_service(
|
||||||
organization_names=organization_names,
|
institution_id,
|
||||||
projects_filtering_properties=ProjectsFilteringProperties(
|
from_year=from_year,
|
||||||
project_type=ProjectType.EU,
|
to_year=to_year,
|
||||||
page=0,
|
|
||||||
size=10000,
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
project_ids = [project.project_id for project in project_page.elements]
|
|
||||||
|
|
||||||
if not project_ids:
|
if not project_ids:
|
||||||
return []
|
return []
|
||||||
|
|
||||||
@@ -2028,11 +2199,7 @@ async def _top_eu_project_publication_authors(
|
|||||||
body={
|
body={
|
||||||
"size": 10000,
|
"size": 10000,
|
||||||
"_source": ["projectID", "qaProcessedDoi"],
|
"_source": ["projectID", "qaProcessedDoi"],
|
||||||
"query": {
|
"query": {"terms": {"projectID": project_ids}},
|
||||||
"terms": {
|
|
||||||
"projectID": project_ids,
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
cluster=ESCluster.INSE,
|
cluster=ESCluster.INSE,
|
||||||
)
|
)
|
||||||
@@ -2066,12 +2233,83 @@ async def _top_eu_project_publication_authors(
|
|||||||
cluster=ESCluster.NES,
|
cluster=ESCluster.NES,
|
||||||
)
|
)
|
||||||
|
|
||||||
return _openalex_work_authors_by_eu_projects(
|
candidates = _openalex_work_authors_by_eu_projects(
|
||||||
works_response,
|
works_response,
|
||||||
doi_project_ids,
|
doi_project_ids,
|
||||||
institution_id,
|
institution_id,
|
||||||
institution_author_ids,
|
institution_author_ids,
|
||||||
|
limit=None,
|
||||||
)
|
)
|
||||||
|
counts = await asyncio.gather(
|
||||||
|
*(
|
||||||
|
_person_eu_project_count(
|
||||||
|
candidate.id,
|
||||||
|
from_year=from_year,
|
||||||
|
to_year=to_year,
|
||||||
|
)
|
||||||
|
for candidate in candidates
|
||||||
|
if candidate.id
|
||||||
|
)
|
||||||
|
)
|
||||||
|
ranked = [
|
||||||
|
TopAuthor(id=candidate.id, name=candidate.name, count=count)
|
||||||
|
for candidate, count in zip(candidates, counts, strict=True)
|
||||||
|
]
|
||||||
|
ranked.sort(key=lambda author: (-author.count, author.name, author.id or ""))
|
||||||
|
return ranked[:TOP_AUTHOR_LIMIT]
|
||||||
|
|
||||||
|
|
||||||
|
async def _get_eu_project_ids_from_projects_service(
|
||||||
|
institution_id: str,
|
||||||
|
from_year: int | None = None,
|
||||||
|
to_year: int | None = None,
|
||||||
|
) -> list[str]:
|
||||||
|
"""Loads all organization EU project IDs from the canonical project service."""
|
||||||
|
period = _dashboard_period(from_year, to_year)
|
||||||
|
page_size = 1000
|
||||||
|
page_number = 0
|
||||||
|
project_ids: set[str] = set()
|
||||||
|
|
||||||
|
while True:
|
||||||
|
projects = await projects_service.search_eu_cordis_projects(
|
||||||
|
institutions_search_client=InstitutionsSearchClient(),
|
||||||
|
raw_oa_institution_id=_raw_institution_id(institution_id),
|
||||||
|
author_id=None,
|
||||||
|
author_ids=None,
|
||||||
|
organization_ids=None,
|
||||||
|
organization_names=None,
|
||||||
|
project_types=list(EuCordisProjectType),
|
||||||
|
keywords=None,
|
||||||
|
topic_ids=None,
|
||||||
|
filter_topic_ids=None,
|
||||||
|
title=None,
|
||||||
|
funding_start_years=(
|
||||||
|
[str(year) for year in range(1900, period[1] + 1)]
|
||||||
|
if period[1] is not None
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
funding_end_years=(
|
||||||
|
[str(year) for year in range(period[0], 2101)]
|
||||||
|
if period[0] is not None
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
countries=None,
|
||||||
|
framework_programmes=None,
|
||||||
|
funding_schemes=None,
|
||||||
|
statuses=None,
|
||||||
|
page=page_number,
|
||||||
|
size=page_size,
|
||||||
|
sort_by="id",
|
||||||
|
sort_direction="asc",
|
||||||
|
fuzzy=False,
|
||||||
|
skip_enrichment=True,
|
||||||
|
)
|
||||||
|
project_ids.update(project.id for project in projects.elements if project.id)
|
||||||
|
if len(project_ids) >= projects.total or not projects.elements:
|
||||||
|
break
|
||||||
|
page_number += 1
|
||||||
|
|
||||||
|
return sorted(project_ids)
|
||||||
|
|
||||||
|
|
||||||
def _cordis_publication_doi_project_ids(
|
def _cordis_publication_doi_project_ids(
|
||||||
@@ -2108,6 +2346,7 @@ def _openalex_work_authors_by_eu_projects(
|
|||||||
doi_project_ids: dict[str, set[str]],
|
doi_project_ids: dict[str, set[str]],
|
||||||
institution_id: str,
|
institution_id: str,
|
||||||
institution_author_ids: set[str],
|
institution_author_ids: set[str],
|
||||||
|
limit: int | None = TOP_AUTHOR_LIMIT,
|
||||||
) -> list[TopAuthor]:
|
) -> list[TopAuthor]:
|
||||||
# Count unique CORDIS projects per author, not publications. Multiple works
|
# Count unique CORDIS projects per author, not publications. Multiple works
|
||||||
# (and therefore multiple DOIs) can belong to the same project ID.
|
# (and therefore multiple DOIs) can belong to the same project ID.
|
||||||
@@ -2143,14 +2382,58 @@ def _openalex_work_authors_by_eu_projects(
|
|||||||
key=lambda item: (-len(item[1]), author_names.get(item[0], ""), item[0]),
|
key=lambda item: (-len(item[1]), author_names.get(item[0], ""), item[0]),
|
||||||
)
|
)
|
||||||
|
|
||||||
return [
|
authors = [
|
||||||
TopAuthor(
|
TopAuthor(
|
||||||
id=_short_author_id(author_id),
|
id=_short_author_id(author_id),
|
||||||
name=author_names[author_id],
|
name=author_names[author_id],
|
||||||
count=len(project_ids),
|
count=len(project_ids),
|
||||||
)
|
)
|
||||||
for author_id, project_ids in ranked_authors[:TOP_AUTHOR_LIMIT]
|
for author_id, project_ids in ranked_authors
|
||||||
]
|
]
|
||||||
|
return authors[:limit] if limit is not None else authors
|
||||||
|
|
||||||
|
|
||||||
|
async def _person_eu_project_count(
|
||||||
|
author_id: str,
|
||||||
|
from_year: int | None = None,
|
||||||
|
to_year: int | None = None,
|
||||||
|
) -> int:
|
||||||
|
"""Uses the same author-only EU project search as the person detail page."""
|
||||||
|
period = _dashboard_period(from_year, to_year)
|
||||||
|
projects = await projects_service.search_eu_cordis_projects(
|
||||||
|
page=0,
|
||||||
|
size=1,
|
||||||
|
project_types=None,
|
||||||
|
raw_oa_institution_id=None,
|
||||||
|
institutions_search_client=None,
|
||||||
|
author_id=_short_author_id(author_id),
|
||||||
|
author_ids=None,
|
||||||
|
organization_ids=None,
|
||||||
|
organization_names=None,
|
||||||
|
keywords=None,
|
||||||
|
topic_ids=None,
|
||||||
|
filter_topic_ids=None,
|
||||||
|
title=None,
|
||||||
|
funding_start_years=(
|
||||||
|
[str(year) for year in range(1900, period[1] + 1)]
|
||||||
|
if period[1] is not None
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
funding_end_years=(
|
||||||
|
[str(year) for year in range(period[0], 2101)]
|
||||||
|
if period[0] is not None
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
countries=None,
|
||||||
|
framework_programmes=None,
|
||||||
|
funding_schemes=None,
|
||||||
|
statuses=None,
|
||||||
|
sort_by="title",
|
||||||
|
sort_direction="asc",
|
||||||
|
fuzzy=False,
|
||||||
|
skip_enrichment=True,
|
||||||
|
)
|
||||||
|
return projects.total
|
||||||
|
|
||||||
|
|
||||||
def _normalize_author_id(value: Any) -> str | None:
|
def _normalize_author_id(value: Any) -> str | None:
|
||||||
|
|||||||
@@ -10,14 +10,32 @@ from inse import config
|
|||||||
from inse.auth.model import AccessToken, Organization, UserRole
|
from inse.auth.model import AccessToken, Organization, UserRole
|
||||||
from inse.dashboard.service import (
|
from inse.dashboard.service import (
|
||||||
_openalex_work_authors_by_eu_projects,
|
_openalex_work_authors_by_eu_projects,
|
||||||
|
_get_dfg_project_ids_from_projects_service,
|
||||||
|
_reconcile_project_status_counts,
|
||||||
|
get_dashboard_bmbf_projects,
|
||||||
|
get_dashboard_dfg_projects,
|
||||||
|
get_dashboard_eu_projects,
|
||||||
get_dashboard_organization,
|
get_dashboard_organization,
|
||||||
|
get_dashboard_persons,
|
||||||
|
get_dashboard_publications,
|
||||||
get_dashboard_statistics,
|
get_dashboard_statistics,
|
||||||
get_top_authors,
|
get_top_authors,
|
||||||
get_topic_heatmap,
|
get_topic_heatmap,
|
||||||
get_topic_word_cloud,
|
get_topic_word_cloud,
|
||||||
)
|
)
|
||||||
from inse.model import ESCluster, ESIndex
|
from inse.model import ESCluster, ESIndex
|
||||||
|
from inse.models.openalex.author_counts_by_year_inner import AuthorCountsByYearInner
|
||||||
from inse.models.openalex.institution import Institution
|
from inse.models.openalex.institution import Institution
|
||||||
|
from inse.models.openalex.meta import Meta
|
||||||
|
from inse.persons.model import CustomAuthorsListResponse
|
||||||
|
from inse.projects.model import (
|
||||||
|
BundProjectPage,
|
||||||
|
DfgProjectPage,
|
||||||
|
DfgProjectSummary,
|
||||||
|
EuCordisProjectSearchPage,
|
||||||
|
EuCordisProjectSummary,
|
||||||
|
EuCordisProjectType,
|
||||||
|
)
|
||||||
|
|
||||||
ORG_INSTITUTION_ID = "https://openalex.org/I123"
|
ORG_INSTITUTION_ID = "https://openalex.org/I123"
|
||||||
|
|
||||||
@@ -27,6 +45,47 @@ def anyio_backend():
|
|||||||
return "asyncio"
|
return "asyncio"
|
||||||
|
|
||||||
|
|
||||||
|
def test_project_status_counts_match_authoritative_total():
|
||||||
|
assert _reconcile_project_status_counts(12, 4, 1, 5) == (6, 1, 5)
|
||||||
|
assert _reconcile_project_status_counts(7, 4, 2, 3) == (2, 2, 3)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_dfg_topic_project_ids_use_paginated_projects_service():
|
||||||
|
pages = [
|
||||||
|
DfgProjectPage(
|
||||||
|
elements=[DfgProjectSummary(id="101"), DfgProjectSummary(id="102")],
|
||||||
|
total=3,
|
||||||
|
page=0,
|
||||||
|
size=1000,
|
||||||
|
),
|
||||||
|
DfgProjectPage(
|
||||||
|
elements=[DfgProjectSummary(id="103")],
|
||||||
|
total=3,
|
||||||
|
page=1,
|
||||||
|
size=1000,
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"inse.dashboard.service.projects_service.get_dfg_projects",
|
||||||
|
new=AsyncMock(side_effect=pages),
|
||||||
|
) as mocked_get_projects:
|
||||||
|
project_ids = await _get_dfg_project_ids_from_projects_service(
|
||||||
|
ORG_INSTITUTION_ID,
|
||||||
|
from_year=2020,
|
||||||
|
to_year=2022,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert project_ids == ["101", "102", "103"]
|
||||||
|
assert mocked_get_projects.await_count == 2
|
||||||
|
first_call = mocked_get_projects.await_args_list[0]
|
||||||
|
assert first_call.kwargs["raw_oa_institution_id"] == "I123"
|
||||||
|
assert first_call.kwargs["skip_enrichment"] is True
|
||||||
|
assert first_call.kwargs["funding_start_years"][-1] == "2022"
|
||||||
|
assert first_call.kwargs["funding_end_years"][0] == "2020"
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
||||||
async def search(**kwargs):
|
async def search(**kwargs):
|
||||||
@@ -84,6 +143,33 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
|||||||
display_name_alternatives=["Example Universität"],
|
display_name_alternatives=["Example Universität"],
|
||||||
)
|
)
|
||||||
),
|
),
|
||||||
|
), patch(
|
||||||
|
"inse.dashboard.service.projects_service.get_dfg_projects",
|
||||||
|
new=AsyncMock(
|
||||||
|
return_value=DfgProjectPage(elements=[], total=3, page=0, size=1)
|
||||||
|
),
|
||||||
|
), patch(
|
||||||
|
"inse.dashboard.service.projects_service.search_eu_cordis_projects",
|
||||||
|
new=AsyncMock(
|
||||||
|
return_value=EuCordisProjectSearchPage(
|
||||||
|
elements=[], total=10, page=0, size=1
|
||||||
|
)
|
||||||
|
),
|
||||||
|
), patch(
|
||||||
|
"inse.dashboard.service.projects_service.search_bund_projects_with_filters",
|
||||||
|
new=AsyncMock(
|
||||||
|
return_value=BundProjectPage(elements=[], total=5, page=0, size=1)
|
||||||
|
),
|
||||||
|
), patch(
|
||||||
|
"inse.dashboard.service.persons_service.search_persons_list",
|
||||||
|
new=AsyncMock(
|
||||||
|
return_value=CustomAuthorsListResponse(
|
||||||
|
results=[], meta=Meta(count=35, page=1, per_page=1)
|
||||||
|
)
|
||||||
|
),
|
||||||
|
), patch(
|
||||||
|
"inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise",
|
||||||
|
new=AsyncMock(return_value=Institution(id=ORG_INSTITUTION_ID, works_count=120)),
|
||||||
):
|
):
|
||||||
result = await get_dashboard_statistics(
|
result = await get_dashboard_statistics(
|
||||||
ORG_INSTITUTION_ID,
|
ORG_INSTITUTION_ID,
|
||||||
@@ -101,64 +187,144 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
|||||||
"bmbf_projects": 5,
|
"bmbf_projects": 5,
|
||||||
}
|
}
|
||||||
|
|
||||||
publication_call = next(
|
@pytest.mark.anyio
|
||||||
call
|
async def test_dashboard_publications_uses_institutions_v2_counts():
|
||||||
for call in mocked_search.await_args_list
|
institution = Institution(
|
||||||
if call.kwargs["index"] == config.settings.openalex_works_search_index
|
id=ORG_INSTITUTION_ID,
|
||||||
|
works_count=250,
|
||||||
|
counts_by_year=[
|
||||||
|
AuthorCountsByYearInner(year=2021, works_count=10),
|
||||||
|
AuthorCountsByYearInner(year=2022, works_count=12),
|
||||||
|
AuthorCountsByYearInner(year=2023, works_count=14),
|
||||||
|
],
|
||||||
)
|
)
|
||||||
assert publication_call.kwargs["query"]["nested"]["query"]["term"] == {
|
|
||||||
"authorships.institutions.id": ORG_INSTITUTION_ID
|
with patch(
|
||||||
|
"inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise",
|
||||||
|
new=AsyncMock(return_value=institution),
|
||||||
|
) as mocked_get_institution:
|
||||||
|
all_time = await get_dashboard_publications(
|
||||||
|
ORG_INSTITUTION_ID,
|
||||||
|
"Example Org",
|
||||||
|
)
|
||||||
|
selected_period = await get_dashboard_publications(
|
||||||
|
ORG_INSTITUTION_ID,
|
||||||
|
"Example Org",
|
||||||
|
from_year=2021,
|
||||||
|
to_year=2022,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert all_time.value == 250
|
||||||
|
assert selected_period.value == 22
|
||||||
|
assert mocked_get_institution.await_args_list[0].kwargs == {
|
||||||
|
"raw_oa_institution_id": "I123",
|
||||||
|
"source": ["id", "works_count", "counts_by_year"],
|
||||||
}
|
}
|
||||||
|
|
||||||
person_call = next(
|
|
||||||
call
|
|
||||||
for call in mocked_search.await_args_list
|
|
||||||
if call.kwargs["index"] == ESIndex.OPENALEX_AUTHORS
|
|
||||||
)
|
|
||||||
person_query = person_call.kwargs["query"]
|
|
||||||
affiliation = person_query["bool"]["should"][0]["bool"]["filter"][1]
|
|
||||||
|
|
||||||
assert affiliation["nested"]["path"] == "affiliations"
|
@pytest.mark.anyio
|
||||||
assert affiliation["nested"]["query"]["bool"]["filter"][0] == {
|
async def test_dashboard_persons_uses_persons_service_for_organization():
|
||||||
"term": {"affiliations.institution.id": ORG_INSTITUTION_ID}
|
response = CustomAuthorsListResponse(
|
||||||
}
|
results=[], meta=Meta(count=64, page=1, per_page=1)
|
||||||
eu_call = next(
|
|
||||||
call
|
|
||||||
for call in mocked_search.await_args_list
|
|
||||||
if call.kwargs["index"] == ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD
|
|
||||||
)
|
)
|
||||||
assert eu_call.kwargs["cluster"] == ESCluster.INSE
|
|
||||||
assert eu_call.kwargs["body"]["query"] == {
|
|
||||||
"terms": {
|
|
||||||
"name.keyword": [
|
|
||||||
"EXAMPLE ORG",
|
|
||||||
"EXAMPLE UNI",
|
|
||||||
"EXAMPLE UNIVERSITY",
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bund_call = next(
|
with patch(
|
||||||
call
|
"inse.dashboard.service.persons_service.search_persons_list",
|
||||||
for call in mocked_search.await_args_list
|
new=AsyncMock(return_value=response),
|
||||||
if call.kwargs["index"] == ESIndex.PROJECTS_BUND_V1
|
) as mocked_search_persons:
|
||||||
|
result = await get_dashboard_persons(
|
||||||
|
ORG_INSTITUTION_ID,
|
||||||
|
"Example Org",
|
||||||
|
from_year=2020,
|
||||||
|
to_year=2023,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result.value == 64
|
||||||
|
call = mocked_search_persons.await_args
|
||||||
|
assert call.kwargs["institution_id"] == ORG_INSTITUTION_ID
|
||||||
|
assert call.kwargs["filter_mode"] == "between"
|
||||||
|
assert call.kwargs["filter_year"] == 2020
|
||||||
|
assert call.kwargs["filter_year_to"] == 2023
|
||||||
|
assert call.kwargs["page"] == 1
|
||||||
|
assert call.kwargs["page_size"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_dashboard_dfg_projects_uses_projects_service_total():
|
||||||
|
project_page = DfgProjectPage(elements=[], total=42, page=0, size=1)
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"inse.dashboard.service.projects_service.get_dfg_projects",
|
||||||
|
new=AsyncMock(return_value=project_page),
|
||||||
|
) as mocked_get_projects:
|
||||||
|
result = await get_dashboard_dfg_projects(
|
||||||
|
ORG_INSTITUTION_ID,
|
||||||
|
"Example Org",
|
||||||
|
from_year=2020,
|
||||||
|
to_year=2022,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result.value == 42
|
||||||
|
mocked_get_projects.assert_awaited_once()
|
||||||
|
call = mocked_get_projects.await_args
|
||||||
|
assert call.kwargs["raw_oa_institution_id"] == "I123"
|
||||||
|
assert call.kwargs["funding_start_years"][-1] == "2022"
|
||||||
|
assert call.kwargs["funding_end_years"][0] == "2020"
|
||||||
|
assert call.kwargs["page"] == 0
|
||||||
|
assert call.kwargs["size"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_dashboard_bmbf_projects_uses_projects_service_total():
|
||||||
|
project_page = BundProjectPage(elements=[], total=29, page=0, size=1)
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"inse.dashboard.service.projects_service.search_bund_projects_with_filters",
|
||||||
|
new=AsyncMock(return_value=project_page),
|
||||||
|
) as mocked_get_projects:
|
||||||
|
result = await get_dashboard_bmbf_projects(
|
||||||
|
ORG_INSTITUTION_ID,
|
||||||
|
"Example Org",
|
||||||
|
from_year=2018,
|
||||||
|
to_year=2020,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result.value == 29
|
||||||
|
mocked_get_projects.assert_awaited_once()
|
||||||
|
call = mocked_get_projects.await_args
|
||||||
|
assert call.kwargs["raw_oa_institution_id"] == "I123"
|
||||||
|
assert call.kwargs["funding_start_years"][-1] == "2020"
|
||||||
|
assert call.kwargs["funding_end_years"][0] == "2018"
|
||||||
|
assert call.kwargs["page"] == 0
|
||||||
|
assert call.kwargs["size"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_dashboard_eu_projects_uses_projects_service_total():
|
||||||
|
project_page = EuCordisProjectSearchPage(
|
||||||
|
elements=[], total=37, page=0, size=1
|
||||||
)
|
)
|
||||||
assert bund_call.kwargs["cluster"] == ESCluster.INSE
|
|
||||||
assert bund_call.kwargs["query"]["bool"]["minimum_should_match"] == 1
|
|
||||||
assert bund_call.kwargs["query"]["bool"]["should"][0]["match"] == {
|
|
||||||
"Zuwendungsempfänger": {
|
|
||||||
"query": "Example Org",
|
|
||||||
"operator": "and",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
dfg_calls = [
|
with patch(
|
||||||
call
|
"inse.dashboard.service.projects_service.search_eu_cordis_projects",
|
||||||
for call in mocked_search.await_args_list
|
new=AsyncMock(return_value=project_page),
|
||||||
if call.kwargs["index"] == ESIndex.DFG_INSTITUTES_V2
|
) as mocked_get_projects:
|
||||||
]
|
result = await get_dashboard_eu_projects(
|
||||||
assert len(dfg_calls) == 2
|
ORG_INSTITUTION_ID,
|
||||||
assert all(call.kwargs["cluster"] == ESCluster.INSE for call in dfg_calls)
|
"Example Org",
|
||||||
|
from_year=2019,
|
||||||
|
to_year=2021,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result.value == 37
|
||||||
|
mocked_get_projects.assert_awaited_once()
|
||||||
|
call = mocked_get_projects.await_args
|
||||||
|
assert call.kwargs["raw_oa_institution_id"] == "I123"
|
||||||
|
assert call.kwargs["funding_start_years"][-1] == "2021"
|
||||||
|
assert call.kwargs["funding_end_years"][0] == "2019"
|
||||||
|
assert call.kwargs["project_types"] == list(EuCordisProjectType)
|
||||||
|
assert call.kwargs["page"] == 0
|
||||||
|
assert call.kwargs["size"] == 1
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
@@ -272,6 +438,25 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
|
|||||||
|
|
||||||
return {"aggregations": {"people": {"buckets": []}}}
|
return {"aggregations": {"people": {"buckets": []}}}
|
||||||
|
|
||||||
|
async def eu_projects(**kwargs):
|
||||||
|
if kwargs.get("raw_oa_institution_id"):
|
||||||
|
return EuCordisProjectSearchPage(
|
||||||
|
elements=[
|
||||||
|
EuCordisProjectSummary(id="P1", project_type=EuCordisProjectType.FP7),
|
||||||
|
EuCordisProjectSummary(id="P2", project_type=EuCordisProjectType.H2020),
|
||||||
|
EuCordisProjectSummary(id="P3", project_type=EuCordisProjectType.HEU),
|
||||||
|
],
|
||||||
|
total=3,
|
||||||
|
page=0,
|
||||||
|
size=1000,
|
||||||
|
)
|
||||||
|
return EuCordisProjectSearchPage(
|
||||||
|
elements=[],
|
||||||
|
total={"A1": 3, "A2": 4}[kwargs["author_id"]],
|
||||||
|
page=0,
|
||||||
|
size=1,
|
||||||
|
)
|
||||||
|
|
||||||
with patch(
|
with patch(
|
||||||
"inse.dashboard.service.elasticsearch.search",
|
"inse.dashboard.service.elasticsearch.search",
|
||||||
new=AsyncMock(side_effect=search),
|
new=AsyncMock(side_effect=search),
|
||||||
@@ -279,16 +464,8 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
|
|||||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||||
new=AsyncMock(return_value=["Example University"]),
|
new=AsyncMock(return_value=["Example University"]),
|
||||||
), patch(
|
), patch(
|
||||||
"inse.dashboard.service.get_eu_organization_project_contributions",
|
"inse.dashboard.service.projects_service.search_eu_cordis_projects",
|
||||||
new=AsyncMock(
|
new=AsyncMock(side_effect=eu_projects),
|
||||||
return_value=SimpleNamespace(
|
|
||||||
elements=[
|
|
||||||
SimpleNamespace(project_id="P1"),
|
|
||||||
SimpleNamespace(project_id="P2"),
|
|
||||||
SimpleNamespace(project_id="P3"),
|
|
||||||
],
|
|
||||||
)
|
|
||||||
),
|
|
||||||
), patch(
|
), patch(
|
||||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||||
new=AsyncMock(
|
new=AsyncMock(
|
||||||
@@ -313,8 +490,8 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
|
|||||||
"count": 4,
|
"count": 4,
|
||||||
}
|
}
|
||||||
assert [author.model_dump() for author in result.eu_projects] == [
|
assert [author.model_dump() for author in result.eu_projects] == [
|
||||||
{"id": "A2", "name": "Grace Example", "count": 2},
|
{"id": "A2", "name": "Grace Example", "count": 4},
|
||||||
{"id": "A1", "name": "Ada Example", "count": 1},
|
{"id": "A1", "name": "Ada Example", "count": 3},
|
||||||
]
|
]
|
||||||
assert result.news[0].model_dump() == {
|
assert result.news[0].model_dump() == {
|
||||||
"id": "A1",
|
"id": "A1",
|
||||||
@@ -573,6 +750,24 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i
|
|||||||
}
|
}
|
||||||
return {"aggregations": {"authors": {"buckets": []}}}
|
return {"aggregations": {"authors": {"buckets": []}}}
|
||||||
|
|
||||||
|
async def eu_projects(**kwargs):
|
||||||
|
if kwargs.get("raw_oa_institution_id"):
|
||||||
|
return EuCordisProjectSearchPage(
|
||||||
|
elements=[
|
||||||
|
EuCordisProjectSummary(id="P1", project_type=EuCordisProjectType.FP7),
|
||||||
|
EuCordisProjectSummary(id="P2", project_type=EuCordisProjectType.H2020),
|
||||||
|
],
|
||||||
|
total=2,
|
||||||
|
page=0,
|
||||||
|
size=1000,
|
||||||
|
)
|
||||||
|
return EuCordisProjectSearchPage(
|
||||||
|
elements=[],
|
||||||
|
total={"A1": 4, "A2": 1}[kwargs["author_id"]],
|
||||||
|
page=0,
|
||||||
|
size=1,
|
||||||
|
)
|
||||||
|
|
||||||
with patch(
|
with patch(
|
||||||
"inse.dashboard.service.elasticsearch.search",
|
"inse.dashboard.service.elasticsearch.search",
|
||||||
new=AsyncMock(side_effect=search),
|
new=AsyncMock(side_effect=search),
|
||||||
@@ -580,15 +775,8 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i
|
|||||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||||
new=AsyncMock(return_value=["Example University"]),
|
new=AsyncMock(return_value=["Example University"]),
|
||||||
), patch(
|
), patch(
|
||||||
"inse.dashboard.service.get_eu_organization_project_contributions",
|
"inse.dashboard.service.projects_service.search_eu_cordis_projects",
|
||||||
new=AsyncMock(
|
new=AsyncMock(side_effect=eu_projects),
|
||||||
return_value=SimpleNamespace(
|
|
||||||
elements=[
|
|
||||||
SimpleNamespace(project_id="P1"),
|
|
||||||
SimpleNamespace(project_id="P2"),
|
|
||||||
],
|
|
||||||
)
|
|
||||||
),
|
|
||||||
), patch(
|
), patch(
|
||||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||||
new=AsyncMock(return_value=[]),
|
new=AsyncMock(return_value=[]),
|
||||||
@@ -599,7 +787,7 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i
|
|||||||
)
|
)
|
||||||
|
|
||||||
assert [author.model_dump() for author in result.eu_projects] == [
|
assert [author.model_dump() for author in result.eu_projects] == [
|
||||||
{"id": "A1", "name": "Ada Example", "count": 2},
|
{"id": "A1", "name": "Ada Example", "count": 4},
|
||||||
{"id": "A2", "name": "Grace Example", "count": 1},
|
{"id": "A2", "name": "Grace Example", "count": 1},
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@@ -361,6 +361,7 @@ class InstitutionsSearchClient:
|
|||||||
"government",
|
"government",
|
||||||
"facility",
|
"facility",
|
||||||
"other",
|
"other",
|
||||||
|
"funder",
|
||||||
}
|
}
|
||||||
|
|
||||||
cleaned_source = {}
|
cleaned_source = {}
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ _VALID_INSTITUTION_TYPES = {
|
|||||||
"government",
|
"government",
|
||||||
"facility",
|
"facility",
|
||||||
"other",
|
"other",
|
||||||
|
"funder",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -174,3 +174,34 @@ async def test_list_institutions_accepts_practical_openalex_type_variants():
|
|||||||
assert result.results[0].counts_by_year[0].cited_by_count is None
|
assert result.results[0].counts_by_year[0].cited_by_count is None
|
||||||
assert result.group_by[0].key == "true"
|
assert result.group_by[0].key == "true"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_list_institutions_accepts_funder_institution_type():
|
||||||
|
def handler(_: httpx.Request) -> httpx.Response:
|
||||||
|
return httpx.Response(
|
||||||
|
200,
|
||||||
|
json={
|
||||||
|
"meta": {"count": 1, "page": 1, "per_page": 25},
|
||||||
|
"results": [
|
||||||
|
{
|
||||||
|
"id": "https://openalex.org/I4210119759",
|
||||||
|
"display_name": "Essen University Hospital",
|
||||||
|
"country_code": "DE",
|
||||||
|
"type": "funder",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
client = OpenAlexInstitutionsClient(
|
||||||
|
api_key="test-key",
|
||||||
|
transport=httpx.MockTransport(handler),
|
||||||
|
)
|
||||||
|
|
||||||
|
result = await logic.list_institutions(client=client)
|
||||||
|
|
||||||
|
assert result.results[0].id == "https://openalex.org/I4210119759"
|
||||||
|
assert result.results[0].display_name == "Essen University Hospital"
|
||||||
|
assert result.results[0].type == "funder"
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -142,15 +142,50 @@ async def autocomplete_institutions(
|
|||||||
if not query:
|
if not query:
|
||||||
return InstitutionPageV2(elements=[], total=0, page=0, size=0)
|
return InstitutionPageV2(elements=[], total=0, page=0, size=0)
|
||||||
|
|
||||||
|
stripped = query.strip()
|
||||||
|
fields = [("display_name", 1.0), ("display_name_alternatives", 0.8)]
|
||||||
|
should_clauses = []
|
||||||
|
for field, weight in fields:
|
||||||
|
should_clauses.extend([
|
||||||
|
{
|
||||||
|
"prefix": {
|
||||||
|
f"{field}.keyword": {
|
||||||
|
"value": stripped,
|
||||||
|
"case_insensitive": True,
|
||||||
|
"boost": 10.0 * weight,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{"match_phrase_prefix": {field: {"query": stripped, "boost": 5.0 * weight, "slop": 3}}},
|
||||||
|
{"match_bool_prefix": {field: {"query": stripped, "boost": 2.0 * weight}}},
|
||||||
|
{
|
||||||
|
"constant_score": {
|
||||||
|
"filter": {
|
||||||
|
"wildcard": {
|
||||||
|
f"{field}.keyword": {
|
||||||
|
"value": f"*{stripped}*",
|
||||||
|
"case_insensitive": True,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"boost": 1.0 * weight,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
])
|
||||||
|
|
||||||
return await search_institutions(
|
return await search_institutions(
|
||||||
page=page,
|
page=page,
|
||||||
size=size,
|
size=size,
|
||||||
query={
|
query={
|
||||||
"bool": {
|
"function_score": {
|
||||||
"should": [
|
"query": {"bool": {"should": should_clauses, "minimum_should_match": 1}},
|
||||||
{"match_phrase_prefix": {"display_name": query}},
|
"field_value_factor": {
|
||||||
{"match_phrase_prefix": {"display_name_alternatives": query}},
|
"field": "works_count",
|
||||||
]
|
"modifier": "log1p",
|
||||||
|
"factor": 0.05,
|
||||||
|
"missing": 1.0,
|
||||||
|
},
|
||||||
|
"boost_mode": "multiply",
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
source=source,
|
source=source,
|
||||||
|
|||||||
@@ -96,6 +96,7 @@ def _index_to_cluster(index: ESIndex) -> ESCluster | None:
|
|||||||
ESIndex.OPENALEX_INSTITUTIONS,
|
ESIndex.OPENALEX_INSTITUTIONS,
|
||||||
ESIndex.OPENALEX_PUBLICATIONS,
|
ESIndex.OPENALEX_PUBLICATIONS,
|
||||||
ESIndex.WORK_CLASSIFICATIONS,
|
ESIndex.WORK_CLASSIFICATIONS,
|
||||||
|
ESIndex.CC_NEWS_WILDCARD,
|
||||||
}:
|
}:
|
||||||
return ESCluster.NES
|
return ESCluster.NES
|
||||||
elif index in {
|
elif index in {
|
||||||
@@ -260,11 +261,10 @@ async def search(
|
|||||||
payload["sort"] = sort
|
payload["sort"] = sort
|
||||||
if aggs is not None:
|
if aggs is not None:
|
||||||
payload["aggs"] = aggs
|
payload["aggs"] = aggs
|
||||||
if track_total_hits:
|
|
||||||
payload["track_total_hits"] = True
|
|
||||||
if highlight is not None:
|
if highlight is not None:
|
||||||
payload["highlight"] = highlight
|
payload["highlight"] = highlight
|
||||||
|
|
||||||
|
payload["track_total_hits"] = True # always track total hits for accurate pagination and counts
|
||||||
if len(payload) == 0:
|
if len(payload) == 0:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"At least one of 'query', 'body', 'source', 'size', 'offset', 'sort', 'aggs' must be provided"
|
"At least one of 'query', 'body', 'source', 'size', 'offset', 'sort', 'aggs' must be provided"
|
||||||
@@ -439,12 +439,16 @@ async def count(
|
|||||||
async def msearch(
|
async def msearch(
|
||||||
searches: list[tuple[ESIndex | str | list[str], dict[str, Any]]],
|
searches: list[tuple[ESIndex | str | list[str], dict[str, Any]]],
|
||||||
cluster: ESCluster = ESCluster.NES,
|
cluster: ESCluster = ESCluster.NES,
|
||||||
|
request_cache: bool = False,
|
||||||
) -> list[dict[str, Any]]:
|
) -> list[dict[str, Any]]:
|
||||||
"""Performs a multi-search request (_msearch) on Elasticsearch.
|
"""Performs a multi-search request (_msearch) on Elasticsearch.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
searches: A list of tuples, each containing (index, payload_dict).
|
searches: A list of tuples, each containing (index, payload_dict).
|
||||||
cluster: The Elasticsearch cluster to execute searches on.
|
cluster: The Elasticsearch cluster to execute searches on.
|
||||||
|
request_cache: Whether to enable the shard request cache for each search.
|
||||||
|
Elasticsearch rejects `request_cache` as an _msearch URL parameter, so
|
||||||
|
it goes into the per-search header line instead.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
List[Dict[str, Any]]: List of response dictionaries for each search in order.
|
List[Dict[str, Any]]: List of response dictionaries for each search in order.
|
||||||
@@ -464,7 +468,9 @@ async def msearch(
|
|||||||
idx_str = ",".join(str(i) for i in idx)
|
idx_str = ",".join(str(i) for i in idx)
|
||||||
else:
|
else:
|
||||||
idx_str = str(idx)
|
idx_str = str(idx)
|
||||||
header_obj = {"index": idx_str}
|
header_obj: dict[str, Any] = {"index": idx_str}
|
||||||
|
if request_cache:
|
||||||
|
header_obj["request_cache"] = True
|
||||||
lines.append(json.dumps(header_obj))
|
lines.append(json.dumps(header_obj))
|
||||||
lines.append(json.dumps(body))
|
lines.append(json.dumps(body))
|
||||||
|
|
||||||
|
|||||||
@@ -52,6 +52,9 @@ class ESIndex(StrEnum):
|
|||||||
OPENALEX_CONTINENTS = "openalex-continents"
|
OPENALEX_CONTINENTS = "openalex-continents"
|
||||||
OPENALEX_TOPICS = "openalex-topics"
|
OPENALEX_TOPICS = "openalex-topics"
|
||||||
OPENALEX_TOPIC_VECTORS = "topicvectors"
|
OPENALEX_TOPIC_VECTORS = "topicvectors"
|
||||||
|
OPENALEX_DOMAINS = "openalex-domains"
|
||||||
|
OPENALEX_FIELDS = "openalex-fields"
|
||||||
|
OPENALEX_SUBFIELDS = "openalex-subfields"
|
||||||
|
|
||||||
EPO_INDEX = "epo_index_1.0"
|
EPO_INDEX = "epo_index_1.0"
|
||||||
USPTO_INDEX = "uspto_patents_3.0"
|
USPTO_INDEX = "uspto_patents_3.0"
|
||||||
@@ -65,6 +68,7 @@ class ESIndex(StrEnum):
|
|||||||
AKTUELLES = "aktuell"
|
AKTUELLES = "aktuell"
|
||||||
AKTUELLES_POSTPROC = "aktuell_postproc"
|
AKTUELLES_POSTPROC = "aktuell_postproc"
|
||||||
AKTUELLES_OPENALEX_TOPICS = "aktuell_openalex_topics"
|
AKTUELLES_OPENALEX_TOPICS = "aktuell_openalex_topics"
|
||||||
|
CC_NEWS_WILDCARD = "cc-news-*"
|
||||||
|
|
||||||
|
|
||||||
CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
|
CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
|
||||||
|
|||||||
@@ -170,25 +170,6 @@ class DfgProjectPublicationSummary(BaseModel):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class DfgProjectSubjectArea(BaseModel):
|
|
||||||
"""A single subject-area classification entry (DFG 'Fachsystematik')."""
|
|
||||||
|
|
||||||
model_config = ConfigDict(populate_by_name=True)
|
|
||||||
|
|
||||||
fach: str | None = None
|
|
||||||
fachgebiet: str | None = None
|
|
||||||
fachkollegium: str | None = None
|
|
||||||
wissenschaftsbereich: str | None = None
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def from_inner(cls, f: DFGProjectFachgebieteInner) -> "DfgProjectSubjectArea":
|
|
||||||
return cls(
|
|
||||||
fach=f.fach,
|
|
||||||
fachgebiet=f.fachgebiet,
|
|
||||||
fachkollegium=f.fachkollegium,
|
|
||||||
wissenschaftsbereich=f.wissenschaftsbereich,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class DfgProjectDetails(BaseModel):
|
class DfgProjectDetails(BaseModel):
|
||||||
"""
|
"""
|
||||||
@@ -253,7 +234,7 @@ class DfgProjectDetails(BaseModel):
|
|||||||
|
|
||||||
subject_area_de: str | None = Field(default=None, description="Subject area, summary text (German)")
|
subject_area_de: str | None = Field(default=None, description="Subject area, summary text (German)")
|
||||||
subject_area_en: str | None = Field(default=None, description="Subject area, summary text (English)")
|
subject_area_en: str | None = Field(default=None, description="Subject area, summary text (English)")
|
||||||
subject_classifications: list[DfgProjectSubjectArea] = Field(
|
subject_classifications: list[DFGProjectFachgebieteInner] = Field(
|
||||||
default_factory=list,
|
default_factory=list,
|
||||||
description="Detailed DFG subject-area classification entries (Fachsystematik)",
|
description="Detailed DFG subject-area classification entries (Fachsystematik)",
|
||||||
)
|
)
|
||||||
@@ -319,7 +300,7 @@ class DfgProjectDetails(BaseModel):
|
|||||||
DfgProjectPublicationSummary.from_inner(p) for p in (project.publications or [])
|
DfgProjectPublicationSummary.from_inner(p) for p in (project.publications or [])
|
||||||
]
|
]
|
||||||
subject_classifications = [
|
subject_classifications = [
|
||||||
DfgProjectSubjectArea.from_inner(f) for f in (project.fachgebiete or [])
|
DFGProjectFachgebieteInner.from_dict(f) for f in (project.subject_classifications or [])
|
||||||
]
|
]
|
||||||
|
|
||||||
# De-duplicated flat views, order-preserving
|
# De-duplicated flat views, order-preserving
|
||||||
@@ -383,8 +364,6 @@ class DfgProjectDetails(BaseModel):
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_dict(cls, obj: dict) -> "DfgProjectDetails":
|
def from_dict(cls, obj: dict) -> "DfgProjectDetails":
|
||||||
"""Convenience constructor from a raw dict (e.g. a JSON API response body)."""
|
|
||||||
obj = cls._sanitize_raw_project_dict(obj)
|
|
||||||
return cls.from_dfg_project(DFGProject.from_dict(obj))
|
return cls.from_dfg_project(DFGProject.from_dict(obj))
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ class Institution(BaseModel):
|
|||||||
ror: StrictStr | None = Field(default=None, description="The ROR ID for this institution. This is the Canonical External ID for institutions.")
|
ror: StrictStr | None = Field(default=None, description="The ROR ID for this institution. This is the Canonical External ID for institutions.")
|
||||||
display_name: StrictStr | None = Field(default=None, description="The primary name of the institution.")
|
display_name: StrictStr | None = Field(default=None, description="The primary name of the institution.")
|
||||||
country_code: StrictStr | None = Field(default=None, description="ISO two-letter country code where this institution is located.")
|
country_code: StrictStr | None = Field(default=None, description="ISO two-letter country code where this institution is located.")
|
||||||
type: StrictStr | None = Field(default=None, description="The institution's primary type (ROR vocabulary): `Education`, `Healthcare`, `Company`, `Archive`, `Nonprofit`, `Government`, `Facility`, `Other`.")
|
type: StrictStr | None = Field(default=None, description="The institution's primary type (ROR vocabulary): `Education`, `Healthcare`, `Company`, `Archive`, `Nonprofit`, `Government`, `Facility`, `Other`, `Funder`.")
|
||||||
homepage_url: StrictStr | None = Field(default=None, description="URL for the institution's primary homepage.")
|
homepage_url: StrictStr | None = Field(default=None, description="URL for the institution's primary homepage.")
|
||||||
image_url: StrictStr | None = Field(default=None, description="URL for an image representing this institution (usually from Wikimedia).")
|
image_url: StrictStr | None = Field(default=None, description="URL for an image representing this institution (usually from Wikimedia).")
|
||||||
image_thumbnail_url: StrictStr | None = Field(default=None, description="Smaller version of `image_url`.")
|
image_thumbnail_url: StrictStr | None = Field(default=None, description="Smaller version of `image_url`.")
|
||||||
@@ -61,8 +61,9 @@ class Institution(BaseModel):
|
|||||||
if value is None:
|
if value is None:
|
||||||
return value
|
return value
|
||||||
|
|
||||||
if value not in set(['education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other']):
|
valid_types = {'education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other', 'funder'}
|
||||||
raise ValueError("must be one of enum values ('education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other')")
|
if value not in valid_types:
|
||||||
|
return 'other'
|
||||||
return value
|
return value
|
||||||
|
|
||||||
model_config = ConfigDict(
|
model_config = ConfigDict(
|
||||||
|
|||||||
@@ -49,7 +49,6 @@ class DFGProject(BaseModel):
|
|||||||
equipment_group: StrictStr | None = None
|
equipment_group: StrictStr | None = None
|
||||||
equipment_name: StrictStr | None = None
|
equipment_name: StrictStr | None = None
|
||||||
external_link: StrictStr | None = None
|
external_link: StrictStr | None = None
|
||||||
fachgebiete: list[DFGProjectFachgebieteInner] | None = None
|
|
||||||
fetched_at: datetime | None = None
|
fetched_at: datetime | None = None
|
||||||
final_report_abstract_de: StrictStr | None = None
|
final_report_abstract_de: StrictStr | None = None
|
||||||
final_report_abstract_en: StrictStr | None = None
|
final_report_abstract_en: StrictStr | None = None
|
||||||
@@ -81,7 +80,7 @@ class DFGProject(BaseModel):
|
|||||||
publications: list[DFGProjectPublicationsInner] | None = None
|
publications: list[DFGProjectPublicationsInner] | None = None
|
||||||
subject_area_de: StrictStr | None = None
|
subject_area_de: StrictStr | None = None
|
||||||
subject_area_en: StrictStr | None = None
|
subject_area_en: StrictStr | None = None
|
||||||
subject_classifications: DFGProjectFachgebieteInner | None = None
|
subject_classifications: list[DFGProjectFachgebieteInner] | None = None
|
||||||
subproject_order: list[StrictStr] | None = None
|
subproject_order: list[StrictStr] | None = None
|
||||||
subprojects: list[DFGProjectSubprojectsInner] | None = None
|
subprojects: list[DFGProjectSubprojectsInner] | None = None
|
||||||
template_type: StrictStr | None = None
|
template_type: StrictStr | None = None
|
||||||
@@ -90,7 +89,7 @@ class DFGProject(BaseModel):
|
|||||||
website_html_de: StrictStr | None = None
|
website_html_de: StrictStr | None = None
|
||||||
website_html_en: StrictStr | None = None
|
website_html_en: StrictStr | None = None
|
||||||
topics: list[Topic] | None = None
|
topics: list[Topic] | None = None
|
||||||
__properties: ClassVar[list[str]] = ["abstract_de", "abstract_en", "equipment_group", "equipment_name", "external_link", "fachgebiete", "fetched_at", "final_report_abstract_de", "final_report_abstract_en", "funding_end", "funding_period_de", "funding_period_en", "funding_start", "funding_type_de", "funding_type_en", "funding_type_key", "funding_type_sort", "id", "institution_roles_order", "institutions", "international_relation_de", "international_relation_en", "is_transfer_project", "link", "page_url", "parent_project_id", "parent_title_de", "parent_title_en", "person_roles_order", "persons", "project", "project_id", "project_identifier_de", "project_identifier_en", "publications", "subject_area_de", "subject_area_en", "subject_classifications", "subproject_order", "subprojects", "template_type", "title_de", "title_en", "website_html_de", "website_html_en"]
|
__properties: ClassVar[list[str]] = ["abstract_de", "abstract_en", "equipment_group", "equipment_name", "external_link","fetched_at", "final_report_abstract_de", "final_report_abstract_en", "funding_end", "funding_period_de", "funding_period_en", "funding_start", "funding_type_de", "funding_type_en", "funding_type_key", "funding_type_sort", "id", "institution_roles_order", "institutions", "international_relation_de", "international_relation_en", "is_transfer_project", "link", "page_url", "parent_project_id", "parent_title_de", "parent_title_en", "person_roles_order", "persons", "project", "project_id", "project_identifier_de", "project_identifier_en", "publications", "subject_area_de", "subject_area_en", "subject_classifications", "subproject_order", "subprojects", "template_type", "title_de", "title_en", "website_html_de", "website_html_en"]
|
||||||
|
|
||||||
model_config = ConfigDict(
|
model_config = ConfigDict(
|
||||||
validate_by_name=True,
|
validate_by_name=True,
|
||||||
@@ -131,13 +130,6 @@ class DFGProject(BaseModel):
|
|||||||
exclude=excluded_fields,
|
exclude=excluded_fields,
|
||||||
exclude_none=True,
|
exclude_none=True,
|
||||||
)
|
)
|
||||||
# override the default output from pydantic by calling `to_dict()` of each item in fachgebiete (list)
|
|
||||||
_items = []
|
|
||||||
if self.fachgebiete:
|
|
||||||
for _item_fachgebiete in self.fachgebiete:
|
|
||||||
if _item_fachgebiete:
|
|
||||||
_items.append(_item_fachgebiete.to_dict())
|
|
||||||
_dict['fachgebiete'] = _items
|
|
||||||
# override the default output from pydantic by calling `to_dict()` of each item in institutions (list)
|
# override the default output from pydantic by calling `to_dict()` of each item in institutions (list)
|
||||||
_items = []
|
_items = []
|
||||||
if self.institutions:
|
if self.institutions:
|
||||||
@@ -164,7 +156,7 @@ class DFGProject(BaseModel):
|
|||||||
_dict['publications'] = _items
|
_dict['publications'] = _items
|
||||||
# override the default output from pydantic by calling `to_dict()` of subject_classifications
|
# override the default output from pydantic by calling `to_dict()` of subject_classifications
|
||||||
if self.subject_classifications:
|
if self.subject_classifications:
|
||||||
_dict['subject_classifications'] = self.subject_classifications.to_dict()
|
_dict['subject_classifications'] = [f.to_dict() for f in self.subject_classifications]
|
||||||
# override the default output from pydantic by calling `to_dict()` of each item in subprojects (list)
|
# override the default output from pydantic by calling `to_dict()` of each item in subprojects (list)
|
||||||
_items = []
|
_items = []
|
||||||
if self.subprojects:
|
if self.subprojects:
|
||||||
@@ -191,14 +183,12 @@ class DFGProject(BaseModel):
|
|||||||
key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"),
|
key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"),
|
||||||
)
|
)
|
||||||
topics = [cls._topic_from_match(t) for t in sorted_topics_raw]
|
topics = [cls._topic_from_match(t) for t in sorted_topics_raw]
|
||||||
|
|
||||||
_obj = cls.model_validate({
|
_obj = cls.model_validate({
|
||||||
"abstract_de": obj.get("abstract_de"),
|
"abstract_de": obj.get("abstract_de"),
|
||||||
"abstract_en": obj.get("abstract_en"),
|
"abstract_en": obj.get("abstract_en"),
|
||||||
"equipment_group": obj.get("equipment_group"),
|
"equipment_group": obj.get("equipment_group"),
|
||||||
"equipment_name": obj.get("equipment_name"),
|
"equipment_name": obj.get("equipment_name"),
|
||||||
"external_link": obj.get("external_link"),
|
"external_link": obj.get("external_link"),
|
||||||
"fachgebiete": [DFGProjectFachgebieteInner.from_dict(_item) for _item in obj["fachgebiete"]] if obj.get("fachgebiete") is not None else None,
|
|
||||||
"fetched_at": obj.get("fetched_at"),
|
"fetched_at": obj.get("fetched_at"),
|
||||||
"final_report_abstract_de": obj.get("final_report_abstract_de"),
|
"final_report_abstract_de": obj.get("final_report_abstract_de"),
|
||||||
"final_report_abstract_en": obj.get("final_report_abstract_en"),
|
"final_report_abstract_en": obj.get("final_report_abstract_en"),
|
||||||
@@ -230,7 +220,7 @@ class DFGProject(BaseModel):
|
|||||||
"publications": [DFGProjectPublicationsInner.from_dict(_item) for _item in obj["publications"]] if obj.get("publications") is not None else None,
|
"publications": [DFGProjectPublicationsInner.from_dict(_item) for _item in obj["publications"]] if obj.get("publications") is not None else None,
|
||||||
"subject_area_de": obj.get("subject_area_de"),
|
"subject_area_de": obj.get("subject_area_de"),
|
||||||
"subject_area_en": obj.get("subject_area_en"),
|
"subject_area_en": obj.get("subject_area_en"),
|
||||||
"subject_classifications": DFGProjectFachgebieteInner.from_dict(obj["subject_classifications"]) if obj.get("subject_classifications") is not None else None,
|
"subject_classifications": [DFGProjectFachgebieteInner.from_dict(f) for f in (obj.get("subject_classifications") or [])],
|
||||||
"subproject_order": obj.get("subproject_order"),
|
"subproject_order": obj.get("subproject_order"),
|
||||||
"subprojects": [DFGProjectSubprojectsInner.from_dict(_item) for _item in obj["subprojects"]] if obj.get("subprojects") is not None else None,
|
"subprojects": [DFGProjectSubprojectsInner.from_dict(_item) for _item in obj["subprojects"]] if obj.get("subprojects") is not None else None,
|
||||||
"template_type": obj.get("template_type"),
|
"template_type": obj.get("template_type"),
|
||||||
|
|||||||
@@ -27,7 +27,6 @@ TOPIC_NUM_CANDIDATES = 100
|
|||||||
TOPIC_SIMILARITY = 0.5
|
TOPIC_SIMILARITY = 0.5
|
||||||
|
|
||||||
TOPICS_INDEX = "aktuell_openalex_topics"
|
TOPICS_INDEX = "aktuell_openalex_topics"
|
||||||
TOPICS_INDEX_MAX_PAIRS = 100
|
|
||||||
|
|
||||||
_SESSION_TOPIC_CACHE: dict[str, list] = {}
|
_SESSION_TOPIC_CACHE: dict[str, list] = {}
|
||||||
|
|
||||||
@@ -48,6 +47,11 @@ RELATED_BLOCK_SIZE = 5
|
|||||||
RELATED_TOPIC_K = 1
|
RELATED_TOPIC_K = 1
|
||||||
EXACT_ID_CAP = 1000
|
EXACT_ID_CAP = 1000
|
||||||
|
|
||||||
|
KEYWORD_SEARCH_FIELDS = ["maintitle^3", "intro_content^2", "tags^2", "full_content"]
|
||||||
|
KEYWORD_SEARCH_SCAN_CAP = 50000
|
||||||
|
KEYWORD_SEARCH_ID_CAP = 2000
|
||||||
|
TOPIC_DOCS_PER_ARTICLE = 25
|
||||||
|
|
||||||
|
|
||||||
async def get_news_page(
|
async def get_news_page(
|
||||||
page: int,
|
page: int,
|
||||||
@@ -127,6 +131,206 @@ async def search_news(
|
|||||||
return news_page
|
return news_page
|
||||||
|
|
||||||
|
|
||||||
|
async def search_news_by_keywords(
|
||||||
|
keywords: list | None = None,
|
||||||
|
topic_ids: list | None = None,
|
||||||
|
filter_topic_ids: list | None = None,
|
||||||
|
fuzzy: bool = False,
|
||||||
|
page: int = 1,
|
||||||
|
page_size: int = 10,
|
||||||
|
year_from: int | None = None,
|
||||||
|
year_to: int | None = None,
|
||||||
|
relevance_values: list | None = None,
|
||||||
|
sort_order: str | None = None,
|
||||||
|
) -> NewsPage:
|
||||||
|
"""Searches the news for the keywords of a keywords-search run.
|
||||||
|
|
||||||
|
`fuzzy` resolves the keywords to OpenAlex topics (via the aktuell_openalex_topics index),
|
||||||
|
otherwise the raw keywords are matched as phrases against the article
|
||||||
|
text. The individual keywords are OR-ed rather than AND-ed.
|
||||||
|
An article carries at most KEYWORD_LIMIT keywords, so requiring all of them
|
||||||
|
would leave every multi-keyword search empty.
|
||||||
|
Articles matching more of them simply rank higher.
|
||||||
|
|
||||||
|
A fuzzy search without any resolved topic ids falls back to the raw
|
||||||
|
keywords. Once there are topic ids the fallback is off: a topic search that matches no article
|
||||||
|
stays empty instead of silently returning keyword hits.
|
||||||
|
|
||||||
|
By default results stay ranked by match strength (Elasticsearch's
|
||||||
|
`_score`). Passing `sort_order` ('asc'/'desc') overrides that with a
|
||||||
|
plain date sort, same as the plain news list.
|
||||||
|
"""
|
||||||
|
wanted_topic_ids: set = set()
|
||||||
|
if fuzzy:
|
||||||
|
wanted_topic_ids = {
|
||||||
|
topic_id
|
||||||
|
for topic_id in (topic_ids or []) + (filter_topic_ids or [])
|
||||||
|
if topic_id
|
||||||
|
}
|
||||||
|
|
||||||
|
if wanted_topic_ids:
|
||||||
|
should = await _topic_id_should_clauses(wanted_topic_ids)
|
||||||
|
else:
|
||||||
|
should = _keyword_should_clauses(keywords)
|
||||||
|
|
||||||
|
if not should:
|
||||||
|
return _empty_page(page, page_size)
|
||||||
|
|
||||||
|
clauses = await _filter_clauses(year_from, year_to, relevance_values)
|
||||||
|
query = {
|
||||||
|
"bool": {
|
||||||
|
"should": should,
|
||||||
|
"minimum_should_match": 1,
|
||||||
|
"filter": clauses,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
highlight = {
|
||||||
|
"fields": {"full_content": {"fragment_size": 200, "number_of_fragments": 1}},
|
||||||
|
"pre_tags": ["<em>"],
|
||||||
|
"post_tags": ["</em>"],
|
||||||
|
"encoder": "html",
|
||||||
|
}
|
||||||
|
|
||||||
|
sort = [{"date_full": sort_order}] if sort_order in ("asc", "desc") else None
|
||||||
|
|
||||||
|
response = await _run_search(
|
||||||
|
query=query,
|
||||||
|
source=["date", "maintitle", "author", "url", "intro_content", "full_content"],
|
||||||
|
size=page_size,
|
||||||
|
offset=(page - 1) * page_size,
|
||||||
|
sort=sort,
|
||||||
|
highlight=None if wanted_topic_ids else highlight,
|
||||||
|
)
|
||||||
|
|
||||||
|
news_page = await _build_page(response, page, page_size)
|
||||||
|
await _attach_topics(news_page.results)
|
||||||
|
|
||||||
|
return news_page
|
||||||
|
|
||||||
|
|
||||||
|
def _keyword_should_clauses(keywords: list | None) -> list:
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"multi_match": {
|
||||||
|
"query": keyword.strip(),
|
||||||
|
"fields": KEYWORD_SEARCH_FIELDS,
|
||||||
|
"type": "phrase",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for keyword in (keywords or [])
|
||||||
|
if keyword and keyword.strip()
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
async def _topic_id_should_clauses(topic_ids: set) -> list:
|
||||||
|
"""Turns matched OpenAlex topics into id clauses, boosted by hit count.
|
||||||
|
|
||||||
|
Articles that match several of the searched topics get a higher boost, so
|
||||||
|
Elasticsearch ranks them above articles that only match one.
|
||||||
|
"""
|
||||||
|
topics_per_article = await _news_ids_by_topic_ids(topic_ids)
|
||||||
|
if not topics_per_article:
|
||||||
|
return []
|
||||||
|
|
||||||
|
ranked = sorted(topics_per_article.items(), key=lambda item: -len(item[1]))
|
||||||
|
ids_by_hit_count: dict[int, list] = {}
|
||||||
|
for news_id, matched_topics in ranked[:KEYWORD_SEARCH_ID_CAP]:
|
||||||
|
ids_by_hit_count.setdefault(len(matched_topics), []).append(news_id)
|
||||||
|
|
||||||
|
return [
|
||||||
|
{"ids": {"values": news_ids, "boost": float(hit_count)}}
|
||||||
|
for hit_count, news_ids in ids_by_hit_count.items()
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
async def _news_ids_by_topic_ids(topic_ids: set) -> dict:
|
||||||
|
"""Returns news_id -> set of searched topic ids the article was mapped to."""
|
||||||
|
query = {"terms": {"topic_matches.topic_id.keyword": sorted(topic_ids)}}
|
||||||
|
|
||||||
|
topics_per_article: dict[str, set] = {}
|
||||||
|
scanned = 0
|
||||||
|
try:
|
||||||
|
async for hit in elasticsearch.scan(
|
||||||
|
index=TOPICS_INDEX,
|
||||||
|
query=query,
|
||||||
|
source=["news_id", "topic_matches.topic_id"],
|
||||||
|
cluster="inse",
|
||||||
|
):
|
||||||
|
scanned += 1
|
||||||
|
source = hit.get("_source", {})
|
||||||
|
news_id = source.get("news_id")
|
||||||
|
if news_id:
|
||||||
|
matched = topics_per_article.setdefault(news_id, set())
|
||||||
|
for match in source.get("topic_matches") or []:
|
||||||
|
topic_id = match.get("topic_id")
|
||||||
|
if topic_id in topic_ids:
|
||||||
|
matched.add(topic_id)
|
||||||
|
if scanned >= KEYWORD_SEARCH_SCAN_CAP:
|
||||||
|
logger.warning(
|
||||||
|
f"Topic lookup hit the scan cap of {KEYWORD_SEARCH_SCAN_CAP} documents."
|
||||||
|
)
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Topic lookup for the keyword news search failed.")
|
||||||
|
return {}
|
||||||
|
|
||||||
|
return {news_id: matched for news_id, matched in topics_per_article.items() if matched}
|
||||||
|
|
||||||
|
|
||||||
|
async def _attach_topics(articles: list) -> None:
|
||||||
|
news_ids = [article.id for article in articles if article.id]
|
||||||
|
if not news_ids:
|
||||||
|
return
|
||||||
|
|
||||||
|
topics_per_article = await _topics_for_news_ids(news_ids)
|
||||||
|
for article in articles:
|
||||||
|
article.topics = topics_per_article.get(article.id, [])
|
||||||
|
|
||||||
|
|
||||||
|
async def _topics_for_news_ids(news_ids: list) -> dict[str, list[MatchedTopic]]:
|
||||||
|
"""Reads the indexed OpenAlex topic matches for the given articles."""
|
||||||
|
try:
|
||||||
|
response = await elasticsearch.search(
|
||||||
|
index=TOPICS_INDEX,
|
||||||
|
query={"terms": {"news_id.keyword": news_ids}},
|
||||||
|
source=["news_id", "keyword", "topic_matches"],
|
||||||
|
size=min(len(news_ids) * TOPIC_DOCS_PER_ARTICLE, 10000),
|
||||||
|
cluster="inse",
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Batched topic lookup for the news result page failed.")
|
||||||
|
return {}
|
||||||
|
|
||||||
|
topics_per_article: dict[str, list[MatchedTopic]] = {}
|
||||||
|
seen_per_article: dict[str, set] = {}
|
||||||
|
for hit in response.get("hits", {}).get("hits", []):
|
||||||
|
source = hit.get("_source", {})
|
||||||
|
news_id = source.get("news_id")
|
||||||
|
if not news_id:
|
||||||
|
continue
|
||||||
|
keyword = source.get("keyword")
|
||||||
|
matched = topics_per_article.setdefault(news_id, [])
|
||||||
|
seen_ids = seen_per_article.setdefault(news_id, set())
|
||||||
|
for match in source.get("topic_matches") or []:
|
||||||
|
topic_id = match.get("topic_id")
|
||||||
|
if not topic_id or topic_id in seen_ids:
|
||||||
|
continue
|
||||||
|
seen_ids.add(topic_id)
|
||||||
|
matched.append(
|
||||||
|
MatchedTopic(
|
||||||
|
id=topic_id,
|
||||||
|
display_name=match.get("topic_display_name"),
|
||||||
|
subfield_name=match.get("subfield"),
|
||||||
|
field_name=match.get("field"),
|
||||||
|
domain_name=match.get("domain"),
|
||||||
|
source_keyword=keyword,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
return topics_per_article
|
||||||
|
|
||||||
|
|
||||||
async def get_news_by_author(
|
async def get_news_by_author(
|
||||||
author_id: str,
|
author_id: str,
|
||||||
page: int = 1,
|
page: int = 1,
|
||||||
@@ -321,7 +525,7 @@ async def _get_article_keywords(
|
|||||||
|
|
||||||
|
|
||||||
async def _get_article_topics(news_id: str, keywords: list) -> list:
|
async def _get_article_topics(news_id: str, keywords: list) -> list:
|
||||||
indexed = await get_article_topics_from_index(news_id)
|
indexed = (await _topics_for_news_ids([news_id])).get(news_id, [])
|
||||||
if indexed:
|
if indexed:
|
||||||
return indexed
|
return indexed
|
||||||
|
|
||||||
@@ -336,42 +540,6 @@ async def _get_article_topics(news_id: str, keywords: list) -> list:
|
|||||||
return topics
|
return topics
|
||||||
|
|
||||||
|
|
||||||
async def get_article_topics_from_index(news_id: str) -> list:
|
|
||||||
try:
|
|
||||||
response = await elasticsearch.search(
|
|
||||||
index=TOPICS_INDEX,
|
|
||||||
query={"term": {"news_id.keyword": news_id}},
|
|
||||||
source=["keyword", "topic_matches"],
|
|
||||||
size=TOPICS_INDEX_MAX_PAIRS,
|
|
||||||
cluster="inse",
|
|
||||||
)
|
|
||||||
except Exception:
|
|
||||||
logger.exception(f"Topic-index lookup for {news_id} failed.")
|
|
||||||
return []
|
|
||||||
|
|
||||||
matched = []
|
|
||||||
seen_ids = set()
|
|
||||||
for hit in response.get("hits", {}).get("hits", []):
|
|
||||||
source = hit.get("_source", {})
|
|
||||||
keyword = source.get("keyword")
|
|
||||||
for match in source.get("topic_matches") or []:
|
|
||||||
topic_id = match.get("topic_id")
|
|
||||||
if not topic_id or topic_id in seen_ids:
|
|
||||||
continue
|
|
||||||
seen_ids.add(topic_id)
|
|
||||||
matched.append(
|
|
||||||
MatchedTopic(
|
|
||||||
id=topic_id,
|
|
||||||
display_name=match.get("topic_display_name"),
|
|
||||||
subfield_name=match.get("subfield"),
|
|
||||||
field_name=match.get("field"),
|
|
||||||
domain_name=match.get("domain"),
|
|
||||||
source_keyword=keyword,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
return matched
|
|
||||||
|
|
||||||
|
|
||||||
def _normalize_keywords(candidates: list) -> list:
|
def _normalize_keywords(candidates: list) -> list:
|
||||||
"""Trims, dedups (case-insensitive) and caps the keywords from the LLM."""
|
"""Trims, dedups (case-insensitive) and caps the keywords from the LLM."""
|
||||||
seen = set()
|
seen = set()
|
||||||
@@ -516,7 +684,7 @@ async def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, s
|
|||||||
return relevant, authors, keywords, hit.get("_id")
|
return relevant, authors, keywords, hit.get("_id")
|
||||||
|
|
||||||
|
|
||||||
async def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict:
|
async def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict | None = None) -> dict:
|
||||||
try:
|
try:
|
||||||
return await elasticsearch.search(
|
return await elasticsearch.search(
|
||||||
index="aktuell",
|
index="aktuell",
|
||||||
|
|||||||
@@ -8,17 +8,6 @@ class NewsKeywords(BaseModel):
|
|||||||
keywords: list[str] = Field(description="The extracted keywords from the article.")
|
keywords: list[str] = Field(description="The extracted keywords from the article.")
|
||||||
|
|
||||||
|
|
||||||
class NewsArticle(BaseModel):
|
|
||||||
id: str
|
|
||||||
date: str | None = None
|
|
||||||
maintitle: str | None = None
|
|
||||||
author: str | None = None
|
|
||||||
url: str | None = None
|
|
||||||
relevant: bool | None = None
|
|
||||||
snippet: str | None = None
|
|
||||||
related: bool | None = None
|
|
||||||
|
|
||||||
|
|
||||||
class MentionedPerson(BaseModel):
|
class MentionedPerson(BaseModel):
|
||||||
name: str
|
name: str
|
||||||
is_ude: bool = False
|
is_ude: bool = False
|
||||||
@@ -34,6 +23,18 @@ class MatchedTopic(BaseModel):
|
|||||||
source_keyword: str | None = None
|
source_keyword: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class NewsArticle(BaseModel):
|
||||||
|
id: str
|
||||||
|
date: str | None = None
|
||||||
|
maintitle: str | None = None
|
||||||
|
author: str | None = None
|
||||||
|
url: str | None = None
|
||||||
|
relevant: bool | None = None
|
||||||
|
snippet: str | None = None
|
||||||
|
related: bool | None = None
|
||||||
|
topics: list[MatchedTopic] | None = None
|
||||||
|
|
||||||
|
|
||||||
class NewsArticleDetail(NewsArticle):
|
class NewsArticleDetail(NewsArticle):
|
||||||
full_content: str | None = None
|
full_content: str | None = None
|
||||||
relevant: bool | None = None
|
relevant: bool | None = None
|
||||||
|
|||||||
@@ -100,6 +100,68 @@ async def search_news(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/keyword/search",
|
||||||
|
operation_id="getNewsByKeywords",
|
||||||
|
response_model=NewsPage,
|
||||||
|
response_model_exclude_none=True,
|
||||||
|
summary="Searches news articles by the keywords or matched topics of a keywords search.",
|
||||||
|
tags=[Tags.NEWS],
|
||||||
|
)
|
||||||
|
async def search_news_by_keywords(
|
||||||
|
keywords: Annotated[
|
||||||
|
list[str] | None, Query(description="Raw keywords to match against title/content.")
|
||||||
|
] = None,
|
||||||
|
topic_ids: Annotated[
|
||||||
|
list[str] | None,
|
||||||
|
Query(alias="topicIds", description="OpenAlex topic ids the keywords resolved to."),
|
||||||
|
] = None,
|
||||||
|
filter_topic_ids: Annotated[
|
||||||
|
list[str] | None,
|
||||||
|
Query(alias="filterTopicIds", description="Additional topic ids to narrow the results by."),
|
||||||
|
] = None,
|
||||||
|
fuzzy: Annotated[
|
||||||
|
bool,
|
||||||
|
Query(description="Search by resolved topics if True, otherwise by raw keywords."),
|
||||||
|
] = False,
|
||||||
|
page: Annotated[
|
||||||
|
int, Query(description="Page number (1-based).", ge=1)
|
||||||
|
] = 1,
|
||||||
|
page_size: Annotated[
|
||||||
|
int, Query(alias="pageSize", description="Articles per page.", ge=1, le=100)
|
||||||
|
] = 10,
|
||||||
|
relevance: Annotated[
|
||||||
|
str | None, Query(description="Comma-separated relevance filter: 'relevant', 'not_relevant'.")
|
||||||
|
] = None,
|
||||||
|
year_from: Annotated[
|
||||||
|
int | None, Query(alias="yearFrom", description="Earliest publication year (inclusive).", ge=0)
|
||||||
|
] = None,
|
||||||
|
year_to: Annotated[
|
||||||
|
int | None, Query(alias="yearTo", description="Latest publication year (inclusive).", ge=0)
|
||||||
|
] = None,
|
||||||
|
sort_order: Annotated[
|
||||||
|
str | None,
|
||||||
|
Query(
|
||||||
|
alias="sortOrder",
|
||||||
|
description="Overrides relevance ranking with a date sort: 'desc' (newest first) or 'asc' (oldest first).",
|
||||||
|
pattern="^(asc|desc)$",
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
):
|
||||||
|
return await logic.search_news_by_keywords(
|
||||||
|
keywords=keywords or [],
|
||||||
|
topic_ids=topic_ids or [],
|
||||||
|
filter_topic_ids=filter_topic_ids or [],
|
||||||
|
fuzzy=fuzzy,
|
||||||
|
page=page,
|
||||||
|
page_size=page_size,
|
||||||
|
sort_order=sort_order,
|
||||||
|
year_from=year_from,
|
||||||
|
year_to=year_to,
|
||||||
|
relevance_values=_parse_relevance(relevance),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
"/by-author",
|
"/by-author",
|
||||||
operation_id="getNewsByAuthor",
|
operation_id="getNewsByAuthor",
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
"""Find patents for extracted OpenAlex keywords via patents_openalex_keywords index."""
|
"""Find patents for extracted OpenAlex keywords via IPC/CPC reverse lookup."""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
@@ -31,7 +31,6 @@ from inse.patents.ipc_lookup import (
|
|||||||
)
|
)
|
||||||
from inse.patents.ipc_search_client import IpcSearchClient
|
from inse.patents.ipc_search_client import IpcSearchClient
|
||||||
from inse.patents.keywords.model import (
|
from inse.patents.keywords.model import (
|
||||||
KeywordEvidence,
|
|
||||||
KeywordPatentMappingStatus,
|
KeywordPatentMappingStatus,
|
||||||
KeywordPatentMatch,
|
KeywordPatentMatch,
|
||||||
KeywordPatentSearchDiagnostics,
|
KeywordPatentSearchDiagnostics,
|
||||||
@@ -76,13 +75,7 @@ _MIN_LEADER_RELATIVE_MASS = 0.20
|
|||||||
_MIN_LEADER_MASS_RATIO = 1.5
|
_MIN_LEADER_MASS_RATIO = 1.5
|
||||||
_TARGET_CUMULATIVE_CLUSTER_MASS = 0.75
|
_TARGET_CUMULATIVE_CLUSTER_MASS = 0.75
|
||||||
_MIN_PATENT_MATCH_SCORE = 0.50
|
_MIN_PATENT_MATCH_SCORE = 0.50
|
||||||
_MIN_TEXT_PATENT_MATCH_SCORE = 0.30
|
|
||||||
_DEFAULT_SCORE_WEIGHTS = {"ipc": 0.60, "topic": 0.25, "text": 0.15}
|
_DEFAULT_SCORE_WEIGHTS = {"ipc": 0.60, "topic": 0.25, "text": 0.15}
|
||||||
# When IPC mapping is abstained, score only topic + text evidence.
|
|
||||||
_TEXT_SCORE_WEIGHTS = {"ipc": 0.0, "topic": 0.45, "text": 0.55}
|
|
||||||
# Also try title/abstract search when IPC mapping produced terms but scoring
|
|
||||||
# returned no patents (empty retrieval or over-filtering).
|
|
||||||
_TEXT_SEARCH_AFTER_EMPTY_IPC = True
|
|
||||||
_TOPIC_SCORE_TOPIC_ID = 1.0
|
_TOPIC_SCORE_TOPIC_ID = 1.0
|
||||||
_TOPIC_SCORE_SUBFIELD = 0.7
|
_TOPIC_SCORE_SUBFIELD = 0.7
|
||||||
_TOPIC_SCORE_COMPATIBLE_FIELD = 0.3
|
_TOPIC_SCORE_COMPATIBLE_FIELD = 0.3
|
||||||
@@ -618,12 +611,6 @@ class TopicEvidence:
|
|||||||
score: float
|
score: float
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class TextGateDecision:
|
|
||||||
accepted: bool
|
|
||||||
reason: str
|
|
||||||
|
|
||||||
|
|
||||||
def _compute_topic_evidence(
|
def _compute_topic_evidence(
|
||||||
patent_topics: list[MappedOpenAlexTopic],
|
patent_topics: list[MappedOpenAlexTopic],
|
||||||
keyword_topic_ids: frozenset[str],
|
keyword_topic_ids: frozenset[str],
|
||||||
@@ -702,16 +689,6 @@ def _tokenize_words(text: str) -> list[str]:
|
|||||||
return re.findall(r"[a-z0-9äöüß]+", (text or "").casefold())
|
return re.findall(r"[a-z0-9äöüß]+", (text or "").casefold())
|
||||||
|
|
||||||
|
|
||||||
def _contains_token_sequence(haystack: list[str], needle: list[str]) -> bool:
|
|
||||||
if not needle or len(needle) > len(haystack):
|
|
||||||
return False
|
|
||||||
width = len(needle)
|
|
||||||
for index in range(len(haystack) - width + 1):
|
|
||||||
if haystack[index : index + width] == needle:
|
|
||||||
return True
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def _token_set(tokens: list[str]) -> set[str]:
|
def _token_set(tokens: list[str]) -> set[str]:
|
||||||
return set(tokens)
|
return set(tokens)
|
||||||
|
|
||||||
@@ -735,23 +712,6 @@ def _text_search_terms(items: list[KeywordPatentSearchItem]) -> list[str]:
|
|||||||
return terms
|
return terms
|
||||||
|
|
||||||
|
|
||||||
def _text_search_phrases(items: list[KeywordPatentSearchItem]) -> list[str]:
|
|
||||||
"""Full phrases for ES title/abstract retrieval (text path)."""
|
|
||||||
phrases: list[str] = []
|
|
||||||
seen: set[str] = set()
|
|
||||||
for item in items:
|
|
||||||
for value in (item.keyword, item.topic_display_name):
|
|
||||||
cleaned = " ".join((value or "").strip().split())
|
|
||||||
if len(cleaned) < 3:
|
|
||||||
continue
|
|
||||||
key = cleaned.casefold()
|
|
||||||
if key in seen:
|
|
||||||
continue
|
|
||||||
seen.add(key)
|
|
||||||
phrases.append(cleaned)
|
|
||||||
return phrases
|
|
||||||
|
|
||||||
|
|
||||||
def _text_overlap_score(
|
def _text_overlap_score(
|
||||||
patent: model.PatentEntry,
|
patent: model.PatentEntry,
|
||||||
search_terms: list[str],
|
search_terms: list[str],
|
||||||
@@ -772,173 +732,6 @@ def _text_overlap_score(
|
|||||||
return min(hits / 3, 1.0)
|
return min(hits / 3, 1.0)
|
||||||
|
|
||||||
|
|
||||||
def _text_match_kind(
|
|
||||||
*,
|
|
||||||
phrase_in_title: bool,
|
|
||||||
phrase_in_abstract: bool,
|
|
||||||
full_token_match: bool,
|
|
||||||
partial_token_match: bool,
|
|
||||||
) -> str:
|
|
||||||
if phrase_in_title:
|
|
||||||
return "phrase_title"
|
|
||||||
if phrase_in_abstract:
|
|
||||||
return "phrase_abstract"
|
|
||||||
if full_token_match:
|
|
||||||
return "full_token"
|
|
||||||
if partial_token_match:
|
|
||||||
return "partial_token"
|
|
||||||
return "none"
|
|
||||||
|
|
||||||
|
|
||||||
def _collect_keyword_text_evidence(
|
|
||||||
patent: model.PatentEntry,
|
|
||||||
phrases: list[str],
|
|
||||||
search_terms: list[str],
|
|
||||||
) -> KeywordEvidence:
|
|
||||||
"""Record phrase / full-token / partial-token evidence separately."""
|
|
||||||
title_tokens = _tokenize_words(patent.title or "")
|
|
||||||
abstract_tokens = _tokenize_words(patent.abstract or "")
|
|
||||||
combined_tokens = _token_set(title_tokens + abstract_tokens)
|
|
||||||
|
|
||||||
phrase_in_title = False
|
|
||||||
phrase_in_abstract = False
|
|
||||||
full_token_match = False
|
|
||||||
partial_token_match = False
|
|
||||||
matched_phrases: list[str] = []
|
|
||||||
|
|
||||||
for phrase in phrases:
|
|
||||||
phrase_tokens = _tokenize_words(phrase)
|
|
||||||
if not phrase_tokens:
|
|
||||||
continue
|
|
||||||
if _contains_token_sequence(title_tokens, phrase_tokens):
|
|
||||||
phrase_in_title = True
|
|
||||||
matched_phrases.append(phrase)
|
|
||||||
elif _contains_token_sequence(abstract_tokens, phrase_tokens):
|
|
||||||
phrase_in_abstract = True
|
|
||||||
matched_phrases.append(phrase)
|
|
||||||
|
|
||||||
present = [token for token in phrase_tokens if token in combined_tokens]
|
|
||||||
if present and len(present) == len(phrase_tokens):
|
|
||||||
full_token_match = True
|
|
||||||
elif present:
|
|
||||||
partial_token_match = True
|
|
||||||
|
|
||||||
matched_words = [term for term in search_terms if term in combined_tokens]
|
|
||||||
if matched_words and not full_token_match and not partial_token_match:
|
|
||||||
# Lone search-term hits without a covering phrase count as partial.
|
|
||||||
partial_token_match = True
|
|
||||||
|
|
||||||
word_match_score = (
|
|
||||||
min(len(matched_words) / 3, 1.0) if search_terms and matched_words else 0.0
|
|
||||||
)
|
|
||||||
kind = _text_match_kind(
|
|
||||||
phrase_in_title=phrase_in_title,
|
|
||||||
phrase_in_abstract=phrase_in_abstract,
|
|
||||||
full_token_match=full_token_match,
|
|
||||||
partial_token_match=partial_token_match,
|
|
||||||
)
|
|
||||||
|
|
||||||
return KeywordEvidence(
|
|
||||||
phrase_in_title=phrase_in_title,
|
|
||||||
phrase_in_abstract=phrase_in_abstract,
|
|
||||||
full_token_match=full_token_match,
|
|
||||||
partial_token_match=partial_token_match,
|
|
||||||
word_match_score=round(word_match_score, 4),
|
|
||||||
matched_phrases=list(dict.fromkeys(matched_phrases)),
|
|
||||||
matched_words=matched_words,
|
|
||||||
text_match_kind=kind,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _keyword_text_score(evidence: KeywordEvidence) -> float:
|
|
||||||
if evidence.phrase_in_title:
|
|
||||||
return 1.0
|
|
||||||
if evidence.phrase_in_abstract:
|
|
||||||
return 0.85
|
|
||||||
if evidence.full_token_match:
|
|
||||||
return 0.55
|
|
||||||
if evidence.partial_token_match:
|
|
||||||
return 0.25
|
|
||||||
return 0.0
|
|
||||||
|
|
||||||
|
|
||||||
def _exact_topic_or_subfield_match(
|
|
||||||
patent_topics: list[MappedOpenAlexTopic],
|
|
||||||
keyword_topic_ids: frozenset[str],
|
|
||||||
keyword_subfield_names: frozenset[str],
|
|
||||||
) -> bool:
|
|
||||||
evidence = _compute_topic_evidence(
|
|
||||||
patent_topics,
|
|
||||||
keyword_topic_ids,
|
|
||||||
keyword_subfield_names,
|
|
||||||
frozenset(),
|
|
||||||
)
|
|
||||||
return evidence.match_kind in {"topic_id", "subfield"}
|
|
||||||
|
|
||||||
|
|
||||||
def _keyword_text_passes_relevance_gate(
|
|
||||||
evidence: KeywordEvidence,
|
|
||||||
*,
|
|
||||||
topic_evidence: TopicEvidence,
|
|
||||||
) -> TextGateDecision:
|
|
||||||
"""Keyword text acceptance policy (no domain hardcoding).
|
|
||||||
|
|
||||||
Accept:
|
|
||||||
- phrase in title (strong)
|
|
||||||
- phrase in abstract (medium)
|
|
||||||
- exact topic/subfield together with full token text evidence
|
|
||||||
Reject:
|
|
||||||
- partial/general words alone
|
|
||||||
- compatible field alone
|
|
||||||
- exact topic/subfield without text evidence
|
|
||||||
"""
|
|
||||||
exact = topic_evidence.match_kind in {"topic_id", "subfield"}
|
|
||||||
|
|
||||||
if evidence.phrase_in_title:
|
|
||||||
return TextGateDecision(True, "phrase_in_title")
|
|
||||||
if evidence.phrase_in_abstract:
|
|
||||||
return TextGateDecision(True, "phrase_in_abstract")
|
|
||||||
if exact and evidence.full_token_match:
|
|
||||||
return TextGateDecision(
|
|
||||||
True,
|
|
||||||
f"{topic_evidence.match_kind}_with_full_token_match",
|
|
||||||
)
|
|
||||||
if exact and evidence.partial_token_match:
|
|
||||||
return TextGateDecision(False, "exact_topic_with_partial_tokens_only")
|
|
||||||
if exact:
|
|
||||||
return TextGateDecision(False, "exact_topic_without_text")
|
|
||||||
if topic_evidence.match_kind == "compatible_field":
|
|
||||||
return TextGateDecision(False, "compatible_field_only")
|
|
||||||
if evidence.partial_token_match or evidence.matched_words:
|
|
||||||
return TextGateDecision(False, "partial_or_loose_words_only")
|
|
||||||
return TextGateDecision(False, "insufficient_evidence")
|
|
||||||
|
|
||||||
|
|
||||||
def _matched_keyword_labels_from_evidence(
|
|
||||||
items: list[KeywordPatentSearchItem],
|
|
||||||
evidence: KeywordEvidence,
|
|
||||||
) -> list[str]:
|
|
||||||
matched: list[str] = []
|
|
||||||
seen: set[str] = set()
|
|
||||||
phrase_keys = {phrase.casefold() for phrase in evidence.matched_phrases}
|
|
||||||
word_keys = set(evidence.matched_words)
|
|
||||||
|
|
||||||
for item in items:
|
|
||||||
for value in (item.keyword, item.topic_display_name):
|
|
||||||
label = (value or "").strip()
|
|
||||||
if not label:
|
|
||||||
continue
|
|
||||||
key = label.casefold()
|
|
||||||
if key in seen:
|
|
||||||
continue
|
|
||||||
label_tokens = _tokenize_words(label)
|
|
||||||
if key in phrase_keys or any(token in word_keys for token in label_tokens):
|
|
||||||
seen.add(key)
|
|
||||||
matched.append(label)
|
|
||||||
break
|
|
||||||
return matched
|
|
||||||
|
|
||||||
|
|
||||||
def _patent_passes_relevance_gate(
|
def _patent_passes_relevance_gate(
|
||||||
patent_topics: list[MappedOpenAlexTopic],
|
patent_topics: list[MappedOpenAlexTopic],
|
||||||
*,
|
*,
|
||||||
@@ -1261,210 +1054,6 @@ async def _score_patents_with_ipc(
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async def _score_patents_text_search(
|
|
||||||
*,
|
|
||||||
raw_patents: list[model.PatentEntry],
|
|
||||||
search_keywords: list[KeywordPatentSearchItem],
|
|
||||||
phrases: list[str],
|
|
||||||
text_search_terms: list[str],
|
|
||||||
keyword_topic_ids: frozenset[str],
|
|
||||||
keyword_subfield_names: frozenset[str],
|
|
||||||
keyword_soft_field_names: frozenset[str],
|
|
||||||
resolver: PatentOpenAlexMappingResolver,
|
|
||||||
) -> tuple[list[KeywordPatentMatch], dict[str, int]]:
|
|
||||||
"""Score patents without IPC using graded topic + structured text evidence."""
|
|
||||||
patent_topics_by_key = await resolver.resolve_topics_for_patents(raw_patents)
|
|
||||||
scored: list[KeywordPatentMatch] = []
|
|
||||||
filtered_by_relevance_gate = 0
|
|
||||||
filtered_by_min_score = 0
|
|
||||||
passed_relevance_gate = 0
|
|
||||||
|
|
||||||
for patent in raw_patents:
|
|
||||||
patent_topics = patent_topics_by_key.get(patent_map_key(patent), [])
|
|
||||||
evidence = _collect_keyword_text_evidence(patent, phrases, text_search_terms)
|
|
||||||
topic_evidence = _compute_topic_evidence(
|
|
||||||
patent_topics,
|
|
||||||
keyword_topic_ids,
|
|
||||||
keyword_subfield_names,
|
|
||||||
keyword_soft_field_names,
|
|
||||||
)
|
|
||||||
decision = _keyword_text_passes_relevance_gate(
|
|
||||||
evidence,
|
|
||||||
topic_evidence=topic_evidence,
|
|
||||||
)
|
|
||||||
if not decision.accepted:
|
|
||||||
filtered_by_relevance_gate += 1
|
|
||||||
logger.info(
|
|
||||||
"Text reject: id=%s title=%s topic_kind=%s topic_score=%.2f "
|
|
||||||
"text_kind=%s phrase_title=%s phrase_abstract=%s "
|
|
||||||
"full_token=%s partial_token=%s reason=%s",
|
|
||||||
patent.patent_id,
|
|
||||||
patent.title,
|
|
||||||
topic_evidence.match_kind,
|
|
||||||
topic_evidence.score,
|
|
||||||
evidence.text_match_kind,
|
|
||||||
evidence.phrase_in_title,
|
|
||||||
evidence.phrase_in_abstract,
|
|
||||||
evidence.full_token_match,
|
|
||||||
evidence.partial_token_match,
|
|
||||||
decision.reason,
|
|
||||||
)
|
|
||||||
continue
|
|
||||||
|
|
||||||
passed_relevance_gate += 1
|
|
||||||
text_score = _keyword_text_score(evidence)
|
|
||||||
# Field-only remains a weak ranking signal when already accepted via phrase.
|
|
||||||
score = _compute_final_score(
|
|
||||||
0.0,
|
|
||||||
topic_evidence.score,
|
|
||||||
text_score,
|
|
||||||
weights=_TEXT_SCORE_WEIGHTS,
|
|
||||||
)
|
|
||||||
if score < _MIN_TEXT_PATENT_MATCH_SCORE:
|
|
||||||
filtered_by_min_score += 1
|
|
||||||
logger.info(
|
|
||||||
"Text reject: id=%s reason=below_min_score score=%.4f",
|
|
||||||
patent.patent_id,
|
|
||||||
score,
|
|
||||||
)
|
|
||||||
continue
|
|
||||||
|
|
||||||
logger.info(
|
|
||||||
"Text accept: id=%s title=%s topic_kind=%s topic_score=%.2f "
|
|
||||||
"text_kind=%s text_score=%.2f final_score=%.4f reason=%s",
|
|
||||||
patent.patent_id,
|
|
||||||
patent.title,
|
|
||||||
topic_evidence.match_kind,
|
|
||||||
topic_evidence.score,
|
|
||||||
evidence.text_match_kind,
|
|
||||||
text_score,
|
|
||||||
score,
|
|
||||||
decision.reason,
|
|
||||||
)
|
|
||||||
scored.append(
|
|
||||||
KeywordPatentMatch(
|
|
||||||
patent=patent,
|
|
||||||
match_score=score,
|
|
||||||
ipc_score=0.0,
|
|
||||||
topic_score=topic_evidence.score,
|
|
||||||
text_score=text_score,
|
|
||||||
matched_keywords=_matched_keyword_labels_from_evidence(
|
|
||||||
search_keywords,
|
|
||||||
evidence,
|
|
||||||
),
|
|
||||||
matched_ipc_symbols=[],
|
|
||||||
text_retrieval=True,
|
|
||||||
keyword_evidence=evidence,
|
|
||||||
topic_match_kind=topic_evidence.match_kind,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
logger.info(
|
|
||||||
"Keyword patent text search: filtered_by_relevance_gate=%d "
|
|
||||||
"filtered_by_min_score=%d passed_relevance_gate=%d scored=%d",
|
|
||||||
filtered_by_relevance_gate,
|
|
||||||
filtered_by_min_score,
|
|
||||||
passed_relevance_gate,
|
|
||||||
len(scored),
|
|
||||||
)
|
|
||||||
return scored, {
|
|
||||||
"filtered_by_relevance_gate": filtered_by_relevance_gate,
|
|
||||||
"filtered_by_min_score": filtered_by_min_score,
|
|
||||||
"passed_relevance_gate": passed_relevance_gate,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
async def _search_patents_text_search(
|
|
||||||
*,
|
|
||||||
client: BasePatentSearchClient,
|
|
||||||
queries: IpcPatentSearchQueries,
|
|
||||||
ipc_search: IpcSearchClient,
|
|
||||||
resolver: PatentOpenAlexMappingResolver,
|
|
||||||
search_keywords: list[KeywordPatentSearchItem],
|
|
||||||
keyword_topic_ids: frozenset[str],
|
|
||||||
keyword_subfield_names: frozenset[str],
|
|
||||||
keyword_soft_field_names: frozenset[str],
|
|
||||||
mapping_status: KeywordPatentMappingStatus,
|
|
||||||
ipc_cluster_selections: list[dict] | None = None,
|
|
||||||
) -> PatentsByKeywordsResponse:
|
|
||||||
cluster_dicts = list(ipc_cluster_selections or [])
|
|
||||||
phrases = _text_search_phrases(search_keywords)
|
|
||||||
text_search_terms = _text_search_terms(search_keywords)
|
|
||||||
if not phrases:
|
|
||||||
logger.info(
|
|
||||||
"Keyword patent text search: no phrases for keywords %s",
|
|
||||||
[item.keyword for item in search_keywords],
|
|
||||||
)
|
|
||||||
return PatentsByKeywordsResponse(
|
|
||||||
patent_count=0,
|
|
||||||
patents=[],
|
|
||||||
mapping_status="no_patents_found",
|
|
||||||
diagnostics=_empty_diagnostics(
|
|
||||||
search_path="text",
|
|
||||||
ipc_cluster_selections=cluster_dicts,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
logger.info(
|
|
||||||
"Keyword patent text search: mapping_status=%s phrases=%s",
|
|
||||||
mapping_status,
|
|
||||||
phrases,
|
|
||||||
)
|
|
||||||
raw_patents = await _fetch_patents_for_queries(
|
|
||||||
client,
|
|
||||||
queries.epo_query_by_text_phrases(phrases, size=_MAX_PATENTS),
|
|
||||||
queries.uspto_query_by_text_phrases(phrases, size=_MAX_PATENTS),
|
|
||||||
)
|
|
||||||
if raw_patents is None:
|
|
||||||
return PatentsByKeywordsResponse(
|
|
||||||
patent_count=0,
|
|
||||||
patents=[],
|
|
||||||
mapping_status="search_error",
|
|
||||||
diagnostics=_empty_diagnostics(
|
|
||||||
search_path="text",
|
|
||||||
ipc_cluster_selections=cluster_dicts,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
logger.info("Keyword patent text search: raw_patents=%d", len(raw_patents))
|
|
||||||
scored, filter_counts = await _score_patents_text_search(
|
|
||||||
raw_patents=raw_patents,
|
|
||||||
search_keywords=search_keywords,
|
|
||||||
phrases=phrases,
|
|
||||||
text_search_terms=text_search_terms,
|
|
||||||
keyword_topic_ids=keyword_topic_ids,
|
|
||||||
keyword_subfield_names=keyword_subfield_names,
|
|
||||||
keyword_soft_field_names=keyword_soft_field_names,
|
|
||||||
resolver=resolver,
|
|
||||||
)
|
|
||||||
scored, diagnostics = _finalize_scored_patents(
|
|
||||||
scored,
|
|
||||||
raw_count=len(raw_patents),
|
|
||||||
filtered_by_ipc=0,
|
|
||||||
filtered_by_relevance_gate=filter_counts["filtered_by_relevance_gate"],
|
|
||||||
filtered_by_min_score=filter_counts["filtered_by_min_score"],
|
|
||||||
passed_relevance_gate=filter_counts["passed_relevance_gate"],
|
|
||||||
search_path="text",
|
|
||||||
ipc_cluster_selections=cluster_dicts,
|
|
||||||
)
|
|
||||||
await enrich_patents_classifications([item.patent for item in scored], ipc_search)
|
|
||||||
|
|
||||||
if not scored:
|
|
||||||
return PatentsByKeywordsResponse(
|
|
||||||
patent_count=0,
|
|
||||||
patents=[],
|
|
||||||
mapping_status="no_patents_found",
|
|
||||||
diagnostics=diagnostics,
|
|
||||||
)
|
|
||||||
|
|
||||||
return PatentsByKeywordsResponse(
|
|
||||||
patent_count=len(scored),
|
|
||||||
patents=scored,
|
|
||||||
mapping_status=mapping_status,
|
|
||||||
diagnostics=diagnostics,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
async def get_patents_by_keywords(
|
async def get_patents_by_keywords(
|
||||||
request: PatentsByKeywordsRequest,
|
request: PatentsByKeywordsRequest,
|
||||||
*,
|
*,
|
||||||
@@ -1528,21 +1117,18 @@ async def get_patents_by_keywords(
|
|||||||
)
|
)
|
||||||
logger.info(
|
logger.info(
|
||||||
"Keyword patent search: no IPC search terms for keywords %s "
|
"Keyword patent search: no IPC search terms for keywords %s "
|
||||||
"(mapping_status=%s) — trying keyword text search",
|
"(mapping_status=%s)",
|
||||||
[item.keyword for item in search_keywords],
|
[item.keyword for item in search_keywords],
|
||||||
mapping_status,
|
mapping_status,
|
||||||
)
|
)
|
||||||
return await _search_patents_text_search(
|
return PatentsByKeywordsResponse(
|
||||||
client=client,
|
patent_count=0,
|
||||||
queries=queries,
|
patents=[],
|
||||||
ipc_search=ipc_search,
|
|
||||||
resolver=resolver,
|
|
||||||
search_keywords=search_keywords,
|
|
||||||
keyword_topic_ids=keyword_topic_ids,
|
|
||||||
keyword_subfield_names=keyword_subfield_names,
|
|
||||||
keyword_soft_field_names=keyword_soft_field_names,
|
|
||||||
mapping_status=mapping_status,
|
mapping_status=mapping_status,
|
||||||
ipc_cluster_selections=cluster_dicts,
|
diagnostics=_empty_diagnostics(
|
||||||
|
search_path="none",
|
||||||
|
ipc_cluster_selections=cluster_dicts,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
text_search_terms = _text_search_terms(search_keywords)
|
text_search_terms = _text_search_terms(search_keywords)
|
||||||
@@ -1594,31 +1180,11 @@ async def get_patents_by_keywords(
|
|||||||
diagnostics=diagnostics,
|
diagnostics=diagnostics,
|
||||||
)
|
)
|
||||||
|
|
||||||
if not _TEXT_SEARCH_AFTER_EMPTY_IPC:
|
return PatentsByKeywordsResponse(
|
||||||
return PatentsByKeywordsResponse(
|
patent_count=0,
|
||||||
patent_count=0,
|
patents=[],
|
||||||
patents=[],
|
mapping_status="no_patents_found",
|
||||||
mapping_status="no_patents_found",
|
diagnostics=diagnostics,
|
||||||
diagnostics=diagnostics,
|
|
||||||
)
|
|
||||||
|
|
||||||
logger.info(
|
|
||||||
"Keyword patent search: IPC path yielded no scored patents — "
|
|
||||||
"trying keyword text search (policy=_TEXT_SEARCH_AFTER_EMPTY_IPC)"
|
|
||||||
)
|
|
||||||
return await _search_patents_text_search(
|
|
||||||
client=client,
|
|
||||||
queries=queries,
|
|
||||||
ipc_search=ipc_search,
|
|
||||||
resolver=resolver,
|
|
||||||
search_keywords=search_keywords,
|
|
||||||
keyword_topic_ids=keyword_topic_ids,
|
|
||||||
keyword_subfield_names=keyword_subfield_names,
|
|
||||||
keyword_soft_field_names=keyword_soft_field_names,
|
|
||||||
# IPC was selected but produced no usable hits; UI treats this like
|
|
||||||
# uncertain IPC evidence and labels patents via text_retrieval.
|
|
||||||
mapping_status="uncertain",
|
|
||||||
ipc_cluster_selections=cluster_dicts,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -46,19 +46,12 @@ _USPTO_SOURCE_FIELDS = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
_MIN_MATCH_TERM_LEN = 4
|
_MIN_MATCH_TERM_LEN = 4
|
||||||
_MIN_TEXT_PHRASE_LEN = 3
|
|
||||||
|
|
||||||
# Prefer concrete group/subgroup hits over broad subclass prefixes.
|
# Prefer concrete group/subgroup hits over broad subclass prefixes.
|
||||||
_BOOST_SUBGROUP = 4.0
|
_BOOST_SUBGROUP = 4.0
|
||||||
_BOOST_MAIN_GROUP = 2.5
|
_BOOST_MAIN_GROUP = 2.5
|
||||||
_BOOST_SUBCLASS = 1.0
|
_BOOST_SUBCLASS = 1.0
|
||||||
|
|
||||||
# Text search: prefer exact phrases in title over abstract / loose match.
|
|
||||||
_BOOST_TEXT_PHRASE_TITLE = 5.0
|
|
||||||
_BOOST_TEXT_PHRASE_ABSTRACT = 3.0
|
|
||||||
_BOOST_TEXT_MATCH_TITLE = 1.5
|
|
||||||
_BOOST_TEXT_MATCH_ABSTRACT = 1.0
|
|
||||||
|
|
||||||
|
|
||||||
def _add_term_boost(weights: dict[str, float], term: str, boost: float) -> None:
|
def _add_term_boost(weights: dict[str, float], term: str, boost: float) -> None:
|
||||||
cleaned = term.strip()
|
cleaned = term.strip()
|
||||||
@@ -157,76 +150,6 @@ def _ipc_match_clauses(field: str, term_boosts: dict[str, float]) -> list[dict[s
|
|||||||
return clauses
|
return clauses
|
||||||
|
|
||||||
|
|
||||||
def _normalize_text_phrases(phrases: list[str]) -> list[str]:
|
|
||||||
cleaned: list[str] = []
|
|
||||||
seen: set[str] = set()
|
|
||||||
for phrase in phrases:
|
|
||||||
value = " ".join((phrase or "").strip().split())
|
|
||||||
if len(value) < _MIN_TEXT_PHRASE_LEN:
|
|
||||||
continue
|
|
||||||
key = value.casefold()
|
|
||||||
if key in seen:
|
|
||||||
continue
|
|
||||||
seen.add(key)
|
|
||||||
cleaned.append(value)
|
|
||||||
return cleaned
|
|
||||||
|
|
||||||
|
|
||||||
def _text_match_clauses(
|
|
||||||
phrases: list[str],
|
|
||||||
*,
|
|
||||||
title_fields: tuple[str, ...],
|
|
||||||
abstract_field: str,
|
|
||||||
) -> list[dict[str, Any]]:
|
|
||||||
"""Build title/abstract should-clauses with phrase boosts over loose match."""
|
|
||||||
clauses: list[dict[str, Any]] = []
|
|
||||||
for phrase in _normalize_text_phrases(phrases):
|
|
||||||
for field in title_fields:
|
|
||||||
clauses.append(
|
|
||||||
{
|
|
||||||
"match_phrase": {
|
|
||||||
field: {
|
|
||||||
"query": phrase,
|
|
||||||
"boost": _BOOST_TEXT_PHRASE_TITLE,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
clauses.append(
|
|
||||||
{
|
|
||||||
"match": {
|
|
||||||
field: {
|
|
||||||
"query": phrase,
|
|
||||||
"operator": "and",
|
|
||||||
"boost": _BOOST_TEXT_MATCH_TITLE,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
clauses.append(
|
|
||||||
{
|
|
||||||
"match_phrase": {
|
|
||||||
abstract_field: {
|
|
||||||
"query": phrase,
|
|
||||||
"boost": _BOOST_TEXT_PHRASE_ABSTRACT,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
clauses.append(
|
|
||||||
{
|
|
||||||
"match": {
|
|
||||||
abstract_field: {
|
|
||||||
"query": phrase,
|
|
||||||
"operator": "and",
|
|
||||||
"boost": _BOOST_TEXT_MATCH_ABSTRACT,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
return clauses
|
|
||||||
|
|
||||||
|
|
||||||
class IpcPatentSearchQueries:
|
class IpcPatentSearchQueries:
|
||||||
def epo_query_by_ipc_terms(
|
def epo_query_by_ipc_terms(
|
||||||
self,
|
self,
|
||||||
@@ -299,55 +222,3 @@ class IpcPatentSearchQueries:
|
|||||||
size: int = DEFAULT_SEARCH_SIZE,
|
size: int = DEFAULT_SEARCH_SIZE,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
return self.uspto_query_by_ipc_terms(_merge_term_boosts(symbols), size=size)
|
return self.uspto_query_by_ipc_terms(_merge_term_boosts(symbols), size=size)
|
||||||
|
|
||||||
def epo_query_by_text_phrases(
|
|
||||||
self,
|
|
||||||
phrases: list[str],
|
|
||||||
size: int = DEFAULT_SEARCH_SIZE,
|
|
||||||
) -> dict[str, Any]:
|
|
||||||
should = _text_match_clauses(
|
|
||||||
phrases,
|
|
||||||
title_fields=("title_en", "title_de"),
|
|
||||||
abstract_field="abstract",
|
|
||||||
)
|
|
||||||
query: dict[str, Any] = (
|
|
||||||
{"match_none": {}}
|
|
||||||
if not should
|
|
||||||
else {"bool": {"should": should, "minimum_should_match": 1}}
|
|
||||||
)
|
|
||||||
return {
|
|
||||||
"size": size,
|
|
||||||
"track_total_hits": True,
|
|
||||||
"sort": [
|
|
||||||
{"_score": {"order": "desc"}},
|
|
||||||
{"date_publication": {"order": "desc", "missing": "_last"}},
|
|
||||||
],
|
|
||||||
"_source": _PATENT_SOURCE_FIELDS,
|
|
||||||
"query": query,
|
|
||||||
}
|
|
||||||
|
|
||||||
def uspto_query_by_text_phrases(
|
|
||||||
self,
|
|
||||||
phrases: list[str],
|
|
||||||
size: int = DEFAULT_SEARCH_SIZE,
|
|
||||||
) -> dict[str, Any]:
|
|
||||||
should = _text_match_clauses(
|
|
||||||
phrases,
|
|
||||||
title_fields=("title",),
|
|
||||||
abstract_field="abstract",
|
|
||||||
)
|
|
||||||
query: dict[str, Any] = (
|
|
||||||
{"match_none": {}}
|
|
||||||
if not should
|
|
||||||
else {"bool": {"should": should, "minimum_should_match": 1}}
|
|
||||||
)
|
|
||||||
return {
|
|
||||||
"size": size,
|
|
||||||
"track_total_hits": True,
|
|
||||||
"sort": [
|
|
||||||
{"_score": {"order": "desc"}},
|
|
||||||
{"publication_date": {"order": "desc", "missing": "_last"}},
|
|
||||||
],
|
|
||||||
"_source": _USPTO_SOURCE_FIELDS,
|
|
||||||
"query": query,
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -10,21 +10,17 @@ from inse.patents.authors.ipc_openalex_mapping import MappedOpenAlexTopic
|
|||||||
from inse.patents.common import model
|
from inse.patents.common import model
|
||||||
from inse.patents.keywords.logic import (
|
from inse.patents.keywords.logic import (
|
||||||
TopicEvidence,
|
TopicEvidence,
|
||||||
_aggregate_subclass_clusters,
|
|
||||||
_collect_keyword_text_evidence,
|
|
||||||
_compute_final_score,
|
_compute_final_score,
|
||||||
_compute_topic_evidence,
|
_compute_topic_evidence,
|
||||||
_exact_topic_or_subfield_match,
|
|
||||||
_filter_keywords_for_patent_search,
|
_filter_keywords_for_patent_search,
|
||||||
_ipc_hierarchy_quality,
|
_ipc_hierarchy_quality,
|
||||||
_keyword_is_patent_searchable,
|
_keyword_is_patent_searchable,
|
||||||
_keyword_text_passes_relevance_gate,
|
|
||||||
_keyword_text_score,
|
|
||||||
_patent_passes_relevance_gate,
|
_patent_passes_relevance_gate,
|
||||||
_patent_search_terms,
|
_patent_search_terms,
|
||||||
_score_ipc_match,
|
_score_ipc_match,
|
||||||
_score_patent,
|
_score_patent,
|
||||||
_select_dominant_clusters,
|
_select_dominant_clusters,
|
||||||
|
_aggregate_subclass_clusters,
|
||||||
_term_from_ipc_match,
|
_term_from_ipc_match,
|
||||||
_text_overlap_score,
|
_text_overlap_score,
|
||||||
_text_search_terms,
|
_text_search_terms,
|
||||||
@@ -34,10 +30,6 @@ from inse.patents.keywords.logic import (
|
|||||||
get_patents_by_keywords,
|
get_patents_by_keywords,
|
||||||
select_ipc_matches_by_cluster_mass,
|
select_ipc_matches_by_cluster_mass,
|
||||||
)
|
)
|
||||||
from inse.patents.keywords.model import (
|
|
||||||
KeywordPatentSearchItem,
|
|
||||||
PatentsByKeywordsRequest,
|
|
||||||
)
|
|
||||||
from inse.patents.keywords.reverse_lookup import (
|
from inse.patents.keywords.reverse_lookup import (
|
||||||
IpcCodeMatch,
|
IpcCodeMatch,
|
||||||
_dedupe_ipc_matches,
|
_dedupe_ipc_matches,
|
||||||
@@ -45,6 +37,7 @@ from inse.patents.keywords.reverse_lookup import (
|
|||||||
_weighted_score,
|
_weighted_score,
|
||||||
clear_reverse_lookup_caches,
|
clear_reverse_lookup_caches,
|
||||||
)
|
)
|
||||||
|
from inse.patents.keywords.model import KeywordPatentSearchItem, PatentsByKeywordsRequest
|
||||||
from inse.patents.keywords.search_queries import (
|
from inse.patents.keywords.search_queries import (
|
||||||
IpcPatentSearchQueries,
|
IpcPatentSearchQueries,
|
||||||
_search_terms_for_symbol,
|
_search_terms_for_symbol,
|
||||||
@@ -646,132 +639,6 @@ def test_text_overlap_score_uses_word_boundaries_not_substrings() -> None:
|
|||||||
assert _text_overlap_score(patent, ["chemistry", "organic"]) == 0.0
|
assert _text_overlap_score(patent, ["chemistry", "organic"]) == 0.0
|
||||||
|
|
||||||
|
|
||||||
def test_fallback_rejects_mechanical_patent_for_organic_chemistry() -> None:
|
|
||||||
"""Soft field / loose words must not accept a mechanical separator patent."""
|
|
||||||
patent = model.PatentEntry(
|
|
||||||
patent_id="EP-MECH",
|
|
||||||
source="EPO",
|
|
||||||
title=(
|
|
||||||
"Rotating machine for separating materials in different "
|
|
||||||
"states of aggregation"
|
|
||||||
),
|
|
||||||
abstract="Apparatus for mechanical separation of materials.",
|
|
||||||
ipc=["B01D45/12"],
|
|
||||||
)
|
|
||||||
phrases = ["Organic Chemistry", "organische Chemie"]
|
|
||||||
terms = ["organic", "chemistry", "organische", "chemie"]
|
|
||||||
evidence = _collect_keyword_text_evidence(patent, phrases, terms)
|
|
||||||
|
|
||||||
assert evidence.phrase_in_title is False
|
|
||||||
assert evidence.phrase_in_abstract is False
|
|
||||||
assert evidence.full_token_match is False
|
|
||||||
assert evidence.matched_phrases == []
|
|
||||||
assert evidence.matched_words == []
|
|
||||||
|
|
||||||
field_only = TopicEvidence(match_kind="compatible_field", score=0.3)
|
|
||||||
assert not _keyword_text_passes_relevance_gate(
|
|
||||||
evidence,
|
|
||||||
topic_evidence=field_only,
|
|
||||||
).accepted
|
|
||||||
exact = TopicEvidence(match_kind="topic_id", score=1.0)
|
|
||||||
assert not _keyword_text_passes_relevance_gate(
|
|
||||||
evidence,
|
|
||||||
topic_evidence=exact,
|
|
||||||
).accepted
|
|
||||||
|
|
||||||
|
|
||||||
def test_fallback_accepts_strong_phrase_or_exact_topic_with_full_tokens() -> None:
|
|
||||||
phrase_patent = model.PatentEntry(
|
|
||||||
patent_id="EP-PHRASE",
|
|
||||||
source="EPO",
|
|
||||||
title="Process for organic chemistry synthesis",
|
|
||||||
abstract="Catalytic reactions.",
|
|
||||||
)
|
|
||||||
phrases = ["organic chemistry"]
|
|
||||||
terms = ["organic", "chemistry"]
|
|
||||||
evidence = _collect_keyword_text_evidence(phrase_patent, phrases, terms)
|
|
||||||
assert evidence.phrase_in_title is True
|
|
||||||
assert evidence.text_match_kind == "phrase_title"
|
|
||||||
assert _keyword_text_score(evidence) == 1.0
|
|
||||||
assert _keyword_text_passes_relevance_gate(
|
|
||||||
evidence,
|
|
||||||
topic_evidence=TopicEvidence(match_kind="none", score=0.0),
|
|
||||||
).accepted
|
|
||||||
|
|
||||||
full_token_patent = model.PatentEntry(
|
|
||||||
patent_id="EP-WORDS",
|
|
||||||
source="EPO",
|
|
||||||
title="Catalytic organic synthesis method",
|
|
||||||
abstract="Uses chemistry laboratory techniques.",
|
|
||||||
)
|
|
||||||
full_evidence = _collect_keyword_text_evidence(
|
|
||||||
full_token_patent,
|
|
||||||
phrases,
|
|
||||||
terms,
|
|
||||||
)
|
|
||||||
assert full_evidence.phrase_in_title is False
|
|
||||||
assert full_evidence.phrase_in_abstract is False
|
|
||||||
assert full_evidence.full_token_match is True
|
|
||||||
assert not _keyword_text_passes_relevance_gate(
|
|
||||||
full_evidence,
|
|
||||||
topic_evidence=TopicEvidence(match_kind="none", score=0.0),
|
|
||||||
).accepted
|
|
||||||
assert _keyword_text_passes_relevance_gate(
|
|
||||||
full_evidence,
|
|
||||||
topic_evidence=TopicEvidence(match_kind="topic_id", score=1.0),
|
|
||||||
).accepted
|
|
||||||
|
|
||||||
partial_patent = model.PatentEntry(
|
|
||||||
patent_id="EP-PARTIAL",
|
|
||||||
source="EPO",
|
|
||||||
title="Organic polymer blend",
|
|
||||||
abstract="Industrial materials processing.",
|
|
||||||
)
|
|
||||||
partial_evidence = _collect_keyword_text_evidence(
|
|
||||||
partial_patent,
|
|
||||||
phrases,
|
|
||||||
terms,
|
|
||||||
)
|
|
||||||
assert partial_evidence.partial_token_match is True
|
|
||||||
assert partial_evidence.full_token_match is False
|
|
||||||
decision = _keyword_text_passes_relevance_gate(
|
|
||||||
partial_evidence,
|
|
||||||
topic_evidence=TopicEvidence(match_kind="topic_id", score=1.0),
|
|
||||||
)
|
|
||||||
assert not decision.accepted
|
|
||||||
assert decision.reason == "exact_topic_with_partial_tokens_only"
|
|
||||||
|
|
||||||
assert _exact_topic_or_subfield_match(
|
|
||||||
[
|
|
||||||
MappedOpenAlexTopic(
|
|
||||||
topic_id="https://openalex.org/TORG",
|
|
||||||
topic_display_name="Organic Chemistry",
|
|
||||||
subfield_name="Organic Chemistry",
|
|
||||||
field_name="Chemistry",
|
|
||||||
)
|
|
||||||
],
|
|
||||||
frozenset({"TORG"}),
|
|
||||||
frozenset({"organic chemistry"}),
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def test_token_match_rejects_machine_inside_micromachined() -> None:
|
|
||||||
patent = model.PatentEntry(
|
|
||||||
patent_id="EP-MICRO",
|
|
||||||
source="EPO",
|
|
||||||
title="Micromachined sensor device",
|
|
||||||
abstract="Fabrication of micromachined structures.",
|
|
||||||
)
|
|
||||||
assert _text_overlap_score(patent, ["machine", "learning"]) == 0.0
|
|
||||||
evidence = _collect_keyword_text_evidence(
|
|
||||||
patent,
|
|
||||||
["Machine Learning"],
|
|
||||||
["machine", "learning"],
|
|
||||||
)
|
|
||||||
assert evidence.matched_words == []
|
|
||||||
assert evidence.full_token_match is False
|
|
||||||
|
|
||||||
|
|
||||||
def test_patent_passes_relevance_gate_with_text_but_no_topics() -> None:
|
def test_patent_passes_relevance_gate_with_text_but_no_topics() -> None:
|
||||||
patent = model.PatentEntry(
|
patent = model.PatentEntry(
|
||||||
patent_id="EP1",
|
patent_id="EP1",
|
||||||
@@ -914,8 +781,7 @@ def test_get_patents_by_keywords_uses_symbol_queries() -> None:
|
|||||||
uspto_symbols.assert_called_once()
|
uspto_symbols.assert_called_once()
|
||||||
assert epo_symbols.call_args.args[0][0] == "C07C243/08"
|
assert epo_symbols.call_args.args[0][0] == "C07C243/08"
|
||||||
assert "C07C" in epo_symbols.call_args.args[0]
|
assert "C07C" in epo_symbols.call_args.args[0]
|
||||||
# IPC search returns empty → text fallback also queries EPO/USPTO.
|
assert captured == ["epo", "uspto"]
|
||||||
assert captured == ["epo", "uspto", "epo", "uspto"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_text_search_terms_include_topic_metadata() -> None:
|
def test_text_search_terms_include_topic_metadata() -> None:
|
||||||
@@ -993,64 +859,84 @@ def test_epo_and_uspto_queries_boost_specific_symbols_over_subclass() -> None:
|
|||||||
assert uspto["sort"][0] == {"_score": {"order": "desc"}}
|
assert uspto["sort"][0] == {"_score": {"order": "desc"}}
|
||||||
|
|
||||||
|
|
||||||
def test_text_queries_prefer_phrase_match_in_title() -> None:
|
def test_technical_search_failure_returns_search_error_not_no_patents_found() -> None:
|
||||||
queries = IpcPatentSearchQueries()
|
request = PatentsByKeywordsRequest(
|
||||||
epo = queries.epo_query_by_text_phrases(["organic chemistry"])
|
keywords=[
|
||||||
uspto = queries.uspto_query_by_text_phrases(["organic chemistry"])
|
KeywordPatentSearchItem(
|
||||||
|
keyword="organische Chemie",
|
||||||
epo_should = epo["query"]["bool"]["should"]
|
keyword_level="coarse",
|
||||||
uspto_should = uspto["query"]["bool"]["should"]
|
topic_id="https://openalex.org/TORG",
|
||||||
|
topic_display_name="Organic Chemistry",
|
||||||
def clause_boost(clauses: list[dict], kind: str, field: str) -> float | None:
|
field_name="Chemistry",
|
||||||
for clause in clauses:
|
relevance_score=1.0,
|
||||||
payload = clause.get(kind, {}).get(field)
|
)
|
||||||
if isinstance(payload, dict) and payload.get("query") == "organic chemistry":
|
]
|
||||||
return float(payload.get("boost", 1.0))
|
|
||||||
return None
|
|
||||||
|
|
||||||
assert clause_boost(epo_should, "match_phrase", "title_en") == 5.0
|
|
||||||
assert clause_boost(epo_should, "match_phrase", "abstract") == 3.0
|
|
||||||
assert clause_boost(epo_should, "match", "title_en") == 1.5
|
|
||||||
assert clause_boost(uspto_should, "match_phrase", "title") == 5.0
|
|
||||||
assert epo["sort"][0] == {"_score": {"order": "desc"}}
|
|
||||||
|
|
||||||
|
|
||||||
def test_uncertain_mapping_uses_text_fallback_not_empty_list() -> None:
|
|
||||||
"""Fragmented IPC abstention must fall back to title/abstract search."""
|
|
||||||
patent = model.PatentEntry(
|
|
||||||
patent_id="EP123",
|
|
||||||
source="EPO",
|
|
||||||
title="Process for organic chemistry synthesis",
|
|
||||||
abstract="A catalytic method in organic chemistry.",
|
|
||||||
publication_date="20240101",
|
|
||||||
ipc=["C07C243/08"],
|
|
||||||
cpc=[],
|
|
||||||
)
|
)
|
||||||
|
ipc_matches = [
|
||||||
|
IpcCodeMatch(
|
||||||
|
"subgroup",
|
||||||
|
"C07C243/08",
|
||||||
|
0.90,
|
||||||
|
"organische Chemie",
|
||||||
|
"topic",
|
||||||
|
"TORG",
|
||||||
|
)
|
||||||
|
]
|
||||||
|
|
||||||
async def fake_search_epo(query):
|
with patch(
|
||||||
assert "match_phrase" in str(query) or "title_en" in str(query)
|
"inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes",
|
||||||
return {
|
new=AsyncMock(return_value=ipc_matches),
|
||||||
"hits": {
|
), patch(
|
||||||
"hits": [
|
"inse.patents.keywords.logic.BasePatentSearchClient.search_epo",
|
||||||
{
|
new=AsyncMock(side_effect=httpx.HTTPError("boom")),
|
||||||
"_source": {
|
), patch(
|
||||||
"doc_number": "123",
|
"inse.patents.keywords.logic.BasePatentSearchClient.search_uspto",
|
||||||
"country": "EP",
|
new=AsyncMock(return_value={"hits": {"hits": []}}),
|
||||||
"kind": "A1",
|
):
|
||||||
"date_publication": "20240101",
|
response = asyncio.run(get_patents_by_keywords(request))
|
||||||
"title_en": patent.title,
|
|
||||||
"abstract": patent.abstract,
|
|
||||||
"ipc": patent.ipc,
|
|
||||||
"cpc": [],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async def fake_search_uspto(query):
|
assert response.mapping_status == "search_error"
|
||||||
return {"hits": {"hits": []}}
|
assert response.patent_count == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_ipc_search_terms_returns_without_text_fallback() -> None:
|
||||||
|
"""Without usable IPC symbols the search abstains — no title/abstract path."""
|
||||||
|
request = PatentsByKeywordsRequest(
|
||||||
|
keywords=[
|
||||||
|
KeywordPatentSearchItem(
|
||||||
|
keyword="organische Chemie",
|
||||||
|
keyword_level="coarse",
|
||||||
|
topic_id="https://openalex.org/TORG",
|
||||||
|
topic_display_name="Organic Chemistry",
|
||||||
|
field_name="Chemistry",
|
||||||
|
relevance_score=1.0,
|
||||||
|
)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
search_epo = AsyncMock(return_value={"hits": {"hits": []}})
|
||||||
|
search_uspto = AsyncMock(return_value={"hits": {"hits": []}})
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes",
|
||||||
|
new=AsyncMock(return_value=[]),
|
||||||
|
), patch(
|
||||||
|
"inse.patents.keywords.logic.BasePatentSearchClient.search_epo",
|
||||||
|
new=search_epo,
|
||||||
|
), patch(
|
||||||
|
"inse.patents.keywords.logic.BasePatentSearchClient.search_uspto",
|
||||||
|
new=search_uspto,
|
||||||
|
):
|
||||||
|
response = asyncio.run(get_patents_by_keywords(request))
|
||||||
|
|
||||||
|
assert response.mapping_status == "no_mapping"
|
||||||
|
assert response.patent_count == 0
|
||||||
|
assert response.patents == []
|
||||||
|
search_epo.assert_not_called()
|
||||||
|
search_uspto.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
def test_uncertain_ipc_cluster_abstention_returns_without_text_fallback() -> None:
|
||||||
|
"""Fragmented IPC mapping abstains without falling back to text retrieval."""
|
||||||
fragmented = [
|
fragmented = [
|
||||||
IpcCodeMatch(
|
IpcCodeMatch(
|
||||||
"subgroup",
|
"subgroup",
|
||||||
@@ -1074,113 +960,31 @@ def test_uncertain_mapping_uses_text_fallback_not_empty_list() -> None:
|
|||||||
)
|
)
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
search_epo = AsyncMock(return_value={"hits": {"hits": []}})
|
||||||
|
|
||||||
with patch(
|
with patch(
|
||||||
"inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes",
|
"inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes",
|
||||||
new=AsyncMock(return_value=fragmented),
|
new=AsyncMock(return_value=fragmented),
|
||||||
), patch(
|
), patch(
|
||||||
"inse.patents.keywords.logic.BasePatentSearchClient.search_epo",
|
"inse.patents.keywords.logic.BasePatentSearchClient.search_epo",
|
||||||
new=AsyncMock(side_effect=fake_search_epo),
|
new=search_epo,
|
||||||
), patch(
|
|
||||||
"inse.patents.keywords.logic.BasePatentSearchClient.search_uspto",
|
|
||||||
new=AsyncMock(side_effect=fake_search_uspto),
|
|
||||||
), patch(
|
|
||||||
"inse.patents.keywords.logic.PatentOpenAlexMappingResolver.resolve_topics_for_patents",
|
|
||||||
new=AsyncMock(return_value={}),
|
|
||||||
), patch(
|
|
||||||
"inse.patents.keywords.logic.enrich_patents_classifications",
|
|
||||||
new=AsyncMock(),
|
|
||||||
), patch.object(
|
|
||||||
IpcPatentSearchQueries,
|
|
||||||
"epo_query_by_text_phrases",
|
|
||||||
wraps=IpcPatentSearchQueries().epo_query_by_text_phrases,
|
|
||||||
) as epo_text:
|
|
||||||
response = asyncio.run(get_patents_by_keywords(request))
|
|
||||||
|
|
||||||
epo_text.assert_called_once()
|
|
||||||
assert response.mapping_status == "uncertain"
|
|
||||||
assert response.patent_count == 1
|
|
||||||
assert response.patents[0].text_retrieval is True
|
|
||||||
assert response.patents[0].ipc_score == 0.0
|
|
||||||
assert response.patents[0].text_score > 0.0
|
|
||||||
assert response.patents[0].matched_ipc_symbols == []
|
|
||||||
assert response.patents[0].keyword_evidence is not None
|
|
||||||
assert response.patents[0].keyword_evidence.phrase_in_title is True
|
|
||||||
assert response.patents[0].keyword_evidence.text_match_kind == "phrase_title"
|
|
||||||
|
|
||||||
|
|
||||||
def test_text_fallback_empty_yields_no_patents_found() -> None:
|
|
||||||
request = PatentsByKeywordsRequest(
|
|
||||||
keywords=[
|
|
||||||
KeywordPatentSearchItem(
|
|
||||||
keyword="organische Chemie",
|
|
||||||
keyword_level="coarse",
|
|
||||||
topic_id="https://openalex.org/TORG",
|
|
||||||
topic_display_name="Organic Chemistry",
|
|
||||||
field_name="Chemistry",
|
|
||||||
relevance_score=1.0,
|
|
||||||
)
|
|
||||||
]
|
|
||||||
)
|
|
||||||
|
|
||||||
with patch(
|
|
||||||
"inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes",
|
|
||||||
new=AsyncMock(return_value=[]),
|
|
||||||
), patch(
|
|
||||||
"inse.patents.keywords.logic.BasePatentSearchClient.search_epo",
|
|
||||||
new=AsyncMock(return_value={"hits": {"hits": []}}),
|
|
||||||
), patch(
|
), patch(
|
||||||
"inse.patents.keywords.logic.BasePatentSearchClient.search_uspto",
|
"inse.patents.keywords.logic.BasePatentSearchClient.search_uspto",
|
||||||
new=AsyncMock(return_value={"hits": {"hits": []}}),
|
new=AsyncMock(return_value={"hits": {"hits": []}}),
|
||||||
), patch(
|
|
||||||
"inse.patents.keywords.logic.PatentOpenAlexMappingResolver.resolve_topics_for_patents",
|
|
||||||
new=AsyncMock(return_value={}),
|
|
||||||
), patch(
|
|
||||||
"inse.patents.keywords.logic.enrich_patents_classifications",
|
|
||||||
new=AsyncMock(),
|
|
||||||
):
|
):
|
||||||
response = asyncio.run(get_patents_by_keywords(request))
|
response = asyncio.run(get_patents_by_keywords(request))
|
||||||
|
|
||||||
assert response.mapping_status == "no_patents_found"
|
assert response.mapping_status == "uncertain"
|
||||||
assert response.patent_count == 0
|
assert response.patent_count == 0
|
||||||
assert response.patents == []
|
assert response.patents == []
|
||||||
|
search_epo.assert_not_called()
|
||||||
|
|
||||||
def test_technical_search_failure_returns_search_error_not_no_patents_found() -> None:
|
|
||||||
request = PatentsByKeywordsRequest(
|
|
||||||
keywords=[
|
|
||||||
KeywordPatentSearchItem(
|
|
||||||
keyword="organische Chemie",
|
|
||||||
keyword_level="coarse",
|
|
||||||
topic_id="https://openalex.org/TORG",
|
|
||||||
topic_display_name="Organic Chemistry",
|
|
||||||
field_name="Chemistry",
|
|
||||||
relevance_score=1.0,
|
|
||||||
)
|
|
||||||
]
|
|
||||||
)
|
|
||||||
|
|
||||||
with patch(
|
|
||||||
"inse.patents.keywords.logic.KeywordIpcReverseLookup.lookup_ipc_codes",
|
|
||||||
new=AsyncMock(return_value=[]),
|
|
||||||
), patch(
|
|
||||||
"inse.patents.keywords.logic.BasePatentSearchClient.search_epo",
|
|
||||||
new=AsyncMock(side_effect=httpx.HTTPError("boom")),
|
|
||||||
), patch(
|
|
||||||
"inse.patents.keywords.logic.BasePatentSearchClient.search_uspto",
|
|
||||||
new=AsyncMock(return_value={"hits": {"hits": []}}),
|
|
||||||
):
|
|
||||||
response = asyncio.run(get_patents_by_keywords(request))
|
|
||||||
|
|
||||||
assert response.mapping_status == "search_error"
|
|
||||||
assert response.patent_count == 0
|
|
||||||
|
|
||||||
|
|
||||||
def test_json_lookup_returns_empty_without_mapping(monkeypatch) -> None:
|
def test_json_lookup_returns_empty_without_mapping(monkeypatch) -> None:
|
||||||
clear_reverse_lookup_caches()
|
clear_reverse_lookup_caches()
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
"inse.patents.keywords.reverse_lookup.load_patents_openalex_keywords_json",
|
"inse.patents.keywords.reverse_lookup.load_patents_openalex_keywords_json",
|
||||||
dict,
|
lambda: {},
|
||||||
)
|
)
|
||||||
clear_reverse_lookup_caches()
|
clear_reverse_lookup_caches()
|
||||||
|
|
||||||
|
|||||||
@@ -944,6 +944,7 @@ async def search_eu_cordis_projects(
|
|||||||
sort_by: str = "title",
|
sort_by: str = "title",
|
||||||
sort_direction: str = "asc",
|
sort_direction: str = "asc",
|
||||||
fuzzy: bool = False,
|
fuzzy: bool = False,
|
||||||
|
skip_enrichment: bool = False,
|
||||||
) -> EuCordisProjectSearchPage:
|
) -> EuCordisProjectSearchPage:
|
||||||
"""
|
"""
|
||||||
Generic EU CORDIS project search across FP7, H2020 and Horizon Europe.
|
Generic EU CORDIS project search across FP7, H2020 and Horizon Europe.
|
||||||
@@ -1015,6 +1016,14 @@ async def search_eu_cordis_projects(
|
|||||||
hits = response.get("hits", {}).get("hits", [])
|
hits = response.get("hits", {}).get("hits", [])
|
||||||
total = response.get("hits", {}).get("total", {}).get("value", 0)
|
total = response.get("hits", {}).get("total", {}).get("value", 0)
|
||||||
|
|
||||||
|
if skip_enrichment:
|
||||||
|
return EuCordisProjectSearchPage(
|
||||||
|
elements=[EuCordisProjectSummary.from_hit(hit) for hit in hits],
|
||||||
|
total=total,
|
||||||
|
page=page,
|
||||||
|
size=size,
|
||||||
|
)
|
||||||
|
|
||||||
project_ids_by_type: dict[EuCordisProjectType, list[str]] = defaultdict(list)
|
project_ids_by_type: dict[EuCordisProjectType, list[str]] = defaultdict(list)
|
||||||
|
|
||||||
for hit in hits:
|
for hit in hits:
|
||||||
@@ -1124,10 +1133,6 @@ async def get_eu_cordis_projects_funding_data(
|
|||||||
"track_total_hits": False,
|
"track_total_hits": False,
|
||||||
"_source": ["id", "startDate", "endDate", "ecMaxContribution"],
|
"_source": ["id", "startDate", "endDate", "ecMaxContribution"],
|
||||||
"query": query,
|
"query": query,
|
||||||
# "id" is unique per project and used elsewhere as a term-filter
|
|
||||||
# field, so it's mapped as keyword - safe + deterministic sort
|
|
||||||
# key for search_after pagination across an arbitrarily large
|
|
||||||
# result set.
|
|
||||||
"sort": [{"id": {"order": "asc", "unmapped_type": "keyword"}}],
|
"sort": [{"id": {"order": "asc", "unmapped_type": "keyword"}}],
|
||||||
}
|
}
|
||||||
if search_after is not None:
|
if search_after is not None:
|
||||||
@@ -1247,68 +1252,6 @@ async def get_openalex_author_ids_by_dois(
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
async def get_openalex_authors_for_cordis_project_ids(
|
|
||||||
project_ids: list[str],
|
|
||||||
) -> dict[str, AuthorPage]:
|
|
||||||
"""Returns a mapping of project_id -> AuthorPage for a batch of projects."""
|
|
||||||
if not project_ids:
|
|
||||||
return {}
|
|
||||||
|
|
||||||
query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}}
|
|
||||||
response = await elasticsearch.search(
|
|
||||||
query=query,
|
|
||||||
index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
|
|
||||||
cluster=ESCluster.INSE,
|
|
||||||
source=["projectID", "doi","qaProcessedDoi"],
|
|
||||||
size=10000,
|
|
||||||
)
|
|
||||||
dois_by_project: dict[str, set[str]] = {}
|
|
||||||
for hit in response.get("hits", {}).get("hits", []):
|
|
||||||
source = hit.get("_source", {})
|
|
||||||
pid = source.get("projectID")
|
|
||||||
doi = source.get("doi")
|
|
||||||
qa_processed_doi = source.get("qaProcessedDoi")
|
|
||||||
if pid:
|
|
||||||
dois_by_project.setdefault(pid, set())
|
|
||||||
if doi:
|
|
||||||
dois_by_project[pid].add(doi)
|
|
||||||
elif qa_processed_doi:
|
|
||||||
dois_by_project[pid].add(qa_processed_doi)
|
|
||||||
|
|
||||||
all_dois = list({doi for dois in dois_by_project.values() for doi in dois})
|
|
||||||
|
|
||||||
# single ES call for the whole batch, keyed by raw DOI
|
|
||||||
author_ids_by_doi = await get_openalex_author_ids_by_dois(dois=all_dois)
|
|
||||||
|
|
||||||
# aggregate per project, dedupe author_ids within a project
|
|
||||||
author_ids_by_project: dict[str, list[str]] = {}
|
|
||||||
for pid, dois in dois_by_project.items():
|
|
||||||
project_author_ids: set[str] = set()
|
|
||||||
for doi in dois:
|
|
||||||
project_author_ids.update(author_ids_by_doi.get(doi, []))
|
|
||||||
author_ids_by_project[pid] = list(project_author_ids)
|
|
||||||
|
|
||||||
# single ES call to fetch all Author objects across every project
|
|
||||||
all_author_ids = list({aid for ids in author_ids_by_project.values() for aid in ids})
|
|
||||||
|
|
||||||
author_page = await get_authors_by_ids(author_ids=all_author_ids)
|
|
||||||
authors_by_id = {author.id: author for author in author_page.elements}
|
|
||||||
|
|
||||||
# split the fetched authors back out per project
|
|
||||||
result: dict[str, AuthorPage] = {}
|
|
||||||
for pid in project_ids:
|
|
||||||
ids_for_project = author_ids_by_project.get(pid, [])
|
|
||||||
authors_for_project = [
|
|
||||||
authors_by_id[aid] for aid in ids_for_project if aid in authors_by_id
|
|
||||||
]
|
|
||||||
result[pid] = AuthorPage(
|
|
||||||
elements=authors_for_project,
|
|
||||||
total=len(authors_for_project),
|
|
||||||
page=0,
|
|
||||||
size=len(authors_for_project),
|
|
||||||
)
|
|
||||||
|
|
||||||
return result
|
|
||||||
|
|
||||||
async def get_openalex_authors_for_projects_ids(
|
async def get_openalex_authors_for_projects_ids(
|
||||||
project_ids_by_type: dict[EuCordisProjectType, list[str]],
|
project_ids_by_type: dict[EuCordisProjectType, list[str]],
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import logging
|
import logging
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
import inse.authors.v2.service as author_service
|
||||||
|
from inse.auth.model import AccessTokenMetadata
|
||||||
from inse.integrations import elasticsearch
|
from inse.integrations import elasticsearch
|
||||||
from inse.model import ESCluster, ESIndex
|
from inse.model import ESCluster, ESIndex
|
||||||
from inse.projects.model import EuCordisProjectType
|
from inse.projects.model import EuCordisProjectType
|
||||||
@@ -359,6 +360,53 @@ async def get_person_institutes(
|
|||||||
}
|
}
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
async def get_dfg_institutes_by_ids(
|
||||||
|
institute_ids: list[int],
|
||||||
|
) -> dict[str, dict]:
|
||||||
|
|
||||||
|
if not institute_ids:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
response = await elasticsearch.search(
|
||||||
|
index=ESIndex.DFG_INSTITUTES,
|
||||||
|
cluster=ESCluster.INSE,
|
||||||
|
body={
|
||||||
|
"size": len(institute_ids),
|
||||||
|
"_source": [
|
||||||
|
"institute_id",
|
||||||
|
"root_id",
|
||||||
|
"root_name_de",
|
||||||
|
"root_name_en",
|
||||||
|
"institute_name_de",
|
||||||
|
"institute_name_en",
|
||||||
|
"address_country_de",
|
||||||
|
"address_country_en",
|
||||||
|
],
|
||||||
|
"query": {
|
||||||
|
"terms": {
|
||||||
|
"_id": institute_ids,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
result = {}
|
||||||
|
|
||||||
|
for hit in response["hits"]["hits"]:
|
||||||
|
source = hit["_source"]
|
||||||
|
|
||||||
|
result[source["institute_id"]] = {
|
||||||
|
"institute_id": source["institute_id"],
|
||||||
|
"root_id": source.get("root_id"),
|
||||||
|
"root_name_de": source.get("root_name_de"),
|
||||||
|
"root_name_en": source.get("root_name_en"),
|
||||||
|
"institute_name_de": source.get("institute_name_de"),
|
||||||
|
"institute_name_en": source.get("institute_name_en"),
|
||||||
|
"address_country_de": source.get("address_country_de"),
|
||||||
|
"address_country_en": source.get("address_country_en"),
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
#EU Cordis Projects
|
#EU Cordis Projects
|
||||||
|
|
||||||
|
|||||||
@@ -254,8 +254,37 @@ class DfgProjectSummary(BaseModel):
|
|||||||
names = []
|
names = []
|
||||||
institutions = {}
|
institutions = {}
|
||||||
project_persons = []
|
project_persons = []
|
||||||
|
|
||||||
persons = source.get("persons", [])
|
persons = source.get("persons", [])
|
||||||
|
institutions_raw= source.get("institutions", [])
|
||||||
|
if isinstance(institutions_raw, list):
|
||||||
|
for institution in institutions_raw:
|
||||||
|
if not isinstance(institution, dict):
|
||||||
|
continue
|
||||||
|
|
||||||
|
institute_id = institution.get("institute_id")
|
||||||
|
if institute_id is not None:
|
||||||
|
institutions[f"institute:{institute_id}"] = DfgInstitutionSummary(
|
||||||
|
id=institute_id,
|
||||||
|
institute_name_de=institution.get("institute_name_de"),
|
||||||
|
institute_name_en=institution.get("institute_name_en"),
|
||||||
|
address_country_de=institution.get("address_country_de"),
|
||||||
|
address_country_en=institution.get("address_country_en"),
|
||||||
|
root_id=institution.get("root_id"),
|
||||||
|
root_name_de=institution.get("root_name_de"),
|
||||||
|
root_name_en=institution.get("root_name_en"),
|
||||||
|
)
|
||||||
|
root_id = institution.get("root_id")
|
||||||
|
if root_id is not None:
|
||||||
|
institutions[f"root:{root_id}"] = DfgInstitutionSummary(
|
||||||
|
id=root_id,
|
||||||
|
institute_name_de=institution.get("root_name_de"),
|
||||||
|
institute_name_en=institution.get("root_name_en"),
|
||||||
|
address_country_de=institution.get("address_country_de"),
|
||||||
|
address_country_en=institution.get("address_country_en"),
|
||||||
|
root_id=None,
|
||||||
|
root_name_de=None,
|
||||||
|
root_name_en=None,
|
||||||
|
)
|
||||||
|
|
||||||
if isinstance(persons, list):
|
if isinstance(persons, list):
|
||||||
for person in persons:
|
for person in persons:
|
||||||
@@ -266,35 +295,35 @@ class DfgProjectSummary(BaseModel):
|
|||||||
|
|
||||||
if full_name:
|
if full_name:
|
||||||
names.append(full_name.strip())
|
names.append(full_name.strip())
|
||||||
|
# previously we were creating institution objects for each person, but now we are using the institutions from the institutions_raw list
|
||||||
|
#institution = None
|
||||||
|
# if person.get("institute_id") is not None:
|
||||||
|
# institute = DfgInstitutionSummary(
|
||||||
|
# id=person["institute_id"],
|
||||||
|
# institute_name_de=person.get("institute_name_de"),
|
||||||
|
# institute_name_en=person.get("institute_name_en"),
|
||||||
|
# address_country_de=person.get("address_country_de"),
|
||||||
|
# address_country_en=person.get("address_country_en"),
|
||||||
|
# root_id=None,
|
||||||
|
# root_name_de=None,
|
||||||
|
# root_name_en=None,
|
||||||
|
# )
|
||||||
|
|
||||||
institution = None
|
# institutions[f"institute:{person['institute_id']}"] = institute
|
||||||
if person.get("institute_id") is not None:
|
|
||||||
institute = DfgInstitutionSummary(
|
|
||||||
id=person["institute_id"],
|
|
||||||
institute_name_de=person.get("institute_name_de"),
|
|
||||||
institute_name_en=person.get("institute_name_en"),
|
|
||||||
address_country_de=person.get("address_country_de"),
|
|
||||||
address_country_en=person.get("address_country_en"),
|
|
||||||
root_id=None,
|
|
||||||
root_name_de=None,
|
|
||||||
root_name_en=None,
|
|
||||||
)
|
|
||||||
|
|
||||||
institutions[f"institute:{person['institute_id']}"] = institute
|
# if person.get("root_id") is not None:
|
||||||
|
# root_institution = DfgInstitutionSummary(
|
||||||
|
# id=person["root_id"],
|
||||||
|
# institute_name_de=person.get("root_name_de"),
|
||||||
|
# institute_name_en=person.get("root_name_en"),
|
||||||
|
# address_country_de=person.get("address_country_de"),
|
||||||
|
# address_country_en=person.get("address_country_en"),
|
||||||
|
# root_id=None,
|
||||||
|
# root_name_de=None,
|
||||||
|
# root_name_en=None,
|
||||||
|
# )
|
||||||
|
|
||||||
if person.get("root_id") is not None:
|
# institutions[f"root:{person['root_id']}"] = root_institution
|
||||||
root_institution = DfgInstitutionSummary(
|
|
||||||
id=person["root_id"],
|
|
||||||
institute_name_de=person.get("root_name_de"),
|
|
||||||
institute_name_en=person.get("root_name_en"),
|
|
||||||
address_country_de=person.get("address_country_de"),
|
|
||||||
address_country_en=person.get("address_country_en"),
|
|
||||||
root_id=None,
|
|
||||||
root_name_de=None,
|
|
||||||
root_name_en=None,
|
|
||||||
)
|
|
||||||
|
|
||||||
institutions[f"root:{person['root_id']}"] = root_institution
|
|
||||||
|
|
||||||
if person.get("person_id") is not None:
|
if person.get("person_id") is not None:
|
||||||
project_persons.append(
|
project_persons.append(
|
||||||
@@ -305,7 +334,7 @@ class DfgProjectSummary(BaseModel):
|
|||||||
full_name=full_name,
|
full_name=full_name,
|
||||||
role_label_en=person.get("role_label_en"),
|
role_label_en=person.get("role_label_en"),
|
||||||
role_label_de=person.get("role_label_de"),
|
role_label_de=person.get("role_label_de"),
|
||||||
institution=institution,
|
institution=None,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
topics_raw = source.get("topics") or []
|
topics_raw = source.get("topics") or []
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ from inse.projects.logic import (
|
|||||||
get_openalex_topics_for_bund_projects,
|
get_openalex_topics_for_bund_projects,
|
||||||
get_openalex_topics_for_dfg_projects,
|
get_openalex_topics_for_dfg_projects,
|
||||||
get_person_ids_by_institution_ids,
|
get_person_ids_by_institution_ids,
|
||||||
|
get_dfg_institutes_by_ids,
|
||||||
get_person_institutes,
|
get_person_institutes,
|
||||||
)
|
)
|
||||||
from inse.projects.model import (
|
from inse.projects.model import (
|
||||||
@@ -194,7 +195,7 @@ async def get_cordis_eu_publications_by_dois(dois: list[str]):
|
|||||||
_type_: The retrieved publications.
|
_type_: The retrieved publications.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
query_dois = list({
|
query_dois = set({
|
||||||
variant
|
variant
|
||||||
for doi in dois
|
for doi in dois
|
||||||
for variant in (
|
for variant in (
|
||||||
@@ -210,8 +211,8 @@ async def get_cordis_eu_publications_by_dois(dois: list[str]):
|
|||||||
{
|
{
|
||||||
"bool": {
|
"bool": {
|
||||||
"should": [
|
"should": [
|
||||||
{"terms": {"doi": query_dois}},
|
{"terms": {"doi": list(query_dois)}},
|
||||||
{"terms": {"qaProcessedDoi": query_dois}},
|
{"terms": {"qaProcessedDoi": list(query_dois)}},
|
||||||
],
|
],
|
||||||
"minimum_should_match": 1,
|
"minimum_should_match": 1,
|
||||||
}
|
}
|
||||||
@@ -222,6 +223,7 @@ async def get_cordis_eu_publications_by_dois(dois: list[str]):
|
|||||||
|
|
||||||
response = await elasticsearch.search(
|
response = await elasticsearch.search(
|
||||||
query=query,
|
query=query,
|
||||||
|
size=10000,
|
||||||
index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
|
index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
|
||||||
cluster=ESCluster.INSE,
|
cluster=ESCluster.INSE,
|
||||||
)
|
)
|
||||||
@@ -263,7 +265,7 @@ async def get_dfg_publications_by_dois(dois: list[str]):
|
|||||||
_type_: The retrieved publications.
|
_type_: The retrieved publications.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
query_dois = list({
|
query_dois = set({
|
||||||
variant
|
variant
|
||||||
for doi in dois
|
for doi in dois
|
||||||
for variant in (
|
for variant in (
|
||||||
@@ -280,7 +282,7 @@ async def get_dfg_publications_by_dois(dois: list[str]):
|
|||||||
"query": {
|
"query": {
|
||||||
"terms": {
|
"terms": {
|
||||||
"publications.doi":
|
"publications.doi":
|
||||||
query_dois
|
list(query_dois)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -290,7 +292,7 @@ async def get_dfg_publications_by_dois(dois: list[str]):
|
|||||||
}
|
}
|
||||||
|
|
||||||
response = await elasticsearch.search(
|
response = await elasticsearch.search(
|
||||||
size=1000,
|
size=10000,
|
||||||
query=query,
|
query=query,
|
||||||
index=ESIndex.DFG_PROJECTS,
|
index=ESIndex.DFG_PROJECTS,
|
||||||
cluster=ESCluster.INSE,
|
cluster=ESCluster.INSE,
|
||||||
@@ -317,7 +319,7 @@ async def get_dfg_project_ids_by_names(names: list[str]) -> list[str]:
|
|||||||
|
|
||||||
response = await elasticsearch.search(
|
response = await elasticsearch.search(
|
||||||
source=["projects.project_id"],
|
source=["projects.project_id"],
|
||||||
size=1000,
|
size=10000,
|
||||||
query=query,
|
query=query,
|
||||||
index=ESIndex.DFG_PERSONS,
|
index=ESIndex.DFG_PERSONS,
|
||||||
cluster=ESCluster.INSE,
|
cluster=ESCluster.INSE,
|
||||||
@@ -366,6 +368,7 @@ async def search_dfg_projects(
|
|||||||
sort_by: str = "id",
|
sort_by: str = "id",
|
||||||
sort_direction: str = "asc",
|
sort_direction: str = "asc",
|
||||||
fuzzy: bool = False,
|
fuzzy: bool = False,
|
||||||
|
skip_enrichment: bool = False,
|
||||||
) -> DfgProjectPage:
|
) -> DfgProjectPage:
|
||||||
"""Searches for DFG projects based on the provided filtering and sorting criteria.
|
"""Searches for DFG projects based on the provided filtering and sorting criteria.
|
||||||
|
|
||||||
@@ -411,6 +414,7 @@ async def search_dfg_projects(
|
|||||||
"subject_area_en",
|
"subject_area_en",
|
||||||
"persons",
|
"persons",
|
||||||
"subject_classifications",
|
"subject_classifications",
|
||||||
|
"institutions",
|
||||||
],
|
],
|
||||||
"query": {},
|
"query": {},
|
||||||
}
|
}
|
||||||
@@ -522,35 +526,55 @@ async def search_dfg_projects(
|
|||||||
)
|
)
|
||||||
if not matching_institution_ids:
|
if not matching_institution_ids:
|
||||||
return DfgProjectPage(elements=[], total=0, page=page, size=size)
|
return DfgProjectPage(elements=[], total=0, page=page, size=size)
|
||||||
matching_person_ids = await get_person_ids_by_institution_ids(
|
#previously we were filtering by person_ids, but now we are filtering by institution_ids directly
|
||||||
institution_ids=matching_institution_ids
|
# matching_person_ids = await get_person_ids_by_institution_ids(
|
||||||
)
|
# institution_ids=matching_institution_ids
|
||||||
|
# )
|
||||||
|
# must_clauses.append(
|
||||||
|
# {
|
||||||
|
# "nested": {
|
||||||
|
# "path": "persons",
|
||||||
|
# "query": {"terms": {"persons.person_id": matching_person_ids}},
|
||||||
|
# }
|
||||||
|
# }
|
||||||
|
# )
|
||||||
must_clauses.append(
|
must_clauses.append(
|
||||||
{
|
{
|
||||||
"nested": {
|
"nested": {
|
||||||
"path": "persons",
|
"path": "institutions",
|
||||||
"query": {"terms": {"persons.person_id": matching_person_ids}},
|
"query": {"terms": {"institutions.institute_id": matching_institution_ids}},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
print("MATCHING_INSTITUTION_IDS", matching_institution_ids)
|
||||||
|
|
||||||
if institution_ids:
|
if institution_ids:
|
||||||
matching_person_ids = await get_person_ids_by_institution_ids(
|
#prevously we were filtering by person_ids, but now we are filtering by institution_ids directly
|
||||||
institution_ids=institution_ids
|
# matching_person_ids = await get_person_ids_by_institution_ids(
|
||||||
)
|
# institution_ids=institution_ids
|
||||||
|
# )
|
||||||
|
|
||||||
if not matching_person_ids:
|
# if not matching_person_ids:
|
||||||
return DfgProjectPage(elements=[], total=0, page=page, size=size)
|
# return DfgProjectPage(elements=[], total=0, page=page, size=size)
|
||||||
|
|
||||||
|
# must_clauses.append(
|
||||||
|
# {
|
||||||
|
# "nested": {
|
||||||
|
# "path": "persons",
|
||||||
|
# "query": {"terms": {"persons.person_id": matching_person_ids}},
|
||||||
|
# }
|
||||||
|
# }
|
||||||
|
# )
|
||||||
must_clauses.append(
|
must_clauses.append(
|
||||||
{
|
{
|
||||||
"nested": {
|
"nested": {
|
||||||
"path": "persons",
|
"path": "institutions",
|
||||||
"query": {"terms": {"persons.person_id": matching_person_ids}},
|
"query": {"terms": {"institutions.institute_id": institution_ids}},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
body["query"] = (
|
body["query"] = (
|
||||||
{"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}}
|
{"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}}
|
||||||
)
|
)
|
||||||
@@ -576,6 +600,7 @@ async def search_dfg_projects(
|
|||||||
body["sort"] = [sort_config]
|
body["sort"] = [sort_config]
|
||||||
# print(f"Executing DFG project search with body: {json.dumps(body, indent=2)}")
|
# print(f"Executing DFG project search with body: {json.dumps(body, indent=2)}")
|
||||||
# === Execute Search ===
|
# === Execute Search ===
|
||||||
|
print(f"Executing DFG project search with body: {json.dumps(body, indent=2)}")
|
||||||
response = await elasticsearch.search(
|
response = await elasticsearch.search(
|
||||||
index=ESIndex.DFG_PROJECTS,
|
index=ESIndex.DFG_PROJECTS,
|
||||||
body=body,
|
body=body,
|
||||||
@@ -584,6 +609,9 @@ async def search_dfg_projects(
|
|||||||
|
|
||||||
hits = response.get("hits", {}).get("hits", [])
|
hits = response.get("hits", {}).get("hits", [])
|
||||||
|
|
||||||
|
if skip_enrichment:
|
||||||
|
return _complete_response_to_dfg_project_page(response, page, size)
|
||||||
|
|
||||||
project_ids = [hit["_source"]["id"] for hit in hits]
|
project_ids = [hit["_source"]["id"] for hit in hits]
|
||||||
topic_lookup = await get_openalex_topics_for_dfg_projects(project_ids=project_ids)
|
topic_lookup = await get_openalex_topics_for_dfg_projects(project_ids=project_ids)
|
||||||
|
|
||||||
@@ -599,20 +627,27 @@ async def search_dfg_projects(
|
|||||||
source = hit["_source"]
|
source = hit["_source"]
|
||||||
project_id = source["id"]
|
project_id = source["id"]
|
||||||
source["topics"] = topic_lookup.get(str(project_id), [])
|
source["topics"] = topic_lookup.get(str(project_id), [])
|
||||||
|
institutions = source.get("institutions", [])
|
||||||
|
for institution in institutions:
|
||||||
|
institute_id = institution.get("institute_id")
|
||||||
|
if institute_id is not None:
|
||||||
|
institute_info = await get_dfg_institutes_by_ids(institute_ids=[institute_id])
|
||||||
|
if institute_info:
|
||||||
|
institution.update(institute_info[institute_id])
|
||||||
persons = source.get("persons", [])
|
persons = source.get("persons", [])
|
||||||
for person in persons:
|
for person in persons:
|
||||||
person_id = person.get("person_id")
|
person_id = person.get("person_id")
|
||||||
institute = person_lookup.get(person_id)
|
institute = person_lookup.get(person_id)
|
||||||
|
|
||||||
if institute:
|
# if institute:
|
||||||
person["root_id"] = institute.get("root_id")
|
# person["root_id"] = institute.get("root_id")
|
||||||
person["institute_id"] = institute.get("institute_id")
|
# person["institute_id"] = institute.get("institute_id")
|
||||||
person["root_name_de"] = institute.get("root_name_de")
|
# person["root_name_de"] = institute.get("root_name_de")
|
||||||
person["root_name_en"] = institute.get("root_name_en")
|
# person["root_name_en"] = institute.get("root_name_en")
|
||||||
person["institute_name_de"] = institute.get("institute_name_de")
|
# person["institute_name_de"] = institute.get("institute_name_de")
|
||||||
person["institute_name_en"] = institute.get("institute_name_en")
|
# person["institute_name_en"] = institute.get("institute_name_en")
|
||||||
person["address_country_de"] = institute.get("address_country_de")
|
# person["address_country_de"] = institute.get("address_country_de")
|
||||||
person["address_country_en"] = institute.get("address_country_en")
|
# person["address_country_en"] = institute.get("address_country_en")
|
||||||
|
|
||||||
return _complete_response_to_dfg_project_page(response, page, size)
|
return _complete_response_to_dfg_project_page(response, page, size)
|
||||||
|
|
||||||
@@ -654,12 +689,128 @@ async def get_dfg_project_by_id(project_id: str) -> DfgProjectDetails | None:
|
|||||||
)
|
)
|
||||||
hits = response.get("hits", {}).get("hits", [])
|
hits = response.get("hits", {}).get("hits", [])
|
||||||
|
|
||||||
if hits:
|
if not hits:
|
||||||
hit = hits[0]
|
return None
|
||||||
hit["_source"]["topics"] = topic_lookup.get(project_id, [])
|
|
||||||
details = DfgProjectDetails.from_elastic_hit(hit=hit)
|
hit = hits[0]
|
||||||
return details
|
source = hit["_source"]
|
||||||
return None
|
source["topics"] = topic_lookup.get(project_id, [])
|
||||||
|
|
||||||
|
persons = source.get("persons", [])
|
||||||
|
|
||||||
|
# --- Enrich persons with institute/root info (mirrors search_dfg_projects) ---
|
||||||
|
person_ids = {
|
||||||
|
person["person_id"]
|
||||||
|
for person in persons
|
||||||
|
if isinstance(person, dict) and person.get("person_id") is not None
|
||||||
|
}
|
||||||
|
person_lookup = await get_person_institutes(person_ids=list(person_ids))
|
||||||
|
|
||||||
|
institutions: dict[str, dict] = {}
|
||||||
|
|
||||||
|
for person in persons:
|
||||||
|
person_id = person.get("person_id")
|
||||||
|
institute = person_lookup.get(person_id)
|
||||||
|
if not institute:
|
||||||
|
continue
|
||||||
|
|
||||||
|
person["root_id"] = institute.get("root_id")
|
||||||
|
person["institute_id"] = institute.get("institute_id")
|
||||||
|
person["root_name_de"] = institute.get("root_name_de")
|
||||||
|
person["root_name_en"] = institute.get("root_name_en")
|
||||||
|
person["institute_name_de"] = institute.get("institute_name_de")
|
||||||
|
person["institute_name_en"] = institute.get("institute_name_en")
|
||||||
|
person["address_country_de"] = institute.get("address_country_de")
|
||||||
|
person["address_country_en"] = institute.get("address_country_en")
|
||||||
|
|
||||||
|
if institute.get("institute_id") is not None:
|
||||||
|
institutions[f"institute:{institute['institute_id']}"] = {
|
||||||
|
"institute_id": institute["institute_id"],
|
||||||
|
"institute_name_de": institute.get("institute_name_de"),
|
||||||
|
"institute_name_en": institute.get("institute_name_en"),
|
||||||
|
}
|
||||||
|
|
||||||
|
if institute.get("root_id") is not None:
|
||||||
|
institutions[f"root:{institute['root_id']}"] = {
|
||||||
|
"institute_id": institute["root_id"],
|
||||||
|
"institute_name_de": institute.get("root_name_de"),
|
||||||
|
"institute_name_en": institute.get("root_name_en"),
|
||||||
|
}
|
||||||
|
|
||||||
|
source["institutions"] = list(institutions.values())
|
||||||
|
|
||||||
|
return DfgProjectDetails.from_elastic_hit(hit=hit)
|
||||||
|
|
||||||
|
async def get_dfg_project_by_id(project_id: str) -> DfgProjectDetails | None:
|
||||||
|
"""Fetches the details of a single DFG project based on its project ID.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
project_id (str): The project ID to fetch.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Optional[DfgProjectDetails]: The project details or None if not found.
|
||||||
|
"""
|
||||||
|
topic_lookup = await get_openalex_topics_for_dfg_projects(project_ids=[project_id])
|
||||||
|
query = {"ids": {"values": [project_id]}}
|
||||||
|
|
||||||
|
response = await elasticsearch.search(
|
||||||
|
index=ESIndex.DFG_PROJECTS,
|
||||||
|
query=query,
|
||||||
|
size=1,
|
||||||
|
)
|
||||||
|
hits = response.get("hits", {}).get("hits", [])
|
||||||
|
|
||||||
|
if not hits:
|
||||||
|
return None
|
||||||
|
|
||||||
|
hit = hits[0]
|
||||||
|
source = hit["_source"]
|
||||||
|
source["topics"] = topic_lookup.get(project_id, [])
|
||||||
|
|
||||||
|
persons = source.get("persons", [])
|
||||||
|
|
||||||
|
#Enrich persons with institute/root info
|
||||||
|
person_ids = {
|
||||||
|
person["person_id"]
|
||||||
|
for person in persons
|
||||||
|
if isinstance(person, dict) and person.get("person_id") is not None
|
||||||
|
}
|
||||||
|
person_lookup = await get_person_institutes(person_ids=list(person_ids))
|
||||||
|
|
||||||
|
institutions: dict[str, dict] = {}
|
||||||
|
|
||||||
|
for person in persons:
|
||||||
|
person_id = person.get("person_id")
|
||||||
|
institute = person_lookup.get(person_id)
|
||||||
|
if not institute:
|
||||||
|
continue
|
||||||
|
|
||||||
|
person["root_id"] = institute.get("root_id")
|
||||||
|
person["institute_id"] = institute.get("institute_id")
|
||||||
|
person["root_name_de"] = institute.get("root_name_de")
|
||||||
|
person["root_name_en"] = institute.get("root_name_en")
|
||||||
|
person["institute_name_de"] = institute.get("institute_name_de")
|
||||||
|
person["institute_name_en"] = institute.get("institute_name_en")
|
||||||
|
person["address_country_de"] = institute.get("address_country_de")
|
||||||
|
person["address_country_en"] = institute.get("address_country_en")
|
||||||
|
|
||||||
|
if institute.get("institute_id") is not None:
|
||||||
|
institutions[f"institute:{institute['institute_id']}"] = {
|
||||||
|
"institute_id": institute["institute_id"],
|
||||||
|
"institute_name_de": institute.get("institute_name_de"),
|
||||||
|
"institute_name_en": institute.get("institute_name_en"),
|
||||||
|
}
|
||||||
|
|
||||||
|
if institute.get("root_id") is not None:
|
||||||
|
institutions[f"root:{institute['root_id']}"] = {
|
||||||
|
"institute_id": institute["root_id"],
|
||||||
|
"institute_name_de": institute.get("root_name_de"),
|
||||||
|
"institute_name_en": institute.get("root_name_en"),
|
||||||
|
}
|
||||||
|
|
||||||
|
source["institutions"] = list(institutions.values())
|
||||||
|
|
||||||
|
return DfgProjectDetails.from_elastic_hit(hit=hit)
|
||||||
|
|
||||||
#BUND
|
#BUND
|
||||||
|
|
||||||
@@ -1000,11 +1151,13 @@ async def search_all_projects(
|
|||||||
page = projects_filtering_properties.page
|
page = projects_filtering_properties.page
|
||||||
offset = page * size
|
offset = page * size
|
||||||
response = await elasticsearch.search(
|
response = await elasticsearch.search(
|
||||||
|
|
||||||
index=index,
|
index=index,
|
||||||
size=size,
|
size=size,
|
||||||
offset=offset,
|
offset=offset,
|
||||||
query=query,
|
query=query,
|
||||||
sort=sort,
|
sort=sort,
|
||||||
|
track_total_hits=True,
|
||||||
)
|
)
|
||||||
return _response_to_funding_project_page(response=response, page=page, size=size)
|
return _response_to_funding_project_page(response=response, page=page, size=size)
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import logging
|
|||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
from fastapi import APIRouter, Body, Depends, Path, Query, status
|
from fastapi import APIRouter, Body, Depends, Path, Query, status
|
||||||
|
from inse.auth.model import AccessTokenMetadata
|
||||||
|
from inse.auth.service import CurrentUserAccessTokenPayloadDep
|
||||||
from inse.institutions.institutions_search_client import (
|
from inse.institutions.institutions_search_client import (
|
||||||
InstitutionsSearchClient,
|
InstitutionsSearchClient,
|
||||||
)
|
)
|
||||||
@@ -28,6 +30,8 @@ from inse.projects.model import (
|
|||||||
SortDirection,
|
SortDirection,
|
||||||
)
|
)
|
||||||
from inse.tags import Tags
|
from inse.tags import Tags
|
||||||
|
from inse.auth.service import can_fetch_gdpr_relevant_data
|
||||||
|
from fastapi import HTTPException as HttpException
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -63,6 +67,109 @@ async def search_bund_projects(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/dfg/search",
|
||||||
|
summary="Get DFG projects.",
|
||||||
|
description="Returns a page of DFG projects based on the provided pagination parameters and optional institution filter.",
|
||||||
|
operation_id="getDfgProjects",
|
||||||
|
responses={
|
||||||
|
status.HTTP_200_OK: {
|
||||||
|
"description": "Successful Response",
|
||||||
|
"model": DfgProjectPage,
|
||||||
|
},
|
||||||
|
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
|
||||||
|
status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"},
|
||||||
|
},
|
||||||
|
response_model_by_alias=False,
|
||||||
|
)
|
||||||
|
async def get_dfg_projects(
|
||||||
|
access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep],
|
||||||
|
institutions_search_client: Annotated[
|
||||||
|
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||||
|
],
|
||||||
|
raw_oa_institution_id: Annotated[
|
||||||
|
str | None, Query(description="The openalex institution ID to filter by.")
|
||||||
|
] = None,
|
||||||
|
author_id: Annotated[str | None, Query(description="The openalex author ID to filter by.")] = None,
|
||||||
|
author_filter_ids: Annotated[list[str] | None, Query(description="The dfg author IDs to filter by.")] = None,
|
||||||
|
institution_ids: Annotated[list[str] | None, Query(description="The institution IDs to filter by.")] = None,
|
||||||
|
title: Annotated[
|
||||||
|
str | None, Query(description="The title to filter by.")
|
||||||
|
] = None,
|
||||||
|
keywords: Annotated[
|
||||||
|
list[str] | None, Query(description="Raw keywords to search in title/abstract/subject fields.")
|
||||||
|
] = None,
|
||||||
|
topic_ids: Annotated[
|
||||||
|
list[str] | None, Query(description="The openalex topic IDs to filter by.")
|
||||||
|
] = None,
|
||||||
|
filter_topic_ids: Annotated[
|
||||||
|
list[str] | None,
|
||||||
|
Query(
|
||||||
|
description="Additional topic IDs to merge into the fuzzy topic-id resolution "
|
||||||
|
"(union with topic_ids). Only used when fuzzy=True."
|
||||||
|
),
|
||||||
|
] = None,
|
||||||
|
funding_start_years: Annotated[list[str] | None, Query(description="The funding start years to filter by.")] = None,
|
||||||
|
funding_end_years: Annotated[list[str] | None, Query(description="The funding end years to filter by.")] = None,
|
||||||
|
|
||||||
|
page: Annotated[int, Query(description="The page number.", ge=0)] = 0,
|
||||||
|
size: Annotated[int, Query(description="The page size.", ge=1)] = 20,
|
||||||
|
sort_by: Annotated[str, Query(description="The field to sort by.")] = "title",
|
||||||
|
sort_direction: Annotated[
|
||||||
|
str, Query(description="The sort direction (asc or desc).")
|
||||||
|
] = "asc",
|
||||||
|
fuzzy: Annotated[
|
||||||
|
bool,
|
||||||
|
Query(description="Use topic_id resolution if True, otherwise use raw keyword search."),
|
||||||
|
] = False,
|
||||||
|
|
||||||
|
) -> DfgProjectPage:
|
||||||
|
logger.debug(
|
||||||
|
"Received request to get DFG projects for author_id=%s, author_filter_ids=%s, "
|
||||||
|
"institution_ids=%s, keywords=%s, topic_ids=%s, filter_topic_ids=%s, title=%s, "
|
||||||
|
"funding_start_years=%s, funding_end_years=%s, page=%d, size=%d, sort_by=%s, "
|
||||||
|
"sort_direction=%s, fuzzy=%s",
|
||||||
|
author_id,
|
||||||
|
author_filter_ids,
|
||||||
|
institution_ids,
|
||||||
|
keywords,
|
||||||
|
topic_ids,
|
||||||
|
filter_topic_ids,
|
||||||
|
title,
|
||||||
|
funding_start_years,
|
||||||
|
funding_end_years,
|
||||||
|
page,
|
||||||
|
size,
|
||||||
|
sort_by,
|
||||||
|
sort_direction,
|
||||||
|
fuzzy,
|
||||||
|
)
|
||||||
|
if (author_id or raw_oa_institution_id):
|
||||||
|
is_allowed = await can_fetch_gdpr_relevant_data(access_token = access_token_metadata, raw_oa_author_id = author_id, raw_oa_institution_id = raw_oa_institution_id)
|
||||||
|
if not is_allowed:
|
||||||
|
raise HttpException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Access denied for the provided author ID or institution ID",
|
||||||
|
)
|
||||||
|
return await projects_service.get_dfg_projects(
|
||||||
|
institutions_search_client=institutions_search_client,
|
||||||
|
raw_oa_institution_id=raw_oa_institution_id,
|
||||||
|
author_id=author_id,
|
||||||
|
author_filter_ids=author_filter_ids,
|
||||||
|
institution_ids=institution_ids,
|
||||||
|
funding_start_years=funding_start_years,
|
||||||
|
funding_end_years=funding_end_years,
|
||||||
|
title=title,
|
||||||
|
keywords=keywords,
|
||||||
|
topic_ids=topic_ids,
|
||||||
|
filter_topic_ids=filter_topic_ids,
|
||||||
|
page=page,
|
||||||
|
size=size,
|
||||||
|
sort_by=sort_by,
|
||||||
|
sort_direction=sort_direction,
|
||||||
|
fuzzy=fuzzy,
|
||||||
|
)
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
"/dfg/{id}",
|
"/dfg/{id}",
|
||||||
summary="Get a single DFG project.",
|
summary="Get a single DFG project.",
|
||||||
@@ -96,10 +203,13 @@ async def get_single_dfg_project(
|
|||||||
"description": "Successful Response",
|
"description": "Successful Response",
|
||||||
"model": BundProjectPage,
|
"model": BundProjectPage,
|
||||||
},
|
},
|
||||||
|
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
|
||||||
|
status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"},
|
||||||
},
|
},
|
||||||
response_model_by_alias=False,
|
response_model_by_alias=False,
|
||||||
)
|
)
|
||||||
async def search_bund_projects(
|
async def search_bund_projects(
|
||||||
|
access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep],
|
||||||
institutions_search_client: Annotated[
|
institutions_search_client: Annotated[
|
||||||
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||||
],
|
],
|
||||||
@@ -155,6 +265,13 @@ async def search_bund_projects(
|
|||||||
Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."),
|
Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."),
|
||||||
] = False,
|
] = False,
|
||||||
) -> BundProjectPage:
|
) -> BundProjectPage:
|
||||||
|
if (raw_oa_institution_id):
|
||||||
|
is_allowed = await can_fetch_gdpr_relevant_data(access_token = access_token_metadata, raw_oa_author_id = None, raw_oa_institution_id = raw_oa_institution_id)
|
||||||
|
if not is_allowed:
|
||||||
|
raise HttpException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Access denied for the provided author ID or institution ID",
|
||||||
|
)
|
||||||
return await projects_service.search_bund_projects_with_filters(
|
return await projects_service.search_bund_projects_with_filters(
|
||||||
institutions_search_client=institutions_search_client,
|
institutions_search_client=institutions_search_client,
|
||||||
executing_agency=executing_agency,
|
executing_agency=executing_agency,
|
||||||
@@ -217,10 +334,12 @@ from inse.projects.service import search_eu_cordis_projects
|
|||||||
"model": EuCordisProjectSearchPage,
|
"model": EuCordisProjectSearchPage,
|
||||||
},
|
},
|
||||||
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
|
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
|
||||||
|
status.HTTP_403_FORBIDDEN: {"description": "Access denied for the provided institution ID"},
|
||||||
},
|
},
|
||||||
response_model_by_alias=False,
|
response_model_by_alias=False,
|
||||||
)
|
)
|
||||||
async def search_eu_cordis_projects_endpoint(
|
async def search_eu_cordis_projects_endpoint(
|
||||||
|
access_token_metadata: Annotated[AccessTokenMetadata, CurrentUserAccessTokenPayloadDep],
|
||||||
institutions_search_client: Annotated[
|
institutions_search_client: Annotated[
|
||||||
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||||
],
|
],
|
||||||
@@ -299,6 +418,7 @@ async def search_eu_cordis_projects_endpoint(
|
|||||||
bool,
|
bool,
|
||||||
Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."),
|
Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."),
|
||||||
] = False,
|
] = False,
|
||||||
|
|
||||||
) -> EuCordisProjectSearchPage:
|
) -> EuCordisProjectSearchPage:
|
||||||
logger.debug(
|
logger.debug(
|
||||||
"Received EU CORDIS search request: raw_oa_institution_id=%s, "
|
"Received EU CORDIS search request: raw_oa_institution_id=%s, "
|
||||||
@@ -330,7 +450,13 @@ async def search_eu_cordis_projects_endpoint(
|
|||||||
sort_direction,
|
sort_direction,
|
||||||
fuzzy,
|
fuzzy,
|
||||||
)
|
)
|
||||||
|
if (author_id or raw_oa_institution_id):
|
||||||
|
is_allowed = await can_fetch_gdpr_relevant_data(access_token = access_token_metadata, raw_oa_author_id = author_id, raw_oa_institution_id = raw_oa_institution_id)
|
||||||
|
if not is_allowed:
|
||||||
|
raise HttpException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Access denied for the provided author ID or institution ID",
|
||||||
|
)
|
||||||
return await search_eu_cordis_projects(
|
return await search_eu_cordis_projects(
|
||||||
institutions_search_client=institutions_search_client,
|
institutions_search_client=institutions_search_client,
|
||||||
raw_oa_institution_id=raw_oa_institution_id,
|
raw_oa_institution_id=raw_oa_institution_id,
|
||||||
@@ -629,102 +755,6 @@ async def get_institution_cordis_eu_projects_funding_over_time(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
|
||||||
"/person/dfg/search",
|
|
||||||
summary="Get DFG projects.",
|
|
||||||
description="Returns a page of DFG projects based on the provided pagination parameters and optional institution filter.",
|
|
||||||
operation_id="getDfgProjects",
|
|
||||||
responses={
|
|
||||||
status.HTTP_200_OK: {
|
|
||||||
"description": "Successful Response",
|
|
||||||
"model": DfgProjectPage,
|
|
||||||
},
|
|
||||||
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
|
|
||||||
},
|
|
||||||
response_model_by_alias=False,
|
|
||||||
)
|
|
||||||
async def get_dfg_projects(
|
|
||||||
institutions_search_client: Annotated[
|
|
||||||
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
|
||||||
],
|
|
||||||
raw_oa_institution_id: Annotated[
|
|
||||||
str | None, Query(description="The openalex institution ID to filter by.")
|
|
||||||
] = None,
|
|
||||||
author_id: Annotated[str | None, Query(description="The openalex author ID to filter by.")] = None,
|
|
||||||
author_filter_ids: Annotated[list[int] | None, Query(description="The dfg author IDs to filter by.")] = None,
|
|
||||||
institution_ids: Annotated[
|
|
||||||
list[int] | None, Query(description="The institution IDs to filter by.")
|
|
||||||
] = None,
|
|
||||||
title: Annotated[
|
|
||||||
str | None, Query(description="The title to filter by.")
|
|
||||||
] = None,
|
|
||||||
keywords: Annotated[
|
|
||||||
list[str] | None, Query(description="Raw keywords to search in title/abstract/subject fields.")
|
|
||||||
] = None,
|
|
||||||
topic_ids: Annotated[
|
|
||||||
list[str] | None, Query(description="The openalex topic IDs to filter by.")
|
|
||||||
] = None,
|
|
||||||
filter_topic_ids: Annotated[
|
|
||||||
list[str] | None,
|
|
||||||
Query(
|
|
||||||
description="Additional topic IDs to merge into the fuzzy topic-id resolution "
|
|
||||||
"(union with topic_ids). Only used when fuzzy=True."
|
|
||||||
),
|
|
||||||
] = None,
|
|
||||||
funding_start_years: Annotated[list[str] | None, Query(description="The funding start years to filter by.")] = None,
|
|
||||||
funding_end_years: Annotated[list[str] | None, Query(description="The funding end years to filter by.")] = None,
|
|
||||||
|
|
||||||
page: Annotated[int, Query(description="The page number.", ge=0)] = 0,
|
|
||||||
size: Annotated[int, Query(description="The page size.", ge=1)] = 20,
|
|
||||||
sort_by: Annotated[str, Query(description="The field to sort by.")] = "title",
|
|
||||||
sort_direction: Annotated[
|
|
||||||
str, Query(description="The sort direction (asc or desc).")
|
|
||||||
] = "asc",
|
|
||||||
fuzzy: Annotated[
|
|
||||||
bool,
|
|
||||||
Query(description="Use topic_id resolution if True, otherwise use raw keyword search."),
|
|
||||||
] = False,
|
|
||||||
|
|
||||||
) -> DfgProjectPage:
|
|
||||||
logger.debug(
|
|
||||||
"Received request to get DFG projects for author_id=%s, author_filter_ids=%s, "
|
|
||||||
"institution_ids=%s, keywords=%s, topic_ids=%s, filter_topic_ids=%s, title=%s, "
|
|
||||||
"funding_start_years=%s, funding_end_years=%s, page=%d, size=%d, sort_by=%s, "
|
|
||||||
"sort_direction=%s, fuzzy=%s",
|
|
||||||
author_id,
|
|
||||||
author_filter_ids,
|
|
||||||
institution_ids,
|
|
||||||
keywords,
|
|
||||||
topic_ids,
|
|
||||||
filter_topic_ids,
|
|
||||||
title,
|
|
||||||
funding_start_years,
|
|
||||||
funding_end_years,
|
|
||||||
page,
|
|
||||||
size,
|
|
||||||
sort_by,
|
|
||||||
sort_direction,
|
|
||||||
fuzzy,
|
|
||||||
)
|
|
||||||
return await projects_service.get_dfg_projects_by_author_id(
|
|
||||||
institutions_search_client=institutions_search_client,
|
|
||||||
raw_oa_institution_id=raw_oa_institution_id,
|
|
||||||
author_id=author_id,
|
|
||||||
author_filter_ids=author_filter_ids,
|
|
||||||
institution_ids=institution_ids,
|
|
||||||
funding_start_years=funding_start_years,
|
|
||||||
funding_end_years=funding_end_years,
|
|
||||||
title=title,
|
|
||||||
keywords=keywords,
|
|
||||||
topic_ids=topic_ids,
|
|
||||||
filter_topic_ids=filter_topic_ids,
|
|
||||||
page=page,
|
|
||||||
size=size,
|
|
||||||
sort_by=sort_by,
|
|
||||||
sort_direction=sort_direction,
|
|
||||||
fuzzy=fuzzy,
|
|
||||||
)
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
"/search",
|
"/search",
|
||||||
summary="Search projects across all funders.",
|
summary="Search projects across all funders.",
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import logging
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from inse.exceptions import NotFoundException
|
from inse.exceptions import NotFoundException
|
||||||
|
from inse.auth.model import AccessTokenMetadata
|
||||||
from inse.institutions.institutions_search_client import (
|
from inse.institutions.institutions_search_client import (
|
||||||
InstitutionsSearchClient,
|
InstitutionsSearchClient,
|
||||||
)
|
)
|
||||||
@@ -26,9 +27,7 @@ from inse.projects.eu_cordis_projects_client import (
|
|||||||
from inse.projects.eu_cordis_projects_client import (
|
from inse.projects.eu_cordis_projects_client import (
|
||||||
search_eu_cordis_projects as _search_eu_cordis_projects_es,
|
search_eu_cordis_projects as _search_eu_cordis_projects_es,
|
||||||
)
|
)
|
||||||
from inse.projects.logic import (
|
|
||||||
get_dfg_author_names_by_ids,
|
|
||||||
)
|
|
||||||
from inse.projects.model import (
|
from inse.projects.model import (
|
||||||
BundProjectPage,
|
BundProjectPage,
|
||||||
DfgProjectPage,
|
DfgProjectPage,
|
||||||
@@ -41,8 +40,9 @@ from inse.projects.model import (
|
|||||||
ProjectType,
|
ProjectType,
|
||||||
SortDirection,
|
SortDirection,
|
||||||
)
|
)
|
||||||
|
from inse.projects.logic import get_dfg_author_names_by_ids
|
||||||
from inse.works.logic import get_publication_dois_of_author
|
from inse.works.logic import get_publication_dois_of_author
|
||||||
|
from fastapi import HTTPException as HttpException
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@@ -157,12 +157,25 @@ async def _get_dfg_project_ids_for_openalex_authors(
|
|||||||
|
|
||||||
return list(set.intersection(*project_sets))
|
return list(set.intersection(*project_sets))
|
||||||
|
|
||||||
async def get_dfg_projects_by_author_id(
|
def _is_number_list(values: list[str] | None) -> bool:
|
||||||
|
if not values:
|
||||||
|
return True # nothing to validate, treat as valid/empty
|
||||||
|
for value in values:
|
||||||
|
if value is None or value == "":
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
float(value)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
async def get_dfg_projects(
|
||||||
institutions_search_client: InstitutionsSearchClient,
|
institutions_search_client: InstitutionsSearchClient,
|
||||||
raw_oa_institution_id: str | None,
|
raw_oa_institution_id: str | None,
|
||||||
author_id: str | None,
|
author_id: str | None,
|
||||||
author_filter_ids: list[int] | None,
|
author_filter_ids: list[str] | None,
|
||||||
institution_ids: list[int] | None,
|
institution_ids: list[str] | None,
|
||||||
keywords: list[str] | None,
|
keywords: list[str] | None,
|
||||||
topic_ids: list[str] | None,
|
topic_ids: list[str] | None,
|
||||||
filter_topic_ids: list[str] | None,
|
filter_topic_ids: list[str] | None,
|
||||||
@@ -174,6 +187,7 @@ async def get_dfg_projects_by_author_id(
|
|||||||
sort_by: str = "topic",
|
sort_by: str = "topic",
|
||||||
sort_direction: str = "asc",
|
sort_direction: str = "asc",
|
||||||
fuzzy: bool = False,
|
fuzzy: bool = False,
|
||||||
|
skip_enrichment: bool = False,
|
||||||
) -> DfgProjectPage:
|
) -> DfgProjectPage:
|
||||||
logger.debug(
|
logger.debug(
|
||||||
"Fetching DFG projects for author_id=%s, author_filter_ids=%s, "
|
"Fetching DFG projects for author_id=%s, author_filter_ids=%s, "
|
||||||
@@ -195,6 +209,23 @@ async def get_dfg_projects_by_author_id(
|
|||||||
sort_direction,
|
sort_direction,
|
||||||
fuzzy,
|
fuzzy,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Validate author_filter_ids / institution_ids. Return an empty page
|
||||||
|
if not _is_number_list(author_filter_ids) or not _is_number_list(institution_ids):
|
||||||
|
logger.debug(
|
||||||
|
"Invalid author_filter_ids=%s or institution_ids=%s, returning empty page",
|
||||||
|
author_filter_ids,
|
||||||
|
institution_ids,
|
||||||
|
)
|
||||||
|
return DfgProjectPage(elements=[], page=page, size=size, total=0)
|
||||||
|
|
||||||
|
author_filter_ids_int = (
|
||||||
|
[int(float(v)) for v in author_filter_ids] if author_filter_ids else None
|
||||||
|
)
|
||||||
|
institution_ids_int = (
|
||||||
|
[int(float(v)) for v in institution_ids] if institution_ids else None
|
||||||
|
)
|
||||||
|
|
||||||
filter_names = []
|
filter_names = []
|
||||||
author_project_ids = []
|
author_project_ids = []
|
||||||
if author_id:
|
if author_id:
|
||||||
@@ -207,19 +238,23 @@ async def get_dfg_projects_by_author_id(
|
|||||||
size=size,
|
size=size,
|
||||||
total=0)
|
total=0)
|
||||||
|
|
||||||
if author_filter_ids:
|
if author_filter_ids_int:
|
||||||
filter_names = (
|
filter_names = (
|
||||||
await get_dfg_author_names_by_ids(author_ids=author_filter_ids)
|
await get_dfg_author_names_by_ids(author_ids=author_filter_ids_int)
|
||||||
if author_filter_ids
|
if author_filter_ids_int
|
||||||
else []
|
else []
|
||||||
)
|
)
|
||||||
if author_filter_ids and not filter_names:
|
if author_filter_ids_int and not filter_names:
|
||||||
logger.debug(
|
logger.debug(
|
||||||
"No author names found for author_filter_ids=%s",
|
"No author names found for author_filter_ids=%s",
|
||||||
author_filter_ids,
|
author_filter_ids_int,
|
||||||
)
|
)
|
||||||
institution_aliases = []
|
institution_aliases = []
|
||||||
if raw_oa_institution_id:
|
if raw_oa_institution_id:
|
||||||
|
if institutions_search_client is None:
|
||||||
|
raise ValueError(
|
||||||
|
"institutions_search_client must be provided when raw_oa_institution_id is set"
|
||||||
|
)
|
||||||
institution_aliases = (
|
institution_aliases = (
|
||||||
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
||||||
raw_oa_institution_id
|
raw_oa_institution_id
|
||||||
@@ -238,7 +273,7 @@ async def get_dfg_projects_by_author_id(
|
|||||||
institution_aliases=institution_aliases,
|
institution_aliases=institution_aliases,
|
||||||
project_ids=author_project_ids,
|
project_ids=author_project_ids,
|
||||||
names=filter_names or [],
|
names=filter_names or [],
|
||||||
institution_ids=institution_ids,
|
institution_ids=institution_ids_int,
|
||||||
keywords=keywords,
|
keywords=keywords,
|
||||||
topic_ids=topic_ids,
|
topic_ids=topic_ids,
|
||||||
filter_topic_ids=filter_topic_ids,
|
filter_topic_ids=filter_topic_ids,
|
||||||
@@ -248,6 +283,7 @@ async def get_dfg_projects_by_author_id(
|
|||||||
sort_by=sort_by,
|
sort_by=sort_by,
|
||||||
sort_direction=sort_direction,
|
sort_direction=sort_direction,
|
||||||
fuzzy=fuzzy,
|
fuzzy=fuzzy,
|
||||||
|
skip_enrichment=skip_enrichment,
|
||||||
)
|
)
|
||||||
|
|
||||||
async def get_institution_cordis_eu_projects_funding_over_time(
|
async def get_institution_cordis_eu_projects_funding_over_time(
|
||||||
@@ -426,6 +462,10 @@ async def search_bund_projects_with_filters(
|
|||||||
) -> BundProjectPage:
|
) -> BundProjectPage:
|
||||||
institution_aliases = []
|
institution_aliases = []
|
||||||
if raw_oa_institution_id:
|
if raw_oa_institution_id:
|
||||||
|
if institutions_search_client is None:
|
||||||
|
raise ValueError(
|
||||||
|
"institutions_search_client must be provided when raw_oa_institution_id is set"
|
||||||
|
)
|
||||||
institution_aliases = (
|
institution_aliases = (
|
||||||
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
|
||||||
raw_oa_institution_id
|
raw_oa_institution_id
|
||||||
@@ -623,6 +663,7 @@ async def search_eu_cordis_projects(
|
|||||||
sort_by: str = "title",
|
sort_by: str = "title",
|
||||||
sort_direction: str = "asc",
|
sort_direction: str = "asc",
|
||||||
fuzzy: bool = False,
|
fuzzy: bool = False,
|
||||||
|
skip_enrichment: bool = False,
|
||||||
) -> EuCordisProjectSearchPage:
|
) -> EuCordisProjectSearchPage:
|
||||||
"""Single entry point for EU CORDIS project search.
|
"""Single entry point for EU CORDIS project search.
|
||||||
|
|
||||||
@@ -639,7 +680,6 @@ async def search_eu_cordis_projects(
|
|||||||
eu_cordis_projects_client.search_eu_cordis_projects.
|
eu_cordis_projects_client.search_eu_cordis_projects.
|
||||||
"""
|
"""
|
||||||
resolved_organization_names: list[str] = list(organization_names or [])
|
resolved_organization_names: list[str] = list(organization_names or [])
|
||||||
|
|
||||||
if raw_oa_institution_id:
|
if raw_oa_institution_id:
|
||||||
if institutions_search_client is None:
|
if institutions_search_client is None:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
@@ -683,4 +723,5 @@ async def search_eu_cordis_projects(
|
|||||||
sort_by=sort_by,
|
sort_by=sort_by,
|
||||||
sort_direction=sort_direction,
|
sort_direction=sort_direction,
|
||||||
fuzzy=fuzzy,
|
fuzzy=fuzzy,
|
||||||
|
skip_enrichment=skip_enrichment,
|
||||||
)
|
)
|
||||||
@@ -3,11 +3,10 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import logging
|
import logging
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
|
from math import floor
|
||||||
from time import time
|
from time import time
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import pandas as pd
|
|
||||||
|
|
||||||
from inse.authors.institution_membership_query import (
|
from inse.authors.institution_membership_query import (
|
||||||
build_active_institution_membership_query,
|
build_active_institution_membership_query,
|
||||||
)
|
)
|
||||||
@@ -746,15 +745,29 @@ def _bucket_to_ranked_author(author_bucket: dict) -> RankedAuthor:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _min_max_normalize(values: pd.Series) -> pd.Series:
|
def _quantile(values: list[float], quantile: float) -> float:
|
||||||
|
"""Returns a linearly interpolated quantile (the former pandas default)."""
|
||||||
|
ordered = sorted(values)
|
||||||
|
if not ordered:
|
||||||
|
return 0.0
|
||||||
|
position = (len(ordered) - 1) * quantile
|
||||||
|
lower_index = floor(position)
|
||||||
|
upper_index = min(lower_index + 1, len(ordered) - 1)
|
||||||
|
fraction = position - lower_index
|
||||||
|
return ordered[lower_index] + (
|
||||||
|
ordered[upper_index] - ordered[lower_index]
|
||||||
|
) * fraction
|
||||||
|
|
||||||
|
|
||||||
|
def _min_max_normalize(values: list[float]) -> list[float]:
|
||||||
"""Scales a numeric column to the range [0, 1] via min-max normalization."""
|
"""Scales a numeric column to the range [0, 1] via min-max normalization."""
|
||||||
minimum = values.min()
|
minimum = min(values)
|
||||||
maximum = values.max()
|
maximum = max(values)
|
||||||
# if all values are the same, return a series of 1.0 to avoid division by zero.
|
# if all values are the same, return a series of 1.0 to avoid division by zero.
|
||||||
if maximum == minimum:
|
if maximum == minimum:
|
||||||
return pd.Series([1.0] * len(values))
|
return [1.0] * len(values)
|
||||||
|
|
||||||
return (values - minimum) / (maximum - minimum)
|
return [(value - minimum) / (maximum - minimum) for value in values]
|
||||||
|
|
||||||
|
|
||||||
def _apply_scores(authors: list[RankedAuthor], weights: RankingWeights) -> None:
|
def _apply_scores(authors: list[RankedAuthor], weights: RankingWeights) -> None:
|
||||||
@@ -775,38 +788,29 @@ def _apply_scores(authors: list[RankedAuthor], weights: RankingWeights) -> None:
|
|||||||
news_counts.append(author.news_count)
|
news_counts.append(author.news_count)
|
||||||
patents_counts.append(author.patents_count)
|
patents_counts.append(author.patents_count)
|
||||||
|
|
||||||
frame = pd.DataFrame({
|
|
||||||
"works": works_counts,
|
|
||||||
"citations": citations_counts,
|
|
||||||
"companies": companies_counts,
|
|
||||||
"news": news_counts,
|
|
||||||
"patents": patents_counts,
|
|
||||||
})
|
|
||||||
|
|
||||||
quantile_value = 0.95
|
quantile_value = 0.95
|
||||||
|
metrics = [
|
||||||
frame["works"] = frame["works"].clip(upper=frame["works"].quantile(quantile_value))
|
works_counts,
|
||||||
frame["citations"] = frame["citations"].clip(upper=frame["citations"].quantile(quantile_value))
|
citations_counts,
|
||||||
frame["companies"] = frame["companies"].clip(upper=frame["companies"].quantile(quantile_value))
|
companies_counts,
|
||||||
frame["news"] = frame["news"].clip(upper=frame["news"].quantile(quantile_value))
|
news_counts,
|
||||||
frame["patents"] = frame["patents"].clip(upper=frame["patents"].quantile(quantile_value))
|
patents_counts,
|
||||||
|
]
|
||||||
works_normalized = _min_max_normalize(frame["works"])
|
normalized_metrics = [
|
||||||
citations_normalized = _min_max_normalize(frame["citations"])
|
_min_max_normalize(
|
||||||
companies_normalized = _min_max_normalize(frame["companies"])
|
[min(value, _quantile(values, quantile_value)) for value in values]
|
||||||
news_normalized = _min_max_normalize(frame["news"])
|
)
|
||||||
patents_normalized = _min_max_normalize(frame["patents"])
|
for values in metrics
|
||||||
|
]
|
||||||
scores = (
|
|
||||||
works_normalized * weights.works
|
|
||||||
+ citations_normalized * weights.citation
|
|
||||||
+ companies_normalized * weights.companies
|
|
||||||
+ news_normalized * weights.news
|
|
||||||
+ patents_normalized * weights.patents
|
|
||||||
)
|
|
||||||
|
|
||||||
for index, author in enumerate(authors):
|
for index, author in enumerate(authors):
|
||||||
author.score = float(scores.iloc[index])
|
author.score = float(
|
||||||
|
normalized_metrics[0][index] * weights.works
|
||||||
|
+ normalized_metrics[1][index] * weights.citation
|
||||||
|
+ normalized_metrics[2][index] * weights.companies
|
||||||
|
+ normalized_metrics[3][index] * weights.news
|
||||||
|
+ normalized_metrics[4][index] * weights.patents
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _author_score(author: RankedAuthor) -> float:
|
def _author_score(author: RankedAuthor) -> float:
|
||||||
|
|||||||
@@ -4,6 +4,9 @@ from typing import Annotated
|
|||||||
import inse.topics.v2.service as topics_service
|
import inse.topics.v2.service as topics_service
|
||||||
from fastapi import APIRouter, Path, Query
|
from fastapi import APIRouter, Path, Query
|
||||||
from inse.model import SortDirection
|
from inse.model import SortDirection
|
||||||
|
from inse.models.openalex.domain import Domain
|
||||||
|
from inse.models.openalex.model_field import ModelField
|
||||||
|
from inse.models.openalex.subfield import Subfield
|
||||||
from inse.models.openalex.topic import Topic
|
from inse.models.openalex.topic import Topic
|
||||||
from inse.router_prefixes import RouterPrefixes
|
from inse.router_prefixes import RouterPrefixes
|
||||||
from inse.tags import Tags
|
from inse.tags import Tags
|
||||||
@@ -78,6 +81,48 @@ async def get_topic_by_id(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/domains/single/{domain_id}",
|
||||||
|
operation_id="getDomainById",
|
||||||
|
summary="Returns a domain for a given domain ID.",
|
||||||
|
)
|
||||||
|
async def get_domain_by_id(
|
||||||
|
domain_id: Annotated[
|
||||||
|
str,
|
||||||
|
Path(description="The ID of the domain to retrieve."),
|
||||||
|
],
|
||||||
|
) -> Domain:
|
||||||
|
return await topics_service.get_domain_by_id_or_raise(domain_id=domain_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/fields/single/{field_id}",
|
||||||
|
operation_id="getFieldById",
|
||||||
|
summary="Returns a field for a given field ID.",
|
||||||
|
)
|
||||||
|
async def get_field_by_id(
|
||||||
|
field_id: Annotated[
|
||||||
|
str,
|
||||||
|
Path(description="The ID of the field to retrieve."),
|
||||||
|
],
|
||||||
|
) -> ModelField:
|
||||||
|
return await topics_service.get_field_by_id_or_raise(field_id=field_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/subfields/single/{subfield_id}",
|
||||||
|
operation_id="getSubfieldById",
|
||||||
|
summary="Returns a subfield for a given subfield ID.",
|
||||||
|
)
|
||||||
|
async def get_subfield_by_id(
|
||||||
|
subfield_id: Annotated[
|
||||||
|
str,
|
||||||
|
Path(description="The ID of the subfield to retrieve."),
|
||||||
|
],
|
||||||
|
) -> Subfield:
|
||||||
|
return await topics_service.get_subfield_by_id_or_raise(subfield_id=subfield_id)
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
"/topics/id",
|
"/topics/id",
|
||||||
operation_id="getTopicsByIds",
|
operation_id="getTopicsByIds",
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
from inse.exceptions import NotFoundException
|
from inse.exceptions import NotFoundException
|
||||||
from inse.integrations import elasticsearch
|
from inse.integrations import elasticsearch
|
||||||
from inse.model import ESIndex, SortDirection
|
from inse.model import ESIndex, SortDirection
|
||||||
|
from inse.models.openalex.domain import Domain
|
||||||
|
from inse.models.openalex.model_field import ModelField
|
||||||
|
from inse.models.openalex.subfield import Subfield
|
||||||
from inse.models.openalex.topic import Topic
|
from inse.models.openalex.topic import Topic
|
||||||
from inse.topics.v2.model import TopicPageV2, TopicSortBy
|
from inse.topics.v2.model import TopicPageV2, TopicSortBy
|
||||||
|
|
||||||
@@ -184,6 +187,117 @@ async def get_topic_by_id_or_raise(raw_oa_topic_id: str) -> Topic:
|
|||||||
return topic
|
return topic
|
||||||
|
|
||||||
|
|
||||||
|
async def get_domain_by_id(domain_id: str) -> Domain | None:
|
||||||
|
"""Retrieves a domain based on its ID.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
domain_id (str): The numeric OpenAlex ID of the domain to retrieve (e.g. "4").
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Domain | None: The domain matching the provided ID, or None if not found.
|
||||||
|
"""
|
||||||
|
response = await elasticsearch.get(
|
||||||
|
index=ESIndex.OPENALEX_DOMAINS,
|
||||||
|
doc_id=domain_id,
|
||||||
|
source=["id", "display_name", "description"],
|
||||||
|
)
|
||||||
|
if response.get("found"):
|
||||||
|
return Domain.from_dict(response.get("_source", {}))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def get_domain_by_id_or_raise(domain_id: str) -> Domain:
|
||||||
|
"""Retrieves a domain based on its ID, raising an exception if not found.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
domain_id (str): The ID of the domain to retrieve.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
NotFoundException: If the domain with the specified ID is not found.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Domain: The domain matching the provided ID.
|
||||||
|
"""
|
||||||
|
domain = await get_domain_by_id(domain_id)
|
||||||
|
if domain is None:
|
||||||
|
raise NotFoundException(f"Domain with ID {domain_id} not found.")
|
||||||
|
return domain
|
||||||
|
|
||||||
|
|
||||||
|
async def get_field_by_id(field_id: str) -> ModelField | None:
|
||||||
|
"""Retrieves a field based on its ID.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
field_id (str): The numeric OpenAlex ID of the field to retrieve (e.g. "27").
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
ModelField | None: The field matching the provided ID, or None if not found.
|
||||||
|
"""
|
||||||
|
response = await elasticsearch.get(
|
||||||
|
index=ESIndex.OPENALEX_FIELDS,
|
||||||
|
doc_id=field_id,
|
||||||
|
source=["id", "display_name", "description"],
|
||||||
|
)
|
||||||
|
if response.get("found"):
|
||||||
|
return ModelField.from_dict(response.get("_source", {}))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def get_field_by_id_or_raise(field_id: str) -> ModelField:
|
||||||
|
"""Retrieves a field based on its ID, raising an exception if not found.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
field_id (str): The ID of the field to retrieve.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
NotFoundException: If the field with the specified ID is not found.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
ModelField: The field matching the provided ID.
|
||||||
|
"""
|
||||||
|
field = await get_field_by_id(field_id)
|
||||||
|
if field is None:
|
||||||
|
raise NotFoundException(f"Field with ID {field_id} not found.")
|
||||||
|
return field
|
||||||
|
|
||||||
|
|
||||||
|
async def get_subfield_by_id(subfield_id: str) -> Subfield | None:
|
||||||
|
"""Retrieves a subfield based on its ID.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
subfield_id (str): The numeric OpenAlex ID of the subfield to retrieve (e.g. "2743").
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Subfield | None: The subfield matching the provided ID, or None if not found.
|
||||||
|
"""
|
||||||
|
response = await elasticsearch.get(
|
||||||
|
index=ESIndex.OPENALEX_SUBFIELDS,
|
||||||
|
doc_id=subfield_id,
|
||||||
|
source=["id", "display_name", "description"],
|
||||||
|
)
|
||||||
|
if response.get("found"):
|
||||||
|
return Subfield.from_dict(response.get("_source", {}))
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def get_subfield_by_id_or_raise(subfield_id: str) -> Subfield:
|
||||||
|
"""Retrieves a subfield based on its ID, raising an exception if not found.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
subfield_id (str): The ID of the subfield to retrieve.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
NotFoundException: If the subfield with the specified ID is not found.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Subfield: The subfield matching the provided ID.
|
||||||
|
"""
|
||||||
|
subfield = await get_subfield_by_id(subfield_id)
|
||||||
|
if subfield is None:
|
||||||
|
raise NotFoundException(f"Subfield with ID {subfield_id} not found.")
|
||||||
|
return subfield
|
||||||
|
|
||||||
|
|
||||||
async def get_topics_by_ids(topic_ids: list[str]) -> TopicPageV2:
|
async def get_topics_by_ids(topic_ids: list[str]) -> TopicPageV2:
|
||||||
"""Retrieves topics based on a list of topic IDs.
|
"""Retrieves topics based on a list of topic IDs.
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import logging
|
import logging
|
||||||
|
import re
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from inse.integrations import elasticsearch
|
from inse.integrations import elasticsearch
|
||||||
@@ -11,6 +12,17 @@ logger = logging.getLogger(__name__)
|
|||||||
DEFAULT_INSTITUTION_ID = "https://openalex.org/I62318514"
|
DEFAULT_INSTITUTION_ID = "https://openalex.org/I62318514"
|
||||||
DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen"
|
DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen"
|
||||||
|
|
||||||
|
# Reserved characters and boolean operators of the Lucene query_string syntax
|
||||||
|
_LUCENE_SPECIAL_CHARS = re.compile(r'([+\-=&|><!(){}\[\]^"~*?:\\/])')
|
||||||
|
_LUCENE_BOOL_OPERATORS = re.compile(r"\b(AND|OR|NOT)\b")
|
||||||
|
|
||||||
|
|
||||||
|
def escape_lucene_query(term: str) -> str:
|
||||||
|
"""Escapes a free-text search term so it is safe inside a ``query_string`` query."""
|
||||||
|
if not term:
|
||||||
|
return ""
|
||||||
|
escaped = _LUCENE_SPECIAL_CHARS.sub(r"\\\1", term)
|
||||||
|
return _LUCENE_BOOL_OPERATORS.sub(lambda m: f'"{m.group(1)}"', escaped)
|
||||||
|
|
||||||
|
|
||||||
def clean_inst_id(id_str: str) -> str:
|
def clean_inst_id(id_str: str) -> str:
|
||||||
@@ -407,6 +419,56 @@ class TrendQueryBuilder:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def build_cc_news_year_agg_body(
|
||||||
|
term: str,
|
||||||
|
start_year: int,
|
||||||
|
end_year: int,
|
||||||
|
languages: list[str] | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Builds a size=0 yearly-count aggregation over the Common Crawl News indices. Buckets
|
||||||
|
by year with a `date_histogram`, since cc-news has a real `content_date` date field rather than
|
||||||
|
the integer `date_year` of `aktuell`.
|
||||||
|
"""
|
||||||
|
return {
|
||||||
|
"size": 0,
|
||||||
|
"track_total_hits": False,
|
||||||
|
"_source": False,
|
||||||
|
"query": {
|
||||||
|
"bool": {
|
||||||
|
"filter": [
|
||||||
|
{
|
||||||
|
"query_string": {
|
||||||
|
"query": escape_lucene_query(term),
|
||||||
|
"fields": CC_NEWS_SEARCH_FIELDS,
|
||||||
|
"default_operator": "AND",
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{"terms": {"language_code": languages or CC_NEWS_LANGUAGES}},
|
||||||
|
{
|
||||||
|
"range": {
|
||||||
|
"content_date": {
|
||||||
|
"gte": f"{start_year}-01-01",
|
||||||
|
"lte": f"{end_year}-12-31",
|
||||||
|
"format": "yyyy-MM-dd",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"aggs": {
|
||||||
|
"by_year": {
|
||||||
|
"date_histogram": {
|
||||||
|
"field": "content_date",
|
||||||
|
"calendar_interval": "year",
|
||||||
|
"format": "yyyy",
|
||||||
|
"min_doc_count": 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def build_bund_receiver_clause(aliases: list[str]) -> dict[str, Any]:
|
def build_bund_receiver_clause(aliases: list[str]) -> dict[str, Any]:
|
||||||
"""Builds Zuwendungsempfänger matching clause for BUND projects."""
|
"""Builds Zuwendungsempfänger matching clause for BUND projects."""
|
||||||
@@ -443,4 +505,7 @@ DFG_PROJECT_TEXT_FIELDS = [
|
|||||||
|
|
||||||
CORDIS_PROJECT_TEXT_FIELDS = ["title", "objective"]
|
CORDIS_PROJECT_TEXT_FIELDS = ["title", "objective"]
|
||||||
AKTUELLES_SEARCH_FIELDS = ["main_content", "full_content", "maintitle", "subtitle", "intro_content"]
|
AKTUELLES_SEARCH_FIELDS = ["main_content", "full_content", "maintitle", "subtitle", "intro_content"]
|
||||||
|
CC_NEWS_SEARCH_FIELDS = ["title", "body"]
|
||||||
|
CC_NEWS_LANGUAGES = ["de", "en"]
|
||||||
|
CC_NEWS_START_YEAR = 2017
|
||||||
|
|
||||||
|
|||||||
@@ -16,11 +16,13 @@ from .model import (
|
|||||||
)
|
)
|
||||||
from .trend_query_builder import (
|
from .trend_query_builder import (
|
||||||
AKTUELLES_SEARCH_FIELDS,
|
AKTUELLES_SEARCH_FIELDS,
|
||||||
|
CC_NEWS_START_YEAR,
|
||||||
DEFAULT_INSTITUTION_ID,
|
DEFAULT_INSTITUTION_ID,
|
||||||
DEFAULT_INSTITUTION_NAME,
|
DEFAULT_INSTITUTION_NAME,
|
||||||
TrendMetadataResolver,
|
TrendMetadataResolver,
|
||||||
TrendQueryBuilder,
|
TrendQueryBuilder,
|
||||||
clean_inst_id,
|
clean_inst_id,
|
||||||
|
escape_lucene_query,
|
||||||
to_full_inst_url,
|
to_full_inst_url,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -47,6 +49,13 @@ EPO_PATENT_FIELDS = [
|
|||||||
"openalex_topics.topic_id",
|
"openalex_topics.topic_id",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
# Synthetic entity id prefixes for the news trend series. The webapp keys colouring, chip
|
||||||
|
# visibility and pie filtering off these, so keep them in sync with uni-trend-parent.component.ts.
|
||||||
|
NEWS_ENTITY_PREFIX = "news_topic_"
|
||||||
|
CC_NEWS_ENTITY_PREFIX = "ccnews_topic_"
|
||||||
|
# Entity id of the collapsed CC-News series in the cross-domain ("all") view.
|
||||||
|
CC_NEWS_COMPOSITE_ID = "ccnews"
|
||||||
|
|
||||||
DFG_INSTITUTION_FIELDS = [
|
DFG_INSTITUTION_FIELDS = [
|
||||||
"Antragstellende Institution",
|
"Antragstellende Institution",
|
||||||
"Mitantragstellende Institution",
|
"Mitantragstellende Institution",
|
||||||
@@ -1042,6 +1051,18 @@ class ProjectsTrendStrategy(TrendStrategy):
|
|||||||
|
|
||||||
|
|
||||||
class NewsTrendStrategy(TrendStrategy):
|
class NewsTrendStrategy(TrendStrategy):
|
||||||
|
"""Yearly news counts per topic.
|
||||||
|
|
||||||
|
Produces one series per topic from the UDE-internal `aktuell` index (entity id
|
||||||
|
``news_topic_<topic>``). When keyword matching is active (``fuzzy=False``) it additionally
|
||||||
|
produces an external Common Crawl News baseline per topic (``ccnews_topic_<topic>``) so the
|
||||||
|
internal coverage can be compared against the wider web. CC-News has no OpenAlex topic
|
||||||
|
mapping, so it is skipped entirely in topic-mapping mode.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, include_cc_news: bool = True):
|
||||||
|
self.include_cc_news = include_cc_news
|
||||||
|
|
||||||
async def get_trend(
|
async def get_trend(
|
||||||
self,
|
self,
|
||||||
topics: list[str],
|
topics: list[str],
|
||||||
@@ -1054,20 +1075,40 @@ class NewsTrendStrategy(TrendStrategy):
|
|||||||
) -> TrendResponse:
|
) -> TrendResponse:
|
||||||
years_range = self._get_years_range()
|
years_range = self._get_years_range()
|
||||||
start_year, end_year = years_range[0], years_range[-1]
|
start_year, end_year = years_range[0], years_range[-1]
|
||||||
|
years_set = set(years_range)
|
||||||
|
|
||||||
|
cc_news_enabled = self.include_cc_news and not fuzzy
|
||||||
|
|
||||||
accumulated_data = {
|
accumulated_data = {
|
||||||
f"news_topic_{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics}
|
f"{NEWS_ENTITY_PREFIX}{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics}
|
||||||
for t in topics
|
for t in topics
|
||||||
}
|
}
|
||||||
|
if cc_news_enabled:
|
||||||
|
accumulated_data.update({
|
||||||
|
f"{CC_NEWS_ENTITY_PREFIX}{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics}
|
||||||
|
for t in topics
|
||||||
|
})
|
||||||
|
|
||||||
STOP_WORDS = {"in", "and", "or", "und", "oder", "der", "die", "das", "von", "mit", "zu", "at", "by", "on", "for", "to", "a", "an", "the"}
|
STOP_WORDS = {"in", "and", "or", "und", "oder", "der", "die", "das", "von", "mit", "zu", "at", "by", "on", "for", "to", "a", "an", "the"}
|
||||||
|
|
||||||
|
def resolve_keyword_term(idx: int, t_name: str) -> str:
|
||||||
|
"""Picks the raw keyword for a topic, falling back to the topic name itself."""
|
||||||
|
if keywords and idx < len(keywords) and keywords[idx]:
|
||||||
|
raw_kw = keywords[idx]
|
||||||
|
term = raw_kw.split(",")[0].strip() if isinstance(raw_kw, str) else raw_kw
|
||||||
|
if term:
|
||||||
|
return term
|
||||||
|
return t_name
|
||||||
|
|
||||||
|
def is_searchable_term(term: str) -> bool:
|
||||||
|
return bool(term) and term.lower() not in STOP_WORDS and len(term.strip()) > 1
|
||||||
|
|
||||||
# Scan UDE news OpenAlex topics index to get matching news IDs without size limit cutoffs
|
# Scan UDE news OpenAlex topics index to get matching news IDs without size limit cutoffs
|
||||||
async def fetch_news_ids_for_term(idx: int, t_name: str) -> list[str]:
|
async def fetch_news_ids_for_term(idx: int, t_name: str) -> list[str]:
|
||||||
news_ids: Set[str] = set()
|
news_ids: Set[str] = set()
|
||||||
if fuzzy:
|
if fuzzy:
|
||||||
term = t_name
|
term = t_name
|
||||||
es_query = {"term": {"topic_matches.topic_display_name.keyword": term}}
|
es_query = {"match_phrase": {"topic_matches.topic_display_name": term}}
|
||||||
try:
|
try:
|
||||||
async for hit in elasticsearch.scan(
|
async for hit in elasticsearch.scan(
|
||||||
index=ESIndex.AKTUELLES_OPENALEX_TOPICS.value,
|
index=ESIndex.AKTUELLES_OPENALEX_TOPICS.value,
|
||||||
@@ -1081,20 +1122,14 @@ class NewsTrendStrategy(TrendStrategy):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning("Failed to scan UDE news OpenAlex topics index %s: %s", ESIndex.AKTUELLES_OPENALEX_TOPICS.value, e)
|
logger.warning("Failed to scan UDE news OpenAlex topics index %s: %s", ESIndex.AKTUELLES_OPENALEX_TOPICS.value, e)
|
||||||
else:
|
else:
|
||||||
if keywords and idx < len(keywords) and keywords[idx]:
|
term = resolve_keyword_term(idx, t_name)
|
||||||
raw_kw = keywords[idx]
|
|
||||||
term = raw_kw.split(",")[0].strip() if isinstance(raw_kw, str) else raw_kw
|
|
||||||
if not term:
|
|
||||||
term = t_name
|
|
||||||
else:
|
|
||||||
term = t_name
|
|
||||||
|
|
||||||
# If non-fuzzy keyword search, search article content fields in 'aktuell' index
|
# If non-fuzzy keyword search, search article content fields in 'aktuell' index
|
||||||
if term and term.lower() not in STOP_WORDS and len(term.strip()) > 1:
|
if is_searchable_term(term):
|
||||||
try:
|
try:
|
||||||
content_query = {
|
content_query = {
|
||||||
"query_string": {
|
"query_string": {
|
||||||
"query": term,
|
"query": escape_lucene_query(term),
|
||||||
"fields": AKTUELLES_SEARCH_FIELDS,
|
"fields": AKTUELLES_SEARCH_FIELDS,
|
||||||
"default_operator": "AND",
|
"default_operator": "AND",
|
||||||
}
|
}
|
||||||
@@ -1113,12 +1148,59 @@ class NewsTrendStrategy(TrendStrategy):
|
|||||||
|
|
||||||
return list(news_ids)
|
return list(news_ids)
|
||||||
|
|
||||||
matching_ids_list = await asyncio.gather(*(fetch_news_ids_for_term(idx, t) for idx, t in enumerate(topics)))
|
async def fetch_cc_news_counts() -> dict[int, dict[int, int]]:
|
||||||
|
"""Yearly CC-News counts per topic index, from a single _msearch over cc-news-*.
|
||||||
|
The year buckets are read straight off a size=0 date_histogram instead.
|
||||||
|
"""
|
||||||
|
searchable = [
|
||||||
|
(idx, term)
|
||||||
|
for idx, t_name in enumerate(topics)
|
||||||
|
if is_searchable_term(term := resolve_keyword_term(idx, t_name))
|
||||||
|
]
|
||||||
|
if not searchable:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
searches = [
|
||||||
|
(
|
||||||
|
ESIndex.CC_NEWS_WILDCARD.value,
|
||||||
|
TrendQueryBuilder.build_cc_news_year_agg_body(term, CC_NEWS_START_YEAR, end_year),
|
||||||
|
)
|
||||||
|
for _, term in searchable
|
||||||
|
]
|
||||||
|
try:
|
||||||
|
responses = await elasticsearch.msearch(
|
||||||
|
searches, cluster=ESCluster.NES, request_cache=True
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Failed to aggregate CC-News years via msearch: %s", e)
|
||||||
|
return {}
|
||||||
|
|
||||||
|
counts: dict[int, dict[int, int]] = {}
|
||||||
|
for (topic_idx, term), res in zip(searchable, responses):
|
||||||
|
if not isinstance(res, dict) or "error" in res:
|
||||||
|
logger.warning("CC-News msearch entry for %r failed: %s", term, (res or {}).get("error"))
|
||||||
|
continue
|
||||||
|
by_year: dict[int, int] = {}
|
||||||
|
for b in res.get("aggregations", {}).get("by_year", {}).get("buckets", []):
|
||||||
|
try:
|
||||||
|
yr = int(b.get("key_as_string"))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
continue
|
||||||
|
if yr in years_set:
|
||||||
|
by_year[yr] = int(b.get("doc_count", 0))
|
||||||
|
counts[topic_idx] = by_year
|
||||||
|
return counts
|
||||||
|
|
||||||
|
news_ids_future = asyncio.gather(*(fetch_news_ids_for_term(idx, t) for idx, t in enumerate(topics)))
|
||||||
|
if cc_news_enabled:
|
||||||
|
matching_ids_list, cc_news_counts = await asyncio.gather(news_ids_future, fetch_cc_news_counts())
|
||||||
|
else:
|
||||||
|
matching_ids_list, cc_news_counts = await news_ids_future, {}
|
||||||
|
|
||||||
async def count_by_year(t_name: str, news_ids: list[str]):
|
async def count_by_year(t_name: str, news_ids: list[str]):
|
||||||
if not news_ids:
|
if not news_ids:
|
||||||
return
|
return
|
||||||
entity_key = f"news_topic_{t_name}"
|
entity_key = f"{NEWS_ENTITY_PREFIX}{t_name}"
|
||||||
|
|
||||||
# Prepare multi-search payloads for chunks of news_ids to avoid payload limits
|
# Prepare multi-search payloads for chunks of news_ids to avoid payload limits
|
||||||
chunk_queries = []
|
chunk_queries = []
|
||||||
@@ -1164,13 +1246,15 @@ class NewsTrendStrategy(TrendStrategy):
|
|||||||
|
|
||||||
await asyncio.gather(*(count_by_year(t, ids) for t, ids in zip(topics, matching_ids_list)))
|
await asyncio.gather(*(count_by_year(t, ids) for t, ids in zip(topics, matching_ids_list)))
|
||||||
|
|
||||||
|
for topic_idx, t_name in enumerate(topics):
|
||||||
|
entity_key = f"{CC_NEWS_ENTITY_PREFIX}{t_name}"
|
||||||
|
for yr, count in cc_news_counts.get(topic_idx, {}).items():
|
||||||
|
prev_count, _ = accumulated_data[entity_key][t_name][yr]
|
||||||
|
accumulated_data[entity_key][t_name][yr] = (prev_count + count, 1)
|
||||||
|
|
||||||
normalized_lookup = self._normalize_series(years_range, accumulated_data, topics)
|
normalized_lookup = self._normalize_series(years_range, accumulated_data, topics)
|
||||||
|
|
||||||
series_list: list[TrendSeries] = []
|
def build_series(entity_key: str, t_name: str, entity_name: str) -> TrendSeries:
|
||||||
for t_name in topics:
|
|
||||||
entity_key = f"news_topic_{t_name}"
|
|
||||||
topic_data_map: dict[str, list[TopicYearlyData]] = {}
|
|
||||||
|
|
||||||
lookup = normalized_lookup.get((entity_key, t_name), {})
|
lookup = normalized_lookup.get((entity_key, t_name), {})
|
||||||
norm_vals = lookup.get("normalized", [0.0] * len(years_range))
|
norm_vals = lookup.get("normalized", [0.0] * len(years_range))
|
||||||
cum_vals = lookup.get("cumulative", [0.0] * len(years_range))
|
cum_vals = lookup.get("cumulative", [0.0] * len(years_range))
|
||||||
@@ -1188,16 +1272,22 @@ class NewsTrendStrategy(TrendStrategy):
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
for topic in topics:
|
topic_data_map: dict[str, list[TopicYearlyData]] = {topic: yearly_data_items for topic in topics}
|
||||||
topic_data_map[topic] = yearly_data_items
|
|
||||||
|
|
||||||
series_list.append(
|
return TrendSeries(
|
||||||
TrendSeries(
|
entity_id=entity_key,
|
||||||
entity_id=entity_key,
|
entity_name=entity_name,
|
||||||
entity_name=t_name,
|
entity_type="institution",
|
||||||
entity_type="institution",
|
topic_data=topic_data_map,
|
||||||
topic_data=topic_data_map,
|
)
|
||||||
)
|
|
||||||
|
series_list: list[TrendSeries] = [
|
||||||
|
build_series(f"{NEWS_ENTITY_PREFIX}{t_name}", t_name, t_name) for t_name in topics
|
||||||
|
]
|
||||||
|
if cc_news_enabled:
|
||||||
|
series_list.extend(
|
||||||
|
build_series(f"{CC_NEWS_ENTITY_PREFIX}{t_name}", t_name, f"{t_name} (CC-News)")
|
||||||
|
for t_name in topics
|
||||||
)
|
)
|
||||||
|
|
||||||
return TrendResponse(series=series_list, years=years_range)
|
return TrendResponse(series=series_list, years=years_range)
|
||||||
@@ -1269,25 +1359,40 @@ class AllTrendStrategy(TrendStrategy):
|
|||||||
add_composite(pat_series, "patents", "Patentanmeldungen")
|
add_composite(pat_series, "patents", "Patentanmeldungen")
|
||||||
add_composite(proj_series, "projects", "Drittmittelförderung")
|
add_composite(proj_series, "projects", "Drittmittelförderung")
|
||||||
|
|
||||||
if is_ude and news_res:
|
def merge_news_composite(prefix: str, c_id: str, c_name: str) -> bool:
|
||||||
merged_news_topic_data: dict[str, list[TopicYearlyData]] = {}
|
"""Collapses the per-topic news series of one source into a single composite.
|
||||||
|
|
||||||
|
Returns False when the source produced no series at all.
|
||||||
|
"""
|
||||||
|
if not news_res or not any(s.entity_id.startswith(prefix) for s in news_res.series):
|
||||||
|
return False
|
||||||
|
|
||||||
|
merged_topic_data: dict[str, list[TopicYearlyData]] = {}
|
||||||
for topic in topics:
|
for topic in topics:
|
||||||
term_key = f"news_topic_{topic}"
|
term_key = f"{prefix}{topic}"
|
||||||
matching_series = next((s for s in news_res.series if s.entity_id == term_key), None)
|
matching_series = next((s for s in news_res.series if s.entity_id == term_key), None)
|
||||||
if matching_series and topic in matching_series.topic_data:
|
if matching_series and topic in matching_series.topic_data:
|
||||||
merged_news_topic_data[topic] = matching_series.topic_data[topic]
|
merged_topic_data[topic] = matching_series.topic_data[topic]
|
||||||
else:
|
else:
|
||||||
merged_news_topic_data[topic] = [
|
merged_topic_data[topic] = [
|
||||||
TopicYearlyData(year=yr, raw=0, normalized=0.0, cumulative=0.0, institutions_count=1)
|
TopicYearlyData(year=yr, raw=0, normalized=0.0, cumulative=0.0, institutions_count=1)
|
||||||
for yr in years_range
|
for yr in years_range
|
||||||
]
|
]
|
||||||
|
|
||||||
news_series = TrendSeries(
|
add_composite(
|
||||||
entity_id="news",
|
TrendSeries(
|
||||||
entity_name="UDE Campus Aktuell Beiträge",
|
entity_id=c_id,
|
||||||
entity_type="institution",
|
entity_name=c_name,
|
||||||
topic_data=merged_news_topic_data,
|
entity_type="institution",
|
||||||
|
topic_data=merged_topic_data,
|
||||||
|
),
|
||||||
|
c_id,
|
||||||
|
c_name,
|
||||||
)
|
)
|
||||||
add_composite(news_series, "news", "UDE Campus Aktuell Beiträge")
|
return True
|
||||||
|
|
||||||
|
if is_ude:
|
||||||
|
merge_news_composite(NEWS_ENTITY_PREFIX, "news", "UDE Campus Aktuell Beiträge")
|
||||||
|
merge_news_composite(CC_NEWS_ENTITY_PREFIX, CC_NEWS_COMPOSITE_ID, "Web-Nachrichten (CC-News)")
|
||||||
|
|
||||||
return TrendResponse(series=composite_series, years=years_range)
|
return TrendResponse(series=composite_series, years=years_range)
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ router = APIRouter(prefix=RouterPrefixes.WORKS_V2, tags=[Tags.WORKS_V2])
|
|||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
"/{raw_oa_work_id}",
|
"/single/{raw_oa_work_id}",
|
||||||
operation_id="getWorkById",
|
operation_id="getWorkById",
|
||||||
summary="Returns a work based on its ID.",
|
summary="Returns a work based on its ID.",
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -654,6 +654,7 @@ async def _search_works(
|
|||||||
size=size,
|
size=size,
|
||||||
offset=page * size,
|
offset=page * size,
|
||||||
sort=sort,
|
sort=sort,
|
||||||
|
track_total_hits=True
|
||||||
)
|
)
|
||||||
|
|
||||||
hits_block = response.get("hits", {})
|
hits_block = response.get("hits", {})
|
||||||
|
|||||||
@@ -103,11 +103,11 @@ model/dfgPersonSummary.ts
|
|||||||
model/dfgPersonSummaryPage.ts
|
model/dfgPersonSummaryPage.ts
|
||||||
model/dfgProjectDetails.ts
|
model/dfgProjectDetails.ts
|
||||||
model/dfgProjectInstitutionRole.ts
|
model/dfgProjectInstitutionRole.ts
|
||||||
|
model/dfgProjectKeyword.ts
|
||||||
model/dfgProjectPage.ts
|
model/dfgProjectPage.ts
|
||||||
model/dfgProjectPersonRole.ts
|
model/dfgProjectPersonRole.ts
|
||||||
model/dfgProjectPublicationSummary.ts
|
model/dfgProjectPublicationSummary.ts
|
||||||
model/dfgProjectStatusStatistics.ts
|
model/dfgProjectStatusStatistics.ts
|
||||||
model/dfgProjectSubjectArea.ts
|
|
||||||
model/dfgProjectSubprojectSummary.ts
|
model/dfgProjectSubprojectSummary.ts
|
||||||
model/dfgProjectSummary.ts
|
model/dfgProjectSummary.ts
|
||||||
model/dfgProjectTopic.ts
|
model/dfgProjectTopic.ts
|
||||||
|
|||||||
@@ -65,6 +65,71 @@ export class AuthService extends BaseService {
|
|||||||
super(basePath, configuration);
|
super(basePath, configuration);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if user can fetch GDPR-relevant data
|
||||||
|
* Check if the authenticated user can fetch GDPR-relevant data for a given author and institution.
|
||||||
|
* @endpoint get /api/auth/v2/can-fetch-gdpr-relevant-data
|
||||||
|
* @param rawOaAuthorId OpenAlex author ID to check access for
|
||||||
|
* @param rawOaInstitutionId OpenAlex institution ID to check access for
|
||||||
|
* @param secureFgpAcc
|
||||||
|
* @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 canFetchGdprRelevantData(rawOaAuthorId?: string, rawOaInstitutionId?: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<boolean>;
|
||||||
|
public canFetchGdprRelevantData(rawOaAuthorId?: string, rawOaInstitutionId?: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<boolean>>;
|
||||||
|
public canFetchGdprRelevantData(rawOaAuthorId?: string, rawOaInstitutionId?: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<boolean>>;
|
||||||
|
public canFetchGdprRelevantData(rawOaAuthorId?: string, rawOaInstitutionId?: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
|
||||||
|
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>rawOaAuthorId, 'raw_oa_author_id');
|
||||||
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
|
<any>rawOaInstitutionId, 'raw_oa_institution_id');
|
||||||
|
|
||||||
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
// authentication (HTTPBearer) required
|
||||||
|
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||||
|
|
||||||
|
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/auth/v2/can-fetch-gdpr-relevant-data`;
|
||||||
|
const { basePath, withCredentials } = this.configuration;
|
||||||
|
return this.httpClient.request<boolean>('get', `${basePath}${localVarPath}`,
|
||||||
|
{
|
||||||
|
context: localVarHttpContext,
|
||||||
|
params: localVarQueryParameters,
|
||||||
|
responseType: <any>responseType_,
|
||||||
|
...(withCredentials ? { withCredentials } : {}),
|
||||||
|
headers: localVarHeaders,
|
||||||
|
observe: observe,
|
||||||
|
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||||
|
reportProgress: reportProgress
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Change Password
|
* Change Password
|
||||||
* Change the user\'s password and invalidate existing tokens.
|
* Change the user\'s password and invalidate existing tokens.
|
||||||
|
|||||||
+1528
-526
File diff suppressed because it is too large
Load Diff
@@ -66,7 +66,7 @@ export class ProjectsService extends BaseService {
|
|||||||
/**
|
/**
|
||||||
* Get DFG projects.
|
* Get DFG projects.
|
||||||
* Returns a page of DFG projects based on the provided pagination parameters and optional institution filter.
|
* Returns a page of DFG projects based on the provided pagination parameters and optional institution filter.
|
||||||
* @endpoint get /api/projects/person/dfg/search
|
* @endpoint get /api/projects/dfg/search
|
||||||
* @param rawOaInstitutionId The openalex institution ID to filter by.
|
* @param rawOaInstitutionId The openalex institution ID to filter by.
|
||||||
* @param authorId The openalex author ID to filter by.
|
* @param authorId The openalex author ID to filter by.
|
||||||
* @param authorFilterIds The dfg author IDs to filter by.
|
* @param authorFilterIds The dfg author IDs to filter by.
|
||||||
@@ -82,13 +82,14 @@ export class ProjectsService extends BaseService {
|
|||||||
* @param sortBy The field to sort by.
|
* @param sortBy The field to sort by.
|
||||||
* @param sortDirection The sort direction (asc or desc).
|
* @param sortDirection The sort direction (asc or desc).
|
||||||
* @param fuzzy Use topic_id resolution if True, otherwise use raw keyword search.
|
* @param fuzzy Use topic_id resolution if True, otherwise use raw keyword search.
|
||||||
|
* @param secureFgpAcc
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
* @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.
|
* @param reportProgress flag to report request and response progress.
|
||||||
*/
|
*/
|
||||||
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<DfgProjectPage>;
|
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<string>, institutionIds?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<DfgProjectPage>;
|
||||||
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<DfgProjectPage>>;
|
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<string>, institutionIds?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<DfgProjectPage>>;
|
||||||
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<DfgProjectPage>>;
|
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<string>, institutionIds?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<DfgProjectPage>>;
|
||||||
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<number>, institutionIds?: Array<number>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
public getDfgProjects(rawOaInstitutionId?: string, authorId?: string, authorFilterIds?: Array<string>, institutionIds?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
|
||||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
@@ -152,6 +153,9 @@ export class ProjectsService extends BaseService {
|
|||||||
|
|
||||||
let localVarHeaders = this.defaultHeaders;
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
// authentication (HTTPBearer) required
|
||||||
|
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||||
|
|
||||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
'application/json'
|
'application/json'
|
||||||
]);
|
]);
|
||||||
@@ -175,7 +179,7 @@ export class ProjectsService extends BaseService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let localVarPath = `/api/projects/person/dfg/search`;
|
let localVarPath = `/api/projects/dfg/search`;
|
||||||
const { basePath, withCredentials } = this.configuration;
|
const { basePath, withCredentials } = this.configuration;
|
||||||
return this.httpClient.request<DfgProjectPage>('get', `${basePath}${localVarPath}`,
|
return this.httpClient.request<DfgProjectPage>('get', `${basePath}${localVarPath}`,
|
||||||
{
|
{
|
||||||
@@ -846,13 +850,14 @@ export class ProjectsService extends BaseService {
|
|||||||
* @param sortBy Sort field.
|
* @param sortBy Sort field.
|
||||||
* @param sortDirection Sort direction: asc or desc.
|
* @param sortDirection Sort direction: asc or desc.
|
||||||
* @param fuzzy Use OpenAlex topic-id resolution if true, otherwise raw keyword search.
|
* @param fuzzy Use OpenAlex topic-id resolution if true, otherwise raw keyword search.
|
||||||
|
* @param secureFgpAcc
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
* @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.
|
* @param reportProgress flag to report request and response progress.
|
||||||
*/
|
*/
|
||||||
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<BundProjectPage>;
|
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<BundProjectPage>;
|
||||||
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<BundProjectPage>>;
|
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<BundProjectPage>>;
|
||||||
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<BundProjectPage>>;
|
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<BundProjectPage>>;
|
||||||
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
public searchBundProjectsWithFilters(executingAgency?: Array<string>, fundingArts?: Array<string>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, rawOaInstitutionId?: string, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
|
||||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||||
if (executingAgency) {
|
if (executingAgency) {
|
||||||
@@ -920,6 +925,9 @@ export class ProjectsService extends BaseService {
|
|||||||
|
|
||||||
let localVarHeaders = this.defaultHeaders;
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
// authentication (HTTPBearer) required
|
||||||
|
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||||
|
|
||||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
'application/json'
|
'application/json'
|
||||||
]);
|
]);
|
||||||
@@ -984,13 +992,14 @@ export class ProjectsService extends BaseService {
|
|||||||
* @param sortBy Sort field.
|
* @param sortBy Sort field.
|
||||||
* @param sortDirection Sort direction: asc or desc.
|
* @param sortDirection Sort direction: asc or desc.
|
||||||
* @param fuzzy Use OpenAlex topic-id resolution if true, otherwise raw keyword search.
|
* @param fuzzy Use OpenAlex topic-id resolution if true, otherwise raw keyword search.
|
||||||
|
* @param secureFgpAcc
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
* @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.
|
* @param reportProgress flag to report request and response progress.
|
||||||
*/
|
*/
|
||||||
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<EuCordisProjectSearchPage>;
|
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<EuCordisProjectSearchPage>;
|
||||||
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<EuCordisProjectSearchPage>>;
|
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<EuCordisProjectSearchPage>>;
|
||||||
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<EuCordisProjectSearchPage>>;
|
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<EuCordisProjectSearchPage>>;
|
||||||
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
public searchEuCordisProjects(rawOaInstitutionId?: string, authorId?: string, authorIds?: Array<string>, organizationIds?: Array<string>, organizationNames?: Array<string>, projectTypes?: Array<EuCordisProjectType>, title?: string, keywords?: Array<string>, topicIds?: Array<string>, filterTopicIds?: Array<string>, fundingStartYears?: Array<string>, fundingEndYears?: Array<string>, countries?: Array<string>, frameworkProgrammes?: Array<string>, fundingSchemes?: Array<string>, statuses?: Array<string>, page?: number, size?: number, sortBy?: string, sortDirection?: string, fuzzy?: boolean, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||||
|
|
||||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||||
@@ -1090,6 +1099,9 @@ export class ProjectsService extends BaseService {
|
|||||||
|
|
||||||
let localVarHeaders = this.defaultHeaders;
|
let localVarHeaders = this.defaultHeaders;
|
||||||
|
|
||||||
|
// authentication (HTTPBearer) required
|
||||||
|
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
|
||||||
|
|
||||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||||
'application/json'
|
'application/json'
|
||||||
]);
|
]);
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -511,7 +511,7 @@ export class WorksV2Service extends BaseService {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a work based on its ID.
|
* Returns a work based on its ID.
|
||||||
* @endpoint get /api/works/v2/{raw_oa_work_id}
|
* @endpoint get /api/works/v2/single/{raw_oa_work_id}
|
||||||
* @param rawOaWorkId The raw OpenAlex work id.
|
* @param rawOaWorkId The raw OpenAlex work id.
|
||||||
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
|
* @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.
|
* @param reportProgress flag to report request and response progress.
|
||||||
@@ -549,7 +549,7 @@ export class WorksV2Service extends BaseService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let localVarPath = `/api/works/v2/${this.configuration.encodeParam({name: "rawOaWorkId", value: rawOaWorkId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
|
let localVarPath = `/api/works/v2/single/${this.configuration.encodeParam({name: "rawOaWorkId", value: rawOaWorkId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
|
||||||
const { basePath, withCredentials } = this.configuration;
|
const { basePath, withCredentials } = this.configuration;
|
||||||
return this.httpClient.request<Work>('get', `${basePath}${localVarPath}`,
|
return this.httpClient.request<Work>('get', `${basePath}${localVarPath}`,
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
import { DfgProjectPersonRole } from './dfgProjectPersonRole';
|
import { DfgProjectPersonRole } from './dfgProjectPersonRole';
|
||||||
import { DfgProjectSubprojectSummary } from './dfgProjectSubprojectSummary';
|
import { DfgProjectSubprojectSummary } from './dfgProjectSubprojectSummary';
|
||||||
import { DfgProjectInstitutionRole } from './dfgProjectInstitutionRole';
|
import { DfgProjectInstitutionRole } from './dfgProjectInstitutionRole';
|
||||||
import { DfgProjectSubjectArea } from './dfgProjectSubjectArea';
|
import { DFGProjectFachgebieteInner } from './dFGProjectFachgebieteInner';
|
||||||
import { Topic } from './topic';
|
import { Topic } from './topic';
|
||||||
import { DfgProjectPublicationSummary } from './dfgProjectPublicationSummary';
|
import { DfgProjectPublicationSummary } from './dfgProjectPublicationSummary';
|
||||||
|
|
||||||
@@ -49,7 +49,7 @@ export interface DfgProjectDetails {
|
|||||||
/**
|
/**
|
||||||
* Detailed DFG subject-area classification entries (Fachsystematik)
|
* Detailed DFG subject-area classification entries (Fachsystematik)
|
||||||
*/
|
*/
|
||||||
subject_classifications?: Array<DfgProjectSubjectArea>;
|
subject_classifications?: Array<DFGProjectFachgebieteInner>;
|
||||||
international_relation_de?: string | null;
|
international_relation_de?: string | null;
|
||||||
international_relation_en?: string | null;
|
international_relation_en?: string | null;
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
/**
|
||||||
|
* Innovation Search Engine API
|
||||||
|
*
|
||||||
|
*
|
||||||
|
*
|
||||||
|
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||||
|
* https://openapi-generator.tech
|
||||||
|
* Do not edit the class manually.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
export interface DfgProjectKeyword {
|
||||||
|
name: string;
|
||||||
|
project_count: number;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
/**
|
|
||||||
* 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.
|
|
||||||
*/
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A single subject-area classification entry (DFG \'Fachsystematik\').
|
|
||||||
*/
|
|
||||||
export interface DfgProjectSubjectArea {
|
|
||||||
fach?: string | null;
|
|
||||||
fachgebiet?: string | null;
|
|
||||||
fachkollegium?: string | null;
|
|
||||||
wissenschaftsbereich?: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -7,6 +7,7 @@
|
|||||||
* https://openapi-generator.tech
|
* https://openapi-generator.tech
|
||||||
* Do not edit the class manually.
|
* Do not edit the class manually.
|
||||||
*/
|
*/
|
||||||
|
import { DfgProjectKeyword } from './dfgProjectKeyword';
|
||||||
|
|
||||||
|
|
||||||
export interface DfgProjectTopic {
|
export interface DfgProjectTopic {
|
||||||
@@ -16,5 +17,5 @@ export interface DfgProjectTopic {
|
|||||||
field?: string | null;
|
field?: string | null;
|
||||||
domain?: string | null;
|
domain?: string | null;
|
||||||
project_count: number;
|
project_count: number;
|
||||||
|
keywords: Array<DfgProjectKeyword>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
/**
|
||||||
|
* 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 { DomainFieldsInner } from './domainFieldsInner';
|
||||||
|
import { DomainIds } from './domainIds';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Top-level category in the topic hierarchy (4 total)
|
||||||
|
*/
|
||||||
|
export interface Domain {
|
||||||
|
id?: string | null;
|
||||||
|
display_name?: string | null;
|
||||||
|
description?: string | null;
|
||||||
|
display_name_alternatives?: Array<string> | null;
|
||||||
|
fields?: Array<DomainFieldsInner> | null;
|
||||||
|
siblings?: Array<DomainFieldsInner> | null;
|
||||||
|
ids?: DomainIds | null;
|
||||||
|
works_count?: number | null;
|
||||||
|
cited_by_count?: number | null;
|
||||||
|
works_api_url?: string | null;
|
||||||
|
created_date?: string | null;
|
||||||
|
updated_date?: string | null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* DomainFieldsInner
|
||||||
|
*/
|
||||||
|
export interface DomainFieldsInner {
|
||||||
|
id?: string | null;
|
||||||
|
display_name?: string | null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* External identifiers:
|
||||||
|
*/
|
||||||
|
export interface DomainIds {
|
||||||
|
openalex?: string | null;
|
||||||
|
wikidata?: string | null;
|
||||||
|
wikipedia?: string | null;
|
||||||
|
}
|
||||||
@@ -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 { DomainFieldsInner } from './domainFieldsInner';
|
||||||
|
import { DomainIds } from './domainIds';
|
||||||
|
import { WorkTopicDomain } from './workTopicDomain';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Second-level category in the topic hierarchy (26 total)
|
||||||
|
*/
|
||||||
|
export interface ModelField {
|
||||||
|
id?: string | null;
|
||||||
|
display_name?: string | null;
|
||||||
|
description?: string | null;
|
||||||
|
display_name_alternatives?: Array<string> | null;
|
||||||
|
domain?: WorkTopicDomain | null;
|
||||||
|
subfields?: Array<DomainFieldsInner> | null;
|
||||||
|
siblings?: Array<DomainFieldsInner> | null;
|
||||||
|
ids?: DomainIds | null;
|
||||||
|
works_count?: number | null;
|
||||||
|
cited_by_count?: number | null;
|
||||||
|
works_api_url?: string | null;
|
||||||
|
created_date?: string | null;
|
||||||
|
updated_date?: string | null;
|
||||||
|
}
|
||||||
@@ -68,16 +68,19 @@ export * from './dfgPersonSummary';
|
|||||||
export * from './dfgPersonSummaryPage';
|
export * from './dfgPersonSummaryPage';
|
||||||
export * from './dfgProjectDetails';
|
export * from './dfgProjectDetails';
|
||||||
export * from './dfgProjectInstitutionRole';
|
export * from './dfgProjectInstitutionRole';
|
||||||
|
export * from './dfgProjectKeyword';
|
||||||
export * from './dfgProjectPage';
|
export * from './dfgProjectPage';
|
||||||
export * from './dfgProjectPersonRole';
|
export * from './dfgProjectPersonRole';
|
||||||
export * from './dfgProjectPublicationSummary';
|
export * from './dfgProjectPublicationSummary';
|
||||||
export * from './dfgProjectStatusStatistics';
|
export * from './dfgProjectStatusStatistics';
|
||||||
export * from './dfgProjectSubjectArea';
|
|
||||||
export * from './dfgProjectSubprojectSummary';
|
export * from './dfgProjectSubprojectSummary';
|
||||||
export * from './dfgProjectSummary';
|
export * from './dfgProjectSummary';
|
||||||
export * from './dfgProjectTopic';
|
export * from './dfgProjectTopic';
|
||||||
export * from './dfgProjectTopics';
|
export * from './dfgProjectTopics';
|
||||||
export * from './dockerHealth';
|
export * from './dockerHealth';
|
||||||
|
export * from './domain';
|
||||||
|
export * from './domainFieldsInner';
|
||||||
|
export * from './domainIds';
|
||||||
export * from './edge';
|
export * from './edge';
|
||||||
export * from './euCordisEurosciVocSummary';
|
export * from './euCordisEurosciVocSummary';
|
||||||
export * from './euCordisOrganizationSelectorPage';
|
export * from './euCordisOrganizationSelectorPage';
|
||||||
@@ -172,6 +175,7 @@ export * from './matchedTopic';
|
|||||||
export * from './mentionedPerson';
|
export * from './mentionedPerson';
|
||||||
export * from './meta';
|
export * from './meta';
|
||||||
export * from './model2YrMeanCitedness';
|
export * from './model2YrMeanCitedness';
|
||||||
|
export * from './modelField';
|
||||||
export * from './newsArticle';
|
export * from './newsArticle';
|
||||||
export * from './newsArticleDetail';
|
export * from './newsArticleDetail';
|
||||||
export * from './newsPage';
|
export * from './newsPage';
|
||||||
@@ -206,6 +210,9 @@ export * from './score';
|
|||||||
export * from './selectedAuthorsRequest';
|
export * from './selectedAuthorsRequest';
|
||||||
export * from './sortDirection';
|
export * from './sortDirection';
|
||||||
export * from './startCollaborationGraphResponse';
|
export * from './startCollaborationGraphResponse';
|
||||||
|
export * from './subfield';
|
||||||
|
export * from './subfieldDomain';
|
||||||
|
export * from './subfieldField';
|
||||||
export * from './subfieldShare';
|
export * from './subfieldShare';
|
||||||
export * from './timespan';
|
export * from './timespan';
|
||||||
export * from './tokenType';
|
export * from './tokenType';
|
||||||
|
|||||||
@@ -7,16 +7,16 @@
|
|||||||
* https://openapi-generator.tech
|
* https://openapi-generator.tech
|
||||||
* Do not edit the class manually.
|
* Do not edit the class manually.
|
||||||
*/
|
*/
|
||||||
|
import { MatchedTopic } from './matchedTopic';
|
||||||
|
|
||||||
export interface NewsArticle {
|
export interface NewsArticle {
|
||||||
id: string;
|
id: string;
|
||||||
date?: string | null;
|
date?: string | null;
|
||||||
maintitle?: string | null;
|
maintitle?: string | null;
|
||||||
author?: string | null;
|
author?: string | null;
|
||||||
url?: string | null;
|
url?: string | null;
|
||||||
relevant?: boolean | null;
|
relevant?: boolean | null;
|
||||||
snippet?: string | null;
|
snippet?: string | null;
|
||||||
related?: boolean | null;
|
related?: boolean | null;
|
||||||
|
topics?: Array<MatchedTopic> | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,19 +10,17 @@
|
|||||||
import { MatchedTopic } from './matchedTopic';
|
import { MatchedTopic } from './matchedTopic';
|
||||||
import { MentionedPerson } from './mentionedPerson';
|
import { MentionedPerson } from './mentionedPerson';
|
||||||
|
|
||||||
|
|
||||||
export interface NewsArticleDetail {
|
export interface NewsArticleDetail {
|
||||||
id: string;
|
id: string;
|
||||||
date?: string | null;
|
date?: string | null;
|
||||||
maintitle?: string | null;
|
maintitle?: string | null;
|
||||||
author?: string | null;
|
author?: string | null;
|
||||||
url?: string | null;
|
url?: string | null;
|
||||||
relevant?: boolean | null;
|
relevant?: boolean | null;
|
||||||
snippet?: string | null;
|
snippet?: string | null;
|
||||||
related?: boolean | null;
|
related?: boolean | null;
|
||||||
full_content?: string | null;
|
topics?: Array<MatchedTopic>;
|
||||||
authors?: Array<MentionedPerson>;
|
full_content?: string | null;
|
||||||
keywords?: Array<string>;
|
authors?: Array<MentionedPerson>;
|
||||||
topics?: Array<MatchedTopic>;
|
keywords?: Array<string>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
/**
|
||||||
|
* 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 { DomainFieldsInner } from './domainFieldsInner';
|
||||||
|
import { DomainIds } from './domainIds';
|
||||||
|
import { SubfieldDomain } from './subfieldDomain';
|
||||||
|
import { SubfieldField } from './subfieldField';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Third-level category in the topic hierarchy (254 total)
|
||||||
|
*/
|
||||||
|
export interface Subfield {
|
||||||
|
id?: string | null;
|
||||||
|
display_name?: string | null;
|
||||||
|
description?: string | null;
|
||||||
|
display_name_alternatives?: Array<string> | null;
|
||||||
|
field?: SubfieldField | null;
|
||||||
|
domain?: SubfieldDomain | null;
|
||||||
|
topics?: Array<DomainFieldsInner> | null;
|
||||||
|
siblings?: Array<DomainFieldsInner> | null;
|
||||||
|
ids?: DomainIds | null;
|
||||||
|
works_count?: number | null;
|
||||||
|
cited_by_count?: number | null;
|
||||||
|
works_api_url?: string | null;
|
||||||
|
created_date?: string | null;
|
||||||
|
updated_date?: string | null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The domain containing this subfield (top level of hierarchy).
|
||||||
|
*/
|
||||||
|
export interface SubfieldDomain {
|
||||||
|
id?: string | null;
|
||||||
|
display_name?: string | null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The field containing this subfield (parent level).
|
||||||
|
*/
|
||||||
|
export interface SubfieldField {
|
||||||
|
id?: string | null;
|
||||||
|
display_name?: string | null;
|
||||||
|
}
|
||||||
@@ -6,7 +6,6 @@ import { personPatentsResolver } from './resolvers/person-patents.resolver';
|
|||||||
import { personResolver } from './resolvers/person.resolver';
|
import { personResolver } from './resolvers/person.resolver';
|
||||||
import { personNewsResolver } from './resolvers/person-news.resolver';
|
import { personNewsResolver } from './resolvers/person-news.resolver';
|
||||||
import { institutionResolver } from './resolvers/institution.resolver';
|
import { institutionResolver } from './resolvers/institution.resolver';
|
||||||
import { bundProjectPageResolver } from './resolvers/bund-project-page.resolver';
|
|
||||||
import {
|
import {
|
||||||
dfgProjectsResolver,
|
dfgProjectsResolver,
|
||||||
RESOLVING_PROJECT_PAGE_FOR,
|
RESOLVING_PROJECT_PAGE_FOR,
|
||||||
@@ -37,6 +36,7 @@ import {
|
|||||||
workPageResolver,
|
workPageResolver,
|
||||||
workQueryParamKeys,
|
workQueryParamKeys,
|
||||||
} from './resolvers/work-page.resolver';
|
} from './resolvers/work-page.resolver';
|
||||||
|
import { keywordsNewsPageResolver } from './resolvers/keywords-news-page.resolver';
|
||||||
import { selectedTopicsResolver } from './resolvers/selected-topics.resolver';
|
import { selectedTopicsResolver } from './resolvers/selected-topics.resolver';
|
||||||
import { selectedInstitutionsResolver } from './resolvers/selected-institutions.resolver';
|
import { selectedInstitutionsResolver } from './resolvers/selected-institutions.resolver';
|
||||||
import { selectedBundInstitutionsResolver } from './resolvers/selected-bund-institutions.resolver';
|
import { selectedBundInstitutionsResolver } from './resolvers/selected-bund-institutions.resolver';
|
||||||
@@ -65,6 +65,7 @@ import {
|
|||||||
topicQueryParamKeys,
|
topicQueryParamKeys,
|
||||||
} from './resolvers/topic-page.resolver';
|
} from './resolvers/topic-page.resolver';
|
||||||
import { topicResolver } from './resolvers/topic.resolver';
|
import { topicResolver } from './resolvers/topic.resolver';
|
||||||
|
import { canFetchGdprRelevantDataResolver } from './resolvers/can-fetch-gdpr-relevant-data.resolver';
|
||||||
export const routes: Routes = [
|
export const routes: Routes = [
|
||||||
{
|
{
|
||||||
path: '',
|
path: '',
|
||||||
@@ -273,7 +274,14 @@ export const routes: Routes = [
|
|||||||
resolvingFor: RESOLVING_WORK_PAGE_FOR.KEYWORDS_SEARCH,
|
resolvingFor: RESOLVING_WORK_PAGE_FOR.KEYWORDS_SEARCH,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{ path: 'news', component: KeywordsToNewsResultsComponent },
|
{
|
||||||
|
path: 'news',
|
||||||
|
component: KeywordsToNewsResultsComponent,
|
||||||
|
runGuardsAndResolvers: 'always',
|
||||||
|
resolve: {
|
||||||
|
newsPage: keywordsNewsPageResolver,
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: 'trends',
|
path: 'trends',
|
||||||
component: UniTrendParentComponent,
|
component: UniTrendParentComponent,
|
||||||
@@ -493,6 +501,7 @@ export const routes: Routes = [
|
|||||||
personData: personResolver,
|
personData: personResolver,
|
||||||
personBio: personBioResolver,
|
personBio: personBioResolver,
|
||||||
personPatents: personPatentsResolver,
|
personPatents: personPatentsResolver,
|
||||||
|
canFetchGdprRelevantData: canFetchGdprRelevantDataResolver,
|
||||||
},
|
},
|
||||||
runGuardsAndResolvers: (from, to) => from.params['id'] !== to.params['id'],
|
runGuardsAndResolvers: (from, to) => from.params['id'] !== to.params['id'],
|
||||||
children: [
|
children: [
|
||||||
@@ -658,16 +667,12 @@ export const routes: Routes = [
|
|||||||
import('./modules/institution/institution.component').then(
|
import('./modules/institution/institution.component').then(
|
||||||
(mod) => mod.InstitutionComponent,
|
(mod) => mod.InstitutionComponent,
|
||||||
),
|
),
|
||||||
resolve: { institution: institutionResolver },
|
resolve: {
|
||||||
|
institution: institutionResolver,
|
||||||
|
canFetchGdprRelevantData: canFetchGdprRelevantDataResolver,
|
||||||
|
},
|
||||||
children: [
|
children: [
|
||||||
{ path: '', pathMatch: 'full', redirectTo: 'overview' },
|
{ path: '', pathMatch: 'full', redirectTo: 'publications' },
|
||||||
{
|
|
||||||
path: 'overview',
|
|
||||||
loadComponent: () =>
|
|
||||||
import('./modules/institution-overview/institution-overview.component').then(
|
|
||||||
(mod) => mod.InstitutionOverviewComponent,
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
path: 'publications',
|
path: 'publications',
|
||||||
loadComponent: () =>
|
loadComponent: () =>
|
||||||
@@ -696,7 +701,9 @@ export const routes: Routes = [
|
|||||||
bundProjectsFunding: bundProjectsFundingResolver,
|
bundProjectsFunding: bundProjectsFundingResolver,
|
||||||
cordisEuProjectsFunding: cordisEuProjectsFundingResolver,
|
cordisEuProjectsFunding: cordisEuProjectsFundingResolver,
|
||||||
},
|
},
|
||||||
runGuardsAndResolvers: 'always',
|
data: {
|
||||||
|
enableFilters: false,
|
||||||
|
},
|
||||||
children: [
|
children: [
|
||||||
{
|
{
|
||||||
path: '',
|
path: '',
|
||||||
@@ -746,18 +753,6 @@ export const routes: Routes = [
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
// resolve: {
|
|
||||||
// bundProjectPage: bundProjectPageResolver,
|
|
||||||
// bundProjectsFunding: bundProjectsFundingResolver,
|
|
||||||
// cordisEuProjectPage: euCordisProjectsResolver,
|
|
||||||
// cordisEuProjectsFunding: cordisEuProjectsFundingResolver,
|
|
||||||
// },
|
|
||||||
// runGuardsAndResolvers: (from, to) => {
|
|
||||||
// const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search'];
|
|
||||||
// return keys.some(
|
|
||||||
// (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
|
|
||||||
// );
|
|
||||||
// },
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'patents',
|
path: 'patents',
|
||||||
|
|||||||
@@ -1,76 +1,80 @@
|
|||||||
import {
|
import {
|
||||||
Directive,
|
Directive,
|
||||||
OnChanges,
|
|
||||||
Input,
|
|
||||||
ElementRef,
|
ElementRef,
|
||||||
|
Input,
|
||||||
|
OnChanges,
|
||||||
Renderer2,
|
Renderer2,
|
||||||
|
SimpleChanges,
|
||||||
|
effect,
|
||||||
|
inject,
|
||||||
} from '@angular/core';
|
} from '@angular/core';
|
||||||
import { SimpleChanges } from '@angular/core';
|
import { ResolverStateService } from '../../app/shared/services/resolver-state.service';
|
||||||
@Directive({ selector: '[skText]', standalone: true })
|
|
||||||
|
@Directive({
|
||||||
|
selector: 'span, [skText]',
|
||||||
|
standalone: true,
|
||||||
|
})
|
||||||
export class SkTextDirective implements OnChanges {
|
export class SkTextDirective implements OnChanges {
|
||||||
@Input() skText = false;
|
@Input() skText = false;
|
||||||
|
|
||||||
private originalText = '';
|
private readonly el = inject(ElementRef<HTMLElement>);
|
||||||
private originalColor = '';
|
private readonly renderer = inject(Renderer2);
|
||||||
|
private readonly resolverStateService = inject(ResolverStateService);
|
||||||
|
|
||||||
constructor(
|
constructor() {
|
||||||
private el: ElementRef,
|
effect(() => {
|
||||||
private renderer: Renderer2,
|
const loading = this.skText || this.resolverStateService.isResolving();
|
||||||
) {}
|
|
||||||
|
|
||||||
ngOnChanges(changes: SimpleChanges) {
|
if (loading) {
|
||||||
const change = changes['skText'];
|
this.showSkeleton();
|
||||||
|
} else {
|
||||||
// skip if value didn't actually change, or is undefined
|
this.hideSkeleton();
|
||||||
if (!change) return;
|
}
|
||||||
|
});
|
||||||
this.skText ? this.showSkeleton() : this.hideSkeleton();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private showSkeleton() {
|
ngOnChanges(changes: SimpleChanges): void {
|
||||||
const el: HTMLElement = this.el.nativeElement;
|
if (!changes['skText']) {
|
||||||
this.originalText = el.textContent ?? '';
|
return;
|
||||||
this.originalColor = el.style.color;
|
}
|
||||||
|
|
||||||
// measure natural width before blanking text
|
if (this.skText || this.resolverStateService.isResolving()) {
|
||||||
const width = Math.min(Math.max(this.originalText.length * 7.5, 48), 60);
|
this.showSkeleton();
|
||||||
const height = 20;
|
} else {
|
||||||
this.renderer.addClass(el, 'sk-text-loading');
|
this.hideSkeleton();
|
||||||
this.renderer.setStyle(el, 'color', 'transparent');
|
}
|
||||||
this.renderer.setStyle(
|
}
|
||||||
el,
|
|
||||||
'background',
|
|
||||||
'linear-gradient(90deg, #e2e8f0 25%, #f8fafc 50%, #e2e8f0 75%)',
|
|
||||||
);
|
|
||||||
this.renderer.setStyle(el, 'background-size', '600px 100%');
|
|
||||||
this.renderer.setStyle(el, 'animation', 'sk-shimmer 1.6s infinite linear');
|
|
||||||
this.renderer.setStyle(el, 'border-radius', '4px');
|
|
||||||
this.renderer.setStyle(el, 'min-width', `${width}px`);
|
|
||||||
this.renderer.setStyle(el, 'max-height', `${height}px`);
|
|
||||||
this.renderer.setStyle(el, 'display', 'inline-block');
|
|
||||||
this.renderer.setStyle(el, 'overflow', 'hidden');
|
|
||||||
this.renderer.setStyle(el, 'pointer-events', 'none');
|
|
||||||
|
|
||||||
Array.from(el.children).forEach((child) => {
|
private showSkeleton(): void {
|
||||||
|
const element = this.el.nativeElement;
|
||||||
|
|
||||||
|
if (element.classList.contains('sk-text-loading')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const text = element.textContent?.trim() ?? '';
|
||||||
|
|
||||||
|
// For ordinary text elements only. Table cells use CSS width naturally.
|
||||||
|
if (element.tagName.toLowerCase() !== 'td') {
|
||||||
|
this.renderer.setStyle(element, 'min-width', `${20}px`);
|
||||||
|
this.renderer.setStyle(element, 'height', '20px');
|
||||||
|
}
|
||||||
|
|
||||||
|
this.renderer.addClass(element, 'sk-text-loading');
|
||||||
|
|
||||||
|
Array.from(element.children).forEach((child) => {
|
||||||
this.renderer.setStyle(child, 'visibility', 'hidden');
|
this.renderer.setStyle(child, 'visibility', 'hidden');
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private hideSkeleton() {
|
private hideSkeleton(): void {
|
||||||
const el: HTMLElement = this.el.nativeElement;
|
const element = this.el.nativeElement;
|
||||||
this.renderer.removeClass(el, 'sk-text-loading');
|
|
||||||
this.renderer.removeStyle(el, 'color');
|
|
||||||
this.renderer.removeStyle(el, 'background');
|
|
||||||
this.renderer.removeStyle(el, 'background-size');
|
|
||||||
this.renderer.removeStyle(el, 'animation');
|
|
||||||
this.renderer.removeStyle(el, 'border-radius');
|
|
||||||
this.renderer.removeStyle(el, 'min-width');
|
|
||||||
this.renderer.removeStyle(el, 'max-height');
|
|
||||||
this.renderer.removeStyle(el, 'display');
|
|
||||||
this.renderer.removeStyle(el, 'overflow');
|
|
||||||
this.renderer.removeStyle(el, 'pointer-events');
|
|
||||||
|
|
||||||
Array.from(el.children).forEach((child) => {
|
this.renderer.removeClass(element, 'sk-text-loading');
|
||||||
|
this.renderer.removeStyle(element, 'min-width');
|
||||||
|
this.renderer.removeStyle(element, 'height');
|
||||||
|
|
||||||
|
Array.from(element.children).forEach((child) => {
|
||||||
this.renderer.removeStyle(child, 'visibility');
|
this.renderer.removeStyle(child, 'visibility');
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -130,12 +130,14 @@ export class ComponentTooltipDirective<T extends object> implements OnDestroy {
|
|||||||
.flexibleConnectedTo(this.elementRef)
|
.flexibleConnectedTo(this.elementRef)
|
||||||
.withPositions(positions)
|
.withPositions(positions)
|
||||||
.withFlexibleDimensions(false)
|
.withFlexibleDimensions(false)
|
||||||
|
.withViewportMargin(12)
|
||||||
.withPush(true);
|
.withPush(true);
|
||||||
|
|
||||||
this.overlayRef = this.overlay.create({
|
this.overlayRef = this.overlay.create({
|
||||||
positionStrategy,
|
positionStrategy,
|
||||||
scrollStrategy: this.overlay.scrollStrategies.reposition(),
|
scrollStrategy: this.overlay.scrollStrategies.reposition(),
|
||||||
panelClass: 'app-tooltip-panel',
|
panelClass: 'app-tooltip-panel',
|
||||||
|
maxWidth: this.tooltipMaxWidth() ?? 'calc(100vw - 24px)',
|
||||||
});
|
});
|
||||||
|
|
||||||
const portal = new ComponentPortal(this.component(), null, this.injector);
|
const portal = new ComponentPortal(this.component(), null, this.injector);
|
||||||
|
|||||||
@@ -13,10 +13,11 @@
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
@if (loading()) {
|
@if (loading()) {
|
||||||
<div class="loading-state">
|
<app-loading
|
||||||
<mat-spinner diameter="42"></mat-spinner>
|
text="Bookmarks werden geladen …"
|
||||||
<p>Bookmarks werden geladen …</p>
|
icon="bookmarks"
|
||||||
</div>
|
[size]="60"
|
||||||
|
[diameter]="60" />
|
||||||
} @else if (persons().length) {
|
} @else if (persons().length) {
|
||||||
<section class="person-grid" aria-label="Gespeicherte Personen">
|
<section class="person-grid" aria-label="Gespeicherte Personen">
|
||||||
@for (person of persons(); track person.id) {
|
@for (person of persons(); track person.id) {
|
||||||
|
|||||||
@@ -65,7 +65,6 @@
|
|||||||
gap: 20px;
|
gap: 20px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.loading-state,
|
|
||||||
.empty-state {
|
.empty-state {
|
||||||
display: flex;
|
display: flex;
|
||||||
min-height: 320px;
|
min-height: 320px;
|
||||||
|
|||||||
@@ -2,12 +2,12 @@ import { CommonModule } from '@angular/common';
|
|||||||
import { Component, DestroyRef, inject, signal } from '@angular/core';
|
import { Component, DestroyRef, inject, signal } from '@angular/core';
|
||||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||||
import { MatIconModule } from '@angular/material/icon';
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
|
|
||||||
import { catchError, forkJoin, map, of, switchMap } from 'rxjs';
|
import { catchError, forkJoin, map, of, switchMap } from 'rxjs';
|
||||||
|
|
||||||
import { CustomAuthor, PersonsService } from '../../api';
|
import { CustomAuthor, PersonsService } from '../../api';
|
||||||
import { BookmarkService } from '../../shared/services/bookmark.service';
|
import { BookmarkService } from '../../shared/services/bookmark.service';
|
||||||
import { PersonCardComponent } from '../person-card/person-card.component';
|
import { PersonCardComponent } from '../person-card/person-card.component';
|
||||||
|
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
|
||||||
|
|
||||||
const PERSON_INCLUDE_TAGS =
|
const PERSON_INCLUDE_TAGS =
|
||||||
'display_name,works_count,cited_by_count,summary_stats,ids,' +
|
'display_name,works_count,cited_by_count,summary_stats,ids,' +
|
||||||
@@ -17,12 +17,7 @@ const PERSON_INCLUDE_TAGS =
|
|||||||
@Component({
|
@Component({
|
||||||
selector: 'app-bookmarks',
|
selector: 'app-bookmarks',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [
|
imports: [CommonModule, MatIconModule, PersonCardComponent, LoadingComponent],
|
||||||
CommonModule,
|
|
||||||
MatIconModule,
|
|
||||||
MatProgressSpinnerModule,
|
|
||||||
PersonCardComponent,
|
|
||||||
],
|
|
||||||
templateUrl: './bookmarks.component.html',
|
templateUrl: './bookmarks.component.html',
|
||||||
styleUrl: './bookmarks.component.scss',
|
styleUrl: './bookmarks.component.scss',
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
<p>institution-overview works!</p>
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
|
||||||
|
|
||||||
import { InstitutionOverviewComponent } from './institution-overview.component';
|
|
||||||
|
|
||||||
describe('InstitutionOverviewComponent', () => {
|
|
||||||
let component: InstitutionOverviewComponent;
|
|
||||||
let fixture: ComponentFixture<InstitutionOverviewComponent>;
|
|
||||||
|
|
||||||
beforeEach(async () => {
|
|
||||||
await TestBed.configureTestingModule({
|
|
||||||
imports: [InstitutionOverviewComponent],
|
|
||||||
}).compileComponents();
|
|
||||||
|
|
||||||
fixture = TestBed.createComponent(InstitutionOverviewComponent);
|
|
||||||
component = fixture.componentInstance;
|
|
||||||
fixture.detectChanges();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should create', () => {
|
|
||||||
expect(component).toBeTruthy();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
import { Component } from '@angular/core';
|
|
||||||
|
|
||||||
@Component({
|
|
||||||
selector: 'app-institution-overview',
|
|
||||||
imports: [],
|
|
||||||
templateUrl: './institution-overview.component.html',
|
|
||||||
styleUrl: './institution-overview.component.scss',
|
|
||||||
})
|
|
||||||
export class InstitutionOverviewComponent {}
|
|
||||||
@@ -54,11 +54,13 @@
|
|||||||
subscriptSizing="dynamic">
|
subscriptSizing="dynamic">
|
||||||
<mat-icon matPrefix fontIcon="sort"></mat-icon>
|
<mat-icon matPrefix fontIcon="sort"></mat-icon>
|
||||||
<mat-select
|
<mat-select
|
||||||
[value]="sortMode"
|
[value]="sortColumn"
|
||||||
(selectionChange)="setSortMode($event.value)">
|
(selectionChange)="setSort($event.value)">
|
||||||
<mat-select-trigger>Sortieren nach</mat-select-trigger>
|
<mat-select-trigger>Sortieren nach</mat-select-trigger>
|
||||||
<mat-option value="date">Datum</mat-option>
|
<mat-option value="year">Jahr</mat-option>
|
||||||
<mat-option value="title">Titel</mat-option>
|
<mat-option value="title">Titel</mat-option>
|
||||||
|
<mat-option value="source">Quelle</mat-option>
|
||||||
|
<mat-option value="matchType">Match-Typ</mat-option>
|
||||||
</mat-select>
|
</mat-select>
|
||||||
</mat-form-field>
|
</mat-form-field>
|
||||||
</div>
|
</div>
|
||||||
@@ -67,11 +69,41 @@
|
|||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>Patent</th>
|
<th>Patent</th>
|
||||||
<th>Quelle</th>
|
<th
|
||||||
<th>Jahr</th>
|
class="sortable"
|
||||||
|
[class.sort-active]="sortColumn === 'source'"
|
||||||
|
(click)="setSort('source')">
|
||||||
|
Quelle
|
||||||
|
@if (sortColumn === 'source') {
|
||||||
|
<mat-icon class="sort-icon">{{
|
||||||
|
sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward'
|
||||||
|
}}</mat-icon>
|
||||||
|
}
|
||||||
|
</th>
|
||||||
|
<th
|
||||||
|
class="sortable"
|
||||||
|
[class.sort-active]="sortColumn === 'year'"
|
||||||
|
(click)="setSort('year')">
|
||||||
|
Jahr
|
||||||
|
@if (sortColumn === 'year') {
|
||||||
|
<mat-icon class="sort-icon">{{
|
||||||
|
sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward'
|
||||||
|
}}</mat-icon>
|
||||||
|
}
|
||||||
|
</th>
|
||||||
<th>Erfinder</th>
|
<th>Erfinder</th>
|
||||||
<th>Applicant/Assignee</th>
|
<th>Applicant/Assignee</th>
|
||||||
<th>Match-Typ</th>
|
<th
|
||||||
|
class="sortable"
|
||||||
|
[class.sort-active]="sortColumn === 'matchType'"
|
||||||
|
(click)="setSort('matchType')">
|
||||||
|
Match-Typ
|
||||||
|
@if (sortColumn === 'matchType') {
|
||||||
|
<mat-icon class="sort-icon">{{
|
||||||
|
sortDirection === 'asc' ? 'arrow_upward' : 'arrow_downward'
|
||||||
|
}}</mat-icon>
|
||||||
|
}
|
||||||
|
</th>
|
||||||
<th>Personen</th>
|
<th>Personen</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
@@ -94,33 +126,119 @@
|
|||||||
{{ patent.source }}
|
{{ patent.source }}
|
||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td>{{ patent.publication_year ?? '-' }}</td>
|
<td>
|
||||||
<td class="cell-preview">{{ getInventorsPreview(patent) }}</td>
|
@if (patent.publication_year) {
|
||||||
<td class="cell-preview">{{ getAssigneesPreview(patent) }}</td>
|
<span class="year-badge">{{
|
||||||
|
patent.publication_year
|
||||||
|
}}</span>
|
||||||
|
} @else {
|
||||||
|
<span>-</span>
|
||||||
|
}
|
||||||
|
</td>
|
||||||
|
<td class="patent-people">
|
||||||
|
@if (patent.inventors && patent.inventors.length) {
|
||||||
|
<div class="person-chips">
|
||||||
|
@for (
|
||||||
|
inventor of patent.inventors.slice(0, 2);
|
||||||
|
track inventor
|
||||||
|
) {
|
||||||
|
<span class="person-chip">
|
||||||
|
<mat-icon>person</mat-icon>
|
||||||
|
{{ inventor }}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
@if (patent.inventors.length > 2) {
|
||||||
|
<span class="person-chip-row">
|
||||||
|
<span class="person-chip">
|
||||||
|
<mat-icon>person</mat-icon>
|
||||||
|
{{ patent.inventors[2] }}
|
||||||
|
</span>
|
||||||
|
@if (patent.inventors.length > 3) {
|
||||||
|
<span class="person-chip person-chip--more"
|
||||||
|
>+{{ patent.inventors.length - 3 }}</span
|
||||||
|
>
|
||||||
|
}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
} @else {
|
||||||
|
<span>-</span>
|
||||||
|
}
|
||||||
|
</td>
|
||||||
|
<td class="patent-people">
|
||||||
|
@if (patent.assignees && patent.assignees.length) {
|
||||||
|
<div class="person-chips">
|
||||||
|
@for (
|
||||||
|
assignee of patent.assignees.slice(0, 2);
|
||||||
|
track assignee
|
||||||
|
) {
|
||||||
|
<span class="person-chip">
|
||||||
|
<mat-icon>{{
|
||||||
|
isAssigneeLikelyPerson(assignee, patent)
|
||||||
|
? 'person'
|
||||||
|
: 'apartment'
|
||||||
|
}}</mat-icon>
|
||||||
|
{{ assignee }}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
@if (patent.assignees.length > 2) {
|
||||||
|
<span class="person-chip-row">
|
||||||
|
<span class="person-chip">
|
||||||
|
<mat-icon>{{
|
||||||
|
isAssigneeLikelyPerson(
|
||||||
|
patent.assignees[2],
|
||||||
|
patent
|
||||||
|
)
|
||||||
|
? 'person'
|
||||||
|
: 'apartment'
|
||||||
|
}}</mat-icon>
|
||||||
|
{{ patent.assignees[2] }}
|
||||||
|
</span>
|
||||||
|
@if (patent.assignees.length > 3) {
|
||||||
|
<span class="person-chip person-chip--more"
|
||||||
|
>+{{ patent.assignees.length - 3 }}</span
|
||||||
|
>
|
||||||
|
}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
} @else {
|
||||||
|
<span>-</span>
|
||||||
|
}
|
||||||
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<span
|
<span
|
||||||
class="match-badge match-badge--{{ patent.match_type }}">
|
class="match-badge match-badge--{{ patent.match_type }}">
|
||||||
{{ getMatchTypeLabel(patent) }}
|
{{ getMatchTypeLabel(patent) }}
|
||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td class="cell-authors">
|
<td>
|
||||||
@if (
|
<div class="cell-authors">
|
||||||
patent.matched_authors && patent.matched_authors.length
|
@if (
|
||||||
) {
|
patent.matched_authors && patent.matched_authors.length
|
||||||
@for (
|
|
||||||
author of patent.matched_authors.slice(0, 2);
|
|
||||||
track author.openalex_author_id
|
|
||||||
) {
|
) {
|
||||||
<a
|
@for (
|
||||||
class="author-link"
|
author of patent.matched_authors.slice(0, 2);
|
||||||
[routerLink]="['/person', author.openalex_author_id]"
|
track author.openalex_author_id
|
||||||
(click)="$event.stopPropagation()">
|
) {
|
||||||
{{ author.author_name }}
|
<a
|
||||||
</a>
|
class="author-link"
|
||||||
|
[routerLink]="[
|
||||||
|
'/person',
|
||||||
|
author.openalex_author_id,
|
||||||
|
]"
|
||||||
|
[appComponentTooltip]="AuthorTooltipComponent"
|
||||||
|
[tooltipInputs]="{
|
||||||
|
authorId: author.openalex_author_id,
|
||||||
|
}"
|
||||||
|
(click)="$event.stopPropagation()">
|
||||||
|
{{ author.author_name }}
|
||||||
|
</a>
|
||||||
|
}
|
||||||
|
} @else {
|
||||||
|
<span>-</span>
|
||||||
}
|
}
|
||||||
} @else {
|
</div>
|
||||||
<span>-</span>
|
|
||||||
}
|
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
}
|
}
|
||||||
@@ -192,7 +310,11 @@
|
|||||||
<li>
|
<li>
|
||||||
<a
|
<a
|
||||||
class="tag author-link"
|
class="tag author-link"
|
||||||
[routerLink]="['/person', author.openalex_author_id]">
|
[routerLink]="['/person', author.openalex_author_id]"
|
||||||
|
[appComponentTooltip]="AuthorTooltipComponent"
|
||||||
|
[tooltipInputs]="{
|
||||||
|
authorId: author.openalex_author_id,
|
||||||
|
}">
|
||||||
{{ author.author_name }}
|
{{ author.author_name }}
|
||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
|
|||||||
@@ -60,22 +60,30 @@ app-query-param-paginator {
|
|||||||
|
|
||||||
table {
|
table {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
border-collapse: separate;
|
border-collapse: collapse;
|
||||||
border-spacing: 0;
|
|
||||||
border: 1px solid var(--sg-border);
|
|
||||||
border-radius: var(--sg-radius-sm);
|
|
||||||
overflow: hidden;
|
|
||||||
|
|
||||||
th {
|
th {
|
||||||
text-align: left;
|
text-align: left;
|
||||||
padding: 12px 16px;
|
padding: 12px 16px;
|
||||||
background: var(--sg-surface-muted);
|
|
||||||
border-bottom: 1px solid var(--sg-border);
|
border-bottom: 1px solid var(--sg-border);
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
text-transform: uppercase;
|
|
||||||
letter-spacing: 0.02em;
|
|
||||||
color: var(--sg-text-muted);
|
color: var(--sg-text-muted);
|
||||||
|
|
||||||
|
&.sortable {
|
||||||
|
display: table-cell;
|
||||||
|
cursor: pointer;
|
||||||
|
-webkit-user-select: none;
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sort-icon {
|
||||||
|
vertical-align: middle;
|
||||||
|
margin-left: 2px;
|
||||||
|
width: 14px;
|
||||||
|
height: 14px;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
tr {
|
tr {
|
||||||
@@ -90,10 +98,6 @@ app-query-param-paginator {
|
|||||||
&.selected td {
|
&.selected td {
|
||||||
background: var(--sg-primary-soft);
|
background: var(--sg-primary-soft);
|
||||||
}
|
}
|
||||||
|
|
||||||
&:last-child td {
|
|
||||||
border-bottom: 0;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
td {
|
td {
|
||||||
@@ -107,19 +111,13 @@ app-query-param-paginator {
|
|||||||
.patent-title {
|
.patent-title {
|
||||||
color: var(--sg-text);
|
color: var(--sg-text);
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
max-width: 280px;
|
max-width: 320px;
|
||||||
white-space: nowrap;
|
white-space: normal;
|
||||||
overflow: hidden;
|
word-break: break-word;
|
||||||
text-overflow: ellipsis;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.cell-preview {
|
.patent-people {
|
||||||
max-width: 160px;
|
max-width: 220px;
|
||||||
white-space: nowrap;
|
|
||||||
overflow: hidden;
|
|
||||||
text-overflow: ellipsis;
|
|
||||||
color: var(--sg-text-muted);
|
|
||||||
font-size: 13px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.cell-authors {
|
.cell-authors {
|
||||||
@@ -131,6 +129,64 @@ app-query-param-paginator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.year-badge {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
min-width: 26px;
|
||||||
|
padding: 2px 10px;
|
||||||
|
border-radius: 999px;
|
||||||
|
border: 1px solid var(--sg-border);
|
||||||
|
color: var(--sg-text);
|
||||||
|
font-size: 0.8rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.person-chips {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.person-chip-row {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.person-chip {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
max-width: 100%;
|
||||||
|
padding: 2px 8px;
|
||||||
|
border: 1px solid var(--sg-border);
|
||||||
|
border-radius: var(--sg-radius-sm);
|
||||||
|
background: var(--sg-surface-soft);
|
||||||
|
color: var(--sg-text);
|
||||||
|
font-size: 0.75rem;
|
||||||
|
line-height: 1.4;
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
|
||||||
|
mat-icon {
|
||||||
|
flex-shrink: 0;
|
||||||
|
width: 14px;
|
||||||
|
height: 14px;
|
||||||
|
font-size: 14px;
|
||||||
|
color: var(--sg-text-soft);
|
||||||
|
}
|
||||||
|
|
||||||
|
&--more {
|
||||||
|
color: var(--sg-text-muted);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.match-badge {
|
.match-badge {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
|||||||
@@ -13,8 +13,11 @@ import {
|
|||||||
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
|
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
|
||||||
import { PageEvent } from '@angular/material/paginator';
|
import { PageEvent } from '@angular/material/paginator';
|
||||||
import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component';
|
import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component';
|
||||||
|
import { ComponentTooltipDirective } from '../../directives/component-tooltip.directive';
|
||||||
|
import { AppAuthorTooltipComponent } from '../../shared/ui/app-author-tooltip/app-author-tooltip.component';
|
||||||
|
|
||||||
type SortMode = 'date' | 'title';
|
type SortColumn = 'title' | 'year' | 'source' | 'matchType';
|
||||||
|
type SortDirection = 'asc' | 'desc';
|
||||||
type SourceFilter = 'all' | 'EPO' | 'USPTO';
|
type SourceFilter = 'all' | 'EPO' | 'USPTO';
|
||||||
type OrgPatentMatchTypeFilter = 'all' | 'institution' | 'name' | 'both';
|
type OrgPatentMatchTypeFilter = 'all' | 'institution' | 'name' | 'both';
|
||||||
|
|
||||||
@@ -28,11 +31,13 @@ type OrgPatentMatchTypeFilter = 'all' | 'institution' | 'name' | 'both';
|
|||||||
MatSelectModule,
|
MatSelectModule,
|
||||||
MatIconModule,
|
MatIconModule,
|
||||||
QueryParamPaginatorComponent,
|
QueryParamPaginatorComponent,
|
||||||
|
ComponentTooltipDirective,
|
||||||
],
|
],
|
||||||
templateUrl: './institution-patents.component.html',
|
templateUrl: './institution-patents.component.html',
|
||||||
styleUrl: './institution-patents.component.scss',
|
styleUrl: './institution-patents.component.scss',
|
||||||
})
|
})
|
||||||
export class InstitutionPatentsComponent implements OnInit {
|
export class InstitutionPatentsComponent implements OnInit {
|
||||||
|
readonly AuthorTooltipComponent = AppAuthorTooltipComponent;
|
||||||
private route = inject(ActivatedRoute);
|
private route = inject(ActivatedRoute);
|
||||||
private router = inject(Router);
|
private router = inject(Router);
|
||||||
private patentsApi = inject(PatentsService);
|
private patentsApi = inject(PatentsService);
|
||||||
@@ -48,7 +53,8 @@ export class InstitutionPatentsComponent implements OnInit {
|
|||||||
|
|
||||||
activeFilter: SourceFilter = 'all';
|
activeFilter: SourceFilter = 'all';
|
||||||
activeMatchType: OrgPatentMatchTypeFilter = 'all';
|
activeMatchType: OrgPatentMatchTypeFilter = 'all';
|
||||||
sortMode: SortMode = 'date';
|
sortColumn: SortColumn = 'year';
|
||||||
|
sortDirection: SortDirection = 'desc';
|
||||||
|
|
||||||
pageIndex = 0;
|
pageIndex = 0;
|
||||||
pageSize = 20;
|
pageSize = 20;
|
||||||
@@ -59,7 +65,8 @@ export class InstitutionPatentsComponent implements OnInit {
|
|||||||
const institutionId = params.get('institutionId') ?? '';
|
const institutionId = params.get('institutionId') ?? '';
|
||||||
|
|
||||||
const filterFromUrl = this.route.snapshot.queryParamMap.get('filter');
|
const filterFromUrl = this.route.snapshot.queryParamMap.get('filter');
|
||||||
const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy');
|
const sortByFromUrl = this.route.snapshot.queryParamMap.get('sortBy');
|
||||||
|
const sortDirFromUrl = this.route.snapshot.queryParamMap.get('sortDir');
|
||||||
const matchTypeFromUrl =
|
const matchTypeFromUrl =
|
||||||
this.route.snapshot.queryParamMap.get('matchType');
|
this.route.snapshot.queryParamMap.get('matchType');
|
||||||
this.pageIndex = this.parsePageIndexParam(
|
this.pageIndex = this.parsePageIndexParam(
|
||||||
@@ -72,8 +79,11 @@ export class InstitutionPatentsComponent implements OnInit {
|
|||||||
if (this.isValidFilter(filterFromUrl)) {
|
if (this.isValidFilter(filterFromUrl)) {
|
||||||
this.activeFilter = filterFromUrl;
|
this.activeFilter = filterFromUrl;
|
||||||
}
|
}
|
||||||
if (this.isValidSortMode(sortFromUrl)) {
|
if (this.isValidSortColumn(sortByFromUrl)) {
|
||||||
this.sortMode = sortFromUrl;
|
this.sortColumn = sortByFromUrl;
|
||||||
|
}
|
||||||
|
if (this.isValidSortDirection(sortDirFromUrl)) {
|
||||||
|
this.sortDirection = sortDirFromUrl;
|
||||||
}
|
}
|
||||||
if (this.isValidMatchType(matchTypeFromUrl)) {
|
if (this.isValidMatchType(matchTypeFromUrl)) {
|
||||||
this.activeMatchType = matchTypeFromUrl;
|
this.activeMatchType = matchTypeFromUrl;
|
||||||
@@ -101,8 +111,13 @@ export class InstitutionPatentsComponent implements OnInit {
|
|||||||
this.reloadPatents();
|
this.reloadPatents();
|
||||||
}
|
}
|
||||||
|
|
||||||
setSortMode(sortMode: SortMode): void {
|
setSort(column: SortColumn): void {
|
||||||
this.sortMode = sortMode;
|
if (this.sortColumn === column) {
|
||||||
|
this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
|
||||||
|
} else {
|
||||||
|
this.sortColumn = column;
|
||||||
|
this.sortDirection = column === 'year' ? 'desc' : 'asc';
|
||||||
|
}
|
||||||
this.filteredPatents = this.sortPatents(this.patents);
|
this.filteredPatents = this.sortPatents(this.patents);
|
||||||
this.updateQueryParams();
|
this.updateQueryParams();
|
||||||
}
|
}
|
||||||
@@ -168,14 +183,27 @@ export class InstitutionPatentsComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private sortPatents(patents: OrgPatentEntry[]): OrgPatentEntry[] {
|
private sortPatents(patents: OrgPatentEntry[]): OrgPatentEntry[] {
|
||||||
if (this.sortMode === 'title') {
|
const direction = this.sortDirection === 'asc' ? 1 : -1;
|
||||||
return [...patents].sort((a, b) =>
|
return [...patents].sort((a, b) => {
|
||||||
(a.title ?? '').localeCompare(b.title ?? '', 'de', {
|
switch (this.sortColumn) {
|
||||||
sensitivity: 'base',
|
case 'year': {
|
||||||
}),
|
const yearA = a.publication_date ?? String(a.publication_year ?? '');
|
||||||
);
|
const yearB = b.publication_date ?? String(b.publication_year ?? '');
|
||||||
}
|
return direction * yearA.localeCompare(yearB);
|
||||||
return [...patents];
|
}
|
||||||
|
case 'source':
|
||||||
|
return direction * a.source.localeCompare(b.source);
|
||||||
|
case 'matchType':
|
||||||
|
return direction * a.match_type.localeCompare(b.match_type);
|
||||||
|
default:
|
||||||
|
return (
|
||||||
|
direction *
|
||||||
|
(a.title ?? '').localeCompare(b.title ?? '', 'de', {
|
||||||
|
sensitivity: 'base',
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private updateQueryParams(): void {
|
private updateQueryParams(): void {
|
||||||
@@ -183,7 +211,8 @@ export class InstitutionPatentsComponent implements OnInit {
|
|||||||
relativeTo: this.route,
|
relativeTo: this.route,
|
||||||
queryParams: {
|
queryParams: {
|
||||||
filter: this.activeFilter,
|
filter: this.activeFilter,
|
||||||
sortBy: this.sortMode,
|
sortBy: this.sortColumn,
|
||||||
|
sortDir: this.sortDirection,
|
||||||
matchType: this.activeMatchType,
|
matchType: this.activeMatchType,
|
||||||
page: this.pageIndex,
|
page: this.pageIndex,
|
||||||
size: this.pageSize,
|
size: this.pageSize,
|
||||||
@@ -207,8 +236,17 @@ export class InstitutionPatentsComponent implements OnInit {
|
|||||||
return value === 'all' || value === 'EPO' || value === 'USPTO';
|
return value === 'all' || value === 'EPO' || value === 'USPTO';
|
||||||
}
|
}
|
||||||
|
|
||||||
private isValidSortMode(value: string | null): value is SortMode {
|
private isValidSortColumn(value: string | null): value is SortColumn {
|
||||||
return value === 'date' || value === 'title';
|
return (
|
||||||
|
value === 'title' ||
|
||||||
|
value === 'year' ||
|
||||||
|
value === 'source' ||
|
||||||
|
value === 'matchType'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private isValidSortDirection(value: string | null): value is SortDirection {
|
||||||
|
return value === 'asc' || value === 'desc';
|
||||||
}
|
}
|
||||||
|
|
||||||
private isValidMatchType(
|
private isValidMatchType(
|
||||||
@@ -287,18 +325,40 @@ export class InstitutionPatentsComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
getInventorsPreview(patent: OrgPatentEntry): string {
|
private static readonly ORG_SUFFIX_PATTERN =
|
||||||
if (!patent.inventors?.length) {
|
/\b(Inc|Ltd|LLC|LLP|GmbH|Corp(oration)?|Co|KG|AG|SE|S\.?A\.?|N\.?V\.?|B\.?V\.?|PLC|Universit(y|ät|é)|Institut(e)?|Foundation|Laborator(y|ies)|Labs?|Group|Holdings?|Company|Gesellschaft)\b\.?/i;
|
||||||
return '-';
|
private static readonly PERSON_SUFFIX_PATTERN =
|
||||||
}
|
/\b(Dr|Prof|PhD|Ph\.D|M\.D|Jr|Sr)\b\.?/i;
|
||||||
return patent.inventors.slice(0, 2).join(', ');
|
|
||||||
|
private normalizeNameForComparison(name: string): string {
|
||||||
|
return name
|
||||||
|
.normalize('NFD')
|
||||||
|
.replace(/[̀-ͯ]/g, '')
|
||||||
|
.replace(/[.,]/g, '')
|
||||||
|
.toUpperCase()
|
||||||
|
.split(/\s+/)
|
||||||
|
.filter(Boolean)
|
||||||
|
.sort()
|
||||||
|
.join(' ');
|
||||||
}
|
}
|
||||||
|
|
||||||
getAssigneesPreview(patent: OrgPatentEntry): string {
|
isAssigneeLikelyPerson(assignee: string, patent: OrgPatentEntry): boolean {
|
||||||
if (!patent.assignees?.length) {
|
if (InstitutionPatentsComponent.ORG_SUFFIX_PATTERN.test(assignee)) {
|
||||||
return '-';
|
return false;
|
||||||
}
|
}
|
||||||
return patent.assignees.slice(0, 2).join(', ');
|
|
||||||
|
const normalizedAssignee = this.normalizeNameForComparison(
|
||||||
|
assignee.replace(InstitutionPatentsComponent.PERSON_SUFFIX_PATTERN, ''),
|
||||||
|
);
|
||||||
|
const matchesInventor = (patent.inventors ?? []).some(
|
||||||
|
(inventor) =>
|
||||||
|
this.normalizeNameForComparison(inventor) === normalizedAssignee,
|
||||||
|
);
|
||||||
|
if (matchesInventor) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return InstitutionPatentsComponent.PERSON_SUFFIX_PATTERN.test(assignee);
|
||||||
}
|
}
|
||||||
|
|
||||||
getMatchedAuthorsPreview(patent: OrgPatentEntry): string {
|
getMatchedAuthorsPreview(patent: OrgPatentEntry): string {
|
||||||
|
|||||||
@@ -1,25 +1,15 @@
|
|||||||
<div class="content">
|
<div class="content">
|
||||||
<h3>Projekte</h3>
|
<div>
|
||||||
|
<h6>Projekte</h6>
|
||||||
|
<p>Übersicht der Projekte, die von der Institution durchgeführt werden.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="funding-area">
|
<mat-accordion multi>
|
||||||
<div class="person-projects">
|
<mat-expansion-panel class="mat-elevation-z1">
|
||||||
<nav mat-tab-nav-bar [tabPanel]="resultTabPanel" class="result-nav">
|
<mat-expansion-panel-header>
|
||||||
@for (route of childRoutes; track route.path) {
|
<mat-panel-title>Förderung über Zeit</mat-panel-title>
|
||||||
<a
|
</mat-expansion-panel-header>
|
||||||
matTabLink
|
|
||||||
[routerLink]="[route.path]"
|
|
||||||
queryParamsHandling="merge"
|
|
||||||
routerLinkActive
|
|
||||||
#rla="routerLinkActive"
|
|
||||||
[active]="rla.isActive">
|
|
||||||
{{ route.label }}
|
|
||||||
</a>
|
|
||||||
}
|
|
||||||
</nav>
|
|
||||||
|
|
||||||
<mat-tab-nav-panel #resultTabPanel>
|
|
||||||
<router-outlet />
|
|
||||||
</mat-tab-nav-panel>
|
|
||||||
<div class="funding-info-section">
|
<div class="funding-info-section">
|
||||||
<mat-card appearance="outlined">
|
<mat-card appearance="outlined">
|
||||||
<mat-card-header>
|
<mat-card-header>
|
||||||
@@ -51,15 +41,35 @@
|
|||||||
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
|
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
|
||||||
" />
|
" />
|
||||||
<app-info-card
|
<app-info-card
|
||||||
[description]="'Durchschnittliche jährliche Förderung durch die Europäische Union'"
|
[description]="
|
||||||
|
'Durchschnittliche jährliche Förderung durch die Europäische Union'
|
||||||
|
"
|
||||||
[value]="
|
[value]="
|
||||||
(euAverageAnnualFunding()
|
(euAverageAnnualFunding()
|
||||||
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
|
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
|
||||||
" />
|
" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</mat-expansion-panel>
|
||||||
</div>
|
|
||||||
|
<mat-expansion-panel class="mat-elevation-z1" [expanded]="true">
|
||||||
|
<mat-expansion-panel-header>
|
||||||
|
<mat-panel-title>Projektliste</mat-panel-title>
|
||||||
|
</mat-expansion-panel-header>
|
||||||
|
|
||||||
|
<div class="person-projects">
|
||||||
|
@if (resultTabPanel) {
|
||||||
|
<app-link-tab-nav-bar
|
||||||
|
[links]="_links()"
|
||||||
|
[tabPanel]="resultTabPanel" />
|
||||||
|
}
|
||||||
|
|
||||||
|
<mat-tab-nav-panel #resultTabPanel>
|
||||||
|
<router-outlet />
|
||||||
|
</mat-tab-nav-panel>
|
||||||
|
</div>
|
||||||
|
</mat-expansion-panel>
|
||||||
|
</mat-accordion>
|
||||||
|
|
||||||
<ng-template #fundingStartTmp let-row>
|
<ng-template #fundingStartTmp let-row>
|
||||||
{{ row.funding_start | date: 'dd.MM.yyyy' }}
|
{{ row.funding_start | date: 'dd.MM.yyyy' }}
|
||||||
@@ -74,8 +84,8 @@
|
|||||||
<ng-template #euProjectActionsTmp let-row>
|
<ng-template #euProjectActionsTmp let-row>
|
||||||
<a mat-icon-button color="primary" [routerLink]="['/projects/eu', row.id]">
|
<a mat-icon-button color="primary" [routerLink]="['/projects/eu', row.id]">
|
||||||
<mat-icon>open_in_new</mat-icon>
|
<mat-icon>open_in_new</mat-icon>
|
||||||
</a></ng-template
|
</a>
|
||||||
>
|
</ng-template>
|
||||||
|
|
||||||
<ng-template #bundProjectActionsTmp let-row>
|
<ng-template #bundProjectActionsTmp let-row>
|
||||||
<a
|
<a
|
||||||
|
|||||||
@@ -1,22 +1,30 @@
|
|||||||
.content {
|
.content {
|
||||||
padding: 16px;
|
|
||||||
}
|
|
||||||
|
|
||||||
mat-card,
|
|
||||||
mat-paginator {
|
|
||||||
background-color: var(--sg-background);
|
|
||||||
}
|
|
||||||
|
|
||||||
.funding-area {
|
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 1rem;
|
gap: 1rem;
|
||||||
|
padding: 2rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.funding-info-section {
|
mat-expansion-panel {
|
||||||
display: flex;
|
border: 1px solid var(--sg-border);
|
||||||
flex-direction: column;
|
border-radius: var(--sg-radius-sm);
|
||||||
gap: 1rem;
|
background: var(--sg-none);
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
mat-expansion-panel-header {
|
||||||
|
padding: 0 16px;
|
||||||
|
min-height: 48px;
|
||||||
|
}
|
||||||
|
|
||||||
|
mat-panel-title {
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
mat-panel-description {
|
||||||
|
font-size: 14px;
|
||||||
|
color: var(--sg-text-muted);
|
||||||
}
|
}
|
||||||
|
|
||||||
.funding-info-cards {
|
.funding-info-cards {
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import {
|
|||||||
import { BundProjectSummary } from '../../api/model/bundProjectSummary';
|
import { BundProjectSummary } from '../../api/model/bundProjectSummary';
|
||||||
import { MatCardModule } from '@angular/material/card';
|
import { MatCardModule } from '@angular/material/card';
|
||||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||||
|
import { MatExpansionModule } from '@angular/material/expansion';
|
||||||
import { MatTabChangeEvent, MatTabsModule } from '@angular/material/tabs';
|
import { MatTabChangeEvent, MatTabsModule } from '@angular/material/tabs';
|
||||||
import { FormsModule } from '@angular/forms';
|
import { FormsModule } from '@angular/forms';
|
||||||
import { MatInputModule } from '@angular/material/input';
|
import { MatInputModule } from '@angular/material/input';
|
||||||
@@ -27,7 +28,10 @@ import { MatIconModule } from '@angular/material/icon';
|
|||||||
import { MatButtonModule } from '@angular/material/button';
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
import { InstitutionProjectsFundingGraphComponent } from '../institution-projects-funding-graph/institution-projects-funding-graph.component';
|
import { InstitutionProjectsFundingGraphComponent } from '../institution-projects-funding-graph/institution-projects-funding-graph.component';
|
||||||
import { AppInfoCardComponent } from '../../shared/ui/app-info-card/app-info-card.component';
|
import { AppInfoCardComponent } from '../../shared/ui/app-info-card/app-info-card.component';
|
||||||
|
import {
|
||||||
|
LinkTabNavBarComponent,
|
||||||
|
LinkTabNavBarItem,
|
||||||
|
} from '../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component';
|
||||||
type BundProjectRow = {
|
type BundProjectRow = {
|
||||||
id: string;
|
id: string;
|
||||||
topic: string;
|
topic: string;
|
||||||
@@ -51,6 +55,7 @@ type EuProjectRow = {
|
|||||||
MatCardModule,
|
MatCardModule,
|
||||||
MatFormFieldModule,
|
MatFormFieldModule,
|
||||||
MatTabsModule,
|
MatTabsModule,
|
||||||
|
MatExpansionModule,
|
||||||
FormsModule,
|
FormsModule,
|
||||||
MatInputModule,
|
MatInputModule,
|
||||||
DatePipe,
|
DatePipe,
|
||||||
@@ -59,6 +64,7 @@ type EuProjectRow = {
|
|||||||
MatButtonModule,
|
MatButtonModule,
|
||||||
InstitutionProjectsFundingGraphComponent,
|
InstitutionProjectsFundingGraphComponent,
|
||||||
AppInfoCardComponent,
|
AppInfoCardComponent,
|
||||||
|
LinkTabNavBarComponent,
|
||||||
RouterModule,
|
RouterModule,
|
||||||
],
|
],
|
||||||
templateUrl: './institution-projects.component.html',
|
templateUrl: './institution-projects.component.html',
|
||||||
@@ -122,6 +128,27 @@ export class InstitutionProjectsComponent implements OnInit {
|
|||||||
label: 'BUND-Projekte',
|
label: 'BUND-Projekte',
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
_links = computed<LinkTabNavBarItem[]>(() => {
|
||||||
|
const links: LinkTabNavBarItem[] = [
|
||||||
|
{
|
||||||
|
label: 'DFG-Projekte',
|
||||||
|
path: 'dfg',
|
||||||
|
disabled: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'EU-Projekte',
|
||||||
|
path: 'eu',
|
||||||
|
disabled: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'BUND-Projekte',
|
||||||
|
path: 'bund',
|
||||||
|
disabled: false,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
return links;
|
||||||
|
});
|
||||||
constructor(
|
constructor(
|
||||||
private readonly activatedRoute: ActivatedRoute,
|
private readonly activatedRoute: ActivatedRoute,
|
||||||
private readonly router: Router,
|
private readonly router: Router,
|
||||||
@@ -275,12 +302,4 @@ export class InstitutionProjectsComponent implements OnInit {
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
selectedTabChange(event: MatTabChangeEvent): void {
|
|
||||||
const tab = ['eu', 'bund'][event.index];
|
|
||||||
this.router.navigate([], {
|
|
||||||
queryParams: { project_tab: tab, page: 0, size: 10 },
|
|
||||||
queryParamsHandling: 'merge',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-2
@@ -16,8 +16,7 @@
|
|||||||
<mat-expansion-panel class="mat-elevation-z1" [expanded]="true">
|
<mat-expansion-panel class="mat-elevation-z1" [expanded]="true">
|
||||||
<mat-expansion-panel-header>
|
<mat-expansion-panel-header>
|
||||||
<mat-panel-title>Publikationsliste</mat-panel-title>
|
<mat-panel-title>Publikationsliste</mat-panel-title>
|
||||||
<mat-panel-description
|
<mat-panel-description>
|
||||||
>{{ total() >= 10000 ? 'mehr als' : '' }}
|
|
||||||
{{ total() }} Publikationen</mat-panel-description
|
{{ total() }} Publikationen</mat-panel-description
|
||||||
>
|
>
|
||||||
</mat-expansion-panel-header>
|
</mat-expansion-panel-header>
|
||||||
|
|||||||
@@ -1,27 +1,15 @@
|
|||||||
<div class="content">
|
<div class="container">
|
||||||
<h1>{{ institution.display_name }}</h1>
|
<div class="content">
|
||||||
<mat-card appearance="outlined">
|
<h1>{{ institution().display_name }}</h1>
|
||||||
<mat-card-content>
|
<mat-card appearance="outlined">
|
||||||
<p>{{ institution.homepage_url }}</p>
|
<mat-card-content>
|
||||||
<p>{{ institution.display_name_alternatives }}</p>
|
<p>{{ institution().homepage_url }}</p>
|
||||||
<p>And many more useful details...</p>
|
<p>{{ institution().display_name_alternatives }}</p>
|
||||||
</mat-card-content>
|
<p>And many more useful details...</p>
|
||||||
</mat-card>
|
</mat-card-content>
|
||||||
|
</mat-card>
|
||||||
<nav mat-tab-nav-bar [tabPanel]="tabPanel">
|
</div>
|
||||||
@for (link of links; track link.path) {
|
<app-link-tab-nav-bar [links]="_links()" [tabPanel]="tabPanel" />
|
||||||
<a
|
|
||||||
mat-tab-link
|
|
||||||
[routerLink]="link.path"
|
|
||||||
[queryParams]="link.queryParams"
|
|
||||||
routerLinkActive
|
|
||||||
#rla="routerLinkActive"
|
|
||||||
[active]="rla.isActive"
|
|
||||||
[disabled]="link.disabled">
|
|
||||||
{{ link.label }}
|
|
||||||
</a>
|
|
||||||
}
|
|
||||||
</nav>
|
|
||||||
</div>
|
</div>
|
||||||
<mat-tab-nav-panel #tabPanel>
|
<mat-tab-nav-panel #tabPanel>
|
||||||
<router-outlet />
|
<router-outlet />
|
||||||
|
|||||||
@@ -1,6 +1,12 @@
|
|||||||
.content {
|
.container {
|
||||||
padding: 16px;
|
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 16px;
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.content {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1rem;
|
||||||
|
margin: 0 1rem;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,74 +1,61 @@
|
|||||||
import { Component, OnInit, inject } from '@angular/core';
|
import { Component, computed, input } from '@angular/core';
|
||||||
import {
|
import { RouterModule } from '@angular/router';
|
||||||
ActivatedRoute,
|
|
||||||
RouterLink,
|
|
||||||
RouterOutlet,
|
|
||||||
RouterLinkActive,
|
|
||||||
} from '@angular/router';
|
|
||||||
import { Institution } from '../../api';
|
import { Institution } from '../../api';
|
||||||
import { PatentsService } from '../../api/api/patents.service';
|
|
||||||
import { MatCardModule } from '@angular/material/card';
|
import { MatCardModule } from '@angular/material/card';
|
||||||
import { MatTabsModule } from '@angular/material/tabs';
|
import { MatTabsModule } from '@angular/material/tabs';
|
||||||
|
import {
|
||||||
const PATENTS_LINK = { label: 'Patente', path: 'patents', disabled: false };
|
LinkTabNavBarComponent,
|
||||||
|
LinkTabNavBarItem,
|
||||||
|
} from '../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component';
|
||||||
|
import {
|
||||||
|
PATENT_ICON,
|
||||||
|
PROJECT_ICON,
|
||||||
|
PUBLICATION_ICON,
|
||||||
|
} from '../../shared/ui/icons';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-institution',
|
selector: 'app-institution',
|
||||||
imports: [
|
imports: [MatCardModule, MatTabsModule, RouterModule, LinkTabNavBarComponent],
|
||||||
MatCardModule,
|
|
||||||
MatTabsModule,
|
|
||||||
RouterLink,
|
|
||||||
RouterOutlet,
|
|
||||||
RouterLinkActive,
|
|
||||||
],
|
|
||||||
templateUrl: './institution.component.html',
|
templateUrl: './institution.component.html',
|
||||||
styleUrl: './institution.component.scss',
|
styleUrl: './institution.component.scss',
|
||||||
})
|
})
|
||||||
export class InstitutionComponent implements OnInit {
|
export class InstitutionComponent {
|
||||||
private readonly patentsApi = inject(PatentsService);
|
institution = input.required<Institution>();
|
||||||
|
canFetchGdprRelevantData = input.required<boolean>();
|
||||||
|
|
||||||
institution!: Institution;
|
_links = computed<LinkTabNavBarItem[]>(() => {
|
||||||
|
const links: LinkTabNavBarItem[] = [
|
||||||
links = [
|
{
|
||||||
{ label: 'Übersicht', path: 'overview', disabled: false },
|
label: 'Publikationen',
|
||||||
{ label: 'Publikationen', path: 'publications', disabled: false },
|
icon: PUBLICATION_ICON,
|
||||||
{
|
path: 'publications',
|
||||||
label: 'Projekte',
|
disabled: false,
|
||||||
path: 'projects',
|
|
||||||
disabled: false,
|
|
||||||
queryParams: {
|
|
||||||
project_tab: 'bund',
|
|
||||||
page: 0,
|
|
||||||
size: 10,
|
|
||||||
search: '',
|
|
||||||
sort_by: 'title',
|
|
||||||
sort_direction: 'asc',
|
|
||||||
},
|
},
|
||||||
},
|
];
|
||||||
];
|
if (this.canFetchGdprRelevantData()) {
|
||||||
|
links.push(
|
||||||
constructor(private readonly activatedRoute: ActivatedRoute) {}
|
{
|
||||||
|
label: 'Projekte',
|
||||||
ngOnInit(): void {
|
icon: PROJECT_ICON,
|
||||||
this.activatedRoute.data.subscribe(({ institution }) => {
|
path: 'projects',
|
||||||
this.institution = institution;
|
disabled: false,
|
||||||
});
|
queryParams: {
|
||||||
|
project_tab: 'bund',
|
||||||
const institutionId =
|
page: 0,
|
||||||
this.activatedRoute.snapshot.paramMap.get('institutionId');
|
size: 10,
|
||||||
if (!institutionId) return;
|
search: '',
|
||||||
|
sort_by: 'title',
|
||||||
// The "Patente" tab only makes sense once org_patents has been indexed for
|
sort_direction: 'asc',
|
||||||
// this institution (currently a manual, ~30-40 min-per-institution process),
|
},
|
||||||
// so only show it once we know there is actually data behind it.
|
|
||||||
this.patentsApi
|
|
||||||
.getOrgPatentsByInstitution(institutionId, undefined, 0, 0)
|
|
||||||
.subscribe({
|
|
||||||
next: (result) => {
|
|
||||||
if ((result.patent_count ?? 0) > 0) {
|
|
||||||
this.links = [...this.links, PATENTS_LINK];
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
});
|
{
|
||||||
}
|
label: 'Patente',
|
||||||
|
icon: PATENT_ICON,
|
||||||
|
path: 'patents',
|
||||||
|
disabled: false,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return links;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,12 +2,11 @@
|
|||||||
|
|
||||||
<mat-dialog-content>
|
<mat-dialog-content>
|
||||||
@if (runsLoading() && runs().length === 0) {
|
@if (runsLoading() && runs().length === 0) {
|
||||||
<div class="runs-loading">
|
<app-loading
|
||||||
<mat-progress-spinner
|
text="Läufe werden geladen …"
|
||||||
diameter="24"
|
icon="history"
|
||||||
mode="indeterminate"></mat-progress-spinner>
|
[size]="48"
|
||||||
<span>Läufe werden geladen …</span>
|
[diameter]="48" />
|
||||||
</div>
|
|
||||||
} @else if (runsError()) {
|
} @else if (runsError()) {
|
||||||
<p class="logs-error">{{ runsError() }}</p>
|
<p class="logs-error">{{ runsError() }}</p>
|
||||||
} @else if (runs().length === 0) {
|
} @else if (runs().length === 0) {
|
||||||
@@ -79,12 +78,11 @@
|
|||||||
|
|
||||||
<div #logsPanel class="logs-panel" (scroll)="onLogsScroll()">
|
<div #logsPanel class="logs-panel" (scroll)="onLogsScroll()">
|
||||||
@if (loading() && !logs()) {
|
@if (loading() && !logs()) {
|
||||||
<div class="logs-loading">
|
<app-loading
|
||||||
<mat-progress-spinner
|
text="Logs werden geladen …"
|
||||||
diameter="20"
|
icon="description"
|
||||||
mode="indeterminate"></mat-progress-spinner>
|
[size]="48"
|
||||||
<span>Logs werden geladen …</span>
|
[diameter]="48" />
|
||||||
</div>
|
|
||||||
} @else {
|
} @else {
|
||||||
<pre>{{ logs() }}</pre>
|
<pre>{{ logs() }}</pre>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,14 +3,6 @@
|
|||||||
margin: 0;
|
margin: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.runs-loading {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 10px;
|
|
||||||
min-height: 120px;
|
|
||||||
color: var(--sg-text-muted);
|
|
||||||
}
|
|
||||||
|
|
||||||
.logs-error {
|
.logs-error {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 16px;
|
padding: 16px;
|
||||||
@@ -93,18 +85,6 @@
|
|||||||
white-space: pre-wrap;
|
white-space: pre-wrap;
|
||||||
word-break: break-word;
|
word-break: break-word;
|
||||||
}
|
}
|
||||||
|
|
||||||
.logs-loading {
|
|
||||||
color: var(--sg-text-muted);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.logs-loading {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 10px;
|
|
||||||
color: var(--sg-text-muted);
|
|
||||||
font-size: 13px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.run-select {
|
.run-select {
|
||||||
|
|||||||
@@ -18,11 +18,11 @@ import {
|
|||||||
} from '@angular/material/dialog';
|
} from '@angular/material/dialog';
|
||||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||||
import { MatIconModule } from '@angular/material/icon';
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
|
|
||||||
import { MatSelectModule } from '@angular/material/select';
|
import { MatSelectModule } from '@angular/material/select';
|
||||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||||
import { finalize, timer } from 'rxjs';
|
import { finalize, timer } from 'rxjs';
|
||||||
import { BackgroundJobsService, BackgroundJobTask, JobRun } from '../../../api';
|
import { BackgroundJobsService, BackgroundJobTask, JobRun } from '../../../api';
|
||||||
|
import { LoadingComponent } from '../../../shared/ui/loading/loading.component';
|
||||||
import {
|
import {
|
||||||
formatRunDuration,
|
formatRunDuration,
|
||||||
formatRunElapsed,
|
formatRunElapsed,
|
||||||
@@ -42,9 +42,9 @@ export interface JobLogsDialogData {
|
|||||||
MatDialogModule,
|
MatDialogModule,
|
||||||
MatFormFieldModule,
|
MatFormFieldModule,
|
||||||
MatIconModule,
|
MatIconModule,
|
||||||
MatProgressSpinnerModule,
|
|
||||||
MatSelectModule,
|
MatSelectModule,
|
||||||
MatTooltipModule,
|
MatTooltipModule,
|
||||||
|
LoadingComponent,
|
||||||
],
|
],
|
||||||
templateUrl: './job-logs-dialog.component.html',
|
templateUrl: './job-logs-dialog.component.html',
|
||||||
styleUrl: './job-logs-dialog.component.scss',
|
styleUrl: './job-logs-dialog.component.scss',
|
||||||
|
|||||||
+180
-89
@@ -1,46 +1,88 @@
|
|||||||
@if (loading()) {
|
@if (loading()) {
|
||||||
<div class="patents-container">
|
<app-loading
|
||||||
<ng-container *ngTemplateOutlet="patentsHeader" />
|
text="Patentdaten werden geladen..."
|
||||||
<app-loading
|
icon="workspace_premium"
|
||||||
text="Patentdaten werden geladen..."
|
[size]="150"
|
||||||
icon="workspace_premium"
|
[diameter]="150" />
|
||||||
[size]="150"
|
|
||||||
[diameter]="150" />
|
|
||||||
</div>
|
|
||||||
} @else if (error()) {
|
} @else if (error()) {
|
||||||
<div class="patents-container">
|
<p class="message">Fehler beim Laden der Patente.</p>
|
||||||
<ng-container *ngTemplateOutlet="patentsHeader" />
|
|
||||||
<p class="message">Fehler beim Laden der Patente.</p>
|
|
||||||
</div>
|
|
||||||
} @else if (matches().length === 0) {
|
} @else if (matches().length === 0) {
|
||||||
<div class="patents-container">
|
<p class="message">{{ emptyMessage() }}</p>
|
||||||
<ng-container *ngTemplateOutlet="patentsHeader" />
|
|
||||||
<p class="message">{{ emptyMessage() }}</p>
|
|
||||||
</div>
|
|
||||||
} @else {
|
} @else {
|
||||||
<div class="patents-container">
|
<div class="patents-container">
|
||||||
<ng-container *ngTemplateOutlet="patentsHeader" />
|
|
||||||
|
|
||||||
<div class="patents-content">
|
<div class="patents-content">
|
||||||
<div class="patents-list">
|
<div class="patents-list">
|
||||||
|
<div class="patents-list-toolbar">
|
||||||
|
<mat-form-field
|
||||||
|
class="patents-toolbar-field"
|
||||||
|
subscriptSizing="dynamic">
|
||||||
|
<mat-icon matPrefix fontIcon="filter_alt"></mat-icon>
|
||||||
|
<mat-select
|
||||||
|
[value]="activeFilter()"
|
||||||
|
(selectionChange)="setFilter($event.value)">
|
||||||
|
<mat-select-trigger>Filter nach Quelle</mat-select-trigger>
|
||||||
|
<mat-option value="all">Alle</mat-option>
|
||||||
|
<mat-option value="EPO">EPO</mat-option>
|
||||||
|
<mat-option value="USPTO">USPTO</mat-option>
|
||||||
|
</mat-select>
|
||||||
|
</mat-form-field>
|
||||||
|
<mat-form-field
|
||||||
|
class="patents-toolbar-field"
|
||||||
|
subscriptSizing="dynamic">
|
||||||
|
<mat-icon matPrefix fontIcon="sort"></mat-icon>
|
||||||
|
<mat-select
|
||||||
|
[value]="sortColumn()"
|
||||||
|
(selectionChange)="setSort($event.value)">
|
||||||
|
<mat-select-trigger>Sortieren nach</mat-select-trigger>
|
||||||
|
<mat-option value="year">Jahr</mat-option>
|
||||||
|
<mat-option value="title">Titel</mat-option>
|
||||||
|
<mat-option value="source">Quelle</mat-option>
|
||||||
|
</mat-select>
|
||||||
|
</mat-form-field>
|
||||||
|
</div>
|
||||||
|
|
||||||
<table>
|
<table>
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>Patent</th>
|
<th>Patent</th>
|
||||||
<th>Score</th>
|
<th
|
||||||
<th>Quelle</th>
|
class="sortable"
|
||||||
<th>Jahr</th>
|
[class.sort-active]="sortColumn() === 'source'"
|
||||||
|
(click)="setSort('source')">
|
||||||
|
Quelle
|
||||||
|
@if (sortColumn() === 'source') {
|
||||||
|
<mat-icon class="sort-icon">{{
|
||||||
|
sortDirection() === 'asc'
|
||||||
|
? 'arrow_upward'
|
||||||
|
: 'arrow_downward'
|
||||||
|
}}</mat-icon>
|
||||||
|
}
|
||||||
|
</th>
|
||||||
|
<th
|
||||||
|
class="sortable"
|
||||||
|
[class.sort-active]="sortColumn() === 'year'"
|
||||||
|
(click)="setSort('year')">
|
||||||
|
Jahr
|
||||||
|
@if (sortColumn() === 'year') {
|
||||||
|
<mat-icon class="sort-icon">{{
|
||||||
|
sortDirection() === 'asc'
|
||||||
|
? 'arrow_upward'
|
||||||
|
: 'arrow_downward'
|
||||||
|
}}</mat-icon>
|
||||||
|
}
|
||||||
|
</th>
|
||||||
|
<th>Erfinder</th>
|
||||||
|
<th>Anmelder</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
@for (item of pagedMatches(); track trackMatch($index, item)) {
|
@for (item of getPagedMatches(); track trackMatch($index, item)) {
|
||||||
<tr
|
<tr
|
||||||
[class.selected]="selectedMatch() === item"
|
[class.selected]="selectedMatch() === item"
|
||||||
(click)="selectMatch(item)">
|
(click)="selectMatch(item)">
|
||||||
<td class="patent-title">
|
<td class="patent-title">
|
||||||
{{ item.patent.title ?? item.patent.patent_id }}
|
{{ item.patent.title ?? item.patent.patent_id }}
|
||||||
</td>
|
</td>
|
||||||
<td class="match-score">{{ formatScore(item.match_score) }}</td>
|
|
||||||
<td>
|
<td>
|
||||||
<span
|
<span
|
||||||
class="source-badge source-badge--{{
|
class="source-badge source-badge--{{
|
||||||
@@ -49,51 +91,103 @@
|
|||||||
{{ item.patent.source }}
|
{{ item.patent.source }}
|
||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td>{{ item.patent.publication_year ?? '-' }}</td>
|
<td>
|
||||||
|
@if (item.patent.publication_year) {
|
||||||
|
<span class="year-badge">{{
|
||||||
|
item.patent.publication_year
|
||||||
|
}}</span>
|
||||||
|
} @else {
|
||||||
|
<span>-</span>
|
||||||
|
}
|
||||||
|
</td>
|
||||||
|
<td class="patent-people">
|
||||||
|
@if (item.patent.inventors && item.patent.inventors.length) {
|
||||||
|
<div class="person-chips">
|
||||||
|
@for (
|
||||||
|
inventor of item.patent.inventors.slice(0, 2);
|
||||||
|
track inventor
|
||||||
|
) {
|
||||||
|
<span class="person-chip">
|
||||||
|
<mat-icon>person</mat-icon>
|
||||||
|
{{ inventor }}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
@if (item.patent.inventors.length > 2) {
|
||||||
|
<span class="person-chip-row">
|
||||||
|
<span class="person-chip">
|
||||||
|
<mat-icon>person</mat-icon>
|
||||||
|
{{ item.patent.inventors[2] }}
|
||||||
|
</span>
|
||||||
|
@if (item.patent.inventors.length > 3) {
|
||||||
|
<span class="person-chip person-chip--more"
|
||||||
|
>+{{ item.patent.inventors.length - 3 }}</span
|
||||||
|
>
|
||||||
|
}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
} @else {
|
||||||
|
<span>-</span>
|
||||||
|
}
|
||||||
|
</td>
|
||||||
|
<td class="patent-people">
|
||||||
|
@if (item.patent.assignees && item.patent.assignees.length) {
|
||||||
|
<div class="person-chips">
|
||||||
|
@for (
|
||||||
|
assignee of item.patent.assignees.slice(0, 2);
|
||||||
|
track assignee
|
||||||
|
) {
|
||||||
|
<span class="person-chip">
|
||||||
|
<mat-icon>{{
|
||||||
|
isAssigneeLikelyPerson(assignee, item.patent)
|
||||||
|
? 'person'
|
||||||
|
: 'apartment'
|
||||||
|
}}</mat-icon>
|
||||||
|
{{ assignee }}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
@if (item.patent.assignees.length > 2) {
|
||||||
|
<span class="person-chip-row">
|
||||||
|
<span class="person-chip">
|
||||||
|
<mat-icon>{{
|
||||||
|
isAssigneeLikelyPerson(
|
||||||
|
item.patent.assignees[2],
|
||||||
|
item.patent
|
||||||
|
)
|
||||||
|
? 'person'
|
||||||
|
: 'apartment'
|
||||||
|
}}</mat-icon>
|
||||||
|
{{ item.patent.assignees[2] }}
|
||||||
|
</span>
|
||||||
|
@if (item.patent.assignees.length > 3) {
|
||||||
|
<span class="person-chip person-chip--more"
|
||||||
|
>+{{ item.patent.assignees.length - 3 }}</span
|
||||||
|
>
|
||||||
|
}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
} @else {
|
||||||
|
<span>-</span>
|
||||||
|
}
|
||||||
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
}
|
}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
|
|
||||||
@if (hasPagination()) {
|
<app-query-param-paginator
|
||||||
<div class="pagination">
|
[total]="filteredMatches().length"
|
||||||
<button
|
queryParamPageKey="page"
|
||||||
[disabled]="selectedPage() === 1"
|
queryParamSizeKey="size"
|
||||||
(click)="setPage(selectedPage() - 1)">
|
[pageSizeOptions]="[10, 25, 50]"
|
||||||
Zurück
|
(handlePageChange)="onPatentPageChange($event)" />
|
||||||
</button>
|
|
||||||
<span>Seite {{ selectedPage() }} von {{ pageCount() }}</span>
|
|
||||||
<button
|
|
||||||
[disabled]="selectedPage() === pageCount()"
|
|
||||||
(click)="setPage(selectedPage() + 1)">
|
|
||||||
Weiter
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@if (selectedMatch(); as match) {
|
@if (selectedMatch(); as match) {
|
||||||
<div class="patent-detail">
|
<div class="patent-detail">
|
||||||
<h3>{{ match.patent.title ?? match.patent.patent_id }}</h3>
|
<h3>{{ match.patent.title ?? match.patent.patent_id }}</h3>
|
||||||
<div class="detail-stats">
|
<div class="detail-stats">
|
||||||
<div class="stat">
|
|
||||||
<span class="stat-label">Match-Score</span>
|
|
||||||
<span class="stat-value">{{
|
|
||||||
formatScore(match.match_score)
|
|
||||||
}}</span>
|
|
||||||
</div>
|
|
||||||
<div class="stat">
|
|
||||||
<span class="stat-label">Gematchte Keywords</span>
|
|
||||||
<span class="stat-value">{{
|
|
||||||
formatMatchList(match.matched_keywords)
|
|
||||||
}}</span>
|
|
||||||
</div>
|
|
||||||
<div class="stat">
|
|
||||||
<span class="stat-label">Gematchte IPC/CPC</span>
|
|
||||||
<span class="stat-value">{{
|
|
||||||
formatMatchList(match.matched_ipc_symbols)
|
|
||||||
}}</span>
|
|
||||||
</div>
|
|
||||||
<div class="stat">
|
<div class="stat">
|
||||||
<span class="stat-label">Quelle</span>
|
<span class="stat-label">Quelle</span>
|
||||||
<span class="stat-value">
|
<span class="stat-value">
|
||||||
@@ -123,6 +217,10 @@
|
|||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
@if (getAbstractPreview(match.patent.abstract); as abstractPreview) {
|
||||||
|
<p class="patent-detail-preview">{{ abstractPreview }}</p>
|
||||||
|
}
|
||||||
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="patent-detail-action"
|
class="patent-detail-action"
|
||||||
@@ -132,40 +230,33 @@
|
|||||||
>
|
>
|
||||||
<mat-icon aria-hidden="true">chevron_right</mat-icon>
|
<mat-icon aria-hidden="true">chevron_right</mat-icon>
|
||||||
</button>
|
</button>
|
||||||
|
<p class="patent-detail-hint">
|
||||||
|
Abstract, Erfinder, Anmelder und IPC/CPC-Klassifikation
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
} @else {
|
||||||
|
<div class="patent-detail overview">
|
||||||
|
<p class="overview-title">Patentübersicht</p>
|
||||||
|
<p class="overview-subtitle">Patente mit passenden Keywords.</p>
|
||||||
|
<div class="overview-stats">
|
||||||
|
<div class="overview-stat overview-stat--total">
|
||||||
|
<span class="overview-value">{{ matches().length }}</span>
|
||||||
|
<span class="overview-label">Patente</span>
|
||||||
|
</div>
|
||||||
|
<div class="overview-stat overview-stat--epo">
|
||||||
|
<span class="overview-value">{{ getEpoCount() }}</span>
|
||||||
|
<span class="overview-label">EPO</span>
|
||||||
|
</div>
|
||||||
|
<div class="overview-stat overview-stat--uspto">
|
||||||
|
<span class="overview-value">{{ getUsptoCount() }}</span>
|
||||||
|
<span class="overview-label">USPTO</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p class="overview-hint">
|
||||||
|
Wähle links ein Patent aus, um Details zu sehen.
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
<ng-template #patentsHeader>
|
|
||||||
<div class="patents-header">
|
|
||||||
<h2 class="section-title">Passende Patente</h2>
|
|
||||||
<div class="patents-header-actions">
|
|
||||||
@if (matches().length > 0) {
|
|
||||||
<label class="sort-control">
|
|
||||||
<span>Filter nach Quelle:</span>
|
|
||||||
<select
|
|
||||||
[value]="activeFilter()"
|
|
||||||
(change)="setFilter($any($event.target).value)">
|
|
||||||
<option value="all">Alle</option>
|
|
||||||
<option value="EPO">EPO</option>
|
|
||||||
<option value="USPTO">USPTO</option>
|
|
||||||
</select>
|
|
||||||
</label>
|
|
||||||
}
|
|
||||||
|
|
||||||
@if (showReload()) {
|
|
||||||
<button
|
|
||||||
mat-stroked-button
|
|
||||||
type="button"
|
|
||||||
class="reload-btn"
|
|
||||||
[disabled]="reloadDisabled()"
|
|
||||||
(click)="onReload()">
|
|
||||||
<mat-icon>refresh</mat-icon>
|
|
||||||
Neu laden
|
|
||||||
</button>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</ng-template>
|
|
||||||
|
|||||||
+292
-56
@@ -25,24 +25,25 @@
|
|||||||
background: var(--sg-card-bg);
|
background: var(--sg-card-bg);
|
||||||
border: 1px solid var(--sg-border);
|
border: 1px solid var(--sg-border);
|
||||||
box-shadow: var(--sg-shadow-sm);
|
box-shadow: var(--sg-shadow-sm);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 16px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.patents-header {
|
.patents-header {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-wrap: wrap;
|
flex-direction: column;
|
||||||
align-items: center;
|
gap: 16px;
|
||||||
justify-content: space-between;
|
|
||||||
gap: 12px;
|
|
||||||
margin-bottom: 16px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.patents-header-actions {
|
app-query-param-paginator {
|
||||||
display: flex;
|
display: block;
|
||||||
flex-wrap: wrap;
|
margin-top: 14px;
|
||||||
align-items: center;
|
}
|
||||||
justify-content: flex-end;
|
|
||||||
gap: 10px;
|
.patents-toolbar-field {
|
||||||
margin-left: auto;
|
width: fit-content;
|
||||||
|
min-width: 180px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.reload-btn {
|
.reload-btn {
|
||||||
@@ -77,79 +78,294 @@
|
|||||||
|
|
||||||
.patents-list {
|
.patents-list {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
|
||||||
|
.patents-list-toolbar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 16px;
|
||||||
|
margin-bottom: 18px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
table {
|
table {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
border-collapse: collapse;
|
border-collapse: collapse;
|
||||||
}
|
|
||||||
|
|
||||||
th {
|
th {
|
||||||
text-align: left;
|
text-align: left;
|
||||||
padding: 10px 12px;
|
padding: 12px 16px;
|
||||||
border-bottom: 2px solid var(--sg-border);
|
border-bottom: 1px solid var(--sg-border);
|
||||||
color: var(--sg-text);
|
font-size: 12px;
|
||||||
}
|
font-weight: 700;
|
||||||
|
color: var(--sg-text-muted);
|
||||||
|
|
||||||
tr {
|
&.sortable {
|
||||||
cursor: pointer;
|
display: table-cell;
|
||||||
color: var(--sg-text);
|
cursor: pointer;
|
||||||
|
-webkit-user-select: none;
|
||||||
|
user-select: none;
|
||||||
|
}
|
||||||
|
|
||||||
&:hover {
|
.sort-icon {
|
||||||
background: var(--sg-surface-soft);
|
vertical-align: middle;
|
||||||
|
margin-left: 2px;
|
||||||
|
width: 14px;
|
||||||
|
height: 14px;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
&.selected {
|
tr {
|
||||||
background: var(--sg-surface-muted);
|
cursor: pointer;
|
||||||
}
|
transition: background-color 0.15s ease;
|
||||||
}
|
|
||||||
|
|
||||||
td {
|
&:hover td {
|
||||||
padding: 10px 12px;
|
background: rgba(16, 26, 61, 0.04);
|
||||||
border-bottom: 1px solid var(--sg-border);
|
}
|
||||||
|
|
||||||
|
&.selected td {
|
||||||
|
background: var(--sg-primary-soft);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
td {
|
||||||
|
padding: 12px 16px;
|
||||||
|
border-bottom: 1px solid var(--sg-border);
|
||||||
|
color: var(--sg-text);
|
||||||
|
font-size: 13px;
|
||||||
|
transition: background-color 0.15s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.patent-title {
|
||||||
|
color: var(--sg-text);
|
||||||
|
font-weight: 600;
|
||||||
|
max-width: 400px;
|
||||||
|
white-space: normal;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
.patent-people {
|
||||||
|
max-width: 220px;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.patent-title {
|
.year-badge {
|
||||||
font-weight: 500;
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
min-width: 26px;
|
||||||
|
padding: 2px 10px;
|
||||||
|
border-radius: 999px;
|
||||||
|
border: 1px solid var(--sg-border);
|
||||||
|
color: var(--sg-text);
|
||||||
|
font-size: 0.8rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.person-chips {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.person-chip-row {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.person-chip {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
max-width: 100%;
|
||||||
|
padding: 2px 8px;
|
||||||
|
border: 1px solid var(--sg-border);
|
||||||
|
border-radius: var(--sg-radius-sm);
|
||||||
|
background: var(--sg-surface-soft);
|
||||||
|
color: var(--sg-text);
|
||||||
|
font-size: 0.75rem;
|
||||||
|
line-height: 1.4;
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
|
||||||
|
mat-icon {
|
||||||
|
flex-shrink: 0;
|
||||||
|
width: 14px;
|
||||||
|
height: 14px;
|
||||||
|
font-size: 14px;
|
||||||
|
color: var(--sg-text-soft);
|
||||||
|
}
|
||||||
|
|
||||||
|
&--more {
|
||||||
|
color: var(--sg-text-muted);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.source-badge {
|
.source-badge {
|
||||||
display: inline-block;
|
display: inline-flex;
|
||||||
padding: 2px 8px;
|
align-items: center;
|
||||||
|
padding: 3px 10px;
|
||||||
border-radius: 999px;
|
border-radius: 999px;
|
||||||
font-size: 12px;
|
font-size: 0.75rem;
|
||||||
font-weight: 600;
|
font-weight: 700;
|
||||||
|
|
||||||
&--epo {
|
&--epo {
|
||||||
background: var(--sg-primary-soft);
|
background: var(--sg-primary-soft);
|
||||||
color: var(--sg-blue-highlight);
|
color: var(--sg-blue-highlight);
|
||||||
|
background: #effaf3;
|
||||||
|
color: #24834f;
|
||||||
|
border: 1px solid #bdebcf;
|
||||||
}
|
}
|
||||||
|
|
||||||
&--uspto {
|
&--uspto {
|
||||||
background: var(--sg-success-soft);
|
background: var(--sg-success-soft);
|
||||||
color: var(--sg-success);
|
color: var(--sg-success);
|
||||||
|
background: #f0f6ff;
|
||||||
|
color: #0b63ce;
|
||||||
|
border: 1px solid #bdd4ff;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.pagination {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 12px;
|
|
||||||
margin-top: 12px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.patent-detail {
|
.patent-detail {
|
||||||
flex: 0 0 320px;
|
flex: 0 0 320px;
|
||||||
padding: 16px;
|
padding: 16px;
|
||||||
border-radius: 12px;
|
border-radius: 12px;
|
||||||
background: var(--sg-surface-muted);
|
background: var(--sg-surface-muted);
|
||||||
border: 1px solid var(--sg-border);
|
border: 1px solid var(--sg-border);
|
||||||
|
width: 440px;
|
||||||
|
padding: 24px;
|
||||||
|
background: var(--sg-surface);
|
||||||
|
box-shadow: var(--sg-shadow-sm);
|
||||||
|
border-radius: var(--sg-radius-sm);
|
||||||
|
|
||||||
|
&.overview {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 12px;
|
||||||
|
|
||||||
|
.overview-title {
|
||||||
|
font-size: 15px;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--sg-text);
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.overview-subtitle {
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--sg-text-muted);
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.overview-stats {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1fr 1fr 1fr;
|
||||||
|
gap: 10px;
|
||||||
|
margin-top: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.overview-stat {
|
||||||
|
background: var(--sg-surface);
|
||||||
|
border: 1px solid var(--sg-border);
|
||||||
|
border-radius: var(--sg-radius-sm);
|
||||||
|
padding: 12px 8px;
|
||||||
|
text-align: center;
|
||||||
|
|
||||||
|
.overview-value {
|
||||||
|
display: block;
|
||||||
|
font-size: 22px;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--sg-text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.overview-label {
|
||||||
|
display: block;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--sg-text-muted);
|
||||||
|
margin-top: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
&--total {
|
||||||
|
.overview-value,
|
||||||
|
.overview-label {
|
||||||
|
color: #7255d9;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
&--epo {
|
||||||
|
.overview-value,
|
||||||
|
.overview-label {
|
||||||
|
color: #24834f;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
&--uspto {
|
||||||
|
.overview-value,
|
||||||
|
.overview-label {
|
||||||
|
color: #0b63ce;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.overview-hint {
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--sg-text-muted);
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
h3 {
|
||||||
|
margin: 0 0 16px 0;
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--sg-text);
|
||||||
|
line-height: 1.4;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.detail-stats {
|
.detail-stats {
|
||||||
display: grid;
|
display: grid;
|
||||||
|
grid-template-columns: 1fr 1fr;
|
||||||
gap: 10px;
|
gap: 10px;
|
||||||
margin: 12px 0;
|
|
||||||
|
.stat {
|
||||||
|
background: var(--sg-surface);
|
||||||
|
border: 1px solid var(--sg-border);
|
||||||
|
border-radius: var(--sg-radius-sm);
|
||||||
|
padding: 10px;
|
||||||
|
text-align: center;
|
||||||
|
|
||||||
|
.stat-label {
|
||||||
|
display: block;
|
||||||
|
font-size: 11px;
|
||||||
|
color: var(--sg-text-muted);
|
||||||
|
margin-bottom: 4px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.03em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stat-value {
|
||||||
|
display: block;
|
||||||
|
font-size: 15px;
|
||||||
|
font-weight: bold;
|
||||||
|
color: var(--sg-text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.patent-detail-preview {
|
||||||
|
margin: 14px 0 0;
|
||||||
|
font-size: 13px;
|
||||||
|
line-height: 1.55;
|
||||||
|
color: var(--sg-text-muted);
|
||||||
}
|
}
|
||||||
|
|
||||||
.match-score {
|
.match-score {
|
||||||
@@ -174,6 +390,7 @@
|
|||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
|
gap: 8px;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
margin-top: 12px;
|
margin-top: 12px;
|
||||||
padding: 10px 12px;
|
padding: 10px 12px;
|
||||||
@@ -181,26 +398,45 @@
|
|||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
background: var(--sg-primary);
|
background: var(--sg-primary);
|
||||||
color: var(--sg-card-bg);
|
color: var(--sg-card-bg);
|
||||||
|
margin-top: 16px;
|
||||||
|
padding: 12px 14px;
|
||||||
|
border: 1px solid #bdd4ff;
|
||||||
|
border-radius: 10px;
|
||||||
|
background: linear-gradient(180deg, #f8fbff 0%, #eef4ff 100%);
|
||||||
|
color: #0b63ce;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 600;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
|
transition:
|
||||||
|
border-color 0.15s,
|
||||||
|
background 0.15s,
|
||||||
|
box-shadow 0.15s;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
border-color: #0b63ce;
|
||||||
|
background: #f0f6ff;
|
||||||
|
box-shadow: 0 2px 8px rgba(11, 99, 206, 0.12);
|
||||||
|
}
|
||||||
|
|
||||||
|
.material-icons {
|
||||||
|
font-size: 20px;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 900px) {
|
.patent-detail-hint {
|
||||||
.patents-header {
|
margin: 8px 0 0;
|
||||||
flex-direction: column;
|
font-size: 12px;
|
||||||
align-items: stretch;
|
line-height: 1.4;
|
||||||
}
|
color: #888;
|
||||||
|
text-align: center;
|
||||||
.patents-header-actions {
|
}
|
||||||
margin-left: 0;
|
|
||||||
justify-content: space-between;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
@media (max-width: 960px) {
|
||||||
.patents-content {
|
.patents-content {
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
}
|
}
|
||||||
|
|
||||||
.patent-detail {
|
.patent-detail {
|
||||||
flex: 1;
|
|
||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+144
-47
@@ -1,11 +1,14 @@
|
|||||||
import { NgTemplateOutlet } from '@angular/common';
|
import { Component, computed, inject, input, output, signal } from '@angular/core';
|
||||||
import { Component, input, output, signal } from '@angular/core';
|
import { toSignal } from '@angular/core/rxjs-interop';
|
||||||
import { MatButtonModule } from '@angular/material/button';
|
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||||
import { MatIconModule } from '@angular/material/icon';
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
import { Router } from '@angular/router';
|
import { MatSelectModule } from '@angular/material/select';
|
||||||
|
import { PageEvent } from '@angular/material/paginator';
|
||||||
|
import { ActivatedRoute, Router } from '@angular/router';
|
||||||
import { PatentEntry } from '../../../api/model/patentEntry';
|
import { PatentEntry } from '../../../api/model/patentEntry';
|
||||||
import { KeywordPatentMatch } from '../../../api/model/keywordPatentMatch';
|
import { KeywordPatentMatch } from '../../../api/model/keywordPatentMatch';
|
||||||
import { LoadingComponent } from '../../../shared/ui/loading/loading.component';
|
import { LoadingComponent } from '../../../shared/ui/loading/loading.component';
|
||||||
|
import { QueryParamPaginatorComponent } from '../../../shared/ui/query-param-paginator/query-param-paginator.component';
|
||||||
import {
|
import {
|
||||||
formatPatentDate,
|
formatPatentDate,
|
||||||
getPublicationStageLabel,
|
getPublicationStageLabel,
|
||||||
@@ -13,14 +16,26 @@ import {
|
|||||||
import { KeywordPatentMappingStatus } from '../../../api';
|
import { KeywordPatentMappingStatus } from '../../../api';
|
||||||
|
|
||||||
type SourceFilter = 'all' | 'EPO' | 'USPTO';
|
type SourceFilter = 'all' | 'EPO' | 'USPTO';
|
||||||
|
type SortColumn = 'title' | 'year' | 'source';
|
||||||
|
type SortDirection = 'asc' | 'desc';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-keywords-patents',
|
selector: 'app-keywords-patents',
|
||||||
imports: [NgTemplateOutlet, MatButtonModule, MatIconModule, LoadingComponent],
|
imports: [
|
||||||
|
MatFormFieldModule,
|
||||||
|
MatIconModule,
|
||||||
|
MatSelectModule,
|
||||||
|
LoadingComponent,
|
||||||
|
QueryParamPaginatorComponent,
|
||||||
|
],
|
||||||
templateUrl: './keywords-patents.component.html',
|
templateUrl: './keywords-patents.component.html',
|
||||||
styleUrl: './keywords-patents.component.scss',
|
styleUrl: './keywords-patents.component.scss',
|
||||||
})
|
})
|
||||||
export class KeywordsPatentsComponent {
|
export class KeywordsPatentsComponent {
|
||||||
|
private readonly route = inject(ActivatedRoute);
|
||||||
|
private readonly router = inject(Router);
|
||||||
|
private readonly queryParams = toSignal(this.route.queryParams);
|
||||||
|
|
||||||
readonly matches = input<KeywordPatentMatch[]>([]);
|
readonly matches = input<KeywordPatentMatch[]>([]);
|
||||||
readonly mappingStatus = input<KeywordPatentMappingStatus | null>(null);
|
readonly mappingStatus = input<KeywordPatentMappingStatus | null>(null);
|
||||||
readonly loading = input(false);
|
readonly loading = input(false);
|
||||||
@@ -30,54 +45,107 @@ export class KeywordsPatentsComponent {
|
|||||||
readonly reload = output<void>();
|
readonly reload = output<void>();
|
||||||
|
|
||||||
activeFilter = signal<SourceFilter>('all');
|
activeFilter = signal<SourceFilter>('all');
|
||||||
|
sortColumn = signal<SortColumn>('year');
|
||||||
|
sortDirection = signal<SortDirection>('desc');
|
||||||
selectedMatch = signal<KeywordPatentMatch | null>(null);
|
selectedMatch = signal<KeywordPatentMatch | null>(null);
|
||||||
selectedPage = signal(1);
|
|
||||||
readonly pageSize = 10;
|
|
||||||
|
|
||||||
constructor(private readonly router: Router) {}
|
readonly pageIndex = computed(() => {
|
||||||
|
const params = this.queryParams();
|
||||||
|
return params?.['page'] ? +params['page'] || 0 : 0;
|
||||||
|
});
|
||||||
|
|
||||||
|
readonly pageSize = computed(() => {
|
||||||
|
const params = this.queryParams();
|
||||||
|
return params?.['size'] ? +params['size'] || 10 : 10;
|
||||||
|
});
|
||||||
|
|
||||||
|
readonly filteredMatches = computed(() => {
|
||||||
|
const filter = this.activeFilter();
|
||||||
|
let items = this.matches();
|
||||||
|
if (filter !== 'all') {
|
||||||
|
items = items.filter((item) => item.patent.source === filter);
|
||||||
|
}
|
||||||
|
return this.sortMatches(items);
|
||||||
|
});
|
||||||
|
|
||||||
emptyMessage(): string {
|
emptyMessage(): string {
|
||||||
switch (this.mappingStatus()) {
|
switch (this.mappingStatus()) {
|
||||||
case 'search_error':
|
case 'search_error':
|
||||||
return 'Die Patentrecherche ist technisch fehlgeschlagen. Bitte später erneut versuchen.';
|
return 'Die Patentrecherche ist technisch fehlgeschlagen. Bitte später erneut versuchen.';
|
||||||
default:
|
default:
|
||||||
return 'Keine passenden Patente gefunden';
|
return 'Keine passenden Patente gefunden.';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
filteredMatches(): KeywordPatentMatch[] {
|
getPagedMatches(): KeywordPatentMatch[] {
|
||||||
const filter = this.activeFilter();
|
const start = this.pageIndex() * this.pageSize();
|
||||||
const items = this.matches();
|
return this.filteredMatches().slice(start, start + this.pageSize());
|
||||||
if (filter === 'all') {
|
|
||||||
return items;
|
|
||||||
}
|
|
||||||
return items.filter((item) => item.patent.source === filter);
|
|
||||||
}
|
|
||||||
|
|
||||||
pagedMatches(): KeywordPatentMatch[] {
|
|
||||||
const start = (this.selectedPage() - 1) * this.pageSize;
|
|
||||||
return this.filteredMatches().slice(start, start + this.pageSize);
|
|
||||||
}
|
|
||||||
|
|
||||||
pageCount(): number {
|
|
||||||
return Math.max(
|
|
||||||
1,
|
|
||||||
Math.ceil(this.filteredMatches().length / this.pageSize),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
hasPagination(): boolean {
|
|
||||||
return this.pageCount() > 1;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
setFilter(filter: SourceFilter): void {
|
setFilter(filter: SourceFilter): void {
|
||||||
this.activeFilter.set(filter);
|
this.activeFilter.set(filter);
|
||||||
this.selectedPage.set(1);
|
this.selectedMatch.set(null);
|
||||||
|
this.resetPage();
|
||||||
|
}
|
||||||
|
|
||||||
|
setSort(column: SortColumn): void {
|
||||||
|
if (this.sortColumn() === column) {
|
||||||
|
this.sortDirection.set(this.sortDirection() === 'asc' ? 'desc' : 'asc');
|
||||||
|
} else {
|
||||||
|
this.sortColumn.set(column);
|
||||||
|
this.sortDirection.set(column === 'year' ? 'desc' : 'asc');
|
||||||
|
}
|
||||||
|
this.selectedMatch.set(null);
|
||||||
|
this.resetPage();
|
||||||
|
}
|
||||||
|
|
||||||
|
isAssigneeLikelyPerson(assignee: string, patent: PatentEntry): boolean {
|
||||||
|
if (KeywordsPatentsComponent.ORG_SUFFIX_PATTERN.test(assignee)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalizedAssignee = this.normalizeNameForComparison(
|
||||||
|
assignee.replace(KeywordsPatentsComponent.PERSON_SUFFIX_PATTERN, ''),
|
||||||
|
);
|
||||||
|
const matchesInventor = (patent.inventors ?? []).some(
|
||||||
|
(inventor) =>
|
||||||
|
this.normalizeNameForComparison(inventor) === normalizedAssignee,
|
||||||
|
);
|
||||||
|
if (matchesInventor) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return KeywordsPatentsComponent.PERSON_SUFFIX_PATTERN.test(assignee);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly ORG_SUFFIX_PATTERN =
|
||||||
|
/\b(Inc|Ltd|LLC|LLP|GmbH|Corp(oration)?|Co|KG|AG|SE|S\.?A\.?|N\.?V\.?|B\.?V\.?|PLC|Universit(y|ät|é)|Institut(e)?|Foundation|Laborator(y|ies)|Labs?|Group|Holdings?|Company|Gesellschaft)\b\.?/i;
|
||||||
|
private static readonly PERSON_SUFFIX_PATTERN =
|
||||||
|
/\b(Dr|Prof|PhD|Ph\.D|M\.D|Jr|Sr)\b\.?/i;
|
||||||
|
|
||||||
|
private normalizeNameForComparison(name: string): string {
|
||||||
|
return name
|
||||||
|
.normalize('NFD')
|
||||||
|
.replace(/[̀-ͯ]/g, '')
|
||||||
|
.replace(/[.,]/g, '')
|
||||||
|
.toUpperCase()
|
||||||
|
.split(/\s+/)
|
||||||
|
.filter(Boolean)
|
||||||
|
.sort()
|
||||||
|
.join(' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
onPatentPageChange(_event: PageEvent): void {
|
||||||
this.selectedMatch.set(null);
|
this.selectedMatch.set(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
setPage(page: number): void {
|
private resetPage(): void {
|
||||||
this.selectedPage.set(Math.min(Math.max(page, 1), this.pageCount()));
|
void this.router.navigate([], {
|
||||||
|
relativeTo: this.route,
|
||||||
|
queryParams: { page: 0 },
|
||||||
|
queryParamsHandling: 'merge',
|
||||||
|
replaceUrl: true,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
selectMatch(item: KeywordPatentMatch): void {
|
selectMatch(item: KeywordPatentMatch): void {
|
||||||
@@ -90,8 +158,13 @@ export class KeywordsPatentsComponent {
|
|||||||
void this.router.navigate(['/patent', match.patent.patent_id]);
|
void this.router.navigate(['/patent', match.patent.patent_id]);
|
||||||
}
|
}
|
||||||
|
|
||||||
onReload(): void {
|
getEpoCount(): number {
|
||||||
this.reload.emit();
|
return this.matches().filter((item) => item.patent.source === 'EPO').length;
|
||||||
|
}
|
||||||
|
|
||||||
|
getUsptoCount(): number {
|
||||||
|
return this.matches().filter((item) => item.patent.source === 'USPTO')
|
||||||
|
.length;
|
||||||
}
|
}
|
||||||
|
|
||||||
formatDate(date: string | null | undefined): string {
|
formatDate(date: string | null | undefined): string {
|
||||||
@@ -102,18 +175,15 @@ export class KeywordsPatentsComponent {
|
|||||||
return getPublicationStageLabel(patent);
|
return getPublicationStageLabel(patent);
|
||||||
}
|
}
|
||||||
|
|
||||||
formatScore(score: number | null | undefined): string {
|
getAbstractPreview(abstract: string | null | undefined): string | null {
|
||||||
if (score == null || Number.isNaN(score)) {
|
if (!abstract?.trim()) {
|
||||||
return '-';
|
return null;
|
||||||
}
|
}
|
||||||
return score.toFixed(2);
|
const text = abstract.trim();
|
||||||
}
|
if (text.length <= 160) {
|
||||||
|
return text;
|
||||||
formatMatchList(values: string[] | null | undefined): string {
|
|
||||||
if (!values || values.length === 0) {
|
|
||||||
return '-';
|
|
||||||
}
|
}
|
||||||
return values.join(', ');
|
return `${text.slice(0, 160).trimEnd()}…`;
|
||||||
}
|
}
|
||||||
|
|
||||||
trackMatch(_index: number, item: KeywordPatentMatch): string {
|
trackMatch(_index: number, item: KeywordPatentMatch): string {
|
||||||
@@ -126,4 +196,31 @@ export class KeywordsPatentsComponent {
|
|||||||
item.match_score,
|
item.match_score,
|
||||||
].join('|');
|
].join('|');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private sortMatches(items: KeywordPatentMatch[]): KeywordPatentMatch[] {
|
||||||
|
const column = this.sortColumn();
|
||||||
|
const direction = this.sortDirection() === 'asc' ? 1 : -1;
|
||||||
|
return [...items].sort((a, b) => {
|
||||||
|
switch (column) {
|
||||||
|
case 'year': {
|
||||||
|
const yearA =
|
||||||
|
a.patent.publication_date ??
|
||||||
|
String(a.patent.publication_year ?? '');
|
||||||
|
const yearB =
|
||||||
|
b.patent.publication_date ??
|
||||||
|
String(b.patent.publication_year ?? '');
|
||||||
|
return direction * yearA.localeCompare(yearB);
|
||||||
|
}
|
||||||
|
case 'source':
|
||||||
|
return direction * a.patent.source.localeCompare(b.patent.source);
|
||||||
|
default:
|
||||||
|
return (
|
||||||
|
direction *
|
||||||
|
(a.patent.title ?? '').localeCompare(b.patent.title ?? '', 'de', {
|
||||||
|
sensitivity: 'base',
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -179,6 +179,8 @@
|
|||||||
<div class="keyword-chip-stack">
|
<div class="keyword-chip-stack">
|
||||||
@for (keyword of keywords; track keyword.llm_keyword.keyword) {
|
@for (keyword of keywords; track keyword.llm_keyword.keyword) {
|
||||||
<app-topic-chip
|
<app-topic-chip
|
||||||
|
[topic]="keyword.topic_mapping?.topic"
|
||||||
|
[topicId]="keyword.topic_mapping?.topic?.id"
|
||||||
[label]="getChipLabel(keyword)"
|
[label]="getChipLabel(keyword)"
|
||||||
[count]="
|
[count]="
|
||||||
keywordView() === 'topic' ? getChipCount(keyword) : null
|
keywordView() === 'topic' ? getChipCount(keyword) : null
|
||||||
@@ -209,6 +211,8 @@
|
|||||||
) {
|
) {
|
||||||
<div class="manual-chip-row">
|
<div class="manual-chip-row">
|
||||||
<app-topic-chip
|
<app-topic-chip
|
||||||
|
[topic]="keyword.topic_mapping?.topic"
|
||||||
|
[topicId]="keyword.topic_mapping?.topic?.id"
|
||||||
[label]="getChipLabel(keyword)"
|
[label]="getChipLabel(keyword)"
|
||||||
[count]="
|
[count]="
|
||||||
keywordView() === 'topic' ? getChipCount(keyword) : null
|
keywordView() === 'topic' ? getChipCount(keyword) : null
|
||||||
|
|||||||
@@ -108,81 +108,3 @@ function sameKeywordSet(a: string[], b: string[]): boolean {
|
|||||||
const setA = new Set(a.map((keyword) => normalizeKeyword(keyword)));
|
const setA = new Set(a.map((keyword) => normalizeKeyword(keyword)));
|
||||||
return b.every((keyword) => setA.has(normalizeKeyword(keyword)));
|
return b.every((keyword) => setA.has(normalizeKeyword(keyword)));
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PatentScoreWeights {
|
|
||||||
ipc: number;
|
|
||||||
topic: number;
|
|
||||||
text: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const DEFAULT_PATENT_SCORE_WEIGHTS: PatentScoreWeights = {
|
|
||||||
ipc: 0.6,
|
|
||||||
topic: 0.25,
|
|
||||||
text: 0.15,
|
|
||||||
};
|
|
||||||
|
|
||||||
export function normalizePatentScoreWeights(
|
|
||||||
raw: Record<string, number>,
|
|
||||||
): PatentScoreWeights {
|
|
||||||
const ipc = raw['ipc'] ?? DEFAULT_PATENT_SCORE_WEIGHTS.ipc;
|
|
||||||
const topic = raw['topic'] ?? DEFAULT_PATENT_SCORE_WEIGHTS.topic;
|
|
||||||
const text = raw['text'] ?? DEFAULT_PATENT_SCORE_WEIGHTS.text;
|
|
||||||
const sum = ipc + topic + text;
|
|
||||||
if (sum <= 0) {
|
|
||||||
return { ...DEFAULT_PATENT_SCORE_WEIGHTS };
|
|
||||||
}
|
|
||||||
return { ipc: ipc / sum, topic: topic / sum, text: text / sum };
|
|
||||||
}
|
|
||||||
|
|
||||||
export function computePatentMatchScore(
|
|
||||||
match: Pick<KeywordPatentMatch, 'ipc_score' | 'topic_score' | 'text_score'>,
|
|
||||||
weights: PatentScoreWeights,
|
|
||||||
): number {
|
|
||||||
return (
|
|
||||||
Math.round(
|
|
||||||
(weights.ipc * match.ipc_score +
|
|
||||||
weights.topic * match.topic_score +
|
|
||||||
weights.text * match.text_score) *
|
|
||||||
10000,
|
|
||||||
) / 10000
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function applyPatentScoreWeights(
|
|
||||||
matches: KeywordPatentMatch[],
|
|
||||||
weights: PatentScoreWeights,
|
|
||||||
): KeywordPatentMatch[] {
|
|
||||||
return [...matches]
|
|
||||||
.map((match) => ({
|
|
||||||
...match,
|
|
||||||
match_score: computePatentMatchScore(match, weights),
|
|
||||||
}))
|
|
||||||
.sort((a, b) => {
|
|
||||||
const scoreDiff = b.match_score - a.match_score;
|
|
||||||
if (scoreDiff !== 0) {
|
|
||||||
return scoreDiff;
|
|
||||||
}
|
|
||||||
|
|
||||||
const dateA = a.patent.publication_date ?? '';
|
|
||||||
const dateB = b.patent.publication_date ?? '';
|
|
||||||
if (dateA !== dateB) {
|
|
||||||
return dateB.localeCompare(dateA);
|
|
||||||
}
|
|
||||||
|
|
||||||
return a.patent.patent_id.localeCompare(b.patent.patent_id);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function hasPatentComponentScores(match: KeywordPatentMatch): boolean {
|
|
||||||
return (
|
|
||||||
typeof match.ipc_score === 'number' &&
|
|
||||||
typeof match.topic_score === 'number' &&
|
|
||||||
typeof match.text_score === 'number'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function canReweightPatentMatches(
|
|
||||||
matches: KeywordPatentMatch[],
|
|
||||||
): boolean {
|
|
||||||
return matches.length > 0 && matches.every(hasPatentComponentScores);
|
|
||||||
}
|
|
||||||
|
|||||||
+150
-29
@@ -1,31 +1,152 @@
|
|||||||
<div class="result-layout">
|
<div class="content">
|
||||||
<mat-card class="results-card">
|
<div class="filters">
|
||||||
<mat-card-content class="results-placeholder">
|
<app-filter-card>
|
||||||
<mat-icon>groups</mat-icon>
|
<app-query-param-selector
|
||||||
<h2>Newsliste</h2>
|
class="relevance-field"
|
||||||
<p>
|
[options]="relevanceOptions"
|
||||||
Die aktuelle Gewichtung ist unter <code>normalized</code> verfügbar.
|
[queryParamKey]="keywordsNewsQueryParamKeys.relevance"
|
||||||
</p>
|
label="Relevanz"
|
||||||
</mat-card-content>
|
icon="check_circle"
|
||||||
</mat-card>
|
[multiple]="true" />
|
||||||
|
|
||||||
<mat-card class="weights-card">
|
<app-query-param-selector
|
||||||
<mat-card-content>
|
class="sort-order-field"
|
||||||
<app-weights-sliders
|
[options]="sortOrderOptions"
|
||||||
[options]="weightOptions"
|
[queryParamKey]="keywordsNewsQueryParamKeys.sortOrder"
|
||||||
[initialWeights]="defaultWeights"
|
label="Sortierung"
|
||||||
title="News-Gewichtung"
|
icon="sort" />
|
||||||
description="Werte zwischen 0 und 1. Summe wird normalisiert zu 1."
|
</app-filter-card>
|
||||||
resetLabel="Ausgewogen"
|
|
||||||
applyLabel="Neu gewichten"
|
<app-year-range-slider
|
||||||
normalizedTitle="Normalisiert"
|
[minYear]="minYear"
|
||||||
queryParamPrefix="newsW_"
|
[maxYear]="maxYear"
|
||||||
[persistInQueryParams]="true"
|
[(startYear)]="yearFrom"
|
||||||
[showApplyButton]="true"
|
[(endYear)]="yearTo"
|
||||||
[showResetButton]="true"
|
(startYearChange)="applyYearFilter()"
|
||||||
[showNormalizedPreview]="true"
|
(endYearChange)="applyYearFilter()">
|
||||||
(weightsChange)="onWeightsChange($event)"
|
</app-year-range-slider>
|
||||||
(applyWeights)="onApplyWeights($event)" />
|
|
||||||
</mat-card-content>
|
@if (hasActiveFilters()) {
|
||||||
</mat-card>
|
<button
|
||||||
|
class="reset-filter-btn"
|
||||||
|
mat-stroked-button
|
||||||
|
type="button"
|
||||||
|
(click)="resetFilters()"
|
||||||
|
aria-label="Filter zurücksetzen">
|
||||||
|
<mat-icon>filter_alt_off</mat-icon>
|
||||||
|
<span>Zurücksetzen</span>
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ng-template #titleTmp let-article>
|
||||||
|
<div class="title-cell">
|
||||||
|
<a class="title" [routerLink]="['/news', article.id]">
|
||||||
|
{{ article.maintitle || 'Kein Titel' }}
|
||||||
|
</a>
|
||||||
|
@if (article.snippet) {
|
||||||
|
<span class="snippet" [innerHTML]="article.snippet"></span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</ng-template>
|
||||||
|
|
||||||
|
<ng-template #dateTmp let-article>
|
||||||
|
@if (article.date) {
|
||||||
|
<span class="date-text">{{ article.date }}</span>
|
||||||
|
} @else {
|
||||||
|
<span class="empty-text">-</span>
|
||||||
|
}
|
||||||
|
</ng-template>
|
||||||
|
|
||||||
|
<ng-template #relevanceTmp let-article>
|
||||||
|
@if (article.relevant === true) {
|
||||||
|
<span class="relevance-badge is-relevant">
|
||||||
|
<mat-icon>check_circle</mat-icon>
|
||||||
|
Relevant
|
||||||
|
</span>
|
||||||
|
} @else if (article.relevant === false) {
|
||||||
|
<span class="relevance-badge not-relevant">
|
||||||
|
<mat-icon>cancel</mat-icon>
|
||||||
|
Nicht relevant
|
||||||
|
</span>
|
||||||
|
} @else {
|
||||||
|
<span
|
||||||
|
class="relevance-badge undetermined"
|
||||||
|
[matTooltip]="relevanceHelp"
|
||||||
|
matTooltipPosition="above">
|
||||||
|
<mat-icon>help</mat-icon>
|
||||||
|
Nicht bestimmt
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
</ng-template>
|
||||||
|
|
||||||
|
<ng-template #topicsTmp let-article>
|
||||||
|
@let topics = article.topics ?? [];
|
||||||
|
@let topicsExpanded = isTopicsExpanded(article);
|
||||||
|
@let visibleTopics =
|
||||||
|
topicsExpanded ? topics : topics.slice(0, topicPreviewCount);
|
||||||
|
|
||||||
|
<div class="topic-chips" aria-label="Themen">
|
||||||
|
@for (topic of visibleTopics; track topic.id ?? topic.display_name) {
|
||||||
|
<app-topic-chip-2
|
||||||
|
size="mini"
|
||||||
|
[topic]="toTopic(topic)"
|
||||||
|
[showIcon]="false"
|
||||||
|
[isSelected]="isTopicActive(topic)"
|
||||||
|
[isClickable]="fuzzySearch()"
|
||||||
|
(handleChipClick)="toggleTopicFilter($event)" />
|
||||||
|
} @empty {
|
||||||
|
<span class="empty-text">-</span>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (topics.length > topicPreviewCount) {
|
||||||
|
<app-chip-overflow-toggle
|
||||||
|
[expanded]="topicsExpanded"
|
||||||
|
[hiddenCount]="topics.length - topicPreviewCount"
|
||||||
|
(toggle)="toggleTopicsExpansion(article)" />
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</ng-template>
|
||||||
|
|
||||||
|
<ng-template #actionsTmp let-article>
|
||||||
|
<a
|
||||||
|
mat-icon-button
|
||||||
|
color="primary"
|
||||||
|
[routerLink]="['/news', article.id]"
|
||||||
|
matTooltip="Details anzeigen">
|
||||||
|
<mat-icon>open_in_new</mat-icon>
|
||||||
|
</a>
|
||||||
|
</ng-template>
|
||||||
|
|
||||||
|
@if (!hasSearchInput()) {
|
||||||
|
<div class="no-results">
|
||||||
|
<span>Keine Keywords ausgewählt.</span>
|
||||||
|
</div>
|
||||||
|
} @else if (total() === 0) {
|
||||||
|
<div class="no-results">
|
||||||
|
@if (hasNarrowingFilters()) {
|
||||||
|
<span>Keine Nachrichten für die aktuellen Filter.</span>
|
||||||
|
<span class="no-results__hint">
|
||||||
|
Setzen Sie die Filter zurück, um mehr Ergebnisse zu sehen.
|
||||||
|
</span>
|
||||||
|
} @else if (searchedByTopics()) {
|
||||||
|
<span>Zu diesen Themen gibt es keine Nachrichten.</span>
|
||||||
|
<span class="no-results__hint">
|
||||||
|
Campus Aktuell deckt nicht jedes Forschungsthema ab. Schalten Sie die
|
||||||
|
Fuzzy Search aus, um direkt nach den Keywords zu suchen.
|
||||||
|
</span>
|
||||||
|
} @else {
|
||||||
|
<span>Keine Nachrichten zu diesen Keywords gefunden.</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
} @else {
|
||||||
|
<div class="table-wrap">
|
||||||
|
<app-data-table [columns]="columns()" [data]="elements()" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<app-query-param-paginator
|
||||||
|
[total]="total()"
|
||||||
|
queryParamPageKey="page"
|
||||||
|
queryParamSizeKey="size" />
|
||||||
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+190
-20
@@ -1,29 +1,199 @@
|
|||||||
|
.content {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
/* ============================================================
|
/* ============================================================
|
||||||
RESULT LAYOUT
|
FILTERS
|
||||||
============================================================ */
|
============================================================ */
|
||||||
.result-layout {
|
.filters {
|
||||||
display: grid;
|
display: flex;
|
||||||
grid-template-columns: minmax(300px, 420px) 1fr;
|
flex-wrap: wrap;
|
||||||
grid-template-areas: 'summary results';
|
align-items: stretch;
|
||||||
gap: 0.75rem;
|
gap: 0.75rem;
|
||||||
align-items: start;
|
|
||||||
}
|
|
||||||
|
|
||||||
.search-summary-card {
|
.relevance-field,
|
||||||
grid-area: summary;
|
.sort-order-field {
|
||||||
}
|
min-width: 200px;
|
||||||
|
}
|
||||||
|
|
||||||
.results-card {
|
app-year-range-slider {
|
||||||
grid-area: results;
|
display: flex;
|
||||||
}
|
}
|
||||||
|
|
||||||
.search-summary-card,
|
::ng-deep app-year-range-slider .year-filter {
|
||||||
.results-card {
|
height: 100%;
|
||||||
background: var(--sg-surface);
|
}
|
||||||
border: 1px solid var(--sg-border);
|
|
||||||
box-shadow: none;
|
|
||||||
|
|
||||||
.mat-mdc-card-content {
|
::ng-deep .mat-mdc-form-field-subscript-wrapper {
|
||||||
padding: 0.75rem;
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
::ng-deep .mat-mdc-form-field-icon-prefix {
|
||||||
|
padding: 0 4px 0 10px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.reset-filter-btn {
|
||||||
|
display: flex;
|
||||||
|
align-self: center;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.25rem;
|
||||||
|
height: 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
TABLE
|
||||||
|
============================================================ */
|
||||||
|
.table-wrap {
|
||||||
|
position: relative;
|
||||||
|
overflow-x: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
::ng-deep .table-wrap table {
|
||||||
|
width: 100%;
|
||||||
|
min-width: 960px;
|
||||||
|
border-collapse: separate;
|
||||||
|
border-spacing: 0 10px;
|
||||||
|
box-shadow: none;
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
::ng-deep .table-wrap .mat-mdc-header-cell {
|
||||||
|
color: var(--sg-text-muted);
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
::ng-deep .table-wrap .mat-mdc-row {
|
||||||
|
height: 86px;
|
||||||
|
}
|
||||||
|
|
||||||
|
::ng-deep .table-wrap .mat-mdc-cell {
|
||||||
|
color: var(--sg-text);
|
||||||
|
border-bottom-color: var(--sg-border);
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
::ng-deep .table-wrap {
|
||||||
|
.mat-column-date,
|
||||||
|
.mat-column-relevant,
|
||||||
|
.mat-mdc-header-cell {
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mat-column-topics {
|
||||||
|
overflow: visible;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
TABLE CELLS
|
||||||
|
============================================================ */
|
||||||
|
.title-cell {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.25rem;
|
||||||
|
padding: 0.5rem 0;
|
||||||
|
max-width: 32rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.title {
|
||||||
|
display: inline-block;
|
||||||
|
max-width: 520px;
|
||||||
|
line-height: 1.35;
|
||||||
|
color: var(--sg-text);
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 700;
|
||||||
|
text-decoration: none;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
color: var(--sg-text);
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.snippet {
|
||||||
|
font-size: 12.5px;
|
||||||
|
line-height: 1.5;
|
||||||
|
color: var(--sg-text-secondary);
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
|
||||||
|
::ng-deep em {
|
||||||
|
font-style: normal;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--sg-blue-highlight);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.date-text {
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-text {
|
||||||
|
color: var(--sg-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.relevance-badge {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
padding: 5px 12px;
|
||||||
|
border-radius: 999px;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 1;
|
||||||
|
white-space: nowrap;
|
||||||
|
|
||||||
|
mat-icon {
|
||||||
|
font-size: 16px;
|
||||||
|
width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
&.is-relevant {
|
||||||
|
background: var(--sg-success-soft);
|
||||||
|
border: 1px solid var(--sg-success);
|
||||||
|
color: var(--sg-success);
|
||||||
|
}
|
||||||
|
|
||||||
|
&.not-relevant {
|
||||||
|
background: var(--sg-surface-muted);
|
||||||
|
border: 1px solid var(--sg-border);
|
||||||
|
color: var(--sg-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
&.undetermined {
|
||||||
|
background: var(--sg-warning-soft);
|
||||||
|
border: 1px solid var(--sg-warning);
|
||||||
|
color: var(--sg-warning);
|
||||||
|
cursor: help;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.topic-chips {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.25rem;
|
||||||
|
align-items: flex-start;
|
||||||
|
padding: 0.5rem 0;
|
||||||
|
max-width: 350px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.no-results {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
padding: 2rem;
|
||||||
|
color: var(--sg-text-muted);
|
||||||
|
text-align: center;
|
||||||
|
|
||||||
|
&__hint {
|
||||||
|
max-width: 34rem;
|
||||||
|
color: var(--sg-text-soft);
|
||||||
|
font-size: 0.8125rem;
|
||||||
|
line-height: 1.5;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+256
-87
@@ -1,115 +1,284 @@
|
|||||||
import { Component, inject, signal } from '@angular/core';
|
|
||||||
|
|
||||||
import { MatCardModule } from '@angular/material/card';
|
|
||||||
import { MatIconModule } from '@angular/material/icon';
|
|
||||||
|
|
||||||
import {
|
import {
|
||||||
WeightMap,
|
Component,
|
||||||
WeightSliderOption,
|
DestroyRef,
|
||||||
WeightsSlidersComponent,
|
computed,
|
||||||
WeightsSlidersValue,
|
inject,
|
||||||
} from '../../../../shared/ui/weights-sliders/weights-sliders.component';
|
input,
|
||||||
|
signal,
|
||||||
|
TemplateRef,
|
||||||
|
viewChild,
|
||||||
|
} from '@angular/core';
|
||||||
|
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
|
||||||
|
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
|
||||||
|
|
||||||
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
|
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||||
|
|
||||||
|
import { MatchedTopic, NewsPage, Topic } from '../../../../api';
|
||||||
|
import {
|
||||||
|
DataTableComponent,
|
||||||
|
GenericColumn,
|
||||||
|
} from '../../../../shared/ui/data-table/data-table.component';
|
||||||
|
import { QueryParamPaginatorComponent } from '../../../../shared/ui/query-param-paginator/query-param-paginator.component';
|
||||||
|
import { AppTopicChipComponent } from '../../../../shared/ui/app-topic-chip/app-topic-chip.component';
|
||||||
|
import { ChipOverflowToggleComponent } from '../../../../shared/ui/chip-overflow-toggle/chip-overflow-toggle.component';
|
||||||
|
import { FilterCardComponent } from '../../../../shared/ui/filter-card/filter-card.component';
|
||||||
|
import {
|
||||||
|
QueryParamSelectorComponent,
|
||||||
|
SelectorOption,
|
||||||
|
} from '../../../../shared/ui/query-param-selector/query-param-selector.component';
|
||||||
|
import { NEWS_MIN_YEAR } from '../../../../shared/ui/news-card/news-card.component';
|
||||||
|
import { keywordsNewsQueryParamKeys } from '../../../../resolvers/keywords-news-page.resolver';
|
||||||
import { SearchResultsStateService } from '../search-results-state.service';
|
import { SearchResultsStateService } from '../search-results-state.service';
|
||||||
|
import { YearRangeSliderComponent } from '../../../../shared/ui/year-range-slider/year-range-slider.component';
|
||||||
|
|
||||||
|
type NewsResult = NewsPage['results'][number];
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-news-results',
|
selector: 'app-news-results',
|
||||||
imports: [MatCardModule, MatIconModule, WeightsSlidersComponent],
|
imports: [
|
||||||
|
RouterModule,
|
||||||
|
MatButtonModule,
|
||||||
|
MatIconModule,
|
||||||
|
MatTooltipModule,
|
||||||
|
DataTableComponent,
|
||||||
|
AppTopicChipComponent,
|
||||||
|
ChipOverflowToggleComponent,
|
||||||
|
FilterCardComponent,
|
||||||
|
QueryParamPaginatorComponent,
|
||||||
|
QueryParamSelectorComponent,
|
||||||
|
YearRangeSliderComponent,
|
||||||
|
],
|
||||||
templateUrl: './news-results.component.html',
|
templateUrl: './news-results.component.html',
|
||||||
styleUrl: './news-results.component.scss',
|
styleUrl: './news-results.component.scss',
|
||||||
})
|
})
|
||||||
export class KeywordsToNewsResultsComponent {
|
export class KeywordsToNewsResultsComponent {
|
||||||
// injects the state set by the parent route — no duplicate parsing here
|
protected readonly keywordsNewsQueryParamKeys = keywordsNewsQueryParamKeys;
|
||||||
|
|
||||||
private readonly state = inject(SearchResultsStateService);
|
private readonly state = inject(SearchResultsStateService);
|
||||||
|
private readonly route = inject(ActivatedRoute);
|
||||||
|
private readonly router = inject(Router);
|
||||||
|
private readonly destroyRef = inject(DestroyRef);
|
||||||
|
|
||||||
readonly defaultWeights: WeightMap = {
|
newsPage = input.required<NewsPage>();
|
||||||
param1: 0.33,
|
|
||||||
param2: 0.33,
|
|
||||||
param3: 0.34,
|
|
||||||
};
|
|
||||||
|
|
||||||
readonly weightOptions: WeightSliderOption[] = [
|
readonly minYear = NEWS_MIN_YEAR;
|
||||||
{
|
readonly maxYear = new Date().getFullYear();
|
||||||
key: 'param1',
|
|
||||||
label: 'Parameter 1',
|
readonly relevanceHelp =
|
||||||
icon: 'workspace_premium',
|
'Ein Artikel gilt als relevant, wenn er für Gründungsforschende interessante Inhalte enthält.';
|
||||||
description: 'Gewichtet Parameter 1.',
|
|
||||||
defaultValue: 0.5,
|
readonly sortOrderOptions: SelectorOption[] = [
|
||||||
queryParamName: 'wParam1',
|
{ value: 'desc', display_name: 'Neueste zuerst' },
|
||||||
},
|
{ value: 'asc', display_name: 'Älteste zuerst' },
|
||||||
{
|
|
||||||
key: 'param2',
|
|
||||||
label: 'Parameter 2',
|
|
||||||
icon: 'workspace_premium',
|
|
||||||
description: 'Gewichtet Parameter 2.',
|
|
||||||
defaultValue: 0.5,
|
|
||||||
queryParamName: 'wParam2',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'param3',
|
|
||||||
label: 'Parameter 3',
|
|
||||||
icon: 'workspace_premium',
|
|
||||||
description: 'Gewichtet Parameter 3.',
|
|
||||||
defaultValue: 0.5,
|
|
||||||
queryParamName: 'wParam3',
|
|
||||||
},
|
|
||||||
];
|
];
|
||||||
|
|
||||||
readonly currentWeights = signal<WeightsSlidersValue>({
|
readonly relevanceOptions: SelectorOption[] = [
|
||||||
raw: this.defaultWeights,
|
{ value: 'relevant', display_name: 'Relevant' },
|
||||||
normalized: {
|
{ value: 'not_relevant', display_name: 'Nicht relevant' },
|
||||||
param1: 0.33,
|
];
|
||||||
param2: 0.33,
|
|
||||||
param3: 0.34,
|
readonly yearFrom = signal<number>(this.minYear);
|
||||||
},
|
readonly yearTo = signal<number>(this.maxYear);
|
||||||
rawSum: 2.5,
|
|
||||||
normalizedSum: 1,
|
protected readonly topicPreviewCount = 3;
|
||||||
valid: true,
|
private readonly expandedTopicsIds = signal<ReadonlySet<string>>(new Set());
|
||||||
|
|
||||||
|
private readonly queryParamMap = toSignal(this.route.queryParamMap, {
|
||||||
|
initialValue: this.route.snapshot.queryParamMap,
|
||||||
});
|
});
|
||||||
|
|
||||||
readonly projects = signal<unknown[]>([]); // placeholder until the results service lands
|
readonly total = computed(() => this.newsPage().total ?? 0);
|
||||||
|
readonly elements = computed(() => this.newsPage().results ?? []);
|
||||||
|
readonly fuzzySearch = computed(
|
||||||
|
() => this.queryParamMap().get('fuzzy') === 'true',
|
||||||
|
);
|
||||||
|
|
||||||
private hasLoadedInitial = false;
|
readonly hasSearchInput = computed(() =>
|
||||||
constructor() {
|
this.fuzzySearch()
|
||||||
console.log('check', this.state.payload());
|
? this.state.topicIds().length > 0 || this.state.keywords().length > 0
|
||||||
}
|
: this.state.keywords().length > 0,
|
||||||
onWeightsChange(value: WeightsSlidersValue): void {
|
);
|
||||||
this.currentWeights.set(value);
|
|
||||||
|
|
||||||
// fires once with the query-param-aware initial state — use it to load
|
readonly selectedTopicIds = computed(() =>
|
||||||
if (!this.hasLoadedInitial) {
|
this.queryParamMap().getAll(keywordsNewsQueryParamKeys.topicId),
|
||||||
this.hasLoadedInitial = true;
|
);
|
||||||
this.loadprojects();
|
|
||||||
|
readonly hasActiveFilters = computed(() => {
|
||||||
|
const params = this.queryParamMap();
|
||||||
|
return (
|
||||||
|
!!params.get(keywordsNewsQueryParamKeys.relevance) ||
|
||||||
|
!!params.get(keywordsNewsQueryParamKeys.yearFrom) ||
|
||||||
|
!!params.get(keywordsNewsQueryParamKeys.yearTo) ||
|
||||||
|
!!params.get(keywordsNewsQueryParamKeys.sortOrder) ||
|
||||||
|
this.selectedTopicIds().length > 0
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
readonly hasNarrowingFilters = computed(() => {
|
||||||
|
const params = this.queryParamMap();
|
||||||
|
return (
|
||||||
|
!!params.get(keywordsNewsQueryParamKeys.relevance) ||
|
||||||
|
!!params.get(keywordsNewsQueryParamKeys.yearFrom) ||
|
||||||
|
!!params.get(keywordsNewsQueryParamKeys.yearTo) ||
|
||||||
|
this.selectedTopicIds().length > 0
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
readonly searchedByTopics = computed(() => {
|
||||||
|
if (!this.fuzzySearch()) {
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
const baseTopicIds = (this.queryParamMap().get('topics') ?? '')
|
||||||
|
.split(',')
|
||||||
|
.filter((value) => value.trim());
|
||||||
|
return baseTopicIds.length > 0 || this.selectedTopicIds().length > 0;
|
||||||
|
});
|
||||||
|
|
||||||
|
titleTmp = viewChild.required<TemplateRef<any>>('titleTmp');
|
||||||
|
dateTmp = viewChild.required<TemplateRef<any>>('dateTmp');
|
||||||
|
relevanceTmp = viewChild.required<TemplateRef<any>>('relevanceTmp');
|
||||||
|
topicsTmp = viewChild.required<TemplateRef<any>>('topicsTmp');
|
||||||
|
actionsTmp = viewChild.required<TemplateRef<any>>('actionsTmp');
|
||||||
|
|
||||||
|
readonly columns = computed<GenericColumn<NewsResult>[]>(() => [
|
||||||
|
{
|
||||||
|
id: 'maintitle',
|
||||||
|
header: 'Titel',
|
||||||
|
type: 'display',
|
||||||
|
cellTemplate: this.titleTmp(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'date',
|
||||||
|
header: 'Datum',
|
||||||
|
type: 'display',
|
||||||
|
cellTemplate: this.dateTmp(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'relevant',
|
||||||
|
header: 'Relevanz',
|
||||||
|
type: 'display',
|
||||||
|
cellTemplate: this.relevanceTmp(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'topics',
|
||||||
|
header: 'Themen',
|
||||||
|
type: 'display',
|
||||||
|
cellTemplate: this.topicsTmp(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'actions',
|
||||||
|
header: 'Aktionen',
|
||||||
|
type: 'display',
|
||||||
|
cellTemplate: this.actionsTmp(),
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.route.queryParamMap
|
||||||
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
|
.subscribe((params) => {
|
||||||
|
this.yearFrom.set(
|
||||||
|
this.parseYear(params.get(keywordsNewsQueryParamKeys.yearFrom)) ??
|
||||||
|
this.minYear,
|
||||||
|
);
|
||||||
|
this.yearTo.set(
|
||||||
|
this.parseYear(params.get(keywordsNewsQueryParamKeys.yearTo)) ??
|
||||||
|
this.maxYear,
|
||||||
|
);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
onApplyWeights(value: WeightsSlidersValue): void {
|
applyYearFilter(): void {
|
||||||
this.currentWeights.set(value);
|
this.router.navigate([], {
|
||||||
this.loadprojects();
|
relativeTo: this.route,
|
||||||
}
|
queryParams: {
|
||||||
|
[keywordsNewsQueryParamKeys.yearFrom]:
|
||||||
private loadprojects(): void {
|
this.yearFrom() > this.minYear ? this.yearFrom() : null,
|
||||||
const weights = this.currentWeights();
|
[keywordsNewsQueryParamKeys.yearTo]:
|
||||||
|
this.yearTo() < this.maxYear ? this.yearTo() : null,
|
||||||
const requestPayload = {
|
[keywordsNewsQueryParamKeys.page]: 0,
|
||||||
manualKeywords: this.state.manualKeywords(),
|
|
||||||
extractedKeywords: this.state.extractedKeywords(),
|
|
||||||
keywords: this.state.keywords(),
|
|
||||||
fuzzy: this.state.fuzzySearch(),
|
|
||||||
weights: {
|
|
||||||
raw: weights.raw,
|
|
||||||
normalized: weights.normalized,
|
|
||||||
},
|
},
|
||||||
|
queryParamsHandling: 'merge',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
toTopic(matched: MatchedTopic): Topic {
|
||||||
|
return {
|
||||||
|
id: matched.id,
|
||||||
|
display_name: matched.display_name,
|
||||||
|
subfield: matched.subfield_name
|
||||||
|
? { display_name: matched.subfield_name }
|
||||||
|
: null,
|
||||||
|
field: matched.field_name ? { display_name: matched.field_name } : null,
|
||||||
|
domain: matched.domain_name
|
||||||
|
? { display_name: matched.domain_name }
|
||||||
|
: null,
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
console.log(requestPayload);
|
isTopicActive(topic: MatchedTopic): boolean {
|
||||||
|
return !!topic.id && this.selectedTopicIds().includes(topic.id);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
isTopicsExpanded(article: NewsResult): boolean {
|
||||||
* TODO:
|
return this.expandedTopicsIds().has(article.id);
|
||||||
* this.projectsService.searchprojects(requestPayload).subscribe({
|
}
|
||||||
* next: results => this.projects.set(results),
|
|
||||||
* error: error => console.error(error),
|
toggleTopicsExpansion(article: NewsResult): void {
|
||||||
* });
|
if (!article.id) {
|
||||||
*/
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.expandedTopicsIds.update((ids) => {
|
||||||
|
const next = new Set(ids);
|
||||||
|
if (next.has(article.id)) {
|
||||||
|
next.delete(article.id);
|
||||||
|
} else {
|
||||||
|
next.add(article.id);
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
toggleTopicFilter(topic: Topic): void {
|
||||||
|
if (!topic.id || !this.fuzzySearch()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const selected = this.selectedTopicIds();
|
||||||
|
const next = selected.includes(topic.id)
|
||||||
|
? selected.filter((id) => id !== topic.id)
|
||||||
|
: [...selected, topic.id];
|
||||||
|
|
||||||
|
this.router.navigate([], {
|
||||||
|
relativeTo: this.route,
|
||||||
|
queryParams: {
|
||||||
|
[keywordsNewsQueryParamKeys.topicId]: next.length ? next : null,
|
||||||
|
[keywordsNewsQueryParamKeys.page]: 0,
|
||||||
|
},
|
||||||
|
queryParamsHandling: 'merge',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
resetFilters(): void {
|
||||||
|
this.router.navigate([], {
|
||||||
|
relativeTo: this.route,
|
||||||
|
queryParams: {
|
||||||
|
[keywordsNewsQueryParamKeys.relevance]: null,
|
||||||
|
[keywordsNewsQueryParamKeys.yearFrom]: null,
|
||||||
|
[keywordsNewsQueryParamKeys.yearTo]: null,
|
||||||
|
[keywordsNewsQueryParamKeys.topicId]: null,
|
||||||
|
[keywordsNewsQueryParamKeys.sortOrder]: null,
|
||||||
|
[keywordsNewsQueryParamKeys.page]: 0,
|
||||||
|
},
|
||||||
|
queryParamsHandling: 'merge',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseYear(raw: string | null): number | null {
|
||||||
|
const year = Number.parseInt(raw ?? '', 10);
|
||||||
|
return Number.isNaN(year) ? null : year;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
-20
@@ -1,24 +1,4 @@
|
|||||||
<div class="result-layout">
|
<div class="result-layout">
|
||||||
<mat-card class="weights-card">
|
|
||||||
<mat-card-content>
|
|
||||||
<app-weights-sliders
|
|
||||||
[options]="weightOptions"
|
|
||||||
[initialWeights]="defaultWeights"
|
|
||||||
title="Patenten-Gewichtung"
|
|
||||||
description="Steuert die Gewichtung von IPC/CPC-Match, OpenAlex-Topic und Text-Match für den Gesamt-Score."
|
|
||||||
resetLabel="Standard"
|
|
||||||
applyLabel="Neu gewichten"
|
|
||||||
normalizedTitle="Normalisiert"
|
|
||||||
queryParamPrefix="patentW_"
|
|
||||||
[persistInQueryParams]="true"
|
|
||||||
[showApplyButton]="true"
|
|
||||||
[showResetButton]="true"
|
|
||||||
[showNormalizedPreview]="true"
|
|
||||||
(weightsChange)="onWeightsChange($event)"
|
|
||||||
(applyWeights)="onApplyWeights($event)" />
|
|
||||||
</mat-card-content>
|
|
||||||
</mat-card>
|
|
||||||
|
|
||||||
<div class="results-card">
|
<div class="results-card">
|
||||||
<app-keywords-patents
|
<app-keywords-patents
|
||||||
[matches]="patentMatches()"
|
[matches]="patentMatches()"
|
||||||
|
|||||||
+1
-13
@@ -1,20 +1,8 @@
|
|||||||
/* ============================================================
|
|
||||||
RESULT LAYOUT
|
|
||||||
============================================================ */
|
|
||||||
.result-layout {
|
.result-layout {
|
||||||
display: grid;
|
display: block;
|
||||||
grid-template-columns: minmax(280px, 360px) minmax(0, 1fr);
|
|
||||||
grid-template-areas: 'summary results';
|
|
||||||
gap: 0.75rem;
|
|
||||||
align-items: start;
|
|
||||||
}
|
|
||||||
|
|
||||||
.weights-card {
|
|
||||||
grid-area: summary;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.results-card {
|
.results-card {
|
||||||
grid-area: results;
|
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+3
-96
@@ -1,26 +1,12 @@
|
|||||||
import { Component, inject, OnInit, signal } from '@angular/core';
|
import { Component, inject, OnInit, signal } from '@angular/core';
|
||||||
|
|
||||||
import { MatButtonModule } from '@angular/material/button';
|
|
||||||
import { MatCardModule } from '@angular/material/card';
|
|
||||||
import { MatIconModule } from '@angular/material/icon';
|
|
||||||
|
|
||||||
import { KeywordsService } from '../../../../api/api/keywords.service';
|
import { KeywordsService } from '../../../../api/api/keywords.service';
|
||||||
import { KeywordPatentMatch } from '../../../../api/model/keywordPatentMatch';
|
import { KeywordPatentMatch } from '../../../../api/model/keywordPatentMatch';
|
||||||
import { PatentsByKeywordsResponse } from '../../../../api/model/patentsByKeywordsResponse';
|
import { PatentsByKeywordsResponse } from '../../../../api/model/patentsByKeywordsResponse';
|
||||||
import {
|
|
||||||
WeightMap,
|
|
||||||
WeightSliderOption,
|
|
||||||
WeightsSlidersComponent,
|
|
||||||
WeightsSlidersValue,
|
|
||||||
} from '../../../../shared/ui/weights-sliders/weights-sliders.component';
|
|
||||||
import { KeywordsPatentsComponent } from '../../keywords-patents/keywords-patents.component';
|
import { KeywordsPatentsComponent } from '../../keywords-patents/keywords-patents.component';
|
||||||
import {
|
import {
|
||||||
applyPatentScoreWeights,
|
|
||||||
buildPatentSearchItemsFromPayload,
|
buildPatentSearchItemsFromPayload,
|
||||||
canReweightPatentMatches,
|
|
||||||
clearPatentsCache,
|
clearPatentsCache,
|
||||||
DEFAULT_PATENT_SCORE_WEIGHTS,
|
|
||||||
normalizePatentScoreWeights,
|
|
||||||
readPatentsCache,
|
readPatentsCache,
|
||||||
writePatentsCache,
|
writePatentsCache,
|
||||||
} from '../../patent-search.utils';
|
} from '../../patent-search.utils';
|
||||||
@@ -29,13 +15,7 @@ import { KeywordPatentMappingStatus } from '../../../../api';
|
|||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-patents-results',
|
selector: 'app-patents-results',
|
||||||
imports: [
|
imports: [KeywordsPatentsComponent],
|
||||||
MatCardModule,
|
|
||||||
MatIconModule,
|
|
||||||
MatButtonModule,
|
|
||||||
WeightsSlidersComponent,
|
|
||||||
KeywordsPatentsComponent,
|
|
||||||
],
|
|
||||||
templateUrl: './patents-results.component.html',
|
templateUrl: './patents-results.component.html',
|
||||||
styleUrl: './patents-results.component.scss',
|
styleUrl: './patents-results.component.scss',
|
||||||
})
|
})
|
||||||
@@ -43,53 +23,11 @@ export class KeywordsToPatentsResultsComponent implements OnInit {
|
|||||||
protected readonly state = inject(SearchResultsStateService);
|
protected readonly state = inject(SearchResultsStateService);
|
||||||
private readonly keywordsService = inject(KeywordsService);
|
private readonly keywordsService = inject(KeywordsService);
|
||||||
|
|
||||||
readonly defaultWeights: WeightMap = { ...DEFAULT_PATENT_SCORE_WEIGHTS };
|
|
||||||
|
|
||||||
readonly weightOptions: WeightSliderOption[] = [
|
|
||||||
{
|
|
||||||
key: 'ipc',
|
|
||||||
label: 'IPC/CPC-Match',
|
|
||||||
icon: 'category',
|
|
||||||
description:
|
|
||||||
'Gewichtet die Übereinstimmung der Patent-Klassifikation (IPC/CPC) mit den Keywords.',
|
|
||||||
defaultValue: DEFAULT_PATENT_SCORE_WEIGHTS.ipc,
|
|
||||||
queryParamName: 'wIpc',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'topic',
|
|
||||||
label: 'OpenAlex-Topic',
|
|
||||||
icon: 'hub',
|
|
||||||
description:
|
|
||||||
'Gewichtet die thematische Übereinstimmung über OpenAlex-Topics und Fachgebiete.',
|
|
||||||
defaultValue: DEFAULT_PATENT_SCORE_WEIGHTS.topic,
|
|
||||||
queryParamName: 'wTopic',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'text',
|
|
||||||
label: 'Text-Match',
|
|
||||||
icon: 'article',
|
|
||||||
description:
|
|
||||||
'Gewichtet Treffer der Keywords im Patenttitel und in der Zusammenfassung.',
|
|
||||||
defaultValue: DEFAULT_PATENT_SCORE_WEIGHTS.text,
|
|
||||||
queryParamName: 'wText',
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
readonly currentWeights = signal<WeightsSlidersValue>({
|
|
||||||
raw: this.defaultWeights,
|
|
||||||
normalized: { ...DEFAULT_PATENT_SCORE_WEIGHTS },
|
|
||||||
rawSum: 1,
|
|
||||||
normalizedSum: 1,
|
|
||||||
valid: true,
|
|
||||||
});
|
|
||||||
|
|
||||||
readonly patentMatches = signal<KeywordPatentMatch[]>([]);
|
readonly patentMatches = signal<KeywordPatentMatch[]>([]);
|
||||||
readonly mappingStatus = signal<KeywordPatentMappingStatus | null>(null);
|
readonly mappingStatus = signal<KeywordPatentMappingStatus | null>(null);
|
||||||
readonly loadingPatents = signal(false);
|
readonly loadingPatents = signal(false);
|
||||||
readonly patentsError = signal(false);
|
readonly patentsError = signal(false);
|
||||||
|
|
||||||
private readonly patentMatchesBase = signal<KeywordPatentMatch[]>([]);
|
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
const cached = readPatentsCache(this.state.keywords());
|
const cached = readPatentsCache(this.state.keywords());
|
||||||
if (cached) {
|
if (cached) {
|
||||||
@@ -100,19 +38,6 @@ export class KeywordsToPatentsResultsComponent implements OnInit {
|
|||||||
this.loadMatchingPatents();
|
this.loadMatchingPatents();
|
||||||
}
|
}
|
||||||
|
|
||||||
onWeightsChange(value: WeightsSlidersValue): void {
|
|
||||||
this.currentWeights.set(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
onApplyWeights(value: WeightsSlidersValue): void {
|
|
||||||
this.currentWeights.set(value);
|
|
||||||
if (!canReweightPatentMatches(this.patentMatchesBase())) {
|
|
||||||
this.reloadPatents();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
this.updateDisplayedMatches();
|
|
||||||
}
|
|
||||||
|
|
||||||
reloadPatents(): void {
|
reloadPatents(): void {
|
||||||
clearPatentsCache();
|
clearPatentsCache();
|
||||||
this.loadMatchingPatents();
|
this.loadMatchingPatents();
|
||||||
@@ -149,26 +74,8 @@ export class KeywordsToPatentsResultsComponent implements OnInit {
|
|||||||
matches: KeywordPatentMatch[],
|
matches: KeywordPatentMatch[],
|
||||||
mappingStatus: KeywordPatentMappingStatus | null = null,
|
mappingStatus: KeywordPatentMappingStatus | null = null,
|
||||||
): void {
|
): void {
|
||||||
this.patentMatchesBase.set(matches);
|
this.patentMatches.set(matches);
|
||||||
this.mappingStatus.set(mappingStatus);
|
this.mappingStatus.set(mappingStatus);
|
||||||
this.updateDisplayedMatches();
|
writePatentsCache(this.state.keywords(), matches, mappingStatus);
|
||||||
writePatentsCache(
|
|
||||||
this.state.keywords(),
|
|
||||||
this.patentMatchesBase(),
|
|
||||||
mappingStatus,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private updateDisplayedMatches(): void {
|
|
||||||
const base = this.patentMatchesBase();
|
|
||||||
if (!canReweightPatentMatches(base)) {
|
|
||||||
this.patentMatches.set(base);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const weights = normalizePatentScoreWeights(
|
|
||||||
this.currentWeights().normalized,
|
|
||||||
);
|
|
||||||
this.patentMatches.set(applyPatentScoreWeights(base, weights));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-13
@@ -4,19 +4,9 @@
|
|||||||
<p>Übersicht der durchgeführten Projekte.</p>
|
<p>Übersicht der durchgeführten Projekte.</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<nav mat-tab-nav-bar [tabPanel]="resultTabPanel" class="result-nav">
|
@if (resultTabPanel) {
|
||||||
@for (route of childRoutes; track route.path) {
|
<app-link-tab-nav-bar [links]="_links()" [tabPanel]="resultTabPanel" />
|
||||||
<a
|
}
|
||||||
matTabLink
|
|
||||||
[routerLink]="[route.path]"
|
|
||||||
queryParamsHandling="merge"
|
|
||||||
routerLinkActive
|
|
||||||
#rla="routerLinkActive"
|
|
||||||
[active]="rla.isActive">
|
|
||||||
{{ route.label }}
|
|
||||||
</a>
|
|
||||||
}
|
|
||||||
</nav>
|
|
||||||
|
|
||||||
<mat-tab-nav-panel #resultTabPanel>
|
<mat-tab-nav-panel #resultTabPanel>
|
||||||
<router-outlet />
|
<router-outlet />
|
||||||
|
|||||||
+31
-22
@@ -6,16 +6,13 @@ import { MatTabsModule } from '@angular/material/tabs';
|
|||||||
import { OnInit, computed } from '@angular/core';
|
import { OnInit, computed } from '@angular/core';
|
||||||
import { ActivatedRoute, Router } from '@angular/router';
|
import { ActivatedRoute, Router } from '@angular/router';
|
||||||
import { toSignal } from '@angular/core/rxjs-interop';
|
import { toSignal } from '@angular/core/rxjs-interop';
|
||||||
|
import {
|
||||||
|
LinkTabNavBarComponent,
|
||||||
|
LinkTabNavBarItem,
|
||||||
|
} from '../../../../shared/ui/link-tab-nav-bar/link-tab-nav-bar.component';
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-projects-results',
|
selector: 'app-projects-results',
|
||||||
imports: [
|
imports: [MatCardModule, MatTabsModule, RouterOutlet, LinkTabNavBarComponent],
|
||||||
MatCardModule,
|
|
||||||
MatTabsModule,
|
|
||||||
RouterLink,
|
|
||||||
RouterLinkActive,
|
|
||||||
RouterOutlet,
|
|
||||||
],
|
|
||||||
templateUrl: './projects-results.component.html',
|
templateUrl: './projects-results.component.html',
|
||||||
styleUrl: './projects-results.component.scss',
|
styleUrl: './projects-results.component.scss',
|
||||||
})
|
})
|
||||||
@@ -32,18 +29,30 @@ export class KeywordsToProjectsResultsComponent {
|
|||||||
() => this.queryParamMap().get('fuzzy') === 'true',
|
() => this.queryParamMap().get('fuzzy') === 'true',
|
||||||
);
|
);
|
||||||
|
|
||||||
readonly childRoutes = [
|
_links = computed<LinkTabNavBarItem[]>(() => {
|
||||||
{
|
const links: LinkTabNavBarItem[] = [
|
||||||
path: 'dfg',
|
{
|
||||||
label: 'DFG-Projekte',
|
label: 'DFG-Projekte',
|
||||||
},
|
path: 'dfg',
|
||||||
{
|
queryParams: { authorId: null, institutionId: null, agency: null },
|
||||||
path: 'eu',
|
queryParamsHandling: 'merge',
|
||||||
label: 'EU-Projekte',
|
disabled: false,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'bund',
|
label: 'EU-Projekte',
|
||||||
label: 'BUND-Projekte',
|
path: 'eu',
|
||||||
},
|
queryParams: { authorId: null, institutionId: null, agency: null },
|
||||||
];
|
queryParamsHandling: 'merge',
|
||||||
|
disabled: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'BUND-Projekte',
|
||||||
|
path: 'bund',
|
||||||
|
queryParams: { authorId: null, institutionId: null, agency: null },
|
||||||
|
queryParamsHandling: 'merge',
|
||||||
|
disabled: false,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
return links;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,6 +36,8 @@
|
|||||||
track getEntryTrack(entry)
|
track getEntryTrack(entry)
|
||||||
) {
|
) {
|
||||||
<app-topic-chip
|
<app-topic-chip
|
||||||
|
[topic]="entry.topic_mapping?.topic"
|
||||||
|
[topicId]="entry.topic_mapping?.topic?.id"
|
||||||
[label]="getChipLabel(entry)"
|
[label]="getChipLabel(entry)"
|
||||||
[count]="getChipCount(entry)"
|
[count]="getChipCount(entry)"
|
||||||
[description]="getChipDescription(entry)"
|
[description]="getChipDescription(entry)"
|
||||||
|
|||||||
@@ -9,10 +9,11 @@
|
|||||||
</button>
|
</button>
|
||||||
|
|
||||||
@if (loading) {
|
@if (loading) {
|
||||||
<div class="state">
|
<app-loading
|
||||||
<mat-spinner diameter="42"></mat-spinner>
|
text="Nachricht wird geladen..."
|
||||||
<p>Nachricht wird geladen...</p>
|
icon="newspaper"
|
||||||
</div>
|
[size]="60"
|
||||||
|
[diameter]="60" />
|
||||||
} @else if (notFound || !article) {
|
} @else if (notFound || !article) {
|
||||||
<div class="state error-state">
|
<div class="state error-state">
|
||||||
<mat-icon>search_off</mat-icon>
|
<mat-icon>search_off</mat-icon>
|
||||||
@@ -229,8 +230,8 @@
|
|||||||
»{{ topic.source_keyword }}«
|
»{{ topic.source_keyword }}«
|
||||||
</button>
|
</button>
|
||||||
<p class="kw-hint">
|
<p class="kw-hint">
|
||||||
Im Artikel hervorgehoben · klicken zum Suche zu
|
Im Artikel hervorgehoben - klicken, um zum
|
||||||
öffnen
|
ersten Vorkommen zu springen.
|
||||||
</p>
|
</p>
|
||||||
} @else {
|
} @else {
|
||||||
<p class="placeholder">
|
<p class="placeholder">
|
||||||
|
|||||||
@@ -6,18 +6,17 @@ import {
|
|||||||
ViewChild,
|
ViewChild,
|
||||||
inject,
|
inject,
|
||||||
} from '@angular/core';
|
} from '@angular/core';
|
||||||
import { Location } from '@angular/common';
|
|
||||||
import { HttpClient } from '@angular/common/http';
|
import { HttpClient } from '@angular/common/http';
|
||||||
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
|
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
|
||||||
import { MatButtonModule } from '@angular/material/button';
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
import { MatIconModule } from '@angular/material/icon';
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
|
|
||||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||||
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
|
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
|
||||||
|
|
||||||
import { WorksService } from '../../api';
|
import { WorksService } from '../../api';
|
||||||
import { topicHierarchyColor } from '../../resolvers/utils/topic-colors';
|
import { topicHierarchyColor } from '../../resolvers/utils/topic-colors';
|
||||||
|
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
|
||||||
|
|
||||||
interface MentionedPerson {
|
interface MentionedPerson {
|
||||||
name: string;
|
name: string;
|
||||||
@@ -52,9 +51,9 @@ interface NewsArticleDetail {
|
|||||||
imports: [
|
imports: [
|
||||||
MatButtonModule,
|
MatButtonModule,
|
||||||
MatIconModule,
|
MatIconModule,
|
||||||
MatProgressSpinnerModule,
|
|
||||||
MatTooltipModule,
|
MatTooltipModule,
|
||||||
RouterLink,
|
RouterLink,
|
||||||
|
LoadingComponent,
|
||||||
],
|
],
|
||||||
templateUrl: './news-detail.component.html',
|
templateUrl: './news-detail.component.html',
|
||||||
styleUrl: './news-detail.component.scss',
|
styleUrl: './news-detail.component.scss',
|
||||||
@@ -66,7 +65,6 @@ export class NewsDetailComponent implements OnInit {
|
|||||||
private readonly route = inject(ActivatedRoute);
|
private readonly route = inject(ActivatedRoute);
|
||||||
private readonly httpClient = inject(HttpClient);
|
private readonly httpClient = inject(HttpClient);
|
||||||
private readonly worksService = inject(WorksService);
|
private readonly worksService = inject(WorksService);
|
||||||
private readonly location = inject(Location);
|
|
||||||
private readonly sanitizer = inject(DomSanitizer);
|
private readonly sanitizer = inject(DomSanitizer);
|
||||||
|
|
||||||
article: NewsArticleDetail | null = null;
|
article: NewsArticleDetail | null = null;
|
||||||
@@ -150,7 +148,7 @@ export class NewsDetailComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
navigateBack(): void {
|
navigateBack(): void {
|
||||||
this.location.back();
|
this.router.navigate(['/news']);
|
||||||
}
|
}
|
||||||
|
|
||||||
formatDate(dateStr?: string | null): string {
|
formatDate(dateStr?: string | null): string {
|
||||||
@@ -200,36 +198,30 @@ export class NewsDetailComponent implements OnInit {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const orphanColors = [
|
|
||||||
'var(--sg-primary)',
|
|
||||||
'var(--sg-blue-highlight)',
|
|
||||||
'var(--sg-success)',
|
|
||||||
'var(--sg-warning)',
|
|
||||||
'var(--sg-error)',
|
|
||||||
];
|
|
||||||
let orphanIdx = 0;
|
|
||||||
|
|
||||||
let html = this.escapeHtml(text);
|
let html = this.escapeHtml(text);
|
||||||
if (keywords.length) {
|
[...keywords]
|
||||||
[...keywords]
|
.sort((a, b) => b.length - a.length)
|
||||||
.sort((a, b) => b.length - a.length)
|
.forEach((kw) => {
|
||||||
.forEach((kw) => {
|
const color = keywordColorMap.get(kw.toLowerCase());
|
||||||
let color = keywordColorMap.get(kw.toLowerCase());
|
if (!color) return;
|
||||||
if (!color) {
|
const kwHtml = this.escapeHtml(kw);
|
||||||
color = orphanColors[orphanIdx % orphanColors.length];
|
const escaped = this.escapeRegex(kwHtml);
|
||||||
orphanIdx++;
|
const before = '(?<![\\w\\u00C0-\\u024F])';
|
||||||
}
|
const acronymLike =
|
||||||
const kwHtml = this.escapeHtml(kw);
|
kw.length <= 3 ||
|
||||||
const re = new RegExp(
|
(kw === kw.toUpperCase() && kw !== kw.toLowerCase());
|
||||||
`(${this.escapeRegex(kwHtml)}[\\w\\u00C0-\\u024F]*)`,
|
const re = new RegExp(
|
||||||
'gi',
|
acronymLike
|
||||||
);
|
? `${before}(${escaped})(?![\\w\\u00C0-\\u024F])`
|
||||||
html = html.replace(
|
: `${before}(${escaped}[\\w\\u00C0-\\u024F]*)`,
|
||||||
re,
|
'gi',
|
||||||
`<mark class="kw-mark" style="--t:${color}" data-kw="${kwHtml}">$1</mark>`,
|
);
|
||||||
);
|
html = html.replace(
|
||||||
});
|
re,
|
||||||
}
|
`<mark class="kw-mark" style="--t:${color}" data-kw="${kwHtml}">$1</mark>`,
|
||||||
|
);
|
||||||
|
});
|
||||||
return this.sanitizer.bypassSecurityTrustHtml(html);
|
return this.sanitizer.bypassSecurityTrustHtml(html);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -18,38 +18,33 @@
|
|||||||
|
|
||||||
<ng-template #additionalFiltersTmp>
|
<ng-template #additionalFiltersTmp>
|
||||||
<div class="additional-filters">
|
<div class="additional-filters">
|
||||||
<mat-form-field appearance="outline" class="relevance-field">
|
<app-filter-card>
|
||||||
<mat-select
|
<app-query-param-selector
|
||||||
[formControl]="relevanceFilter"
|
class="relevance-field"
|
||||||
placeholder="Relevanz"
|
[options]="relevanceOptions"
|
||||||
multiple>
|
queryParamKey="relevance"
|
||||||
<mat-option value="relevant">Relevant</mat-option>
|
label="Relevanz"
|
||||||
<mat-option value="not_relevant">Nicht relevant</mat-option>
|
icon="check_circle"
|
||||||
</mat-select>
|
[multiple]="true" />
|
||||||
</mat-form-field>
|
|
||||||
|
|
||||||
<div class="year-field">
|
@if (!isSearching()) {
|
||||||
<div class="year-field__head">
|
<app-query-param-selector
|
||||||
<span class="year-field__label">Datum</span>
|
class="sort-order-field"
|
||||||
<span class="year-field__range">
|
[options]="sortingDirectionOptionsAll"
|
||||||
{{ yearFrom.value }} – {{ yearTo.value }}
|
queryParamKey="sorting_order"
|
||||||
</span>
|
label="Sortierung"
|
||||||
</div>
|
icon="sort" />
|
||||||
<mat-slider [min]="minYear" [max]="maxYear" step="1" discrete>
|
}
|
||||||
<input matSliderStartThumb [formControl]="yearFrom" />
|
</app-filter-card>
|
||||||
<input matSliderEndThumb [formControl]="yearTo" />
|
|
||||||
</mat-slider>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<button
|
<app-year-range-slider
|
||||||
class="reset-filter-btn"
|
class="year-field"
|
||||||
mat-stroked-button
|
[minYear]="minYear"
|
||||||
type="button"
|
[maxYear]="maxYear"
|
||||||
(click)="resetFilters()"
|
[startYear]="yearFrom.value"
|
||||||
aria-label="Filter zurücksetzen">
|
[endYear]="yearTo.value"
|
||||||
<mat-icon>filter_alt_off</mat-icon>
|
(startYearChange)="yearFrom.setValue($event)"
|
||||||
<span>Zurücksetzen</span>
|
(endYearChange)="yearTo.setValue($event)" />
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
</ng-template>
|
</ng-template>
|
||||||
|
|
||||||
@@ -70,7 +65,5 @@
|
|||||||
[additionalFiltersTmp]="additionalFiltersTmp"
|
[additionalFiltersTmp]="additionalFiltersTmp"
|
||||||
[noResultsTmp]="noResultsTmp"
|
[noResultsTmp]="noResultsTmp"
|
||||||
[cardMinWidth]="380"
|
[cardMinWidth]="380"
|
||||||
[sortingDirectionOptions]="sortingDirectionOptions()"
|
|
||||||
sortingDirectionLabel="Sortierung"
|
|
||||||
searchLabel="Nachrichten durchsuchen" />
|
searchLabel="Nachrichten durchsuchen" />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -44,67 +44,36 @@
|
|||||||
color: var(--sg-text-muted);
|
color: var(--sg-text-muted);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$card-min-width: 380px;
|
||||||
|
|
||||||
.additional-filters {
|
.additional-filters {
|
||||||
display: flex;
|
display: grid;
|
||||||
align-items: center;
|
grid-template-columns: repeat(auto-fill, minmax($card-min-width, 1fr));
|
||||||
flex-wrap: wrap;
|
align-items: stretch;
|
||||||
gap: 12px;
|
gap: 1.5rem;
|
||||||
padding: 0 1rem 1rem;
|
padding: 0 1rem 1rem;
|
||||||
}
|
|
||||||
|
|
||||||
.relevance-field {
|
app-year-range-slider {
|
||||||
width: 180px;
|
display: flex;
|
||||||
}
|
|
||||||
|
|
||||||
.year-field {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
justify-content: center;
|
|
||||||
min-width: 220px;
|
|
||||||
padding: 0 6px;
|
|
||||||
margin-top: -20px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.year-field__head {
|
|
||||||
display: flex;
|
|
||||||
align-items: baseline;
|
|
||||||
justify-content: space-between;
|
|
||||||
gap: 10px;
|
|
||||||
font-size: 12px;
|
|
||||||
margin-bottom: 20px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.year-field__label {
|
|
||||||
color: var(--sg-text-muted);
|
|
||||||
font-weight: 600;
|
|
||||||
}
|
|
||||||
|
|
||||||
.year-field__range {
|
|
||||||
color: var(--sg-text);
|
|
||||||
font-weight: 600;
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
.year-field mat-slider {
|
|
||||||
width: 100%;
|
|
||||||
margin: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.reset-filter-btn {
|
|
||||||
min-width: 132px;
|
|
||||||
height: 42px;
|
|
||||||
padding: 0 14px;
|
|
||||||
border: 1px solid var(--sg-border);
|
|
||||||
border-radius: var(--sg-radius-sm);
|
|
||||||
color: var(--sg-text);
|
|
||||||
background: var(--sg-surface);
|
|
||||||
|
|
||||||
mat-icon {
|
|
||||||
margin-right: 6px;
|
|
||||||
width: 20px;
|
|
||||||
height: 20px;
|
|
||||||
font-size: 20px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
::ng-deep app-year-range-slider .year-filter {
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
::ng-deep .mat-mdc-form-field-subscript-wrapper {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
::ng-deep .mat-mdc-form-field-icon-prefix {
|
||||||
|
padding: 0 4px 0 10px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.relevance-field,
|
||||||
|
.sort-order-field {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 600px) {
|
@media (max-width: 600px) {
|
||||||
|
|||||||
@@ -7,15 +7,10 @@ import {
|
|||||||
signal,
|
signal,
|
||||||
} from '@angular/core';
|
} from '@angular/core';
|
||||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||||
import { FormControl, ReactiveFormsModule } from '@angular/forms';
|
import { FormControl } from '@angular/forms';
|
||||||
import { ActivatedRoute, Router } from '@angular/router';
|
import { ActivatedRoute, Router } from '@angular/router';
|
||||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||||
import { debounceTime, merge } from 'rxjs';
|
import { debounceTime, merge } from 'rxjs';
|
||||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
|
||||||
import { MatSelectModule } from '@angular/material/select';
|
|
||||||
import { MatSliderModule } from '@angular/material/slider';
|
|
||||||
import { MatButtonModule } from '@angular/material/button';
|
|
||||||
import { MatIconModule } from '@angular/material/icon';
|
|
||||||
|
|
||||||
import { WorksService } from '../../api';
|
import { WorksService } from '../../api';
|
||||||
import {
|
import {
|
||||||
@@ -27,7 +22,12 @@ import {
|
|||||||
NewsCardComponent,
|
NewsCardComponent,
|
||||||
NEWS_MIN_YEAR,
|
NEWS_MIN_YEAR,
|
||||||
} from '../../shared/ui/news-card/news-card.component';
|
} from '../../shared/ui/news-card/news-card.component';
|
||||||
import { SelectorOption } from '../../shared/ui/query-param-selector/query-param-selector.component';
|
import {
|
||||||
|
QueryParamSelectorComponent,
|
||||||
|
SelectorOption,
|
||||||
|
} from '../../shared/ui/query-param-selector/query-param-selector.component';
|
||||||
|
import { FilterCardComponent } from '../../shared/ui/filter-card/filter-card.component';
|
||||||
|
import { YearRangeSliderComponent } from '../../shared/ui/year-range-slider/year-range-slider.component';
|
||||||
|
|
||||||
interface NewsArticle extends NewsArticleBase {
|
interface NewsArticle extends NewsArticleBase {
|
||||||
author?: string | null;
|
author?: string | null;
|
||||||
@@ -46,14 +46,11 @@ type SortOrder = 'desc' | 'asc';
|
|||||||
@Component({
|
@Component({
|
||||||
selector: 'app-news',
|
selector: 'app-news',
|
||||||
imports: [
|
imports: [
|
||||||
ReactiveFormsModule,
|
|
||||||
MatFormFieldModule,
|
|
||||||
MatSelectModule,
|
|
||||||
MatSliderModule,
|
|
||||||
MatButtonModule,
|
|
||||||
MatIconModule,
|
|
||||||
CardSearchComponent,
|
CardSearchComponent,
|
||||||
NewsCardComponent,
|
NewsCardComponent,
|
||||||
|
FilterCardComponent,
|
||||||
|
QueryParamSelectorComponent,
|
||||||
|
YearRangeSliderComponent,
|
||||||
],
|
],
|
||||||
templateUrl: './news.component.html',
|
templateUrl: './news.component.html',
|
||||||
styleUrl: './news.component.scss',
|
styleUrl: './news.component.scss',
|
||||||
@@ -68,11 +65,16 @@ export class NewsComponent implements OnInit {
|
|||||||
readonly minYear = NEWS_MIN_YEAR;
|
readonly minYear = NEWS_MIN_YEAR;
|
||||||
readonly maxYear = new Date().getFullYear();
|
readonly maxYear = new Date().getFullYear();
|
||||||
|
|
||||||
private readonly sortingDirectionOptionsAll: SelectorOption[] = [
|
readonly sortingDirectionOptionsAll: SelectorOption[] = [
|
||||||
{ value: 'desc', display_name: 'Neueste zuerst' },
|
{ value: 'desc', display_name: 'Neueste zuerst' },
|
||||||
{ value: 'asc', display_name: 'Älteste zuerst' },
|
{ value: 'asc', display_name: 'Älteste zuerst' },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
readonly relevanceOptions: SelectorOption[] = [
|
||||||
|
{ value: 'relevant', display_name: 'Relevant' },
|
||||||
|
{ value: 'not_relevant', display_name: 'Nicht relevant' },
|
||||||
|
];
|
||||||
|
|
||||||
readonly relevanceFilter = new FormControl<string[]>([], {
|
readonly relevanceFilter = new FormControl<string[]>([], {
|
||||||
nonNullable: true,
|
nonNullable: true,
|
||||||
});
|
});
|
||||||
@@ -89,9 +91,6 @@ export class NewsComponent implements OnInit {
|
|||||||
readonly searchQuery = signal('');
|
readonly searchQuery = signal('');
|
||||||
|
|
||||||
readonly isSearching = computed(() => this.searchQuery().trim().length > 0);
|
readonly isSearching = computed(() => this.searchQuery().trim().length > 0);
|
||||||
readonly sortingDirectionOptions = computed<SelectorOption[]>(() =>
|
|
||||||
this.isSearching() ? [] : this.sortingDirectionOptionsAll,
|
|
||||||
);
|
|
||||||
|
|
||||||
readonly page = computed<Page>(() => ({
|
readonly page = computed<Page>(() => ({
|
||||||
page: this.currentPage,
|
page: this.currentPage,
|
||||||
@@ -138,12 +137,6 @@ export class NewsComponent implements OnInit {
|
|||||||
.subscribe(() => this.applyFilters());
|
.subscribe(() => this.applyFilters());
|
||||||
}
|
}
|
||||||
|
|
||||||
resetFilters(): void {
|
|
||||||
this.relevanceFilter.setValue([]);
|
|
||||||
this.yearFrom.setValue(this.minYear);
|
|
||||||
this.yearTo.setValue(this.maxYear);
|
|
||||||
}
|
|
||||||
|
|
||||||
private applyFilters(): void {
|
private applyFilters(): void {
|
||||||
const relevance =
|
const relevance =
|
||||||
this.relevanceFilter.value.length > 0
|
this.relevanceFilter.value.length > 0
|
||||||
|
|||||||
@@ -9,10 +9,11 @@
|
|||||||
</button>
|
</button>
|
||||||
|
|
||||||
@if (loading) {
|
@if (loading) {
|
||||||
<div class="state">
|
<app-loading
|
||||||
<mat-spinner diameter="42"></mat-spinner>
|
text="Patent wird geladen..."
|
||||||
<p>Patent wird geladen...</p>
|
icon="workspace_premium"
|
||||||
</div>
|
[size]="60"
|
||||||
|
[diameter]="60" />
|
||||||
} @else if (notFound || !patent) {
|
} @else if (notFound || !patent) {
|
||||||
<div class="state error-state">
|
<div class="state error-state">
|
||||||
<mat-icon>search_off</mat-icon>
|
<mat-icon>search_off</mat-icon>
|
||||||
@@ -137,6 +138,7 @@
|
|||||||
track topic.topic_id ?? topic.topic_display_name
|
track topic.topic_id ?? topic.topic_display_name
|
||||||
) {
|
) {
|
||||||
<app-topic-chip
|
<app-topic-chip
|
||||||
|
[topicId]="topic.topic_id"
|
||||||
[label]="topic.topic_display_name"
|
[label]="topic.topic_display_name"
|
||||||
[fieldName]="topic.field_name"
|
[fieldName]="topic.field_name"
|
||||||
[domainName]="topic.domain_name"
|
[domainName]="topic.domain_name"
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import { Component, DestroyRef, OnInit, inject } from '@angular/core';
|
|||||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||||
import { MatButtonModule } from '@angular/material/button';
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
import { MatIconModule } from '@angular/material/icon';
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
|
|
||||||
import { ActivatedRoute, RouterLink } from '@angular/router';
|
import { ActivatedRoute, RouterLink } from '@angular/router';
|
||||||
import { finalize } from 'rxjs';
|
import { finalize } from 'rxjs';
|
||||||
|
|
||||||
@@ -15,6 +14,7 @@ import {
|
|||||||
classificationSectionColor,
|
classificationSectionColor,
|
||||||
topicHierarchyColor,
|
topicHierarchyColor,
|
||||||
} from '../../resolvers/utils/topic-colors';
|
} from '../../resolvers/utils/topic-colors';
|
||||||
|
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
|
||||||
import {
|
import {
|
||||||
ClassificationCard,
|
ClassificationCard,
|
||||||
ClassificationSystem,
|
ClassificationSystem,
|
||||||
@@ -32,9 +32,9 @@ import {
|
|||||||
imports: [
|
imports: [
|
||||||
MatButtonModule,
|
MatButtonModule,
|
||||||
MatIconModule,
|
MatIconModule,
|
||||||
MatProgressSpinnerModule,
|
|
||||||
RouterLink,
|
RouterLink,
|
||||||
TopicChipComponent,
|
TopicChipComponent,
|
||||||
|
LoadingComponent,
|
||||||
],
|
],
|
||||||
templateUrl: './patent-detail.component.html',
|
templateUrl: './patent-detail.component.html',
|
||||||
styleUrl: './patent-detail.component.scss',
|
styleUrl: './patent-detail.component.scss',
|
||||||
|
|||||||
@@ -26,54 +26,14 @@
|
|||||||
<mat-chip-option value="USPTO">USPTO</mat-chip-option>
|
<mat-chip-option value="USPTO">USPTO</mat-chip-option>
|
||||||
</mat-chip-listbox>
|
</mat-chip-listbox>
|
||||||
|
|
||||||
<div class="year-filter">
|
<app-year-range-slider
|
||||||
<div class="year-filter-top">
|
class="patent-year-filter"
|
||||||
<span class="year-filter-label">Zeitraum</span>
|
[minYear]="minYear"
|
||||||
|
[maxYear]="maxYear"
|
||||||
<span class="year-filter-values">
|
[(startYear)]="selectedStartYear"
|
||||||
{{ selectedStartYear }} bis {{ selectedEndYear }}
|
[(endYear)]="selectedEndYear"
|
||||||
</span>
|
(startYearChange)="onYearRangeChange()"
|
||||||
|
(endYearChange)="onYearRangeChange()" />
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="reset-range-button"
|
|
||||||
[disabled]="!canResetYearRange"
|
|
||||||
(click)="resetYearRange()">
|
|
||||||
Zurücksetzen
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div
|
|
||||||
class="year-range-slider"
|
|
||||||
[style.--range-start]="rangeStartPercent"
|
|
||||||
[style.--range-end]="rangeEndPercent">
|
|
||||||
<div class="range-track"></div>
|
|
||||||
<input
|
|
||||||
class="range-input range-input-start"
|
|
||||||
type="range"
|
|
||||||
[min]="minYear"
|
|
||||||
[max]="maxYear"
|
|
||||||
[value]="selectedStartYear"
|
|
||||||
[style.z-index]="selectedStartYear >= selectedEndYear - 5 ? 4 : 2"
|
|
||||||
(input)="onStartYearDrag($event)"
|
|
||||||
(change)="onStartYearInput($event)"
|
|
||||||
aria-label="Startjahr" />
|
|
||||||
<input
|
|
||||||
class="range-input range-input-end"
|
|
||||||
type="range"
|
|
||||||
[min]="minYear"
|
|
||||||
[max]="maxYear"
|
|
||||||
[value]="selectedEndYear"
|
|
||||||
(input)="onEndYearDrag($event)"
|
|
||||||
(change)="onEndYearInput($event)"
|
|
||||||
aria-label="Endjahr" />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="year-filter-bounds">
|
|
||||||
<span>{{ minYear }}</span>
|
|
||||||
<span>{{ maxYear }}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -151,6 +111,7 @@
|
|||||||
track topic.topic_id ?? topic.topic_display_name
|
track topic.topic_id ?? topic.topic_display_name
|
||||||
) {
|
) {
|
||||||
<app-topic-chip
|
<app-topic-chip
|
||||||
|
[topicId]="topic.topic_id"
|
||||||
[label]="topic.topic_display_name"
|
[label]="topic.topic_display_name"
|
||||||
[fieldName]="topic.field_name"
|
[fieldName]="topic.field_name"
|
||||||
[domainName]="topic.domain_name"
|
[domainName]="topic.domain_name"
|
||||||
|
|||||||
@@ -32,134 +32,8 @@ h1 {
|
|||||||
border-radius: var(--sg-radius-sm);
|
border-radius: var(--sg-radius-sm);
|
||||||
}
|
}
|
||||||
|
|
||||||
.year-filter {
|
.patent-year-filter {
|
||||||
width: min(285px, 100%);
|
width: min(285px, 100%);
|
||||||
padding: 5px 10px;
|
|
||||||
border: 1px solid var(--sg-border);
|
|
||||||
border-radius: 10px;
|
|
||||||
background: var(--sg-surface-muted);
|
|
||||||
box-sizing: border-box;
|
|
||||||
}
|
|
||||||
|
|
||||||
.year-filter-top {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: space-between;
|
|
||||||
gap: 10px;
|
|
||||||
margin-bottom: 4px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.year-filter-label {
|
|
||||||
color: var(--sg-text);
|
|
||||||
font-size: 12px;
|
|
||||||
font-weight: 700;
|
|
||||||
}
|
|
||||||
|
|
||||||
.reset-range-button {
|
|
||||||
border: 0;
|
|
||||||
background: transparent;
|
|
||||||
color: var(--sg-blue-highlight);
|
|
||||||
font-size: 11px;
|
|
||||||
cursor: pointer;
|
|
||||||
padding: 0;
|
|
||||||
font-family: inherit;
|
|
||||||
|
|
||||||
&:disabled {
|
|
||||||
color: var(--sg-text-soft);
|
|
||||||
cursor: default;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.year-filter-values {
|
|
||||||
color: var(--sg-text-muted);
|
|
||||||
font-size: 12px;
|
|
||||||
font-weight: 600;
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
.year-filter-bounds {
|
|
||||||
display: flex;
|
|
||||||
justify-content: space-between;
|
|
||||||
margin-top: 0;
|
|
||||||
color: var(--sg-text-soft);
|
|
||||||
font-size: 10px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.year-range-slider {
|
|
||||||
--range-start: 0%;
|
|
||||||
--range-end: 100%;
|
|
||||||
--accent: var(--sg-blue-highlight);
|
|
||||||
|
|
||||||
position: relative;
|
|
||||||
height: 16px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.range-track {
|
|
||||||
position: absolute;
|
|
||||||
top: 50%;
|
|
||||||
left: 0;
|
|
||||||
right: 0;
|
|
||||||
height: 5px;
|
|
||||||
transform: translateY(-50%);
|
|
||||||
border-radius: 999px;
|
|
||||||
background: linear-gradient(
|
|
||||||
to right,
|
|
||||||
var(--sg-border) 0%,
|
|
||||||
var(--sg-border) var(--range-start),
|
|
||||||
var(--accent) var(--range-start),
|
|
||||||
var(--accent) var(--range-end),
|
|
||||||
var(--sg-border) var(--range-end),
|
|
||||||
var(--sg-border) 100%
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
.range-input {
|
|
||||||
position: absolute;
|
|
||||||
inset: 0;
|
|
||||||
width: 100%;
|
|
||||||
height: 22px;
|
|
||||||
margin: 0;
|
|
||||||
appearance: none;
|
|
||||||
background: transparent;
|
|
||||||
pointer-events: none;
|
|
||||||
|
|
||||||
&::-webkit-slider-runnable-track,
|
|
||||||
&::-moz-range-track {
|
|
||||||
height: 5px;
|
|
||||||
background: transparent;
|
|
||||||
border: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
&::-webkit-slider-thumb {
|
|
||||||
appearance: none;
|
|
||||||
width: 15px;
|
|
||||||
height: 15px;
|
|
||||||
margin-top: -5px;
|
|
||||||
border: 2px solid var(--sg-surface);
|
|
||||||
border-radius: 50%;
|
|
||||||
background: var(--sg-blue-highlight);
|
|
||||||
box-shadow: var(--sg-shadow-sm);
|
|
||||||
cursor: pointer;
|
|
||||||
pointer-events: auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
&::-moz-range-thumb {
|
|
||||||
width: 15px;
|
|
||||||
height: 15px;
|
|
||||||
border: 2px solid var(--sg-surface);
|
|
||||||
border-radius: 50%;
|
|
||||||
background: var(--sg-blue-highlight);
|
|
||||||
box-shadow: var(--sg-shadow-sm);
|
|
||||||
cursor: pointer;
|
|
||||||
pointer-events: auto;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.range-input-start {
|
|
||||||
z-index: 2;
|
|
||||||
}
|
|
||||||
.range-input-end {
|
|
||||||
z-index: 3;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.state-message {
|
.state-message {
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import { IpcClassification } from '../../api';
|
|||||||
import { OpenAlexTopicTag } from '../../api/model/openAlexTopicTag';
|
import { OpenAlexTopicTag } from '../../api/model/openAlexTopicTag';
|
||||||
import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component';
|
import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component';
|
||||||
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
|
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
|
||||||
|
import { YearRangeSliderComponent } from '../../shared/ui/year-range-slider/year-range-slider.component';
|
||||||
import {
|
import {
|
||||||
classificationSectionColor,
|
classificationSectionColor,
|
||||||
topicHierarchyColor,
|
topicHierarchyColor,
|
||||||
@@ -54,6 +55,7 @@ const MIN_YEAR = 1978;
|
|||||||
MatDividerModule,
|
MatDividerModule,
|
||||||
TopicChipComponent,
|
TopicChipComponent,
|
||||||
LoadingComponent,
|
LoadingComponent,
|
||||||
|
YearRangeSliderComponent,
|
||||||
],
|
],
|
||||||
templateUrl: './patents.component.html',
|
templateUrl: './patents.component.html',
|
||||||
styleUrl: './patents.component.scss',
|
styleUrl: './patents.component.scss',
|
||||||
@@ -117,69 +119,7 @@ export class PatentsComponent implements OnInit {
|
|||||||
this.loadPatents();
|
this.loadPatents();
|
||||||
}
|
}
|
||||||
|
|
||||||
get rangeStartPercent(): string {
|
onYearRangeChange(): void {
|
||||||
const total = this.maxYear - this.minYear;
|
|
||||||
return `${((this.selectedStartYear - this.minYear) / total) * 100}%`;
|
|
||||||
}
|
|
||||||
|
|
||||||
get rangeEndPercent(): string {
|
|
||||||
const total = this.maxYear - this.minYear;
|
|
||||||
return `${((this.selectedEndYear - this.minYear) / total) * 100}%`;
|
|
||||||
}
|
|
||||||
|
|
||||||
get canResetYearRange(): boolean {
|
|
||||||
return (
|
|
||||||
this.selectedStartYear !== this.minYear ||
|
|
||||||
this.selectedEndYear !== this.maxYear
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fired continuously while dragging: only updates the displayed value/handle
|
|
||||||
// position, no HTTP request yet.
|
|
||||||
onStartYearDrag(event: Event): void {
|
|
||||||
const input = event.target as HTMLInputElement;
|
|
||||||
this.selectedStartYear = Math.min(
|
|
||||||
parseInt(input.value, 10),
|
|
||||||
this.selectedEndYear,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
onEndYearDrag(event: Event): void {
|
|
||||||
const input = event.target as HTMLInputElement;
|
|
||||||
this.selectedEndYear = Math.max(
|
|
||||||
parseInt(input.value, 10),
|
|
||||||
this.selectedStartYear,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fired once on release: commits the value and triggers the search request.
|
|
||||||
onStartYearInput(event: Event): void {
|
|
||||||
const input = event.target as HTMLInputElement;
|
|
||||||
this.selectedStartYear = Math.min(
|
|
||||||
parseInt(input.value, 10),
|
|
||||||
this.selectedEndYear,
|
|
||||||
);
|
|
||||||
input.value = String(this.selectedStartYear);
|
|
||||||
this.page = 0;
|
|
||||||
this.loadPatents();
|
|
||||||
this.updateQueryParams();
|
|
||||||
}
|
|
||||||
|
|
||||||
onEndYearInput(event: Event): void {
|
|
||||||
const input = event.target as HTMLInputElement;
|
|
||||||
this.selectedEndYear = Math.max(
|
|
||||||
parseInt(input.value, 10),
|
|
||||||
this.selectedStartYear,
|
|
||||||
);
|
|
||||||
input.value = String(this.selectedEndYear);
|
|
||||||
this.page = 0;
|
|
||||||
this.loadPatents();
|
|
||||||
this.updateQueryParams();
|
|
||||||
}
|
|
||||||
|
|
||||||
resetYearRange(): void {
|
|
||||||
this.selectedStartYear = this.minYear;
|
|
||||||
this.selectedEndYear = this.maxYear;
|
|
||||||
this.page = 0;
|
this.page = 0;
|
||||||
this.loadPatents();
|
this.loadPatents();
|
||||||
this.updateQueryParams();
|
this.updateQueryParams();
|
||||||
|
|||||||
@@ -40,19 +40,10 @@
|
|||||||
{{ hIndexString() }}
|
{{ hIndexString() }}
|
||||||
</p>
|
</p>
|
||||||
@if (!loading()) {
|
@if (!loading()) {
|
||||||
@if (careerStage(); as careerStage) {
|
<app-career-stage-chip
|
||||||
<div [skText]="loading()" class="career-stage-line">
|
[careerStage]="person().career_metrics?.career_stage"
|
||||||
<span class="career-stage-label">Career Stage:</span>
|
[activeYears]="person().career_metrics?.active_years"
|
||||||
<span
|
size="sm" />
|
||||||
class="career-stage-chip"
|
|
||||||
[matTooltip]="getCareerStageTooltip(careerStage)"
|
|
||||||
matTooltipPosition="right"
|
|
||||||
matTooltipClass="career-stage-tooltip"
|
|
||||||
[matTooltipShowDelay]="250">
|
|
||||||
{{ careerStage }}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
</a>
|
</a>
|
||||||
@@ -86,12 +77,11 @@
|
|||||||
>{{ inst.display_name ?? '' }}</span
|
>{{ inst.display_name ?? '' }}</span
|
||||||
>
|
>
|
||||||
@if (inst.country_code && !loading()) {
|
@if (inst.country_code && !loading()) {
|
||||||
<img
|
<app-country-flag
|
||||||
alt=""
|
[countryCode]="inst.country_code"
|
||||||
class="flag-img"
|
[height]="10"
|
||||||
[src]="`https://flagcdn.io/${inst.country_code.toLowerCase()}.svg`"
|
[bordered]="false"
|
||||||
height="10"
|
style="margin-left: 6px" />
|
||||||
style="margin-left: 6px; vertical-align: middle" />
|
|
||||||
<span
|
<span
|
||||||
class="country-code"
|
class="country-code"
|
||||||
style="font-size: 9px; margin-left: 2px; vertical-align: middle"
|
style="font-size: 9px; margin-left: 2px; vertical-align: middle"
|
||||||
@@ -116,6 +106,8 @@
|
|||||||
[skText]="loading()"
|
[skText]="loading()"
|
||||||
class="person-topic-chip"
|
class="person-topic-chip"
|
||||||
size="mini"
|
size="mini"
|
||||||
|
[topic]="topic"
|
||||||
|
[topicId]="topic.id"
|
||||||
[label]="topic.display_name || ''"
|
[label]="topic.display_name || ''"
|
||||||
[description]="topic.description"
|
[description]="topic.description"
|
||||||
[subfieldName]="topic.subfield?.display_name"
|
[subfieldName]="topic.subfield?.display_name"
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user