Merge branch 'dev' into ts-136-patent-to-researchers-v2
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
Resolve conflicts in patent module re-export shims by keeping the refactored search_client and modular logic layout from this branch.
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" \
|
||||
"openai~=2.41.0"
|
||||
|
||||
COPY [ "src/main", "/home" ]
|
||||
|
||||
@@ -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, 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,24 +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 get(
|
||||
index: ESIndex,
|
||||
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"}
|
||||
|
||||
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
|
||||
|
||||
|
||||
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"}
|
||||
|
||||
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
|
||||
|
||||
|
||||
async def scan(
|
||||
index: str,
|
||||
query: Dict,
|
||||
source: Optional[List] = None,
|
||||
page_size: int = 1000,
|
||||
keep_alive: str = "1m",
|
||||
cluster: str = "nes",
|
||||
) -> 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 = await open_point_in_time(index, keep_alive=keep_alive, cluster=cluster)
|
||||
search_after: Optional[List] = None
|
||||
try:
|
||||
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
|
||||
|
||||
try:
|
||||
response = await client.post(
|
||||
f"{elasticsearch_url}/_search", json=payload, headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
result = response.json()
|
||||
|
||||
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
|
||||
finally:
|
||||
try:
|
||||
await close_point_in_time(pit_id, cluster=cluster)
|
||||
except Exception:
|
||||
logger.exception("Failed to close Elasticsearch point-in-time.")
|
||||
|
||||
|
||||
async def get(
|
||||
index: ESIndex | str,
|
||||
doc_id: str,
|
||||
source: Optional[list] = None,
|
||||
cluster: ESCluster = ESCluster.NES,
|
||||
@@ -187,9 +324,56 @@ 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
|
||||
|
||||
|
||||
async def update(
|
||||
index: str,
|
||||
doc_id: str,
|
||||
doc: Dict[str, Any],
|
||||
cluster: ESCluster = ESCluster.NES,
|
||||
) -> Dict[str, Any]:
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
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
|
||||
|
||||
|
||||
async def index_doc(
|
||||
index: str,
|
||||
doc_id: str,
|
||||
document: Dict[str, Any],
|
||||
cluster: ESCluster = ESCluster.NES,
|
||||
) -> Dict[str, Any]:
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
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
|
||||
@@ -83,11 +89,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/")
|
||||
|
||||
@@ -4,33 +4,69 @@
|
||||
Business logic for the "aktuell" news index on the INSE cluster.
|
||||
"""
|
||||
|
||||
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
|
||||
from ..integrations import elasticsearch, llm
|
||||
from ..persons.logic import find_ude_author_by_name, get_author_name_by_id
|
||||
from .model import MentionedPerson, NewsArticle, NewsArticleDetail, NewsPage
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
TOPIC_LIMIT = 4
|
||||
TOPIC_QUERY_CONTENT_CHARS = 300
|
||||
TOPIC_NUM_CANDIDATES = 100
|
||||
TOPIC_SIMILARITY = 0.5
|
||||
|
||||
def get_news_page(page: int, page_size: int, sort_order: str = "desc") -> NewsPage:
|
||||
KEYWORD_LIMIT = 6
|
||||
KEYWORD_CONTENT_CHARS = 4000
|
||||
KEYWORD_SYSTEM_PROMPT = """\
|
||||
Extrahiere aus dem folgenden Nachrichtenartikel die wichtigsten Schlagwörter (Keywords).
|
||||
Gib maximal sechs prägnante Begriffe oder kurze Phrasen zurück, die den inhaltlichen Kern
|
||||
des Artikels erfassen. Antworte ausschließlich mit einem JSON-Array von Strings, ohne
|
||||
weiteren Text, zum Beispiel ["Künstliche Intelligenz", "Klimaforschung"].
|
||||
"""
|
||||
|
||||
RELATED_BLOCK_SIZE = 5
|
||||
RELATED_TOPIC_K = 1
|
||||
EXACT_ID_CAP = 1000
|
||||
|
||||
|
||||
async def get_news_page(
|
||||
page: int,
|
||||
page_size: int,
|
||||
sort_order: str = "desc",
|
||||
year_from: int | None = None,
|
||||
year_to: int | None = None,
|
||||
relevance_values: list | None = None,
|
||||
) -> NewsPage:
|
||||
offset = (page - 1) * page_size
|
||||
|
||||
response = _run_search(
|
||||
query={"match_all": {}},
|
||||
source=["date", "maintitle", "author", "url"],
|
||||
clauses = await _filter_clauses(year_from, year_to, relevance_values)
|
||||
query = {"bool": {"filter": clauses}} if clauses else {"match_all": {}}
|
||||
|
||||
response = await _run_search(
|
||||
query=query,
|
||||
source=["date", "maintitle", "author", "url", "intro_content", "full_content"],
|
||||
size=page_size,
|
||||
offset=offset,
|
||||
sort=[{"date_full": sort_order}],
|
||||
)
|
||||
|
||||
return _build_page(response, page, page_size)
|
||||
return await _build_page(response, page, page_size)
|
||||
|
||||
|
||||
def search_news(query_text: str, page: int, page_size: int) -> NewsPage:
|
||||
async def search_news(
|
||||
query_text: str,
|
||||
page: int,
|
||||
page_size: int,
|
||||
year_from: int | None = None,
|
||||
year_to: int | None = None,
|
||||
relevance_values: list | None = None,
|
||||
) -> NewsPage:
|
||||
offset = (page - 1) * page_size
|
||||
|
||||
highlight = {
|
||||
@@ -40,8 +76,16 @@ def search_news(query_text: str, page: int, page_size: int) -> NewsPage:
|
||||
"encoder": "html",
|
||||
}
|
||||
|
||||
response = _run_search(
|
||||
query={"match": {"full_content": query_text}},
|
||||
# Filter einmal berechnen (der Relevanz-Filter macht eine ES-Abfrage).
|
||||
clauses = await _filter_clauses(year_from, year_to, relevance_values)
|
||||
exact_query = {
|
||||
"bool": {
|
||||
"must": [{"match": {"full_content": query_text}}],
|
||||
"filter": clauses,
|
||||
}
|
||||
}
|
||||
response = await _run_search(
|
||||
query=exact_query,
|
||||
source=["date", "maintitle", "author", "url"],
|
||||
size=page_size,
|
||||
offset=offset,
|
||||
@@ -49,9 +93,20 @@ def search_news(query_text: str, page: int, page_size: int) -> NewsPage:
|
||||
highlight=highlight,
|
||||
)
|
||||
|
||||
return _build_page(response, page, page_size)
|
||||
news_page = await _build_page(response, page, page_size)
|
||||
|
||||
def get_news_by_author(
|
||||
if _is_last_page(page, page_size, news_page.total):
|
||||
exclude_ids = await _exact_match_ids(exact_query)
|
||||
news_page.results.extend(
|
||||
await _related_articles(
|
||||
query_text, exclude_ids=exclude_ids, extra_filters=clauses
|
||||
)
|
||||
)
|
||||
|
||||
return news_page
|
||||
|
||||
|
||||
async def get_news_by_author(
|
||||
author_id: str,
|
||||
page: int = 1,
|
||||
page_size: int = 10,
|
||||
@@ -59,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)
|
||||
|
||||
@@ -74,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,
|
||||
@@ -82,13 +137,71 @@ def get_news_by_author(
|
||||
sort=[{"date_full": sort_order}],
|
||||
)
|
||||
|
||||
return _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 = await _exact_match_ids(es_query)
|
||||
news_page.results.extend(
|
||||
await _related_articles(
|
||||
query_text, exclude_ids=exclude_ids, filter_news_ids=news_ids
|
||||
)
|
||||
)
|
||||
|
||||
return news_page
|
||||
|
||||
|
||||
def _find_news_ids_for_author(author_name: str) -> list:
|
||||
async def _filter_clauses(
|
||||
year_from: int | None,
|
||||
year_to: int | None,
|
||||
relevance_values: list | None,
|
||||
) -> list:
|
||||
clauses = []
|
||||
|
||||
if year_from is not None or year_to is not None:
|
||||
date_range = {}
|
||||
if year_from is not None:
|
||||
date_range["gte"] = year_from
|
||||
if year_to is not None:
|
||||
date_range["lte"] = year_to
|
||||
clauses.append({"range": {"date_year": date_range}})
|
||||
|
||||
relevant_ids = await _relevance_news_ids(relevance_values)
|
||||
if relevant_ids is not None:
|
||||
clauses.append({"ids": {"values": relevant_ids}})
|
||||
|
||||
return clauses
|
||||
|
||||
|
||||
async def _relevance_news_ids(relevance_values: list | None) -> list | None:
|
||||
selected = set(relevance_values or [])
|
||||
|
||||
if not selected or {"relevant", "not_relevant"} <= selected:
|
||||
return None
|
||||
|
||||
relevant_value = 1 if "relevant" in selected else 0
|
||||
|
||||
news_ids = []
|
||||
try:
|
||||
async for hit in elasticsearch.scan(
|
||||
index="aktuell_postproc",
|
||||
query={"term": {"relevant": relevant_value}},
|
||||
source=["news_id"],
|
||||
cluster="inse",
|
||||
):
|
||||
news_id = hit.get("_source", {}).get("news_id")
|
||||
if news_id:
|
||||
news_ids.append(news_id)
|
||||
except Exception:
|
||||
logger.exception("Relevanz-IDs aus aktuell_postproc konnten nicht geladen werden.")
|
||||
return []
|
||||
|
||||
return news_ids
|
||||
|
||||
|
||||
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"],
|
||||
@@ -112,24 +225,29 @@ 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 = _get_postproc_labels(news_id)
|
||||
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,
|
||||
source.get("maintitle"),
|
||||
source.get("full_content"),
|
||||
)
|
||||
|
||||
return NewsArticleDetail(
|
||||
id=response.get("_id"),
|
||||
@@ -139,17 +257,131 @@ 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 _build_mentioned_persons(author_names: list) -> 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 = await _topic_vector_search(query, TOPIC_LIMIT, ["display_name"])
|
||||
return [topic["display_name"] for topic in topics if topic.get("display_name")]
|
||||
|
||||
|
||||
async def _get_article_keywords(
|
||||
news_id: str,
|
||||
postproc_id: str | None,
|
||||
cached_keywords: list,
|
||||
maintitle: str | None,
|
||||
full_content: str | None,
|
||||
) -> list:
|
||||
if cached_keywords:
|
||||
return cached_keywords
|
||||
|
||||
text = " ".join(
|
||||
part for part in (maintitle, (full_content or "")[:KEYWORD_CONTENT_CHARS]) if part
|
||||
).strip()
|
||||
if not text:
|
||||
return []
|
||||
|
||||
raw = llm.call(
|
||||
system_prompt=KEYWORD_SYSTEM_PROMPT,
|
||||
user_prompt=f"Artikel:\n{text}",
|
||||
temperature=0.3,
|
||||
)
|
||||
keywords = _parse_keywords(raw)
|
||||
|
||||
if keywords:
|
||||
await _store_keywords(news_id, postproc_id, keywords)
|
||||
|
||||
return keywords
|
||||
|
||||
|
||||
def _parse_keywords(raw: str) -> list:
|
||||
raw = (raw or "").strip()
|
||||
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
candidates = parsed if isinstance(parsed, list) else []
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
candidates = re.split(r"[,\n]", raw)
|
||||
|
||||
seen = set()
|
||||
keywords = []
|
||||
for item in candidates:
|
||||
term = str(item).strip().strip('"').strip()
|
||||
if term and term.lower() not in seen:
|
||||
seen.add(term.lower())
|
||||
keywords.append(term)
|
||||
|
||||
return keywords[:KEYWORD_LIMIT]
|
||||
|
||||
|
||||
async def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) -> None:
|
||||
try:
|
||||
if postproc_id:
|
||||
await elasticsearch.update(
|
||||
index="aktuell_postproc",
|
||||
doc_id=postproc_id,
|
||||
doc={"keywords": keywords},
|
||||
cluster="inse",
|
||||
)
|
||||
else:
|
||||
await elasticsearch.index_doc(
|
||||
index="aktuell_postproc",
|
||||
doc_id=news_id,
|
||||
document={"news_id": news_id, "keywords": keywords},
|
||||
cluster="inse",
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(f"Failed to cache keywords for {news_id}.")
|
||||
|
||||
|
||||
async def _topic_vector_search(query_text: str, k: int, source_fields: list) -> list:
|
||||
try:
|
||||
from ..util import get_model
|
||||
|
||||
query_vector = get_model().encode(query_text).tolist()
|
||||
except Exception:
|
||||
logger.exception("Failed to encode text for topic vector search.")
|
||||
return []
|
||||
|
||||
try:
|
||||
response = await elasticsearch.search(
|
||||
index="topicvectors",
|
||||
body={
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": k,
|
||||
"num_candidates": TOPIC_NUM_CANDIDATES,
|
||||
"similarity": TOPIC_SIMILARITY,
|
||||
},
|
||||
"_source": source_fields,
|
||||
"size": k,
|
||||
},
|
||||
cluster="nes",
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Topic vector search failed.")
|
||||
return []
|
||||
|
||||
return [hit.get("_source", {}) for hit in response.get("hits", {}).get("hits", [])]
|
||||
|
||||
|
||||
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"])
|
||||
@@ -160,33 +392,35 @@ def _build_mentioned_persons(author_names: list) -> list:
|
||||
return ude_persons + other_persons
|
||||
|
||||
|
||||
def _get_postproc_labels(news_id: str) -> tuple[bool | None, list]:
|
||||
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"],
|
||||
source=["relevant", "authors", "keywords"],
|
||||
size=1,
|
||||
cluster="inse",
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(f"Postproc-Lookup for {news_id} failed.")
|
||||
return None, []
|
||||
return None, [], [], None
|
||||
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
return None, []
|
||||
return None, [], [], None
|
||||
|
||||
postproc_source = hits[0].get("_source", {})
|
||||
hit = hits[0]
|
||||
postproc_source = hit.get("_source", {})
|
||||
relevant = bool(postproc_source.get("relevant", 0))
|
||||
authors = postproc_source.get("authors") or []
|
||||
keywords = postproc_source.get("keywords") or []
|
||||
|
||||
return relevant, authors
|
||||
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,
|
||||
@@ -197,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", [])
|
||||
@@ -216,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:
|
||||
@@ -232,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"],
|
||||
@@ -262,7 +493,11 @@ def _parse_hit(hit: dict) -> NewsArticle:
|
||||
source = hit.get("_source", {})
|
||||
|
||||
fragments = hit.get("highlight", {}).get("full_content")
|
||||
snippet = fragments[0] if fragments else None
|
||||
|
||||
if fragments:
|
||||
snippet = fragments[0]
|
||||
else:
|
||||
snippet = _make_preview(source)
|
||||
|
||||
return NewsArticle(
|
||||
id=hit.get("_id"),
|
||||
@@ -272,3 +507,104 @@ def _parse_hit(hit: dict) -> NewsArticle:
|
||||
url=source.get("url"),
|
||||
snippet=snippet,
|
||||
)
|
||||
|
||||
|
||||
def _make_preview(source: dict) -> str | None:
|
||||
text = source.get("intro_content") or source.get("full_content")
|
||||
|
||||
if not text:
|
||||
return None
|
||||
|
||||
words = text.split()
|
||||
|
||||
PREVIEW_WORD_COUNT = 10
|
||||
preview = " ".join(words[:PREVIEW_WORD_COUNT])
|
||||
if len(words) > PREVIEW_WORD_COUNT:
|
||||
preview = preview + " …"
|
||||
return preview
|
||||
|
||||
|
||||
def _is_last_page(page: int, page_size: int, total: int) -> bool:
|
||||
return page * page_size >= total
|
||||
|
||||
|
||||
async def _exact_match_ids(query: dict) -> list:
|
||||
try:
|
||||
response = await _run_search(
|
||||
query=query,
|
||||
source=[],
|
||||
size=EXACT_ID_CAP,
|
||||
offset=0,
|
||||
sort=None,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Failed to collect exact-match ids for dedup.")
|
||||
return []
|
||||
|
||||
return [
|
||||
hit.get("_id")
|
||||
for hit in response.get("hits", {}).get("hits", [])
|
||||
if hit.get("_id")
|
||||
]
|
||||
|
||||
|
||||
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 = await _related_search_terms(query_text)
|
||||
if not related_terms:
|
||||
return []
|
||||
|
||||
bool_query = {
|
||||
"should": [{"match": {"full_content": term}} for term in related_terms],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
if exclude_ids:
|
||||
bool_query["must_not"] = [{"ids": {"values": exclude_ids}}]
|
||||
if filter_news_ids is not None:
|
||||
bool_query["filter"] = [{"ids": {"values": filter_news_ids}}]
|
||||
if extra_filters:
|
||||
bool_query.setdefault("filter", []).extend(extra_filters)
|
||||
|
||||
try:
|
||||
response = await elasticsearch.search(
|
||||
index="aktuell",
|
||||
query={"bool": bool_query},
|
||||
source=["date", "maintitle", "author", "url", "intro_content", "full_content"],
|
||||
size=k,
|
||||
offset=0,
|
||||
cluster="inse",
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Related-articles search failed.")
|
||||
return []
|
||||
|
||||
articles = []
|
||||
for hit in response.get("hits", {}).get("hits", []):
|
||||
article = _parse_hit(hit)
|
||||
article.related = True
|
||||
articles.append(article)
|
||||
|
||||
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
|
||||
|
||||
|
||||
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 = []
|
||||
for topic in topics:
|
||||
for term in [topic.get("display_name"), *(topic.get("keywords") or [])]:
|
||||
if term and term.lower() not in seen:
|
||||
seen.add(term.lower())
|
||||
terms.append(term)
|
||||
|
||||
return terms
|
||||
|
||||
@@ -14,6 +14,7 @@ class NewsArticle(BaseModel):
|
||||
url: Optional[str] = None
|
||||
relevant: Optional[bool] = None
|
||||
snippet: Optional[str] = None
|
||||
related: Optional[bool] = None
|
||||
|
||||
|
||||
class MentionedPerson(BaseModel):
|
||||
@@ -26,6 +27,8 @@ class NewsArticleDetail(NewsArticle):
|
||||
full_content: Optional[str] = None
|
||||
relevant: Optional[bool] = None
|
||||
authors: List[MentionedPerson] = []
|
||||
topics: List[str] = []
|
||||
keywords: List[str] = []
|
||||
|
||||
|
||||
class NewsPage(BaseModel):
|
||||
|
||||
@@ -16,6 +16,15 @@ from .model import NewsArticleDetail, NewsPage
|
||||
|
||||
router = APIRouter(prefix="/api/news", tags=[Tags.NEWS])
|
||||
|
||||
ALLOWED_RELEVANCE_VALUES = {"relevant", "not_relevant"}
|
||||
|
||||
|
||||
def _parse_relevance(relevance: str | None) -> list:
|
||||
if not relevance:
|
||||
return []
|
||||
values = [entry.strip() for entry in relevance.split(",")]
|
||||
return [value for value in values if value in ALLOWED_RELEVANCE_VALUES]
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
@@ -25,7 +34,7 @@ router = APIRouter(prefix="/api/news", tags=[Tags.NEWS])
|
||||
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,
|
||||
@@ -35,8 +44,24 @@ def list_news(
|
||||
sort_order: Annotated[
|
||||
str, Query(alias="sortOrder", description="Sort order: 'desc' (newest first) or 'asc' (oldest first).", pattern="^(asc|desc)$")
|
||||
] = "desc",
|
||||
relevance: Annotated[
|
||||
str | None, Query(description="Comma-separated relevance filter: 'relevant', 'not_relevant'.")
|
||||
] = None,
|
||||
year_from: Annotated[
|
||||
int | None, Query(alias="yearFrom", description="Earliest publication year (inclusive).", ge=0)
|
||||
] = None,
|
||||
year_to: Annotated[
|
||||
int | None, Query(alias="yearTo", description="Latest publication year (inclusive).", ge=0)
|
||||
] = None,
|
||||
):
|
||||
return logic.get_news_page(page, page_size, sort_order)
|
||||
return await logic.get_news_page(
|
||||
page,
|
||||
page_size,
|
||||
sort_order,
|
||||
year_from=year_from,
|
||||
year_to=year_to,
|
||||
relevance_values=_parse_relevance(relevance),
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -47,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)
|
||||
],
|
||||
@@ -57,8 +82,24 @@ def search_news(
|
||||
page_size: Annotated[
|
||||
int, Query(alias="pageSize", description="Articles per page.", ge=1, le=100)
|
||||
] = 10,
|
||||
relevance: Annotated[
|
||||
str | None, Query(description="Comma-separated relevance filter: 'relevant', 'not_relevant'.")
|
||||
] = None,
|
||||
year_from: Annotated[
|
||||
int | None, Query(alias="yearFrom", description="Earliest publication year (inclusive).", ge=0)
|
||||
] = None,
|
||||
year_to: Annotated[
|
||||
int | None, Query(alias="yearTo", description="Latest publication year (inclusive).", ge=0)
|
||||
] = None,
|
||||
):
|
||||
return logic.search_news(query, page, page_size)
|
||||
return await logic.search_news(
|
||||
query,
|
||||
page,
|
||||
page_size,
|
||||
year_from=year_from,
|
||||
year_to=year_to,
|
||||
relevance_values=_parse_relevance(relevance),
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -69,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.")
|
||||
],
|
||||
@@ -86,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(
|
||||
@@ -97,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"
|
||||
@@ -233,15 +236,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)
|
||||
@@ -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)
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -7,6 +7,7 @@ import { personResolver } from './resolvers/person.resolver';
|
||||
import { institutionResolver } from './resolvers/institution.resolver';
|
||||
import { bundProjectPageResolver } from './resolvers/bund-project-page.resolver';
|
||||
import { dfgProjectsResolver } from './resolvers/dfg-projects.resolver';
|
||||
import { personNewsResolver } from './resolvers/person-news.resolver';
|
||||
import { institutionsResolver } from './resolvers/institutions.resolver';
|
||||
import { bundProjectsFundingResolver } from './resolvers/bund-projects-funding.resolver';
|
||||
import { dfgSingleProjectResolver } from './resolvers/dfg-single-project-resolver';
|
||||
@@ -57,8 +58,15 @@ export const routes: Routes = [
|
||||
},
|
||||
runGuardsAndResolvers: (to, from) => {
|
||||
const keys = [
|
||||
'query', 'page', 'pageSize', 'institutionName',
|
||||
'sortBy', 'sortOrder', 'yearFilterEnabled', 'filterMode', 'filterYear',
|
||||
'query',
|
||||
'page',
|
||||
'pageSize',
|
||||
'institutionName',
|
||||
'sortBy',
|
||||
'sortOrder',
|
||||
'yearFilterEnabled',
|
||||
'filterMode',
|
||||
'filterYear',
|
||||
];
|
||||
const scalarChanged = keys.some(
|
||||
(key) => to.queryParamMap.get(key) !== from.queryParamMap.get(key),
|
||||
@@ -71,6 +79,20 @@ export const routes: Routes = [
|
||||
return scalarChanged || topicsChanged;
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'news',
|
||||
canActivate: [userGuard],
|
||||
loadComponent: () =>
|
||||
import('./modules/news/news.component').then((mod) => mod.NewsComponent),
|
||||
},
|
||||
{
|
||||
path: 'news/:id',
|
||||
canActivate: [userGuard],
|
||||
loadComponent: () =>
|
||||
import('./modules/news-detail/news-detail.component').then(
|
||||
(mod) => mod.NewsDetailComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'publication/:publicationId',
|
||||
canActivate: [userGuard],
|
||||
@@ -110,7 +132,7 @@ export const routes: Routes = [
|
||||
),
|
||||
resolve: { bundSingleProject: bundSingleProjectResolver },
|
||||
},
|
||||
{
|
||||
{
|
||||
path: 'projects/eu/:id',
|
||||
canActivate: [userGuard],
|
||||
pathMatch: 'full',
|
||||
@@ -149,7 +171,10 @@ export const routes: Routes = [
|
||||
import('./modules/person-projects/person-projects.component').then(
|
||||
(mod) => mod.PersonProjectsComponent,
|
||||
),
|
||||
resolve: { dfgProjectPage: dfgProjectsResolver },
|
||||
resolve: {
|
||||
dfgProjectPage: dfgProjectsResolver,
|
||||
personCordisEuProjectPage: personCordisEuProjectPageResolver,
|
||||
},
|
||||
runGuardsAndResolvers: (from, to) => {
|
||||
const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search'];
|
||||
return keys.some(
|
||||
@@ -173,9 +198,15 @@ export const routes: Routes = [
|
||||
resolve: { collaborationNetwork: collaborationNetworkResolver },
|
||||
runGuardsAndResolvers: (from, to) => {
|
||||
const keys = [
|
||||
'filter_by', 'start_year', 'end_year', 'min_contributors',
|
||||
'max_contributors', 'min_collaborations', 'max_collaborations',
|
||||
'institutions', 'topics',
|
||||
'filter_by',
|
||||
'start_year',
|
||||
'end_year',
|
||||
'min_contributors',
|
||||
'max_contributors',
|
||||
'min_collaborations',
|
||||
'max_collaborations',
|
||||
'institutions',
|
||||
'topics',
|
||||
];
|
||||
return keys.some(
|
||||
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
|
||||
@@ -282,7 +313,12 @@ export const routes: Routes = [
|
||||
resolve: { fundingProjectPage: fundingProjectPageResolver },
|
||||
runGuardsAndResolvers: (from, to) => {
|
||||
const keys = [
|
||||
'search', 'page', 'size', 'selected_project_types', 'sort_by', 'sorting_order',
|
||||
'search',
|
||||
'page',
|
||||
'size',
|
||||
'selected_project_types',
|
||||
'sort_by',
|
||||
'sorting_order',
|
||||
];
|
||||
return keys.some(
|
||||
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
|
||||
@@ -313,7 +349,8 @@ export const routes: Routes = [
|
||||
data: {
|
||||
routeStatusCode: 404,
|
||||
routeTitle: 'Seite nicht gefunden',
|
||||
routeMessage: 'Die gesuchte Seite existiert leider nicht oder wurde verschoben.',
|
||||
routeMessage:
|
||||
'Die gesuchte Seite existiert leider nicht oder wurde verschoben.',
|
||||
},
|
||||
canActivate: [userGuard],
|
||||
},
|
||||
|
||||
@@ -107,13 +107,21 @@
|
||||
<div class="sidebar-card">
|
||||
<h3>
|
||||
<mat-icon>label</mat-icon>
|
||||
Relevante Themen
|
||||
Schlüsselwörter
|
||||
</h3>
|
||||
<div class="chip-list">
|
||||
@for (topic of relevantTopics; track topic; let i = $index) {
|
||||
<span class="topic-chip" [ngClass]="chipColor(i)">{{
|
||||
topic
|
||||
}}</span>
|
||||
@if (article.keywords && article.keywords.length) {
|
||||
@for (
|
||||
keyword of article.keywords;
|
||||
track keyword;
|
||||
let i = $index
|
||||
) {
|
||||
<span class="topic-chip" [ngClass]="chipColor(i)">{{
|
||||
keyword
|
||||
}}</span>
|
||||
}
|
||||
} @else {
|
||||
<p class="placeholder">Keine Schlüsselwörter gefunden.</p>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -180,6 +180,9 @@ main {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
max-height: 375px;
|
||||
overflow-y: auto;
|
||||
padding-right: 4px;
|
||||
}
|
||||
|
||||
.person-item {
|
||||
|
||||
@@ -24,6 +24,7 @@ interface NewsArticleDetail {
|
||||
full_content?: string | null;
|
||||
relevant?: boolean;
|
||||
authors?: MentionedPerson[];
|
||||
keywords?: string[];
|
||||
}
|
||||
|
||||
@Component({
|
||||
@@ -49,13 +50,6 @@ export class NewsDetailComponent implements OnInit {
|
||||
loading = false;
|
||||
notFound = false;
|
||||
|
||||
readonly relevantTopics = [
|
||||
'Künstliche Intelligenz',
|
||||
'Maschinelles Lernen',
|
||||
'Digitalisierung',
|
||||
'Datenwissenschaft',
|
||||
];
|
||||
|
||||
private readonly chipColors = ['purple', 'blue', 'green', 'orange', 'pink'];
|
||||
|
||||
chipColor(index: number): string {
|
||||
|
||||
@@ -4,107 +4,31 @@
|
||||
<p>Aktuelle Nachrichten aus Campus-Aktuell.</p>
|
||||
</div>
|
||||
|
||||
<div class="news-toolbar">
|
||||
<mat-form-field appearance="outline" class="search-field">
|
||||
<mat-icon matPrefix>search</mat-icon>
|
||||
<input
|
||||
matInput
|
||||
[formControl]="searchControl"
|
||||
placeholder="Nachrichten durchsuchen..." />
|
||||
</mat-form-field>
|
||||
|
||||
@if (!isSearching) {
|
||||
<mat-form-field appearance="outline" class="sort-field">
|
||||
<mat-select
|
||||
[value]="sortOrder"
|
||||
(selectionChange)="onSortChange($event.value)">
|
||||
<mat-option value="desc">Neueste zuerst</mat-option>
|
||||
<mat-option value="asc">Älteste zuerst</mat-option>
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<ng-template #snippetTpl let-article>
|
||||
@if (article.snippet) {
|
||||
<span class="snippet" [innerHTML]="article.snippet"></span>
|
||||
} @else {
|
||||
<span class="snippet-empty">—</span>
|
||||
}
|
||||
</div>
|
||||
</ng-template>
|
||||
|
||||
<div class="table-wrap">
|
||||
@if (loading) {
|
||||
<div class="loading">
|
||||
<mat-spinner diameter="36"></mat-spinner>
|
||||
</div>
|
||||
}
|
||||
|
||||
<table mat-table [dataSource]="articles" class="mat-elevation-z2">
|
||||
<ng-container matColumnDef="maintitle">
|
||||
<th mat-header-cell *matHeaderCellDef>Titel</th>
|
||||
<td mat-cell *matCellDef="let article">
|
||||
<a class="article-title" [routerLink]="['/news', article.id]">{{
|
||||
article.maintitle || 'Kein Titel'
|
||||
}}</a>
|
||||
</td>
|
||||
</ng-container>
|
||||
|
||||
<ng-container matColumnDef="snippet">
|
||||
<th mat-header-cell *matHeaderCellDef>Fundstelle</th>
|
||||
<td mat-cell *matCellDef="let article">
|
||||
@if (article.snippet) {
|
||||
<span class="snippet" [innerHTML]="article.snippet"></span>
|
||||
} @else {
|
||||
<span class="snippet-empty">—</span>
|
||||
}
|
||||
</td>
|
||||
</ng-container>
|
||||
|
||||
<ng-container matColumnDef="relevance">
|
||||
<th mat-header-cell *matHeaderCellDef>Relevanz</th>
|
||||
<td mat-cell *matCellDef="let article">
|
||||
@if (article.relevant === true) {
|
||||
<span class="relevance-badge is-relevant">
|
||||
<mat-icon>check_circle</mat-icon>
|
||||
Relevant
|
||||
</span>
|
||||
} @else if (article.relevant === false) {
|
||||
<span class="relevance-badge not-relevant">
|
||||
<mat-icon>cancel</mat-icon>
|
||||
Nicht relevant
|
||||
</span>
|
||||
} @else {
|
||||
<span class="relevance-badge undetermined">
|
||||
<mat-icon>help</mat-icon>
|
||||
Nicht bestimmt
|
||||
</span>
|
||||
}
|
||||
</td>
|
||||
</ng-container>
|
||||
|
||||
<ng-container matColumnDef="date">
|
||||
<th mat-header-cell *matHeaderCellDef>Datum</th>
|
||||
<td mat-cell *matCellDef="let article">
|
||||
{{ formatDate(article.date) }}
|
||||
</td>
|
||||
</ng-container>
|
||||
|
||||
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
|
||||
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
|
||||
</table>
|
||||
|
||||
@if (!loading && articles.length === 0) {
|
||||
<div class="empty-state">
|
||||
@if (isSearching) {
|
||||
Keine Ergebnisse für „{{ searchControl.value.trim() }}" gefunden.
|
||||
} @else {
|
||||
Keine Nachrichten gefunden.
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="table-footer">
|
||||
<span>{{ articleRange() }}</span>
|
||||
<mat-paginator
|
||||
[length]="total"
|
||||
[pageIndex]="currentPage - 1"
|
||||
[pageSize]="paginationService.selection"
|
||||
[pageSizeOptions]="paginationService.options"
|
||||
(page)="onPage($event)">
|
||||
</mat-paginator>
|
||||
</div>
|
||||
<app-news-list
|
||||
[articles]="articles"
|
||||
[showFilters]="true"
|
||||
[displayedColumns]="displayedColumns"
|
||||
[total]="total"
|
||||
[loading]="loading"
|
||||
[currentPage]="currentPage"
|
||||
[sortOrder]="sortOrder"
|
||||
[searchControl]="searchControl"
|
||||
[initialRelevance]="relevanceValues"
|
||||
[initialYearFrom]="yearFrom"
|
||||
[initialYearTo]="yearTo"
|
||||
extraColumnId="snippet"
|
||||
extraColumnHeader="Inhalt"
|
||||
[extraColumnTemplate]="snippetTpl"
|
||||
(sortChange)="onSortChange($event)"
|
||||
(pageChange)="onPage($event)"
|
||||
(filtersChange)="onFiltersChange($event)">
|
||||
</app-news-list>
|
||||
</div>
|
||||
|
||||
@@ -17,107 +17,14 @@ h6 {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.news-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
padding-top: 10px;
|
||||
padding-bottom: 25px;
|
||||
}
|
||||
|
||||
.search-field {
|
||||
max-width: 480px;
|
||||
}
|
||||
|
||||
::ng-deep .news-toolbar .mat-mdc-form-field-subscript-wrapper {
|
||||
display: none;
|
||||
}
|
||||
|
||||
::ng-deep .news-toolbar .mat-mdc-text-field-wrapper {
|
||||
height: 42px;
|
||||
background: #fff;
|
||||
border-radius: var(--sg-radius-sm);
|
||||
}
|
||||
|
||||
::ng-deep .news-toolbar .mat-mdc-form-field-infix {
|
||||
min-height: unset;
|
||||
height: 42px;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
::ng-deep .news-toolbar .mdc-notched-outline__leading,
|
||||
::ng-deep .news-toolbar .mdc-notched-outline__notch,
|
||||
::ng-deep .news-toolbar .mdc-notched-outline__trailing {
|
||||
border-color: #d9e2f0;
|
||||
}
|
||||
|
||||
::ng-deep .news-toolbar input.mat-mdc-input-element {
|
||||
color: var(--sg-text);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
::ng-deep .news-toolbar input.mat-mdc-input-element::placeholder {
|
||||
color: var(--sg-text-muted);
|
||||
opacity: 1;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.sort-field {
|
||||
width: 180px;
|
||||
}
|
||||
|
||||
.table-wrap {
|
||||
position: relative;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
min-width: 600px;
|
||||
border-collapse: separate;
|
||||
border-spacing: 0 10px;
|
||||
background: transparent;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.article-title {
|
||||
display: inline-block;
|
||||
max-width: 520px;
|
||||
line-height: 1.35;
|
||||
color: var(--sg-text);
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
text-decoration: none;
|
||||
|
||||
&:hover {
|
||||
color: var(--sg-text);
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
|
||||
.loading {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 1;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: rgba(255, 255, 255, 0.65);
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
padding: 28px;
|
||||
text-align: center;
|
||||
color: rgba(0, 0, 0, 0.6);
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.snippet {
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
color: var(--sg-text-muted);
|
||||
font-size: 13px;
|
||||
line-height: 1.4;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
::ng-deep .snippet em {
|
||||
@@ -131,79 +38,8 @@ table {
|
||||
color: var(--sg-text-muted);
|
||||
}
|
||||
|
||||
.relevance-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 5px 12px;
|
||||
border-radius: 999px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
line-height: 1;
|
||||
white-space: nowrap;
|
||||
|
||||
mat-icon {
|
||||
font-size: 16px;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
}
|
||||
|
||||
&.is-relevant {
|
||||
background: #effaf3;
|
||||
border: 1px solid #bdebcf;
|
||||
color: #24834f;
|
||||
}
|
||||
|
||||
&.not-relevant {
|
||||
background: var(--sg-surface-muted);
|
||||
border: 1px solid #e2e2e2;
|
||||
color: var(--sg-text-muted);
|
||||
}
|
||||
|
||||
&.undetermined {
|
||||
background: #fff7e8;
|
||||
border: 1px solid #ffd796;
|
||||
color: #c67500;
|
||||
}
|
||||
}
|
||||
|
||||
::ng-deep .mat-mdc-header-cell {
|
||||
color: var(--sg-text-muted);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
::ng-deep .mat-mdc-row {
|
||||
height: 72px;
|
||||
}
|
||||
|
||||
::ng-deep .mat-mdc-cell {
|
||||
color: var(--sg-text);
|
||||
border-bottom-color: var(--sg-border);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
mat-paginator {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.table-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
min-height: 66px;
|
||||
padding: 0 22px 0 28px;
|
||||
color: var(--sg-text-muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.page {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.table-footer {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,27 +1,23 @@
|
||||
import { Component, DestroyRef, OnInit, inject } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { FormControl, ReactiveFormsModule } from '@angular/forms';
|
||||
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { MatPaginatorModule, PageEvent } from '@angular/material/paginator';
|
||||
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
|
||||
import { MatTableModule } from '@angular/material/table';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { PageEvent } from '@angular/material/paginator';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { debounceTime, distinctUntilChanged } from 'rxjs';
|
||||
|
||||
import { WorksService } from '../../api';
|
||||
import { PaginationService } from '../../shared/services/pagination.service';
|
||||
import {
|
||||
NewsArticleBase,
|
||||
NewsFilterState,
|
||||
NewsListComponent,
|
||||
NEWS_MIN_YEAR,
|
||||
SortOrder,
|
||||
} from '../../shared/ui/news-list/news-list.component';
|
||||
|
||||
interface NewsArticle {
|
||||
id: string;
|
||||
date?: string | null;
|
||||
maintitle?: string | null;
|
||||
interface NewsArticle extends NewsArticleBase {
|
||||
author?: string | null;
|
||||
url?: string | null;
|
||||
relevant?: boolean | null;
|
||||
snippet?: string | null;
|
||||
}
|
||||
|
||||
@@ -32,22 +28,11 @@ interface NewsPage {
|
||||
results: NewsArticle[];
|
||||
}
|
||||
|
||||
type SortOrder = 'desc' | 'asc';
|
||||
const DEFAULT_SORT_ORDER: SortOrder = 'desc';
|
||||
|
||||
@Component({
|
||||
selector: 'app-news',
|
||||
imports: [
|
||||
MatIconModule,
|
||||
MatSelectModule,
|
||||
MatFormFieldModule,
|
||||
MatInputModule,
|
||||
MatPaginatorModule,
|
||||
MatProgressSpinnerModule,
|
||||
MatTableModule,
|
||||
ReactiveFormsModule,
|
||||
RouterLink,
|
||||
],
|
||||
imports: [ReactiveFormsModule, NewsListComponent],
|
||||
templateUrl: './news.component.html',
|
||||
styleUrl: './news.component.scss',
|
||||
})
|
||||
@@ -61,12 +46,12 @@ export class NewsComponent implements OnInit {
|
||||
|
||||
readonly searchControl = new FormControl('', { nonNullable: true });
|
||||
|
||||
get displayedColumns(): string[] {
|
||||
if (this.isSearching) {
|
||||
return ['maintitle', 'snippet', 'relevance', 'date'];
|
||||
}
|
||||
return ['maintitle', 'relevance', 'date'];
|
||||
}
|
||||
readonly displayedColumns: string[] = [
|
||||
'maintitle',
|
||||
'snippet',
|
||||
'relevance',
|
||||
'date',
|
||||
];
|
||||
|
||||
articles: NewsArticle[] = [];
|
||||
total = 0;
|
||||
@@ -75,9 +60,12 @@ export class NewsComponent implements OnInit {
|
||||
currentPage = 1;
|
||||
sortOrder: SortOrder = DEFAULT_SORT_ORDER;
|
||||
|
||||
get isSearching(): boolean {
|
||||
return this.searchControl.value.trim().length > 0;
|
||||
}
|
||||
relevanceValues: string[] = [];
|
||||
yearFrom: number | null = null;
|
||||
yearTo: number | null = null;
|
||||
|
||||
private readonly minYear = NEWS_MIN_YEAR;
|
||||
private readonly maxYear = new Date().getFullYear();
|
||||
|
||||
ngOnInit(): void {
|
||||
this.route.queryParamMap
|
||||
@@ -88,6 +76,9 @@ export class NewsComponent implements OnInit {
|
||||
params.get('pageSize'),
|
||||
);
|
||||
this.sortOrder = this.parseSortOrder(params.get('sortOrder'));
|
||||
this.relevanceValues = this.parseRelevance(params.get('relevance'));
|
||||
this.yearFrom = this.parseYear(params.get('yearFrom'));
|
||||
this.yearTo = this.parseYear(params.get('yearTo'));
|
||||
this.searchControl.setValue(params.get('q') ?? '', {
|
||||
emitEvent: false,
|
||||
});
|
||||
@@ -115,10 +106,11 @@ export class NewsComponent implements OnInit {
|
||||
const basePath = this.worksService.configuration.basePath ?? '';
|
||||
|
||||
if (query) {
|
||||
const params = new HttpParams()
|
||||
let params = new HttpParams()
|
||||
.set('query', query)
|
||||
.set('page', this.currentPage)
|
||||
.set('pageSize', this.paginationService.selection);
|
||||
params = this.appendFilters(params);
|
||||
|
||||
this.httpClient
|
||||
.get<NewsPage>(`${basePath}/api/news/search`, { params })
|
||||
@@ -135,10 +127,11 @@ export class NewsComponent implements OnInit {
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const params = new HttpParams()
|
||||
let params = new HttpParams()
|
||||
.set('page', this.currentPage)
|
||||
.set('pageSize', this.paginationService.selection)
|
||||
.set('sortOrder', this.sortOrder);
|
||||
params = this.appendFilters(params);
|
||||
|
||||
this.httpClient
|
||||
.get<NewsPage>(`${basePath}/api/news`, { params })
|
||||
@@ -157,6 +150,19 @@ export class NewsComponent implements OnInit {
|
||||
}
|
||||
}
|
||||
|
||||
private appendFilters(params: HttpParams): HttpParams {
|
||||
if (this.relevanceValues.length > 0) {
|
||||
params = params.set('relevance', this.relevanceValues.join(','));
|
||||
}
|
||||
if (this.yearFrom !== null) {
|
||||
params = params.set('yearFrom', this.yearFrom);
|
||||
}
|
||||
if (this.yearTo !== null) {
|
||||
params = params.set('yearTo', this.yearTo);
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
onPage(event: PageEvent): void {
|
||||
this.router.navigate([], {
|
||||
relativeTo: this.route,
|
||||
@@ -179,19 +185,22 @@ export class NewsComponent implements OnInit {
|
||||
});
|
||||
}
|
||||
|
||||
formatDate(dateStr?: string | null): string {
|
||||
if (!dateStr) return '-';
|
||||
const date = new Date(dateStr);
|
||||
if (isNaN(date.getTime())) return dateStr;
|
||||
return new Intl.DateTimeFormat('de-DE').format(date);
|
||||
}
|
||||
onFiltersChange(state: NewsFilterState): void {
|
||||
const relevance =
|
||||
state.relevance.length > 0 ? state.relevance.join(',') : null;
|
||||
const yearFrom = state.yearFrom > this.minYear ? state.yearFrom : null;
|
||||
const yearTo = state.yearTo < this.maxYear ? state.yearTo : null;
|
||||
|
||||
articleRange(): string {
|
||||
if (this.total === 0) return 'Keine Nachrichten gefunden';
|
||||
const pageSize = this.paginationService.selection;
|
||||
const start = (this.currentPage - 1) * pageSize + 1;
|
||||
const end = Math.min(start + this.articles.length - 1, this.total);
|
||||
return `Zeige ${start} bis ${end} von ${this.total} Nachrichten`;
|
||||
this.router.navigate([], {
|
||||
relativeTo: this.route,
|
||||
queryParams: {
|
||||
relevance,
|
||||
yearFrom,
|
||||
yearTo,
|
||||
page: 1,
|
||||
},
|
||||
queryParamsHandling: 'merge',
|
||||
});
|
||||
}
|
||||
|
||||
private parsePage(value: string | null): number {
|
||||
@@ -216,4 +225,23 @@ export class NewsComponent implements OnInit {
|
||||
}
|
||||
return DEFAULT_SORT_ORDER;
|
||||
}
|
||||
|
||||
private parseRelevance(value: string | null): string[] {
|
||||
if (!value) {
|
||||
return [];
|
||||
}
|
||||
const allowed = ['relevant', 'not_relevant'];
|
||||
return value
|
||||
.split(',')
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => allowed.includes(entry));
|
||||
}
|
||||
|
||||
private parseYear(value: string | null): number | null {
|
||||
const year = Number.parseInt(value ?? '', 10);
|
||||
if (Number.isNaN(year)) {
|
||||
return null;
|
||||
}
|
||||
return year;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,79 +4,15 @@
|
||||
<p>Aktuelle Nachrichten zu dieser Person.</p>
|
||||
</div>
|
||||
|
||||
<div class="news-toolbar">
|
||||
<mat-form-field appearance="outline" class="search-field">
|
||||
<mat-icon matPrefix>search</mat-icon>
|
||||
<input
|
||||
matInput
|
||||
[formControl]="searchControl"
|
||||
placeholder="Nachrichten durchsuchen..." />
|
||||
</mat-form-field>
|
||||
|
||||
<mat-form-field appearance="outline" class="sort-field">
|
||||
<mat-select
|
||||
[value]="sortOrder"
|
||||
(selectionChange)="onSortChange($event.value)">
|
||||
<mat-option value="desc">Neueste zuerst</mat-option>
|
||||
<mat-option value="asc">Älteste zuerst</mat-option>
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
</div>
|
||||
|
||||
<div class="table-wrap">
|
||||
@if (loading) {
|
||||
<div class="loading">
|
||||
<mat-spinner diameter="36"></mat-spinner>
|
||||
</div>
|
||||
}
|
||||
|
||||
<table mat-table [dataSource]="articles" class="mat-elevation-z2">
|
||||
<ng-container matColumnDef="maintitle">
|
||||
<th mat-header-cell *matHeaderCellDef>Titel</th>
|
||||
<td mat-cell *matCellDef="let article">
|
||||
<a class="article-title" [routerLink]="['/news', article.id]">{{
|
||||
article.maintitle || 'Kein Titel'
|
||||
}}</a>
|
||||
</td>
|
||||
</ng-container>
|
||||
|
||||
<ng-container matColumnDef="author">
|
||||
<th mat-header-cell *matHeaderCellDef>Autor</th>
|
||||
<td mat-cell *matCellDef="let article">
|
||||
{{ article.author || '-' }}
|
||||
</td>
|
||||
</ng-container>
|
||||
|
||||
<ng-container matColumnDef="date">
|
||||
<th mat-header-cell *matHeaderCellDef>Datum</th>
|
||||
<td mat-cell *matCellDef="let article">
|
||||
{{ formatDate(article.date) }}
|
||||
</td>
|
||||
</ng-container>
|
||||
|
||||
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
|
||||
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
|
||||
</table>
|
||||
|
||||
@if (!loading && articles.length === 0) {
|
||||
<div class="empty-state">
|
||||
@if (isSearching) {
|
||||
Keine Ergebnisse für „{{ searchControl.value.trim() }}" gefunden.
|
||||
} @else {
|
||||
Keine Nachrichten gefunden.
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="table-footer">
|
||||
<span>{{ articleRange() }}</span>
|
||||
<mat-paginator
|
||||
[length]="total"
|
||||
[pageIndex]="currentPageIndex"
|
||||
[pageSize]="paginationService.selection"
|
||||
[pageSizeOptions]="paginationService.options"
|
||||
(page)="onPage($event)">
|
||||
</mat-paginator>
|
||||
</div>
|
||||
<app-news-list
|
||||
[articles]="articles"
|
||||
[displayedColumns]="displayedColumns"
|
||||
[total]="total"
|
||||
[loading]="loading"
|
||||
[currentPage]="currentPage"
|
||||
[sortOrder]="sortOrder"
|
||||
[searchControl]="searchControl"
|
||||
(sortChange)="onSortChange($event)"
|
||||
(pageChange)="onPage($event)">
|
||||
</app-news-list>
|
||||
</div>
|
||||
|
||||
@@ -17,140 +17,8 @@ h6 {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.news-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
padding-top: 10px;
|
||||
padding-bottom: 25px;
|
||||
}
|
||||
|
||||
.search-field {
|
||||
max-width: 480px;
|
||||
}
|
||||
|
||||
::ng-deep .news-toolbar .mat-mdc-form-field-subscript-wrapper {
|
||||
display: none;
|
||||
}
|
||||
|
||||
::ng-deep .news-toolbar .mat-mdc-text-field-wrapper {
|
||||
height: 42px;
|
||||
background: #fff;
|
||||
border-radius: var(--sg-radius-sm);
|
||||
}
|
||||
|
||||
::ng-deep .news-toolbar .mat-mdc-form-field-infix {
|
||||
min-height: unset;
|
||||
height: 42px;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
::ng-deep .news-toolbar .mdc-notched-outline__leading,
|
||||
::ng-deep .news-toolbar .mdc-notched-outline__notch,
|
||||
::ng-deep .news-toolbar .mdc-notched-outline__trailing {
|
||||
border-color: #d9e2f0;
|
||||
}
|
||||
|
||||
::ng-deep .news-toolbar input.mat-mdc-input-element {
|
||||
color: var(--sg-text);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
::ng-deep .news-toolbar input.mat-mdc-input-element::placeholder {
|
||||
color: var(--sg-text-muted);
|
||||
opacity: 1;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.sort-field {
|
||||
width: 180px;
|
||||
}
|
||||
|
||||
.table-wrap {
|
||||
position: relative;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
min-width: 600px;
|
||||
border-collapse: separate;
|
||||
border-spacing: 0 10px;
|
||||
background: transparent;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.article-title {
|
||||
display: inline-block;
|
||||
max-width: 520px;
|
||||
line-height: 1.35;
|
||||
color: var(--sg-text);
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
text-decoration: none;
|
||||
|
||||
&:hover {
|
||||
color: var(--sg-text);
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
|
||||
.loading {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 1;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: rgba(255, 255, 255, 0.65);
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
padding: 28px;
|
||||
text-align: center;
|
||||
color: rgba(0, 0, 0, 0.6);
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
::ng-deep .mat-mdc-header-cell {
|
||||
color: var(--sg-text-muted);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
::ng-deep .mat-mdc-row {
|
||||
height: 72px;
|
||||
}
|
||||
|
||||
::ng-deep .mat-mdc-cell {
|
||||
color: var(--sg-text);
|
||||
border-bottom-color: var(--sg-border);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
mat-paginator {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.table-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
min-height: 66px;
|
||||
padding: 0 22px 0 28px;
|
||||
color: var(--sg-text-muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.page {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.table-footer {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,33 +1,21 @@
|
||||
import { Component, DestroyRef, OnInit, inject } from '@angular/core';
|
||||
import { FormControl, ReactiveFormsModule } from '@angular/forms';
|
||||
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { MatPaginatorModule, PageEvent } from '@angular/material/paginator';
|
||||
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
|
||||
import { MatTableModule } from '@angular/material/table';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { PageEvent } from '@angular/material/paginator';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { debounceTime, distinctUntilChanged } from 'rxjs';
|
||||
|
||||
import { PaginationService } from '../../shared/services/pagination.service';
|
||||
import { ResolverStateService } from '../../shared/services/resolver-state.service';
|
||||
import { NewsArticle, NewsPage } from '../../resolvers/person-news.resolver';
|
||||
import {
|
||||
NewsListComponent,
|
||||
SortOrder,
|
||||
} from '../../shared/ui/news-list/news-list.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-person-news',
|
||||
imports: [
|
||||
MatIconModule,
|
||||
MatSelectModule,
|
||||
MatFormFieldModule,
|
||||
MatInputModule,
|
||||
MatPaginatorModule,
|
||||
MatProgressSpinnerModule,
|
||||
MatTableModule,
|
||||
ReactiveFormsModule,
|
||||
RouterLink,
|
||||
],
|
||||
imports: [ReactiveFormsModule, NewsListComponent],
|
||||
templateUrl: './person-news.component.html',
|
||||
styleUrl: './person-news.component.scss',
|
||||
})
|
||||
@@ -40,11 +28,11 @@ export class PersonNewsComponent implements OnInit {
|
||||
|
||||
readonly searchControl = new FormControl('', { nonNullable: true });
|
||||
|
||||
displayedColumns = ['maintitle', 'author', 'date'];
|
||||
displayedColumns = ['maintitle', 'relevance', 'date'];
|
||||
articles: NewsArticle[] = [];
|
||||
total = 0;
|
||||
currentPageIndex = 0;
|
||||
sortOrder: 'desc' | 'asc' = 'desc';
|
||||
currentPage = 1;
|
||||
sortOrder: SortOrder = 'desc';
|
||||
|
||||
get loading(): boolean {
|
||||
return this.resolverStateService.isResolving();
|
||||
@@ -75,7 +63,7 @@ export class PersonNewsComponent implements OnInit {
|
||||
const sortOrder = params.get('sortOrder');
|
||||
const query = params.get('query') ?? '';
|
||||
|
||||
this.currentPageIndex = page - 1;
|
||||
this.currentPage = page;
|
||||
this.paginationService.selection = pageSize;
|
||||
this.sortOrder = sortOrder === 'asc' ? 'asc' : 'desc';
|
||||
this.searchControl.setValue(query, { emitEvent: false });
|
||||
@@ -103,30 +91,13 @@ export class PersonNewsComponent implements OnInit {
|
||||
});
|
||||
}
|
||||
|
||||
onSortChange(order: 'desc' | 'asc'): void {
|
||||
onSortChange(order: SortOrder): void {
|
||||
this.updateQueryParams({
|
||||
sortOrder: order,
|
||||
page: 1,
|
||||
});
|
||||
}
|
||||
|
||||
formatDate(dateStr?: string | null): string {
|
||||
if (!dateStr) return '-';
|
||||
const date = new Date(dateStr);
|
||||
if (isNaN(date.getTime())) return dateStr;
|
||||
return new Intl.DateTimeFormat('de-DE').format(date);
|
||||
}
|
||||
|
||||
articleRange(): string {
|
||||
if (this.total === 0) return 'Keine Nachrichten gefunden';
|
||||
const start = this.currentPageIndex * this.paginationService.selection + 1;
|
||||
const end = Math.min(
|
||||
start + this.paginationService.selection - 1,
|
||||
this.total,
|
||||
);
|
||||
return `Zeige ${start} bis ${end} von ${this.total} Nachrichten`;
|
||||
}
|
||||
|
||||
private updateQueryParams(
|
||||
overrides: Record<string, string | number | null>,
|
||||
): void {
|
||||
|
||||
@@ -11,6 +11,7 @@ export interface NewsArticle {
|
||||
maintitle?: string | null;
|
||||
author?: string | null;
|
||||
url?: string | null;
|
||||
relevant?: boolean | null;
|
||||
}
|
||||
|
||||
export interface NewsPage {
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
<div class="news-toolbar">
|
||||
<mat-form-field appearance="outline" class="search-field">
|
||||
<mat-icon matPrefix>search</mat-icon>
|
||||
<input
|
||||
matInput
|
||||
[formControl]="searchControl"
|
||||
placeholder="Nachrichten durchsuchen..." />
|
||||
</mat-form-field>
|
||||
|
||||
@if (!isSearching) {
|
||||
<mat-form-field appearance="outline" class="sort-field">
|
||||
<mat-select
|
||||
[value]="sortOrder"
|
||||
(selectionChange)="onSortChange($event.value)"
|
||||
placeholder="Sortierung">
|
||||
<mat-option value="desc">Neueste zuerst</mat-option>
|
||||
<mat-option value="asc">Älteste zuerst</mat-option>
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
|
||||
@if (showFilters) {
|
||||
<mat-form-field appearance="outline" class="relevance-field">
|
||||
<mat-select
|
||||
[formControl]="relevanceFilter"
|
||||
placeholder="Relevanz"
|
||||
multiple>
|
||||
<mat-option value="relevant">Relevant</mat-option>
|
||||
<mat-option value="not_relevant">Nicht relevant</mat-option>
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
|
||||
<div class="year-field">
|
||||
<div class="year-field__head">
|
||||
<span class="year-field__label">Datum</span>
|
||||
<span class="year-field__range">
|
||||
{{ yearFrom.value }} – {{ yearTo.value }}
|
||||
</span>
|
||||
</div>
|
||||
<mat-slider [min]="minYear" [max]="maxYear" step="1" discrete>
|
||||
<input matSliderStartThumb [formControl]="yearFrom" />
|
||||
<input matSliderEndThumb [formControl]="yearTo" />
|
||||
</mat-slider>
|
||||
</div>
|
||||
|
||||
<button
|
||||
class="reset-filter-btn"
|
||||
mat-stroked-button
|
||||
type="button"
|
||||
(click)="resetFilters()"
|
||||
aria-label="Filter zurücksetzen">
|
||||
<mat-icon>filter_alt_off</mat-icon>
|
||||
<span>Zurücksetzen</span>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="table-wrap">
|
||||
@if (loading) {
|
||||
<div class="loading">
|
||||
<mat-spinner diameter="36"></mat-spinner>
|
||||
</div>
|
||||
}
|
||||
|
||||
<table mat-table [dataSource]="articles" class="mat-elevation-z2">
|
||||
<ng-container matColumnDef="maintitle">
|
||||
<th mat-header-cell *matHeaderCellDef>Titel</th>
|
||||
<td mat-cell *matCellDef="let article">
|
||||
<a class="article-title" [routerLink]="['/news', article.id]">{{
|
||||
article.maintitle || 'Kein Titel'
|
||||
}}</a>
|
||||
@if (article.related) {
|
||||
<span class="related-badge"> Ähnlich zu deiner Suche </span>
|
||||
}
|
||||
</td>
|
||||
</ng-container>
|
||||
|
||||
<ng-container matColumnDef="relevance">
|
||||
<th mat-header-cell *matHeaderCellDef>
|
||||
<span class="relevance-header">
|
||||
Relevanz
|
||||
<mat-icon
|
||||
class="relevance-info"
|
||||
tabindex="0"
|
||||
aria-label="Was bedeutet die Relevanz?"
|
||||
[matTooltip]="relevanceHelp"
|
||||
matTooltipClass="relevance-tooltip">
|
||||
info
|
||||
</mat-icon>
|
||||
</span>
|
||||
</th>
|
||||
<td mat-cell *matCellDef="let article">
|
||||
@if (article.relevant === true) {
|
||||
<span class="relevance-badge is-relevant">
|
||||
<mat-icon>check_circle</mat-icon>
|
||||
Relevant
|
||||
</span>
|
||||
} @else if (article.relevant === false) {
|
||||
<span class="relevance-badge not-relevant">
|
||||
<mat-icon>cancel</mat-icon>
|
||||
Nicht relevant
|
||||
</span>
|
||||
} @else {
|
||||
<span class="relevance-badge undetermined">
|
||||
<mat-icon>help</mat-icon>
|
||||
Nicht bestimmt
|
||||
</span>
|
||||
}
|
||||
</td>
|
||||
</ng-container>
|
||||
|
||||
<ng-container matColumnDef="date">
|
||||
<th mat-header-cell *matHeaderCellDef>Datum</th>
|
||||
<td mat-cell *matCellDef="let article">
|
||||
{{ formatDate(article.date) }}
|
||||
</td>
|
||||
</ng-container>
|
||||
|
||||
@if (extraColumnId && extraColumnTemplate) {
|
||||
<ng-container [matColumnDef]="extraColumnId">
|
||||
<th mat-header-cell *matHeaderCellDef>{{ extraColumnHeader }}</th>
|
||||
<td mat-cell *matCellDef="let article">
|
||||
<ng-container
|
||||
*ngTemplateOutlet="
|
||||
extraColumnTemplate;
|
||||
context: { $implicit: article }
|
||||
"></ng-container>
|
||||
</td>
|
||||
</ng-container>
|
||||
}
|
||||
|
||||
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
|
||||
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
|
||||
</table>
|
||||
|
||||
@if (!loading && articles.length === 0) {
|
||||
<div class="empty-state">
|
||||
@if (isSearching) {
|
||||
Keine Ergebnisse für „{{ searchControl.value.trim() }}" gefunden.
|
||||
} @else {
|
||||
Keine Nachrichten gefunden.
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="table-footer">
|
||||
<span>{{ articleRange() }}</span>
|
||||
<mat-paginator
|
||||
[length]="total"
|
||||
[pageIndex]="currentPage - 1"
|
||||
[pageSize]="paginationService.selection"
|
||||
[pageSizeOptions]="paginationService.options"
|
||||
(page)="onPage($event)">
|
||||
</mat-paginator>
|
||||
</div>
|
||||
@@ -0,0 +1,279 @@
|
||||
.news-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
padding-top: 10px;
|
||||
padding-bottom: 25px;
|
||||
}
|
||||
|
||||
.search-field {
|
||||
max-width: 480px;
|
||||
}
|
||||
|
||||
::ng-deep .news-toolbar .mat-mdc-form-field-subscript-wrapper {
|
||||
display: none;
|
||||
}
|
||||
|
||||
::ng-deep .news-toolbar .mat-mdc-text-field-wrapper {
|
||||
height: 42px;
|
||||
background: #fff;
|
||||
border-radius: var(--sg-radius-sm);
|
||||
}
|
||||
|
||||
::ng-deep .news-toolbar .mat-mdc-form-field-infix {
|
||||
min-height: unset;
|
||||
height: 42px;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
::ng-deep .news-toolbar .mdc-notched-outline__leading,
|
||||
::ng-deep .news-toolbar .mdc-notched-outline__notch,
|
||||
::ng-deep .news-toolbar .mdc-notched-outline__trailing {
|
||||
border-color: #d9e2f0;
|
||||
}
|
||||
|
||||
::ng-deep .news-toolbar input.mat-mdc-input-element {
|
||||
color: var(--sg-text);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
::ng-deep .news-toolbar input.mat-mdc-input-element::placeholder {
|
||||
color: var(--sg-text-muted);
|
||||
opacity: 1;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.sort-field {
|
||||
width: 180px;
|
||||
}
|
||||
|
||||
.relevance-field {
|
||||
width: 180px;
|
||||
}
|
||||
|
||||
.year-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
min-width: 220px;
|
||||
padding: 0 6px;
|
||||
}
|
||||
|
||||
.year-field__head {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.year-field__label {
|
||||
color: var(--sg-text-muted);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.year-field__range {
|
||||
color: var(--sg-text);
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.year-field mat-slider {
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.reset-filter-btn {
|
||||
min-width: 132px;
|
||||
height: 42px;
|
||||
padding: 0 14px;
|
||||
border-color: #d9e2f0;
|
||||
border-radius: var(--sg-radius-sm);
|
||||
color: var(--sg-text);
|
||||
background: #fff;
|
||||
|
||||
mat-icon {
|
||||
margin-right: 6px;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
font-size: 20px;
|
||||
}
|
||||
}
|
||||
|
||||
.table-wrap {
|
||||
position: relative;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
min-width: 600px;
|
||||
table-layout: fixed;
|
||||
border-collapse: separate;
|
||||
border-spacing: 0 10px;
|
||||
background: transparent;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
::ng-deep .mat-column-maintitle {
|
||||
width: 30%;
|
||||
}
|
||||
|
||||
::ng-deep .mat-column-relevance {
|
||||
width: 160px;
|
||||
}
|
||||
|
||||
::ng-deep .mat-column-date {
|
||||
width: 110px;
|
||||
}
|
||||
|
||||
.article-title {
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
line-height: 1.45;
|
||||
color: var(--sg-text);
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
text-decoration: none;
|
||||
|
||||
&:hover {
|
||||
color: var(--sg-text);
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
|
||||
.related-badge {
|
||||
display: flex;
|
||||
width: fit-content;
|
||||
align-items: center;
|
||||
margin-top: 6px;
|
||||
padding: 3px 10px;
|
||||
border-radius: 999px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
line-height: 1;
|
||||
white-space: nowrap;
|
||||
background: #eef3fe;
|
||||
border: 1px solid #c5d6f7;
|
||||
color: #2f5bd0;
|
||||
}
|
||||
|
||||
.loading {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 1;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: rgba(255, 255, 255, 0.65);
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
padding: 28px;
|
||||
text-align: center;
|
||||
color: rgba(0, 0, 0, 0.6);
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.relevance-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 5px 12px;
|
||||
border-radius: 999px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
line-height: 1;
|
||||
white-space: nowrap;
|
||||
|
||||
mat-icon {
|
||||
font-size: 16px;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
}
|
||||
|
||||
&.is-relevant {
|
||||
background: #effaf3;
|
||||
border: 1px solid #bdebcf;
|
||||
color: #24834f;
|
||||
}
|
||||
|
||||
&.not-relevant {
|
||||
background: var(--sg-surface-muted);
|
||||
border: 1px solid #e2e2e2;
|
||||
color: var(--sg-text-muted);
|
||||
}
|
||||
|
||||
&.undetermined {
|
||||
background: #fff7e8;
|
||||
border: 1px solid #ffd796;
|
||||
color: #c67500;
|
||||
}
|
||||
}
|
||||
|
||||
::ng-deep .mat-mdc-header-cell {
|
||||
color: var(--sg-text-muted);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.relevance-header {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.relevance-info {
|
||||
font-size: 15px;
|
||||
width: 15px;
|
||||
height: 15px;
|
||||
color: var(--sg-text-muted);
|
||||
cursor: help;
|
||||
|
||||
&:hover,
|
||||
&:focus {
|
||||
color: var(--sg-text);
|
||||
}
|
||||
}
|
||||
|
||||
::ng-deep .relevance-tooltip.mdc-tooltip .mdc-tooltip__surface {
|
||||
max-width: 260px;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.5;
|
||||
padding: 8px 12px;
|
||||
}
|
||||
|
||||
::ng-deep .mat-mdc-cell {
|
||||
padding-top: 18px;
|
||||
padding-bottom: 18px;
|
||||
vertical-align: top;
|
||||
color: var(--sg-text);
|
||||
border-bottom-color: var(--sg-border);
|
||||
font-size: 13px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
mat-paginator {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.table-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
min-height: 66px;
|
||||
padding: 0 22px 0 28px;
|
||||
color: var(--sg-text-muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.table-footer {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
import {
|
||||
Component,
|
||||
EventEmitter,
|
||||
Input,
|
||||
Output,
|
||||
TemplateRef,
|
||||
inject,
|
||||
} from '@angular/core';
|
||||
import { NgTemplateOutlet } from '@angular/common';
|
||||
import { FormControl, ReactiveFormsModule } from '@angular/forms';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { RouterLink } from '@angular/router';
|
||||
import { merge, debounceTime } from 'rxjs';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { MatPaginatorModule, PageEvent } from '@angular/material/paginator';
|
||||
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
|
||||
import { MatTableModule } from '@angular/material/table';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
import { MatSliderModule } from '@angular/material/slider';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
|
||||
import { PaginationService } from '../../services/pagination.service';
|
||||
|
||||
export interface NewsArticleBase {
|
||||
id: string;
|
||||
date?: string | null;
|
||||
maintitle?: string | null;
|
||||
url?: string | null;
|
||||
relevant?: boolean | null;
|
||||
related?: boolean | null;
|
||||
}
|
||||
|
||||
export type SortOrder = 'desc' | 'asc';
|
||||
|
||||
export const NEWS_MIN_YEAR = 2000;
|
||||
|
||||
export interface NewsFilterState {
|
||||
relevance: string[];
|
||||
yearFrom: number;
|
||||
yearTo: number;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-news-list',
|
||||
imports: [
|
||||
MatIconModule,
|
||||
MatSelectModule,
|
||||
MatFormFieldModule,
|
||||
MatInputModule,
|
||||
MatPaginatorModule,
|
||||
MatProgressSpinnerModule,
|
||||
MatTableModule,
|
||||
MatTooltipModule,
|
||||
MatSliderModule,
|
||||
MatButtonModule,
|
||||
NgTemplateOutlet,
|
||||
ReactiveFormsModule,
|
||||
RouterLink,
|
||||
],
|
||||
templateUrl: './news-list.component.html',
|
||||
styleUrl: './news-list.component.scss',
|
||||
})
|
||||
export class NewsListComponent {
|
||||
readonly paginationService = inject(PaginationService);
|
||||
|
||||
readonly relevanceHelp =
|
||||
'Zeigt, ob ein Artikel inhaltlich über eine konkrete Person berichtet ' +
|
||||
'(Relevant) oder eine allgemeine Mitteilung ohne Personenbezug ist ' +
|
||||
'(Nicht relevant).';
|
||||
|
||||
@Input({ required: true }) articles: NewsArticleBase[] = [];
|
||||
@Input({ required: true }) displayedColumns: string[] = [];
|
||||
@Input() total = 0;
|
||||
@Input() loading = false;
|
||||
@Input() currentPage = 1;
|
||||
@Input() sortOrder: SortOrder = 'desc';
|
||||
@Input({ required: true }) searchControl!: FormControl<string>;
|
||||
@Input() showFilters = false;
|
||||
|
||||
readonly minYear = NEWS_MIN_YEAR;
|
||||
readonly maxYear = new Date().getFullYear();
|
||||
|
||||
readonly relevanceFilter = new FormControl<string[]>([], {
|
||||
nonNullable: true,
|
||||
});
|
||||
readonly yearFrom = new FormControl<number>(this.minYear, {
|
||||
nonNullable: true,
|
||||
});
|
||||
readonly yearTo = new FormControl<number>(this.maxYear, {
|
||||
nonNullable: true,
|
||||
});
|
||||
|
||||
@Input() set initialRelevance(values: string[] | null) {
|
||||
this.relevanceFilter.setValue(values ?? [], { emitEvent: false });
|
||||
}
|
||||
@Input() set initialYearFrom(year: number | null) {
|
||||
this.yearFrom.setValue(year ?? this.minYear, { emitEvent: false });
|
||||
}
|
||||
@Input() set initialYearTo(year: number | null) {
|
||||
this.yearTo.setValue(year ?? this.maxYear, { emitEvent: false });
|
||||
}
|
||||
|
||||
@Input() extraColumnId: string | null = null;
|
||||
@Input() extraColumnHeader = '';
|
||||
@Input() extraColumnTemplate: TemplateRef<{
|
||||
$implicit: NewsArticleBase;
|
||||
}> | null = null;
|
||||
|
||||
@Output() sortChange = new EventEmitter<SortOrder>();
|
||||
@Output() pageChange = new EventEmitter<PageEvent>();
|
||||
@Output() filtersChange = new EventEmitter<NewsFilterState>();
|
||||
|
||||
constructor() {
|
||||
merge(
|
||||
this.relevanceFilter.valueChanges,
|
||||
this.yearFrom.valueChanges,
|
||||
this.yearTo.valueChanges,
|
||||
)
|
||||
.pipe(debounceTime(300), takeUntilDestroyed())
|
||||
.subscribe(() => {
|
||||
this.filtersChange.emit({
|
||||
relevance: this.relevanceFilter.value,
|
||||
yearFrom: this.yearFrom.value,
|
||||
yearTo: this.yearTo.value,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
get isSearching(): boolean {
|
||||
return this.searchControl.value.trim().length > 0;
|
||||
}
|
||||
|
||||
onSortChange(order: SortOrder): void {
|
||||
this.sortChange.emit(order);
|
||||
}
|
||||
|
||||
onPage(event: PageEvent): void {
|
||||
this.pageChange.emit(event);
|
||||
}
|
||||
|
||||
resetFilters(): void {
|
||||
this.relevanceFilter.setValue([]);
|
||||
this.yearFrom.setValue(this.minYear);
|
||||
this.yearTo.setValue(this.maxYear);
|
||||
}
|
||||
|
||||
formatDate(dateStr?: string | null): string {
|
||||
if (!dateStr) {
|
||||
return '-';
|
||||
}
|
||||
|
||||
const parts = dateStr.split('.');
|
||||
|
||||
if (parts.length === 3) {
|
||||
const day = parts[0].trim().padStart(2, '0');
|
||||
const month = parts[1].trim().padStart(2, '0');
|
||||
const year = parts[2].trim();
|
||||
return `${day}.${month}.${year}`;
|
||||
}
|
||||
|
||||
const date = new Date(dateStr);
|
||||
|
||||
if (isNaN(date.getTime())) {
|
||||
return dateStr;
|
||||
}
|
||||
|
||||
return new Intl.DateTimeFormat('de-DE', {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
year: 'numeric',
|
||||
}).format(date);
|
||||
}
|
||||
|
||||
articleRange(): string {
|
||||
const relatedCount = this.articles.filter(
|
||||
(article) => article.related,
|
||||
).length;
|
||||
const matchCount = this.articles.length - relatedCount;
|
||||
|
||||
if (this.total === 0 && relatedCount === 0) {
|
||||
return 'Keine Nachrichten gefunden';
|
||||
}
|
||||
|
||||
const pageSize = this.paginationService.selection;
|
||||
const start = matchCount > 0 ? (this.currentPage - 1) * pageSize + 1 : 0;
|
||||
const end = Math.min(start + matchCount - 1, this.total);
|
||||
|
||||
const base =
|
||||
matchCount > 0
|
||||
? `Zeige ${start} bis ${end} von ${this.total} Nachrichten`
|
||||
: 'Keine direkten Treffer';
|
||||
|
||||
if (relatedCount > 0) {
|
||||
const suffix =
|
||||
relatedCount === 1
|
||||
? '1 ähnlicher Vorschlag'
|
||||
: `${relatedCount} ähnliche Vorschläge`;
|
||||
return `${base} · ${suffix}`;
|
||||
}
|
||||
|
||||
return base;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user