Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
This commit is contained in:
@@ -13,7 +13,6 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c
|
||||
"pytest~=8.1.0" \
|
||||
"httpx~=0.27.0" \
|
||||
"python-multipart~=0.0.19"\
|
||||
"elasticsearch~=9.4.0" \
|
||||
"beautifulsoup4==4.12.3" \
|
||||
"openai~=2.41.0"
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"cryptography~=42.0.0",
|
||||
"dotenv>=0.9.9",
|
||||
"elasticsearch~=9.4.0",
|
||||
"fastapi~=0.115.0",
|
||||
"httpx~=0.27.0",
|
||||
"openai~=2.41.0",
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY, HTTP_503_SERVICE_UNAVAILABLE
|
||||
|
||||
from . import model
|
||||
from .search_client import CompanyConnectionsSearchClient, MissingApiKeyError
|
||||
from inse.exceptions import MissingApiKeyError, ElasticsearchException, NotFoundException
|
||||
from .search_client import CompanyConnectionsSearchClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -23,22 +20,10 @@ async def get_company_connections_by_author_id(
|
||||
) -> model.CompanyConnectionsResponse:
|
||||
search_client = client or CompanyConnectionsSearchClient()
|
||||
|
||||
try:
|
||||
author_hit = await search_client.get_openalex_author(author_id)
|
||||
except MissingApiKeyError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Elasticsearch is not configured.",
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex author lookup failed for %s.", author_id)
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex author lookup failed.",
|
||||
) from exc
|
||||
author_hit = await search_client.get_openalex_author(author_id)
|
||||
|
||||
if author_hit is None:
|
||||
raise HTTPException(status_code=404, detail=f"Author {author_id} not found.")
|
||||
raise NotFoundException(f"Author {author_id} not found.")
|
||||
|
||||
source = author_hit.get("_source", {})
|
||||
display_name = _clean(source.get("display_name"))
|
||||
@@ -59,21 +44,9 @@ async def get_company_connections_by_author_id(
|
||||
connections=[],
|
||||
)
|
||||
|
||||
try:
|
||||
hr_response = await search_client.search_handelsregister_by_officer_name(
|
||||
display_name
|
||||
)
|
||||
except MissingApiKeyError as exc:
|
||||
raise HTTPException(
|
||||
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Elasticsearch is not configured.",
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("Handelsregister lookup failed for %s.", display_name)
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="Handelsregister lookup failed.",
|
||||
) from exc
|
||||
hr_response = await search_client.search_handelsregister_by_officer_name(
|
||||
display_name
|
||||
)
|
||||
|
||||
company_count, company_count_relation = _parse_total(hr_response)
|
||||
connections = _parse_company_connections(
|
||||
|
||||
@@ -5,8 +5,12 @@ import httpx
|
||||
from .. import config
|
||||
|
||||
|
||||
class MissingApiKeyError(Exception):
|
||||
pass
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster
|
||||
from inse.exceptions import ElasticsearchNotFoundException
|
||||
|
||||
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
|
||||
|
||||
class CompanyConnectionsSearchClient:
|
||||
@@ -28,7 +32,7 @@ class CompanyConnectionsSearchClient:
|
||||
api_key
|
||||
if api_key is not None
|
||||
else config.settings.elasticsearch_api_key
|
||||
)
|
||||
)
|
||||
self.openalex_index = openalex_index
|
||||
self.handelsregister_index = handelsregister_index
|
||||
self.timeout = timeout
|
||||
@@ -39,26 +43,15 @@ class CompanyConnectionsSearchClient:
|
||||
return author_id.strip().removeprefix("https://openalex.org/")
|
||||
|
||||
async def get_openalex_author(self, author_id: str) -> dict[str, Any] | None:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("Elasticsearch API key is not configured.")
|
||||
|
||||
doc_id = self.openalex_doc_id(author_id)
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.get(
|
||||
f"/{self.openalex_index}/_doc/{doc_id}",
|
||||
headers={"Authorization": f"ApiKey {self.api_key}"},
|
||||
try:
|
||||
return await elasticsearch.get(
|
||||
index=self.openalex_index,
|
||||
doc_id=doc_id,
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
|
||||
if response.status_code == 404:
|
||||
return None
|
||||
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except ElasticsearchNotFoundException:
|
||||
return None
|
||||
|
||||
async def search_handelsregister_by_officer_name(
|
||||
self,
|
||||
@@ -66,27 +59,16 @@ class CompanyConnectionsSearchClient:
|
||||
size: int = 10000,
|
||||
track_total_hits: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("Elasticsearch API key is not configured.")
|
||||
|
||||
payload = self.handelsregister_officer_name_query(
|
||||
officer_name=officer_name,
|
||||
size=size,
|
||||
track_total_hits=track_total_hits,
|
||||
)
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"/{self.handelsregister_index}/_search",
|
||||
headers={"Authorization": f"ApiKey {self.api_key}"},
|
||||
json=payload,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
return await elasticsearch.search(
|
||||
index=self.handelsregister_index,
|
||||
body=payload,
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def handelsregister_officer_name_query(
|
||||
|
||||
@@ -1,3 +1,36 @@
|
||||
class NotFoundException(Exception):
|
||||
def __init__(self, message: str):
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class ElasticsearchException(Exception):
|
||||
"""Base exception for all Elasticsearch integrations."""
|
||||
pass
|
||||
|
||||
|
||||
class ElasticsearchNotFoundException(NotFoundException, ElasticsearchException):
|
||||
"""Raised when an Elasticsearch document or index is not found."""
|
||||
pass
|
||||
|
||||
|
||||
class ElasticsearchConnectionException(ElasticsearchException):
|
||||
"""Raised when connecting to Elasticsearch fails."""
|
||||
pass
|
||||
|
||||
|
||||
class MissingApiKeyError(Exception):
|
||||
"""Raised when a required API key is missing."""
|
||||
pass
|
||||
|
||||
|
||||
class UpstreamAPIException(Exception):
|
||||
"""Raised when an upstream third-party service (e.g. REST API) fails."""
|
||||
def __init__(self, message: str, status_code: int = 502):
|
||||
self.message = message
|
||||
self.status_code = status_code
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class BadRequestException(Exception):
|
||||
"""Raised when request parameters are invalid or validation fails."""
|
||||
pass
|
||||
|
||||
@@ -8,10 +8,11 @@ from typing import Any
|
||||
import httpx
|
||||
|
||||
from .. import config
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster
|
||||
|
||||
|
||||
class MissingApiKeyError(Exception):
|
||||
pass
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
|
||||
|
||||
class FundedPublicationsSearchClient:
|
||||
@@ -177,15 +178,8 @@ class FundedPublicationsSearchClient:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"/{self.index}/_search",
|
||||
headers={"Authorization": f"ApiKey {self.api_key}"},
|
||||
json=payload,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
return await elasticsearch.search(
|
||||
index=self.index,
|
||||
body=payload,
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
|
||||
@@ -6,16 +6,11 @@
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from pydantic import ValidationError
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
|
||||
|
||||
from ..persons import logic as person_logic
|
||||
from . import model
|
||||
from .elastic_search_client import FundedPublicationsSearchClient
|
||||
from .elastic_search_client import MissingApiKeyError
|
||||
from inse.exceptions import MissingApiKeyError, ElasticsearchException, UpstreamAPIException
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -62,7 +57,7 @@ async def get_funders_by_author_id(
|
||||
funder_counts: dict[str, dict[str, Any]] = {}
|
||||
|
||||
normalized_author_id = FundedPublicationsSearchClient.indexed_author_id(author_id)
|
||||
author_name = _get_author_name(author_id)
|
||||
author_name = await _get_author_name(author_id)
|
||||
|
||||
try:
|
||||
_, all_hits = await _fetch_all_author_work_hits(
|
||||
@@ -92,9 +87,9 @@ async def get_funders_by_author_id(
|
||||
)
|
||||
except ValidationError as exc:
|
||||
logger.exception("Funders response could not be validated for author %s.", author_id)
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="Funders response could not be parsed.",
|
||||
raise UpstreamAPIException(
|
||||
message="Funders response could not be parsed.",
|
||||
status_code=502,
|
||||
) from exc
|
||||
|
||||
|
||||
@@ -144,26 +139,13 @@ async def _search_funded_publications(
|
||||
*,
|
||||
funded_only: bool = False,
|
||||
) -> dict:
|
||||
try:
|
||||
payload = search_client.publications_by_author_query(
|
||||
author_id,
|
||||
page,
|
||||
page_size,
|
||||
funded_only=funded_only,
|
||||
)
|
||||
return await search_client.search(payload)
|
||||
except MissingApiKeyError as exc:
|
||||
logger.error("OpenAlex works Elasticsearch API key is not configured.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="OpenAlex works search is not configured.",
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex works search request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex works search request failed.",
|
||||
) from exc
|
||||
payload = search_client.publications_by_author_query(
|
||||
author_id,
|
||||
page,
|
||||
page_size,
|
||||
funded_only=funded_only,
|
||||
)
|
||||
return await search_client.search(payload)
|
||||
|
||||
|
||||
def _parse_publication_search_response(data: dict) -> tuple[int, list[dict]]:
|
||||
@@ -180,9 +162,9 @@ def _parse_publication_search_response(data: dict) -> tuple[int, list[dict]]:
|
||||
return total, results
|
||||
|
||||
|
||||
def _get_author_name(author_id: str) -> str | None:
|
||||
async def _get_author_name(author_id: str) -> str | None:
|
||||
short_author_id = author_id.replace("https://openalex.org/", "")
|
||||
search_result = person_logic.search_persons(author_id=short_author_id)
|
||||
search_result = await person_logic.search_persons(author_id=short_author_id)
|
||||
|
||||
if not search_result.results:
|
||||
return None
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from unittest.mock import AsyncMock, patch
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
|
||||
from inse.funders import logic
|
||||
from inse.funders.elastic_search_client import FundedPublicationsSearchClient
|
||||
@@ -68,201 +66,177 @@ def _funded_publication_hit(
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_funders_by_author_id_aggregates_funders_and_awards(monkeypatch):
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
payload = json.loads(request.content.decode("utf-8"))
|
||||
assert payload["from"] == 0
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"hits": {
|
||||
"total": {"value": 2},
|
||||
"hits": [
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W1",
|
||||
funder_id="https://openalex.org/F123",
|
||||
funder_name="Funder A",
|
||||
author_position="first",
|
||||
pdf_url="https://example.org/w1.pdf",
|
||||
abstract_inverted_index={
|
||||
"This": [0],
|
||||
"is": [1],
|
||||
"an": [2],
|
||||
"abstract.": [3],
|
||||
async def test_get_funders_by_author_id_aggregates_funders_and_awards():
|
||||
mock_es_response = {
|
||||
"hits": {
|
||||
"total": {"value": 2},
|
||||
"hits": [
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W1",
|
||||
funder_id="https://openalex.org/F123",
|
||||
funder_name="Funder A",
|
||||
author_position="first",
|
||||
pdf_url="https://example.org/w1.pdf",
|
||||
abstract_inverted_index={
|
||||
"This": [0],
|
||||
"is": [1],
|
||||
"an": [2],
|
||||
"abstract.": [3],
|
||||
},
|
||||
extra_source={
|
||||
"title": "Example publication: full detail",
|
||||
"funders": [
|
||||
{
|
||||
"id": "https://openalex.org/F456",
|
||||
"display_name": "Funder B",
|
||||
}
|
||||
],
|
||||
"publication_year": 2020,
|
||||
"publication_date": "2020-05-10",
|
||||
"type": "article",
|
||||
"language": "en",
|
||||
"cited_by_count": 12,
|
||||
"is_retracted": False,
|
||||
"primary_location": {
|
||||
"pdf_url": "https://example.org/w1.pdf",
|
||||
"is_oa": True,
|
||||
"license": "cc-by",
|
||||
"source": {
|
||||
"display_name": "Example Journal",
|
||||
"type": "journal",
|
||||
},
|
||||
extra_source={
|
||||
"title": "Example publication: full detail",
|
||||
"funders": [
|
||||
{
|
||||
"id": "https://openalex.org/F456",
|
||||
"display_name": "Funder B",
|
||||
}
|
||||
],
|
||||
"publication_year": 2020,
|
||||
"publication_date": "2020-05-10",
|
||||
"type": "article",
|
||||
"language": "en",
|
||||
"cited_by_count": 12,
|
||||
"is_retracted": False,
|
||||
"primary_location": {
|
||||
"pdf_url": "https://example.org/w1.pdf",
|
||||
"is_oa": True,
|
||||
"license": "cc-by",
|
||||
"source": {
|
||||
"display_name": "Example Journal",
|
||||
"type": "journal",
|
||||
},
|
||||
},
|
||||
"open_access": {
|
||||
"is_oa": True,
|
||||
"oa_status": "gold",
|
||||
"any_repository_has_fulltext": True,
|
||||
},
|
||||
"primary_topic": {
|
||||
"display_name": "Clinical Trials",
|
||||
"subfield": {"display_name": "Medicine"},
|
||||
"field": {"display_name": "Health Sciences"},
|
||||
"domain": {"display_name": "Life Sciences"},
|
||||
},
|
||||
"topics": [
|
||||
{"display_name": "Trials", "score": 0.8},
|
||||
{"display_name": "Guidelines", "score": 0.6},
|
||||
],
|
||||
"keywords": [
|
||||
{"display_name": "randomised trials", "score": 0.9},
|
||||
{"display_name": "reporting guideline", "score": 0.7},
|
||||
],
|
||||
"counts_by_year": [
|
||||
{"year": 2024, "cited_by_count": 3},
|
||||
{"year": 2023, "cited_by_count": 2},
|
||||
],
|
||||
},
|
||||
),
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W2",
|
||||
funder_id=None,
|
||||
funder_name=None,
|
||||
award_funder_id="https://openalex.org/F123",
|
||||
award_funder_name="Funder A",
|
||||
award_display_name="Project Grant",
|
||||
award_number="PG-42",
|
||||
author_position="last",
|
||||
),
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
},
|
||||
"open_access": {
|
||||
"is_oa": True,
|
||||
"oa_status": "gold",
|
||||
"any_repository_has_fulltext": True,
|
||||
},
|
||||
"primary_topic": {
|
||||
"display_name": "Clinical Trials",
|
||||
"subfield": {"display_name": "Medicine"},
|
||||
"field": {"display_name": "Health Sciences"},
|
||||
"domain": {"display_name": "Life Sciences"},
|
||||
},
|
||||
"topics": [
|
||||
{"display_name": "Trials", "score": 0.8},
|
||||
{"display_name": "Guidelines", "score": 0.6},
|
||||
],
|
||||
"keywords": [
|
||||
{"display_name": "randomised trials", "score": 0.9},
|
||||
{"display_name": "reporting guideline", "score": 0.7},
|
||||
],
|
||||
"counts_by_year": [
|
||||
{"year": 2024, "cited_by_count": 3},
|
||||
{"year": 2023, "cited_by_count": 2},
|
||||
],
|
||||
},
|
||||
),
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W2",
|
||||
funder_id=None,
|
||||
funder_name=None,
|
||||
award_funder_id="https://openalex.org/F123",
|
||||
award_funder_name="Funder A",
|
||||
award_display_name="Project Grant",
|
||||
award_number="PG-42",
|
||||
author_position="last",
|
||||
),
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
logic.person_logic,
|
||||
"search_persons",
|
||||
lambda author_id: type(
|
||||
"Result",
|
||||
(),
|
||||
{"results": [type("Author", (), {"display_name": "Example Author"})()]},
|
||||
)(),
|
||||
)
|
||||
mock_author_result = type(
|
||||
"Result",
|
||||
(),
|
||||
{"results": [type("Author", (), {"display_name": "Example Author"})()]}
|
||||
)()
|
||||
|
||||
client = FundedPublicationsSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \
|
||||
patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons:
|
||||
mock_search.return_value = mock_es_response
|
||||
mock_search_persons.return_value = mock_author_result
|
||||
|
||||
response = await logic.get_funders_by_author_id("A5023888391", client=client)
|
||||
client = FundedPublicationsSearchClient(api_key="test-key")
|
||||
response = await logic.get_funders_by_author_id("A5023888391", client=client)
|
||||
|
||||
assert response.author_id == "https://openalex.org/A5023888391"
|
||||
assert response.author_name == "Example Author"
|
||||
assert response.funder_count == 2
|
||||
assert response.funders[0].funder_id == "https://openalex.org/F123"
|
||||
assert response.funders[0].funder_name == "Funder A"
|
||||
assert response.funders[0].publication_count == 2
|
||||
assert response.funders[0].author_position_count.first == 1
|
||||
assert response.funders[0].author_position_count.last == 1
|
||||
assert response.funders[0].publication_ids.first == ["https://openalex.org/W1"]
|
||||
assert response.funders[0].publication_ids.last == ["https://openalex.org/W2"]
|
||||
assert response.funders[0].publication_urls["https://openalex.org/W1"] == "https://example.org/w1.pdf"
|
||||
assert response.funders[0].publication_urls["https://openalex.org/W2"] == "https://openalex.org/W2"
|
||||
publication_detail = response.funders[0].publication_details["https://openalex.org/W1"]
|
||||
assert publication_detail.title == "Example publication: full detail"
|
||||
assert publication_detail.funder_names == ["Funder A", "Funder B"]
|
||||
assert publication_detail.abstract == "This is an abstract."
|
||||
assert publication_detail.publication_date == "2020-05-10"
|
||||
assert publication_detail.publication_type == "article"
|
||||
assert publication_detail.source_name == "Example Journal"
|
||||
assert publication_detail.source_type == "journal"
|
||||
assert publication_detail.is_open_access is True
|
||||
assert publication_detail.open_access_status == "gold"
|
||||
assert publication_detail.has_fulltext is True
|
||||
assert publication_detail.license == "cc-by"
|
||||
assert publication_detail.cited_by_count == 12
|
||||
assert publication_detail.primary_topic == "Clinical Trials"
|
||||
assert publication_detail.topic_field == "Health Sciences"
|
||||
assert publication_detail.topic_subfield == "Medicine"
|
||||
assert publication_detail.topic_domain == "Life Sciences"
|
||||
assert publication_detail.topics == ["Trials", "Guidelines"]
|
||||
assert publication_detail.keywords == ["randomised trials", "reporting guideline"]
|
||||
assert publication_detail.counts_by_year == [
|
||||
{"year": 2024, "cited_by_count": 3},
|
||||
{"year": 2023, "cited_by_count": 2},
|
||||
]
|
||||
assert response.funders[0].publication_details["https://openalex.org/W2"].grant_labels == [
|
||||
"Project Grant"
|
||||
]
|
||||
assert response.author_id == "https://openalex.org/A5023888391"
|
||||
assert response.author_name == "Example Author"
|
||||
assert response.funder_count == 2
|
||||
|
||||
funder_a = next(f for f in response.funders if f.funder_id == "https://openalex.org/F123")
|
||||
assert funder_a.funder_name == "Funder A"
|
||||
assert funder_a.publication_count == 2
|
||||
assert funder_a.author_position_count.first == 1
|
||||
assert funder_a.author_position_count.last == 1
|
||||
assert funder_a.publication_ids.first == ["https://openalex.org/W1"]
|
||||
assert funder_a.publication_ids.last == ["https://openalex.org/W2"]
|
||||
assert funder_a.publication_urls["https://openalex.org/W1"] == "https://example.org/w1.pdf"
|
||||
assert funder_a.publication_urls["https://openalex.org/W2"] == "https://openalex.org/W2"
|
||||
|
||||
pub1_detail = funder_a.publication_details["https://openalex.org/W1"]
|
||||
assert pub1_detail.title == "Example publication: full detail"
|
||||
assert pub1_detail.funder_names == ["Funder A", "Funder B"]
|
||||
assert pub1_detail.abstract == "This is an abstract."
|
||||
assert pub1_detail.publication_date == "2020-05-10"
|
||||
assert pub1_detail.publication_type == "article"
|
||||
assert pub1_detail.source_name == "Example Journal"
|
||||
assert pub1_detail.source_type == "journal"
|
||||
assert pub1_detail.is_open_access is True
|
||||
assert pub1_detail.open_access_status == "gold"
|
||||
assert pub1_detail.has_fulltext is True
|
||||
assert pub1_detail.license == "cc-by"
|
||||
assert pub1_detail.cited_by_count == 12
|
||||
assert pub1_detail.primary_topic == "Clinical Trials"
|
||||
assert pub1_detail.topic_field == "Health Sciences"
|
||||
assert pub1_detail.topic_subfield == "Medicine"
|
||||
assert pub1_detail.topic_domain == "Life Sciences"
|
||||
assert pub1_detail.topics == ["Trials", "Guidelines"]
|
||||
assert pub1_detail.keywords == ["randomised trials", "reporting guideline"]
|
||||
assert pub1_detail.counts_by_year == [
|
||||
{"year": 2024, "cited_by_count": 3},
|
||||
{"year": 2023, "cited_by_count": 2},
|
||||
]
|
||||
assert funder_a.publication_details["https://openalex.org/W2"].grant_labels == ["Project Grant"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_publication_grant_labels_ignore_funder_award_id_without_display_name(monkeypatch):
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"hits": {
|
||||
"total": {"value": 1},
|
||||
"hits": [
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W3",
|
||||
funder_id="https://openalex.org/F123",
|
||||
funder_name="Funder A",
|
||||
award_funder_id="https://openalex.org/F123",
|
||||
award_funder_name="Funder A",
|
||||
award_display_name=None,
|
||||
award_number="ANR-12-1234",
|
||||
),
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
async def test_publication_grant_labels_ignore_funder_award_id_without_display_name():
|
||||
mock_es_response = {
|
||||
"hits": {
|
||||
"total": {"value": 1},
|
||||
"hits": [
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W3",
|
||||
funder_id="https://openalex.org/F123",
|
||||
funder_name="Funder A",
|
||||
award_funder_id="https://openalex.org/F123",
|
||||
award_funder_name="Funder A",
|
||||
award_display_name=None,
|
||||
award_number="ANR-12-1234",
|
||||
),
|
||||
],
|
||||
},
|
||||
}
|
||||
mock_author_result = type("Result", (), {"results": [type("Author", (), {"display_name": "Example Author"})()]})()
|
||||
|
||||
monkeypatch.setattr(
|
||||
logic.person_logic,
|
||||
"search_persons",
|
||||
lambda author_id: type(
|
||||
"Result",
|
||||
(),
|
||||
{"results": [type("Author", (), {"display_name": "Example Author"})()]},
|
||||
)(),
|
||||
)
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \
|
||||
patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons:
|
||||
mock_search.return_value = mock_es_response
|
||||
mock_search_persons.return_value = mock_author_result
|
||||
|
||||
client = FundedPublicationsSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
client = FundedPublicationsSearchClient(api_key="test-key")
|
||||
response = await logic.get_funders_by_author_id("A5023888391", client=client)
|
||||
|
||||
response = await logic.get_funders_by_author_id("A5023888391", client=client)
|
||||
|
||||
assert response.funders[0].publication_details["https://openalex.org/W3"].grant_labels == []
|
||||
assert response.funders[0].publication_details["https://openalex.org/W3"].grant_labels == []
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded(monkeypatch):
|
||||
async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded():
|
||||
requested_pages: list[int] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
payload = json.loads(request.content.decode("utf-8"))
|
||||
size = payload["size"]
|
||||
offset = payload["from"]
|
||||
async def mock_search_func(index, body, cluster=None):
|
||||
size = body["size"]
|
||||
offset = body["from"]
|
||||
page = offset // size + 1
|
||||
requested_pages.append(page)
|
||||
total = size + 1
|
||||
@@ -284,115 +258,87 @@ async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded(m
|
||||
)
|
||||
]
|
||||
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"hits": {
|
||||
"total": {"value": total},
|
||||
"hits": hits,
|
||||
},
|
||||
return {
|
||||
"hits": {
|
||||
"total": {"value": total},
|
||||
"hits": hits,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
logic.person_logic,
|
||||
"search_persons",
|
||||
lambda author_id: type("Result", (), {"results": []})(),
|
||||
)
|
||||
mock_author_result = type("Result", (), {"results": []})()
|
||||
|
||||
client = FundedPublicationsSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
with patch("inse.integrations.elasticsearch.search", side_effect=mock_search_func) as mock_search, \
|
||||
patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons:
|
||||
mock_search_persons.return_value = mock_author_result
|
||||
|
||||
response = await logic.get_funders_by_author_id("A5023888391", client=client)
|
||||
client = FundedPublicationsSearchClient(api_key="test-key")
|
||||
response = await logic.get_funders_by_author_id("A5023888391", client=client)
|
||||
|
||||
assert requested_pages == [1, 2]
|
||||
assert response.funder_count > 1
|
||||
funder_names = {funder.funder_name for funder in response.funders}
|
||||
assert "Funder 1" in funder_names
|
||||
assert requested_pages == [1, 2]
|
||||
assert response.funder_count > 1
|
||||
funder_names = {funder.funder_name for funder in response.funders}
|
||||
assert "Funder 1" in funder_names
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_funders_by_author_id_ignores_publications_without_funders(monkeypatch):
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"hits": {
|
||||
"total": {"value": 2},
|
||||
"hits": [
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W1",
|
||||
funder_id="https://openalex.org/F123",
|
||||
funder_name="Bundesministerium",
|
||||
),
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W2",
|
||||
funder_id=None,
|
||||
funder_name=None,
|
||||
),
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
async def test_get_funders_by_author_id_ignores_publications_without_funders():
|
||||
mock_es_response = {
|
||||
"hits": {
|
||||
"total": {"value": 2},
|
||||
"hits": [
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W1",
|
||||
funder_id="https://openalex.org/F123",
|
||||
funder_name="Bundesministerium",
|
||||
),
|
||||
_funded_publication_hit(
|
||||
"https://openalex.org/W2",
|
||||
funder_id=None,
|
||||
funder_name=None,
|
||||
),
|
||||
],
|
||||
},
|
||||
}
|
||||
mock_author_result = type("Result", (), {"results": []})()
|
||||
|
||||
monkeypatch.setattr(
|
||||
logic.person_logic,
|
||||
"search_persons",
|
||||
lambda author_id: type("Result", (), {"results": []})(),
|
||||
)
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \
|
||||
patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons:
|
||||
mock_search.return_value = mock_es_response
|
||||
mock_search_persons.return_value = mock_author_result
|
||||
|
||||
client = FundedPublicationsSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
client = FundedPublicationsSearchClient(api_key="test-key")
|
||||
response = await logic.get_funders_by_author_id("A5093075883", client=client)
|
||||
|
||||
response = await logic.get_funders_by_author_id("A5093075883", client=client)
|
||||
|
||||
assert response.funder_count == 1
|
||||
assert response.funders[0].funder_name == "Bundesministerium"
|
||||
assert response.funders[0].publication_count == 1
|
||||
assert response.funder_count == 1
|
||||
assert response.funders[0].funder_name == "Bundesministerium"
|
||||
assert response.funders[0].publication_count == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_funders_by_author_id_returns_empty_when_elasticsearch_has_no_funders(monkeypatch):
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"hits": {"total": {"value": 0}, "hits": []}},
|
||||
)
|
||||
async def test_get_funders_by_author_id_returns_empty_when_elasticsearch_has_no_funders():
|
||||
mock_es_response = {"hits": {"total": {"value": 0}, "hits": []}}
|
||||
mock_author_result = type("Result", (), {"results": []})()
|
||||
|
||||
monkeypatch.setattr(
|
||||
logic.person_logic,
|
||||
"search_persons",
|
||||
lambda author_id: type("Result", (), {"results": []})(),
|
||||
)
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search, \
|
||||
patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons:
|
||||
mock_search.return_value = mock_es_response
|
||||
mock_search_persons.return_value = mock_author_result
|
||||
|
||||
client = FundedPublicationsSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
client = FundedPublicationsSearchClient(api_key="test-key")
|
||||
response = await logic.get_funders_by_author_id("A5093075883", client=client)
|
||||
|
||||
response = await logic.get_funders_by_author_id("A5093075883", client=client)
|
||||
|
||||
assert response.funder_count == 0
|
||||
assert response.funders == []
|
||||
assert response.funder_count == 0
|
||||
assert response.funders == []
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_funders_by_author_id_maps_missing_api_key_to_service_unavailable(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
logic.person_logic,
|
||||
"search_persons",
|
||||
lambda author_id: type("Result", (), {"results": []})(),
|
||||
)
|
||||
client = FundedPublicationsSearchClient(api_key="")
|
||||
async def test_get_funders_by_author_id_maps_missing_api_key_to_service_unavailable():
|
||||
mock_author_result = type("Result", (), {"results": []})()
|
||||
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
await logic.get_funders_by_author_id("A5023888391", client=client)
|
||||
with patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons:
|
||||
mock_search_persons.return_value = mock_author_result
|
||||
|
||||
assert exc.value.status_code == 503
|
||||
client = FundedPublicationsSearchClient(api_key="")
|
||||
|
||||
with pytest.raises(MissingApiKeyError):
|
||||
await logic.get_funders_by_author_id("A5023888391", client=client)
|
||||
|
||||
@@ -20,7 +20,7 @@ class InstitutionsSearchClient:
|
||||
"""
|
||||
pass
|
||||
|
||||
def get_institution_by_id(self, raw_oa_institution_id: str) -> Institution:
|
||||
async def get_institution_by_id(self, raw_oa_institution_id: str) -> Institution:
|
||||
"""Retrieves an institution by its raw OpenAlex institution ID.
|
||||
|
||||
Args:
|
||||
@@ -38,7 +38,7 @@ class InstitutionsSearchClient:
|
||||
}
|
||||
}
|
||||
|
||||
res = elasticsearch.search(index="openalex-institutions", query=query, size=1)
|
||||
res = await elasticsearch.search(index="openalex-institutions", query=query, size=1)
|
||||
|
||||
hits = res.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
@@ -72,7 +72,7 @@ class InstitutionsSearchClient:
|
||||
# TODO: Implement actual retrieval of RCN from Elasticsearch or another source instead of using a hardcoded cache.
|
||||
return cache.get(raw_institution_id)
|
||||
|
||||
def get_institutions_by_name(
|
||||
async def get_institutions_by_name(
|
||||
self,
|
||||
name: str,
|
||||
page: int = 0,
|
||||
@@ -122,7 +122,7 @@ class InstitutionsSearchClient:
|
||||
query,
|
||||
)
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="openalex-institutions",
|
||||
offset=page * size,
|
||||
size=size,
|
||||
@@ -189,7 +189,7 @@ class InstitutionsSearchClient:
|
||||
query,
|
||||
)
|
||||
|
||||
res = elasticsearch.search(index="openalex-authors", query=query)
|
||||
res = await elasticsearch.search(index="openalex-authors", query=query)
|
||||
hits = res.get("hits", {}).get("hits", [])
|
||||
|
||||
# Extracting display_name directly from the author document source
|
||||
@@ -200,7 +200,7 @@ class InstitutionsSearchClient:
|
||||
}
|
||||
return list(authors)
|
||||
|
||||
def search_institutions(
|
||||
async def search_institutions(
|
||||
self,
|
||||
query_text: str,
|
||||
country_code: str | None = None,
|
||||
@@ -265,7 +265,7 @@ class InstitutionsSearchClient:
|
||||
}
|
||||
}
|
||||
|
||||
res = elasticsearch.search(
|
||||
res = await elasticsearch.search(
|
||||
index="openalex-institutions",
|
||||
query=query,
|
||||
size=limit,
|
||||
@@ -288,7 +288,7 @@ class InstitutionsSearchClient:
|
||||
|
||||
return [Institution.from_dict(hit["_source"]) for hit in hits]
|
||||
|
||||
def get_institution_aliases_by_oa_institution_id(
|
||||
async def get_institution_aliases_by_oa_institution_id(
|
||||
self, raw_oa_institution_id: str
|
||||
) -> List[str]:
|
||||
"""Get a list of institution aliases for a given institution ID, including both display name alternatives and predefined aliases.
|
||||
@@ -299,7 +299,7 @@ class InstitutionsSearchClient:
|
||||
Returns:
|
||||
List[str]: A list of aliases for the given institution ID.
|
||||
"""
|
||||
institution = self.get_institution_by_id(raw_oa_institution_id)
|
||||
institution = await self.get_institution_by_id(raw_oa_institution_id)
|
||||
aliases = list(
|
||||
self.augment_aliases(set(institution.display_name_alternatives or []))
|
||||
| self.get_predefined_institution_aliases(raw_oa_institution_id)
|
||||
@@ -426,7 +426,7 @@ class InstitutionsSearchClient:
|
||||
)
|
||||
return None
|
||||
|
||||
def get_cordis_eu_organisation_ids_by_oa_institution_id(
|
||||
async def get_cordis_eu_organisation_ids_by_oa_institution_id(
|
||||
self, raw_oa_institution_id: str
|
||||
) -> Optional[List[str]]:
|
||||
"""Retrieves the corresponding EU organisation IDs for a given OpenAlex institution ID by searching for institution aliases and matching them against the Cordis EU organisations indices.
|
||||
@@ -439,7 +439,7 @@ class InstitutionsSearchClient:
|
||||
"""
|
||||
|
||||
institution_aliases = set(
|
||||
self.get_institution_aliases_by_oa_institution_id(
|
||||
await self.get_institution_aliases_by_oa_institution_id(
|
||||
raw_oa_institution_id=raw_oa_institution_id
|
||||
)
|
||||
)
|
||||
@@ -476,7 +476,7 @@ class InstitutionsSearchClient:
|
||||
|
||||
try:
|
||||
# IMPORTANT: The indices are named organizations and not organisations. + 15 Minutes debugging why the search returns 0 results
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="cordis_eu_*_organizations", body=body, cluster="inse"
|
||||
)
|
||||
except Exception as e:
|
||||
|
||||
@@ -9,10 +9,8 @@ from copy import deepcopy
|
||||
from typing import Any, Optional
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from pydantic import ValidationError
|
||||
from starlette.status import HTTP_400_BAD_REQUEST
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||
from inse.exceptions import UpstreamAPIException, BadRequestException
|
||||
|
||||
from inse.models.openalex.autocomplete_response import AutocompleteResponse
|
||||
from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta
|
||||
@@ -41,7 +39,7 @@ _VALID_INSTITUTION_TYPES = {
|
||||
async def get_institution_by_id(
|
||||
raw_institution_id: str, client: InstitutionsSearchClient
|
||||
) -> Institution:
|
||||
return client.get_institution_by_id(raw_institution_id)
|
||||
return await client.get_institution_by_id(raw_institution_id)
|
||||
|
||||
|
||||
async def list_institutions(
|
||||
@@ -58,10 +56,7 @@ async def list_institutions(
|
||||
client: OpenAlexInstitutionsClient | None = None,
|
||||
) -> InstitutionsListResponse:
|
||||
if sample is not None and (sort or page not in (None, 1)):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST,
|
||||
detail="sample cannot be combined with sort or page.",
|
||||
)
|
||||
raise BadRequestException("sample cannot be combined with sort or page.")
|
||||
|
||||
openalex_client = client or OpenAlexInstitutionsClient()
|
||||
|
||||
@@ -86,12 +81,12 @@ async def list_institutions(
|
||||
except ValueError:
|
||||
if exc.response.text:
|
||||
detail = exc.response.text
|
||||
raise HTTPException(status_code=status_code, detail=detail) from exc
|
||||
raise UpstreamAPIException(message=detail, status_code=status_code) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex institutions request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex institutions request failed.",
|
||||
raise UpstreamAPIException(
|
||||
message="OpenAlex institutions request failed.",
|
||||
status_code=502,
|
||||
) from exc
|
||||
|
||||
try:
|
||||
@@ -102,9 +97,9 @@ async def list_institutions(
|
||||
)
|
||||
except ValidationError as exc:
|
||||
logger.exception("OpenAlex institutions response could not be parsed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex institutions response could not be parsed.",
|
||||
raise UpstreamAPIException(
|
||||
message="OpenAlex institutions response could not be parsed.",
|
||||
status_code=502,
|
||||
) from exc
|
||||
|
||||
|
||||
@@ -120,7 +115,7 @@ async def autocomplete_institutions(
|
||||
Returns institution options for autocomplete inputs using the local
|
||||
Elasticsearch cluster via the provided client.
|
||||
"""
|
||||
institutions = client.search_institutions(
|
||||
institutions = await client.search_institutions(
|
||||
query_text=query,
|
||||
country_code=country_code,
|
||||
institution_type=institution_type,
|
||||
|
||||
@@ -72,7 +72,7 @@ async def search_institutions_by_name(
|
||||
),
|
||||
] = "asc",
|
||||
) -> InstitutionPage:
|
||||
return client.get_institutions_by_name(
|
||||
return await client.get_institutions_by_name(
|
||||
name=name,
|
||||
page=page,
|
||||
size=size,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from inse.exceptions import BadRequestException
|
||||
|
||||
from inse.institutions import logic
|
||||
from inse.institutions.search_client import OpenAlexInstitutionsClient
|
||||
@@ -96,11 +96,9 @@ async def test_list_institutions_maps_openalex_response_to_model():
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_institutions_rejects_sample_with_sort():
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
with pytest.raises(BadRequestException) as exc_info:
|
||||
await logic.list_institutions(sample=10, sort="works_count:desc")
|
||||
|
||||
assert exc_info.value.status_code == 400
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_institutions_accepts_practical_openalex_type_variants():
|
||||
|
||||
@@ -1,13 +1,37 @@
|
||||
import json
|
||||
import logging
|
||||
from typing import Any, Dict, Iterator, List, Optional, Tuple
|
||||
from typing import Any, Dict, AsyncIterator, List, Optional, Tuple
|
||||
|
||||
import httpx
|
||||
|
||||
from inse.exceptions import (
|
||||
ElasticsearchException,
|
||||
ElasticsearchNotFoundException,
|
||||
ElasticsearchConnectionException,
|
||||
MissingApiKeyError,
|
||||
)
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from .. import config
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_client: Optional[httpx.AsyncClient] = None
|
||||
_loop = None
|
||||
|
||||
|
||||
def get_client() -> httpx.AsyncClient:
|
||||
global _client, _loop
|
||||
try:
|
||||
import asyncio
|
||||
current_loop = asyncio.get_running_loop()
|
||||
except RuntimeError:
|
||||
current_loop = None
|
||||
|
||||
if _client is None or _loop is not current_loop:
|
||||
_client = httpx.AsyncClient(timeout=httpx.Timeout(30.0))
|
||||
_loop = current_loop
|
||||
return _client
|
||||
|
||||
|
||||
def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
|
||||
"""Retrieves the Elasticsearch URL and API key for the specified cluster from the configuration.
|
||||
@@ -21,22 +45,23 @@ def _cluster_credentials(cluster: ESCluster) -> Tuple[str, str]:
|
||||
Returns:
|
||||
Tuple[str, str]: The Elasticsearch URL and API key for the specified cluster.
|
||||
"""
|
||||
|
||||
|
||||
if cluster == ESCluster.NES:
|
||||
if (
|
||||
not config.settings.elasticsearch_url
|
||||
or not config.settings.elasticsearch_api_key
|
||||
):
|
||||
raise ValueError(
|
||||
raise MissingApiKeyError(
|
||||
"Elasticsearch URL and API key must be set in the configuration for cluster 'nes'"
|
||||
)
|
||||
|
||||
return config.settings.elasticsearch_url, config.settings.elasticsearch_api_key
|
||||
elif cluster == ESCluster.INSE:
|
||||
if (
|
||||
not config.settings.elasticsearch_inse_url
|
||||
or not config.settings.elasticsearch_inse_api_key
|
||||
):
|
||||
raise ValueError(
|
||||
raise MissingApiKeyError(
|
||||
"Elasticsearch INSE URL and API key must be set in the configuration for cluster 'inse'"
|
||||
)
|
||||
|
||||
@@ -80,8 +105,18 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
|
||||
return None
|
||||
|
||||
|
||||
def search(
|
||||
index: ESIndex | List[ESIndex],
|
||||
def _wrap_exception(e: Exception) -> Exception:
|
||||
if isinstance(e, httpx.HTTPStatusError):
|
||||
if e.response.status_code == 404:
|
||||
return ElasticsearchNotFoundException(f"Elasticsearch resource not found: {e}")
|
||||
return ElasticsearchException(f"Elasticsearch returned status {e.response.status_code}: {e}")
|
||||
elif isinstance(e, httpx.RequestError):
|
||||
return ElasticsearchConnectionException(f"Elasticsearch connection error: {e}")
|
||||
return ElasticsearchException(f"Unexpected Elasticsearch error: {e}")
|
||||
|
||||
|
||||
async def search(
|
||||
index: ESIndex | List[ESIndex] | str | List[str],
|
||||
query: Optional[Dict] = None,
|
||||
source: Optional[List] = None,
|
||||
size: Optional[int] = None,
|
||||
@@ -112,10 +147,11 @@ def search(
|
||||
clusters = set()
|
||||
if isinstance(index, list):
|
||||
for idx in index:
|
||||
cluster_for_index = _index_to_cluster(idx)
|
||||
if cluster_for_index is not None:
|
||||
clusters.add(cluster_for_index)
|
||||
else:
|
||||
if isinstance(idx, ESIndex):
|
||||
cluster_for_index = _index_to_cluster(idx)
|
||||
if cluster_for_index is not None:
|
||||
clusters.add(cluster_for_index)
|
||||
elif isinstance(index, ESIndex):
|
||||
cluster_for_index = _index_to_cluster(index)
|
||||
if cluster_for_index is not None:
|
||||
clusters.add(cluster_for_index)
|
||||
@@ -156,111 +192,125 @@ def search(
|
||||
"At least one of 'query', 'body', 'source', 'size', 'offset', 'sort' must be provided"
|
||||
)
|
||||
|
||||
with httpx.Client(timeout=httpx.Timeout(30.0)) as client:
|
||||
logger.debug(
|
||||
f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {json.dumps(payload)}"
|
||||
)
|
||||
if isinstance(index, list):
|
||||
index_str = ",".join(index)
|
||||
else:
|
||||
index_str = index
|
||||
client = get_client()
|
||||
logger.debug(
|
||||
f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {json.dumps(payload)}"
|
||||
)
|
||||
if isinstance(index, list):
|
||||
index_str = ",".join(str(idx) for idx in index)
|
||||
else:
|
||||
index_str = str(index)
|
||||
|
||||
response = client.post(
|
||||
try:
|
||||
response = await client.post(
|
||||
f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
|
||||
def open_point_in_time(index: str, keep_alive: str = "1m", cluster: str = "nes") -> str:
|
||||
async def open_point_in_time(index: str, keep_alive: str = "1m", cluster: str = "nes") -> str:
|
||||
"""Opens a point-in-time on the given index and returns its id."""
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
with httpx.Client(timeout=httpx.Timeout(30.0)) as client:
|
||||
response = client.post(
|
||||
client = get_client()
|
||||
try:
|
||||
response = await client.post(
|
||||
f"{elasticsearch_url}/{index}/_pit",
|
||||
params={"keep_alive": keep_alive},
|
||||
headers=headers,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()["id"]
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
|
||||
def close_point_in_time(pit_id: str, cluster: str = "nes") -> None:
|
||||
async def close_point_in_time(pit_id: str, cluster: str = "nes") -> None:
|
||||
"""Closes a previously opened point-in-time."""
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
with httpx.Client(timeout=httpx.Timeout(30.0)) as client:
|
||||
response = client.request(
|
||||
client = get_client()
|
||||
try:
|
||||
response = await client.request(
|
||||
"DELETE",
|
||||
f"{elasticsearch_url}/_pit",
|
||||
json={"id": pit_id},
|
||||
headers=headers,
|
||||
)
|
||||
response.raise_for_status()
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
|
||||
def scan(
|
||||
async def scan(
|
||||
index: str,
|
||||
query: Dict,
|
||||
source: Optional[List] = None,
|
||||
page_size: int = 1000,
|
||||
keep_alive: str = "1m",
|
||||
cluster: str = "nes",
|
||||
) -> Iterator[Dict[str, Any]]:
|
||||
) -> AsyncIterator[Dict[str, Any]]:
|
||||
"""Yields every hit matching ``query`` using a point-in-time + ``search_after``.
|
||||
|
||||
|
||||
Unlike ``from``/``size`` pagination, this is not bounded by
|
||||
``index.max_result_window``, so it can stream result sets larger than 10k.
|
||||
"""
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
pit_id = open_point_in_time(index, keep_alive=keep_alive, cluster=cluster)
|
||||
pit_id = await open_point_in_time(index, keep_alive=keep_alive, cluster=cluster)
|
||||
search_after: Optional[List] = None
|
||||
try:
|
||||
with httpx.Client(timeout=httpx.Timeout(30.0)) as client:
|
||||
while True:
|
||||
payload: Dict[str, Any] = {
|
||||
"size": page_size,
|
||||
"query": query,
|
||||
"pit": {"id": pit_id, "keep_alive": keep_alive},
|
||||
"sort": [{"_shard_doc": "asc"}],
|
||||
"track_total_hits": False,
|
||||
}
|
||||
if source is not None:
|
||||
payload["_source"] = source
|
||||
if search_after is not None:
|
||||
payload["search_after"] = search_after
|
||||
client = get_client()
|
||||
while True:
|
||||
payload: Dict[str, Any] = {
|
||||
"size": page_size,
|
||||
"query": query,
|
||||
"pit": {"id": pit_id, "keep_alive": keep_alive},
|
||||
"sort": [{"_shard_doc": "asc"}],
|
||||
"track_total_hits": False,
|
||||
}
|
||||
if source is not None:
|
||||
payload["_source"] = source
|
||||
if search_after is not None:
|
||||
payload["search_after"] = search_after
|
||||
|
||||
response = client.post(
|
||||
try:
|
||||
response = await client.post(
|
||||
f"{elasticsearch_url}/_search", json=payload, headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
result = response.json()
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
hits = result.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
break
|
||||
result = response.json()
|
||||
|
||||
yield from hits
|
||||
hits = result.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
break
|
||||
|
||||
for hit in hits:
|
||||
yield hit
|
||||
|
||||
# The pit id can be refreshed between requests; keep the latest.
|
||||
pit_id = result.get("pit_id", pit_id)
|
||||
search_after = hits[-1].get("sort")
|
||||
if search_after is None or len(hits) < page_size:
|
||||
break
|
||||
pit_id = result.get("pit_id", pit_id)
|
||||
search_after = hits[-1].get("sort")
|
||||
if search_after is None or len(hits) < page_size:
|
||||
break
|
||||
finally:
|
||||
try:
|
||||
close_point_in_time(pit_id, cluster=cluster)
|
||||
await close_point_in_time(pit_id, cluster=cluster)
|
||||
except Exception:
|
||||
logger.exception("Failed to close Elasticsearch point-in-time.")
|
||||
|
||||
|
||||
def get(
|
||||
index: ESIndex,
|
||||
async def get(
|
||||
index: ESIndex | str,
|
||||
doc_id: str,
|
||||
source: Optional[list] = None,
|
||||
cluster: ESCluster = ESCluster.NES,
|
||||
@@ -274,15 +324,18 @@ def get(
|
||||
if source is not None:
|
||||
params["_source_includes"] = ",".join(source)
|
||||
|
||||
with httpx.Client() as client:
|
||||
response = client.get(
|
||||
client = get_client()
|
||||
try:
|
||||
response = await client.get(
|
||||
f"{elasticsearch_url}/{index}/_doc/{doc_id}", params=params, headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
|
||||
def update(
|
||||
async def update(
|
||||
index: str,
|
||||
doc_id: str,
|
||||
doc: Dict[str, Any],
|
||||
@@ -291,17 +344,20 @@ def update(
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
with httpx.Client(timeout=httpx.Timeout(30.0)) as client:
|
||||
response = client.post(
|
||||
client = get_client()
|
||||
try:
|
||||
response = await client.post(
|
||||
f"{elasticsearch_url}/{index}/_update/{doc_id}",
|
||||
json={"doc": doc},
|
||||
headers=headers,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
|
||||
def index_doc(
|
||||
async def index_doc(
|
||||
index: str,
|
||||
doc_id: str,
|
||||
document: Dict[str, Any],
|
||||
@@ -310,11 +366,14 @@ def index_doc(
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
with httpx.Client(timeout=httpx.Timeout(30.0)) as client:
|
||||
response = client.put(
|
||||
client = get_client()
|
||||
try:
|
||||
response = await client.put(
|
||||
f"{elasticsearch_url}/{index}/_doc/{doc_id}",
|
||||
json=document,
|
||||
headers=headers,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
@@ -18,6 +18,7 @@ import json
|
||||
from . import schema
|
||||
from . import model
|
||||
from . import config
|
||||
from inse.integrations import elasticsearch
|
||||
|
||||
|
||||
from inse.models.openalex.topic import Topic
|
||||
@@ -103,56 +104,42 @@ def _load_topic_cache() -> dict:
|
||||
return {}
|
||||
|
||||
|
||||
def build_topic_cache(page_size: int = 200, save_json: bool = True) -> dict:
|
||||
async def build_topic_cache(save_json: bool = True) -> dict:
|
||||
"""
|
||||
Fetch topics from the hosted OpenAlex topics index and build a lookup cache (scheduled task).
|
||||
|
||||
Arguments:
|
||||
page_size (int): Number of topics to fetch per request (default: 200)
|
||||
save_json (bool): Whether to save the cache as a JSON file (default: True)
|
||||
|
||||
Returns:
|
||||
taxonomy_cache (dict): The topic hierarchy dictionary.
|
||||
"""
|
||||
output_filename: str = "topic_hierarchy_cache.json"
|
||||
headers = {
|
||||
"Authorization": f"ApiKey {config.settings.elasticsearch_api_key}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
taxonomy_cache = {}
|
||||
offset = 0
|
||||
|
||||
with httpx.Client(timeout=30.0) as client:
|
||||
while True:
|
||||
payload = {"query": {"match_all": {}}, "from": offset, "size": page_size}
|
||||
response = client.post(
|
||||
config.settings.elasticsearch_url + "/openalex-topics/_search",
|
||||
json=payload,
|
||||
headers=headers,
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
try:
|
||||
async for hit in elasticsearch.scan(
|
||||
index="openalex-topics",
|
||||
query={"match_all": {}},
|
||||
source=["display_name", "name", "id", "subfield", "field", "domain"],
|
||||
cluster="nes",
|
||||
):
|
||||
source = hit.get("_source", {})
|
||||
topic_name = source.get("display_name") or source.get("name")
|
||||
if not topic_name:
|
||||
continue
|
||||
|
||||
hits = data.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
break
|
||||
taxonomy_cache[topic_name] = {
|
||||
"topic_id": source.get("id") or hit.get("_id", ""),
|
||||
"subfield": source.get("subfield", {}).get("display_name", ""),
|
||||
"field": source.get("field", {}).get("display_name", ""),
|
||||
"domain": source.get("domain", {}).get("display_name", ""),
|
||||
}
|
||||
except Exception as exc:
|
||||
logger.error("Failed to scan topics from Elasticsearch: %s", exc)
|
||||
|
||||
for hit in hits:
|
||||
source = hit.get("_source", {})
|
||||
topic_name = source.get("display_name") or source.get("name")
|
||||
if not topic_name:
|
||||
continue
|
||||
|
||||
taxonomy_cache[topic_name] = {
|
||||
"topic_id": source.get("id") or hit.get("_id", ""),
|
||||
"subfield": source.get("subfield", {}).get("display_name", ""),
|
||||
"field": source.get("field", {}).get("display_name", ""),
|
||||
"domain": source.get("domain", {}).get("display_name", ""),
|
||||
}
|
||||
|
||||
offset += len(hits)
|
||||
logger.info("Processed %s topics total", len(taxonomy_cache))
|
||||
logger.info("Processed %s topics total", len(taxonomy_cache))
|
||||
|
||||
if save_json:
|
||||
data_json = json.dumps(taxonomy_cache, indent=2, ensure_ascii=True)
|
||||
|
||||
@@ -14,7 +14,13 @@ from fastapi.responses import JSONResponse, RedirectResponse
|
||||
|
||||
from inse.collaboration_network.router import router as collaboration_network_router
|
||||
from inse.company_connections.service import router as company_connections_router
|
||||
from inse.exceptions import NotFoundException
|
||||
from inse.exceptions import (
|
||||
NotFoundException,
|
||||
ElasticsearchException,
|
||||
MissingApiKeyError,
|
||||
UpstreamAPIException,
|
||||
BadRequestException,
|
||||
)
|
||||
from inse.funders.service import router as funders_service_router
|
||||
from inse.projects.router import router as projects_router
|
||||
from inse.university_ranking.router import router as university_ranking_router
|
||||
@@ -87,11 +93,37 @@ app.add_middleware(
|
||||
)
|
||||
|
||||
|
||||
# exception handlers
|
||||
|
||||
@app.exception_handler(NotFoundException)
|
||||
async def handle_not_found(request: Request, exc: NotFoundException):
|
||||
return JSONResponse(status_code=404, content={"message": str(exc)})
|
||||
|
||||
|
||||
@app.exception_handler(ElasticsearchException)
|
||||
async def handle_elasticsearch_error(request: Request, exc: ElasticsearchException):
|
||||
logger.error("Elasticsearch integration error: %s", str(exc))
|
||||
return JSONResponse(status_code=502, content={"message": "Search service temporarily unavailable"})
|
||||
|
||||
|
||||
@app.exception_handler(MissingApiKeyError)
|
||||
async def handle_missing_api_key(request: Request, exc: MissingApiKeyError):
|
||||
logger.error("Configuration error: %s", str(exc))
|
||||
return JSONResponse(status_code=503, content={"message": str(exc) or "Search service is not configured"})
|
||||
|
||||
|
||||
@app.exception_handler(UpstreamAPIException)
|
||||
async def handle_upstream_api_error(request: Request, exc: UpstreamAPIException):
|
||||
logger.error("Upstream API error: %s", str(exc))
|
||||
return JSONResponse(status_code=exc.status_code, content={"message": exc.message})
|
||||
|
||||
|
||||
@app.exception_handler(BadRequestException)
|
||||
async def handle_bad_request(request: Request, exc: BadRequestException):
|
||||
logger.error("Bad Request: %s", str(exc))
|
||||
return JSONResponse(status_code=400, content={"message": str(exc)})
|
||||
|
||||
|
||||
@app.exception_handler(404)
|
||||
async def redirect(_, __):
|
||||
return RedirectResponse(url="/inse-webapp/")
|
||||
|
||||
@@ -8,8 +8,7 @@ import json
|
||||
import logging
|
||||
import re
|
||||
|
||||
from fastapi import HTTPException
|
||||
from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR
|
||||
from inse.exceptions import ElasticsearchException
|
||||
|
||||
from ..integrations import elasticsearch, llm
|
||||
from ..persons.logic import find_ude_author_by_name, get_author_name_by_id
|
||||
@@ -36,7 +35,7 @@ RELATED_TOPIC_K = 1
|
||||
EXACT_ID_CAP = 1000
|
||||
|
||||
|
||||
def get_news_page(
|
||||
async def get_news_page(
|
||||
page: int,
|
||||
page_size: int,
|
||||
sort_order: str = "desc",
|
||||
@@ -46,10 +45,10 @@ def get_news_page(
|
||||
) -> NewsPage:
|
||||
offset = (page - 1) * page_size
|
||||
|
||||
clauses = _filter_clauses(year_from, year_to, relevance_values)
|
||||
clauses = await _filter_clauses(year_from, year_to, relevance_values)
|
||||
query = {"bool": {"filter": clauses}} if clauses else {"match_all": {}}
|
||||
|
||||
response = _run_search(
|
||||
response = await _run_search(
|
||||
query=query,
|
||||
source=["date", "maintitle", "author", "url", "intro_content", "full_content"],
|
||||
size=page_size,
|
||||
@@ -57,10 +56,10 @@ def get_news_page(
|
||||
sort=[{"date_full": sort_order}],
|
||||
)
|
||||
|
||||
return _build_page(response, page, page_size)
|
||||
return await _build_page(response, page, page_size)
|
||||
|
||||
|
||||
def search_news(
|
||||
async def search_news(
|
||||
query_text: str,
|
||||
page: int,
|
||||
page_size: int,
|
||||
@@ -78,14 +77,14 @@ def search_news(
|
||||
}
|
||||
|
||||
# Filter einmal berechnen (der Relevanz-Filter macht eine ES-Abfrage).
|
||||
clauses = _filter_clauses(year_from, year_to, relevance_values)
|
||||
clauses = await _filter_clauses(year_from, year_to, relevance_values)
|
||||
exact_query = {
|
||||
"bool": {
|
||||
"must": [{"match": {"full_content": query_text}}],
|
||||
"filter": clauses,
|
||||
}
|
||||
}
|
||||
response = _run_search(
|
||||
response = await _run_search(
|
||||
query=exact_query,
|
||||
source=["date", "maintitle", "author", "url"],
|
||||
size=page_size,
|
||||
@@ -94,19 +93,20 @@ def search_news(
|
||||
highlight=highlight,
|
||||
)
|
||||
|
||||
news_page = _build_page(response, page, page_size)
|
||||
news_page = await _build_page(response, page, page_size)
|
||||
|
||||
if _is_last_page(page, page_size, news_page.total):
|
||||
exclude_ids = _exact_match_ids(exact_query)
|
||||
exclude_ids = await _exact_match_ids(exact_query)
|
||||
news_page.results.extend(
|
||||
_related_articles(
|
||||
await _related_articles(
|
||||
query_text, exclude_ids=exclude_ids, extra_filters=clauses
|
||||
)
|
||||
)
|
||||
|
||||
return news_page
|
||||
|
||||
def get_news_by_author(
|
||||
|
||||
async def get_news_by_author(
|
||||
author_id: str,
|
||||
page: int = 1,
|
||||
page_size: int = 10,
|
||||
@@ -114,11 +114,11 @@ def get_news_by_author(
|
||||
query_text: str | None = None,
|
||||
) -> NewsPage:
|
||||
|
||||
author_name = get_author_name_by_id(author_id)
|
||||
author_name = await get_author_name_by_id(author_id)
|
||||
if not author_name:
|
||||
return _empty_page(page, page_size)
|
||||
|
||||
news_ids = _find_news_ids_for_author(author_name)
|
||||
news_ids = await _find_news_ids_for_author(author_name)
|
||||
if not news_ids:
|
||||
return _empty_page(page, page_size)
|
||||
|
||||
@@ -129,7 +129,7 @@ def get_news_by_author(
|
||||
]
|
||||
|
||||
offset = (page - 1) * page_size
|
||||
response = _run_search(
|
||||
response = await _run_search(
|
||||
query=es_query,
|
||||
source=["date", "maintitle", "author", "url"],
|
||||
size=page_size,
|
||||
@@ -137,12 +137,12 @@ def get_news_by_author(
|
||||
sort=[{"date_full": sort_order}],
|
||||
)
|
||||
|
||||
news_page = _build_page(response, page, page_size)
|
||||
news_page = await _build_page(response, page, page_size)
|
||||
|
||||
if query_text and _is_last_page(page, page_size, news_page.total):
|
||||
exclude_ids = _exact_match_ids(es_query)
|
||||
exclude_ids = await _exact_match_ids(es_query)
|
||||
news_page.results.extend(
|
||||
_related_articles(
|
||||
await _related_articles(
|
||||
query_text, exclude_ids=exclude_ids, filter_news_ids=news_ids
|
||||
)
|
||||
)
|
||||
@@ -150,7 +150,7 @@ def get_news_by_author(
|
||||
return news_page
|
||||
|
||||
|
||||
def _filter_clauses(
|
||||
async def _filter_clauses(
|
||||
year_from: int | None,
|
||||
year_to: int | None,
|
||||
relevance_values: list | None,
|
||||
@@ -165,14 +165,14 @@ def _filter_clauses(
|
||||
date_range["lte"] = year_to
|
||||
clauses.append({"range": {"date_year": date_range}})
|
||||
|
||||
relevant_ids = _relevance_news_ids(relevance_values)
|
||||
relevant_ids = await _relevance_news_ids(relevance_values)
|
||||
if relevant_ids is not None:
|
||||
clauses.append({"ids": {"values": relevant_ids}})
|
||||
|
||||
return clauses
|
||||
|
||||
|
||||
def _relevance_news_ids(relevance_values: list | None) -> list | None:
|
||||
async def _relevance_news_ids(relevance_values: list | None) -> list | None:
|
||||
selected = set(relevance_values or [])
|
||||
|
||||
if not selected or {"relevant", "not_relevant"} <= selected:
|
||||
@@ -182,7 +182,7 @@ def _relevance_news_ids(relevance_values: list | None) -> list | None:
|
||||
|
||||
news_ids = []
|
||||
try:
|
||||
for hit in elasticsearch.scan(
|
||||
async for hit in elasticsearch.scan(
|
||||
index="aktuell_postproc",
|
||||
query={"term": {"relevant": relevant_value}},
|
||||
source=["news_id"],
|
||||
@@ -198,10 +198,10 @@ def _relevance_news_ids(relevance_values: list | None) -> list | None:
|
||||
return news_ids
|
||||
|
||||
|
||||
def _find_news_ids_for_author(author_name: str) -> list:
|
||||
async def _find_news_ids_for_author(author_name: str) -> list:
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="aktuell_postproc",
|
||||
query={"term": {"authors.keyword": author_name}},
|
||||
source=["news_id"],
|
||||
@@ -225,26 +225,23 @@ def _empty_page(page: int = 1, page_size: int = 0) -> NewsPage:
|
||||
return NewsPage(total=0, page=page, page_size=page_size, results=[])
|
||||
|
||||
|
||||
def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
||||
async def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
||||
try:
|
||||
response = elasticsearch.get(
|
||||
response = await elasticsearch.get(
|
||||
index="aktuell",
|
||||
doc_id=news_id,
|
||||
source=["date", "maintitle", "author", "url", "full_content"],
|
||||
cluster="inse",
|
||||
)
|
||||
except Exception as exc:
|
||||
except ElasticsearchException as exc:
|
||||
logger.exception("Abruf des News-Artikels fehlgeschlagen.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="Etwas ist schiefgelaufen.",
|
||||
) from exc
|
||||
raise
|
||||
|
||||
source = response.get("_source", {})
|
||||
|
||||
relevant, authors, cached_keywords, postproc_id = _get_postproc_labels(news_id)
|
||||
topics = _get_article_topics(source.get("maintitle"), source.get("full_content"))
|
||||
keywords = _get_article_keywords(
|
||||
relevant, authors, cached_keywords, postproc_id = await _get_postproc_labels(news_id)
|
||||
topics = await _get_article_topics(source.get("maintitle"), source.get("full_content"))
|
||||
keywords = await _get_article_keywords(
|
||||
news_id,
|
||||
postproc_id,
|
||||
cached_keywords,
|
||||
@@ -260,24 +257,24 @@ def get_news_by_id(news_id: str) -> NewsArticleDetail:
|
||||
url=source.get("url"),
|
||||
full_content=source.get("full_content"),
|
||||
relevant=relevant,
|
||||
authors=_build_mentioned_persons(authors),
|
||||
authors=await _build_mentioned_persons(authors),
|
||||
topics=topics,
|
||||
keywords=keywords,
|
||||
)
|
||||
|
||||
|
||||
def _get_article_topics(maintitle: str | None, full_content: str | None) -> list:
|
||||
async def _get_article_topics(maintitle: str | None, full_content: str | None) -> list:
|
||||
query = " ".join(
|
||||
part for part in (maintitle, (full_content or "")[:TOPIC_QUERY_CONTENT_CHARS]) if part
|
||||
).strip()
|
||||
if not query:
|
||||
return []
|
||||
|
||||
topics = _topic_vector_search(query, TOPIC_LIMIT, ["display_name"])
|
||||
topics = await _topic_vector_search(query, TOPIC_LIMIT, ["display_name"])
|
||||
return [topic["display_name"] for topic in topics if topic.get("display_name")]
|
||||
|
||||
|
||||
def _get_article_keywords(
|
||||
async def _get_article_keywords(
|
||||
news_id: str,
|
||||
postproc_id: str | None,
|
||||
cached_keywords: list,
|
||||
@@ -301,7 +298,7 @@ def _get_article_keywords(
|
||||
keywords = _parse_keywords(raw)
|
||||
|
||||
if keywords:
|
||||
_store_keywords(news_id, postproc_id, keywords)
|
||||
await _store_keywords(news_id, postproc_id, keywords)
|
||||
|
||||
return keywords
|
||||
|
||||
@@ -326,17 +323,17 @@ def _parse_keywords(raw: str) -> list:
|
||||
return keywords[:KEYWORD_LIMIT]
|
||||
|
||||
|
||||
def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) -> None:
|
||||
async def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) -> None:
|
||||
try:
|
||||
if postproc_id:
|
||||
elasticsearch.update(
|
||||
await elasticsearch.update(
|
||||
index="aktuell_postproc",
|
||||
doc_id=postproc_id,
|
||||
doc={"keywords": keywords},
|
||||
cluster="inse",
|
||||
)
|
||||
else:
|
||||
elasticsearch.index_doc(
|
||||
await elasticsearch.index_doc(
|
||||
index="aktuell_postproc",
|
||||
doc_id=news_id,
|
||||
document={"news_id": news_id, "keywords": keywords},
|
||||
@@ -346,7 +343,7 @@ def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) -> No
|
||||
logger.exception(f"Failed to cache keywords for {news_id}.")
|
||||
|
||||
|
||||
def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list:
|
||||
async def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list:
|
||||
try:
|
||||
from ..util import get_model
|
||||
|
||||
@@ -356,7 +353,7 @@ def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list:
|
||||
return []
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="topicvectors",
|
||||
body={
|
||||
"knn": {
|
||||
@@ -378,13 +375,13 @@ def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list:
|
||||
return [hit.get("_source", {}) for hit in response.get("hits", {}).get("hits", [])]
|
||||
|
||||
|
||||
def _build_mentioned_persons(author_names: list) -> list:
|
||||
async def _build_mentioned_persons(author_names: list) -> list:
|
||||
|
||||
ude_persons = []
|
||||
other_persons = []
|
||||
|
||||
for name in author_names:
|
||||
match = find_ude_author_by_name(name)
|
||||
match = await find_ude_author_by_name(name)
|
||||
if match:
|
||||
ude_persons.append(
|
||||
MentionedPerson(name=name, is_ude=True, person_id=match["id"])
|
||||
@@ -395,9 +392,9 @@ def _build_mentioned_persons(author_names: list) -> list:
|
||||
return ude_persons + other_persons
|
||||
|
||||
|
||||
def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, str | None]:
|
||||
async def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, str | None]:
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="aktuell_postproc",
|
||||
query={"term": {"news_id.keyword": news_id}},
|
||||
source=["relevant", "authors", "keywords"],
|
||||
@@ -421,9 +418,9 @@ def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, str | N
|
||||
return relevant, authors, keywords, hit.get("_id")
|
||||
|
||||
|
||||
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) -> dict:
|
||||
try:
|
||||
return elasticsearch.search(
|
||||
return await elasticsearch.search(
|
||||
index="aktuell",
|
||||
query=query,
|
||||
source=source,
|
||||
@@ -434,15 +431,12 @@ def _run_search(query: dict, source: list, size: int, offset: int, sort, highlig
|
||||
highlight=highlight,
|
||||
cluster="inse",
|
||||
)
|
||||
except Exception as exc:
|
||||
except ElasticsearchException as exc:
|
||||
logger.exception("Elasticsearch-Anfrage an Index 'aktuell' fehlgeschlagen.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="Etwas ist schiefgelaufen.",
|
||||
) from exc
|
||||
raise
|
||||
|
||||
|
||||
def _build_page(response: dict, page: int, page_size: int) -> NewsPage:
|
||||
async def _build_page(response: dict, page: int, page_size: int) -> NewsPage:
|
||||
hits_section = response.get("hits", {})
|
||||
total = hits_section.get("total", {}).get("value", 0)
|
||||
hits = hits_section.get("hits", [])
|
||||
@@ -453,7 +447,7 @@ def _build_page(response: dict, page: int, page_size: int) -> NewsPage:
|
||||
if news_id:
|
||||
news_ids.append(news_id)
|
||||
|
||||
relevance_map = _get_relevance_map(news_ids)
|
||||
relevance_map = await _get_relevance_map(news_ids)
|
||||
|
||||
articles = []
|
||||
for hit in hits:
|
||||
@@ -469,12 +463,12 @@ def _build_page(response: dict, page: int, page_size: int) -> NewsPage:
|
||||
)
|
||||
|
||||
|
||||
def _get_relevance_map(news_ids: list) -> dict:
|
||||
async def _get_relevance_map(news_ids: list) -> dict:
|
||||
if not news_ids:
|
||||
return {}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="aktuell_postproc",
|
||||
query={"terms": {"news_id.keyword": news_ids}},
|
||||
source=["news_id", "relevant"],
|
||||
@@ -499,7 +493,7 @@ def _parse_hit(hit: dict) -> NewsArticle:
|
||||
source = hit.get("_source", {})
|
||||
|
||||
fragments = hit.get("highlight", {}).get("full_content")
|
||||
|
||||
|
||||
if fragments:
|
||||
snippet = fragments[0]
|
||||
else:
|
||||
@@ -517,7 +511,7 @@ def _parse_hit(hit: dict) -> NewsArticle:
|
||||
|
||||
def _make_preview(source: dict) -> str | None:
|
||||
text = source.get("intro_content") or source.get("full_content")
|
||||
|
||||
|
||||
if not text:
|
||||
return None
|
||||
|
||||
@@ -534,9 +528,9 @@ def _is_last_page(page: int, page_size: int, total: int) -> bool:
|
||||
return page * page_size >= total
|
||||
|
||||
|
||||
def _exact_match_ids(query: dict) -> list:
|
||||
async def _exact_match_ids(query: dict) -> list:
|
||||
try:
|
||||
response = _run_search(
|
||||
response = await _run_search(
|
||||
query=query,
|
||||
source=[],
|
||||
size=EXACT_ID_CAP,
|
||||
@@ -554,14 +548,14 @@ def _exact_match_ids(query: dict) -> list:
|
||||
]
|
||||
|
||||
|
||||
def _related_articles(
|
||||
async def _related_articles(
|
||||
query_text: str,
|
||||
exclude_ids: list | None = None,
|
||||
filter_news_ids: list | None = None,
|
||||
extra_filters: list | None = None,
|
||||
k: int = RELATED_BLOCK_SIZE,
|
||||
) -> list:
|
||||
related_terms = _related_search_terms(query_text)
|
||||
related_terms = await _related_search_terms(query_text)
|
||||
if not related_terms:
|
||||
return []
|
||||
|
||||
@@ -577,7 +571,7 @@ def _related_articles(
|
||||
bool_query.setdefault("filter", []).extend(extra_filters)
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="aktuell",
|
||||
query={"bool": bool_query},
|
||||
source=["date", "maintitle", "author", "url", "intro_content", "full_content"],
|
||||
@@ -595,15 +589,15 @@ def _related_articles(
|
||||
article.related = True
|
||||
articles.append(article)
|
||||
|
||||
relevance_map = _get_relevance_map([article.id for article in articles])
|
||||
relevance_map = await _get_relevance_map([article.id for article in articles])
|
||||
for article in articles:
|
||||
article.relevant = relevance_map.get(article.id)
|
||||
|
||||
return articles
|
||||
|
||||
|
||||
def _related_search_terms(query_text: str) -> list:
|
||||
topics = _topic_vector_search(query_text, RELATED_TOPIC_K, ["display_name", "keywords"])
|
||||
async def _related_search_terms(query_text: str) -> list:
|
||||
topics = await _topic_vector_search(query_text, RELATED_TOPIC_K, ["display_name", "keywords"])
|
||||
|
||||
seen = {query_text.lower()}
|
||||
terms = []
|
||||
|
||||
@@ -34,7 +34,7 @@ def _parse_relevance(relevance: str | None) -> list:
|
||||
summary="Returns a page of news articles, newest first.",
|
||||
tags=[Tags.NEWS],
|
||||
)
|
||||
def list_news(
|
||||
async def list_news(
|
||||
page: Annotated[
|
||||
int, Query(description="Page number (1-based).", ge=1)
|
||||
] = 1,
|
||||
@@ -54,7 +54,7 @@ def list_news(
|
||||
int | None, Query(alias="yearTo", description="Latest publication year (inclusive).", ge=0)
|
||||
] = None,
|
||||
):
|
||||
return logic.get_news_page(
|
||||
return await logic.get_news_page(
|
||||
page,
|
||||
page_size,
|
||||
sort_order,
|
||||
@@ -72,7 +72,7 @@ def list_news(
|
||||
summary="Searches news articles by full text (full_content).",
|
||||
tags=[Tags.NEWS],
|
||||
)
|
||||
def search_news(
|
||||
async def search_news(
|
||||
query: Annotated[
|
||||
str, Query(description="Search term, matched against the full text (full_content).", min_length=1)
|
||||
],
|
||||
@@ -92,7 +92,7 @@ def search_news(
|
||||
int | None, Query(alias="yearTo", description="Latest publication year (inclusive).", ge=0)
|
||||
] = None,
|
||||
):
|
||||
return logic.search_news(
|
||||
return await logic.search_news(
|
||||
query,
|
||||
page,
|
||||
page_size,
|
||||
@@ -110,7 +110,7 @@ def search_news(
|
||||
summary="Returns news articles in which the given person is mentioned.",
|
||||
tags=[Tags.NEWS],
|
||||
)
|
||||
def get_news_by_author(
|
||||
async def get_news_by_author(
|
||||
author_id: Annotated[
|
||||
str, Query(alias="authorId", description="OpenAlex author id, e.g. A5034365278.")
|
||||
],
|
||||
@@ -127,7 +127,7 @@ def get_news_by_author(
|
||||
str | None, Query(description="Optional search term, matched against title/author.")
|
||||
] = None,
|
||||
):
|
||||
return logic.get_news_by_author(author_id, page, page_size, sort_order, query)
|
||||
return await logic.get_news_by_author(author_id, page, page_size, sort_order, query)
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -138,9 +138,9 @@ def get_news_by_author(
|
||||
summary="Returns a single news article including its full content.",
|
||||
tags=[Tags.NEWS],
|
||||
)
|
||||
def get_news_by_id(
|
||||
async def get_news_by_id(
|
||||
news_id: Annotated[
|
||||
str, Path(description="The unique id of the news article (Elasticsearch _id).")
|
||||
],
|
||||
):
|
||||
return logic.get_news_by_id(news_id)
|
||||
return await logic.get_news_by_id(news_id)
|
||||
|
||||
@@ -8,7 +8,10 @@ from typing import Any
|
||||
import httpx
|
||||
|
||||
from .. import config
|
||||
from .elastic_search_client import MissingApiKeyError
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster
|
||||
|
||||
EPO_INDEX = "epo_index_1.0"
|
||||
USPTO_INDEX = "uspto_patents_3.0"
|
||||
@@ -261,15 +264,4 @@ class AllPatentsSearchClient:
|
||||
return await self._search(USPTO_INDEX, payload)
|
||||
|
||||
async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"/{index}/_search",
|
||||
headers=self._headers(),
|
||||
json=payload,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
return await elasticsearch.search(index=index, body=payload, cluster=ESCluster.INSE)
|
||||
@@ -1,2 +1,281 @@
|
||||
"""Backward-compatible re-exports."""
|
||||
from inse.patents.search_client import * # noqa: F403
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
HTTP client for patent searches in EPO and USPTO Elasticsearch indices.
|
||||
"""
|
||||
from typing import Any
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
import httpx
|
||||
import asyncio
|
||||
from .. import config
|
||||
from .name_matching import search_name_variants
|
||||
|
||||
DEFAULT_SEARCH_SIZE = 100
|
||||
|
||||
|
||||
def _match_name_field(field: str, name: str) -> dict[str, Any]:
|
||||
"""Match a name field, including transliterated variants (Müller/Mueller)."""
|
||||
variants = search_name_variants(name)
|
||||
if len(variants) <= 1:
|
||||
return {"match": {field: variants[0] if variants else name}}
|
||||
return {
|
||||
"bool": {
|
||||
"should": [{"match": {field: variant}} for variant in variants],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
|
||||
|
||||
class PatentSearchClient:
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str | None = None,
|
||||
api_key: str | None = None,
|
||||
timeout: float = 30.0,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
):
|
||||
self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/")
|
||||
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
|
||||
self.timeout = timeout
|
||||
self.transport = transport
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("Patent Elasticsearch API key is not configured.")
|
||||
return {
|
||||
"Authorization": f"ApiKey {self.api_key}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
def epo_query_by_inventor(
|
||||
self,
|
||||
last_name: str,
|
||||
first_name: str | None = None,
|
||||
size: int = DEFAULT_SEARCH_SIZE,
|
||||
) -> dict[str, Any]:
|
||||
"""Search EPO index: first AND last name in the SAME inventor entry."""
|
||||
if first_name:
|
||||
query = {
|
||||
"nested": {
|
||||
"path": "inventors_name_nested",
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [
|
||||
_match_name_field("inventors_name_nested.inventor", last_name),
|
||||
_match_name_field("inventors_name_nested.inventor", first_name),
|
||||
]
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
else:
|
||||
query = {
|
||||
"nested": {
|
||||
"path": "inventors_name_nested",
|
||||
"query": _match_name_field("inventors_name_nested.inventor", last_name),
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"sort": [
|
||||
{"_score": {"order": "desc"}},
|
||||
{"date_publication": {"order": "desc", "missing": "_last"}},
|
||||
"_doc",
|
||||
],
|
||||
"_source": [
|
||||
"doc_number",
|
||||
"country",
|
||||
"kind",
|
||||
"date_publication",
|
||||
"date_publication_year",
|
||||
"application_number",
|
||||
"application_filing_date",
|
||||
"title_en",
|
||||
"title_de",
|
||||
"abstract",
|
||||
"inventors_name",
|
||||
"applicants_name",
|
||||
"ipc",
|
||||
"cpc",
|
||||
],
|
||||
"query": query,
|
||||
}
|
||||
|
||||
def uspto_query_by_inventor(
|
||||
self,
|
||||
last_name: str,
|
||||
first_name: str | None = None,
|
||||
size: int = DEFAULT_SEARCH_SIZE,
|
||||
) -> dict[str, Any]:
|
||||
"""Search USPTO index: first AND last name in the SAME inventor entry."""
|
||||
if first_name:
|
||||
query = {
|
||||
"nested": {
|
||||
"path": "inventors",
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [
|
||||
_match_name_field("inventors.name", last_name),
|
||||
_match_name_field("inventors.name", first_name),
|
||||
]
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
else:
|
||||
query = {
|
||||
"nested": {
|
||||
"path": "inventors",
|
||||
"query": _match_name_field("inventors.name", last_name),
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"sort": [
|
||||
{"_score": {"order": "desc"}},
|
||||
{"publication_date": {"order": "desc", "missing": "_last"}},
|
||||
"_doc",
|
||||
],
|
||||
"_source": [
|
||||
"publication_number",
|
||||
"country",
|
||||
"publication_date",
|
||||
"publication_year",
|
||||
"application_number",
|
||||
"application_date",
|
||||
"application_type",
|
||||
"title",
|
||||
"abstract",
|
||||
"inventors_names",
|
||||
"assignees_orgs",
|
||||
"ipcr",
|
||||
"cpc",
|
||||
"number_of_claims",
|
||||
"status",
|
||||
],
|
||||
"query": query,
|
||||
}
|
||||
|
||||
async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return await self._search(ESIndex.EPO_INDEX, payload)
|
||||
|
||||
async def search_uspto(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return await self._search(ESIndex.USPTO_INDEX, payload)
|
||||
|
||||
async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
response = await elasticsearch.search(index=index, body=payload, cluster=ESCluster.INSE)
|
||||
return response
|
||||
|
||||
async def get_by_id_or_title(
|
||||
self,
|
||||
patent_id: str,
|
||||
prefix: str,
|
||||
title: str,
|
||||
size: int = 1,
|
||||
) -> dict[str, Any]:
|
||||
"""Search EPO and USPTO by ID; fall back to match_phrase on title if no hits.
|
||||
|
||||
Args:
|
||||
patent_id: The raw document/publication number (e.g. "1234567", "US1234567A").
|
||||
prefix: "EP" routes the title fallback to EPO; "US" routes it to USPTO.
|
||||
Both indices are always queried for the ID lookup.
|
||||
title: Used only when the ID lookup returns zero hits.
|
||||
size: Maximum number of results to return.
|
||||
"""
|
||||
epo_id_payload = self._epo_query_by_id(patent_id, size)
|
||||
uspto_id_payload = self._uspto_query_by_id(patent_id, size)
|
||||
|
||||
epo_result, uspto_result = await asyncio.gather(
|
||||
self.search_epo(epo_id_payload),
|
||||
self.search_uspto(uspto_id_payload),
|
||||
)
|
||||
|
||||
epo_hits = epo_result.get("hits", {}).get("total", {}).get("value", 0)
|
||||
uspto_hits = uspto_result.get("hits", {}).get("total", {}).get("value", 0)
|
||||
|
||||
if epo_hits > 0 or uspto_hits > 0:
|
||||
if prefix.upper() == "EP" and epo_hits > 0:
|
||||
return epo_result
|
||||
if prefix.upper() == "US" and uspto_hits > 0:
|
||||
return uspto_result
|
||||
return epo_result if epo_hits > 0 else uspto_result
|
||||
|
||||
if prefix.upper() == "US":
|
||||
payload = self._uspto_query_by_title(title, size)
|
||||
return await self.search_uspto(payload)
|
||||
|
||||
payload = self._epo_query_by_title(title, size)
|
||||
return await self.search_epo(payload)
|
||||
#query builders
|
||||
|
||||
def _epo_query_by_id(self, patent_id: str, size: int) -> dict[str, Any]:
|
||||
"""Term query against doc_number; strips a leading 'EP' prefix if present."""
|
||||
raw_id = patent_id.upper().removeprefix("EP")
|
||||
return {
|
||||
"size": size,
|
||||
"_source": [
|
||||
"doc_number", "country", "kind", "date_publication",
|
||||
"date_publication_year", "application_number",
|
||||
"application_filing_date", "title_en", "title_de", "abstract",
|
||||
"inventors_name", "applicants_name", "ipc", "cpc",
|
||||
],
|
||||
"query": {"term": {"doc_number": raw_id}},
|
||||
}
|
||||
|
||||
def _uspto_query_by_id(self, patent_id: str, size: int) -> dict[str, Any]:
|
||||
"""Term query against publication_number; tries the ID as-is."""
|
||||
return {
|
||||
"size": size,
|
||||
"track_total_hits": True,
|
||||
"sort": [{"publication_date": {"order": "desc", "missing": "_last"}}, "_doc"],
|
||||
"_source": [
|
||||
"publication_number", "country", "publication_date",
|
||||
"publication_year", "application_number", "application_date",
|
||||
"application_type", "title", "abstract", "inventors_names",
|
||||
"assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
|
||||
],
|
||||
"query": {"term": {"publication_number": patent_id}},
|
||||
}
|
||||
|
||||
def _epo_query_by_title(self, title: str, size: int) -> dict[str, Any]:
|
||||
"""match_phrase fallback on title_en (and title_de as a should clause)."""
|
||||
return {
|
||||
"size": size,
|
||||
"_source": [
|
||||
"doc_number", "country", "kind", "date_publication",
|
||||
"date_publication_year", "application_number",
|
||||
"application_filing_date", "title_en", "title_de", "abstract",
|
||||
"inventors_name", "applicants_name", "ipc", "cpc",
|
||||
],
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match_phrase": {"title_en": title}},
|
||||
{"match_phrase": {"title_de": title}},
|
||||
{"match_phrase": {"title_fr": title}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
def _uspto_query_by_title(self, title: str, size: int) -> dict[str, Any]:
|
||||
"""match_phrase fallback on title."""
|
||||
return {
|
||||
"size": size,
|
||||
"_source": [
|
||||
"publication_number", "country", "publication_date",
|
||||
"publication_year", "application_number", "application_date",
|
||||
"application_type", "title", "abstract", "inventors_names",
|
||||
"assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
|
||||
],
|
||||
"query": {"match_phrase": {"title": title}},
|
||||
}
|
||||
|
||||
@@ -11,11 +11,14 @@ import httpx
|
||||
|
||||
from .. import config
|
||||
from . import model
|
||||
from .elastic_search_client import MissingApiKeyError
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
from .ipc_lookup import IpcHierarchyKeys
|
||||
from .ipc_lookup import build_ipc_classification
|
||||
from .ipc_lookup import parse_ipc_symbol
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster
|
||||
|
||||
IPC_INDEX = "ipc"
|
||||
|
||||
_LEVELS: tuple[tuple[str, str, str], ...] = (
|
||||
@@ -136,15 +139,4 @@ class IpcSearchClient:
|
||||
return found
|
||||
|
||||
async def _search(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"/{IPC_INDEX}/_search",
|
||||
headers=self._headers(),
|
||||
json=payload,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
return await elasticsearch.search(index=IPC_INDEX, body=payload, cluster=ESCluster.INSE)
|
||||
|
||||
@@ -7,11 +7,308 @@ from inse.patents.institutions.logic import (
|
||||
get_patents_by_institution_id,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"_deduplicate_patents",
|
||||
"_filter_patents_by_institution",
|
||||
"get_all_patents",
|
||||
"get_patent_by_id",
|
||||
"get_patents_by_author_id",
|
||||
"get_patents_by_institution_id",
|
||||
]
|
||||
import httpx
|
||||
|
||||
from ..persons import logic as person_logic
|
||||
from ..models.openalex.author import Author
|
||||
from . import model
|
||||
from inse.exceptions import MissingApiKeyError, ElasticsearchException
|
||||
from .elastic_search_client import PatentSearchClient
|
||||
from .elastic_search_all_patents_client import AllPatentsSearchClient
|
||||
from .ipc_search_client import IpcSearchClient
|
||||
from .ipc_lookup import extract_ipc_symbol
|
||||
from .name_matching import name_matches
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def get_patent(
|
||||
patent_id: str,
|
||||
title: str,
|
||||
prefix: str,
|
||||
client: PatentSearchClient | None = None,
|
||||
) -> model.PatentEntry:
|
||||
search_client = client or PatentSearchClient()
|
||||
|
||||
data = await search_client.get_by_id_or_title(
|
||||
patent_id=patent_id,
|
||||
prefix=prefix,
|
||||
title=title,
|
||||
)
|
||||
|
||||
parse = _parse_uspto_hits if prefix.upper() == "US" else _parse_epo_hits
|
||||
elements = parse(data)
|
||||
|
||||
if not elements:
|
||||
return None
|
||||
return elements[0]
|
||||
|
||||
|
||||
async def get_patents_by_author_id(
|
||||
author_id: str,
|
||||
client: PatentSearchClient | None = None,
|
||||
ipc_client: IpcSearchClient | None = None,
|
||||
) -> model.PatentsByAuthorResponse:
|
||||
search_client = client or PatentSearchClient()
|
||||
ipc_search_client = ipc_client or IpcSearchClient()
|
||||
|
||||
author = await _get_author(author_id)
|
||||
if not author:
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=None,
|
||||
patent_count=0,
|
||||
patents=[],
|
||||
)
|
||||
|
||||
author_name = author.display_name
|
||||
last_name = _extract_last_name(author_name)
|
||||
first_name = _extract_first_name(author_name)
|
||||
|
||||
if not last_name:
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=author_name,
|
||||
patent_count=0,
|
||||
patents=[],
|
||||
)
|
||||
|
||||
epo_data, uspto_data = await _search_both_indices(
|
||||
search_client, last_name, first_name
|
||||
)
|
||||
|
||||
all_patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data)
|
||||
|
||||
if first_name and last_name:
|
||||
all_patents = _filter_patents_by_name(all_patents, first_name, last_name)
|
||||
|
||||
all_patents = _deduplicate_patents(all_patents)
|
||||
|
||||
await _enrich_patents_classifications(all_patents, ipc_search_client)
|
||||
|
||||
return model.PatentsByAuthorResponse(
|
||||
author_id=author_id,
|
||||
author_name=author_name,
|
||||
patent_count=len(all_patents),
|
||||
patents=all_patents,
|
||||
)
|
||||
|
||||
|
||||
async def _search_both_indices(client, last_name, first_name):
|
||||
epo_result, uspto_result = await asyncio.gather(
|
||||
client.search_epo(client.epo_query_by_inventor(last_name, first_name)),
|
||||
client.search_uspto(client.uspto_query_by_inventor(last_name, first_name)),
|
||||
)
|
||||
return epo_result, uspto_result
|
||||
|
||||
|
||||
def _parse_epo_hits(data: dict) -> list[model.PatentEntry]:
|
||||
patents = []
|
||||
for hit in data.get("hits", {}).get("hits", []):
|
||||
src = hit.get("_source", {})
|
||||
inventors = src.get("inventors_name") or []
|
||||
applicants = src.get("applicants_name") or []
|
||||
ipc = src.get("ipc") or []
|
||||
cpc = src.get("cpc") or []
|
||||
patents.append(model.PatentEntry(
|
||||
patent_id=f"EP{src.get('doc_number', hit.get('_id', ''))}",
|
||||
source="EPO",
|
||||
title=src.get("title_en") or src.get("title_de"),
|
||||
abstract=src.get("abstract"),
|
||||
publication_date=str(src.get("date_publication")) if src.get("date_publication") else None,
|
||||
publication_year=str(src.get("date_publication_year")) if src.get("date_publication_year") else None,
|
||||
application_number=src.get("application_number"),
|
||||
application_date=src.get("application_filing_date"),
|
||||
kind=src.get("kind"),
|
||||
inventors=[i for i in (inventors if isinstance(inventors, list) else [inventors]) if i is not None],
|
||||
assignees=[a for a in (applicants if isinstance(applicants, list) else [applicants]) if a is not None],
|
||||
ipc=_to_classification_strings(ipc),
|
||||
cpc=_to_classification_strings(cpc),
|
||||
country=src.get("country", "EP"),
|
||||
))
|
||||
return patents
|
||||
|
||||
|
||||
def _parse_uspto_hits(data: dict) -> list[model.PatentEntry]:
|
||||
patents = []
|
||||
for hit in data.get("hits", {}).get("hits", []):
|
||||
src = hit.get("_source", {})
|
||||
inventors = src.get("inventors_names") or []
|
||||
assignees = src.get("assignees_orgs") or []
|
||||
ipc = src.get("ipcr") or []
|
||||
cpc = src.get("cpc") or []
|
||||
patents.append(model.PatentEntry(
|
||||
patent_id=f"US{src.get('publication_number', hit.get('_id', ''))}",
|
||||
source="USPTO",
|
||||
title=src.get("title"),
|
||||
abstract=src.get("abstract"),
|
||||
publication_date=str(src.get("publication_date")) if src.get("publication_date") else None,
|
||||
publication_year=str(src.get("publication_year")) if src.get("publication_year") else None,
|
||||
application_number=src.get("application_number"),
|
||||
application_date=str(src.get("application_date")) if src.get("application_date") else None,
|
||||
application_type=src.get("application_type"),
|
||||
number_of_claims=src.get("number_of_claims"),
|
||||
status=src.get("status"),
|
||||
inventors=[i for i in (inventors if isinstance(inventors, list) else [inventors]) if i is not None],
|
||||
assignees=[a for a in (assignees if isinstance(assignees, list) else [assignees]) if a is not None],
|
||||
ipc=_to_classification_strings(ipc),
|
||||
cpc=_to_classification_strings(cpc),
|
||||
country=src.get("country", "US"),
|
||||
))
|
||||
return patents
|
||||
|
||||
|
||||
def _to_classification_strings(value) -> list[str]:
|
||||
if not value:
|
||||
return []
|
||||
items = value if isinstance(value, list) else [value]
|
||||
return [str(item).strip() for item in items if item and str(item).strip()]
|
||||
|
||||
|
||||
def _descriptions_for_raw_codes(
|
||||
raw_codes: list[str],
|
||||
resolved: dict[str, model.IpcClassification],
|
||||
) -> list[model.IpcClassification]:
|
||||
return [
|
||||
resolved[extract_ipc_symbol(raw)]
|
||||
for raw in raw_codes
|
||||
if extract_ipc_symbol(raw) in resolved
|
||||
]
|
||||
|
||||
|
||||
async def _enrich_patents_classifications(
|
||||
patents: list[model.PatentEntry],
|
||||
ipc_client: IpcSearchClient,
|
||||
) -> None:
|
||||
symbols = list(dict.fromkeys(
|
||||
extract_ipc_symbol(raw)
|
||||
for patent in patents
|
||||
for raw in (*patent.ipc, *patent.cpc)
|
||||
))
|
||||
if not symbols:
|
||||
return
|
||||
|
||||
try:
|
||||
resolved = await ipc_client.resolve_symbols(symbols)
|
||||
except MissingApiKeyError:
|
||||
logger.warning("Classification enrichment skipped: Elasticsearch API key not configured.")
|
||||
return
|
||||
except ElasticsearchException as exc:
|
||||
logger.warning("Classification enrichment failed: %s", exc)
|
||||
return
|
||||
except Exception as exc:
|
||||
logger.exception("Classification enrichment failed unexpectedly: %s", exc)
|
||||
return
|
||||
|
||||
for patent in patents:
|
||||
patent.ipc_descriptions = _descriptions_for_raw_codes(patent.ipc, resolved)
|
||||
patent.cpc_descriptions = _descriptions_for_raw_codes(patent.cpc, resolved)
|
||||
|
||||
|
||||
def _filter_patents_by_name(
|
||||
patents: list[model.PatentEntry],
|
||||
first_name: str,
|
||||
last_name: str,
|
||||
) -> list[model.PatentEntry]:
|
||||
return [
|
||||
patent for patent in patents
|
||||
if any(name_matches(inventor, first_name, last_name) for inventor in patent.inventors)
|
||||
]
|
||||
|
||||
|
||||
def _deduplicate_patents(patents: list[model.PatentEntry]) -> list[model.PatentEntry]:
|
||||
seen: set[tuple[str, str, str, str]] = set()
|
||||
deduplicated: list[model.PatentEntry] = []
|
||||
|
||||
for patent in patents:
|
||||
key = _patent_dedup_key(patent)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
deduplicated.append(patent)
|
||||
|
||||
return deduplicated
|
||||
|
||||
|
||||
def _patent_dedup_key(patent: model.PatentEntry) -> tuple[str, str, str, str]:
|
||||
stage = patent.kind or patent.application_type or ""
|
||||
return (
|
||||
patent.source,
|
||||
patent.patent_id,
|
||||
patent.publication_date or "",
|
||||
stage,
|
||||
)
|
||||
|
||||
|
||||
async def _get_author(author_id: str) -> Author | None:
|
||||
short_id = author_id.replace("https://openalex.org/", "")
|
||||
result = await person_logic.search_persons(author_id=short_id)
|
||||
return result.results[0] if result.results else None
|
||||
|
||||
|
||||
def _extract_last_name(name: str | None) -> str | None:
|
||||
if not name:
|
||||
return None
|
||||
parts = name.strip().split()
|
||||
return parts[-1] if parts else None
|
||||
|
||||
|
||||
def _extract_first_name(name: str | None) -> str | None:
|
||||
if not name:
|
||||
return None
|
||||
parts = name.strip().split()
|
||||
return parts[0] if len(parts) > 1 else None
|
||||
|
||||
|
||||
async def get_all_patents(
|
||||
page: int = 0,
|
||||
size: int = 10,
|
||||
search: str | None = None,
|
||||
source: str | None = None,
|
||||
sort_by: str = "date",
|
||||
sort_direction: str = "desc",
|
||||
client: PatentSearchClient | None = None,
|
||||
ipc_client: IpcSearchClient | None = None,
|
||||
) -> model.AllPatentsResponse:
|
||||
all_patents_client = AllPatentsSearchClient()
|
||||
ipc_search_client = ipc_client or IpcSearchClient()
|
||||
|
||||
if source == "EPO":
|
||||
epo_data = await all_patents_client.search_epo(
|
||||
all_patents_client.epo_query(page, size, search, sort_direction)
|
||||
)
|
||||
patents = _parse_epo_hits(epo_data)
|
||||
total = epo_data.get("hits", {}).get("total", {}).get("value", 0)
|
||||
|
||||
elif source == "USPTO":
|
||||
uspto_data = await all_patents_client.search_uspto(
|
||||
all_patents_client.uspto_query(page, size, search, sort_direction)
|
||||
)
|
||||
patents = _parse_uspto_hits(uspto_data)
|
||||
total = uspto_data.get("hits", {}).get("total", {}).get("value", 0)
|
||||
|
||||
else:
|
||||
half = size // 2
|
||||
epo_data, uspto_data = await asyncio.gather(
|
||||
all_patents_client.search_epo(
|
||||
all_patents_client.epo_query(page, half, search, sort_direction)
|
||||
),
|
||||
all_patents_client.search_uspto(
|
||||
all_patents_client.uspto_query(page, half, search, sort_direction)
|
||||
),
|
||||
)
|
||||
patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data)
|
||||
total = (
|
||||
epo_data.get("hits", {}).get("total", {}).get("value", 0) +
|
||||
uspto_data.get("hits", {}).get("total", {}).get("value", 0)
|
||||
)
|
||||
|
||||
|
||||
await _enrich_patents_classifications(patents, ipc_search_client)
|
||||
|
||||
return model.AllPatentsResponse(
|
||||
total=total,
|
||||
page=page,
|
||||
size=size,
|
||||
patents=patents,
|
||||
)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import httpx
|
||||
from unittest.mock import AsyncMock, patch
|
||||
import pytest
|
||||
|
||||
from inse.patents.ipc_search_client import IPC_INDEX, IpcSearchClient
|
||||
@@ -11,57 +11,51 @@ def anyio_backend():
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_resolve_symbols_posts_to_ipc_index():
|
||||
requests: list[str] = []
|
||||
mock_response = {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"cpc_section_number": "H",
|
||||
"cpc_section_name": "ELECTRICITY",
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"cpc_class_number": "H01L",
|
||||
"cpc_class_name": "SEMICONDUCTOR DEVICES",
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"cpc_group_number": "H01L21/02",
|
||||
"cpc_group_name": "Manufacture or treatment of semiconductor devices",
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
requests.append(request.url.path)
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"cpc_section_number": "H",
|
||||
"cpc_section_name": "ELECTRICITY",
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"cpc_class_number": "H01L",
|
||||
"cpc_class_name": "SEMICONDUCTOR DEVICES",
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"cpc_group_number": "H01L21/02",
|
||||
"cpc_group_name": "Manufacture or treatment of semiconductor devices",
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
},
|
||||
)
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
|
||||
mock_search.return_value = mock_response
|
||||
client = IpcSearchClient()
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
client = IpcSearchClient(api_key="test-key", transport=transport)
|
||||
result = await client.resolve_symbols(["H01L 21/02"])
|
||||
|
||||
result = await client.resolve_symbols(["H01L 21/02"])
|
||||
|
||||
assert len(requests) >= 1
|
||||
assert all(path.endswith(f"/{IPC_INDEX}/_search") for path in requests)
|
||||
assert "H01L 21/02" in result
|
||||
assert result["H01L 21/02"].section == "H - ELECTRICITY"
|
||||
assert result["H01L 21/02"].subclass == "H01L - SEMICONDUCTOR DEVICES"
|
||||
assert mock_search.call_count >= 1
|
||||
_, kwargs = mock_search.call_args
|
||||
assert kwargs.get("index") == IPC_INDEX
|
||||
assert "H01L 21/02" in result
|
||||
assert result["H01L 21/02"].section == "H - ELECTRICITY"
|
||||
assert result["H01L 21/02"].subclass == "H01L - SEMICONDUCTOR DEVICES"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_resolve_symbols_does_not_crash_for_subclass_codes():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(200, json={"hits": {"hits": []}})
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
|
||||
mock_search.return_value = {"hits": {"hits": []}}
|
||||
client = IpcSearchClient()
|
||||
result = await client.resolve_symbols(["A61J 1/14", "C07D 319/06"])
|
||||
|
||||
client = IpcSearchClient(api_key="test-key", transport=httpx.MockTransport(handler))
|
||||
result = await client.resolve_symbols(["A61J 1/14", "C07D 319/06"])
|
||||
|
||||
assert "A61J 1/14" in result
|
||||
assert "C07D 319/06" in result
|
||||
assert "A61J 1/14" in result
|
||||
assert "C07D 319/06" in result
|
||||
|
||||
@@ -9,10 +9,15 @@ import logging
|
||||
import time
|
||||
from datetime import datetime
|
||||
from typing import Optional, Callable, Any, List
|
||||
from elasticsearch import ApiError, NotFoundError
|
||||
import hashlib
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from inse.exceptions import (
|
||||
NotFoundException,
|
||||
ElasticsearchException,
|
||||
ElasticsearchNotFoundException,
|
||||
ElasticsearchConnectionException,
|
||||
BadRequestException,
|
||||
)
|
||||
|
||||
from inse.model import ESIndex
|
||||
from .. import config
|
||||
@@ -35,7 +40,7 @@ logger = logging.getLogger(__name__)
|
||||
INDEX_NAME = "openalex-authors"
|
||||
UDE_INSTITUTION_ID = "https://openalex.org/I62318514" # Universität Duisburg-Essen
|
||||
|
||||
def find_ude_author_by_name(display_name: str) -> Optional[dict]:
|
||||
async def find_ude_author_by_name(display_name: str) -> Optional[dict]:
|
||||
query = {
|
||||
"_source": ["display_name"],
|
||||
"query": {
|
||||
@@ -63,7 +68,7 @@ def find_ude_author_by_name(display_name: str) -> Optional[dict]:
|
||||
}
|
||||
|
||||
try:
|
||||
data = elasticsearch.search(index=INDEX_NAME, body=query)
|
||||
data = await elasticsearch.search(index=INDEX_NAME, body=query)
|
||||
except Exception:
|
||||
logger.exception(f"UDE-Lookup für '{display_name}' fehlgeschlagen.")
|
||||
return None
|
||||
@@ -89,7 +94,7 @@ def find_ude_author_by_name(display_name: str) -> Optional[dict]:
|
||||
}
|
||||
|
||||
|
||||
def get_author_name_by_id(author_id: str) -> Optional[str]:
|
||||
async def get_author_name_by_id(author_id: str) -> Optional[str]:
|
||||
try:
|
||||
query = {
|
||||
"_source": ["id", "display_name"],
|
||||
@@ -99,7 +104,7 @@ def get_author_name_by_id(author_id: str) -> Optional[str]:
|
||||
"size": 1,
|
||||
}
|
||||
|
||||
data = elasticsearch.search(index=INDEX_NAME, body=query)
|
||||
data = await elasticsearch.search(index=INDEX_NAME, body=query)
|
||||
hits = data.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
return None
|
||||
@@ -109,7 +114,7 @@ def get_author_name_by_id(author_id: str) -> Optional[str]:
|
||||
return None
|
||||
|
||||
|
||||
def search_persons(
|
||||
async def search_persons(
|
||||
author_id: Optional[str] = None,
|
||||
query: Optional[str] = None,
|
||||
) -> AuthorsListResponse:
|
||||
@@ -131,7 +136,7 @@ def search_persons(
|
||||
else:
|
||||
return AuthorsListResponse(results=[], meta=Meta(count=0))
|
||||
|
||||
data = elasticsearch.search(index=ESIndex.OPENALEX_AUTHORS, query=query_)
|
||||
data = await elasticsearch.search(index=ESIndex.OPENALEX_AUTHORS, query=query_)
|
||||
|
||||
authors = []
|
||||
for hit in data.get("hits", {}).get("hits", []):
|
||||
@@ -155,7 +160,7 @@ def search_persons(
|
||||
return AuthorsListResponse(results=authors, meta=Meta(count=len(authors)))
|
||||
|
||||
|
||||
def _fetch_author_display_name(author_id: str) -> Optional[str]:
|
||||
async def _fetch_author_display_name(author_id: str) -> Optional[str]:
|
||||
|
||||
query = {
|
||||
"query_string": {
|
||||
@@ -164,7 +169,7 @@ def _fetch_author_display_name(author_id: str) -> Optional[str]:
|
||||
}
|
||||
}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=INDEX_NAME,
|
||||
query=query,
|
||||
source=["display_name"],
|
||||
@@ -178,7 +183,7 @@ def _fetch_author_display_name(author_id: str) -> Optional[str]:
|
||||
return hits[0].get("_source", {}).get("display_name")
|
||||
|
||||
|
||||
def _fetch_works_and_topics(author_id: str) -> tuple[list, list]:
|
||||
async def _fetch_works_and_topics(author_id: str) -> tuple[list, list]:
|
||||
|
||||
WORK_SOURCE_FIELDS = [
|
||||
"title",
|
||||
@@ -221,7 +226,7 @@ def _fetch_works_and_topics(author_id: str) -> tuple[list, list]:
|
||||
},
|
||||
}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body=body,
|
||||
)
|
||||
@@ -251,7 +256,7 @@ def _fetch_works_and_topics(author_id: str) -> tuple[list, list]:
|
||||
return works, topics
|
||||
|
||||
|
||||
def _get_publication_years_for_author(author_id: str) -> list[int]:
|
||||
async def _get_publication_years_for_author(author_id: str) -> list[int]:
|
||||
author_url = f"https://openalex.org/{author_id.strip()}"
|
||||
|
||||
body = {
|
||||
@@ -278,7 +283,7 @@ def _get_publication_years_for_author(author_id: str) -> list[int]:
|
||||
},
|
||||
}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body=body,
|
||||
)
|
||||
@@ -359,8 +364,8 @@ def _compute_career_metrics(publication_years: list[int]) -> CareerMetrics:
|
||||
)
|
||||
|
||||
|
||||
def get_career_metrics_for_author(author_id: str) -> CareerMetrics:
|
||||
publication_years = _get_publication_years_for_author(author_id)
|
||||
async def get_career_metrics_for_author(author_id: str) -> CareerMetrics:
|
||||
publication_years = await _get_publication_years_for_author(author_id)
|
||||
return _compute_career_metrics(publication_years)
|
||||
|
||||
|
||||
@@ -382,13 +387,13 @@ def _build_papers(works: list) -> list:
|
||||
return papers
|
||||
|
||||
|
||||
def get_data_for_bio(author_id: str) -> Optional[dict]:
|
||||
async def get_data_for_bio(author_id: str) -> Optional[dict]:
|
||||
|
||||
display_name = _fetch_author_display_name(author_id)
|
||||
display_name = await _fetch_author_display_name(author_id)
|
||||
if display_name is None:
|
||||
return None
|
||||
|
||||
works, top_topics = _fetch_works_and_topics(author_id)
|
||||
works, top_topics = await _fetch_works_and_topics(author_id)
|
||||
papers = _build_papers(works)
|
||||
|
||||
author_data = {
|
||||
@@ -399,9 +404,9 @@ def get_data_for_bio(author_id: str) -> Optional[dict]:
|
||||
return author_data
|
||||
|
||||
|
||||
def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> str:
|
||||
async def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> str:
|
||||
start_time = time.time()
|
||||
author_data = get_data_for_bio(author_id)
|
||||
author_data = await get_data_for_bio(author_id)
|
||||
if author_data is None:
|
||||
return "No person found."
|
||||
|
||||
@@ -430,27 +435,23 @@ def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> s
|
||||
return bio
|
||||
|
||||
|
||||
def get_person_by_id(
|
||||
async def get_person_by_id(
|
||||
author_id: str, include: Optional[str] = None
|
||||
) -> CustomAuthorsListResponse:
|
||||
source = include.split(",") if include else None
|
||||
|
||||
try:
|
||||
hit = elasticsearch.get(
|
||||
hit = await elasticsearch.get(
|
||||
index="openalex-authors",
|
||||
doc_id=author_id,
|
||||
source=source,
|
||||
)
|
||||
except NotFoundError:
|
||||
raise HTTPException(
|
||||
status_code=404, detail=f"Person with id {author_id} not found"
|
||||
)
|
||||
except ApiError as e:
|
||||
raise HTTPException(status_code=500, detail=f"Elasticsearch error: {str(e)}")
|
||||
except NotFoundException as e:
|
||||
raise NotFoundException(f"Person with id {author_id} not found") from e
|
||||
|
||||
author = util.get_persons_data(hit)
|
||||
start_time = time.time()
|
||||
career_metrics = get_career_metrics_for_author(author_id)
|
||||
career_metrics = await get_career_metrics_for_author(author_id)
|
||||
elapsed_time = time.time() - start_time
|
||||
|
||||
logger.info(
|
||||
@@ -465,14 +466,14 @@ def get_person_by_id(
|
||||
return CustomAuthorsListResponse(results=[custom_author])
|
||||
|
||||
|
||||
def search_persons_by_name(
|
||||
async def search_persons_by_name(
|
||||
author_name: str,
|
||||
limit: Optional[int] = 10,
|
||||
page_offset: Optional[int] = 0,
|
||||
include: Optional[str] = None,
|
||||
) -> AuthorsListResponse:
|
||||
if not author_name:
|
||||
raise HTTPException(status_code=400, detail="name must be provided")
|
||||
raise BadRequestException("name must be provided")
|
||||
search_query = {
|
||||
"bool": {
|
||||
"should": [
|
||||
@@ -495,7 +496,7 @@ def search_persons_by_name(
|
||||
}
|
||||
}
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="openalex-authors",
|
||||
query=search_query,
|
||||
offset=page_offset,
|
||||
@@ -504,10 +505,8 @@ def search_persons_by_name(
|
||||
track_total_hits=True,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
|
||||
)
|
||||
except ElasticsearchException as e:
|
||||
raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e
|
||||
total_count = response.get("hits", {}).get("total", {}).get("value", 0)
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
|
||||
@@ -518,11 +517,11 @@ def search_persons_by_name(
|
||||
)
|
||||
|
||||
|
||||
def search_persons_autocomplete(
|
||||
async def search_persons_autocomplete(
|
||||
author_name: str, limit: Optional[int] = 5, include: Optional[str] = None
|
||||
) -> AuthorsListResponse:
|
||||
if not author_name:
|
||||
raise HTTPException(status_code=400, detail="name must be provided")
|
||||
raise BadRequestException("name must be provided")
|
||||
search_query = {
|
||||
"function_score": {
|
||||
"query": {
|
||||
@@ -555,11 +554,9 @@ def search_persons_autocomplete(
|
||||
"collapse": collapse,
|
||||
}
|
||||
try:
|
||||
response = elasticsearch.search(index="openalex-authors", body=body)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
|
||||
)
|
||||
response = await elasticsearch.search(index="openalex-authors", body=body)
|
||||
except ElasticsearchException as e:
|
||||
raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e
|
||||
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
|
||||
@@ -587,7 +584,7 @@ def search_persons_autocomplete(
|
||||
return AuthorsListResponse(results=persons)
|
||||
|
||||
|
||||
def search_persons_by_institution(
|
||||
async def search_persons_by_institution(
|
||||
institution_name: str,
|
||||
limit: Optional[int] = 10,
|
||||
page_offset: Optional[int] = 0,
|
||||
@@ -595,7 +592,7 @@ def search_persons_by_institution(
|
||||
) -> AuthorsListResponse:
|
||||
|
||||
if not institution_name:
|
||||
raise HTTPException(status_code=400, detail="institution_name must be provided")
|
||||
raise BadRequestException("institution_name must be provided")
|
||||
|
||||
search_query = {
|
||||
"nested": {
|
||||
@@ -614,7 +611,7 @@ def search_persons_by_institution(
|
||||
}
|
||||
}
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="openalex-authors",
|
||||
query=search_query,
|
||||
source=include.split(",") if include else True,
|
||||
@@ -624,10 +621,8 @@ def search_persons_by_institution(
|
||||
track_total_hits=True,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
|
||||
)
|
||||
except ElasticsearchException as e:
|
||||
raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e
|
||||
total_count = response.get("hits", {}).get("total", {}).get("value", 0)
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
persons = [util.get_persons_data(hit) for hit in hits]
|
||||
@@ -679,7 +674,7 @@ def _enrich_author_data(author_data) -> Optional[CustomAuthor]:
|
||||
return author
|
||||
|
||||
|
||||
def advanced_search_persons(
|
||||
async def advanced_search_persons(
|
||||
query: Optional[str] = None,
|
||||
institution_name: Optional[str] = None,
|
||||
sort_by: Optional[str] = None,
|
||||
@@ -707,39 +702,20 @@ def advanced_search_persons(
|
||||
filter_mode=filter_mode,
|
||||
filter_year=filter_year,
|
||||
)
|
||||
response_dict = elasticsearch.search(
|
||||
response_dict = await elasticsearch.search(
|
||||
index=INDEX_NAME,
|
||||
body=query_body,
|
||||
)
|
||||
except httpx.HTTPStatusError as e:
|
||||
if e.response.status_code == 404:
|
||||
logger.warning(f"Elasticsearch index '{INDEX_NAME}' not found.")
|
||||
return CustomAuthorsListResponse(
|
||||
results=[], meta=Meta(count=0, page=page, per_page=page_size)
|
||||
)
|
||||
elif e.response.status_code == 400:
|
||||
logger.error(f"Elasticsearch request error: {str(e)}")
|
||||
raise HTTPException(
|
||||
status_code=400, detail=f"Elasticsearch request error: {str(e)}"
|
||||
)
|
||||
else:
|
||||
logger.error(f"Elasticsearch API error: {str(e)}")
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"Elasticsearch API error: {str(e)}"
|
||||
)
|
||||
except httpx.RequestError as e:
|
||||
logger.error(f"Elasticsearch connection/request error: {str(e)}")
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"Elasticsearch connection/request error: {str(e)}"
|
||||
except ElasticsearchNotFoundException:
|
||||
logger.warning(f"Elasticsearch index '{INDEX_NAME}' not found.")
|
||||
return CustomAuthorsListResponse(
|
||||
results=[], meta=Meta(count=0, page=page, per_page=page_size)
|
||||
)
|
||||
except Exception as e:
|
||||
except ElasticsearchException as e:
|
||||
logger.error(f"Elasticsearch search failed: {str(e)}")
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
|
||||
)
|
||||
raise
|
||||
total_count = response_dict.get("hits", {}).get("total", {}).get("value", 0)
|
||||
hits = response_dict.get("hits", {}).get("hits", [])
|
||||
total_count = response_dict.get("hits", {}).get("total", {}).get("value", 0)
|
||||
|
||||
include_career_metrics = include is None or "career_metrics" in include
|
||||
results = []
|
||||
@@ -749,7 +725,7 @@ def advanced_search_persons(
|
||||
if custom_author:
|
||||
if include_career_metrics:
|
||||
start_time = time.time()
|
||||
custom_author.career_metrics = get_career_metrics_for_author(
|
||||
custom_author.career_metrics = await get_career_metrics_for_author(
|
||||
custom_author.id
|
||||
)
|
||||
elapsed_time = time.time() - start_time
|
||||
|
||||
@@ -29,7 +29,7 @@ router = APIRouter(
|
||||
summary="Searches for persons by ID or name.",
|
||||
response_model_exclude_none=True,
|
||||
)
|
||||
def search_persons(
|
||||
async def search_persons(
|
||||
author_id: Annotated[
|
||||
str, Query(description="OpenAlex author ID (e.g., A5093075883)")
|
||||
] = None,
|
||||
@@ -53,7 +53,7 @@ def search_persons(
|
||||
if include
|
||||
else None
|
||||
)
|
||||
return logic.search_persons(author_id, query)
|
||||
return await logic.search_persons(author_id, query)
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -62,7 +62,7 @@ def search_persons(
|
||||
response_model=model.PersonBio,
|
||||
summary="Generates a bio for a person by author ID.",
|
||||
)
|
||||
def generate_person_bio(
|
||||
async def generate_person_bio(
|
||||
author_id: Annotated[
|
||||
str, Query(description="OpenAlex author ID (e.g., A5093075883)")
|
||||
],
|
||||
@@ -79,7 +79,7 @@ def generate_person_bio(
|
||||
if include
|
||||
else None
|
||||
)
|
||||
bio = logic.generate_person_bio(author_id, include_set)
|
||||
bio = await logic.generate_person_bio(author_id, include_set)
|
||||
return model.PersonBio(bio=bio)
|
||||
|
||||
@router.get(
|
||||
@@ -89,7 +89,7 @@ def generate_person_bio(
|
||||
summary="Searches for person by ID.",
|
||||
tags=["Persons"],
|
||||
)
|
||||
def get_person_by_id(
|
||||
async def get_person_by_id(
|
||||
id: Annotated[
|
||||
str, Path(description="OpenAlex author ID", examples=["A5093075883"])
|
||||
],
|
||||
@@ -104,7 +104,7 @@ def get_person_by_id(
|
||||
),
|
||||
] = None,
|
||||
):
|
||||
return logic.get_person_by_id(author_id=id, include=include)
|
||||
return await logic.get_person_by_id(author_id=id, include=include)
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -114,7 +114,7 @@ def get_person_by_id(
|
||||
summary="Searches for person by name.",
|
||||
tags=["Persons"],
|
||||
)
|
||||
def search_persons_by_name(
|
||||
async def search_persons_by_name(
|
||||
author_name: Annotated[str, Query(description="Authors name (e.g., Arman Arzani)")],
|
||||
include: Annotated[
|
||||
Optional[str],
|
||||
@@ -129,24 +129,25 @@ def search_persons_by_name(
|
||||
limit:Annotated[Optional[int], Query(description=("Limit of search page results"),example ="2")]= None,
|
||||
page_offset : Annotated[Optional[int], Query(description=("Offset of the result page"),example="2")] = None,
|
||||
):
|
||||
return logic.search_persons_by_name(author_name=author_name, include=include,page_offset=page_offset,limit=limit)
|
||||
return await logic.search_persons_by_name(author_name=author_name, include=include, page_offset=page_offset, limit=limit)
|
||||
|
||||
|
||||
@router.get(
|
||||
'/persons/autocomplete',
|
||||
operation_id='searchPersonsAutocomplete',
|
||||
response_model=AuthorsListResponse,
|
||||
summary='Searches for person by name.',
|
||||
tags=[ 'Persons' ])
|
||||
def search_persons_autocomplete(
|
||||
tags=['Persons'])
|
||||
async def search_persons_autocomplete(
|
||||
author_name: Annotated[str, Query(description="Authors name (e.g., Arman Arzani)")],
|
||||
include : Annotated[Optional[str], Query(
|
||||
description=(
|
||||
"Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
|
||||
"last_known_institutions, ..."
|
||||
),
|
||||
example="topics_full,topic_share"
|
||||
)]):
|
||||
return logic.search_persons_autocomplete(author_name=author_name,include=include)
|
||||
description=(
|
||||
"Which data do we require? include tags: topics_full, topic_share, summary_stats, ids, "
|
||||
"last_known_institutions, ..."
|
||||
),
|
||||
example="topics_full,topic_share"
|
||||
)]):
|
||||
return await logic.search_persons_autocomplete(author_name=author_name, include=include)
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -156,7 +157,7 @@ def search_persons_autocomplete(
|
||||
summary="Searches for persons by institution name.",
|
||||
tags=["Persons"],
|
||||
)
|
||||
def search_persons_by_institution(
|
||||
async def search_persons_by_institution(
|
||||
institution_name: Annotated[
|
||||
str, Query(description="Institution name (e.g., MIT, Oxford University)")
|
||||
],
|
||||
@@ -173,7 +174,8 @@ def search_persons_by_institution(
|
||||
limit:Annotated[Optional[int], Query(description=("Limit of search page results"),example ="2")]= None,
|
||||
page_offset : Annotated[Optional[int], Query(description=("Offset of the result page"),example="2")] = None,
|
||||
):
|
||||
return logic.search_persons_by_institution(institution_name, include=include,page_offset=page_offset,limit=limit)
|
||||
return await logic.search_persons_by_institution(institution_name, include=include, page_offset=page_offset, limit=limit)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/persons/search-list",
|
||||
@@ -183,7 +185,7 @@ def search_persons_by_institution(
|
||||
response_model_exclude_none=True,
|
||||
tags=["Persons"],
|
||||
)
|
||||
def search_persons_list(
|
||||
async def search_persons_list(
|
||||
query: Annotated[
|
||||
Optional[str], Query(description="Search query (e.g., Arman AND Arzani)")
|
||||
] = None,
|
||||
@@ -227,7 +229,7 @@ def search_persons_list(
|
||||
if include
|
||||
else None
|
||||
)
|
||||
return logic.advanced_search_persons(
|
||||
return await logic.advanced_search_persons(
|
||||
query=query,
|
||||
institution_name=institution_name,
|
||||
sort_by=sort_by,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import logging
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
import asyncio
|
||||
from typing import Any, Dict, List, Optional, Union
|
||||
|
||||
from inse.config import get_settings
|
||||
@@ -85,7 +85,7 @@ _HEU_ENTITY_CONFIGS = [
|
||||
{"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS, "model_class": HEULegalBasis},
|
||||
]
|
||||
|
||||
def get_enriched_cordis_project_by_id(
|
||||
async def get_enriched_cordis_project_by_id(
|
||||
project_id: str,
|
||||
) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]:
|
||||
"""
|
||||
@@ -102,7 +102,7 @@ def get_enriched_cordis_project_by_id(
|
||||
|
||||
query = {"bool": {"filter": [{"term": {"id": project_id}}]}}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
query=query,
|
||||
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
|
||||
cluster=ESCluster.INSE,
|
||||
@@ -131,7 +131,7 @@ def get_enriched_cordis_project_by_id(
|
||||
logger.warning(f"Unknown programme type for index: {index}")
|
||||
return CordisEuProject.model_validate(source)
|
||||
|
||||
return enricher(project_id, source)
|
||||
return await enricher(project_id, source)
|
||||
|
||||
# helpers
|
||||
def _determine_program_type_from_index(index: str) -> str:
|
||||
@@ -146,10 +146,9 @@ def _determine_program_type_from_index(index: str) -> str:
|
||||
return "unknown"
|
||||
|
||||
|
||||
def _fetch_related_entities_parallel(
|
||||
async def _fetch_related_entities_parallel(
|
||||
project_id: str,
|
||||
entity_configs: List[Dict[str, Any]],
|
||||
max_workers: int = 8,
|
||||
) -> Dict[str, List[Any]]:
|
||||
"""
|
||||
Fetches all related entity types for a project in parallel.
|
||||
@@ -157,35 +156,35 @@ def _fetch_related_entities_parallel(
|
||||
Args:
|
||||
project_id: The project ID to fetch entities for.
|
||||
entity_configs: List of dicts with keys 'key', 'index_pattern', 'model_class'.
|
||||
max_workers: Maximum number of concurrent Elasticsearch requests.
|
||||
|
||||
Returns:
|
||||
Dictionary mapping each config 'key' to a list of validated entities.
|
||||
"""
|
||||
def _fetch_one(config: Dict[str, Any]):
|
||||
entities = _fetch_related_entities(
|
||||
async def _fetch_one(config: Dict[str, Any]):
|
||||
entities = await _fetch_related_entities(
|
||||
project_ids=[project_id],
|
||||
index_pattern=config["index_pattern"],
|
||||
model_class=config["model_class"],
|
||||
)
|
||||
return config["key"], entities.get(project_id, [])
|
||||
|
||||
tasks = [_fetch_one(cfg) for cfg in entity_configs]
|
||||
completed = await asyncio.gather(*tasks, return_exceptions=True)
|
||||
|
||||
results: Dict[str, List[Any]] = {}
|
||||
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
||||
futures = {executor.submit(_fetch_one, cfg): cfg["key"] for cfg in entity_configs}
|
||||
for future in as_completed(futures):
|
||||
try:
|
||||
key, data = future.result()
|
||||
results[key] = data
|
||||
except Exception as e:
|
||||
key = futures[future]
|
||||
logger.error(f"Parallel fetch failed for '{key}': {e}")
|
||||
results[key] = []
|
||||
for cfg, res in zip(entity_configs, completed):
|
||||
key = cfg["key"]
|
||||
if isinstance(res, Exception):
|
||||
logger.error(f"Parallel fetch failed for '{key}': {res}")
|
||||
results[key] = []
|
||||
else:
|
||||
key_name, data = res
|
||||
results[key_name] = data
|
||||
|
||||
return results
|
||||
|
||||
|
||||
def _fetch_related_entities(
|
||||
async def _fetch_related_entities(
|
||||
project_ids: List[str],
|
||||
index_pattern: str,
|
||||
model_class: Any,
|
||||
@@ -204,7 +203,7 @@ def _fetch_related_entities(
|
||||
query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
query=query,
|
||||
index=index_pattern,
|
||||
cluster=ESCluster.INSE,
|
||||
@@ -234,7 +233,7 @@ def _fetch_related_entities(
|
||||
return grouped
|
||||
|
||||
|
||||
def _enrich_fp7_project(
|
||||
async def _enrich_fp7_project(
|
||||
project_id: str,
|
||||
project_source: Dict[str, Any],
|
||||
) -> Optional[Fp7ProjectDetails]:
|
||||
@@ -245,12 +244,12 @@ def _enrich_fp7_project(
|
||||
logger.error(f"Failed to validate FP7 project {project_id}: {e}")
|
||||
return None
|
||||
|
||||
related = _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS)
|
||||
related = await _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS)
|
||||
|
||||
return Fp7ProjectDetails.from_project_with_relations(project=project, **related)
|
||||
|
||||
|
||||
def _enrich_h2020_project(
|
||||
async def _enrich_h2020_project(
|
||||
project_id: str,
|
||||
project_source: Dict[str, Any],
|
||||
) -> Optional[H2020ProjectDetails]:
|
||||
@@ -261,12 +260,12 @@ def _enrich_h2020_project(
|
||||
logger.error(f"Failed to validate H2020 project {project_id}: {e}")
|
||||
return None
|
||||
|
||||
related = _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS)
|
||||
related = await _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS)
|
||||
|
||||
return H2020ProjectDetails.from_project_with_relations(project=project, **related)
|
||||
|
||||
|
||||
def _enrich_heu_project(
|
||||
async def _enrich_heu_project(
|
||||
project_id: str,
|
||||
project_source: Dict[str, Any],
|
||||
) -> Optional[HEUProjectDetails]:
|
||||
@@ -277,6 +276,6 @@ def _enrich_heu_project(
|
||||
logger.error(f"Failed to validate Horizon Europe project {project_id}: {e}")
|
||||
return None
|
||||
|
||||
related = _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS)
|
||||
related = await _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS)
|
||||
|
||||
return HEUProjectDetails.from_project_with_relations(project=project, **related)
|
||||
@@ -101,7 +101,7 @@ DFG_PERSON_FIELDS: List[str] = [
|
||||
# BUND
|
||||
|
||||
|
||||
def search_bund_projects(
|
||||
async def search_bund_projects(
|
||||
filter_properties: ProjectsFilteringProperties,
|
||||
institution_names: List[str] = [],
|
||||
) -> BundProjectPage:
|
||||
@@ -160,7 +160,7 @@ def search_bund_projects(
|
||||
}
|
||||
]
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_BUND_V1,
|
||||
query=query,
|
||||
sort=sort,
|
||||
@@ -194,7 +194,7 @@ def _complete_response_to_bund_project_page(
|
||||
return BundProjectPage(elements=elements, total=total_hits, page=page, size=size)
|
||||
|
||||
|
||||
def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]:
|
||||
async def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]:
|
||||
"""Decodes project_id and fetches the details of a single Bund project based on its project ID.
|
||||
|
||||
Args:
|
||||
@@ -207,7 +207,7 @@ def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]:
|
||||
decoded_id = urllib.parse.unquote(project_id)
|
||||
query = {"term": {"Förderkennzeichen.keyword": {"value": decoded_id}}}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_BUND_V1,
|
||||
query=query,
|
||||
size=1,
|
||||
@@ -224,7 +224,7 @@ def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]:
|
||||
# EU
|
||||
|
||||
|
||||
def get_eu_organization_project_contributions(
|
||||
async def get_eu_organization_project_contributions(
|
||||
organization_names: List[str],
|
||||
projects_filtering_properties: ProjectsFilteringProperties,
|
||||
) -> EuOrganizationProjectSummaryPage:
|
||||
@@ -241,11 +241,11 @@ def get_eu_organization_project_contributions(
|
||||
# For FUNDING_AMOUNT before on the organization project contributions
|
||||
# For the rest after the contributions are known on the real projects
|
||||
|
||||
organization_project_contributions = get_eu_organization_contributions(
|
||||
organization_project_contributions = await get_eu_organization_contributions(
|
||||
organization_names=organization_names,
|
||||
)
|
||||
|
||||
total_projects, projects = get_eu_organization_projects(
|
||||
total_projects, projects = await get_eu_organization_projects(
|
||||
project_contributions=list(organization_project_contributions.values()),
|
||||
projects_filtering_properties=projects_filtering_properties,
|
||||
)
|
||||
@@ -271,7 +271,7 @@ def get_eu_organization_project_contributions(
|
||||
)
|
||||
|
||||
|
||||
def get_eu_organization_contributions(
|
||||
async def get_eu_organization_contributions(
|
||||
organization_names: List[str],
|
||||
) -> Dict[str, EuOrganizationShort]:
|
||||
"""Fetches the contributions of EU organizations to projects based on the provided organization names.
|
||||
@@ -293,7 +293,7 @@ def get_eu_organization_contributions(
|
||||
}
|
||||
}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
|
||||
cluster=ESCluster.INSE,
|
||||
source=source,
|
||||
@@ -343,7 +343,7 @@ def _process_organization_project_contributions(
|
||||
return project_contributions
|
||||
|
||||
|
||||
def get_eu_organization_projects(
|
||||
async def get_eu_organization_projects(
|
||||
project_contributions: List[EuOrganizationShort],
|
||||
projects_filtering_properties: ProjectsFilteringProperties,
|
||||
) -> Tuple[int, Dict[str, EuProjectShort]]:
|
||||
@@ -388,7 +388,7 @@ def get_eu_organization_projects(
|
||||
|
||||
# Project contributions have been filtered before based on ecContribution
|
||||
if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
|
||||
cluster=ESCluster.INSE,
|
||||
source=source,
|
||||
@@ -396,7 +396,7 @@ def get_eu_organization_projects(
|
||||
size=10000,
|
||||
)
|
||||
else:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
|
||||
cluster=ESCluster.INSE,
|
||||
source=source,
|
||||
@@ -496,7 +496,7 @@ def _get_raw_doi(doi: str) -> str:
|
||||
return doi
|
||||
|
||||
|
||||
def get_cordis_eu_publications_by_dois(dois: List[str]):
|
||||
async def get_cordis_eu_publications_by_dois(dois: List[str]):
|
||||
"""Retrieves Cordis EU publications associated with the given list of DOIs.
|
||||
|
||||
Args:
|
||||
@@ -508,7 +508,7 @@ def get_cordis_eu_publications_by_dois(dois: List[str]):
|
||||
raw_dois = [_get_raw_doi(doi) for doi in dois]
|
||||
query = {"bool": {"filter": [{"terms": {"qaProcessedDoi": raw_dois}}]}}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
query=query,
|
||||
index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
|
||||
cluster=ESCluster.INSE,
|
||||
@@ -519,7 +519,7 @@ def get_cordis_eu_publications_by_dois(dois: List[str]):
|
||||
return response
|
||||
|
||||
|
||||
def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]:
|
||||
async def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]:
|
||||
"""Retrieves the project IDs of Cordis EU projects associated with the given list of DOIs.
|
||||
|
||||
Args:
|
||||
@@ -528,7 +528,7 @@ def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]:
|
||||
Returns:
|
||||
List[str]: The list of project IDs.
|
||||
"""
|
||||
response = get_cordis_eu_publications_by_dois(dois=dois)
|
||||
response = await get_cordis_eu_publications_by_dois(dois=dois)
|
||||
hits_block = response.get("hits", {})
|
||||
project_ids = set()
|
||||
for hit in hits_block.get("hits", []):
|
||||
@@ -539,12 +539,12 @@ def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]:
|
||||
return list(project_ids)
|
||||
|
||||
|
||||
def get_cordis_eu_projects_by_project_ids(
|
||||
async def get_cordis_eu_projects_by_project_ids(
|
||||
project_ids: List[str],
|
||||
) -> CordisEuProjectPage:
|
||||
query = {"bool": {"filter": [{"terms": {"id": project_ids}}]}}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
query=query,
|
||||
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
|
||||
cluster=ESCluster.INSE,
|
||||
@@ -561,7 +561,7 @@ def get_cordis_eu_projects_by_project_ids(
|
||||
)
|
||||
|
||||
|
||||
def get_eu_cordis_projects_by_id(
|
||||
async def get_eu_cordis_projects_by_id(
|
||||
project_id: str,
|
||||
) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]:
|
||||
"""
|
||||
@@ -573,14 +573,14 @@ def get_eu_cordis_projects_by_id(
|
||||
Returns:
|
||||
The enriched project details, or None if not found
|
||||
"""
|
||||
enriched_project = get_enriched_cordis_project_by_id(
|
||||
enriched_project = await get_enriched_cordis_project_by_id(
|
||||
project_id=project_id
|
||||
)
|
||||
return enriched_project
|
||||
# DFG
|
||||
|
||||
|
||||
def search_dfg_projects(
|
||||
async def search_dfg_projects(
|
||||
page: int,
|
||||
size: int,
|
||||
names: Optional[List[str]] = None,
|
||||
@@ -750,7 +750,7 @@ def search_dfg_projects(
|
||||
|
||||
body["sort"] = [sort_config]
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_DFG_ALL,
|
||||
body=body,
|
||||
)
|
||||
@@ -776,7 +776,7 @@ def _complete_response_to_dfg_project_page(
|
||||
return DfgProjectPage(elements=elements, total=total_hits, page=page, size=size)
|
||||
|
||||
|
||||
def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
|
||||
async def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
|
||||
"""Fetches the details of a single DFG project based on its project ID.
|
||||
|
||||
Args:
|
||||
@@ -787,7 +787,7 @@ def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
|
||||
"""
|
||||
query = {"ids": {"values": [project_id]}}
|
||||
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_DFG_ALL,
|
||||
query=query,
|
||||
size=1,
|
||||
@@ -804,7 +804,7 @@ def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
|
||||
# All
|
||||
|
||||
|
||||
def search_all_projects(
|
||||
async def search_all_projects(
|
||||
projects_filtering_properties: ProjectsFilteringProperties,
|
||||
selected_project_types: Optional[Set[ProjectType]] = None,
|
||||
) -> FundingProjectPage:
|
||||
@@ -882,7 +882,7 @@ def search_all_projects(
|
||||
size = projects_filtering_properties.size
|
||||
page = projects_filtering_properties.page
|
||||
offset = page * size
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=index,
|
||||
size=size,
|
||||
offset=offset,
|
||||
|
||||
@@ -51,13 +51,13 @@ router = APIRouter(prefix="/api/projects", tags=[Tags.PROJECTS])
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
def get_eu_projects_for_author(
|
||||
async def get_eu_projects_for_author(
|
||||
raw_oa_author_id: Annotated[str, Path(description="The author ID to filter by.")],
|
||||
) -> CordisEuProjectPage:
|
||||
logger.debug(
|
||||
f"Received request to get EU projects for author_id={raw_oa_author_id}"
|
||||
)
|
||||
return projects_service.search_cordis_eu_projects_for_author_id(
|
||||
return await projects_service.search_cordis_eu_projects_for_author_id(
|
||||
raw_oa_author_id=raw_oa_author_id,
|
||||
)
|
||||
|
||||
@@ -85,7 +85,7 @@ async def search_bund_projects(
|
||||
Body(description="The filtering properties for the projects search."),
|
||||
],
|
||||
) -> BundProjectPage:
|
||||
return projects_service.search_bund_projects(
|
||||
return await projects_service.search_bund_projects(
|
||||
institutions_search_client=institutions_search_client,
|
||||
filtering_properties=filtering_properties,
|
||||
)
|
||||
@@ -105,11 +105,11 @@ async def search_bund_projects(
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
def get_single_dfg_project(
|
||||
async def get_single_dfg_project(
|
||||
id: Annotated[str, Path(description="The ID of the DFG project to retrieve.")],
|
||||
) -> DfgProjectDetails:
|
||||
logger.debug(f"Received request to get single DFG project for id={id}")
|
||||
return projects_service.get_single_dfg_project(
|
||||
return await projects_service.get_single_dfg_project(
|
||||
project_id=id,
|
||||
)
|
||||
|
||||
@@ -128,11 +128,11 @@ def get_single_dfg_project(
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
def get_single_bund_project(
|
||||
async def get_single_bund_project(
|
||||
id: Annotated[str, Path(description="The ID of the BUND project to retrieve.")],
|
||||
) -> BundProjectDetails:
|
||||
logger.debug(f"Received request to get single BUND project for id={id}")
|
||||
return projects_service.get_single_bund_project(
|
||||
return await projects_service.get_single_bund_project(
|
||||
project_id=id,
|
||||
)
|
||||
|
||||
@@ -157,9 +157,7 @@ def get_single_bund_project(
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def get_single_eu_cordis_project(
|
||||
async def get_single_eu_cordis_project(
|
||||
id: Annotated[str, Path(description="The ID of the EU Cordis project to retrieve.")],
|
||||
) -> EuCordisProjectResponse:
|
||||
"""
|
||||
@@ -170,7 +168,7 @@ def get_single_eu_cordis_project(
|
||||
|
||||
try:
|
||||
# Get the project from the service
|
||||
project = projects_service.get_single_eu_cordis_project(project_id=id)
|
||||
project = await projects_service.get_single_eu_cordis_project(project_id=id)
|
||||
|
||||
# Check if project exists
|
||||
if project is None:
|
||||
@@ -216,6 +214,7 @@ def get_single_eu_cordis_project(
|
||||
error=f"Internal server error: {str(e)}"
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/institution/bund/funding-over-time",
|
||||
summary="Get funding over time for bund projects.",
|
||||
@@ -230,7 +229,7 @@ def get_single_eu_cordis_project(
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
def get_institution_bund_projects_funding_over_time(
|
||||
async def get_institution_bund_projects_funding_over_time(
|
||||
institutions_search_client: Annotated[
|
||||
InstitutionsSearchClient, Depends(get_institutions_search_client)
|
||||
],
|
||||
@@ -238,7 +237,7 @@ def get_institution_bund_projects_funding_over_time(
|
||||
str, Query(description="The institution ID to filter by.")
|
||||
],
|
||||
) -> InstitutionFunderSummary:
|
||||
return projects_service.get_institution_bund_projects_funding_over_time(
|
||||
return await projects_service.get_institution_bund_projects_funding_over_time(
|
||||
institutions_search_client=institutions_search_client,
|
||||
raw_oa_institution_id=raw_oa_institution_id,
|
||||
)
|
||||
@@ -267,7 +266,7 @@ async def search_cordis_eu_projects(
|
||||
Body(description="The filtering properties for the projects search."),
|
||||
],
|
||||
) -> EuOrganizationProjectSummaryPage:
|
||||
return projects_service.search_cordis_eu_projects(
|
||||
return await projects_service.search_cordis_eu_projects(
|
||||
institutions_search_client=institutions_search_client,
|
||||
projects_filtering_properties=projects_filtering_properties,
|
||||
)
|
||||
@@ -359,7 +358,7 @@ async def get_dfg_projects(
|
||||
},
|
||||
response_model_by_alias=False,
|
||||
)
|
||||
def search_projects(
|
||||
async def search_projects(
|
||||
page: Annotated[int, Query(description="The page number.", ge=0)] = 0,
|
||||
size: Annotated[int, Query(description="The page size.", ge=1)] = 10,
|
||||
selected_project_types: Annotated[
|
||||
@@ -378,7 +377,7 @@ def search_projects(
|
||||
SortDirection, Query(description="The sort direction (asc or desc).")
|
||||
] = SortDirection.ASC,
|
||||
) -> FundingProjectPage:
|
||||
return projects_service.search_all_projects(
|
||||
return await projects_service.search_all_projects(
|
||||
page=page,
|
||||
size=size,
|
||||
selected_project_types=selected_project_types,
|
||||
|
||||
@@ -35,7 +35,7 @@ from typing import Union
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def search_all_projects(
|
||||
async def search_all_projects(
|
||||
page: int,
|
||||
size: int,
|
||||
sort_by: ProjectsSortBy,
|
||||
@@ -43,7 +43,7 @@ def search_all_projects(
|
||||
selected_project_types: Optional[Set[ProjectType]] = None,
|
||||
title: Optional[str] = None,
|
||||
) -> FundingProjectPage:
|
||||
return projects_search_client.search_all_projects(
|
||||
return await projects_search_client.search_all_projects(
|
||||
projects_filtering_properties=ProjectsFilteringProperties(
|
||||
project_type=ProjectType.EU, # placeholder, shall be ignored in search_all_projects
|
||||
page=page,
|
||||
@@ -56,7 +56,7 @@ def search_all_projects(
|
||||
)
|
||||
|
||||
|
||||
def search_bund_projects(
|
||||
async def search_bund_projects(
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
filtering_properties: ProjectsFilteringProperties,
|
||||
) -> BundProjectPage:
|
||||
@@ -69,13 +69,13 @@ def search_bund_projects(
|
||||
f"search_bund_projects called with filtering_properties: {filtering_properties}"
|
||||
)
|
||||
|
||||
return get_bund_projects_by_institution_id(
|
||||
return await get_bund_projects_by_institution_id(
|
||||
institutions_search_client=institutions_search_client,
|
||||
filtering_properties=filtering_properties,
|
||||
)
|
||||
|
||||
|
||||
def get_bund_projects_by_institution_id(
|
||||
async def get_bund_projects_by_institution_id(
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
filtering_properties: ProjectsFilteringProperties,
|
||||
) -> BundProjectPage:
|
||||
@@ -93,7 +93,7 @@ def get_bund_projects_by_institution_id(
|
||||
logger.debug(
|
||||
f"get_bund_projects_by_institution_id: Found institution aliases for institution_id={filtering_properties.raw_oa_institution_id}: {institution_aliases}"
|
||||
)
|
||||
response = projects_search_client.search_bund_projects(
|
||||
response = await projects_search_client.search_bund_projects(
|
||||
institution_names=institution_aliases,
|
||||
filter_properties=filtering_properties,
|
||||
)
|
||||
@@ -101,7 +101,7 @@ def get_bund_projects_by_institution_id(
|
||||
return response
|
||||
|
||||
|
||||
def search_cordis_eu_projects(
|
||||
async def search_cordis_eu_projects(
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
projects_filtering_properties: ProjectsFilteringProperties,
|
||||
) -> EuOrganizationProjectSummaryPage:
|
||||
@@ -110,13 +110,13 @@ def search_cordis_eu_projects(
|
||||
f"Invalid project type: {projects_filtering_properties.project_type}. Expected 'eu'."
|
||||
)
|
||||
|
||||
return get_cordis_eu_projects_by_institution_id(
|
||||
return await get_cordis_eu_projects_by_institution_id(
|
||||
institutions_search_client=institutions_search_client,
|
||||
projects_filtering_properties=projects_filtering_properties,
|
||||
)
|
||||
|
||||
|
||||
def get_cordis_eu_projects_by_institution_id(
|
||||
async def get_cordis_eu_projects_by_institution_id(
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
projects_filtering_properties: ProjectsFilteringProperties,
|
||||
) -> EuOrganizationProjectSummaryPage:
|
||||
@@ -137,7 +137,7 @@ def get_cordis_eu_projects_by_institution_id(
|
||||
f"Found institution aliases for institution_id={projects_filtering_properties.raw_oa_institution_id}: {institution_aliases}"
|
||||
)
|
||||
|
||||
page = get_eu_organization_project_contributions(
|
||||
page = await get_eu_organization_project_contributions(
|
||||
organization_names=institution_aliases,
|
||||
projects_filtering_properties=projects_filtering_properties,
|
||||
)
|
||||
@@ -158,7 +158,7 @@ async def get_dfg_projects_by_author_id(
|
||||
logger.debug(
|
||||
f"Fetching DFG projects for author_id={author_id}, topic={topic}, page={page}, size={size}, sort_by={sort_by}, sort_direction={sort_direction}"
|
||||
)
|
||||
name = get_author_name_by_id(author_id)
|
||||
name = await get_author_name_by_id(author_id)
|
||||
if not name:
|
||||
logger.debug(f"No author name found for author_id={author_id}")
|
||||
raise NotFoundException(
|
||||
@@ -166,7 +166,7 @@ async def get_dfg_projects_by_author_id(
|
||||
)
|
||||
logger.debug(f"Found author name for author_id={author_id}: {name}")
|
||||
|
||||
response = projects_search_client.search_dfg_projects(
|
||||
response = await projects_search_client.search_dfg_projects(
|
||||
page=page,
|
||||
size=size,
|
||||
names=[name],
|
||||
@@ -186,7 +186,7 @@ async def get_institution_cordis_eu_projects_funding_over_time(
|
||||
raw_oa_institution_id
|
||||
)
|
||||
)
|
||||
page = get_eu_organization_project_contributions(
|
||||
page = await get_eu_organization_project_contributions(
|
||||
organization_names=institution_aliases,
|
||||
projects_filtering_properties=ProjectsFilteringProperties(
|
||||
project_type=ProjectType.EU,
|
||||
@@ -204,7 +204,7 @@ async def get_institution_cordis_eu_projects_funding_over_time(
|
||||
)
|
||||
|
||||
|
||||
def get_institution_bund_projects_funding_over_time(
|
||||
async def get_institution_bund_projects_funding_over_time(
|
||||
institutions_search_client: InstitutionsSearchClient,
|
||||
raw_oa_institution_id: str,
|
||||
) -> InstitutionFunderSummary:
|
||||
@@ -219,7 +219,7 @@ def get_institution_bund_projects_funding_over_time(
|
||||
logger.debug(
|
||||
f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}"
|
||||
)
|
||||
response = projects_search_client.search_bund_projects(
|
||||
response = await projects_search_client.search_bund_projects(
|
||||
filter_properties=ProjectsFilteringProperties(
|
||||
project_type=ProjectType.BUND,
|
||||
page=0,
|
||||
@@ -305,38 +305,40 @@ def _calculate_funding_over_time(
|
||||
)
|
||||
|
||||
|
||||
def get_single_dfg_project(
|
||||
async def get_single_dfg_project(
|
||||
project_id: str,
|
||||
) -> DfgProjectDetails:
|
||||
logger.debug(f"Fetching single DFG project for id={project_id}")
|
||||
|
||||
project = projects_search_client.get_dfg_project_by_id(project_id)
|
||||
project = await projects_search_client.get_dfg_project_by_id(project_id)
|
||||
if not project:
|
||||
raise NotFoundException(f"DFG project with id {project_id} not found")
|
||||
return project
|
||||
|
||||
|
||||
def get_single_bund_project(
|
||||
async def get_single_bund_project(
|
||||
project_id: str,
|
||||
) -> BundProjectDetails:
|
||||
logger.debug(f"Fetching single BUND project for id={project_id}")
|
||||
|
||||
project = projects_search_client.get_bund_project_by_id(project_id)
|
||||
project = await projects_search_client.get_bund_project_by_id(project_id)
|
||||
if not project:
|
||||
raise NotFoundException(f"BUND project with id {project_id} not found")
|
||||
return project
|
||||
|
||||
def get_single_eu_cordis_project(
|
||||
|
||||
async def get_single_eu_cordis_project(
|
||||
project_id: str,
|
||||
) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]:
|
||||
logger.debug(f"Fetching single EU Cordis project for id={project_id}")
|
||||
|
||||
project = projects_search_client.get_eu_cordis_projects_by_id(project_id)
|
||||
project = await projects_search_client.get_eu_cordis_projects_by_id(project_id)
|
||||
if not project:
|
||||
raise NotFoundException(f"EU project with id {project_id} not found")
|
||||
return project
|
||||
|
||||
def search_cordis_eu_projects_for_author_id(
|
||||
|
||||
async def search_cordis_eu_projects_for_author_id(
|
||||
raw_oa_author_id: str,
|
||||
) -> CordisEuProjectPage:
|
||||
|
||||
@@ -345,17 +347,17 @@ def search_cordis_eu_projects_for_author_id(
|
||||
# 2. CORDIS EU projects have associated publications with DOIs
|
||||
# 3. Matching DOIs of author publications with DOIs of CORDIS EU project publications -> projects with associated publications of the author
|
||||
|
||||
dois = get_publication_dois_of_author(raw_oa_author_id=raw_oa_author_id)
|
||||
dois = await get_publication_dois_of_author(raw_oa_author_id=raw_oa_author_id)
|
||||
|
||||
logger.debug(f"Found DOIs for author_id={raw_oa_author_id}: {dois}")
|
||||
|
||||
project_ids = projects_search_client.get_cordis_eu_project_ids_by_dois(dois=dois)
|
||||
project_ids = await projects_search_client.get_cordis_eu_project_ids_by_dois(dois=dois)
|
||||
|
||||
logger.debug(
|
||||
f"Found project IDs {project_ids} for author_id={raw_oa_author_id} and dois={dois}"
|
||||
)
|
||||
|
||||
funding_project_page = projects_search_client.get_cordis_eu_projects_by_project_ids(
|
||||
funding_project_page = await projects_search_client.get_cordis_eu_projects_by_project_ids(
|
||||
project_ids=project_ids
|
||||
)
|
||||
|
||||
|
||||
@@ -8,10 +8,8 @@ from copy import deepcopy
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from pydantic import ValidationError
|
||||
from starlette.status import HTTP_400_BAD_REQUEST
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||
from inse.exceptions import UpstreamAPIException, BadRequestException, ElasticsearchException
|
||||
|
||||
from inse.models.openalex.autocomplete_response import AutocompleteResponse
|
||||
from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta
|
||||
@@ -38,10 +36,7 @@ async def list_topics(
|
||||
client: OpenAlexTopicsClient | None = None,
|
||||
) -> TopicsListResponse:
|
||||
if sample is not None and (sort or page not in (None, 1)):
|
||||
raise HTTPException(
|
||||
status_code=HTTP_400_BAD_REQUEST,
|
||||
detail="sample cannot be combined with sort or page.",
|
||||
)
|
||||
raise BadRequestException("sample cannot be combined with sort or page.")
|
||||
|
||||
openalex_client = client or OpenAlexTopicsClient()
|
||||
|
||||
@@ -66,12 +61,12 @@ async def list_topics(
|
||||
except ValueError:
|
||||
if exc.response.text:
|
||||
detail = exc.response.text
|
||||
raise HTTPException(status_code=status_code, detail=detail) from exc
|
||||
raise UpstreamAPIException(message=detail, status_code=status_code) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex topics request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex topics request failed.",
|
||||
raise UpstreamAPIException(
|
||||
message="OpenAlex topics request failed.",
|
||||
status_code=502,
|
||||
) from exc
|
||||
|
||||
try:
|
||||
@@ -79,9 +74,9 @@ async def list_topics(
|
||||
return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse()
|
||||
except ValidationError as exc:
|
||||
logger.exception("OpenAlex topics response could not be parsed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex topics response could not be parsed.",
|
||||
raise UpstreamAPIException(
|
||||
message="OpenAlex topics response could not be parsed.",
|
||||
status_code=502,
|
||||
) from exc
|
||||
|
||||
|
||||
@@ -282,10 +277,7 @@ async def vector_search_topics(
|
||||
|
||||
except Exception as exc:
|
||||
logger.exception("Failed to load elasticsearch integration.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail=f"Failed to load elasticsearch integration: {exc}"
|
||||
)
|
||||
raise ElasticsearchException(f"Failed to load elasticsearch integration: {exc}") from exc
|
||||
|
||||
# 1. Vectorize query
|
||||
try:
|
||||
@@ -293,10 +285,7 @@ async def vector_search_topics(
|
||||
query_vector = model.encode(query).tolist()
|
||||
except Exception as exc:
|
||||
logger.exception("Failed to encode query text.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail=f"Failed to encode query text: {exc}"
|
||||
)
|
||||
raise ElasticsearchException(f"Failed to encode query text: {exc}") from exc
|
||||
|
||||
# 2. Query Elasticsearch using standard Bool Should hybrid search
|
||||
should_clauses = []
|
||||
@@ -357,17 +346,14 @@ async def vector_search_topics(
|
||||
}
|
||||
|
||||
try:
|
||||
raw_results = elasticsearch.search(
|
||||
raw_results = await elasticsearch.search(
|
||||
index="topicvectors",
|
||||
body=body,
|
||||
cluster="nes"
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.exception("Elasticsearch vector search failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail=f"Elasticsearch vector search failed: {exc}"
|
||||
)
|
||||
logger.exception("Elasticsearch vector search failed with unexpected error.")
|
||||
raise ElasticsearchException(f"Unexpected vector search failure: {exc}") from exc
|
||||
|
||||
# 3. Format result
|
||||
hits = raw_results.get("hits", {}).get("hits", [])
|
||||
@@ -389,8 +375,5 @@ async def vector_search_topics(
|
||||
return TopicsListResponse.from_dict(normalized_data) or TopicsListResponse()
|
||||
except ValidationError as exc:
|
||||
logger.exception("Vector search response could not be parsed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="Vector search response could not be parsed.",
|
||||
) from exc
|
||||
raise ElasticsearchException(f"Vector search response could not be parsed: {exc}") from exc
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from inse.exceptions import BadRequestException
|
||||
|
||||
from inse.topics import logic
|
||||
from inse.topics.search_client import OpenAlexTopicsClient
|
||||
@@ -76,11 +76,9 @@ async def test_list_topics_maps_openalex_response_to_model():
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_rejects_sample_with_sort():
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
with pytest.raises(BadRequestException) as exc_info:
|
||||
await logic.list_topics(sample=10, sort="works_count:desc")
|
||||
|
||||
assert exc_info.value.status_code == 400
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_list_topics_accepts_practical_openalex_type_variants():
|
||||
|
||||
@@ -31,7 +31,7 @@ async def get_ranking_data(topic: ResearchTopic, metric: DashboardMetric) -> Ran
|
||||
|
||||
|
||||
# Fetch top institutions for the topic by works_count
|
||||
res = elasticsearch.search(
|
||||
res = await elasticsearch.search(
|
||||
index="openalex-institutions",
|
||||
query=query,
|
||||
size=10,
|
||||
|
||||
@@ -8,15 +8,14 @@ from typing import Optional
|
||||
from typing import TypeVar
|
||||
from inse.models.openalex import Author
|
||||
from . import model
|
||||
from fastapi import HTTPException
|
||||
from starlette.status import HTTP_404_NOT_FOUND
|
||||
from inse.exceptions import NotFoundException
|
||||
|
||||
T = TypeVar('T')
|
||||
|
||||
def raise_not_found_if_none(value: Optional[T]) -> T:
|
||||
''' Returns the value, if it is set, or raises a 404, if the value is None.'''
|
||||
if value == None:
|
||||
raise HTTPException(HTTP_404_NOT_FOUND)
|
||||
raise NotFoundException("Not found.")
|
||||
else:
|
||||
return value
|
||||
|
||||
|
||||
@@ -9,11 +9,8 @@ from time import time
|
||||
from typing import Any, List
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
from pydantic import ValidationError
|
||||
from starlette.status import HTTP_502_BAD_GATEWAY
|
||||
from starlette.status import HTTP_404_NOT_FOUND
|
||||
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
|
||||
|
||||
from inse import config
|
||||
from inse.integrations import elasticsearch
|
||||
@@ -24,7 +21,7 @@ from inse.models.openalex.meta import Meta
|
||||
from inse.models.openalex.topic_count import TopicCount
|
||||
from inse.models.openalex.topics_by_year import TopicsByYear
|
||||
from inse.models.openalex.topics_by_time import TopicsByTime
|
||||
from .search_client import MissingApiKeyError
|
||||
from inse.exceptions import MissingApiKeyError, ElasticsearchException, UpstreamAPIException
|
||||
from .search_client import OpenAlexWorksSearchClient
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -122,10 +119,10 @@ async def get_primary_topic_counts(
|
||||
author_id: str,
|
||||
client: OpenAlexWorksSearchClient | None = None,
|
||||
) -> List[TopicCount]:
|
||||
topic_counts = _get_primary_topic_counts_from_es(author_id)
|
||||
topic_counts = await _get_primary_topic_counts_from_es(author_id)
|
||||
|
||||
topic_ids = [item["id"] for item in topic_counts if item["id"]]
|
||||
details = _get_topic_details(topic_ids)
|
||||
details = await _get_topic_details(topic_ids)
|
||||
|
||||
result = []
|
||||
|
||||
@@ -148,7 +145,7 @@ async def get_primary_topic_counts(
|
||||
return result
|
||||
|
||||
|
||||
def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
|
||||
async def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
|
||||
|
||||
indexed_author_id = f"https://openalex.org/{author_id.strip()}"
|
||||
|
||||
@@ -174,16 +171,13 @@ def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
|
||||
}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body=body,
|
||||
)
|
||||
except httpx.HTTPError as exc:
|
||||
except ElasticsearchException as exc:
|
||||
logger.exception("OpenAlex primary topic aggregation request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex works search request failed.",
|
||||
) from exc
|
||||
raise
|
||||
|
||||
aggregations = response.get("aggregations", {})
|
||||
buckets = aggregations.get("primary_topics", {}).get("buckets", [])
|
||||
@@ -212,18 +206,18 @@ async def get_work(
|
||||
return elements[0]
|
||||
|
||||
|
||||
def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
|
||||
async def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
|
||||
if not topic_ids:
|
||||
return {}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="openalex-topics",
|
||||
query={"terms": {"id": topic_ids}},
|
||||
source=TOPIC_DETAIL_SOURCE_FIELDS,
|
||||
size=len(topic_ids),
|
||||
)
|
||||
except httpx.HTTPError:
|
||||
except Exception:
|
||||
logger.exception("Could not load topic details from Elasticsearch.")
|
||||
return {}
|
||||
|
||||
@@ -242,7 +236,7 @@ def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
|
||||
"domain": _extract_topic_hierarchy_item(source, "domain"),
|
||||
}
|
||||
|
||||
_enrich_topic_hierarchy_descriptions(details)
|
||||
await _enrich_topic_hierarchy_descriptions(details)
|
||||
|
||||
return details
|
||||
|
||||
@@ -260,7 +254,7 @@ def _extract_topic_hierarchy_item(source: dict, key: str) -> dict[str, str | Non
|
||||
}
|
||||
|
||||
|
||||
def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None:
|
||||
async def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None:
|
||||
for hierarchy_key, index in TOPIC_HIERARCHY_DESCRIPTION_INDICES.items():
|
||||
hierarchy_ids = {
|
||||
item.get(hierarchy_key, {}).get("id")
|
||||
@@ -268,7 +262,7 @@ def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None:
|
||||
if item.get(hierarchy_key, {}).get("id")
|
||||
}
|
||||
|
||||
descriptions = _get_topic_hierarchy_descriptions(index, list(hierarchy_ids))
|
||||
descriptions = await _get_topic_hierarchy_descriptions(index, list(hierarchy_ids))
|
||||
|
||||
for item in details.values():
|
||||
hierarchy_item = item.get(hierarchy_key) or {}
|
||||
@@ -278,7 +272,7 @@ def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None:
|
||||
hierarchy_item["description"] = descriptions[hierarchy_id]
|
||||
|
||||
|
||||
def _get_topic_hierarchy_descriptions(
|
||||
async def _get_topic_hierarchy_descriptions(
|
||||
index: str,
|
||||
hierarchy_ids: list[str],
|
||||
) -> dict[str, str | None]:
|
||||
@@ -286,13 +280,13 @@ def _get_topic_hierarchy_descriptions(
|
||||
return {}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=index,
|
||||
query={"terms": {"id": hierarchy_ids}},
|
||||
source=TOPIC_HIERARCHY_DESCRIPTION_SOURCE_FIELDS,
|
||||
size=len(hierarchy_ids),
|
||||
)
|
||||
except httpx.HTTPError:
|
||||
except Exception:
|
||||
logger.exception("Could not load topic hierarchy details from %s.", index)
|
||||
return {}
|
||||
|
||||
@@ -433,7 +427,7 @@ async def get_topics_by_time_by_author(
|
||||
client=client,
|
||||
)
|
||||
|
||||
return _get_topics_by_time_by_author_from_es(
|
||||
return await _get_topics_by_time_by_author_from_es(
|
||||
author_id,
|
||||
max_topics_per_year=max_topics_per_year,
|
||||
target_publications=target_publications,
|
||||
@@ -521,7 +515,7 @@ async def _get_topics_by_time_by_author_from_work_pages(
|
||||
if topic["id"]:
|
||||
topic_ids.add(topic["id"])
|
||||
|
||||
topic_details = _get_topic_details(list(topic_ids))
|
||||
topic_details = await _get_topic_details(list(topic_ids))
|
||||
|
||||
elements = []
|
||||
|
||||
@@ -580,13 +574,13 @@ async def _get_topics_by_time_by_author_from_work_pages(
|
||||
)
|
||||
|
||||
|
||||
def _get_topics_by_time_by_author_from_es(
|
||||
async def _get_topics_by_time_by_author_from_es(
|
||||
author_id: str,
|
||||
max_topics_per_year: int = 3,
|
||||
target_publications: int = 300,
|
||||
include_all: bool = False,
|
||||
) -> TopicsByTime:
|
||||
year_buckets, total_publications = _get_publication_year_counts_from_es(author_id)
|
||||
year_buckets, total_publications = await _get_publication_year_counts_from_es(author_id)
|
||||
selected_years, is_limited = _select_complete_timeline_years(
|
||||
year_buckets,
|
||||
target_publications=target_publications,
|
||||
@@ -602,13 +596,13 @@ def _get_topics_by_time_by_author_from_es(
|
||||
total_publications=total_publications,
|
||||
)
|
||||
|
||||
year_topic_buckets = _get_timeline_topic_counts_from_es(
|
||||
year_topic_buckets = await _get_timeline_topic_counts_from_es(
|
||||
author_id,
|
||||
years=selected_years,
|
||||
max_topics_per_year=max_topics_per_year,
|
||||
)
|
||||
topic_ids = _collect_topic_ids_from_year_buckets(year_topic_buckets)
|
||||
topic_details = _get_topic_details(list(topic_ids))
|
||||
topic_details = await _get_topic_details(list(topic_ids))
|
||||
|
||||
elements = _build_timeline_elements_from_aggregations(
|
||||
year_topic_buckets,
|
||||
@@ -625,7 +619,7 @@ def _get_topics_by_time_by_author_from_es(
|
||||
)
|
||||
|
||||
|
||||
def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], int]:
|
||||
async def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], int]:
|
||||
body = {
|
||||
"size": 0,
|
||||
"track_total_hits": True,
|
||||
@@ -642,21 +636,18 @@ def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], in
|
||||
}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body=body,
|
||||
)
|
||||
except httpx.HTTPError as exc:
|
||||
except ElasticsearchException as exc:
|
||||
logger.exception("OpenAlex publication year aggregation request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex works search request failed.",
|
||||
) from exc
|
||||
raise
|
||||
|
||||
return _parse_year_count_buckets(response), _parse_total_hits(response)
|
||||
|
||||
|
||||
def _get_timeline_topic_counts_from_es(
|
||||
async def _get_timeline_topic_counts_from_es(
|
||||
author_id: str,
|
||||
years: list[int],
|
||||
max_topics_per_year: int,
|
||||
@@ -713,16 +704,13 @@ def _get_timeline_topic_counts_from_es(
|
||||
}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body=body,
|
||||
)
|
||||
except httpx.HTTPError as exc:
|
||||
except ElasticsearchException as exc:
|
||||
logger.exception("OpenAlex timeline topic aggregation request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex works search request failed.",
|
||||
) from exc
|
||||
raise
|
||||
|
||||
return response.get("aggregations", {}).get("by_year", {}).get("buckets", [])
|
||||
|
||||
@@ -883,29 +871,16 @@ async def _search_author_works_data(
|
||||
institution_id: list[str] | None = None,
|
||||
topic_id: list[str] | None = None,
|
||||
) -> dict:
|
||||
try:
|
||||
return await search_client.search_author_works(
|
||||
author_id,
|
||||
page,
|
||||
size,
|
||||
publication_year=publication_year,
|
||||
work_type=work_type,
|
||||
language=language,
|
||||
institution_id=institution_id,
|
||||
topic_id=topic_id,
|
||||
)
|
||||
except MissingApiKeyError as exc:
|
||||
logger.error("OpenAlex works Elasticsearch API key is not configured.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="OpenAlex works search is not configured.",
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
logger.exception("OpenAlex works search request failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex works search request failed.",
|
||||
) from exc
|
||||
return await search_client.search_author_works(
|
||||
author_id,
|
||||
page,
|
||||
size,
|
||||
publication_year=publication_year,
|
||||
work_type=work_type,
|
||||
language=language,
|
||||
institution_id=institution_id,
|
||||
topic_id=topic_id,
|
||||
)
|
||||
|
||||
|
||||
def _parse_full_work_search_response(data: dict) -> tuple[list[Work], int]:
|
||||
@@ -946,15 +921,15 @@ def _parse_full_work_search_response(data: dict) -> tuple[list[Work], int]:
|
||||
elements.append(work)
|
||||
except ValidationError as exc:
|
||||
logger.exception("OpenAlex works search response could not be parsed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex works search response could not be parsed.",
|
||||
raise UpstreamAPIException(
|
||||
message="OpenAlex works search response could not be parsed.",
|
||||
status_code=502,
|
||||
) from exc
|
||||
|
||||
return elements, total
|
||||
|
||||
|
||||
def get_publication_dois_of_author(
|
||||
async def get_publication_dois_of_author(
|
||||
raw_oa_author_id: str,
|
||||
) -> List[str]:
|
||||
query = {
|
||||
@@ -976,19 +951,16 @@ def get_publication_dois_of_author(
|
||||
}
|
||||
|
||||
try:
|
||||
response = elasticsearch.search(
|
||||
response = await elasticsearch.search(
|
||||
index="openalex-works",
|
||||
source=["doi"],
|
||||
size=10000,
|
||||
query=query,
|
||||
cluster="nes",
|
||||
)
|
||||
except httpx.HTTPError as exc:
|
||||
except ElasticsearchException as exc:
|
||||
logger.exception("Request for publication DOIs of author failed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="Request for publication DOIs of author failed.",
|
||||
) from exc
|
||||
raise
|
||||
|
||||
dois = []
|
||||
for hit in response.get("hits", {}).get("hits", []):
|
||||
|
||||
@@ -11,8 +11,7 @@ import urllib
|
||||
from .. import config
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
class MissingApiKeyError(Exception):
|
||||
pass
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -141,62 +140,49 @@ class OpenAlexWorksSearchClient:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
timeout=self.timeout,
|
||||
transport=self.transport,
|
||||
) as client:
|
||||
response = await client.post(
|
||||
f"/{self.index}/_search",
|
||||
headers={"Authorization": f"ApiKey {self.api_key}"},
|
||||
json=self.author_works_query(
|
||||
author_id,
|
||||
page,
|
||||
size,
|
||||
publication_year=publication_year,
|
||||
work_type=work_type,
|
||||
language=language,
|
||||
institution_id=institution_id,
|
||||
topic_id=topic_id,
|
||||
),
|
||||
)
|
||||
# logging.debug(f"Response: {response.text}")
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
body = self.author_works_query(
|
||||
author_id,
|
||||
page,
|
||||
size,
|
||||
publication_year=publication_year,
|
||||
work_type=work_type,
|
||||
language=language,
|
||||
institution_id=institution_id,
|
||||
topic_id=topic_id,
|
||||
)
|
||||
return await elasticsearch.search(index=self.index,body=body,cluster=ESCluster.NES,)
|
||||
|
||||
async def search_work(self, identifier: str) -> dict[str, Any]:
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
|
||||
decoded_id = urllib.parse.unquote(identifier)
|
||||
body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
if not self.api_key:
|
||||
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
|
||||
decoded_id = urllib.parse.unquote(identifier)
|
||||
body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"term": {
|
||||
"_id": {
|
||||
"value": decoded_id,
|
||||
"boost": 5
|
||||
"term": {
|
||||
"_id": {
|
||||
"value": decoded_id,
|
||||
"boost": 5
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"term": {
|
||||
"doi": {
|
||||
"value": "https://doi.org/" + decoded_id.lower(),
|
||||
"boost": 3
|
||||
"term": {
|
||||
"doi": {
|
||||
"value": "https://doi.org/" + decoded_id.lower(),
|
||||
"boost": 3
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"minimum_should_match": 1
|
||||
}
|
||||
}
|
||||
}
|
||||
print(body)
|
||||
response = elasticsearch.search(index=f'{ESIndex.OPENALEX_WORKS}*',body=body,cluster=ESCluster.NES,size=1)
|
||||
return response
|
||||
}
|
||||
}
|
||||
response = await elasticsearch.search(index=f"{ESIndex.OPENALEX_WORKS}*",body=body,cluster=ESCluster.NES,size=1)
|
||||
return response
|
||||
|
||||
async def search_for_work_by_title(
|
||||
self,
|
||||
@@ -220,6 +206,6 @@ class OpenAlexWorksSearchClient:
|
||||
{"cited_by_count": {"order": "desc", "missing": "_last"}},
|
||||
],
|
||||
}
|
||||
response = elasticsearch.search(index=f'{ESIndex.OPENALEX_WORKS}*',body=body,cluster=ESCluster.NES,size=1)
|
||||
response = await elasticsearch.search(index=f'{ESIndex.OPENALEX_WORKS}*',body=body,cluster=ESCluster.NES,size=1)
|
||||
|
||||
return response
|
||||
@@ -3,7 +3,7 @@ import json
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from inse.works.search_client import MissingApiKeyError
|
||||
from inse.exceptions import MissingApiKeyError
|
||||
from inse.works.search_client import OpenAlexWorksSearchClient
|
||||
|
||||
|
||||
@@ -152,37 +152,47 @@ def test_author_works_query_adds_topic_filter():
|
||||
]
|
||||
|
||||
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_search_author_works_passes_institution_filter_to_query():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
body = json.loads(request.content)
|
||||
assert body["query"]["bool"]["must"][1]["nested"]["path"] == (
|
||||
"authorships.institutions"
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
|
||||
mock_search.return_value = {"hits": {"total": {"value": 1}, "hits": []}}
|
||||
client = OpenAlexWorksSearchClient(index="openalex-works")
|
||||
|
||||
await client.search_author_works(
|
||||
"A5023888391",
|
||||
page=1,
|
||||
size=20,
|
||||
institution_id=["https://openalex.org/I205640436"],
|
||||
)
|
||||
|
||||
assert mock_search.call_count == 1
|
||||
_, kwargs = mock_search.call_args
|
||||
body = kwargs.get("body")
|
||||
assert body["query"]["bool"]["must"][1]["nested"]["path"] == "authorships.institutions"
|
||||
assert body["query"]["bool"]["must"][1]["nested"]["query"]["terms"] == {
|
||||
"authorships.institutions.id": ["https://openalex.org/I205640436"],
|
||||
}
|
||||
return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}})
|
||||
|
||||
client = OpenAlexWorksSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
index="openalex-works",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
await client.search_author_works(
|
||||
"A5023888391",
|
||||
page=1,
|
||||
size=20,
|
||||
institution_id=["https://openalex.org/I205640436"],
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_search_author_works_passes_topic_filter_to_query():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
body = json.loads(request.content)
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
|
||||
mock_search.return_value = {"hits": {"total": {"value": 1}, "hits": []}}
|
||||
client = OpenAlexWorksSearchClient(index="openalex-works")
|
||||
|
||||
await client.search_author_works(
|
||||
"A5023888391",
|
||||
page=1,
|
||||
size=20,
|
||||
topic_id=["https://openalex.org/T12419"],
|
||||
)
|
||||
|
||||
assert mock_search.call_count == 1
|
||||
_, kwargs = mock_search.call_args
|
||||
body = kwargs.get("body")
|
||||
assert body["query"]["bool"]["filter"] == [
|
||||
{
|
||||
"bool": {
|
||||
@@ -207,61 +217,55 @@ async def test_search_author_works_passes_topic_filter_to_query():
|
||||
},
|
||||
},
|
||||
]
|
||||
return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}})
|
||||
|
||||
client = OpenAlexWorksSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
index="openalex-works",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
await client.search_author_works(
|
||||
"A5023888391",
|
||||
page=1,
|
||||
size=20,
|
||||
topic_id=["https://openalex.org/T12419"],
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_search_author_works_calls_elasticsearch_index_with_api_key():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
assert request.method == "POST"
|
||||
assert request.url.path == "/elastic/openalex-works/_search"
|
||||
assert request.headers["Authorization"] == "ApiKey test-key"
|
||||
return httpx.Response(200, json={"hits": {"total": {"value": 0}, "hits": []}})
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
|
||||
mock_search.return_value = {"hits": {"total": {"value": 0}, "hits": []}}
|
||||
client = OpenAlexWorksSearchClient(index="openalex-works")
|
||||
|
||||
client = OpenAlexWorksSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
index="openalex-works",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
result = await client.search_author_works("A5023888391", page=1, size=20)
|
||||
|
||||
result = await client.search_author_works("A5023888391", page=1, size=20)
|
||||
|
||||
assert result == {"hits": {"total": {"value": 0}, "hits": []}}
|
||||
assert result == {"hits": {"total": {"value": 0}, "hits": []}}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_search_work_filters_by_work_id():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
body = json.loads(request.content)
|
||||
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
|
||||
mock_search.return_value = {"hits": {"total": {"value": 1}, "hits": []}}
|
||||
client = OpenAlexWorksSearchClient(index="openalex-works")
|
||||
|
||||
await client.search_work("W2741809807")
|
||||
|
||||
assert mock_search.call_count == 1
|
||||
_, kwargs = mock_search.call_args
|
||||
body = kwargs.get("body")
|
||||
assert body == {
|
||||
"size": 1,
|
||||
"query": {"term": {"id": "https://openalex.org/W2741809807"}},
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"term": {
|
||||
"_id": {
|
||||
"value": "W2741809807",
|
||||
"boost": 5
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"term": {
|
||||
"doi": {
|
||||
"value": "https://doi.org/w2741809807",
|
||||
"boost": 3
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"minimum_should_match": 1
|
||||
}
|
||||
}
|
||||
}
|
||||
return httpx.Response(200, json={"hits": {"total": {"value": 1}, "hits": []}})
|
||||
|
||||
client = OpenAlexWorksSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
index="openalex-works",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
await client.search_work("W2741809807")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
|
||||
Generated
-62
@@ -178,36 +178,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b2/b7/545d2c10c1fc15e48653c91efde329a790f2eecfbbf2bd16003b5db2bab0/dotenv-0.9.9-py2.py3-none-any.whl", hash = "sha256:29cf74a087b31dafdb5a446b6d7e11cbce8ed2741540e2339c69fbef92c94ce9", size = 1892, upload-time = "2025-02-19T22:15:01.647Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "elastic-transport"
|
||||
version = "9.4.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "certifi" },
|
||||
{ name = "sniffio" },
|
||||
{ name = "urllib3" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/0f/a8/dd1431b95daa54d4859c1d250362433df6df9cfaab7bfac3eafd410d019a/elastic_transport-9.4.1.tar.gz", hash = "sha256:d12c86ea73528690ebf63a488d9ae323292e6aa5ee55e1e29f14293472f4197f", size = 79170, upload-time = "2026-05-25T14:16:47.416Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/5c/f6/508c1e541b840b6eaf60a46a8994ba55affd07bf6a311cffc860781ae06a/elastic_transport-9.4.1-py3-none-any.whl", hash = "sha256:186a29e6c66ff269487e33f7b17176316e18b6061702c25eb0bb15681302e91d", size = 66229, upload-time = "2026-05-25T14:16:45.882Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "elasticsearch"
|
||||
version = "9.4.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "anyio" },
|
||||
{ name = "elastic-transport" },
|
||||
{ name = "python-dateutil" },
|
||||
{ name = "sniffio" },
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/e0/4b/9b753f0a8f56ae508dced2f7ac87bef7a27ce8f890e349e16812e9f7f4fa/elasticsearch-9.4.1.tar.gz", hash = "sha256:1d78fdfba97a903ec35a5eb5808a74e33392b7c620bd5f742d465a3a26c27d75", size = 908138, upload-time = "2026-05-26T16:28:40.132Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/cf/8e/2c93805e93e724a90156004a9212572ec86473974deede4605a33b8b169a/elasticsearch-9.4.1-py3-none-any.whl", hash = "sha256:71ab71c3d1b20fd88c2922fb82c3277cce7ea03c160686e7b9368b265c2b4cac", size = 993647, upload-time = "2026-05-26T16:28:36.556Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastapi"
|
||||
version = "0.115.14"
|
||||
@@ -799,18 +769,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/f0/d7/a812a0bd0f5160823e647524488cc9734f93782f2c273b8f77e8afc60a37/pytest-8.1.2-py3-none-any.whl", hash = "sha256:6c06dc309ff46a05721e6fd48e492a775ed8165d2ecdf57f156a80c7e95bb142", size = 337456, upload-time = "2024-04-26T18:05:15.452Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "python-dateutil"
|
||||
version = "2.9.0.post0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "six" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "python-dotenv"
|
||||
version = "1.2.2"
|
||||
@@ -1127,7 +1085,6 @@ source = { virtual = "." }
|
||||
dependencies = [
|
||||
{ name = "cryptography" },
|
||||
{ name = "dotenv" },
|
||||
{ name = "elasticsearch" },
|
||||
{ name = "fastapi" },
|
||||
{ name = "httpx" },
|
||||
{ name = "openai" },
|
||||
@@ -1148,7 +1105,6 @@ dependencies = [
|
||||
requires-dist = [
|
||||
{ name = "cryptography", specifier = "~=42.0.0" },
|
||||
{ name = "dotenv", specifier = ">=0.9.9" },
|
||||
{ name = "elasticsearch", specifier = "~=9.4.0" },
|
||||
{ name = "fastapi", specifier = "~=0.115.0" },
|
||||
{ name = "httpx", specifier = "~=0.27.0" },
|
||||
{ name = "openai", specifier = "~=2.41.0" },
|
||||
@@ -1182,15 +1138,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "six"
|
||||
version = "1.17.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sniffio"
|
||||
version = "1.3.1"
|
||||
@@ -1421,15 +1368,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/18/67/36e9267722cc04a6b9f15c7f3441c2363321a3ea07da7ae0c0707beb2a9c/typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548", size = 44614, upload-time = "2025-08-25T13:49:24.86Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "urllib3"
|
||||
version = "2.7.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "uvicorn"
|
||||
version = "0.29.0"
|
||||
|
||||
Generated
-10
@@ -19,7 +19,6 @@
|
||||
"@angular/platform-browser-dynamic": "^21.2.14",
|
||||
"@angular/router": "^21.2.14",
|
||||
"echarts": "^6.1.0",
|
||||
"echarts-wordcloud": "^2.1.0",
|
||||
"ngx-echarts": "^21.0.0",
|
||||
"rxjs": "~7.8.0",
|
||||
"tslib": "^2.3.0",
|
||||
@@ -6088,15 +6087,6 @@
|
||||
"zrender": "6.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/echarts-wordcloud": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/echarts-wordcloud/-/echarts-wordcloud-2.1.0.tgz",
|
||||
"integrity": "sha512-Kt1JmbcROgb+3IMI48KZECK2AP5lG6bSsOEs+AsuwaWJxQom31RTNd6NFYI01E/YaI1PFZeueaupjlmzSQasjQ==",
|
||||
"license": "ISC",
|
||||
"peerDependencies": {
|
||||
"echarts": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/echarts/node_modules/tslib": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.0.tgz",
|
||||
|
||||
@@ -22,7 +22,6 @@
|
||||
"@angular/platform-browser-dynamic": "^21.2.14",
|
||||
"@angular/router": "^21.2.14",
|
||||
"echarts": "^6.1.0",
|
||||
"echarts-wordcloud": "^2.1.0",
|
||||
"ngx-echarts": "^21.0.0",
|
||||
"rxjs": "~7.8.0",
|
||||
"tslib": "^2.3.0",
|
||||
|
||||
@@ -178,7 +178,10 @@ export const routes: Routes = [
|
||||
import('./modules/person-projects/person-projects.component').then(
|
||||
(mod) => mod.PersonProjectsComponent,
|
||||
),
|
||||
resolve: { dfgProjectPage: dfgProjectsResolver },
|
||||
resolve: {
|
||||
dfgProjectPage: dfgProjectsResolver,
|
||||
personCordisEuProjectPage: cordisEuProjectPageResolver,
|
||||
},
|
||||
runGuardsAndResolvers: (from, to) => {
|
||||
const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search'];
|
||||
return keys.some(
|
||||
@@ -301,9 +304,9 @@ export const routes: Routes = [
|
||||
{
|
||||
path: 'patents',
|
||||
loadComponent: () =>
|
||||
import(
|
||||
'./modules/institution-patents/institution-patents.component'
|
||||
).then((mod) => mod.InstitutionPatentsComponent),
|
||||
import('./modules/institution-patents/institution-patents.component').then(
|
||||
(mod) => mod.InstitutionPatentsComponent,
|
||||
),
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -8,62 +8,15 @@
|
||||
</span>
|
||||
}
|
||||
</div>
|
||||
@if (visibleLegendGroups().length > 0) {
|
||||
<div class="interest-legend" aria-label="Aktuell sichtbare Themenbereiche">
|
||||
<mat-icon
|
||||
class="interest-legend-info"
|
||||
matTooltip="Fachgebiete geben die Farbfamilie vor, Themenbereiche bestimmen die konkrete Farbvariante."
|
||||
matTooltipPosition="above"
|
||||
aria-label="Informationen zur Farblegende">
|
||||
info_outline
|
||||
</mat-icon>
|
||||
|
||||
<div class="interest-legend-content">
|
||||
@for (group of visibleLegendGroups(); track group.id) {
|
||||
<span class="interest-legend-group">
|
||||
<span
|
||||
class="interest-legend-field"
|
||||
[matTooltip]="group.tooltip"
|
||||
[matTooltipDisabled]="!group.tooltip"
|
||||
matTooltipClass="topic-chip-tooltip"
|
||||
matTooltipPosition="above"
|
||||
>{{ group.name }}</span
|
||||
>
|
||||
<span class="interest-legend-items">
|
||||
@for (item of group.items; track item.id) {
|
||||
<span
|
||||
class="interest-legend-item"
|
||||
[matTooltip]="item.tooltip"
|
||||
[matTooltipDisabled]="!item.tooltip"
|
||||
matTooltipClass="topic-chip-tooltip"
|
||||
matTooltipPosition="above">
|
||||
<span
|
||||
class="interest-legend-dot"
|
||||
[style.background]="item.color"
|
||||
aria-hidden="true"></span>
|
||||
<span>{{ item.name }}</span>
|
||||
</span>
|
||||
}
|
||||
</span>
|
||||
</span>
|
||||
}
|
||||
|
||||
@if (hasHiddenLegendGroups()) {
|
||||
<button
|
||||
type="button"
|
||||
class="interest-legend-more"
|
||||
[attr.aria-expanded]="legendExpanded()"
|
||||
(click)="toggleLegend()">
|
||||
@if (legendExpanded()) {
|
||||
Weniger anzeigen
|
||||
} @else {
|
||||
+{{ hiddenLegendItemCount() }} weitere
|
||||
}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
<app-topic-legend
|
||||
[groups]="legendGroups()"
|
||||
[expanded]="legendExpanded()"
|
||||
[showTitle]="false"
|
||||
[showVisibilityToggle]="false"
|
||||
[collapsedGroupLimit]="3"
|
||||
variant="compact"
|
||||
(expandedChange)="onLegendExpandedChange($event)">
|
||||
</app-topic-legend>
|
||||
<div class="interest-tags">
|
||||
@if (tags().length > 0) {
|
||||
@for (tag of tags(); track tag.label) {
|
||||
|
||||
@@ -45,127 +45,6 @@
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.interest-legend {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 9px;
|
||||
width: fit-content;
|
||||
max-width: 100%;
|
||||
margin: 0 0 16px;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid #dbe5f6;
|
||||
border-radius: 8px;
|
||||
background: #ffffff;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.interest-legend-content,
|
||||
.interest-legend-group,
|
||||
.interest-legend-items,
|
||||
.interest-legend-item {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.interest-legend-info {
|
||||
flex: 0 0 auto;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
color: #7d8aa8;
|
||||
font-size: 14px;
|
||||
line-height: 14px;
|
||||
}
|
||||
|
||||
.interest-legend-content {
|
||||
gap: 7px;
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.interest-legend-group {
|
||||
gap: 6px;
|
||||
flex: 0 1 auto;
|
||||
flex-wrap: wrap;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
min-height: 24px;
|
||||
padding: 3px 7px;
|
||||
border: 1px solid #dbe5f6;
|
||||
border-radius: 999px;
|
||||
background: #fbfdff;
|
||||
}
|
||||
|
||||
.interest-legend-field {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
color: #07163d;
|
||||
font-size: 10px;
|
||||
font-weight: 800;
|
||||
line-height: 1.2;
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.interest-legend-items {
|
||||
flex: 0 1 auto;
|
||||
gap: 4px 7px;
|
||||
min-width: 0;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.interest-legend-item {
|
||||
gap: 4px;
|
||||
flex: 0 0 auto;
|
||||
min-width: 0;
|
||||
color: #53617e;
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
line-height: 1.2;
|
||||
white-space: nowrap;
|
||||
cursor: help;
|
||||
|
||||
span:last-child {
|
||||
overflow: visible;
|
||||
text-overflow: clip;
|
||||
}
|
||||
}
|
||||
|
||||
.interest-legend-dot {
|
||||
flex: 0 0 auto;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.85);
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 0 0 1px rgba(15, 23, 42, 0.2);
|
||||
}
|
||||
|
||||
.interest-legend-more {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
flex: 0 0 auto;
|
||||
min-height: 24px;
|
||||
padding: 0 2px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--accent, #0057ff);
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
white-space: nowrap;
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--accent, #0057ff);
|
||||
outline-offset: 2px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
.interest-tags .interest-empty {
|
||||
padding: 9px 16px;
|
||||
border: 1px solid #e2e8f0;
|
||||
|
||||
@@ -10,13 +10,14 @@ import {
|
||||
} from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
|
||||
import { TopicCount } from '../../api';
|
||||
import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component';
|
||||
import { TopicLegendComponent } from '../../shared/ui/topic-legend/topic-legend.component';
|
||||
import { topicHierarchyColor } from '../../shared/utils/topic-colors';
|
||||
import { buildTopicLegendGroups } from '../../shared/utils/topic-legend';
|
||||
|
||||
interface InterestTag {
|
||||
id: string;
|
||||
@@ -35,30 +36,16 @@ interface InterestTag {
|
||||
domainDescription: string;
|
||||
}
|
||||
|
||||
interface InterestLegendGroup {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
domainName: string;
|
||||
domainDescription: string;
|
||||
tooltip: string;
|
||||
items: InterestLegendItem[];
|
||||
}
|
||||
|
||||
interface InterestLegendItem {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
color: string;
|
||||
tooltip: string;
|
||||
}
|
||||
|
||||
const MAX_TAGS = 5;
|
||||
const MAX_LEGEND_GROUPS = 3;
|
||||
|
||||
@Component({
|
||||
selector: 'app-person-interesting',
|
||||
imports: [CommonModule, MatIconModule, MatTooltipModule, TopicChipComponent],
|
||||
imports: [
|
||||
CommonModule,
|
||||
MatIconModule,
|
||||
TopicChipComponent,
|
||||
TopicLegendComponent,
|
||||
],
|
||||
templateUrl: './person-interesting.component.html',
|
||||
styleUrl: './person-interesting.component.scss',
|
||||
})
|
||||
@@ -104,95 +91,22 @@ export class PersonInterestingComponent implements OnInit {
|
||||
return tags.sort((a, b) => b.count - a.count).slice(0, MAX_TAGS);
|
||||
});
|
||||
|
||||
readonly legendGroups = computed<InterestLegendGroup[]>(() => {
|
||||
const groups = new Map<string, InterestLegendGroup>();
|
||||
|
||||
for (const tag of this.tags()) {
|
||||
if (!tag.subfieldName) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const fieldName = tag.fieldName || 'Ohne Field';
|
||||
const fieldId = tag.fieldId || fieldName.toLowerCase();
|
||||
const subfieldId = tag.subfieldId || tag.subfieldName.toLowerCase();
|
||||
|
||||
if (!groups.has(fieldId)) {
|
||||
groups.set(fieldId, {
|
||||
id: fieldId,
|
||||
name: fieldName,
|
||||
description: tag.fieldDescription,
|
||||
domainName: tag.domainName,
|
||||
domainDescription: tag.domainDescription,
|
||||
tooltip: this.buildLegendTooltip([
|
||||
{
|
||||
label: 'Fachgebiet',
|
||||
value: fieldName,
|
||||
description: tag.fieldDescription,
|
||||
},
|
||||
{
|
||||
label: 'Wissenschaftsbereich',
|
||||
value: tag.domainName,
|
||||
description: tag.domainDescription,
|
||||
},
|
||||
]),
|
||||
items: [],
|
||||
});
|
||||
}
|
||||
|
||||
const group = groups.get(fieldId);
|
||||
|
||||
if (!group || group.items.some((item) => item.id === subfieldId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
group.items.push({
|
||||
id: subfieldId,
|
||||
name: tag.subfieldName,
|
||||
description: tag.subfieldDescription,
|
||||
color: tag.color,
|
||||
tooltip: this.buildLegendTooltip([
|
||||
{
|
||||
label: 'Themenbereich',
|
||||
value: tag.subfieldName,
|
||||
description: tag.subfieldDescription,
|
||||
},
|
||||
{
|
||||
label: 'Fachgebiet',
|
||||
value: fieldName,
|
||||
description: tag.fieldDescription,
|
||||
},
|
||||
{
|
||||
label: 'Wissenschaftsbereich',
|
||||
value: tag.domainName,
|
||||
description: tag.domainDescription,
|
||||
},
|
||||
]),
|
||||
});
|
||||
}
|
||||
|
||||
return [...groups.values()]
|
||||
.map((group) => ({
|
||||
...group,
|
||||
items: group.items.sort((left, right) =>
|
||||
left.name.localeCompare(right.name),
|
||||
),
|
||||
}))
|
||||
.sort((left, right) => left.name.localeCompare(right.name));
|
||||
});
|
||||
|
||||
readonly visibleLegendGroups = computed<InterestLegendGroup[]>(() => {
|
||||
const groups = this.legendGroups();
|
||||
return this.legendExpanded() ? groups : groups.slice(0, MAX_LEGEND_GROUPS);
|
||||
});
|
||||
|
||||
readonly hasHiddenLegendGroups = computed<boolean>(
|
||||
() => this.legendGroups().length > MAX_LEGEND_GROUPS,
|
||||
);
|
||||
|
||||
readonly hiddenLegendItemCount = computed<number>(() =>
|
||||
this.legendGroups()
|
||||
.slice(MAX_LEGEND_GROUPS)
|
||||
.reduce((count, group) => count + group.items.length, 0),
|
||||
readonly legendGroups = computed(() =>
|
||||
buildTopicLegendGroups(
|
||||
this.tags().map((tag) => ({
|
||||
id: tag.id,
|
||||
name: tag.label,
|
||||
subfield_id: tag.subfieldId,
|
||||
subfield_name: tag.subfieldName,
|
||||
subfield_description: tag.subfieldDescription,
|
||||
field_id: tag.fieldId,
|
||||
field_name: tag.fieldName,
|
||||
field_description: tag.fieldDescription,
|
||||
domain_id: tag.domainId,
|
||||
domain_name: tag.domainName,
|
||||
domain_description: tag.domainDescription,
|
||||
})),
|
||||
),
|
||||
);
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -215,8 +129,7 @@ export class PersonInterestingComponent implements OnInit {
|
||||
this.tagClick.emit({ id: tag.id, name: tag.label });
|
||||
}
|
||||
|
||||
toggleLegend(): void {
|
||||
const expanded = !this.legendExpanded();
|
||||
onLegendExpandedChange(expanded: boolean): void {
|
||||
this.legendExpanded.set(expanded);
|
||||
|
||||
void this.router.navigate([], {
|
||||
@@ -249,31 +162,4 @@ export class PersonInterestingComponent implements OnInit {
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
private buildLegendTooltip(
|
||||
entries: Array<{ label: string; value: string; description: string }>,
|
||||
): string {
|
||||
const lines: string[] = [];
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!entry.value && !entry.description) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (lines.length > 0) {
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (entry.value) {
|
||||
lines.push(`${entry.label}: ${entry.value}`);
|
||||
}
|
||||
|
||||
if (entry.description) {
|
||||
lines.push('');
|
||||
lines.push(`Beschreibung: ${entry.description}`);
|
||||
}
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
}
|
||||
|
||||
+8
-81
@@ -7,87 +7,14 @@
|
||||
<span>(basierend auf Publikationen)</span>
|
||||
</p>
|
||||
|
||||
<div
|
||||
*ngIf="subfieldLegendGroups.length > 0"
|
||||
class="subfield-legend"
|
||||
[class.expanded]="subfieldLegendExpanded"
|
||||
aria-label="Aktuell sichtbare Themenbereiche">
|
||||
<div class="subfield-legend-header">
|
||||
<div class="subfield-legend-title">
|
||||
<span>Farben nach Themenbereich</span>
|
||||
<mat-icon
|
||||
class="subfield-legend-info"
|
||||
matTooltip="Fachgebiete geben die Farbfamilie vor, Themenbereiche bestimmen die konkrete Farbvariante."
|
||||
matTooltipPosition="above"
|
||||
aria-label="Informationen zur Farblegende">
|
||||
info_outline
|
||||
</mat-icon>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="subfield-legend-visibility-toggle"
|
||||
[attr.aria-expanded]="subfieldLegendVisible"
|
||||
(click)="toggleSubfieldLegendVisibility()">
|
||||
<span>
|
||||
{{
|
||||
subfieldLegendVisible
|
||||
? 'Legende ausblenden'
|
||||
: 'Legende einblenden'
|
||||
}}
|
||||
</span>
|
||||
<mat-icon aria-hidden="true">
|
||||
{{ subfieldLegendVisible ? 'expand_less' : 'expand_more' }}
|
||||
</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div *ngIf="subfieldLegendVisible" class="subfield-legend-content">
|
||||
<div
|
||||
*ngFor="
|
||||
let group of subfieldLegendGroups;
|
||||
trackBy: trackByLegendGroup
|
||||
"
|
||||
class="subfield-legend-group">
|
||||
<span
|
||||
class="subfield-legend-field"
|
||||
[matTooltip]="group.tooltip"
|
||||
[matTooltipDisabled]="!group.tooltip"
|
||||
matTooltipClass="topic-chip-tooltip"
|
||||
matTooltipPosition="above"
|
||||
>{{ group.name }}</span
|
||||
>
|
||||
|
||||
<span class="subfield-legend-items">
|
||||
<span
|
||||
*ngFor="let item of group.items; trackBy: trackByLegendItem"
|
||||
class="subfield-legend-item"
|
||||
[matTooltip]="item.tooltip"
|
||||
[matTooltipDisabled]="!item.tooltip"
|
||||
matTooltipClass="topic-chip-tooltip"
|
||||
matTooltipPosition="above">
|
||||
<span
|
||||
class="subfield-legend-dot"
|
||||
[style.background]="item.color"
|
||||
aria-hidden="true"></span>
|
||||
<span>{{ item.name }}</span>
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<button
|
||||
*ngIf="showSubfieldLegendToggle"
|
||||
type="button"
|
||||
class="subfield-legend-more-toggle"
|
||||
(click)="toggleSubfieldLegend()">
|
||||
{{
|
||||
subfieldLegendExpanded
|
||||
? 'Weniger anzeigen'
|
||||
: '+' + hiddenSubfieldLegendItemCount + ' weitere'
|
||||
}}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<app-topic-legend
|
||||
[groups]="topicLegendGroups"
|
||||
[visible]="subfieldLegendVisible"
|
||||
[expanded]="subfieldLegendExpanded"
|
||||
[collapsedGroupLimit]="3"
|
||||
(visibleChange)="onSubfieldLegendVisibleChange($event)"
|
||||
(expandedChange)="onSubfieldLegendExpandedChange($event)">
|
||||
</app-topic-legend>
|
||||
|
||||
<span
|
||||
*ngIf="
|
||||
|
||||
-125
@@ -64,131 +64,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
.subfield-legend {
|
||||
width: min(760px, 100%);
|
||||
box-sizing: border-box;
|
||||
margin-top: 16px;
|
||||
padding: 13px 16px;
|
||||
border: 1px solid #dbe5f6;
|
||||
border-radius: 8px;
|
||||
background: #ffffff;
|
||||
}
|
||||
|
||||
.subfield-legend-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.subfield-legend-title,
|
||||
.subfield-legend-visibility-toggle,
|
||||
.subfield-legend-content,
|
||||
.subfield-legend-group,
|
||||
.subfield-legend-items,
|
||||
.subfield-legend-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.subfield-legend-title {
|
||||
gap: 5px;
|
||||
color: #07163d;
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
.subfield-legend-info {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
color: #7d8aa8;
|
||||
font-size: 14px;
|
||||
line-height: 14px;
|
||||
}
|
||||
|
||||
.subfield-legend-visibility-toggle {
|
||||
flex: 0 0 auto;
|
||||
gap: 4px;
|
||||
color: var(--accent);
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
line-height: 1.2;
|
||||
|
||||
mat-icon {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
font-size: 14px;
|
||||
line-height: 14px;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
text-decoration: none;
|
||||
}
|
||||
}
|
||||
|
||||
.subfield-legend-content {
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 17px;
|
||||
}
|
||||
|
||||
.subfield-legend-group {
|
||||
gap: 9px;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
min-height: 28px;
|
||||
padding: 5px 9px;
|
||||
border: 1px solid #dbe5f6;
|
||||
border-radius: 999px;
|
||||
background: #fbfdff;
|
||||
}
|
||||
|
||||
.subfield-legend-field {
|
||||
flex: 0 0 auto;
|
||||
color: #07163d;
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
line-height: 1.2;
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.subfield-legend-items {
|
||||
flex-wrap: wrap;
|
||||
gap: 6px 11px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.subfield-legend-item {
|
||||
gap: 5px;
|
||||
min-width: 0;
|
||||
color: #53617e;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.subfield-legend-dot {
|
||||
flex: 0 0 auto;
|
||||
width: 9px;
|
||||
height: 9px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.85);
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 0 0 1px rgba(15, 23, 42, 0.2);
|
||||
}
|
||||
|
||||
.subfield-legend-more-toggle {
|
||||
flex: 0 0 auto;
|
||||
color: var(--accent);
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
|
||||
&:hover {
|
||||
text-decoration: none;
|
||||
}
|
||||
}
|
||||
|
||||
.view-toggle {
|
||||
justify-self: center;
|
||||
display: flex;
|
||||
|
||||
+19
-164
@@ -1,5 +1,4 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import {
|
||||
@@ -14,7 +13,13 @@ import {
|
||||
ViewChild,
|
||||
} from '@angular/core';
|
||||
import { TopicChipComponent } from '../../../../shared/ui/topic-chip/topic-chip.component';
|
||||
import { TopicLegendComponent } from '../../../../shared/ui/topic-legend/topic-legend.component';
|
||||
import { topicHierarchyColor } from '../../../../shared/utils/topic-colors';
|
||||
import {
|
||||
buildTopicLegendGroups,
|
||||
TopicLegendGroup,
|
||||
TopicLegendTopic,
|
||||
} from '../../../../shared/utils/topic-legend';
|
||||
import { buildTopicHierarchyTooltip } from '../../../../shared/utils/topic-tooltip';
|
||||
|
||||
export interface TopicTimelineTopic {
|
||||
@@ -78,33 +83,15 @@ interface TimelineScrollAnchor {
|
||||
scrollLeft: number;
|
||||
}
|
||||
|
||||
interface TopicSubfieldLegendItem {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
color: string;
|
||||
tooltip: string;
|
||||
}
|
||||
|
||||
interface TopicFieldLegendGroup {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
domainName: string;
|
||||
domainDescription: string;
|
||||
tooltip: string;
|
||||
items: TopicSubfieldLegendItem[];
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-research-timeline',
|
||||
standalone: true,
|
||||
imports: [
|
||||
CommonModule,
|
||||
MatIconModule,
|
||||
MatProgressSpinnerModule,
|
||||
MatTooltipModule,
|
||||
TopicChipComponent,
|
||||
TopicLegendComponent,
|
||||
],
|
||||
templateUrl: './research-timeline.component.html',
|
||||
styleUrl: './research-timeline.component.scss',
|
||||
@@ -123,6 +110,7 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
|
||||
@Input() endYear: number | undefined;
|
||||
@Input() subfieldLegendVisible = true;
|
||||
@Input() subfieldLegendExpanded = false;
|
||||
@Input() wordCloudLegendTopics: TopicLegendTopic[] = [];
|
||||
|
||||
@Output() viewModeChange = new EventEmitter<TimelineViewMode>();
|
||||
@Output() yearRangeChange = new EventEmitter<TimelineYearRange>();
|
||||
@@ -142,7 +130,6 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
|
||||
private readonly columnWidth = 240;
|
||||
private readonly displayedTopicLimit = 3;
|
||||
private readonly displayedPhaseTopicLimit = 4;
|
||||
private readonly collapsedSubfieldLegendGroupLimit = 3;
|
||||
private readonly scrollRestoreThreshold = 24;
|
||||
private readonly expandedPhaseIds = new Set<string>();
|
||||
|
||||
@@ -198,30 +185,8 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
|
||||
return this.buildCompactPhases(this.timelineItems);
|
||||
}
|
||||
|
||||
get subfieldLegendGroups(): TopicFieldLegendGroup[] {
|
||||
const groups = this.allSubfieldLegendGroups;
|
||||
|
||||
if (this.subfieldLegendExpanded) {
|
||||
return groups;
|
||||
}
|
||||
|
||||
return groups.slice(0, this.collapsedSubfieldLegendGroupLimit);
|
||||
}
|
||||
|
||||
get hiddenSubfieldLegendItemCount(): number {
|
||||
if (this.subfieldLegendExpanded) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return this.allSubfieldLegendGroups
|
||||
.slice(this.collapsedSubfieldLegendGroupLimit)
|
||||
.reduce((count, group) => count + group.items.length, 0);
|
||||
}
|
||||
|
||||
get showSubfieldLegendToggle(): boolean {
|
||||
return (
|
||||
this.subfieldLegendExpanded || this.hiddenSubfieldLegendItemCount > 0
|
||||
);
|
||||
get topicLegendGroups(): TopicLegendGroup[] {
|
||||
return this.allSubfieldLegendGroups;
|
||||
}
|
||||
|
||||
get hasYearRange(): boolean {
|
||||
@@ -416,33 +381,6 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
|
||||
return this.getTopicTooltip(topic).length > 0;
|
||||
}
|
||||
|
||||
buildLegendTooltip(
|
||||
entries: Array<{ label: string; value: string; description: string }>,
|
||||
): string {
|
||||
const lines: string[] = [];
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!entry.value && !entry.description) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (lines.length > 0) {
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (entry.value) {
|
||||
lines.push(`${entry.label}: ${entry.value}`);
|
||||
}
|
||||
|
||||
if (entry.description) {
|
||||
lines.push('');
|
||||
lines.push(`Beschreibung: ${entry.description}`);
|
||||
}
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
getYearTopicCountTooltip(
|
||||
topic: TopicTimelineTopic,
|
||||
item: TopicTimelineElement,
|
||||
@@ -477,24 +415,16 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
|
||||
return topicHierarchyColor(topic);
|
||||
}
|
||||
|
||||
toggleSubfieldLegend(): void {
|
||||
this.subfieldLegendExpanded = !this.subfieldLegendExpanded;
|
||||
onSubfieldLegendExpandedChange(expanded: boolean): void {
|
||||
this.subfieldLegendExpanded = expanded;
|
||||
this.subfieldLegendExpandedChange.emit(this.subfieldLegendExpanded);
|
||||
}
|
||||
|
||||
toggleSubfieldLegendVisibility(): void {
|
||||
this.subfieldLegendVisible = !this.subfieldLegendVisible;
|
||||
onSubfieldLegendVisibleChange(visible: boolean): void {
|
||||
this.subfieldLegendVisible = visible;
|
||||
this.subfieldLegendVisibleChange.emit(this.subfieldLegendVisible);
|
||||
}
|
||||
|
||||
trackByLegendGroup(_: number, group: TopicFieldLegendGroup): string {
|
||||
return group.id;
|
||||
}
|
||||
|
||||
trackByLegendItem(_: number, item: TopicSubfieldLegendItem): string {
|
||||
return item.id;
|
||||
}
|
||||
|
||||
trackByYear(_: number, item: TopicTimelineElement): number {
|
||||
return item.year;
|
||||
}
|
||||
@@ -641,91 +571,16 @@ export class ResearchTimelineComponent implements OnChanges, AfterViewChecked {
|
||||
);
|
||||
}
|
||||
|
||||
private get allSubfieldLegendGroups(): TopicFieldLegendGroup[] {
|
||||
if (
|
||||
this.loading ||
|
||||
this.loadFailed ||
|
||||
this.timelineViewMode === 'wordcloud'
|
||||
) {
|
||||
private get allSubfieldLegendGroups(): TopicLegendGroup[] {
|
||||
if (this.loading || this.loadFailed) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const groups = new Map<string, TopicFieldLegendGroup>();
|
||||
|
||||
for (const topic of this.visibleLegendTopics) {
|
||||
const subfieldName = topic.subfield_name?.trim();
|
||||
|
||||
if (!subfieldName) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const fieldName = topic.field_name?.trim() || 'Ohne Field';
|
||||
const fieldKey = topic.field_id ?? this.normalizeTopicName(fieldName);
|
||||
const subfieldKey =
|
||||
topic.subfield_id ?? this.normalizeTopicName(subfieldName);
|
||||
|
||||
if (!groups.has(fieldKey)) {
|
||||
groups.set(fieldKey, {
|
||||
id: fieldKey,
|
||||
name: fieldName,
|
||||
description: topic.field_description?.trim() ?? '',
|
||||
domainName: topic.domain_name?.trim() ?? '',
|
||||
domainDescription: topic.domain_description?.trim() ?? '',
|
||||
tooltip: this.buildLegendTooltip([
|
||||
{
|
||||
label: 'Fachgebiet',
|
||||
value: fieldName,
|
||||
description: topic.field_description?.trim() ?? '',
|
||||
},
|
||||
{
|
||||
label: 'Wissenschaftsbereich',
|
||||
value: topic.domain_name?.trim() ?? '',
|
||||
description: topic.domain_description?.trim() ?? '',
|
||||
},
|
||||
]),
|
||||
items: [],
|
||||
});
|
||||
}
|
||||
|
||||
const group = groups.get(fieldKey);
|
||||
|
||||
if (!group || group.items.some((item) => item.id === subfieldKey)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
group.items.push({
|
||||
id: subfieldKey,
|
||||
name: subfieldName,
|
||||
description: topic.subfield_description?.trim() ?? '',
|
||||
color: this.getTopicColor(topic),
|
||||
tooltip: this.buildLegendTooltip([
|
||||
{
|
||||
label: 'Themenbereich',
|
||||
value: subfieldName,
|
||||
description: topic.subfield_description?.trim() ?? '',
|
||||
},
|
||||
{
|
||||
label: 'Fachgebiet',
|
||||
value: fieldName,
|
||||
description: topic.field_description?.trim() ?? '',
|
||||
},
|
||||
{
|
||||
label: 'Wissenschaftsbereich',
|
||||
value: topic.domain_name?.trim() ?? '',
|
||||
description: topic.domain_description?.trim() ?? '',
|
||||
},
|
||||
]),
|
||||
});
|
||||
if (this.timelineViewMode === 'wordcloud') {
|
||||
return buildTopicLegendGroups(this.wordCloudLegendTopics);
|
||||
}
|
||||
|
||||
return [...groups.values()]
|
||||
.map((group) => ({
|
||||
...group,
|
||||
items: group.items.sort((left, right) =>
|
||||
left.name.localeCompare(right.name),
|
||||
),
|
||||
}))
|
||||
.sort((left, right) => left.name.localeCompare(right.name));
|
||||
return buildTopicLegendGroups(this.visibleLegendTopics);
|
||||
}
|
||||
|
||||
private get visibleLegendTopics(): TopicTimelineTopic[] {
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
[endYear]="timelineEndYear"
|
||||
[subfieldLegendVisible]="timelineLegendVisible"
|
||||
[subfieldLegendExpanded]="timelineLegendExpanded"
|
||||
[wordCloudLegendTopics]="wordCloudLegendTopics"
|
||||
(viewModeChange)="onTimelineViewModeChange($event)"
|
||||
(yearRangeChange)="onTimelineYearRangeChange($event)"
|
||||
(subfieldLegendVisibleChange)="onTimelineLegendVisibleChange($event)"
|
||||
@@ -21,12 +22,24 @@
|
||||
<div timeline-wordcloud-content class="word-cloud-view">
|
||||
@if (loadingWordCloud) {
|
||||
<div class="word-cloud-state">Forschungsthemen werden geladen ...</div>
|
||||
} @else if (wordCloudOptions) {
|
||||
<div
|
||||
echarts
|
||||
[options]="wordCloudOptions"
|
||||
(chartClick)="onWordClick($event)"
|
||||
class="word-cloud-chart"></div>
|
||||
} @else if (wordCloudWords.length) {
|
||||
<div class="word-cloud-chart">
|
||||
@for (word of wordCloudWords; track word.name) {
|
||||
<button
|
||||
type="button"
|
||||
class="word-cloud-word"
|
||||
[style.color]="word.color"
|
||||
[style.fontSize.px]="word.fontSize"
|
||||
[style.fontWeight]="word.fontWeight"
|
||||
[disabled]="!word.topicId"
|
||||
[matTooltip]="word.tooltip"
|
||||
[matTooltipDisabled]="!word.tooltip"
|
||||
matTooltipClass="topic-chip-tooltip"
|
||||
(click)="onWordClick(word)">
|
||||
{{ word.name }}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
} @else if (wordCloudEmpty) {
|
||||
<p class="word-cloud-empty">Keine Forschungsthemen gefunden.</p>
|
||||
}
|
||||
|
||||
@@ -11,8 +11,37 @@
|
||||
|
||||
.word-cloud-chart {
|
||||
width: 100%;
|
||||
height: 420px;
|
||||
min-height: 420px;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-content: center;
|
||||
align-items: baseline;
|
||||
justify-content: center;
|
||||
gap: 0.35em 1em;
|
||||
padding: 1.5rem 1rem;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.word-cloud-word {
|
||||
appearance: none;
|
||||
border: none;
|
||||
background: none;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
font-family: 'Open Sans', Arial, sans-serif;
|
||||
line-height: 1.1;
|
||||
cursor: pointer;
|
||||
transition: transform 0.15s ease;
|
||||
|
||||
&:hover:not(:disabled),
|
||||
&:focus-visible {
|
||||
transform: scale(1.08);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
cursor: default;
|
||||
}
|
||||
}
|
||||
|
||||
.word-cloud-state,
|
||||
|
||||
@@ -2,12 +2,13 @@ import { CommonModule } from '@angular/common';
|
||||
import { Component, DestroyRef, OnInit, inject } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { ActivatedRoute, ParamMap, Router } from '@angular/router';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { combineLatest, distinctUntilChanged, map } from 'rxjs';
|
||||
import { NgxEchartsDirective } from 'ngx-echarts';
|
||||
import type { EChartsOption } from 'echarts';
|
||||
import 'echarts-wordcloud';
|
||||
|
||||
import { TopicCount, TopicsByYear, WorksService } from '../../api';
|
||||
import { topicHierarchyColor } from '../../shared/utils/topic-colors';
|
||||
import { TopicLegendTopic } from '../../shared/utils/topic-legend';
|
||||
import { buildTopicHierarchyTooltip } from '../../shared/utils/topic-tooltip';
|
||||
import {
|
||||
ResearchTimelineComponent,
|
||||
TimelineViewMode,
|
||||
@@ -17,10 +18,20 @@ import {
|
||||
TopicTimelineTopic,
|
||||
} from './components/research-timeline/research-timeline.component';
|
||||
|
||||
export interface WordCloudWord {
|
||||
name: string;
|
||||
value: number;
|
||||
topicId: string | undefined;
|
||||
color: string;
|
||||
fontSize: number;
|
||||
fontWeight: number;
|
||||
tooltip: string;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-person-overview',
|
||||
standalone: true,
|
||||
imports: [CommonModule, ResearchTimelineComponent, NgxEchartsDirective],
|
||||
imports: [CommonModule, ResearchTimelineComponent, MatTooltipModule],
|
||||
templateUrl: './person-overview.component.html',
|
||||
styleUrl: './person-overview.component.scss',
|
||||
})
|
||||
@@ -56,7 +67,8 @@ export class PersonOverviewComponent implements OnInit {
|
||||
timelineLegendVisible = true;
|
||||
timelineLegendExpanded = false;
|
||||
|
||||
wordCloudOptions: EChartsOption | null = null;
|
||||
wordCloudWords: WordCloudWord[] = [];
|
||||
wordCloudLegendTopics: TopicLegendTopic[] = [];
|
||||
loadingWordCloud = false;
|
||||
wordCloudEmpty = false;
|
||||
|
||||
@@ -64,6 +76,12 @@ export class PersonOverviewComponent implements OnInit {
|
||||
name: string;
|
||||
topicId: string;
|
||||
year: number | undefined;
|
||||
fieldId: string | undefined;
|
||||
fieldName: string | undefined;
|
||||
domainId: string | undefined;
|
||||
domainName: string | undefined;
|
||||
subfieldId: string | undefined;
|
||||
subfieldName: string | undefined;
|
||||
}> = [];
|
||||
|
||||
ngOnInit(): void {
|
||||
@@ -199,17 +217,14 @@ export class PersonOverviewComponent implements OnInit {
|
||||
this.loadCompleteTopicTimeline(this.currentAuthorId);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
onWordClick(event: any): void {
|
||||
const topicId = event?.data?.topicId;
|
||||
const topicName = event?.data?.name;
|
||||
if (!topicId) return;
|
||||
onWordClick(word: WordCloudWord): void {
|
||||
if (!word.topicId) return;
|
||||
void this.router.navigate(['../publications'], {
|
||||
relativeTo: this.route,
|
||||
queryParams: {
|
||||
publicationPage: 1,
|
||||
publicationTopicId: topicId,
|
||||
publicationTopicName: topicName,
|
||||
publicationTopicId: word.topicId,
|
||||
publicationTopicName: word.name,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -331,17 +346,10 @@ export class PersonOverviewComponent implements OnInit {
|
||||
this.timelineEarlierYearsLoadFailed = false;
|
||||
}
|
||||
|
||||
private readonly timelineColors = [
|
||||
'#7255d9',
|
||||
'#2678e8',
|
||||
'#39a96b',
|
||||
'#f59e0b',
|
||||
'#e0527c',
|
||||
];
|
||||
|
||||
private loadWordCloud(authorId: string): void {
|
||||
if (!authorId || authorId === '0') {
|
||||
this.wordCloudOptions = null;
|
||||
this.wordCloudWords = [];
|
||||
this.wordCloudLegendTopics = [];
|
||||
this.wordCloudEmpty = false;
|
||||
this.loadingWordCloud = false;
|
||||
this.rawTopicOccurrences = [];
|
||||
@@ -350,7 +358,8 @@ export class PersonOverviewComponent implements OnInit {
|
||||
|
||||
this.loadingWordCloud = true;
|
||||
this.wordCloudEmpty = false;
|
||||
this.wordCloudOptions = null;
|
||||
this.wordCloudWords = [];
|
||||
this.wordCloudLegendTopics = [];
|
||||
|
||||
this.worksService
|
||||
.getAuthorWorks(authorId, 1, 100)
|
||||
@@ -366,6 +375,12 @@ export class PersonOverviewComponent implements OnInit {
|
||||
name: topic.display_name,
|
||||
topicId: topic.id,
|
||||
year,
|
||||
fieldId: topic.field?.id ?? undefined,
|
||||
fieldName: topic.field?.display_name ?? undefined,
|
||||
domainId: topic.domain?.id ?? undefined,
|
||||
domainName: topic.domain?.display_name ?? undefined,
|
||||
subfieldId: topic.subfield?.id ?? undefined,
|
||||
subfieldName: topic.subfield?.display_name ?? undefined,
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -374,6 +389,7 @@ export class PersonOverviewComponent implements OnInit {
|
||||
this.loadingWordCloud = false;
|
||||
|
||||
if (this.rawTopicOccurrences.length === 0) {
|
||||
this.wordCloudLegendTopics = [];
|
||||
this.wordCloudEmpty = true;
|
||||
return;
|
||||
}
|
||||
@@ -383,6 +399,7 @@ export class PersonOverviewComponent implements OnInit {
|
||||
error: (error) => {
|
||||
console.error('Word cloud could not be loaded.', error);
|
||||
this.loadingWordCloud = false;
|
||||
this.wordCloudLegendTopics = [];
|
||||
this.wordCloudEmpty = true;
|
||||
},
|
||||
});
|
||||
@@ -393,6 +410,7 @@ export class PersonOverviewComponent implements OnInit {
|
||||
const end = this.timelineEndYear;
|
||||
const counts = new Map<string, number>();
|
||||
const nameToId = new Map<string, string>();
|
||||
const nameToColorInput = new Map<string, TopicLegendTopic>();
|
||||
|
||||
for (const occ of this.rawTopicOccurrences) {
|
||||
if (start !== undefined && (occ.year === undefined || occ.year < start))
|
||||
@@ -400,11 +418,24 @@ export class PersonOverviewComponent implements OnInit {
|
||||
if (end !== undefined && (occ.year === undefined || occ.year > end))
|
||||
continue;
|
||||
counts.set(occ.name, (counts.get(occ.name) ?? 0) + 1);
|
||||
if (!nameToId.has(occ.name)) nameToId.set(occ.name, occ.topicId);
|
||||
if (!nameToId.has(occ.name)) {
|
||||
nameToId.set(occ.name, occ.topicId);
|
||||
nameToColorInput.set(occ.name, {
|
||||
id: occ.topicId,
|
||||
name: occ.name,
|
||||
field_id: occ.fieldId,
|
||||
field_name: occ.fieldName,
|
||||
domain_id: occ.domainId,
|
||||
domain_name: occ.domainName,
|
||||
subfield_id: occ.subfieldId,
|
||||
subfield_name: occ.subfieldName,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (counts.size === 0) {
|
||||
this.wordCloudOptions = null;
|
||||
this.wordCloudWords = [];
|
||||
this.wordCloudLegendTopics = [];
|
||||
this.wordCloudEmpty = true;
|
||||
return;
|
||||
}
|
||||
@@ -414,51 +445,45 @@ export class PersonOverviewComponent implements OnInit {
|
||||
const allValues = Array.from(counts.values());
|
||||
const minVal = Math.min(...allValues);
|
||||
const maxVal = Math.max(...allValues);
|
||||
const computeSize = (v: number): number =>
|
||||
maxVal === minVal
|
||||
? 22
|
||||
: Math.round(12 + ((v - minVal) / (maxVal - minVal)) * (32 - 12));
|
||||
const intensity = (v: number): number =>
|
||||
maxVal === minVal ? 1 : (v - minVal) / (maxVal - minVal);
|
||||
|
||||
const sorted = Array.from(counts.entries()).sort((a, b) => b[1] - a[1]);
|
||||
const topNames = sorted.slice(0, 30).map(([name]) => name);
|
||||
|
||||
const data = sorted.slice(0, 30).map(([name, value], i) => {
|
||||
const fontSize = computeSize(value);
|
||||
const color = this.timelineColors[i % this.timelineColors.length];
|
||||
this.wordCloudLegendTopics = topNames
|
||||
.map((name) => nameToColorInput.get(name))
|
||||
.filter((topic): topic is TopicLegendTopic => Boolean(topic));
|
||||
|
||||
const words = sorted.slice(0, 30).map(([name, value]): WordCloudWord => {
|
||||
const t = intensity(value);
|
||||
const colorInput = nameToColorInput.get(name);
|
||||
return {
|
||||
name,
|
||||
value,
|
||||
topicId: nameToId.get(name),
|
||||
textStyle: { color, fontSize },
|
||||
emphasis: {
|
||||
textStyle: {
|
||||
fontSize: Math.round(fontSize * 1.1),
|
||||
color,
|
||||
shadowBlur: 16,
|
||||
shadowColor: 'rgba(0, 87, 255, 0.35)',
|
||||
},
|
||||
},
|
||||
color: topicHierarchyColor(colorInput),
|
||||
fontSize: Math.round(12 + t * (32 - 12)),
|
||||
fontWeight: t > 0.66 ? 800 : t > 0.33 ? 600 : 400,
|
||||
tooltip: buildTopicHierarchyTooltip({
|
||||
topicName: name,
|
||||
subfieldName: colorInput?.subfield_name,
|
||||
fieldName: colorInput?.field_name,
|
||||
domainName: colorInput?.domain_name,
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
this.wordCloudOptions = {
|
||||
series: [
|
||||
{
|
||||
type: 'wordCloud',
|
||||
rotationRange: [0, 0],
|
||||
rotationStep: 0,
|
||||
gridSize: 4,
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
drawOutOfBound: false,
|
||||
textStyle: {
|
||||
fontFamily: 'Open Sans, sans-serif',
|
||||
fontWeight: 'bold',
|
||||
},
|
||||
data,
|
||||
},
|
||||
],
|
||||
} as any;
|
||||
const centred: WordCloudWord[] = [];
|
||||
words.forEach((word, i) => {
|
||||
if (i % 2 === 0) {
|
||||
centred.push(word);
|
||||
} else {
|
||||
centred.unshift(word);
|
||||
}
|
||||
});
|
||||
|
||||
this.wordCloudWords = centred;
|
||||
}
|
||||
|
||||
private mapTimelineElements(
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
<section
|
||||
*ngIf="hasGroups"
|
||||
class="topic-legend"
|
||||
[class.topic-legend-compact]="variant === 'compact'"
|
||||
[class.topic-legend-expanded]="expanded"
|
||||
aria-label="Aktuell sichtbare Themenbereiche">
|
||||
<div *ngIf="hasHeader" class="topic-legend-header">
|
||||
<div *ngIf="showTitle" class="topic-legend-title">
|
||||
<span>{{ title }}</span>
|
||||
<mat-icon
|
||||
class="topic-legend-info"
|
||||
[matTooltip]="infoTooltip"
|
||||
matTooltipPosition="above"
|
||||
aria-label="Informationen zur Farblegende">
|
||||
info_outline
|
||||
</mat-icon>
|
||||
</div>
|
||||
|
||||
<button
|
||||
*ngIf="showVisibilityToggle"
|
||||
type="button"
|
||||
class="topic-legend-visibility-toggle"
|
||||
[attr.aria-expanded]="visible"
|
||||
(click)="toggleVisibility()">
|
||||
<span>{{ visible ? 'Legende ausblenden' : 'Legende einblenden' }}</span>
|
||||
<mat-icon aria-hidden="true">
|
||||
{{ visible ? 'expand_less' : 'expand_more' }}
|
||||
</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
*ngIf="visible"
|
||||
class="topic-legend-body"
|
||||
[class.topic-legend-body-inline-info]="!hasHeader">
|
||||
<mat-icon
|
||||
*ngIf="!hasHeader"
|
||||
class="topic-legend-info topic-legend-info-inline"
|
||||
[matTooltip]="infoTooltip"
|
||||
matTooltipPosition="above"
|
||||
aria-label="Informationen zur Farblegende">
|
||||
info_outline
|
||||
</mat-icon>
|
||||
|
||||
<div class="topic-legend-content">
|
||||
<div
|
||||
*ngFor="let group of visibleGroups; trackBy: trackByGroup"
|
||||
class="topic-legend-group">
|
||||
<span
|
||||
class="topic-legend-field"
|
||||
[matTooltip]="group.tooltip"
|
||||
[matTooltipDisabled]="!group.tooltip"
|
||||
matTooltipClass="topic-chip-tooltip"
|
||||
matTooltipPosition="above">
|
||||
<span
|
||||
class="topic-legend-dot"
|
||||
[style.background]="group.color"
|
||||
aria-hidden="true"></span>
|
||||
<span>{{ group.name }}</span>
|
||||
</span>
|
||||
|
||||
<span class="topic-legend-items">
|
||||
<span
|
||||
*ngFor="let item of group.items; trackBy: trackByItem"
|
||||
class="topic-legend-item"
|
||||
[matTooltip]="item.tooltip"
|
||||
[matTooltipDisabled]="!item.tooltip"
|
||||
matTooltipClass="topic-chip-tooltip"
|
||||
matTooltipPosition="above">
|
||||
{{ item.name }}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<button
|
||||
*ngIf="showExpandedToggle"
|
||||
type="button"
|
||||
class="topic-legend-more-toggle"
|
||||
[attr.aria-expanded]="expanded"
|
||||
(click)="toggleExpanded()">
|
||||
{{
|
||||
expanded
|
||||
? 'Weniger anzeigen'
|
||||
: '+' + hiddenLegendItemCount + ' weitere'
|
||||
}}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -0,0 +1,201 @@
|
||||
:host {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.topic-legend {
|
||||
--topic-legend-accent: #0057ff;
|
||||
|
||||
width: min(760px, 100%);
|
||||
box-sizing: border-box;
|
||||
margin-top: 16px;
|
||||
padding: 13px 16px;
|
||||
border: 1px solid #dbe5f6;
|
||||
border-radius: 8px;
|
||||
background: #ffffff;
|
||||
}
|
||||
|
||||
.topic-legend-header,
|
||||
.topic-legend-title,
|
||||
.topic-legend-visibility-toggle,
|
||||
.topic-legend-body,
|
||||
.topic-legend-content,
|
||||
.topic-legend-group,
|
||||
.topic-legend-field,
|
||||
.topic-legend-items {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.topic-legend-header {
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.topic-legend-title {
|
||||
gap: 5px;
|
||||
color: #07163d;
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
.topic-legend-info {
|
||||
flex: 0 0 auto;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
color: #7d8aa8;
|
||||
font-size: 14px;
|
||||
line-height: 14px;
|
||||
}
|
||||
|
||||
.topic-legend-visibility-toggle,
|
||||
.topic-legend-more-toggle {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--topic-legend-accent);
|
||||
cursor: pointer;
|
||||
font-family: inherit;
|
||||
font-weight: 700;
|
||||
|
||||
&:hover {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--topic-legend-accent);
|
||||
outline-offset: 2px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
.topic-legend-visibility-toggle {
|
||||
flex: 0 0 auto;
|
||||
gap: 4px;
|
||||
padding: 0;
|
||||
font-size: 11px;
|
||||
line-height: 1.2;
|
||||
|
||||
mat-icon {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
font-size: 14px;
|
||||
line-height: 14px;
|
||||
}
|
||||
}
|
||||
|
||||
.topic-legend-body {
|
||||
align-items: flex-start;
|
||||
gap: 9px;
|
||||
margin-top: 17px;
|
||||
}
|
||||
|
||||
.topic-legend-body-inline-info {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.topic-legend-content {
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.topic-legend-group {
|
||||
gap: 9px;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
min-height: 28px;
|
||||
padding: 5px 9px;
|
||||
border: 1px solid #dbe5f6;
|
||||
border-radius: 999px;
|
||||
background: #fbfdff;
|
||||
}
|
||||
|
||||
.topic-legend-field {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
gap: 5px;
|
||||
color: #07163d;
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
line-height: 1.2;
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.topic-legend-field span:last-child,
|
||||
.topic-legend-item {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.topic-legend-dot {
|
||||
flex: 0 0 auto;
|
||||
width: 9px;
|
||||
height: 9px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.85);
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 0 0 1px rgba(15, 23, 42, 0.2);
|
||||
}
|
||||
|
||||
.topic-legend-items {
|
||||
flex: 0 1 auto;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px 11px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.topic-legend-item {
|
||||
color: #53617e;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.topic-legend-more-toggle {
|
||||
flex: 0 0 auto;
|
||||
padding: 0;
|
||||
font-size: 11px;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
.topic-legend-compact {
|
||||
width: fit-content;
|
||||
max-width: 100%;
|
||||
margin: 0 0 16px;
|
||||
padding: 8px 10px;
|
||||
|
||||
.topic-legend-body {
|
||||
gap: 9px;
|
||||
}
|
||||
|
||||
.topic-legend-content {
|
||||
gap: 7px;
|
||||
}
|
||||
|
||||
.topic-legend-group {
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
min-height: 24px;
|
||||
padding: 3px 7px;
|
||||
}
|
||||
|
||||
.topic-legend-field,
|
||||
.topic-legend-item {
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
.topic-legend-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
.topic-legend-more-toggle {
|
||||
min-height: 24px;
|
||||
padding: 0 2px;
|
||||
font-size: 11px;
|
||||
white-space: nowrap;
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Component, EventEmitter, Input, Output } from '@angular/core';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { TopicLegendGroup, TopicLegendItem } from '../../utils/topic-legend';
|
||||
|
||||
export type TopicLegendVariant = 'default' | 'compact';
|
||||
|
||||
@Component({
|
||||
selector: 'app-topic-legend',
|
||||
standalone: true,
|
||||
imports: [CommonModule, MatIconModule, MatTooltipModule],
|
||||
templateUrl: './topic-legend.component.html',
|
||||
styleUrl: './topic-legend.component.scss',
|
||||
})
|
||||
export class TopicLegendComponent {
|
||||
@Input() groups: TopicLegendGroup[] = [];
|
||||
@Input() title = 'Farben nach Fachgebiet';
|
||||
@Input() infoTooltip =
|
||||
'Fachgebiete bestimmen die Farbe. Themenbereiche werden darunter gruppiert.';
|
||||
@Input() visible = true;
|
||||
@Input() expanded = false;
|
||||
@Input() showTitle = true;
|
||||
@Input() showVisibilityToggle = true;
|
||||
@Input() collapsedGroupLimit = 3;
|
||||
@Input() variant: TopicLegendVariant = 'default';
|
||||
|
||||
@Output() visibleChange = new EventEmitter<boolean>();
|
||||
@Output() expandedChange = new EventEmitter<boolean>();
|
||||
|
||||
get hasGroups(): boolean {
|
||||
return this.groups.length > 0;
|
||||
}
|
||||
|
||||
get hasHeader(): boolean {
|
||||
return this.showTitle || this.showVisibilityToggle;
|
||||
}
|
||||
|
||||
get visibleGroups(): TopicLegendGroup[] {
|
||||
if (this.expanded) {
|
||||
return this.groups;
|
||||
}
|
||||
|
||||
return this.groups.slice(0, this.collapsedGroupLimit);
|
||||
}
|
||||
|
||||
get hiddenLegendItemCount(): number {
|
||||
if (this.expanded) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return this.groups
|
||||
.slice(this.collapsedGroupLimit)
|
||||
.reduce((count, group) => count + group.items.length, 0);
|
||||
}
|
||||
|
||||
get showExpandedToggle(): boolean {
|
||||
return this.expanded || this.hiddenLegendItemCount > 0;
|
||||
}
|
||||
|
||||
toggleVisibility(): void {
|
||||
this.visibleChange.emit(!this.visible);
|
||||
}
|
||||
|
||||
toggleExpanded(): void {
|
||||
this.expandedChange.emit(!this.expanded);
|
||||
}
|
||||
|
||||
trackByGroup(_: number, group: TopicLegendGroup): string {
|
||||
return group.id;
|
||||
}
|
||||
|
||||
trackByItem(_: number, item: TopicLegendItem): string {
|
||||
return item.id;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
export interface TopicHierarchyColorInput {
|
||||
id?: string | null;
|
||||
name?: string | null;
|
||||
subfield_id?: string | null;
|
||||
subfield_name?: string | null;
|
||||
field_id?: string | null;
|
||||
field_name?: string | null;
|
||||
domain_id?: string | null;
|
||||
@@ -52,30 +50,8 @@ const DOMAIN_FALLBACK_HUES: Record<string, number> = {
|
||||
'social sciences': 24,
|
||||
};
|
||||
|
||||
interface SubfieldColorVariant {
|
||||
hueOffset: number;
|
||||
saturation: number;
|
||||
lightness: number;
|
||||
}
|
||||
|
||||
const SUBFIELD_COLOR_VARIANTS: readonly SubfieldColorVariant[] = [
|
||||
{ hueOffset: -6, saturation: 92, lightness: 27 },
|
||||
{ hueOffset: 6, saturation: 82, lightness: 48 },
|
||||
{ hueOffset: -2, saturation: 90, lightness: 35 },
|
||||
{ hueOffset: 7, saturation: 78, lightness: 42 },
|
||||
{ hueOffset: -8, saturation: 86, lightness: 31 },
|
||||
{ hueOffset: 3, saturation: 94, lightness: 24 },
|
||||
{ hueOffset: 8, saturation: 84, lightness: 38 },
|
||||
{ hueOffset: -4, saturation: 80, lightness: 45 },
|
||||
{ hueOffset: 0, saturation: 92, lightness: 30 },
|
||||
{ hueOffset: 8, saturation: 76, lightness: 50 },
|
||||
{ hueOffset: -7, saturation: 88, lightness: 40 },
|
||||
{ hueOffset: 4, saturation: 80, lightness: 33 },
|
||||
{ hueOffset: -8, saturation: 82, lightness: 47 },
|
||||
{ hueOffset: 2, saturation: 96, lightness: 26 },
|
||||
{ hueOffset: 8, saturation: 86, lightness: 36 },
|
||||
{ hueOffset: -2, saturation: 78, lightness: 43 },
|
||||
];
|
||||
const FIELD_COLOR_SATURATION = 86;
|
||||
const FIELD_COLOR_LIGHTNESS = 36;
|
||||
|
||||
export function topicHierarchyColor(
|
||||
topic: TopicHierarchyColorInput | undefined | null,
|
||||
@@ -86,29 +62,22 @@ export function topicHierarchyColor(
|
||||
|
||||
const fieldKey = normalizeColorKey(topic.field_name);
|
||||
const domainKey = normalizeColorKey(topic.domain_name);
|
||||
const fieldIdentity =
|
||||
topic.field_id ?? fieldKey ?? topic.domain_id ?? domainKey;
|
||||
const subfieldIdentity =
|
||||
topic.subfield_id ??
|
||||
normalizeColorKey(topic.subfield_name) ??
|
||||
const fieldIdentity = topic.field_id ?? fieldKey;
|
||||
const fallbackIdentity =
|
||||
fieldIdentity ??
|
||||
topic.domain_id ??
|
||||
domainKey ??
|
||||
topic.id ??
|
||||
normalizeColorKey(topic.name) ??
|
||||
fieldIdentity ??
|
||||
'topic';
|
||||
|
||||
const baseHue =
|
||||
(fieldKey ? FIELD_HUES[fieldKey] : undefined) ??
|
||||
(domainKey ? DOMAIN_FALLBACK_HUES[domainKey] : undefined) ??
|
||||
stableHue(fieldIdentity ?? subfieldIdentity);
|
||||
stableHue(fallbackIdentity);
|
||||
const hue = normalizeHue(baseHue);
|
||||
|
||||
const variantHash = stableHash(subfieldIdentity);
|
||||
const variant =
|
||||
SUBFIELD_COLOR_VARIANTS[variantHash % SUBFIELD_COLOR_VARIANTS.length];
|
||||
const hue = normalizeHue(baseHue + variant.hueOffset);
|
||||
const saturation = variant.saturation;
|
||||
const lightness = variant.lightness;
|
||||
|
||||
return `hsl(${hue} ${saturation}% ${lightness}%)`;
|
||||
return `hsl(${hue} ${FIELD_COLOR_SATURATION}% ${FIELD_COLOR_LIGHTNESS}%)`;
|
||||
}
|
||||
|
||||
function normalizeColorKey(
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
import { topicHierarchyColor, TopicHierarchyColorInput } from './topic-colors';
|
||||
|
||||
export interface TopicLegendTopic extends TopicHierarchyColorInput {
|
||||
subfield_id?: string | null;
|
||||
subfield_name?: string | null;
|
||||
subfield_description?: string | null;
|
||||
field_description?: string | null;
|
||||
domain_description?: string | null;
|
||||
}
|
||||
|
||||
export interface TopicLegendItem {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
tooltip: string;
|
||||
}
|
||||
|
||||
export interface TopicLegendGroup {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
domainName: string;
|
||||
domainDescription: string;
|
||||
color: string;
|
||||
tooltip: string;
|
||||
items: TopicLegendItem[];
|
||||
}
|
||||
|
||||
export function buildTopicLegendGroups(
|
||||
topics: readonly TopicLegendTopic[],
|
||||
): TopicLegendGroup[] {
|
||||
const groups = new Map<string, TopicLegendGroup>();
|
||||
|
||||
for (const topic of topics) {
|
||||
const subfieldName = normalizeLegendValue(topic.subfield_name);
|
||||
|
||||
if (!subfieldName) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const fieldName =
|
||||
normalizeLegendValue(topic.field_name) ?? 'Ohne Fachgebiet';
|
||||
const fieldDescription =
|
||||
normalizeLegendValue(topic.field_description) ?? '';
|
||||
const domainName = normalizeLegendValue(topic.domain_name) ?? '';
|
||||
const domainDescription =
|
||||
normalizeLegendValue(topic.domain_description) ?? '';
|
||||
const subfieldDescription =
|
||||
normalizeLegendValue(topic.subfield_description) ?? '';
|
||||
const fieldKey = topic.field_id ?? normalizeLegendKey(fieldName);
|
||||
const subfieldKey = topic.subfield_id ?? normalizeLegendKey(subfieldName);
|
||||
|
||||
if (!groups.has(fieldKey)) {
|
||||
groups.set(fieldKey, {
|
||||
id: fieldKey,
|
||||
name: fieldName,
|
||||
description: fieldDescription,
|
||||
domainName,
|
||||
domainDescription,
|
||||
color: topicHierarchyColor(topic),
|
||||
tooltip: buildTopicLegendTooltip([
|
||||
{
|
||||
label: 'Fachgebiet',
|
||||
value: fieldName,
|
||||
description: fieldDescription,
|
||||
},
|
||||
{
|
||||
label: 'Wissenschaftsbereich',
|
||||
value: domainName,
|
||||
description: domainDescription,
|
||||
},
|
||||
]),
|
||||
items: [],
|
||||
});
|
||||
}
|
||||
|
||||
const group = groups.get(fieldKey);
|
||||
|
||||
if (!group || group.items.some((item) => item.id === subfieldKey)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
group.items.push({
|
||||
id: subfieldKey,
|
||||
name: subfieldName,
|
||||
description: subfieldDescription,
|
||||
tooltip: buildTopicLegendTooltip([
|
||||
{
|
||||
label: 'Themenbereich',
|
||||
value: subfieldName,
|
||||
description: subfieldDescription,
|
||||
},
|
||||
{
|
||||
label: 'Fachgebiet',
|
||||
value: fieldName,
|
||||
description: fieldDescription,
|
||||
},
|
||||
{
|
||||
label: 'Wissenschaftsbereich',
|
||||
value: domainName,
|
||||
description: domainDescription,
|
||||
},
|
||||
]),
|
||||
});
|
||||
}
|
||||
|
||||
return [...groups.values()]
|
||||
.map((group) => ({
|
||||
...group,
|
||||
items: group.items.sort((left, right) =>
|
||||
left.name.localeCompare(right.name),
|
||||
),
|
||||
}))
|
||||
.sort((left, right) => left.name.localeCompare(right.name));
|
||||
}
|
||||
|
||||
function buildTopicLegendTooltip(
|
||||
entries: Array<{ label: string; value: string; description: string }>,
|
||||
): string {
|
||||
const lines: string[] = [];
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!entry.value && !entry.description) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (lines.length > 0) {
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (entry.value) {
|
||||
lines.push(`${entry.label}: ${entry.value}`);
|
||||
}
|
||||
|
||||
if (entry.description) {
|
||||
lines.push('');
|
||||
lines.push(`Beschreibung: ${entry.description}`);
|
||||
}
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
function normalizeLegendValue(value: string | null | undefined): string | null {
|
||||
const normalized = value?.trim();
|
||||
|
||||
return normalized || null;
|
||||
}
|
||||
|
||||
function normalizeLegendKey(value: string): string {
|
||||
return value.trim().toLowerCase();
|
||||
}
|
||||
Reference in New Issue
Block a user