Compare commits

..
Author SHA1 Message Date
genja 0817640449 added patent linking from projects to patents page
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-29 00:45:16 +02:00
khalti 569d73aa9f feat(patents): add server-side pagination and source filter to org_patents endpoint
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-28 14:15:38 +02:00
khalti 0873d25345 feat(patents): add server-side pagination and source filter to org_patents endpoint
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-28 13:58:23 +02:00
taguesokoudjou 6c13415b1e Add org_patents indexing and institution patent match-type UI
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
Introduce a batch script and Elasticsearch index to pre-aggregate institution
patents via assignee and inventor name matching, expose them through a new API
endpoint, and update the institution patents page with match-type filtering.
2026-06-28 12:21:17 +02:00
khalti 56015846b0 feat(patents): Customize search field
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-28 11:33:37 +02:00
taguesokoudjou 7602fef243 Fix patent search client test to mock httpx transport
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-06-27 19:18:18 +02:00
taguesokoudjou 81539d5dbd Merge branch 'dev' into ts-136-patent-to-researchers-v2
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-06-27 19:09:45 +02:00
taguesokoudjou f5991ef660 Add centralized patent detail page with backend lookup by ID
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
Introduce /patent/:patentId and a dedicated detail view modeled after
publications, backed by GET /api/inse-service/patents/{patent_id}.
Route patent overview and detail actions from list, person, and
institution views to the shared page instead of inline detail panels.
2026-06-27 18:53:55 +02:00
khalti 6fc491fd87 feat(patents): add year range filter to global patents page
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-06-27 11:30:09 +02:00
taguesokoudjou 163fdfaa39 refactor(patents): decouple author and institution patent lookup into separate modules
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-26 12:17:50 +02:00
taguesokoudjou e37de88cc8 feat(institutions): add patents view per institution with assignee-based search
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-26 11:27:11 +02:00
125 changed files with 8072 additions and 5126 deletions
+1
View File
@@ -13,6 +13,7 @@ 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" ]
+1
View File
@@ -7,6 +7,7 @@ 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",
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""Index org_patents for an institution."""
from __future__ import annotations
import argparse
import asyncio
import logging
import sys
from pathlib import Path
current_dir = Path(__file__).resolve().parent
sys.path.insert(0, str(current_dir.parent / "src" / "main"))
from dotenv import load_dotenv
load_dotenv(dotenv_path=current_dir.parent / "src" / "main" / "inse" / ".env")
from inse.patents.org.logic import index_org_patents_for_institution
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
logger = logging.getLogger(__name__)
async def main() -> None:
parser = argparse.ArgumentParser(description="Index org_patents for an institution.")
parser.add_argument(
"--institution-id",
required=True,
help="OpenAlex institution ID, e.g. I62318514",
)
args = parser.parse_args()
count = await index_org_patents_for_institution(args.institution_id)
logger.info("Finished indexing %d patents for institution %s", count, args.institution_id)
if __name__ == "__main__":
asyncio.run(main())
@@ -1,9 +1,12 @@
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 inse.exceptions import MissingApiKeyError, ElasticsearchException, NotFoundException
from .search_client import CompanyConnectionsSearchClient
from .search_client import CompanyConnectionsSearchClient, MissingApiKeyError
logger = logging.getLogger(__name__)
@@ -20,10 +23,22 @@ async def get_company_connections_by_author_id(
) -> model.CompanyConnectionsResponse:
search_client = client or CompanyConnectionsSearchClient()
author_hit = await search_client.get_openalex_author(author_id)
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
if author_hit is None:
raise NotFoundException(f"Author {author_id} not found.")
raise HTTPException(status_code=404, detail=f"Author {author_id} not found.")
source = author_hit.get("_source", {})
display_name = _clean(source.get("display_name"))
@@ -44,9 +59,21 @@ async def get_company_connections_by_author_id(
connections=[],
)
hr_response = await search_client.search_handelsregister_by_officer_name(
display_name
)
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
company_count, company_count_relation = _parse_total(hr_response)
connections = _parse_company_connections(
@@ -5,12 +5,8 @@ import httpx
from .. import config
from inse.integrations import elasticsearch
from inse.model import ESCluster
from inse.exceptions import ElasticsearchNotFoundException
from inse.exceptions import MissingApiKeyError
class MissingApiKeyError(Exception):
pass
class CompanyConnectionsSearchClient:
@@ -32,7 +28,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
@@ -43,15 +39,26 @@ 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)
try:
return await elasticsearch.get(
index=self.openalex_index,
doc_id=doc_id,
cluster=ESCluster.NES,
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}"},
)
except ElasticsearchNotFoundException:
return None
if response.status_code == 404:
return None
response.raise_for_status()
return response.json()
async def search_handelsregister_by_officer_name(
self,
@@ -59,16 +66,27 @@ 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,
)
return await elasticsearch.search(
index=self.handelsregister_index,
body=payload,
cluster=ESCluster.NES,
)
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()
@staticmethod
def handelsregister_officer_name_query(
-33
View File
@@ -1,36 +1,3 @@
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,11 +8,10 @@ from typing import Any
import httpx
from .. import config
from inse.integrations import elasticsearch
from inse.model import ESCluster
from inse.exceptions import MissingApiKeyError
class MissingApiKeyError(Exception):
pass
class FundedPublicationsSearchClient:
@@ -178,8 +177,15 @@ class FundedPublicationsSearchClient:
if not self.api_key:
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
return await elasticsearch.search(
index=self.index,
body=payload,
cluster=ESCluster.NES,
)
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()
+32 -14
View File
@@ -6,11 +6,16 @@
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 inse.exceptions import MissingApiKeyError, ElasticsearchException, UpstreamAPIException
from .elastic_search_client import MissingApiKeyError
logger = logging.getLogger(__name__)
@@ -57,7 +62,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 = await _get_author_name(author_id)
author_name = _get_author_name(author_id)
try:
_, all_hits = await _fetch_all_author_work_hits(
@@ -87,9 +92,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 UpstreamAPIException(
message="Funders response could not be parsed.",
status_code=502,
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="Funders response could not be parsed.",
) from exc
@@ -139,13 +144,26 @@ async def _search_funded_publications(
*,
funded_only: bool = False,
) -> dict:
payload = search_client.publications_by_author_query(
author_id,
page,
page_size,
funded_only=funded_only,
)
return await search_client.search(payload)
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
def _parse_publication_search_response(data: dict) -> tuple[int, list[dict]]:
@@ -162,9 +180,9 @@ def _parse_publication_search_response(data: dict) -> tuple[int, list[dict]]:
return total, results
async def _get_author_name(author_id: str) -> str | None:
def _get_author_name(author_id: str) -> str | None:
short_author_id = author_id.replace("https://openalex.org/", "")
search_result = await person_logic.search_persons(author_id=short_author_id)
search_result = person_logic.search_persons(author_id=short_author_id)
if not search_result.results:
return None
+273 -219
View File
@@ -1,6 +1,8 @@
import json
import httpx
import pytest
from unittest.mock import AsyncMock, patch
from inse.exceptions import MissingApiKeyError
from fastapi import HTTPException
from inse.funders import logic
from inse.funders.elastic_search_client import FundedPublicationsSearchClient
@@ -66,177 +68,201 @@ def _funded_publication_hit(
@pytest.mark.anyio
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",
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],
},
},
"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",
),
],
},
}
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",
),
],
},
},
)
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.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"]
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"
]
@pytest.mark.anyio
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"})()]})()
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",
),
],
},
},
)
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
monkeypatch.setattr(
logic.person_logic,
"search_persons",
lambda author_id: type(
"Result",
(),
{"results": [type("Author", (), {"display_name": "Example Author"})()]},
)(),
)
client = FundedPublicationsSearchClient(api_key="test-key")
response = await logic.get_funders_by_author_id("A5023888391", client=client)
client = FundedPublicationsSearchClient(
base_url="https://project.nes.uni-due.de/elastic",
api_key="test-key",
transport=httpx.MockTransport(handler),
)
assert response.funders[0].publication_details["https://openalex.org/W3"].grant_labels == []
response = await logic.get_funders_by_author_id("A5023888391", client=client)
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():
async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded(monkeypatch):
requested_pages: list[int] = []
async def mock_search_func(index, body, cluster=None):
size = body["size"]
offset = body["from"]
def handler(request: httpx.Request) -> httpx.Response:
payload = json.loads(request.content.decode("utf-8"))
size = payload["size"]
offset = payload["from"]
page = offset // size + 1
requested_pages.append(page)
total = size + 1
@@ -258,87 +284,115 @@ async def test_get_funders_by_author_id_paginates_until_all_results_are_loaded()
)
]
return {
"hits": {
"total": {"value": total},
"hits": hits,
return httpx.Response(
200,
json={
"hits": {
"total": {"value": total},
"hits": 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", 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
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 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():
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": []})()
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,
),
],
},
},
)
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
monkeypatch.setattr(
logic.person_logic,
"search_persons",
lambda author_id: type("Result", (), {"results": []})(),
)
client = FundedPublicationsSearchClient(api_key="test-key")
response = await logic.get_funders_by_author_id("A5093075883", client=client)
client = FundedPublicationsSearchClient(
base_url="https://project.nes.uni-due.de/elastic",
api_key="test-key",
transport=httpx.MockTransport(handler),
)
assert response.funder_count == 1
assert response.funders[0].funder_name == "Bundesministerium"
assert response.funders[0].publication_count == 1
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
@pytest.mark.anyio
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": []})()
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": []}},
)
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
monkeypatch.setattr(
logic.person_logic,
"search_persons",
lambda author_id: type("Result", (), {"results": []})(),
)
client = FundedPublicationsSearchClient(api_key="test-key")
response = await logic.get_funders_by_author_id("A5093075883", client=client)
client = FundedPublicationsSearchClient(
base_url="https://project.nes.uni-due.de/elastic",
api_key="test-key",
transport=httpx.MockTransport(handler),
)
assert response.funder_count == 0
assert response.funders == []
response = await logic.get_funders_by_author_id("A5093075883", client=client)
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():
mock_author_result = type("Result", (), {"results": []})()
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="")
with patch("inse.persons.logic.search_persons", new_callable=AsyncMock) as mock_search_persons:
mock_search_persons.return_value = mock_author_result
with pytest.raises(HTTPException) as exc:
await logic.get_funders_by_author_id("A5023888391", client=client)
client = FundedPublicationsSearchClient(api_key="")
with pytest.raises(MissingApiKeyError):
await logic.get_funders_by_author_id("A5023888391", client=client)
assert exc.value.status_code == 503
@@ -20,7 +20,7 @@ class InstitutionsSearchClient:
"""
pass
async def get_institution_by_id(self, raw_oa_institution_id: str) -> Institution:
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 = await elasticsearch.search(index="openalex-institutions", query=query, size=1)
res = 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)
async def get_institutions_by_name(
def get_institutions_by_name(
self,
name: str,
page: int = 0,
@@ -122,7 +122,7 @@ class InstitutionsSearchClient:
query,
)
try:
response = await elasticsearch.search(
response = elasticsearch.search(
index="openalex-institutions",
offset=page * size,
size=size,
@@ -189,7 +189,7 @@ class InstitutionsSearchClient:
query,
)
res = await elasticsearch.search(index="openalex-authors", query=query)
res = 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)
async def search_institutions(
def search_institutions(
self,
query_text: str,
country_code: str | None = None,
@@ -265,7 +265,7 @@ class InstitutionsSearchClient:
}
}
res = await elasticsearch.search(
res = 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]
async def get_institution_aliases_by_oa_institution_id(
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 = await self.get_institution_by_id(raw_oa_institution_id)
institution = 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
async def get_cordis_eu_organisation_ids_by_oa_institution_id(
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(
await self.get_institution_aliases_by_oa_institution_id(
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 = await elasticsearch.search(
response = elasticsearch.search(
index="cordis_eu_*_organizations", body=body, cluster="inse"
)
except Exception as e:
+16 -11
View File
@@ -9,8 +9,10 @@ from copy import deepcopy
from typing import Any, Optional
import httpx
from fastapi import HTTPException
from pydantic import ValidationError
from inse.exceptions import UpstreamAPIException, BadRequestException
from starlette.status import HTTP_400_BAD_REQUEST
from starlette.status import HTTP_502_BAD_GATEWAY
from inse.models.openalex.autocomplete_response import AutocompleteResponse
from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta
@@ -39,7 +41,7 @@ _VALID_INSTITUTION_TYPES = {
async def get_institution_by_id(
raw_institution_id: str, client: InstitutionsSearchClient
) -> Institution:
return await client.get_institution_by_id(raw_institution_id)
return client.get_institution_by_id(raw_institution_id)
async def list_institutions(
@@ -56,7 +58,10 @@ async def list_institutions(
client: OpenAlexInstitutionsClient | None = None,
) -> InstitutionsListResponse:
if sample is not None and (sort or page not in (None, 1)):
raise BadRequestException("sample cannot be combined with sort or page.")
raise HTTPException(
status_code=HTTP_400_BAD_REQUEST,
detail="sample cannot be combined with sort or page.",
)
openalex_client = client or OpenAlexInstitutionsClient()
@@ -81,12 +86,12 @@ async def list_institutions(
except ValueError:
if exc.response.text:
detail = exc.response.text
raise UpstreamAPIException(message=detail, status_code=status_code) from exc
raise HTTPException(status_code=status_code, detail=detail) from exc
except httpx.HTTPError as exc:
logger.exception("OpenAlex institutions request failed.")
raise UpstreamAPIException(
message="OpenAlex institutions request failed.",
status_code=502,
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex institutions request failed.",
) from exc
try:
@@ -97,9 +102,9 @@ async def list_institutions(
)
except ValidationError as exc:
logger.exception("OpenAlex institutions response could not be parsed.")
raise UpstreamAPIException(
message="OpenAlex institutions response could not be parsed.",
status_code=502,
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex institutions response could not be parsed.",
) from exc
@@ -115,7 +120,7 @@ async def autocomplete_institutions(
Returns institution options for autocomplete inputs using the local
Elasticsearch cluster via the provided client.
"""
institutions = await client.search_institutions(
institutions = client.search_institutions(
query_text=query,
country_code=country_code,
institution_type=institution_type,
+1 -1
View File
@@ -72,7 +72,7 @@ async def search_institutions_by_name(
),
] = "asc",
) -> InstitutionPage:
return await client.get_institutions_by_name(
return client.get_institutions_by_name(
name=name,
page=page,
size=size,
@@ -1,6 +1,6 @@
import httpx
import pytest
from inse.exceptions import BadRequestException
from fastapi import HTTPException
from inse.institutions import logic
from inse.institutions.search_client import OpenAlexInstitutionsClient
@@ -96,9 +96,11 @@ 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(BadRequestException) as exc_info:
with pytest.raises(HTTPException) 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,37 +1,13 @@
import json
import logging
from typing import Any, Dict, AsyncIterator, List, Optional, Tuple
from typing import Any, Dict, 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.
@@ -45,23 +21,22 @@ 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 MissingApiKeyError(
raise ValueError(
"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 MissingApiKeyError(
raise ValueError(
"Elasticsearch INSE URL and API key must be set in the configuration for cluster 'inse'"
)
@@ -105,18 +80,8 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
return None
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],
def search(
index: ESIndex | List[ESIndex],
query: Optional[Dict] = None,
source: Optional[List] = None,
size: Optional[int] = None,
@@ -147,11 +112,10 @@ async def search(
clusters = set()
if isinstance(index, list):
for idx in index:
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(idx)
if cluster_for_index is not None:
clusters.add(cluster_for_index)
else:
cluster_for_index = _index_to_cluster(index)
if cluster_for_index is not None:
clusters.add(cluster_for_index)
@@ -192,125 +156,24 @@ async def search(
"At least one of 'query', 'body', 'source', 'size', 'offset', 'sort' must be provided"
)
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)
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
try:
response = await client.post(
response = 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
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,
def get(
index: ESIndex,
doc_id: str,
source: Optional[list] = None,
cluster: ESCluster = ESCluster.NES,
@@ -324,56 +187,9 @@ async def get(
if source is not None:
params["_source_includes"] = ",".join(source)
client = get_client()
try:
response = await client.get(
with httpx.Client() as client:
response = 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
+35 -22
View File
@@ -18,7 +18,6 @@ import json
from . import schema
from . import model
from . import config
from inse.integrations import elasticsearch
from inse.models.openalex.topic import Topic
@@ -104,42 +103,56 @@ def _load_topic_cache() -> dict:
return {}
async def build_topic_cache(save_json: bool = True) -> dict:
def build_topic_cache(page_size: int = 200, 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
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
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()
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)
hits = data.get("hits", {}).get("hits", [])
if not hits:
break
logger.info("Processed %s topics total", len(taxonomy_cache))
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))
if save_json:
data_json = json.dumps(taxonomy_cache, indent=2, ensure_ascii=True)
+9 -36
View File
@@ -14,13 +14,7 @@ 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,
ElasticsearchException,
MissingApiKeyError,
UpstreamAPIException,
BadRequestException,
)
from inse.exceptions import NotFoundException
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
@@ -34,13 +28,16 @@ from inse.persons.service import router as persons_service_router
from inse.funders.service import router as funders_service_router
from inse.news.service import router as news_service_router
from inse.projects.router import router as projects_router
from inse.patents.service import router as patents_service_router
from inse.institutions.router import router as institutions_router
from . import config
from .account.service import router as account_router
from .service import router as service_router
from inse.patents.service import router as patents_service_router, patents_router as patents_all_router
from inse.patents.org.service import router as org_patents_router
from inse.patents.service import (
institution_patents_router,
patents_router as patents_all_router,
router as patents_service_router,
)
logger = logging.getLogger(__name__)
@@ -56,6 +53,8 @@ app = FastAPI(
servers=settings.servers,
)
app.include_router(collaboration_network_router)
app.include_router(institution_patents_router)
app.include_router(org_patents_router)
app.include_router(institutions_router)
app.include_router(topics_service_router)
app.include_router(works_service_router)
@@ -84,37 +83,11 @@ 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/")
+13 -7
View File
@@ -25,11 +25,15 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
# Cache hit + not expired
if entry and time.time() < entry["expires"]:
if client_etag == entry["etag"]:
return Response(status_code=304, headers={"ETag": entry["etag"]})
return Response(
status_code=entry["status_code"],
headers={"ETag": entry["etag"]},
)
# Client has stale ETag - return fresh cached body
return Response(
content=entry["body"],
status_code=entry["status_code"],
media_type="application/json",
headers={"ETag": entry["etag"], "Cache-Control": f"max-age={self.ttl}"}
)
@@ -39,11 +43,13 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
body = b"".join([chunk async for chunk in response.body_iterator])
etag = f'"{hashlib.md5(body).hexdigest()}"'
self.cache[key] = {
"body": body,
"etag": etag,
"expires": time.time() + self.ttl
}
if response.status_code < 400:
self.cache[key] = {
"body": body,
"etag": etag,
"expires": time.time() + self.ttl,
"status_code": response.status_code,
}
return Response(
content=body,
status_code=response.status_code,
+1
View File
@@ -58,6 +58,7 @@ class ESIndex(StrEnum):
EPO_INDEX = "epo_index_1.0"
USPTO_INDEX = "uspto_patents_3.0"
ORG_PATENTS = "org_patents"
PROJECTS_BUND_V1 = "projects_bund_v1"
PROJECTS_DFG_ALL = "projects_dfg_all"
+49 -385
View File
@@ -4,69 +4,33 @@
Business logic for the "aktuell" news index on the INSE cluster.
"""
import json
import logging
import re
from inse.exceptions import ElasticsearchException
from fastapi import HTTPException
from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR
from ..integrations import elasticsearch, llm
from ..integrations import elasticsearch
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
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:
def get_news_page(page: int, page_size: int, sort_order: str = "desc") -> NewsPage:
offset = (page - 1) * page_size
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"],
response = _run_search(
query={"match_all": {}},
source=["date", "maintitle", "author", "url"],
size=page_size,
offset=offset,
sort=[{"date_full": sort_order}],
)
return await _build_page(response, page, page_size)
return _build_page(response, page, page_size)
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:
def search_news(query_text: str, page: int, page_size: int) -> NewsPage:
offset = (page - 1) * page_size
highlight = {
@@ -76,16 +40,8 @@ async def search_news(
"encoder": "html",
}
# 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,
response = _run_search(
query={"match": {"full_content": query_text}},
source=["date", "maintitle", "author", "url"],
size=page_size,
offset=offset,
@@ -93,20 +49,9 @@ async def search_news(
highlight=highlight,
)
news_page = await _build_page(response, page, page_size)
return _build_page(response, page, page_size)
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(
def get_news_by_author(
author_id: str,
page: int = 1,
page_size: int = 10,
@@ -114,11 +59,11 @@ async def get_news_by_author(
query_text: str | None = None,
) -> NewsPage:
author_name = await get_author_name_by_id(author_id)
author_name = get_author_name_by_id(author_id)
if not author_name:
return _empty_page(page, page_size)
news_ids = await _find_news_ids_for_author(author_name)
news_ids = _find_news_ids_for_author(author_name)
if not news_ids:
return _empty_page(page, page_size)
@@ -129,7 +74,7 @@ async def get_news_by_author(
]
offset = (page - 1) * page_size
response = await _run_search(
response = _run_search(
query=es_query,
source=["date", "maintitle", "author", "url"],
size=page_size,
@@ -137,71 +82,13 @@ async def get_news_by_author(
sort=[{"date_full": sort_order}],
)
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
return _build_page(response, page, page_size)
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:
def _find_news_ids_for_author(author_name: str) -> list:
try:
response = await elasticsearch.search(
response = elasticsearch.search(
index="aktuell_postproc",
query={"term": {"authors.keyword": author_name}},
source=["news_id"],
@@ -225,29 +112,24 @@ def _empty_page(page: int = 1, page_size: int = 0) -> NewsPage:
return NewsPage(total=0, page=page, page_size=page_size, results=[])
async def get_news_by_id(news_id: str) -> NewsArticleDetail:
def get_news_by_id(news_id: str) -> NewsArticleDetail:
try:
response = await elasticsearch.get(
response = elasticsearch.get(
index="aktuell",
doc_id=news_id,
source=["date", "maintitle", "author", "url", "full_content"],
cluster="inse",
)
except ElasticsearchException as exc:
except Exception as exc:
logger.exception("Abruf des News-Artikels fehlgeschlagen.")
raise
raise HTTPException(
status_code=HTTP_500_INTERNAL_SERVER_ERROR,
detail="Etwas ist schiefgelaufen.",
) from exc
source = response.get("_source", {})
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"),
)
relevant, authors = _get_postproc_labels(news_id)
return NewsArticleDetail(
id=response.get("_id"),
@@ -257,131 +139,17 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail:
url=source.get("url"),
full_content=source.get("full_content"),
relevant=relevant,
authors=await _build_mentioned_persons(authors),
topics=topics,
keywords=keywords,
authors=_build_mentioned_persons(authors),
)
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:
def _build_mentioned_persons(author_names: list) -> list:
ude_persons = []
other_persons = []
for name in author_names:
match = await find_ude_author_by_name(name)
match = find_ude_author_by_name(name)
if match:
ude_persons.append(
MentionedPerson(name=name, is_ude=True, person_id=match["id"])
@@ -392,35 +160,33 @@ async def _build_mentioned_persons(author_names: list) -> list:
return ude_persons + other_persons
async def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, str | None]:
def _get_postproc_labels(news_id: str) -> tuple[bool | None, list]:
try:
response = await elasticsearch.search(
response = elasticsearch.search(
index="aktuell_postproc",
query={"term": {"news_id.keyword": news_id}},
source=["relevant", "authors", "keywords"],
source=["relevant", "authors"],
size=1,
cluster="inse",
)
except Exception:
logger.exception(f"Postproc-Lookup for {news_id} failed.")
return None, [], [], None
return None, []
hits = response.get("hits", {}).get("hits", [])
if not hits:
return None, [], [], None
return None, []
hit = hits[0]
postproc_source = hit.get("_source", {})
postproc_source = hits[0].get("_source", {})
relevant = bool(postproc_source.get("relevant", 0))
authors = postproc_source.get("authors") or []
keywords = postproc_source.get("keywords") or []
return relevant, authors, keywords, hit.get("_id")
return relevant, authors
async def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict:
def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict:
try:
return await elasticsearch.search(
return elasticsearch.search(
index="aktuell",
query=query,
source=source,
@@ -431,12 +197,15 @@ async def _run_search(query: dict, source: list, size: int, offset: int, sort, h
highlight=highlight,
cluster="inse",
)
except ElasticsearchException as exc:
except Exception as exc:
logger.exception("Elasticsearch-Anfrage an Index 'aktuell' fehlgeschlagen.")
raise
raise HTTPException(
status_code=HTTP_500_INTERNAL_SERVER_ERROR,
detail="Etwas ist schiefgelaufen.",
) from exc
async def _build_page(response: dict, page: int, page_size: int) -> NewsPage:
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", [])
@@ -447,7 +216,7 @@ async def _build_page(response: dict, page: int, page_size: int) -> NewsPage:
if news_id:
news_ids.append(news_id)
relevance_map = await _get_relevance_map(news_ids)
relevance_map = _get_relevance_map(news_ids)
articles = []
for hit in hits:
@@ -463,12 +232,12 @@ async def _build_page(response: dict, page: int, page_size: int) -> NewsPage:
)
async def _get_relevance_map(news_ids: list) -> dict:
def _get_relevance_map(news_ids: list) -> dict:
if not news_ids:
return {}
try:
response = await elasticsearch.search(
response = elasticsearch.search(
index="aktuell_postproc",
query={"terms": {"news_id.keyword": news_ids}},
source=["news_id", "relevant"],
@@ -493,11 +262,7 @@ def _parse_hit(hit: dict) -> NewsArticle:
source = hit.get("_source", {})
fragments = hit.get("highlight", {}).get("full_content")
if fragments:
snippet = fragments[0]
else:
snippet = _make_preview(source)
snippet = fragments[0] if fragments else None
return NewsArticle(
id=hit.get("_id"),
@@ -507,104 +272,3 @@ 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
-3
View File
@@ -14,7 +14,6 @@ class NewsArticle(BaseModel):
url: Optional[str] = None
relevant: Optional[bool] = None
snippet: Optional[str] = None
related: Optional[bool] = None
class MentionedPerson(BaseModel):
@@ -27,8 +26,6 @@ class NewsArticleDetail(NewsArticle):
full_content: Optional[str] = None
relevant: Optional[bool] = None
authors: List[MentionedPerson] = []
topics: List[str] = []
keywords: List[str] = []
class NewsPage(BaseModel):
+8 -49
View File
@@ -16,15 +16,6 @@ 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(
"",
@@ -34,7 +25,7 @@ def _parse_relevance(relevance: str | None) -> list:
summary="Returns a page of news articles, newest first.",
tags=[Tags.NEWS],
)
async def list_news(
def list_news(
page: Annotated[
int, Query(description="Page number (1-based).", ge=1)
] = 1,
@@ -44,24 +35,8 @@ async 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 await logic.get_news_page(
page,
page_size,
sort_order,
year_from=year_from,
year_to=year_to,
relevance_values=_parse_relevance(relevance),
)
return logic.get_news_page(page, page_size, sort_order)
@router.get(
@@ -72,7 +47,7 @@ async def list_news(
summary="Searches news articles by full text (full_content).",
tags=[Tags.NEWS],
)
async def search_news(
def search_news(
query: Annotated[
str, Query(description="Search term, matched against the full text (full_content).", min_length=1)
],
@@ -82,24 +57,8 @@ async 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 await logic.search_news(
query,
page,
page_size,
year_from=year_from,
year_to=year_to,
relevance_values=_parse_relevance(relevance),
)
return logic.search_news(query, page, page_size)
@router.get(
@@ -110,7 +69,7 @@ async def search_news(
summary="Returns news articles in which the given person is mentioned.",
tags=[Tags.NEWS],
)
async def get_news_by_author(
def get_news_by_author(
author_id: Annotated[
str, Query(alias="authorId", description="OpenAlex author id, e.g. A5034365278.")
],
@@ -127,7 +86,7 @@ async def get_news_by_author(
str | None, Query(description="Optional search term, matched against title/author.")
] = None,
):
return await logic.get_news_by_author(author_id, page, page_size, sort_order, query)
return logic.get_news_by_author(author_id, page, page_size, sort_order, query)
@router.get(
@@ -138,9 +97,9 @@ async def get_news_by_author(
summary="Returns a single news article including its full content.",
tags=[Tags.NEWS],
)
async def get_news_by_id(
def get_news_by_id(
news_id: Annotated[
str, Path(description="The unique id of the news article (Elasticsearch _id).")
],
):
return await logic.get_news_by_id(news_id)
return logic.get_news_by_id(news_id)
@@ -0,0 +1 @@
"""Global patent listing."""
+154
View File
@@ -0,0 +1,154 @@
"""Business logic for global patent listing."""
import asyncio
from datetime import datetime
import httpx
from fastapi import HTTPException
from starlette.status import HTTP_404_NOT_FOUND
from starlette.status import HTTP_502_BAD_GATEWAY
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
from inse.patents.common import model
from inse.patents.common.elastic_search_client import MissingApiKeyError
from inse.patents.common.parsing import (
enrich_patents_classifications,
parse_epo_hits,
parse_uspto_hits,
)
from inse.patents.elastic_search_all_patents_client import AllPatentsSearchClient
from inse.patents.ipc_search_client import IpcSearchClient
from inse.patents.search_client import PatentSearchClient
def normalize_patent_date(date_str: str) -> str:
return datetime.strptime(date_str.strip(), "%Y-%m-%d").strftime("%Y%m%d")
async def get_all_patents(
page: int = 0,
size: int = 10,
search: str | None = None,
source: str | None = None,
sort_by: str = "date",
sort_direction: str = "desc",
year_from: int | None = None,
year_to: int | None = None,
client: PatentSearchClient | None = None,
ipc_client: IpcSearchClient | None = None,
) -> model.AllPatentsResponse:
all_patents_client = AllPatentsSearchClient()
ipc_search_client = ipc_client or IpcSearchClient()
try:
if source == "EPO":
epo_data = await all_patents_client.search_epo(
all_patents_client.epo_query(page, size, search, sort_direction, year_from, year_to)
)
patents = parse_epo_hits(epo_data)
total = epo_data.get("hits", {}).get("total", {}).get("value", 0)
elif source == "USPTO":
uspto_data = await all_patents_client.search_uspto(
all_patents_client.uspto_query(page, size, search, sort_direction, year_from, year_to)
)
patents = parse_uspto_hits(uspto_data)
total = uspto_data.get("hits", {}).get("total", {}).get("value", 0)
else:
half = size // 2
epo_data, uspto_data = await asyncio.gather(
all_patents_client.search_epo(
all_patents_client.epo_query(page, half, search, sort_direction, year_from, year_to)
),
all_patents_client.search_uspto(
all_patents_client.uspto_query(page, half, search, sort_direction, year_from, year_to)
),
)
patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)
total = (
epo_data.get("hits", {}).get("total", {}).get("value", 0)
+ uspto_data.get("hits", {}).get("total", {}).get("value", 0)
)
except MissingApiKeyError as exc:
raise HTTPException(
status_code=HTTP_503_SERVICE_UNAVAILABLE,
detail="Patent search is not configured.",
) from exc
except httpx.HTTPError as exc:
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="Patent search request failed.",
) from exc
await enrich_patents_classifications(patents, ipc_search_client)
return model.AllPatentsResponse(
total=total,
page=page,
size=size,
patents=patents,
)
async def _search_by_id(
client: AllPatentsSearchClient,
patent_id: str,
prefix: str | None = None,
filling_date: str | None = None
) -> list[model.PatentEntry]:
if prefix == "US":
data = await client.search_uspto(client.uspto_detail_query(patent_id, filling_date=filling_date))
return parse_uspto_hits(data)
data = await client.search_epo(client.epo_detail_query(patent_id, filling_date=filling_date))
return parse_epo_hits(data)
async def _search_by_title(
client: AllPatentsSearchClient,
title: str,
prefix: str | None = None,
filling_date: str | None = None
) -> list[model.PatentEntry]:
epo_data, uspto_data = await asyncio.gather(
client.search_epo(client.epo_title_query(title, filling_date=filling_date)),
client.search_uspto(client.uspto_title_query(title,filling_date=filling_date)),
)
return parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)
async def get_patent_by_id(
patent_id: str,
title: str | None = None,
prefix: str | None = None,
filling_date: str | None = None,
ipc_client: IpcSearchClient | None = None,
) -> model.PatentEntry:
all_patents_client = AllPatentsSearchClient()
ipc_search_client = ipc_client or IpcSearchClient()
if filling_date:
filling_date = normalize_patent_date(filling_date)
try:
patents = await _search_by_id(all_patents_client, patent_id,prefix=prefix, filling_date=filling_date)
if not patents:
patents = await _search_by_title(all_patents_client, title,prefix=prefix,filling_date=filling_date) if title else []
if not patents:
raise HTTPException(
status_code=HTTP_404_NOT_FOUND,
detail="Patent not found.",
)
except MissingApiKeyError as exc:
raise HTTPException(
status_code=HTTP_503_SERVICE_UNAVAILABLE,
detail="Patent search is not configured.",
) from exc
except httpx.HTTPError as exc:
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="Patent search request failed.",
) from exc
await enrich_patents_classifications(patents[:1], ipc_search_client)
return patents[0]
@@ -0,0 +1,45 @@
"""Business logic for global patent listing."""
from fastapi import APIRouter
from inse.patents.all import logic
from inse.patents.common import model
router = APIRouter(prefix="/api/inse-service", tags=["Patents"])
@router.get(
"/patents",
operation_id="getAllPatents",
response_model=model.AllPatentsResponse,
summary="Get all patents with pagination and search.",
)
async def get_all_patents(
page: int = 0,
size: int = 10,
search: str | None = None,
source: str | None = None,
sort_by: str = "date",
sort_direction: str = "desc",
year_from: int | None = None,
year_to: int | None = None,
):
return await logic.get_all_patents(
page=page,
size=size,
search=search,
source=source,
sort_by=sort_by,
sort_direction=sort_direction,
year_from=year_from,
year_to=year_to,
)
@router.get(
"/patents/{patent_id}",
operation_id="getPatentById",
response_model=model.PatentEntry,
summary="Get a single patent by its identifier.",
)
async def get_patent_by_id(patent_id: str, title: str | None = None, prefix: str | None = None, filling_date: str | None = None):
return await logic.get_patent_by_id(patent_id, title=title, prefix=prefix, filling_date=filling_date)
@@ -0,0 +1 @@
"""Patent lookup by inventor."""
@@ -0,0 +1,122 @@
"""Business logic for patent lookup by inventor."""
import asyncio
import logging
import httpx
from fastapi import HTTPException
from starlette.status import HTTP_502_BAD_GATEWAY
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
from inse.patents.authors.name_matching import name_matches
from inse.patents.common import model
from inse.patents.common.elastic_search_client import MissingApiKeyError
from inse.patents.common.parsing import (
deduplicate_patents,
enrich_patents_classifications,
parse_epo_hits,
parse_uspto_hits,
)
from inse.patents.ipc_search_client import IpcSearchClient
from inse.patents.search_client import PatentSearchClient
from inse.persons import logic as person_logic
from inse.models.openalex.author import Author
logger = logging.getLogger(__name__)
async def get_patents_by_author_id(
author_id: str,
client: PatentSearchClient | None = None,
ipc_client: IpcSearchClient | None = None,
) -> model.PatentsByAuthorResponse:
search_client = client or PatentSearchClient()
ipc_search_client = ipc_client or IpcSearchClient()
author = _get_author(author_id)
if not author:
return model.PatentsByAuthorResponse(
author_id=author_id,
author_name=None,
patent_count=0,
patents=[],
)
author_name = author.display_name
last_name = _extract_last_name(author_name)
first_name = _extract_first_name(author_name)
if not last_name:
return model.PatentsByAuthorResponse(
author_id=author_id,
author_name=author_name,
patent_count=0,
patents=[],
)
try:
epo_data, uspto_data = await _search_both_indices(
search_client, last_name, first_name
)
except MissingApiKeyError as exc:
raise HTTPException(
status_code=HTTP_503_SERVICE_UNAVAILABLE,
detail="Patent search is not configured.",
) from exc
except httpx.HTTPError as exc:
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="Patent search request failed.",
) from exc
all_patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)
if first_name and last_name:
all_patents = _filter_patents_by_name(all_patents, first_name, last_name)
all_patents = deduplicate_patents(all_patents)
await enrich_patents_classifications(all_patents, ipc_search_client)
return model.PatentsByAuthorResponse(
author_id=author_id,
author_name=author_name,
patent_count=len(all_patents),
patents=all_patents,
)
async def _search_both_indices(client, last_name, first_name):
return await asyncio.gather(
client.search_epo(client.epo_query_by_inventor(last_name, first_name)),
client.search_uspto(client.uspto_query_by_inventor(last_name, first_name)),
)
def _filter_patents_by_name(
patents: list[model.PatentEntry],
first_name: str,
last_name: str,
) -> list[model.PatentEntry]:
return [
patent for patent in patents
if any(name_matches(inventor, first_name, last_name) for inventor in patent.inventors)
]
def _get_author(author_id: str) -> Author | None:
short_id = author_id.replace("https://openalex.org/", "")
result = person_logic.search_persons(author_id=short_id)
return result.results[0] if result.results else None
def _extract_last_name(name: str | None) -> str | None:
if not name:
return None
parts = name.strip().split()
return parts[-1] if parts else None
def _extract_first_name(name: str | None) -> str | None:
if not name:
return None
parts = name.strip().split()
return parts[0] if len(parts) > 1 else None
@@ -0,0 +1,128 @@
"""Inventor name normalization and matching."""
import re
from inse.patents.common.text_normalization import (
name_token_variants,
normalize_name_part,
patent_transliteration_expansions,
)
def tokens_equal(
left: str | None,
right: str | None,
*,
allow_initial: bool = True,
) -> bool:
left_variants = name_token_variants(left)
right_variants = name_token_variants(right)
if not left_variants or not right_variants:
return False
if left_variants & right_variants:
return True
if not allow_initial:
return False
return _initial_tokens_match(left, right)
def _initial_letter(token: str | None) -> str | None:
normalized = normalize_name_part(token)
if len(normalized) == 1 and normalized.isalpha():
return normalized
return None
def _initial_tokens_match(left: str | None, right: str | None) -> bool:
left_initial = _initial_letter(left)
right_initial = _initial_letter(right)
left_full = normalize_name_part(left)
right_full = normalize_name_part(right)
if left_initial and right_full and len(right_full) > 1:
return right_full.startswith(left_initial)
if right_initial and left_full and len(left_full) > 1:
return left_full.startswith(right_initial)
if left_initial and right_initial:
return left_initial == right_initial
return False
def _inventor_first_token(inventor_name: str) -> str:
if "," in inventor_name:
_, first_part = [p.strip() for p in inventor_name.split(",", 1)]
return first_part.split()[0] if first_part else ""
parts = inventor_name.split()
return parts[0] if parts else ""
def first_name_match_kind(
inventor_name: str,
first_name: str,
last_name: str,
) -> str:
if not name_matches(inventor_name, first_name, last_name):
return "none"
inventor_first = _inventor_first_token(inventor_name)
if tokens_equal(inventor_first, first_name, allow_initial=False):
return "full"
return "initial"
def search_name_variants(value: str | None) -> list[str]:
if not value or not value.strip():
return []
seen: set[str] = set()
ordered: list[str] = []
def _add(candidate: str) -> None:
key = candidate.casefold()
if candidate.strip() and key not in seen:
seen.add(key)
ordered.append(candidate.strip())
_add(value.strip())
normalized = normalize_name_part(value)
if normalized:
_add(normalized.title())
for variant in name_token_variants(value):
_add(variant.title())
for variant in patent_transliteration_expansions(normalized):
_add(variant.title())
if normalized and len(normalized) > 1:
_add(normalized[0].upper())
return ordered
def name_matches(inventor_name: str, first_name: str, last_name: str) -> bool:
if not inventor_name or not last_name:
return False
name = inventor_name.strip()
if "," in name:
last_part, first_part = [p.strip() for p in name.split(",", 1)]
first_token = first_part.split()[0] if first_part else ""
return (
tokens_equal(last_part, last_name, allow_initial=False)
and bool(first_name)
and tokens_equal(first_token, first_name)
)
parts = name.split()
if len(parts) < 2:
return False
return (
tokens_equal(parts[-1], last_name, allow_initial=False)
and bool(first_name)
and tokens_equal(parts[0], first_name)
)
@@ -0,0 +1,130 @@
"""Elasticsearch query builders for inventor-based patent search."""
from typing import Any
from inse.patents.authors.name_matching import search_name_variants
from inse.patents.common.elastic_search_client import DEFAULT_SEARCH_SIZE
def _match_name_field(field: str, name: str) -> dict[str, Any]:
variants = search_name_variants(name)
if len(variants) <= 1:
return {"match": {field: variants[0] if variants else name}}
return {
"bool": {
"should": [{"match": {field: variant}} for variant in variants],
"minimum_should_match": 1,
}
}
class InventorSearchQueries:
def epo_query_by_inventor(
self,
last_name: str,
first_name: str | None = None,
size: int = DEFAULT_SEARCH_SIZE,
) -> dict[str, Any]:
if first_name:
query = {
"nested": {
"path": "inventors_name_nested",
"query": {
"bool": {
"must": [
_match_name_field("inventors_name_nested.inventor", last_name),
_match_name_field("inventors_name_nested.inventor", first_name),
]
}
},
}
}
else:
query = {
"nested": {
"path": "inventors_name_nested",
"query": _match_name_field("inventors_name_nested.inventor", last_name),
}
}
return {
"size": size,
"track_total_hits": True,
"sort": [
{"_score": {"order": "desc"}},
{"date_publication": {"order": "desc", "missing": "_last"}},
"_doc",
],
"_source": [
"doc_number",
"country",
"kind",
"date_publication",
"date_publication_year",
"application_number",
"application_filing_date",
"title_en",
"title_de",
"abstract",
"inventors_name",
"applicants_name",
"ipc",
"cpc",
],
"query": query,
}
def uspto_query_by_inventor(
self,
last_name: str,
first_name: str | None = None,
size: int = DEFAULT_SEARCH_SIZE,
) -> dict[str, Any]:
if first_name:
query = {
"nested": {
"path": "inventors",
"query": {
"bool": {
"must": [
_match_name_field("inventors.name", last_name),
_match_name_field("inventors.name", first_name),
]
}
},
}
}
else:
query = {
"nested": {
"path": "inventors",
"query": _match_name_field("inventors.name", last_name),
}
}
return {
"size": size,
"track_total_hits": True,
"sort": [
{"_score": {"order": "desc"}},
{"publication_date": {"order": "desc", "missing": "_last"}},
"_doc",
],
"_source": [
"publication_number",
"country",
"publication_date",
"publication_year",
"application_number",
"application_date",
"application_type",
"title",
"abstract",
"inventors_names",
"assignees_orgs",
"ipcr",
"cpc",
"number_of_claims",
"status",
],
"query": query,
}
@@ -0,0 +1,16 @@
from fastapi import APIRouter
from inse.patents.authors import logic
from inse.patents.common import model
router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"])
@router.get(
"/{author_id}/patents",
operation_id="getPatentsByAuthor",
response_model=model.PatentsByAuthorResponse,
summary="Get patents matched to an author by name.",
)
async def get_patents_by_author(author_id: str):
return await logic.get_patents_by_author_id(author_id)
@@ -0,0 +1 @@
"""Shared patent infrastructure."""
@@ -0,0 +1,56 @@
"""Base HTTP client for patent Elasticsearch indices."""
from typing import Any
import httpx
from ... import config
EPO_INDEX = "epo_index_1.0"
USPTO_INDEX = "uspto_patents_3.0"
DEFAULT_SEARCH_SIZE = 100
class MissingApiKeyError(Exception):
pass
class BasePatentSearchClient:
def __init__(
self,
base_url: str | None = None,
api_key: str | None = None,
timeout: float = 30.0,
transport: httpx.AsyncBaseTransport | None = None,
):
self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/")
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
self.timeout = timeout
self.transport = transport
def _headers(self) -> dict[str, str]:
if not self.api_key:
raise MissingApiKeyError("Patent Elasticsearch API key is not configured.")
return {
"Authorization": f"ApiKey {self.api_key}",
"Content-Type": "application/json",
}
async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]:
return await self._search(EPO_INDEX, payload)
async def search_uspto(self, payload: dict[str, Any]) -> dict[str, Any]:
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()
@@ -0,0 +1,55 @@
from pydantic import BaseModel, ConfigDict, Field
class IpcClassification(BaseModel):
symbol: str
section: str | None = None
ipc_class: str | None = Field(default=None, serialization_alias="class")
subclass: str | None = None
main_group: str | None = None
subgroup: str | None = None
model_config = ConfigDict(populate_by_name=True)
class PatentEntry(BaseModel):
patent_id: str
source: str
title: str | None = None
abstract: str | None = None
publication_date: str | None = None
publication_year: str | None = None
application_number: str | None = None
application_date: str | None = None
kind: str | None = None
application_type: str | None = None
number_of_claims: int | None = None
status: str | None = None
inventors: list[str] = Field(default_factory=list)
assignees: list[str] = Field(default_factory=list)
ipc: list[str] = Field(default_factory=list)
ipc_descriptions: list[IpcClassification] = Field(default_factory=list)
cpc: list[str] = Field(default_factory=list)
cpc_descriptions: list[IpcClassification] = Field(default_factory=list)
country: str | None = None
class PatentsByAuthorResponse(BaseModel):
author_id: str
author_name: str | None = None
patent_count: int
patents: list[PatentEntry]
class PatentsByInstitutionResponse(BaseModel):
institution_id: str
institution_name: str | None = None
patent_count: int
patents: list[PatentEntry]
class AllPatentsResponse(BaseModel):
total: int
page: int
size: int
patents: list[PatentEntry]
@@ -0,0 +1,138 @@
"""Shared patent hit parsing, deduplication, and classification enrichment."""
import logging
import httpx
from inse.patents.common import model
from inse.patents.common.elastic_search_client import MissingApiKeyError
from inse.patents.ipc_lookup import extract_ipc_symbol
from inse.patents.ipc_search_client import IpcSearchClient
logger = logging.getLogger(__name__)
def parse_epo_hits(data: dict) -> list[model.PatentEntry]:
patents = []
for hit in data.get("hits", {}).get("hits", []):
src = hit.get("_source", {})
inventors = src.get("inventors_name") or []
applicants = src.get("applicants_name") or []
ipc = src.get("ipc") or []
cpc = src.get("cpc") or []
patents.append(model.PatentEntry(
patent_id=f"EP{src.get('doc_number', hit.get('_id', ''))}",
source="EPO",
title=src.get("title_en") or src.get("title_de"),
abstract=src.get("abstract"),
publication_date=str(src.get("date_publication")) if src.get("date_publication") else None,
publication_year=str(src.get("date_publication_year")) if src.get("date_publication_year") else None,
application_number=src.get("application_number"),
application_date=src.get("application_filing_date"),
kind=src.get("kind"),
inventors=[i for i in (inventors if isinstance(inventors, list) else [inventors]) if i is not None],
assignees=[a for a in (applicants if isinstance(applicants, list) else [applicants]) if a is not None],
ipc=_to_classification_strings(ipc),
cpc=_to_classification_strings(cpc),
country=src.get("country", "EP"),
))
return patents
def parse_uspto_hits(data: dict) -> list[model.PatentEntry]:
patents = []
for hit in data.get("hits", {}).get("hits", []):
src = hit.get("_source", {})
inventors = src.get("inventors_names") or []
assignees = src.get("assignees_orgs") or []
ipc = src.get("ipcr") or []
cpc = src.get("cpc") or []
patents.append(model.PatentEntry(
patent_id=f"US{src.get('publication_number', hit.get('_id', ''))}",
source="USPTO",
title=src.get("title"),
abstract=src.get("abstract"),
publication_date=str(src.get("publication_date")) if src.get("publication_date") else None,
publication_year=str(src.get("publication_year")) if src.get("publication_year") else None,
application_number=src.get("application_number"),
application_date=str(src.get("application_date")) if src.get("application_date") else None,
application_type=src.get("application_type"),
number_of_claims=src.get("number_of_claims"),
status=src.get("status"),
inventors=[i for i in (inventors if isinstance(inventors, list) else [inventors]) if i is not None],
assignees=[a for a in (assignees if isinstance(assignees, list) else [assignees]) if a is not None],
ipc=_to_classification_strings(ipc),
cpc=_to_classification_strings(cpc),
country=src.get("country", "US"),
))
return patents
def deduplicate_patents(patents: list[model.PatentEntry]) -> list[model.PatentEntry]:
seen: set[tuple[str, str, str, str]] = set()
deduplicated: list[model.PatentEntry] = []
for patent in patents:
key = patent_dedup_key(patent)
if key in seen:
continue
seen.add(key)
deduplicated.append(patent)
return deduplicated
def patent_dedup_key(patent: model.PatentEntry) -> tuple[str, str, str, str]:
stage = patent.kind or patent.application_type or ""
return (
patent.source,
patent.patent_id,
patent.publication_date or "",
stage,
)
async def enrich_patents_classifications(
patents: list[model.PatentEntry],
ipc_client: IpcSearchClient,
) -> None:
symbols = list(dict.fromkeys(
extract_ipc_symbol(raw)
for patent in patents
for raw in (*patent.ipc, *patent.cpc)
))
if not symbols:
return
try:
resolved = await ipc_client.resolve_symbols(symbols)
except MissingApiKeyError:
logger.warning("Classification enrichment skipped: Elasticsearch API key not configured.")
return
except httpx.HTTPError as exc:
logger.warning("Classification enrichment failed: %s", exc)
return
except Exception as exc:
logger.exception("Classification enrichment failed unexpectedly: %s", exc)
return
for patent in patents:
patent.ipc_descriptions = _descriptions_for_raw_codes(patent.ipc, resolved)
patent.cpc_descriptions = _descriptions_for_raw_codes(patent.cpc, resolved)
def _to_classification_strings(value) -> list[str]:
if not value:
return []
items = value if isinstance(value, list) else [value]
return [str(item).strip() for item in items if item and str(item).strip()]
def _descriptions_for_raw_codes(
raw_codes: list[str],
resolved: dict[str, model.IpcClassification],
) -> list[model.IpcClassification]:
return [
resolved[extract_ipc_symbol(raw)]
for raw in raw_codes
if extract_ipc_symbol(raw) in resolved
]
@@ -0,0 +1,79 @@
"""Shared text normalization for patent name matching."""
import re
import unicodedata
_CHAR_REPLACEMENTS: dict[str, str] = {
"ß": "ss",
"ẞ": "ss",
"æ": "ae",
"Æ": "ae",
"œ": "oe",
"Œ": "oe",
"ø": "o",
"Ø": "o",
"đ": "d",
"Đ": "d",
"ð": "d",
"Ð": "d",
"þ": "th",
"Þ": "th",
"ł": "l",
"Ł": "l",
"ı": "i",
"ſ": "s",
}
_DIGRAPH_COLLAPSES: tuple[tuple[str, str], ...] = (
("ae", "a"),
("oe", "o"),
("ue", "u"),
)
_PATENT_VOWEL_EXPANSIONS: tuple[tuple[str, str], ...] = (
(r"u([lmnrt])", r"ue\1"),
(r"o([lmnrt])", r"oe\1"),
(r"a([lmnrt])", r"ae\1"),
)
def normalize_name_part(value: str | None) -> str:
if not value:
return ""
text = value.strip()
for src, dst in _CHAR_REPLACEMENTS.items():
text = text.replace(src, dst)
text = unicodedata.normalize("NFKD", text)
text = "".join(c for c in text if not unicodedata.combining(c))
text = text.lower()
text = re.sub(r"[''`´]", "", text)
text = re.sub(r"[^\w\s-]", "", text)
text = re.sub(r"\s+", " ", text).strip()
return text
def name_token_variants(value: str | None) -> set[str]:
base = normalize_name_part(value)
if not base:
return set()
variants = {base}
for src, dst in _DIGRAPH_COLLAPSES:
if src in base:
variants.add(base.replace(src, dst))
if "-" in base:
variants.add(base.replace("-", ""))
variants.add(base.replace("-", " "))
return {v for v in variants if v}
def patent_transliteration_expansions(normalized: str) -> set[str]:
expanded = {normalized}
for pattern, repl in _PATENT_VOWEL_EXPANSIONS:
if re.search(pattern, normalized):
expanded.add(re.sub(pattern, repl, normalized))
return expanded
@@ -8,10 +8,7 @@ from typing import Any
import httpx
from .. import config
from inse.exceptions import MissingApiKeyError
from inse.integrations import elasticsearch
from inse.model import ESCluster
from .elastic_search_client import MissingApiKeyError
EPO_INDEX = "epo_index_1.0"
USPTO_INDEX = "uspto_patents_3.0"
@@ -44,24 +41,45 @@ class AllPatentsSearchClient:
size: int = 10,
search: str | None = None,
sort_direction: str = "desc",
year_from: int | None = None,
year_to: int | None = None,
) -> dict[str, Any]:
sort = [{"date_publication": {"order": sort_direction, "missing": "_last"}}, "_doc"]
if search and search.strip():
term = search.strip()
doc_number = term.upper().removeprefix("EP")
query: dict[str, Any] = {
search_query: dict[str, Any] = {
"bool": {
"should": [
{"match_phrase": {"title_en": {"query": term}}},
{"match_phrase": {"title_de": {"query": term}}},
{"match": {"title_en": {"query": term, "operator": "and", "fuzziness": "AUTO"}}},
{"match": {"title_de": {"query": term, "operator": "and", "fuzziness": "AUTO"}}},
{"term": {"doc_number": doc_number}},
],
"minimum_should_match": 1,
}
}
else:
query = {"match_all": {}}
search_query = {"match_all": {}}
filters = []
if year_from or year_to:
date_range: dict[str, Any] = {}
if year_from:
date_range["gte"] = year_from * 10000
if year_to:
date_range["lte"] = (year_to * 10000) + 9999
filters.append({"range": {"date_publication": date_range}})
if filters:
query: dict[str, Any] = {
"bool": {
"must": search_query,
"filter": filters,
}
}
else:
query = search_query
return {
"from": page * size,
@@ -76,30 +94,54 @@ class AllPatentsSearchClient:
],
"query": query,
}
def remove_year(self, patent_id: str) -> str:
return patent_id[4:].strip()
def uspto_query(
self,
page: int = 0,
size: int = 10,
search: str | None = None,
sort_direction: str = "desc",
year_from: int | None = None,
year_to: int | None = None,
) -> dict[str, Any]:
sort = [{"publication_date": {"order": sort_direction, "missing": "_last"}}, "_doc"]
if search and search.strip():
term = search.strip()
pub_number = term.upper().removeprefix("US")
query: dict[str, Any] = {
search_query: dict[str, Any] = {
"bool": {
"should": [
{"match_phrase": {"title": {"query": term}}},
{"match": {"title": {"query": term, "operator": "and", "fuzziness": "AUTO"}}},
{"term": {"publication_number": pub_number}},
],
"minimum_should_match": 1,
}
}
else:
query = {"match_all": {}}
search_query = {"match_all": {}}
filters = []
if year_from or year_to:
date_range: dict[str, Any] = {}
if year_from:
date_range["gte"] = year_from * 10000
if year_to:
date_range["lte"] = (year_to * 10000) + 9999
filters.append({"range": {"publication_date": date_range}})
if filters:
query: dict[str, Any] = {
"bool": {
"must": search_query,
"filter": filters,
}
}
else:
query = search_query
return {
"from": page * size,
@@ -115,6 +157,103 @@ class AllPatentsSearchClient:
"query": query,
}
def epo_detail_query(self, doc_number: str,filling_date: str | None = None) -> dict[str, Any]:
query: dict[str, Any] = {
"bool": {
"should": [
{"term": {"doc_number": doc_number}},
{"term": {"doc_number": self.remove_year(doc_number)}},
{"term": {"application_number": self.remove_year(doc_number)}},
{"term": {"application_number": doc_number}},
],
"minimum_should_match": 1,
}
}
if filling_date:
query["bool"]["must"] = [{"term": {"application_filing_date": filling_date}}]
return {
"size": 1,
"_source": [
"doc_number", "country", "kind", "date_publication",
"date_publication_year", "application_number",
"application_filing_date", "title_en", "title_de",
"abstract", "inventors_name", "applicants_name", "ipc", "cpc",
],
"query": query,
}
def uspto_detail_query(self, number: str,filling_date: str | None = None) -> dict[str, Any]:
query: dict[str, Any] = {
"bool": {
"should": [
{"term": {"publication_number": number}},
{"term": {"publication_number": self.remove_year(number)}},
{"term": {"application_number": number}},
{"term": {"application_number": self.remove_year(number)}},
],
"minimum_should_match": 1,
}
}
if filling_date:
query["bool"]["must"] = [{"term": {"application_date": filling_date}}]
return {
"size": 1,
"_source": [
"publication_number", "country", "publication_date",
"publication_year", "application_number", "application_date",
"application_type", "title", "abstract", "inventors_names",
"assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
],
"query": query,
}
def epo_title_query(self, title: str,filling_date: str | None = None) -> dict[str, Any]:
query: dict[str, Any] = {
"bool": {
"should": [
{"match_phrase": {"title_en": title}},
{"match_phrase": {"title_de": title}},
],
"minimum_should_match": 1,
}
}
if filling_date:
query["bool"]["must"] = [{"term": {"application_filing_date": filling_date}}]
return {
"size": 1,
"_source": [
"doc_number", "country", "kind", "date_publication",
"date_publication_year", "application_number",
"application_filing_date", "title_en", "title_de",
"abstract", "inventors_name", "applicants_name", "ipc", "cpc",
],
"query": query,
}
def uspto_title_query(self, title: str,filling_date: str | None = None) -> dict[str, Any]:
query: dict[str, Any] = {
"bool": {
"should": [{"match_phrase": {"title": title}}],
"minimum_should_match": 1,
}
}
if filling_date:
query["bool"]["must"] = [{"term": {"application_date": filling_date}}]
return {
"size": 1,
"_source": [
"publication_number", "country", "publication_date",
"publication_year", "application_number", "application_date",
"application_type", "title", "abstract", "inventors_names",
"assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
],
"query": query,
}
async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]:
return await self._search(EPO_INDEX, payload)
@@ -122,4 +261,15 @@ class AllPatentsSearchClient:
return await self._search(USPTO_INDEX, payload)
async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]:
return await elasticsearch.search(index=index, body=payload, cluster=ESCluster.INSE)
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()
@@ -1,281 +1,2 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
HTTP client for patent searches in EPO and USPTO Elasticsearch indices.
"""
from typing import Any
from inse.integrations import elasticsearch
from inse.model import ESCluster, ESIndex
import httpx
import asyncio
from .. import config
from .name_matching import search_name_variants
DEFAULT_SEARCH_SIZE = 100
def _match_name_field(field: str, name: str) -> dict[str, Any]:
"""Match a name field, including transliterated variants (Müller/Mueller)."""
variants = search_name_variants(name)
if len(variants) <= 1:
return {"match": {field: variants[0] if variants else name}}
return {
"bool": {
"should": [{"match": {field: variant}} for variant in variants],
"minimum_should_match": 1,
}
}
from inse.exceptions import MissingApiKeyError
class PatentSearchClient:
def __init__(
self,
base_url: str | None = None,
api_key: str | None = None,
timeout: float = 30.0,
transport: httpx.AsyncBaseTransport | None = None,
):
self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/")
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
self.timeout = timeout
self.transport = transport
def _headers(self) -> dict[str, str]:
if not self.api_key:
raise MissingApiKeyError("Patent Elasticsearch API key is not configured.")
return {
"Authorization": f"ApiKey {self.api_key}",
"Content-Type": "application/json",
}
def epo_query_by_inventor(
self,
last_name: str,
first_name: str | None = None,
size: int = DEFAULT_SEARCH_SIZE,
) -> dict[str, Any]:
"""Search EPO index: first AND last name in the SAME inventor entry."""
if first_name:
query = {
"nested": {
"path": "inventors_name_nested",
"query": {
"bool": {
"must": [
_match_name_field("inventors_name_nested.inventor", last_name),
_match_name_field("inventors_name_nested.inventor", first_name),
]
}
},
}
}
else:
query = {
"nested": {
"path": "inventors_name_nested",
"query": _match_name_field("inventors_name_nested.inventor", last_name),
}
}
return {
"size": size,
"track_total_hits": True,
"sort": [
{"_score": {"order": "desc"}},
{"date_publication": {"order": "desc", "missing": "_last"}},
"_doc",
],
"_source": [
"doc_number",
"country",
"kind",
"date_publication",
"date_publication_year",
"application_number",
"application_filing_date",
"title_en",
"title_de",
"abstract",
"inventors_name",
"applicants_name",
"ipc",
"cpc",
],
"query": query,
}
def uspto_query_by_inventor(
self,
last_name: str,
first_name: str | None = None,
size: int = DEFAULT_SEARCH_SIZE,
) -> dict[str, Any]:
"""Search USPTO index: first AND last name in the SAME inventor entry."""
if first_name:
query = {
"nested": {
"path": "inventors",
"query": {
"bool": {
"must": [
_match_name_field("inventors.name", last_name),
_match_name_field("inventors.name", first_name),
]
}
},
}
}
else:
query = {
"nested": {
"path": "inventors",
"query": _match_name_field("inventors.name", last_name),
}
}
return {
"size": size,
"track_total_hits": True,
"sort": [
{"_score": {"order": "desc"}},
{"publication_date": {"order": "desc", "missing": "_last"}},
"_doc",
],
"_source": [
"publication_number",
"country",
"publication_date",
"publication_year",
"application_number",
"application_date",
"application_type",
"title",
"abstract",
"inventors_names",
"assignees_orgs",
"ipcr",
"cpc",
"number_of_claims",
"status",
],
"query": query,
}
async def search_epo(self, payload: dict[str, Any]) -> dict[str, Any]:
return await self._search(ESIndex.EPO_INDEX, payload)
async def search_uspto(self, payload: dict[str, Any]) -> dict[str, Any]:
return await self._search(ESIndex.USPTO_INDEX, payload)
async def _search(self, index: str, payload: dict[str, Any]) -> dict[str, Any]:
response = await elasticsearch.search(index=index, body=payload, cluster=ESCluster.INSE)
return response
async def get_by_id_or_title(
self,
patent_id: str,
prefix: str,
title: str,
size: int = 1,
) -> dict[str, Any]:
"""Search EPO and USPTO by ID; fall back to match_phrase on title if no hits.
Args:
patent_id: The raw document/publication number (e.g. "1234567", "US1234567A").
prefix: "EP" routes the title fallback to EPO; "US" routes it to USPTO.
Both indices are always queried for the ID lookup.
title: Used only when the ID lookup returns zero hits.
size: Maximum number of results to return.
"""
epo_id_payload = self._epo_query_by_id(patent_id, size)
uspto_id_payload = self._uspto_query_by_id(patent_id, size)
epo_result, uspto_result = await asyncio.gather(
self.search_epo(epo_id_payload),
self.search_uspto(uspto_id_payload),
)
epo_hits = epo_result.get("hits", {}).get("total", {}).get("value", 0)
uspto_hits = uspto_result.get("hits", {}).get("total", {}).get("value", 0)
if epo_hits > 0 or uspto_hits > 0:
if prefix.upper() == "EP" and epo_hits > 0:
return epo_result
if prefix.upper() == "US" and uspto_hits > 0:
return uspto_result
return epo_result if epo_hits > 0 else uspto_result
if prefix.upper() == "US":
payload = self._uspto_query_by_title(title, size)
return await self.search_uspto(payload)
payload = self._epo_query_by_title(title, size)
return await self.search_epo(payload)
#query builders
def _epo_query_by_id(self, patent_id: str, size: int) -> dict[str, Any]:
"""Term query against doc_number; strips a leading 'EP' prefix if present."""
raw_id = patent_id.upper().removeprefix("EP")
return {
"size": size,
"_source": [
"doc_number", "country", "kind", "date_publication",
"date_publication_year", "application_number",
"application_filing_date", "title_en", "title_de", "abstract",
"inventors_name", "applicants_name", "ipc", "cpc",
],
"query": {"term": {"doc_number": raw_id}},
}
def _uspto_query_by_id(self, patent_id: str, size: int) -> dict[str, Any]:
"""Term query against publication_number; tries the ID as-is."""
return {
"size": size,
"track_total_hits": True,
"sort": [{"publication_date": {"order": "desc", "missing": "_last"}}, "_doc"],
"_source": [
"publication_number", "country", "publication_date",
"publication_year", "application_number", "application_date",
"application_type", "title", "abstract", "inventors_names",
"assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
],
"query": {"term": {"publication_number": patent_id}},
}
def _epo_query_by_title(self, title: str, size: int) -> dict[str, Any]:
"""match_phrase fallback on title_en (and title_de as a should clause)."""
return {
"size": size,
"_source": [
"doc_number", "country", "kind", "date_publication",
"date_publication_year", "application_number",
"application_filing_date", "title_en", "title_de", "abstract",
"inventors_name", "applicants_name", "ipc", "cpc",
],
"query": {
"bool": {
"should": [
{"match_phrase": {"title_en": title}},
{"match_phrase": {"title_de": title}},
{"match_phrase": {"title_fr": title}},
],
"minimum_should_match": 1,
}
},
}
def _uspto_query_by_title(self, title: str, size: int) -> dict[str, Any]:
"""match_phrase fallback on title."""
return {
"size": size,
"_source": [
"publication_number", "country", "publication_date",
"publication_year", "application_number", "application_date",
"application_type", "title", "abstract", "inventors_names",
"assignees_orgs", "ipcr", "cpc", "number_of_claims", "status",
],
"query": {"match_phrase": {"title": title}},
}
"""Backward-compatible re-exports."""
from inse.patents.search_client import * # noqa: F403
@@ -0,0 +1 @@
"""Patent lookup by institution assignee."""
@@ -0,0 +1,144 @@
"""Business logic for patent lookup by institution assignee."""
import asyncio
import logging
import httpx
from fastapi import HTTPException
from starlette.status import HTTP_502_BAD_GATEWAY
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
from inse.institutions.institutions_search_client import InstitutionsSearchClient
from inse.models.openalex.institution import Institution
from inse.patents.common import model
from inse.patents.common.elastic_search_client import MissingApiKeyError
from inse.patents.common.parsing import (
deduplicate_patents,
enrich_patents_classifications,
parse_epo_hits,
parse_uspto_hits,
)
from inse.patents.institutions.name_matching import (
MIN_INSTITUTION_ACRONYM_LEN,
assignee_matches_institution_name,
institution_search_variants,
)
from inse.patents.ipc_search_client import IpcSearchClient
from inse.patents.search_client import PatentSearchClient
logger = logging.getLogger(__name__)
async def get_patents_by_institution_id(
institution_id: str,
client: PatentSearchClient | None = None,
ipc_client: IpcSearchClient | None = None,
institutions_client: InstitutionsSearchClient | None = None,
) -> model.PatentsByInstitutionResponse:
search_client = client or PatentSearchClient()
ipc_search_client = ipc_client or IpcSearchClient()
institution_client = institutions_client or InstitutionsSearchClient()
short_id = institution_id.replace("https://openalex.org/", "")
institution = institution_client.get_institution_by_id(short_id)
search_names = _institution_search_names(institution)
if not search_names:
return model.PatentsByInstitutionResponse(
institution_id=short_id,
institution_name=institution.display_name,
patent_count=0,
patents=[],
)
try:
epo_data, uspto_data = await asyncio.gather(
search_client.search_epo(
search_client.epo_query_by_applicant(search_names)
),
search_client.search_uspto(
search_client.uspto_query_by_assignee(search_names)
),
)
except MissingApiKeyError as exc:
raise HTTPException(
status_code=HTTP_503_SERVICE_UNAVAILABLE,
detail="Patent search is not configured.",
) from exc
except httpx.HTTPError as exc:
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="Patent search request failed.",
) from exc
all_patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)
all_patents = filter_patents_by_institution(all_patents, institution)
all_patents = deduplicate_patents(all_patents)
await enrich_patents_classifications(all_patents, ipc_search_client)
return model.PatentsByInstitutionResponse(
institution_id=short_id,
institution_name=institution.display_name,
patent_count=len(all_patents),
patents=all_patents,
)
def _institution_search_names(institution: Institution) -> list[str]:
names: list[str] = []
seen: set[str] = set()
def _add(name: str | None) -> None:
if not name or not name.strip():
return
for variant in institution_search_variants(name.strip()):
key = variant.casefold()
if key not in seen:
seen.add(key)
names.append(variant)
_add(institution.display_name)
for alternative in institution.display_name_alternatives or []:
_add(alternative)
for acronym in institution.display_name_acronyms or []:
if acronym and len(acronym.strip()) >= MIN_INSTITUTION_ACRONYM_LEN:
_add(acronym)
return names
def _institution_canonical_names(institution: Institution) -> list[str]:
names: list[str] = []
seen: set[str] = set()
def _add(name: str | None) -> None:
if not name or not name.strip():
return
key = name.strip().casefold()
if key not in seen:
seen.add(key)
names.append(name.strip())
_add(institution.display_name)
for alternative in institution.display_name_alternatives or []:
_add(alternative)
for acronym in institution.display_name_acronyms or []:
if acronym and len(acronym.strip()) >= MIN_INSTITUTION_ACRONYM_LEN:
_add(acronym)
return names
def filter_patents_by_institution(
patents: list[model.PatentEntry],
institution: Institution,
) -> list[model.PatentEntry]:
canonical_names = _institution_canonical_names(institution)
return [
patent for patent in patents
if any(
assignee_matches_institution_name(assignee, name)
for assignee in patent.assignees
for name in canonical_names
)
]
@@ -0,0 +1,91 @@
"""Institution assignee name normalization and matching."""
from inse.patents.common.text_normalization import (
name_token_variants,
normalize_name_part,
patent_transliteration_expansions,
)
_INSTITUTION_GENERIC_TOKENS = frozenset({
"university", "universitat", "universitaet", "universiteit", "college",
"institute", "institut", "institution", "national", "sciences", "science",
"school", "center", "centre", "laboratory", "department", "academy",
"the", "of", "for", "and", "de", "la", "des", "der", "die", "das", "und",
"fur", "von",
})
MIN_INSTITUTION_SUBSTRING_LEN = 6
MIN_INSTITUTION_VARIANT_LEN = 4
MIN_INSTITUTION_ACRONYM_LEN = 3
def institution_search_variants(value: str | None) -> list[str]:
if not value or not value.strip():
return []
stripped = value.strip()
min_len = (
MIN_INSTITUTION_ACRONYM_LEN
if stripped.isupper() and " " not in stripped
else MIN_INSTITUTION_VARIANT_LEN
)
seen: set[str] = set()
ordered: list[str] = []
def _add(candidate: str) -> None:
candidate = candidate.strip()
if len(candidate) < min_len:
return
key = candidate.casefold()
if key not in seen:
seen.add(key)
ordered.append(candidate)
_add(stripped)
normalized = normalize_name_part(value)
if normalized:
_add(normalized.title())
for variant in name_token_variants(value):
_add(variant.title())
for variant in patent_transliteration_expansions(normalized):
_add(variant.title())
return ordered
def _significant_institution_tokens(text: str) -> set[str]:
return {
token
for token in normalize_name_part(text).split()
if len(token) >= MIN_INSTITUTION_VARIANT_LEN
and token not in _INSTITUTION_GENERIC_TOKENS
}
def assignee_matches_institution_name(assignee: str, institution_name: str) -> bool:
norm_assignee = normalize_name_part(assignee)
norm_name = normalize_name_part(institution_name)
if not norm_assignee or not norm_name:
return False
original = institution_name.strip()
assignee_tokens = set(norm_assignee.split())
if len(original) <= 6 and " " not in original:
return norm_name in assignee_tokens
if len(norm_name) >= MIN_INSTITUTION_SUBSTRING_LEN:
if norm_name in norm_assignee or norm_assignee in norm_name:
return True
significant = _significant_institution_tokens(institution_name)
if not significant:
return False
matched = significant & assignee_tokens
if len(significant) >= 2:
return len(matched) >= 2
return bool(matched)
@@ -0,0 +1,94 @@
"""Elasticsearch query builders for institution assignee patent search."""
from typing import Any
from inse.patents.common.elastic_search_client import DEFAULT_SEARCH_SIZE
from inse.patents.institutions.name_matching import institution_search_variants
class AssigneeSearchQueries:
def _match_organization_names(self, field: str, names: list[str]) -> dict[str, Any]:
clauses: list[dict[str, Any]] = []
seen: set[str] = set()
for name in names:
for variant in institution_search_variants(name):
key = variant.casefold()
if not variant or key in seen:
continue
seen.add(key)
clauses.append({"match_phrase": {field: {"query": variant}}})
if not clauses:
return {"match_none": {}}
return {
"bool": {
"should": clauses,
"minimum_should_match": 1,
}
}
def epo_query_by_applicant(
self,
institution_names: list[str],
size: int = DEFAULT_SEARCH_SIZE,
) -> dict[str, Any]:
return {
"size": size,
"track_total_hits": True,
"sort": [
{"_score": {"order": "desc"}},
{"date_publication": {"order": "desc", "missing": "_last"}},
"_doc",
],
"_source": [
"doc_number",
"country",
"kind",
"date_publication",
"date_publication_year",
"application_number",
"application_filing_date",
"title_en",
"title_de",
"abstract",
"inventors_name",
"applicants_name",
"ipc",
"cpc",
],
"query": self._match_organization_names("applicants_name", institution_names),
}
def uspto_query_by_assignee(
self,
institution_names: list[str],
size: int = DEFAULT_SEARCH_SIZE,
) -> dict[str, Any]:
return {
"size": size,
"track_total_hits": True,
"sort": [
{"_score": {"order": "desc"}},
{"publication_date": {"order": "desc", "missing": "_last"}},
"_doc",
],
"_source": [
"publication_number",
"country",
"publication_date",
"publication_year",
"application_number",
"application_date",
"application_type",
"title",
"abstract",
"inventors_names",
"assignees_orgs",
"ipcr",
"cpc",
"number_of_claims",
"status",
],
"query": self._match_organization_names("assignees_orgs", institution_names),
}
@@ -0,0 +1,33 @@
from functools import lru_cache
from typing import Annotated
from fastapi import APIRouter, Depends
from inse.institutions.institutions_search_client import InstitutionsSearchClient
from inse.patents.common import model
from inse.patents.institutions import logic
router = APIRouter(prefix="/api/inse-service/institutions", tags=["Patents"])
@lru_cache
def get_institutions_search_client() -> InstitutionsSearchClient:
return InstitutionsSearchClient()
@router.get(
"/{id}/patents",
operation_id="getPatentsByInstitution",
response_model=model.PatentsByInstitutionResponse,
summary="Get patents matched to an institution by assignee name.",
)
async def get_patents_by_institution(
id: str,
client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
) -> model.PatentsByInstitutionResponse:
return await logic.get_patents_by_institution_id(
institution_id=id,
institutions_client=client,
)
@@ -11,14 +11,11 @@ import httpx
from .. import config
from . import model
from inse.exceptions import MissingApiKeyError
from .elastic_search_client 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], ...] = (
@@ -139,4 +136,15 @@ class IpcSearchClient:
return found
async def _search(self, payload: dict[str, Any]) -> dict[str, Any]:
return await elasticsearch.search(index=IPC_INDEX, body=payload, cluster=ESCluster.INSE)
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()
+16 -312
View File
@@ -1,313 +1,17 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Business logic for patent matching by author name.
"""
import logging
import asyncio
"""Backward-compatible re-exports."""
from inse.patents.all.logic import get_all_patents, get_patent_by_id
from inse.patents.authors.logic import get_patents_by_author_id
from inse.patents.common.parsing import deduplicate_patents as _deduplicate_patents
from inse.patents.institutions.logic import (
filter_patents_by_institution as _filter_patents_by_institution,
get_patents_by_institution_id,
)
import httpx
from ..persons import logic as person_logic
from ..models.openalex.author import Author
from . import model
from inse.exceptions import MissingApiKeyError, ElasticsearchException
from .elastic_search_client import PatentSearchClient
from .elastic_search_all_patents_client import AllPatentsSearchClient
from .ipc_search_client import IpcSearchClient
from .ipc_lookup import extract_ipc_symbol
from .name_matching import name_matches
logger = logging.getLogger(__name__)
async def get_patent(
patent_id: str,
title: str,
prefix: str,
client: PatentSearchClient | None = None,
) -> model.PatentEntry:
search_client = client or PatentSearchClient()
data = await search_client.get_by_id_or_title(
patent_id=patent_id,
prefix=prefix,
title=title,
)
parse = _parse_uspto_hits if prefix.upper() == "US" else _parse_epo_hits
elements = parse(data)
if not elements:
return None
return elements[0]
async def get_patents_by_author_id(
author_id: str,
client: PatentSearchClient | None = None,
ipc_client: IpcSearchClient | None = None,
) -> model.PatentsByAuthorResponse:
search_client = client or PatentSearchClient()
ipc_search_client = ipc_client or IpcSearchClient()
author = await _get_author(author_id)
if not author:
return model.PatentsByAuthorResponse(
author_id=author_id,
author_name=None,
patent_count=0,
patents=[],
)
author_name = author.display_name
last_name = _extract_last_name(author_name)
first_name = _extract_first_name(author_name)
if not last_name:
return model.PatentsByAuthorResponse(
author_id=author_id,
author_name=author_name,
patent_count=0,
patents=[],
)
epo_data, uspto_data = await _search_both_indices(
search_client, last_name, first_name
)
all_patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data)
if first_name and last_name:
all_patents = _filter_patents_by_name(all_patents, first_name, last_name)
all_patents = _deduplicate_patents(all_patents)
await _enrich_patents_classifications(all_patents, ipc_search_client)
return model.PatentsByAuthorResponse(
author_id=author_id,
author_name=author_name,
patent_count=len(all_patents),
patents=all_patents,
)
async def _search_both_indices(client, last_name, first_name):
epo_result, uspto_result = await asyncio.gather(
client.search_epo(client.epo_query_by_inventor(last_name, first_name)),
client.search_uspto(client.uspto_query_by_inventor(last_name, first_name)),
)
return epo_result, uspto_result
def _parse_epo_hits(data: dict) -> list[model.PatentEntry]:
patents = []
for hit in data.get("hits", {}).get("hits", []):
src = hit.get("_source", {})
inventors = src.get("inventors_name") or []
applicants = src.get("applicants_name") or []
ipc = src.get("ipc") or []
cpc = src.get("cpc") or []
patents.append(model.PatentEntry(
patent_id=f"EP{src.get('doc_number', hit.get('_id', ''))}",
source="EPO",
title=src.get("title_en") or src.get("title_de"),
abstract=src.get("abstract"),
publication_date=str(src.get("date_publication")) if src.get("date_publication") else None,
publication_year=str(src.get("date_publication_year")) if src.get("date_publication_year") else None,
application_number=src.get("application_number"),
application_date=src.get("application_filing_date"),
kind=src.get("kind"),
inventors=[i for i in (inventors if isinstance(inventors, list) else [inventors]) if i is not None],
assignees=[a for a in (applicants if isinstance(applicants, list) else [applicants]) if a is not None],
ipc=_to_classification_strings(ipc),
cpc=_to_classification_strings(cpc),
country=src.get("country", "EP"),
))
return patents
def _parse_uspto_hits(data: dict) -> list[model.PatentEntry]:
patents = []
for hit in data.get("hits", {}).get("hits", []):
src = hit.get("_source", {})
inventors = src.get("inventors_names") or []
assignees = src.get("assignees_orgs") or []
ipc = src.get("ipcr") or []
cpc = src.get("cpc") or []
patents.append(model.PatentEntry(
patent_id=f"US{src.get('publication_number', hit.get('_id', ''))}",
source="USPTO",
title=src.get("title"),
abstract=src.get("abstract"),
publication_date=str(src.get("publication_date")) if src.get("publication_date") else None,
publication_year=str(src.get("publication_year")) if src.get("publication_year") else None,
application_number=src.get("application_number"),
application_date=str(src.get("application_date")) if src.get("application_date") else None,
application_type=src.get("application_type"),
number_of_claims=src.get("number_of_claims"),
status=src.get("status"),
inventors=[i for i in (inventors if isinstance(inventors, list) else [inventors]) if i is not None],
assignees=[a for a in (assignees if isinstance(assignees, list) else [assignees]) if a is not None],
ipc=_to_classification_strings(ipc),
cpc=_to_classification_strings(cpc),
country=src.get("country", "US"),
))
return patents
def _to_classification_strings(value) -> list[str]:
if not value:
return []
items = value if isinstance(value, list) else [value]
return [str(item).strip() for item in items if item and str(item).strip()]
def _descriptions_for_raw_codes(
raw_codes: list[str],
resolved: dict[str, model.IpcClassification],
) -> list[model.IpcClassification]:
return [
resolved[extract_ipc_symbol(raw)]
for raw in raw_codes
if extract_ipc_symbol(raw) in resolved
]
async def _enrich_patents_classifications(
patents: list[model.PatentEntry],
ipc_client: IpcSearchClient,
) -> None:
symbols = list(dict.fromkeys(
extract_ipc_symbol(raw)
for patent in patents
for raw in (*patent.ipc, *patent.cpc)
))
if not symbols:
return
try:
resolved = await ipc_client.resolve_symbols(symbols)
except MissingApiKeyError:
logger.warning("Classification enrichment skipped: Elasticsearch API key not configured.")
return
except ElasticsearchException as exc:
logger.warning("Classification enrichment failed: %s", exc)
return
except Exception as exc:
logger.exception("Classification enrichment failed unexpectedly: %s", exc)
return
for patent in patents:
patent.ipc_descriptions = _descriptions_for_raw_codes(patent.ipc, resolved)
patent.cpc_descriptions = _descriptions_for_raw_codes(patent.cpc, resolved)
def _filter_patents_by_name(
patents: list[model.PatentEntry],
first_name: str,
last_name: str,
) -> list[model.PatentEntry]:
return [
patent for patent in patents
if any(name_matches(inventor, first_name, last_name) for inventor in patent.inventors)
]
def _deduplicate_patents(patents: list[model.PatentEntry]) -> list[model.PatentEntry]:
seen: set[tuple[str, str, str, str]] = set()
deduplicated: list[model.PatentEntry] = []
for patent in patents:
key = _patent_dedup_key(patent)
if key in seen:
continue
seen.add(key)
deduplicated.append(patent)
return deduplicated
def _patent_dedup_key(patent: model.PatentEntry) -> tuple[str, str, str, str]:
stage = patent.kind or patent.application_type or ""
return (
patent.source,
patent.patent_id,
patent.publication_date or "",
stage,
)
async def _get_author(author_id: str) -> Author | None:
short_id = author_id.replace("https://openalex.org/", "")
result = await person_logic.search_persons(author_id=short_id)
return result.results[0] if result.results else None
def _extract_last_name(name: str | None) -> str | None:
if not name:
return None
parts = name.strip().split()
return parts[-1] if parts else None
def _extract_first_name(name: str | None) -> str | None:
if not name:
return None
parts = name.strip().split()
return parts[0] if len(parts) > 1 else None
async def get_all_patents(
page: int = 0,
size: int = 10,
search: str | None = None,
source: str | None = None,
sort_by: str = "date",
sort_direction: str = "desc",
client: PatentSearchClient | None = None,
ipc_client: IpcSearchClient | None = None,
) -> model.AllPatentsResponse:
all_patents_client = AllPatentsSearchClient()
ipc_search_client = ipc_client or IpcSearchClient()
if source == "EPO":
epo_data = await all_patents_client.search_epo(
all_patents_client.epo_query(page, size, search, sort_direction)
)
patents = _parse_epo_hits(epo_data)
total = epo_data.get("hits", {}).get("total", {}).get("value", 0)
elif source == "USPTO":
uspto_data = await all_patents_client.search_uspto(
all_patents_client.uspto_query(page, size, search, sort_direction)
)
patents = _parse_uspto_hits(uspto_data)
total = uspto_data.get("hits", {}).get("total", {}).get("value", 0)
else:
half = size // 2
epo_data, uspto_data = await asyncio.gather(
all_patents_client.search_epo(
all_patents_client.epo_query(page, half, search, sort_direction)
),
all_patents_client.search_uspto(
all_patents_client.uspto_query(page, half, search, sort_direction)
),
)
patents = _parse_epo_hits(epo_data) + _parse_uspto_hits(uspto_data)
total = (
epo_data.get("hits", {}).get("total", {}).get("value", 0) +
uspto_data.get("hits", {}).get("total", {}).get("value", 0)
)
await _enrich_patents_classifications(patents, ipc_search_client)
return model.AllPatentsResponse(
total=total,
page=page,
size=size,
patents=patents,
)
__all__ = [
"_deduplicate_patents",
"_filter_patents_by_institution",
"get_all_patents",
"get_patent_by_id",
"get_patents_by_author_id",
"get_patents_by_institution_id",
]
+2 -47
View File
@@ -1,47 +1,2 @@
from pydantic import BaseModel, ConfigDict, Field
class IpcClassification(BaseModel):
symbol: str
section: str | None = None
ipc_class: str | None = Field(default=None, serialization_alias="class")
subclass: str | None = None
main_group: str | None = None
subgroup: str | None = None
model_config = ConfigDict(populate_by_name=True)
class PatentEntry(BaseModel):
patent_id: str
source: str # "EPO" or "USPTO"
title: str | None = None
abstract: str | None = None
publication_date: str | None = None
publication_year: str | None = None
application_number: str | None = None
application_date: str | None = None
kind: str | None = None # EPO only
application_type: str | None = None # USPTO only
number_of_claims: int | None = None # USPTO only
status: str | None = None # USPTO only
inventors: list[str] = Field(default_factory=list)
assignees: list[str] = Field(default_factory=list)
ipc: list[str] = Field(default_factory=list)
ipc_descriptions: list[IpcClassification] = Field(default_factory=list)
cpc: list[str] = Field(default_factory=list)
cpc_descriptions: list[IpcClassification] = Field(default_factory=list)
country: str | None = None
class PatentsByAuthorResponse(BaseModel):
author_id: str
author_name: str | None = None
patent_count: int
patents: list[PatentEntry]
class AllPatentsResponse(BaseModel):
total: int
page: int
size: int
patents: list[PatentEntry]
"""Backward-compatible re-exports."""
from inse.patents.common.model import * # noqa: F403
+16 -240
View File
@@ -1,242 +1,18 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Name normalization and matching for patent inventor lookup.
Handles umlauts, diacritics, and common Latin transliterations so that
e.g. 'Müller' matches 'Mueller' and 'Muller'.
"""
import re
import unicodedata
# Characters that NFKD does not map to ASCII-friendly forms.
_CHAR_REPLACEMENTS: dict[str, str] = {
"ß": "ss",
"ẞ": "ss",
"æ": "ae",
"Æ": "ae",
"œ": "oe",
"Œ": "oe",
"ø": "o",
"Ø": "o",
"đ": "d",
"Đ": "d",
"ð": "d",
"Ð": "d",
"þ": "th",
"Þ": "th",
"ł": "l",
"Ł": "l",
"ı": "i",
"ſ": "s",
}
# German patent transliterations: ae/oe/ue often stand in for ä/ö/ü.
_DIGRAPH_COLLAPSES: tuple[tuple[str, str], ...] = (
("ae", "a"),
("oe", "o"),
("ue", "u"),
"""Backward-compatible re-exports."""
from inse.patents.authors.name_matching import ( # noqa: F401
first_name_match_kind,
name_matches,
search_name_variants,
tokens_equal,
)
# Common ASCII spellings in patent records for umlaut-derived vowels.
_PATENT_VOWEL_EXPANSIONS: tuple[tuple[str, str], ...] = (
(r"u([lmnrt])", r"ue\1"),
(r"o([lmnrt])", r"oe\1"),
(r"a([lmnrt])", r"ae\1"),
from inse.patents.common.text_normalization import ( # noqa: F401
name_token_variants,
normalize_name_part,
)
from inse.patents.institutions.name_matching import ( # noqa: F401
MIN_INSTITUTION_ACRONYM_LEN,
MIN_INSTITUTION_SUBSTRING_LEN,
MIN_INSTITUTION_VARIANT_LEN,
assignee_matches_institution_name,
institution_search_variants,
)
def normalize_name_part(value: str | None) -> str:
"""
Normalize a single name token for comparison.
Steps: transliteration map -> NFKD -> strip diacritics -> lowercase
-> remove apostrophes/punctuation -> collapse whitespace.
"""
if not value:
return ""
text = value.strip()
for src, dst in _CHAR_REPLACEMENTS.items():
text = text.replace(src, dst)
text = unicodedata.normalize("NFKD", text)
text = "".join(c for c in text if not unicodedata.combining(c))
text = text.lower()
text = re.sub(r"[''`´]", "", text)
text = re.sub(r"[^\w\s-]", "", text)
text = re.sub(r"\s+", " ", text).strip()
return text
def name_token_variants(value: str | None) -> set[str]:
"""
Return equivalent forms of a name token.
Includes the normalized base plus German digraph collapses
(Mueller -> muller) and hyphen Relaxed forms (Jean-Pierre -> jean pierre).
"""
base = normalize_name_part(value)
if not base:
return set()
variants = {base}
for src, dst in _DIGRAPH_COLLAPSES:
if src in base:
variants.add(base.replace(src, dst))
if "-" in base:
variants.add(base.replace("-", ""))
variants.add(base.replace("-", " "))
return {v for v in variants if v}
def _patent_transliteration_expansions(normalized: str) -> set[str]:
"""
ASCII spellings used in patent records (e.g. Müller indexed as Mueller).
Used for Elasticsearch recall only; post-filter applies stricter matching.
"""
expanded = {normalized}
for pattern, repl in _PATENT_VOWEL_EXPANSIONS:
if re.search(pattern, normalized):
expanded.add(re.sub(pattern, repl, normalized))
return expanded
def tokens_equal(
left: str | None,
right: str | None,
*,
allow_initial: bool = True,
) -> bool:
"""True when two name tokens are equivalent after normalization."""
left_variants = name_token_variants(left)
right_variants = name_token_variants(right)
if not left_variants or not right_variants:
return False
if left_variants & right_variants:
return True
if not allow_initial:
return False
return _initial_tokens_match(left, right)
def _initial_letter(token: str | None) -> str | None:
normalized = normalize_name_part(token)
if len(normalized) == 1 and normalized.isalpha():
return normalized
return None
def _initial_tokens_match(left: str | None, right: str | None) -> bool:
"""True when one token is a single-letter initial matching the other token."""
left_initial = _initial_letter(left)
right_initial = _initial_letter(right)
left_full = normalize_name_part(left)
right_full = normalize_name_part(right)
if left_initial and right_full and len(right_full) > 1:
return right_full.startswith(left_initial)
if right_initial and left_full and len(left_full) > 1:
return left_full.startswith(right_initial)
if left_initial and right_initial:
return left_initial == right_initial
return False
def _inventor_first_token(inventor_name: str) -> str:
if "," in inventor_name:
_, first_part = [p.strip() for p in inventor_name.split(",", 1)]
return first_part.split()[0] if first_part else ""
parts = inventor_name.split()
return parts[0] if parts else ""
def first_name_match_kind(
inventor_name: str,
first_name: str,
last_name: str,
) -> str:
"""
Match quality for the inventor first name: 'full', 'initial', or 'none'.
"""
if not name_matches(inventor_name, first_name, last_name):
return "none"
inventor_first = _inventor_first_token(inventor_name)
if tokens_equal(inventor_first, first_name, allow_initial=False):
return "full"
return "initial"
def search_name_variants(value: str | None) -> list[str]:
"""
Distinct search strings for Elasticsearch, preserving original casing
where useful but including normalized and transliterated forms.
"""
if not value or not value.strip():
return []
seen: set[str] = set()
ordered: list[str] = []
def _add(candidate: str) -> None:
key = candidate.casefold()
if candidate.strip() and key not in seen:
seen.add(key)
ordered.append(candidate.strip())
_add(value.strip())
normalized = normalize_name_part(value)
if normalized:
_add(normalized.title())
for variant in name_token_variants(value):
_add(variant.title())
for variant in _patent_transliteration_expansions(normalized):
_add(variant.title())
if normalized and len(normalized) > 1:
_add(normalized[0].upper())
return ordered
def name_matches(inventor_name: str, first_name: str, last_name: str) -> bool:
"""
True when an inventor entry matches first_name + last_name.
Supports:
- USPTO: 'Christian Weber', 'Christian Hans Weber'
- EPO: 'Weber, Christian', 'Weber, Christian Hans'
"""
if not inventor_name or not last_name:
return False
name = inventor_name.strip()
if "," in name:
last_part, first_part = [p.strip() for p in name.split(",", 1)]
first_token = first_part.split()[0] if first_part else ""
return (
tokens_equal(last_part, last_name, allow_initial=False)
and bool(first_name)
and tokens_equal(first_token, first_name)
)
parts = name.split()
if len(parts) < 2:
return False
return (
tokens_equal(parts[-1], last_name, allow_initial=False)
and bool(first_name)
and tokens_equal(parts[0], first_name)
)
@@ -0,0 +1 @@
"""Org patents index: institution-scoped patent aggregation."""
@@ -0,0 +1,199 @@
"""HTTP client for the org_patents Elasticsearch index."""
import json
import logging
from typing import Any
import httpx
from inse.patents.common.elastic_search_client import MissingApiKeyError
from inse.patents.org.mapping import ORG_PATENTS_INDEX, ORG_PATENTS_MAPPING
from inse.patents.org.model import MatchTypeFilter, OrgPatentEntry
from inse import config
logger = logging.getLogger(__name__)
DEFAULT_PAGE_SIZE = 20
class OrgPatentsSearchClient:
def __init__(
self,
base_url: str | None = None,
api_key: str | None = None,
timeout: float = 60.0,
transport: httpx.AsyncBaseTransport | None = None,
):
self.base_url = (base_url or config.settings.patent_elasticsearch_url).rstrip("/")
self.api_key = api_key if api_key is not None else config.settings.patent_elasticsearch_api_key
self.timeout = timeout
self.transport = transport
def _headers(self, content_type: str = "application/json") -> dict[str, str]:
if not self.api_key:
raise MissingApiKeyError("Patent Elasticsearch API key is not configured.")
return {
"Authorization": f"ApiKey {self.api_key}",
"Content-Type": content_type,
}
async def ensure_index(self) -> None:
async with httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
transport=self.transport,
) as client:
response = await client.head(
f"/{ORG_PATENTS_INDEX}",
headers=self._headers(),
)
if response.status_code == 404:
create_response = await client.put(
f"/{ORG_PATENTS_INDEX}",
headers=self._headers(),
json={"mappings": ORG_PATENTS_MAPPING},
)
create_response.raise_for_status()
logger.info("Created index %s", ORG_PATENTS_INDEX)
return
response.raise_for_status()
mapping_response = await client.put(
f"/{ORG_PATENTS_INDEX}/_mapping",
headers=self._headers(),
json=ORG_PATENTS_MAPPING,
)
mapping_response.raise_for_status()
async def delete_by_institution(self, institution_id: str) -> int:
payload = {
"query": {"term": {"institution_id": institution_id.upper()}},
}
async with httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
transport=self.transport,
) as client:
response = await client.post(
f"/{ORG_PATENTS_INDEX}/_delete_by_query",
headers=self._headers(),
json=payload,
params={"refresh": "true"},
)
if response.status_code == 404:
return 0
response.raise_for_status()
return response.json().get("deleted", 0)
async def bulk_index(self, documents: list[tuple[str, dict[str, Any]]]) -> None:
if not documents:
return
batch_size = 500
async with httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
transport=self.transport,
) as client:
for start in range(0, len(documents), batch_size):
batch = documents[start : start + batch_size]
bulk_lines: list[str] = []
for doc_id, source in batch:
bulk_lines.append(json.dumps({"index": {"_index": ORG_PATENTS_INDEX, "_id": doc_id}}))
bulk_lines.append(json.dumps(source))
payload = "\n".join(bulk_lines) + "\n"
response = await client.post(
"/_bulk",
content=payload,
headers=self._headers("application/x-ndjson"),
params={"refresh": "true"},
)
response.raise_for_status()
result = response.json()
if result.get("errors"):
failed = [
item
for item in result.get("items", [])
if item.get("index", {}).get("status", 200) >= 400
]
logger.error("Bulk index errors: %s", failed[:3])
raise RuntimeError("Bulk indexing into org_patents failed.")
async def search_by_institution(
self,
institution_id: str,
match_type: MatchTypeFilter = "all",
page: int = 0,
size: int = DEFAULT_PAGE_SIZE,
source: str | None = None,
) -> tuple[list[OrgPatentEntry], int]:
short_id = institution_id.replace("https://openalex.org/", "").upper()
filters: list[dict[str, Any]] = [{"term": {"institution_id": short_id}}]
if match_type == "institution":
filters.append({"terms": {"match_type": ["institution", "both"]}})
elif match_type == "name":
filters.append({"terms": {"match_type": ["name", "both"]}})
elif match_type == "both":
filters.append({"term": {"match_type": "both"}})
if source in ("EPO", "USPTO"):
filters.append({"term": {"source": source}})
payload = {
"from": page * size,
"size": size,
"track_total_hits": True,
"query": {"bool": {"filter": filters}},
"sort": [
{"publication_year": {"order": "desc", "missing": "_last"}},
{"patent_id": {"order": "asc"}},
],
}
async with httpx.AsyncClient(
base_url=self.base_url,
timeout=self.timeout,
transport=self.transport,
) as client:
response = await client.post(
f"/{ORG_PATENTS_INDEX}/_search",
headers=self._headers(),
json=payload,
)
if response.status_code == 404:
return [], 0
response.raise_for_status()
data = response.json()
total = data.get("hits", {}).get("total", {}).get("value", 0)
patents = [_hit_to_org_patent(hit) for hit in data.get("hits", {}).get("hits", [])]
return patents, total
def _hit_to_org_patent(hit: dict[str, Any]) -> OrgPatentEntry:
source = hit.get("_source", {})
publication_year = source.get("publication_year")
return OrgPatentEntry(
institution_id=source.get("institution_id", ""),
institution_name=source.get("institution_name"),
patent_id=source.get("patent_id", ""),
source=source.get("source", ""),
match_type=source.get("match_type", "institution"),
title=source.get("title"),
abstract=source.get("abstract"),
publication_date=source.get("publication_date"),
publication_year=str(publication_year) if publication_year is not None else None,
application_number=source.get("application_number"),
application_date=source.get("application_date"),
kind=source.get("kind"),
application_type=source.get("application_type"),
number_of_claims=source.get("number_of_claims"),
status=source.get("status"),
inventors=source.get("inventors") or [],
assignees=source.get("assignees") or [],
ipc=source.get("ipc") or [],
cpc=source.get("cpc") or [],
country=source.get("country"),
matched_authors=source.get("matched_authors") or [],
)
+429
View File
@@ -0,0 +1,429 @@
"""Business logic for org_patents index build and retrieval."""
import asyncio
import logging
import re
from dataclasses import dataclass, field
import httpx
from fastapi import HTTPException
from starlette.status import HTTP_502_BAD_GATEWAY
from starlette.status import HTTP_503_SERVICE_UNAVAILABLE
from inse.institutions.institutions_search_client import InstitutionsSearchClient
from inse.integrations import elasticsearch
from inse.models.openalex.author import Author
from inse.patents.authors.name_matching import name_matches
from inse.patents.common.elastic_search_client import MissingApiKeyError
from inse.patents.common.model import PatentEntry
from inse.patents.common.parsing import (
deduplicate_patents,
enrich_patents_classifications,
parse_epo_hits,
parse_uspto_hits,
patent_dedup_key,
)
from inse.patents.institutions.logic import get_patents_by_institution_id
from inse.patents.ipc_search_client import IpcSearchClient
from inse.patents.org.elastic_search_client import OrgPatentsSearchClient
from inse.patents.org.model import (
MatchType,
MatchTypeFilter,
MatchedAuthor,
OrgPatentEntry,
OrgPatentsResponse,
)
from inse.patents.search_client import PatentSearchClient
logger = logging.getLogger(__name__)
AUTHOR_PAGE_SIZE = 500
ORG_PATENT_SEARCH_SIZE = 500
AUTHOR_SEARCH_CONCURRENCY = 8
def _extract_last_name(name: str | None) -> str | None:
if not name:
return None
parts = name.strip().split()
return parts[-1] if parts else None
def _extract_first_name(name: str | None) -> str | None:
if not name:
return None
parts = name.strip().split()
return parts[0] if len(parts) > 1 else None
def _filter_patents_by_name(
patents: list[PatentEntry],
first_name: str,
last_name: str,
) -> list[PatentEntry]:
return [
patent
for patent in patents
if any(
name_matches(inventor, first_name, last_name)
for inventor in patent.inventors
)
]
@dataclass
class _AccumulatedPatent:
patent: PatentEntry
institution_match: bool = False
matched_authors: dict[str, MatchedAuthor] = field(default_factory=dict)
def normalize_institution_id(institution_id: str) -> str:
return institution_id.replace("https://openalex.org/", "").upper()
def normalize_author_id(author_id: str | None) -> str:
if not author_id:
return ""
return author_id.replace("https://openalex.org/", "").upper()
def org_patent_document_id(institution_id: str, patent: PatentEntry) -> str:
stage = patent.kind or patent.application_type or "none"
safe_patent_id = re.sub(r"[^A-Za-z0-9_-]", "_", patent.patent_id)
safe_date = patent.publication_date or "none"
safe_stage = re.sub(r"[^A-Za-z0-9_-]", "_", stage)
return f"{normalize_institution_id(institution_id)}_{patent.source}_{safe_patent_id}_{safe_date}_{safe_stage}"
def resolve_match_type(institution_match: bool, has_name_match: bool) -> MatchType:
if institution_match and has_name_match:
return "both"
if institution_match:
return "institution"
return "name"
def merge_org_patents(
institution_id: str,
institution_name: str | None,
institution_patents: list[PatentEntry],
author_patents: list[tuple[Author, list[PatentEntry]]],
) -> list[OrgPatentEntry]:
accumulated: dict[tuple[str, str, str, str], _AccumulatedPatent] = {}
for patent in institution_patents:
key = patent_dedup_key(patent)
entry = accumulated.get(key)
if entry is None:
accumulated[key] = _AccumulatedPatent(patent=patent, institution_match=True)
else:
entry.institution_match = True
for author, patents in author_patents:
author_id = normalize_author_id(author.id)
author_name = author.display_name or ""
if not author_id or not author_name:
continue
matched_author = MatchedAuthor(
openalex_author_id=author_id,
author_name=author_name,
)
for patent in patents:
key = patent_dedup_key(patent)
entry = accumulated.get(key)
if entry is None:
accumulated[key] = _AccumulatedPatent(
patent=patent,
matched_authors={author_id: matched_author},
)
else:
entry.matched_authors[author_id] = matched_author
org_patents: list[OrgPatentEntry] = []
short_institution_id = normalize_institution_id(institution_id)
for entry in accumulated.values():
has_name_match = bool(entry.matched_authors)
match_type = resolve_match_type(entry.institution_match, has_name_match)
org_patents.append(
OrgPatentEntry(
institution_id=short_institution_id,
institution_name=institution_name,
match_type=match_type,
matched_authors=list(entry.matched_authors.values()),
**entry.patent.model_dump(),
)
)
org_patents.sort(
key=lambda patent: (
patent.publication_year or "",
patent.patent_id,
),
reverse=True,
)
return org_patents
def org_patent_to_es_document(patent: OrgPatentEntry) -> dict:
publication_year = None
if patent.publication_year:
try:
publication_year = int(patent.publication_year)
except ValueError:
publication_year = None
return {
"institution_id": patent.institution_id,
"institution_name": patent.institution_name,
"patent_id": patent.patent_id,
"source": patent.source,
"match_type": patent.match_type,
"title": patent.title,
"abstract": patent.abstract,
"publication_date": patent.publication_date,
"publication_year": publication_year,
"application_number": patent.application_number,
"application_date": patent.application_date,
"kind": patent.kind,
"application_type": patent.application_type,
"number_of_claims": patent.number_of_claims,
"status": patent.status,
"inventors": patent.inventors,
"assignees": patent.assignees,
"ipc": patent.ipc,
"cpc": patent.cpc,
"country": patent.country,
"matched_authors": [
author.model_dump() for author in patent.matched_authors
],
}
def fetch_authors_for_institution(institution_id: str) -> list[Author]:
short_id = normalize_institution_id(institution_id)
query = {
"nested": {
"path": "last_known_institutions",
"query": {
"term": {
"last_known_institutions.id": f"https://openalex.org/{short_id}",
}
},
}
}
authors: list[Author] = []
search_after: list | None = None
sort = [
{"works_count": {"order": "desc"}},
{"id": {"order": "asc"}},
]
while True:
body: dict = {
"size": AUTHOR_PAGE_SIZE,
"query": query,
"sort": sort,
}
if search_after:
body["search_after"] = search_after
response = elasticsearch.search(index="openalex-authors", body=body)
hits = response.get("hits", {}).get("hits", [])
if not hits:
break
for hit in hits:
source = dict(hit.get("_source", {}))
source["id"] = source.get("id") or hit.get("_id", "")
author = Author.from_dict(source)
if author:
authors.append(author)
if len(hits) < AUTHOR_PAGE_SIZE:
break
search_after = hits[-1].get("sort")
if not search_after:
break
return authors
async def _search_patents_by_author(
author: Author,
search_client: PatentSearchClient,
) -> list[PatentEntry]:
author_name = author.display_name
last_name = _extract_last_name(author_name)
first_name = _extract_first_name(author_name)
if not last_name:
return []
try:
epo_data, uspto_data = await asyncio.gather(
search_client.search_epo(
search_client.epo_query_by_inventor(
last_name, first_name, size=ORG_PATENT_SEARCH_SIZE
)
),
search_client.search_uspto(
search_client.uspto_query_by_inventor(
last_name, first_name, size=ORG_PATENT_SEARCH_SIZE
)
),
)
except (MissingApiKeyError, httpx.HTTPError):
raise
patents = parse_epo_hits(epo_data) + parse_uspto_hits(uspto_data)
if first_name and last_name:
patents = _filter_patents_by_name(patents, first_name, last_name)
return deduplicate_patents(patents)
async def build_org_patents_for_institution(
institution_id: str,
search_client: PatentSearchClient | None = None,
ipc_client: IpcSearchClient | None = None,
institutions_client: InstitutionsSearchClient | None = None,
) -> list[OrgPatentEntry]:
patent_client = search_client or PatentSearchClient()
ipc_search_client = ipc_client or IpcSearchClient()
institution_client = institutions_client or InstitutionsSearchClient()
short_id = normalize_institution_id(institution_id)
institution = institution_client.get_institution_by_id(short_id)
institution_name = institution.display_name
institution_response = await get_patents_by_institution_id(
institution_id=short_id,
client=patent_client,
ipc_client=ipc_search_client,
institutions_client=institution_client,
)
institution_patents = institution_response.patents
authors = fetch_authors_for_institution(short_id)
logger.info(
"Building org_patents for %s (%s): %d authors, %d institution patents",
institution_name,
short_id,
len(authors),
len(institution_patents),
)
semaphore = asyncio.Semaphore(AUTHOR_SEARCH_CONCURRENCY)
async def _fetch_for_author(author: Author) -> tuple[Author, list[PatentEntry]]:
async with semaphore:
patents = await _search_patents_by_author(author, patent_client)
return author, patents
author_results = await asyncio.gather(
*[_fetch_for_author(author) for author in authors],
return_exceptions=True,
)
author_patents: list[tuple[Author, list[PatentEntry]]] = []
for result in author_results:
if isinstance(result, Exception):
logger.warning("Author patent search failed: %s", result)
continue
author_patents.append(result)
org_patents = merge_org_patents(
institution_id=short_id,
institution_name=institution_name,
institution_patents=institution_patents,
author_patents=author_patents,
)
await enrich_patents_classifications(
[patent for patent in org_patents],
ipc_search_client,
)
return org_patents
async def index_org_patents_for_institution(
institution_id: str,
search_client: PatentSearchClient | None = None,
ipc_client: IpcSearchClient | None = None,
institutions_client: InstitutionsSearchClient | None = None,
org_client: OrgPatentsSearchClient | None = None,
) -> int:
short_id = normalize_institution_id(institution_id)
org_patents_client = org_client or OrgPatentsSearchClient()
org_patents = await build_org_patents_for_institution(
institution_id=short_id,
search_client=search_client,
ipc_client=ipc_client,
institutions_client=institutions_client,
)
await org_patents_client.ensure_index()
deleted = await org_patents_client.delete_by_institution(short_id)
logger.info("Deleted %d existing org_patents documents for %s", deleted, short_id)
documents = [
(
org_patent_document_id(short_id, patent),
org_patent_to_es_document(patent),
)
for patent in org_patents
]
await org_patents_client.bulk_index(documents)
logger.info("Indexed %d org_patents documents for %s", len(documents), short_id)
return len(documents)
async def get_org_patents_by_institution_id(
institution_id: str,
match_type: MatchTypeFilter = "all",
page: int = 0,
size: int = 20,
source: str | None = None,
org_client: OrgPatentsSearchClient | None = None,
institutions_client: InstitutionsSearchClient | None = None,
) -> OrgPatentsResponse:
short_id = normalize_institution_id(institution_id)
org_patents_client = org_client or OrgPatentsSearchClient()
institution_client = institutions_client or InstitutionsSearchClient()
try:
institution = institution_client.get_institution_by_id(short_id)
institution_name = institution.display_name
except Exception:
institution_name = None
try:
await org_patents_client.ensure_index()
patents, total = await org_patents_client.search_by_institution(
institution_id=short_id,
match_type=match_type,
page=page,
size=size,
source=source,
)
except MissingApiKeyError as exc:
raise HTTPException(
status_code=HTTP_503_SERVICE_UNAVAILABLE,
detail="Patent search is not configured.",
) from exc
except httpx.HTTPError as exc:
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="org_patents search request failed.",
) from exc
return OrgPatentsResponse(
institution_id=short_id,
institution_name=institution_name,
patent_count=total,
page=page,
size=size,
patents=patents,
)
@@ -0,0 +1,33 @@
ORG_PATENTS_INDEX = "org_patents"
ORG_PATENTS_MAPPING = {
"properties": {
"institution_id": {"type": "keyword"},
"institution_name": {"type": "text", "fields": {"keyword": {"type": "keyword"}}},
"patent_id": {"type": "keyword"},
"source": {"type": "keyword"},
"match_type": {"type": "keyword"},
"title": {"type": "text"},
"abstract": {"type": "text"},
"publication_date": {"type": "keyword"},
"publication_year": {"type": "integer"},
"application_number": {"type": "keyword"},
"application_date": {"type": "keyword"},
"kind": {"type": "keyword"},
"application_type": {"type": "keyword"},
"number_of_claims": {"type": "integer"},
"status": {"type": "keyword"},
"inventors": {"type": "keyword"},
"assignees": {"type": "keyword"},
"ipc": {"type": "keyword"},
"cpc": {"type": "keyword"},
"country": {"type": "keyword"},
"matched_authors": {
"type": "nested",
"properties": {
"openalex_author_id": {"type": "keyword"},
"author_name": {"type": "keyword"},
},
},
}
}
@@ -0,0 +1,29 @@
from typing import Literal
from pydantic import BaseModel, Field
from inse.patents.common.model import PatentEntry
MatchType = Literal["institution", "name", "both"]
MatchTypeFilter = Literal["institution", "name", "both", "all"]
class MatchedAuthor(BaseModel):
openalex_author_id: str
author_name: str
class OrgPatentEntry(PatentEntry):
institution_id: str
institution_name: str | None = None
match_type: MatchType
matched_authors: list[MatchedAuthor] = Field(default_factory=list)
class OrgPatentsResponse(BaseModel):
institution_id: str
institution_name: str | None = None
patent_count: int
page: int = 0
size: int = 20
patents: list[OrgPatentEntry]
@@ -0,0 +1,44 @@
from functools import lru_cache
from typing import Annotated
from fastapi import APIRouter, Depends, Query
from inse.institutions.institutions_search_client import InstitutionsSearchClient
from inse.patents.org import logic
from inse.patents.org.model import MatchTypeFilter, OrgPatentsResponse
router = APIRouter(prefix="/api/inse-service/institutions", tags=["Patents"])
@lru_cache
def get_institutions_search_client() -> InstitutionsSearchClient:
return InstitutionsSearchClient()
@router.get(
"/{id}/org-patents",
operation_id="getOrgPatentsByInstitution",
response_model=OrgPatentsResponse,
summary="Get pre-indexed org patents for an institution.",
)
async def get_org_patents_by_institution(
id: str,
client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
match_type: Annotated[
MatchTypeFilter,
Query(description="Filter patents by match type."),
] = "all",
page: int = 0,
size: int = 20,
source: str | None = None,
) -> OrgPatentsResponse:
return await logic.get_org_patents_by_institution_id(
institution_id=id,
match_type=match_type,
page=page,
size=size,
source=source,
institutions_client=client,
)
@@ -0,0 +1,100 @@
from inse.patents.common.model import PatentEntry
from inse.patents.org.logic import merge_org_patents, org_patent_document_id, resolve_match_type
from inse.patents.org.model import MatchedAuthor
from inse.models.openalex.author import Author
def _patent(
patent_id: str = "EP1234567",
source: str = "EPO",
) -> PatentEntry:
return PatentEntry(
patent_id=patent_id,
source=source,
title="Example patent",
publication_year="2024",
)
def _author(author_id: str, name: str) -> Author:
return Author(
id=f"https://openalex.org/{author_id}",
display_name=name,
)
def test_resolve_match_type() -> None:
assert resolve_match_type(True, True) == "both"
assert resolve_match_type(True, False) == "institution"
assert resolve_match_type(False, True) == "name"
def test_merge_org_patents_keeps_institution_only_patents() -> None:
result = merge_org_patents(
institution_id="I62318514",
institution_name="University of Duisburg-Essen",
institution_patents=[_patent("EP111")],
author_patents=[],
)
assert len(result) == 1
assert result[0].match_type == "institution"
assert result[0].matched_authors == []
def test_merge_org_patents_keeps_name_only_patents() -> None:
author = _author("A123", "Max Mustermann")
result = merge_org_patents(
institution_id="I62318514",
institution_name="University of Duisburg-Essen",
institution_patents=[],
author_patents=[(author, [_patent("EP222")])],
)
assert len(result) == 1
assert result[0].match_type == "name"
assert result[0].matched_authors[0].openalex_author_id == "A123"
def test_merge_org_patents_marks_both_when_same_patent_found_twice() -> None:
author = _author("A123", "Max Mustermann")
patent = _patent("EP333")
result = merge_org_patents(
institution_id="I62318514",
institution_name="University of Duisburg-Essen",
institution_patents=[patent],
author_patents=[(author, [patent])],
)
assert len(result) == 1
assert result[0].match_type == "both"
assert len(result[0].matched_authors) == 1
def test_merge_org_patents_deduplicates_and_collects_multiple_authors() -> None:
author_one = _author("A111", "Max Mustermann")
author_two = _author("A222", "Maria Muster")
patent = _patent("EP444")
result = merge_org_patents(
institution_id="I62318514",
institution_name="University of Duisburg-Essen",
institution_patents=[],
author_patents=[
(author_one, [patent]),
(author_two, [patent]),
],
)
assert len(result) == 1
assert result[0].match_type == "name"
assert {author.openalex_author_id for author in result[0].matched_authors} == {"A111", "A222"}
def test_org_patent_document_id_is_stable() -> None:
patent = _patent("EP1234567")
patent.kind = "A1"
patent.publication_date = "20240101"
doc_id = org_patent_document_id("I62318514", patent)
assert doc_id == "I62318514_EPO_EP1234567_20240101_A1"
@@ -0,0 +1,27 @@
"""Combined patent Elasticsearch client."""
from inse.patents.authors.search_queries import InventorSearchQueries
from inse.patents.common.elastic_search_client import (
DEFAULT_SEARCH_SIZE,
EPO_INDEX,
USPTO_INDEX,
BasePatentSearchClient,
MissingApiKeyError,
)
from inse.patents.institutions.search_queries import AssigneeSearchQueries
class PatentSearchClient(
InventorSearchQueries,
AssigneeSearchQueries,
BasePatentSearchClient,
):
pass
__all__ = [
"DEFAULT_SEARCH_SIZE",
"EPO_INDEX",
"MissingApiKeyError",
"PatentSearchClient",
"USPTO_INDEX",
]
+7 -61
View File
@@ -1,64 +1,10 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Aggregates patent API routers."""
from fastapi import APIRouter
from . import logic
from . import model
from typing import Annotated, Optional
from fastapi import Path
from fastapi import Query
router = APIRouter(prefix="/api/inse-service/authors", tags=["Patents"])
patents_router = APIRouter(prefix="/api/inse-service", tags=["Patents"])
from inse.patents.all.service import router as all_patents_router
from inse.patents.authors.service import router as author_patents_router
from inse.patents.institutions.service import router as institution_patents_router
@router.get(
"/{author_id}/patents",
operation_id="getPatentsByAuthor",
response_model=model.PatentsByAuthorResponse,
summary="Get patents matched to an author by name.",
)
async def get_patents_by_author(author_id: str):
return await logic.get_patents_by_author_id(author_id)
@patents_router.get(
"/patents/{identifier}",
operation_id="getPatentByIdOrTitle",
response_model=model.PatentEntry | None,
summary="Returns one publication by OpenAlex ID or DOI.",
)
async def get_patent_by_identifier(
identifier: Annotated[
str, Path(description="")
],
prefix: Annotated[
Optional[str], Query(description="Application Prefix (EP or US)")
] = "",
title: Annotated[
Optional[str], Query(description="Do we want to fallback to title search if ID and DOI dont work?")
] = "",
):
return await logic.get_patent(patent_id=identifier,prefix=prefix,title=title)
@patents_router.get(
"/patents",
operation_id="getAllPatents",
response_model=model.AllPatentsResponse,
summary="Get all patents with pagination and search.",
)
async def get_all_patents(
page: int = 0,
size: int = 10,
search: str | None = None,
source: str | None = None,
sort_by: str = "date",
sort_direction: str = "desc",
):
return await logic.get_all_patents(
page=page,
size=size,
search=search,
source=source,
sort_by=sort_by,
sort_direction=sort_direction,
)
router = author_patents_router
patents_router = all_patents_router
institution_patents_router = institution_patents_router
@@ -1,6 +1,9 @@
import json
import httpx
import pytest
from unittest.mock import patch, MagicMock
from inse.model import ESIndex
from inse.patents.elastic_search_all_patents_client import AllPatentsSearchClient
from inse.patents.elastic_search_client import (
DEFAULT_SEARCH_SIZE,
PatentSearchClient,
@@ -30,17 +33,53 @@ def test_uspto_index_is_3_0():
assert ESIndex.EPO_INDEX == "epo_index_1.0"
def test_epo_query_by_applicant_uses_applicants_name_field():
client = PatentSearchClient(api_key="test-key")
payload = client.epo_query_by_applicant(
["University of Duisburg-Essen", "Universität Duisburg-Essen"]
)
assert payload["size"] == DEFAULT_SEARCH_SIZE
assert "applicants_name" in str(payload["query"])
assert payload["query"]["bool"]["minimum_should_match"] == 1
def test_uspto_query_by_assignee_uses_assignees_orgs_field():
client = PatentSearchClient(api_key="test-key")
payload = client.uspto_query_by_assignee(["Harvard University"])
assert "assignees_orgs" in str(payload["query"])
def test_detail_and_title_queries_skip_empty_date_filters():
client = AllPatentsSearchClient(api_key="test-key")
epo_payload = client.epo_title_query("method for generating and using a map")
uspto_payload = client.uspto_detail_query("US12508845")
assert "must" not in epo_payload["query"]["bool"]
assert "must" not in uspto_payload["query"]["bool"]
@pytest.mark.anyio
async def test_search_epo_posts_to_correct_index():
captured: list[dict] = []
def fake_search(index: str, body: dict, cluster=None):
captured.append({"index": index, "body": body})
return {"hits": {"hits": []}}
def handler(request: httpx.Request) -> httpx.Response:
path_parts = request.url.path.strip("/").split("/")
captured.append(
{
"index": path_parts[-2],
"body": json.loads(request.content) if request.content else {},
}
)
return httpx.Response(200, json={"hits": {"hits": []}})
with patch("inse.integrations.elasticsearch.search", side_effect=fake_search):
client = PatentSearchClient(api_key="test-key")
await client.search_epo(client.epo_query_by_inventor("Weber", "Christian"))
client = PatentSearchClient(
api_key="test-key",
transport=httpx.MockTransport(handler),
)
await client.search_epo(client.epo_query_by_inventor("Weber", "Christian"))
assert len(captured) == 1
assert captured[0]["index"] == ESIndex.EPO_INDEX
@@ -0,0 +1,83 @@
from inse.patents import model
from inse.patents.institutions.logic import filter_patents_by_institution
from inse.patents.institutions.name_matching import (
assignee_matches_institution_name,
institution_search_variants,
)
def test_institution_search_variants_exclude_single_letter_initials() -> None:
variants = institution_search_variants("Harvard University")
assert "H" not in variants
assert "U" not in variants
assert any("Harvard" in variant for variant in variants)
def test_assignee_matches_institution_name_accepts_valid_university() -> None:
assert assignee_matches_institution_name(
"Universitaet Duisburg-Essen",
"University of Duisburg-Essen",
)
assert assignee_matches_institution_name(
"President and Fellows of Harvard College",
"Harvard University",
)
def test_assignee_matches_institution_name_rejects_false_positives() -> None:
assert not assignee_matches_institution_name("u-blox AG", "Harvard University")
assert not assignee_matches_institution_name(
"LG H&H CO., LTD.",
"Harvard University",
)
assert not assignee_matches_institution_name(
"K & N Engineering, Inc.",
"National Institute for Fusion Science",
)
assert not assignee_matches_institution_name(
"K&K INC.",
"National Institute for Fusion Science",
)
def test_filter_patents_by_institution_removes_unrelated_assignees() -> None:
institution = _institution(
display_name="Harvard University",
alternatives=["Universidad de Harvard"],
)
patents = [
model.PatentEntry(
patent_id="US1",
source="USPTO",
assignees=["President and Fellows of Harvard College"],
),
model.PatentEntry(
patent_id="US2",
source="USPTO",
assignees=["u-blox AG"],
),
model.PatentEntry(
patent_id="US3",
source="USPTO",
assignees=["LG H&H CO., LTD."],
),
]
result = filter_patents_by_institution(patents, institution)
assert len(result) == 1
assert result[0].patent_id == "US1"
def _institution(
display_name: str,
alternatives: list[str] | None = None,
):
from inse.models.openalex.institution import Institution
return Institution(
id="https://openalex.org/I123",
display_name=display_name,
display_name_alternatives=alternatives,
)
@@ -1,4 +1,4 @@
from unittest.mock import AsyncMock, patch
import httpx
import pytest
from inse.patents.ipc_search_client import IPC_INDEX, IpcSearchClient
@@ -11,51 +11,57 @@ def anyio_backend():
@pytest.mark.anyio
async def test_resolve_symbols_posts_to_ipc_index():
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",
}
},
]
}
}
requests: list[str] = []
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
mock_search.return_value = mock_response
client = IpcSearchClient()
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",
}
},
]
}
},
)
result = await client.resolve_symbols(["H01L 21/02"])
transport = httpx.MockTransport(handler)
client = IpcSearchClient(api_key="test-key", transport=transport)
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"
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"
@pytest.mark.anyio
async def test_resolve_symbols_does_not_crash_for_subclass_codes():
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"])
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, json={"hits": {"hits": []}})
assert "A61J 1/14" in result
assert "C07D 319/06" in result
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
+60 -7
View File
@@ -1,4 +1,6 @@
from inse.patents import logic, model
from inse.patents import model
from inse.patents.common.parsing import deduplicate_patents
from inse.patents.institutions.logic import filter_patents_by_institution
def _uspto_patent(
@@ -34,7 +36,7 @@ def _epo_patent(
def test_deduplicate_patents_removes_exact_duplicates() -> None:
patents = [_uspto_patent(), _uspto_patent(), _uspto_patent()]
result = logic._deduplicate_patents(patents)
result = deduplicate_patents(patents)
assert len(result) == 1
assert result[0].patent_id == "US12508845"
@@ -43,7 +45,7 @@ def test_deduplicate_patents_removes_exact_duplicates() -> None:
def test_deduplicate_patents_keeps_distinct_publication_numbers() -> None:
patents = [_uspto_patent("US12508845"), _uspto_patent("US12303461")]
result = logic._deduplicate_patents(patents)
result = deduplicate_patents(patents)
assert len(result) == 2
assert [patent.patent_id for patent in result] == ["US12508845", "US12303461"]
@@ -55,7 +57,7 @@ def test_deduplicate_patents_keeps_first_occurrence_of_exact_duplicate() -> None
duplicate = _uspto_patent()
duplicate.abstract = "Second abstract"
result = logic._deduplicate_patents([first, duplicate])
result = deduplicate_patents([first, duplicate])
assert len(result) == 1
assert result[0].abstract == "First abstract"
@@ -65,7 +67,7 @@ def test_deduplicate_patents_keeps_epo_application_and_grant_stages() -> None:
application = _epo_patent(publication_date="20161005", kind="A1")
grant = _epo_patent(publication_date="20180411", kind="B1")
result = logic._deduplicate_patents([application, grant])
result = deduplicate_patents([application, grant])
assert len(result) == 2
assert [patent.kind for patent in result] == ["A1", "B1"]
@@ -75,7 +77,7 @@ def test_deduplicate_patents_keeps_same_patent_number_with_different_dates() ->
earlier = _uspto_patent(publication_date="20241230")
later = _uspto_patent(publication_date="20251230")
result = logic._deduplicate_patents([earlier, later])
result = deduplicate_patents([earlier, later])
assert len(result) == 2
assert [patent.publication_date for patent in result] == ["20241230", "20251230"]
@@ -85,7 +87,58 @@ def test_deduplicate_patents_keeps_same_patent_number_with_different_uspto_types
utility = _uspto_patent(application_type="utility")
reissue = _uspto_patent(application_type="reissue")
result = logic._deduplicate_patents([utility, reissue])
result = deduplicate_patents([utility, reissue])
assert len(result) == 2
assert [patent.application_type for patent in result] == ["utility", "reissue"]
def test_assignee_matches_institution_name_accepts_alternative_names() -> None:
from inse.patents.name_matching import assignee_matches_institution_name
assert assignee_matches_institution_name(
"Universitaet Duisburg-Essen",
"University of Duisburg-Essen",
)
assert not assignee_matches_institution_name(
"Harvard University",
"University of Duisburg-Essen",
)
def test_filter_patents_by_institution_keeps_matching_assignees() -> None:
institution = _institution(
display_name="University of Duisburg-Essen",
alternatives=["Universität Duisburg-Essen"],
)
matching = model.PatentEntry(
patent_id="EP123",
source="EPO",
assignees=["University of Duisburg-Essen"],
)
other = model.PatentEntry(
patent_id="EP456",
source="EPO",
assignees=["Harvard University"],
)
result = filter_patents_by_institution(
[matching, other],
institution,
)
assert len(result) == 1
assert result[0].patent_id == "EP123"
def _institution(
display_name: str,
alternatives: list[str] | None = None,
):
from inse.models.openalex.institution import Institution
return Institution(
id="https://openalex.org/I123",
display_name=display_name,
display_name_alternatives=alternatives,
)
+79 -55
View File
@@ -9,15 +9,10 @@ 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 inse.exceptions import (
NotFoundException,
ElasticsearchException,
ElasticsearchNotFoundException,
ElasticsearchConnectionException,
BadRequestException,
)
from fastapi import HTTPException
from inse.model import ESIndex
from .. import config
@@ -40,7 +35,7 @@ logger = logging.getLogger(__name__)
INDEX_NAME = "openalex-authors"
UDE_INSTITUTION_ID = "https://openalex.org/I62318514" # Universität Duisburg-Essen
async def find_ude_author_by_name(display_name: str) -> Optional[dict]:
def find_ude_author_by_name(display_name: str) -> Optional[dict]:
query = {
"_source": ["display_name"],
"query": {
@@ -68,7 +63,7 @@ async def find_ude_author_by_name(display_name: str) -> Optional[dict]:
}
try:
data = await elasticsearch.search(index=INDEX_NAME, body=query)
data = elasticsearch.search(index=INDEX_NAME, body=query)
except Exception:
logger.exception(f"UDE-Lookup für '{display_name}' fehlgeschlagen.")
return None
@@ -94,7 +89,7 @@ async def find_ude_author_by_name(display_name: str) -> Optional[dict]:
}
async def get_author_name_by_id(author_id: str) -> Optional[str]:
def get_author_name_by_id(author_id: str) -> Optional[str]:
try:
query = {
"_source": ["id", "display_name"],
@@ -104,7 +99,7 @@ async def get_author_name_by_id(author_id: str) -> Optional[str]:
"size": 1,
}
data = await elasticsearch.search(index=INDEX_NAME, body=query)
data = elasticsearch.search(index=INDEX_NAME, body=query)
hits = data.get("hits", {}).get("hits", [])
if not hits:
return None
@@ -114,7 +109,7 @@ async def get_author_name_by_id(author_id: str) -> Optional[str]:
return None
async def search_persons(
def search_persons(
author_id: Optional[str] = None,
query: Optional[str] = None,
) -> AuthorsListResponse:
@@ -136,7 +131,7 @@ async def search_persons(
else:
return AuthorsListResponse(results=[], meta=Meta(count=0))
data = await elasticsearch.search(index=ESIndex.OPENALEX_AUTHORS, query=query_)
data = elasticsearch.search(index=ESIndex.OPENALEX_AUTHORS, query=query_)
authors = []
for hit in data.get("hits", {}).get("hits", []):
@@ -160,7 +155,7 @@ async def search_persons(
return AuthorsListResponse(results=authors, meta=Meta(count=len(authors)))
async def _fetch_author_display_name(author_id: str) -> Optional[str]:
def _fetch_author_display_name(author_id: str) -> Optional[str]:
query = {
"query_string": {
@@ -169,7 +164,7 @@ async def _fetch_author_display_name(author_id: str) -> Optional[str]:
}
}
response = await elasticsearch.search(
response = elasticsearch.search(
index=INDEX_NAME,
query=query,
source=["display_name"],
@@ -183,7 +178,7 @@ async def _fetch_author_display_name(author_id: str) -> Optional[str]:
return hits[0].get("_source", {}).get("display_name")
async def _fetch_works_and_topics(author_id: str) -> tuple[list, list]:
def _fetch_works_and_topics(author_id: str) -> tuple[list, list]:
WORK_SOURCE_FIELDS = [
"title",
@@ -226,7 +221,7 @@ async def _fetch_works_and_topics(author_id: str) -> tuple[list, list]:
},
}
response = await elasticsearch.search(
response = elasticsearch.search(
index=config.settings.openalex_works_search_index,
body=body,
)
@@ -256,7 +251,7 @@ async def _fetch_works_and_topics(author_id: str) -> tuple[list, list]:
return works, topics
async def _get_publication_years_for_author(author_id: str) -> list[int]:
def _get_publication_years_for_author(author_id: str) -> list[int]:
author_url = f"https://openalex.org/{author_id.strip()}"
body = {
@@ -283,7 +278,7 @@ async def _get_publication_years_for_author(author_id: str) -> list[int]:
},
}
response = await elasticsearch.search(
response = elasticsearch.search(
index=config.settings.openalex_works_search_index,
body=body,
)
@@ -364,8 +359,8 @@ def _compute_career_metrics(publication_years: list[int]) -> CareerMetrics:
)
async def get_career_metrics_for_author(author_id: str) -> CareerMetrics:
publication_years = await _get_publication_years_for_author(author_id)
def get_career_metrics_for_author(author_id: str) -> CareerMetrics:
publication_years = _get_publication_years_for_author(author_id)
return _compute_career_metrics(publication_years)
@@ -387,13 +382,13 @@ def _build_papers(works: list) -> list:
return papers
async def get_data_for_bio(author_id: str) -> Optional[dict]:
def get_data_for_bio(author_id: str) -> Optional[dict]:
display_name = await _fetch_author_display_name(author_id)
display_name = _fetch_author_display_name(author_id)
if display_name is None:
return None
works, top_topics = await _fetch_works_and_topics(author_id)
works, top_topics = _fetch_works_and_topics(author_id)
papers = _build_papers(works)
author_data = {
@@ -404,9 +399,9 @@ async def get_data_for_bio(author_id: str) -> Optional[dict]:
return author_data
async def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> str:
def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> str:
start_time = time.time()
author_data = await get_data_for_bio(author_id)
author_data = get_data_for_bio(author_id)
if author_data is None:
return "No person found."
@@ -435,23 +430,27 @@ async def generate_person_bio(author_id: str, include: Optional[set[str]] = None
return bio
async def get_person_by_id(
def get_person_by_id(
author_id: str, include: Optional[str] = None
) -> CustomAuthorsListResponse:
source = include.split(",") if include else None
try:
hit = await elasticsearch.get(
hit = elasticsearch.get(
index="openalex-authors",
doc_id=author_id,
source=source,
)
except NotFoundException as e:
raise NotFoundException(f"Person with id {author_id} not found") from e
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)}")
author = util.get_persons_data(hit)
start_time = time.time()
career_metrics = await get_career_metrics_for_author(author_id)
career_metrics = get_career_metrics_for_author(author_id)
elapsed_time = time.time() - start_time
logger.info(
@@ -466,14 +465,14 @@ async def get_person_by_id(
return CustomAuthorsListResponse(results=[custom_author])
async def search_persons_by_name(
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 BadRequestException("name must be provided")
raise HTTPException(status_code=400, detail="name must be provided")
search_query = {
"bool": {
"should": [
@@ -496,7 +495,7 @@ async def search_persons_by_name(
}
}
try:
response = await elasticsearch.search(
response = elasticsearch.search(
index="openalex-authors",
query=search_query,
offset=page_offset,
@@ -505,8 +504,10 @@ async def search_persons_by_name(
track_total_hits=True,
)
except ElasticsearchException as e:
raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
)
total_count = response.get("hits", {}).get("total", {}).get("value", 0)
hits = response.get("hits", {}).get("hits", [])
@@ -517,11 +518,11 @@ async def search_persons_by_name(
)
async def search_persons_autocomplete(
def search_persons_autocomplete(
author_name: str, limit: Optional[int] = 5, include: Optional[str] = None
) -> AuthorsListResponse:
if not author_name:
raise BadRequestException("name must be provided")
raise HTTPException(status_code=400, detail="name must be provided")
search_query = {
"function_score": {
"query": {
@@ -554,9 +555,11 @@ async def search_persons_autocomplete(
"collapse": collapse,
}
try:
response = await elasticsearch.search(index="openalex-authors", body=body)
except ElasticsearchException as e:
raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e
response = elasticsearch.search(index="openalex-authors", body=body)
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
)
hits = response.get("hits", {}).get("hits", [])
@@ -584,7 +587,7 @@ async def search_persons_autocomplete(
return AuthorsListResponse(results=persons)
async def search_persons_by_institution(
def search_persons_by_institution(
institution_name: str,
limit: Optional[int] = 10,
page_offset: Optional[int] = 0,
@@ -592,7 +595,7 @@ async def search_persons_by_institution(
) -> AuthorsListResponse:
if not institution_name:
raise BadRequestException("institution_name must be provided")
raise HTTPException(status_code=400, detail="institution_name must be provided")
search_query = {
"nested": {
@@ -611,7 +614,7 @@ async def search_persons_by_institution(
}
}
try:
response = await elasticsearch.search(
response = elasticsearch.search(
index="openalex-authors",
query=search_query,
source=include.split(",") if include else True,
@@ -621,8 +624,10 @@ async def search_persons_by_institution(
track_total_hits=True,
)
except ElasticsearchException as e:
raise ElasticsearchException(f"Elasticsearch search failed: {str(e)}") from e
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Elasticsearch search failed: {str(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]
@@ -674,7 +679,7 @@ def _enrich_author_data(author_data) -> Optional[CustomAuthor]:
return author
async def advanced_search_persons(
def advanced_search_persons(
query: Optional[str] = None,
institution_name: Optional[str] = None,
sort_by: Optional[str] = None,
@@ -702,20 +707,39 @@ async def advanced_search_persons(
filter_mode=filter_mode,
filter_year=filter_year,
)
response_dict = await elasticsearch.search(
response_dict = elasticsearch.search(
index=INDEX_NAME,
body=query_body,
)
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 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 ElasticsearchException as e:
except Exception as e:
logger.error(f"Elasticsearch search failed: {str(e)}")
raise
raise HTTPException(
status_code=500, detail=f"Elasticsearch search failed: {str(e)}"
)
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 = []
@@ -725,7 +749,7 @@ async def advanced_search_persons(
if custom_author:
if include_career_metrics:
start_time = time.time()
custom_author.career_metrics = await get_career_metrics_for_author(
custom_author.career_metrics = get_career_metrics_for_author(
custom_author.id
)
elapsed_time = time.time() - start_time
+21 -23
View File
@@ -29,7 +29,7 @@ router = APIRouter(
summary="Searches for persons by ID or name.",
response_model_exclude_none=True,
)
async def search_persons(
def search_persons(
author_id: Annotated[
str, Query(description="OpenAlex author ID (e.g., A5093075883)")
] = None,
@@ -53,7 +53,7 @@ async def search_persons(
if include
else None
)
return await logic.search_persons(author_id, query)
return logic.search_persons(author_id, query)
@router.get(
@@ -62,7 +62,7 @@ async def search_persons(
response_model=model.PersonBio,
summary="Generates a bio for a person by author ID.",
)
async def generate_person_bio(
def generate_person_bio(
author_id: Annotated[
str, Query(description="OpenAlex author ID (e.g., A5093075883)")
],
@@ -79,7 +79,7 @@ async def generate_person_bio(
if include
else None
)
bio = await logic.generate_person_bio(author_id, include_set)
bio = logic.generate_person_bio(author_id, include_set)
return model.PersonBio(bio=bio)
@router.get(
@@ -89,7 +89,7 @@ async def generate_person_bio(
summary="Searches for person by ID.",
tags=["Persons"],
)
async def get_person_by_id(
def get_person_by_id(
id: Annotated[
str, Path(description="OpenAlex author ID", examples=["A5093075883"])
],
@@ -104,7 +104,7 @@ async def get_person_by_id(
),
] = None,
):
return await logic.get_person_by_id(author_id=id, include=include)
return logic.get_person_by_id(author_id=id, include=include)
@router.get(
@@ -114,7 +114,7 @@ async def get_person_by_id(
summary="Searches for person by name.",
tags=["Persons"],
)
async def search_persons_by_name(
def search_persons_by_name(
author_name: Annotated[str, Query(description="Authors name (e.g., Arman Arzani)")],
include: Annotated[
Optional[str],
@@ -129,25 +129,24 @@ async 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 await logic.search_persons_by_name(author_name=author_name, include=include, page_offset=page_offset, limit=limit)
return 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'])
async def search_persons_autocomplete(
tags=[ 'Persons' ])
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 await 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 logic.search_persons_autocomplete(author_name=author_name,include=include)
@router.get(
@@ -157,7 +156,7 @@ async def search_persons_autocomplete(
summary="Searches for persons by institution name.",
tags=["Persons"],
)
async def search_persons_by_institution(
def search_persons_by_institution(
institution_name: Annotated[
str, Query(description="Institution name (e.g., MIT, Oxford University)")
],
@@ -174,8 +173,7 @@ async 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 await logic.search_persons_by_institution(institution_name, include=include, page_offset=page_offset, limit=limit)
return logic.search_persons_by_institution(institution_name, include=include,page_offset=page_offset,limit=limit)
@router.get(
"/persons/search-list",
@@ -185,7 +183,7 @@ async def search_persons_by_institution(
response_model_exclude_none=True,
tags=["Persons"],
)
async def search_persons_list(
def search_persons_list(
query: Annotated[
Optional[str], Query(description="Search query (e.g., Arman AND Arzani)")
] = None,
@@ -229,7 +227,7 @@ async def search_persons_list(
if include
else None
)
return await logic.advanced_search_persons(
return logic.advanced_search_persons(
query=query,
institution_name=institution_name,
sort_by=sort_by,
@@ -1,5 +1,5 @@
import logging
import asyncio
from concurrent.futures import ThreadPoolExecutor, as_completed
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},
]
async def get_enriched_cordis_project_by_id(
def get_enriched_cordis_project_by_id(
project_id: str,
) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]:
"""
@@ -102,7 +102,7 @@ async def get_enriched_cordis_project_by_id(
query = {"bool": {"filter": [{"term": {"id": project_id}}]}}
response = await elasticsearch.search(
response = elasticsearch.search(
query=query,
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
cluster=ESCluster.INSE,
@@ -131,7 +131,7 @@ async def get_enriched_cordis_project_by_id(
logger.warning(f"Unknown programme type for index: {index}")
return CordisEuProject.model_validate(source)
return await enricher(project_id, source)
return enricher(project_id, source)
# helpers
def _determine_program_type_from_index(index: str) -> str:
@@ -146,9 +146,10 @@ def _determine_program_type_from_index(index: str) -> str:
return "unknown"
async def _fetch_related_entities_parallel(
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.
@@ -156,35 +157,35 @@ async 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.
"""
async def _fetch_one(config: Dict[str, Any]):
entities = await _fetch_related_entities(
def _fetch_one(config: Dict[str, Any]):
entities = _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]] = {}
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
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] = []
return results
async def _fetch_related_entities(
def _fetch_related_entities(
project_ids: List[str],
index_pattern: str,
model_class: Any,
@@ -203,7 +204,7 @@ async def _fetch_related_entities(
query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}}
try:
response = await elasticsearch.search(
response = elasticsearch.search(
query=query,
index=index_pattern,
cluster=ESCluster.INSE,
@@ -233,7 +234,7 @@ async def _fetch_related_entities(
return grouped
async def _enrich_fp7_project(
def _enrich_fp7_project(
project_id: str,
project_source: Dict[str, Any],
) -> Optional[Fp7ProjectDetails]:
@@ -244,12 +245,12 @@ async def _enrich_fp7_project(
logger.error(f"Failed to validate FP7 project {project_id}: {e}")
return None
related = await _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS)
related = _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS)
return Fp7ProjectDetails.from_project_with_relations(project=project, **related)
async def _enrich_h2020_project(
def _enrich_h2020_project(
project_id: str,
project_source: Dict[str, Any],
) -> Optional[H2020ProjectDetails]:
@@ -260,12 +261,12 @@ async def _enrich_h2020_project(
logger.error(f"Failed to validate H2020 project {project_id}: {e}")
return None
related = await _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS)
related = _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS)
return H2020ProjectDetails.from_project_with_relations(project=project, **related)
async def _enrich_heu_project(
def _enrich_heu_project(
project_id: str,
project_source: Dict[str, Any],
) -> Optional[HEUProjectDetails]:
@@ -276,6 +277,6 @@ async def _enrich_heu_project(
logger.error(f"Failed to validate Horizon Europe project {project_id}: {e}")
return None
related = await _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS)
related = _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
async def search_bund_projects(
def search_bund_projects(
filter_properties: ProjectsFilteringProperties,
institution_names: List[str] = [],
) -> BundProjectPage:
@@ -160,7 +160,7 @@ async def search_bund_projects(
}
]
response = await elasticsearch.search(
response = 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)
async def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails]:
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 @@ async 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 = await elasticsearch.search(
response = elasticsearch.search(
index=ESIndex.PROJECTS_BUND_V1,
query=query,
size=1,
@@ -224,7 +224,7 @@ async def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails
# EU
async def get_eu_organization_project_contributions(
def get_eu_organization_project_contributions(
organization_names: List[str],
projects_filtering_properties: ProjectsFilteringProperties,
) -> EuOrganizationProjectSummaryPage:
@@ -241,11 +241,11 @@ async 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 = await get_eu_organization_contributions(
organization_project_contributions = get_eu_organization_contributions(
organization_names=organization_names,
)
total_projects, projects = await get_eu_organization_projects(
total_projects, projects = get_eu_organization_projects(
project_contributions=list(organization_project_contributions.values()),
projects_filtering_properties=projects_filtering_properties,
)
@@ -271,7 +271,7 @@ async def get_eu_organization_project_contributions(
)
async def get_eu_organization_contributions(
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 @@ async def get_eu_organization_contributions(
}
}
response = await elasticsearch.search(
response = 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
async def get_eu_organization_projects(
def get_eu_organization_projects(
project_contributions: List[EuOrganizationShort],
projects_filtering_properties: ProjectsFilteringProperties,
) -> Tuple[int, Dict[str, EuProjectShort]]:
@@ -388,7 +388,7 @@ async def get_eu_organization_projects(
# Project contributions have been filtered before based on ecContribution
if projects_filtering_properties.sort_by == ProjectsSortBy.FUNDING_AMOUNT:
response = await elasticsearch.search(
response = elasticsearch.search(
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
cluster=ESCluster.INSE,
source=source,
@@ -396,7 +396,7 @@ async def get_eu_organization_projects(
size=10000,
)
else:
response = await elasticsearch.search(
response = 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
async def get_cordis_eu_publications_by_dois(dois: List[str]):
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 @@ async 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 = await elasticsearch.search(
response = elasticsearch.search(
query=query,
index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
cluster=ESCluster.INSE,
@@ -519,7 +519,7 @@ async def get_cordis_eu_publications_by_dois(dois: List[str]):
return response
async def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]:
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 @@ async def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]:
Returns:
List[str]: The list of project IDs.
"""
response = await get_cordis_eu_publications_by_dois(dois=dois)
response = 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 @@ async def get_cordis_eu_project_ids_by_dois(dois: List[str]) -> List[str]:
return list(project_ids)
async def get_cordis_eu_projects_by_project_ids(
def get_cordis_eu_projects_by_project_ids(
project_ids: List[str],
) -> CordisEuProjectPage:
query = {"bool": {"filter": [{"terms": {"id": project_ids}}]}}
response = await elasticsearch.search(
response = elasticsearch.search(
query=query,
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
cluster=ESCluster.INSE,
@@ -561,7 +561,7 @@ async def get_cordis_eu_projects_by_project_ids(
)
async def get_eu_cordis_projects_by_id(
def get_eu_cordis_projects_by_id(
project_id: str,
) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]:
"""
@@ -573,14 +573,14 @@ async def get_eu_cordis_projects_by_id(
Returns:
The enriched project details, or None if not found
"""
enriched_project = await get_enriched_cordis_project_by_id(
enriched_project = get_enriched_cordis_project_by_id(
project_id=project_id
)
return enriched_project
# DFG
async def search_dfg_projects(
def search_dfg_projects(
page: int,
size: int,
names: Optional[List[str]] = None,
@@ -750,7 +750,7 @@ async def search_dfg_projects(
body["sort"] = [sort_config]
response = await elasticsearch.search(
response = 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)
async def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
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 @@ async def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
"""
query = {"ids": {"values": [project_id]}}
response = await elasticsearch.search(
response = elasticsearch.search(
index=ESIndex.PROJECTS_DFG_ALL,
query=query,
size=1,
@@ -804,7 +804,7 @@ async def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
# All
async def search_all_projects(
def search_all_projects(
projects_filtering_properties: ProjectsFilteringProperties,
selected_project_types: Optional[Set[ProjectType]] = None,
) -> FundingProjectPage:
@@ -882,7 +882,7 @@ async def search_all_projects(
size = projects_filtering_properties.size
page = projects_filtering_properties.page
offset = page * size
response = await elasticsearch.search(
response = elasticsearch.search(
index=index,
size=size,
offset=offset,
+16 -15
View File
@@ -51,13 +51,13 @@ router = APIRouter(prefix="/api/projects", tags=[Tags.PROJECTS])
},
response_model_by_alias=False,
)
async def get_eu_projects_for_author(
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 await projects_service.search_cordis_eu_projects_for_author_id(
return 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 await projects_service.search_bund_projects(
return 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,
)
async def get_single_dfg_project(
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 await projects_service.get_single_dfg_project(
return projects_service.get_single_dfg_project(
project_id=id,
)
@@ -128,11 +128,11 @@ async def get_single_dfg_project(
},
response_model_by_alias=False,
)
async def get_single_bund_project(
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 await projects_service.get_single_bund_project(
return projects_service.get_single_bund_project(
project_id=id,
)
@@ -157,7 +157,9 @@ async def get_single_bund_project(
}
},
)
async def get_single_eu_cordis_project(
def get_single_eu_cordis_project(
id: Annotated[str, Path(description="The ID of the EU Cordis project to retrieve.")],
) -> EuCordisProjectResponse:
"""
@@ -168,7 +170,7 @@ async def get_single_eu_cordis_project(
try:
# Get the project from the service
project = await projects_service.get_single_eu_cordis_project(project_id=id)
project = projects_service.get_single_eu_cordis_project(project_id=id)
# Check if project exists
if project is None:
@@ -214,7 +216,6 @@ async 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.",
@@ -229,7 +230,7 @@ async def get_single_eu_cordis_project(
},
response_model_by_alias=False,
)
async def get_institution_bund_projects_funding_over_time(
def get_institution_bund_projects_funding_over_time(
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
@@ -237,7 +238,7 @@ async def get_institution_bund_projects_funding_over_time(
str, Query(description="The institution ID to filter by.")
],
) -> InstitutionFunderSummary:
return await projects_service.get_institution_bund_projects_funding_over_time(
return projects_service.get_institution_bund_projects_funding_over_time(
institutions_search_client=institutions_search_client,
raw_oa_institution_id=raw_oa_institution_id,
)
@@ -266,7 +267,7 @@ async def search_cordis_eu_projects(
Body(description="The filtering properties for the projects search."),
],
) -> EuOrganizationProjectSummaryPage:
return await projects_service.search_cordis_eu_projects(
return projects_service.search_cordis_eu_projects(
institutions_search_client=institutions_search_client,
projects_filtering_properties=projects_filtering_properties,
)
@@ -358,7 +359,7 @@ async def get_dfg_projects(
},
response_model_by_alias=False,
)
async def search_projects(
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[
@@ -377,7 +378,7 @@ async def search_projects(
SortDirection, Query(description="The sort direction (asc or desc).")
] = SortDirection.ASC,
) -> FundingProjectPage:
return await projects_service.search_all_projects(
return projects_service.search_all_projects(
page=page,
size=size,
selected_project_types=selected_project_types,
+25 -27
View File
@@ -35,7 +35,7 @@ from typing import Union
logger = logging.getLogger(__name__)
async def search_all_projects(
def search_all_projects(
page: int,
size: int,
sort_by: ProjectsSortBy,
@@ -43,7 +43,7 @@ async def search_all_projects(
selected_project_types: Optional[Set[ProjectType]] = None,
title: Optional[str] = None,
) -> FundingProjectPage:
return await projects_search_client.search_all_projects(
return 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 @@ async def search_all_projects(
)
async def search_bund_projects(
def search_bund_projects(
institutions_search_client: InstitutionsSearchClient,
filtering_properties: ProjectsFilteringProperties,
) -> BundProjectPage:
@@ -69,13 +69,13 @@ async def search_bund_projects(
f"search_bund_projects called with filtering_properties: {filtering_properties}"
)
return await get_bund_projects_by_institution_id(
return get_bund_projects_by_institution_id(
institutions_search_client=institutions_search_client,
filtering_properties=filtering_properties,
)
async def get_bund_projects_by_institution_id(
def get_bund_projects_by_institution_id(
institutions_search_client: InstitutionsSearchClient,
filtering_properties: ProjectsFilteringProperties,
) -> BundProjectPage:
@@ -93,7 +93,7 @@ async 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 = await projects_search_client.search_bund_projects(
response = projects_search_client.search_bund_projects(
institution_names=institution_aliases,
filter_properties=filtering_properties,
)
@@ -101,7 +101,7 @@ async def get_bund_projects_by_institution_id(
return response
async def search_cordis_eu_projects(
def search_cordis_eu_projects(
institutions_search_client: InstitutionsSearchClient,
projects_filtering_properties: ProjectsFilteringProperties,
) -> EuOrganizationProjectSummaryPage:
@@ -110,13 +110,13 @@ async def search_cordis_eu_projects(
f"Invalid project type: {projects_filtering_properties.project_type}. Expected 'eu'."
)
return await get_cordis_eu_projects_by_institution_id(
return get_cordis_eu_projects_by_institution_id(
institutions_search_client=institutions_search_client,
projects_filtering_properties=projects_filtering_properties,
)
async def get_cordis_eu_projects_by_institution_id(
def get_cordis_eu_projects_by_institution_id(
institutions_search_client: InstitutionsSearchClient,
projects_filtering_properties: ProjectsFilteringProperties,
) -> EuOrganizationProjectSummaryPage:
@@ -137,7 +137,7 @@ async 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 = await get_eu_organization_project_contributions(
page = 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 = await get_author_name_by_id(author_id)
name = 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 = await projects_search_client.search_dfg_projects(
response = 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 = await get_eu_organization_project_contributions(
page = 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(
)
async def get_institution_bund_projects_funding_over_time(
def get_institution_bund_projects_funding_over_time(
institutions_search_client: InstitutionsSearchClient,
raw_oa_institution_id: str,
) -> InstitutionFunderSummary:
@@ -219,7 +219,7 @@ async def get_institution_bund_projects_funding_over_time(
logger.debug(
f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}"
)
response = await projects_search_client.search_bund_projects(
response = projects_search_client.search_bund_projects(
filter_properties=ProjectsFilteringProperties(
project_type=ProjectType.BUND,
page=0,
@@ -305,40 +305,38 @@ def _calculate_funding_over_time(
)
async def get_single_dfg_project(
def get_single_dfg_project(
project_id: str,
) -> DfgProjectDetails:
logger.debug(f"Fetching single DFG project for id={project_id}")
project = await projects_search_client.get_dfg_project_by_id(project_id)
project = 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
async def get_single_bund_project(
def get_single_bund_project(
project_id: str,
) -> BundProjectDetails:
logger.debug(f"Fetching single BUND project for id={project_id}")
project = await projects_search_client.get_bund_project_by_id(project_id)
project = 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
async def get_single_eu_cordis_project(
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 = await projects_search_client.get_eu_cordis_projects_by_id(project_id)
project = 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
async def search_cordis_eu_projects_for_author_id(
def search_cordis_eu_projects_for_author_id(
raw_oa_author_id: str,
) -> CordisEuProjectPage:
@@ -347,17 +345,17 @@ async 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 = await get_publication_dois_of_author(raw_oa_author_id=raw_oa_author_id)
dois = 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 = await projects_search_client.get_cordis_eu_project_ids_by_dois(dois=dois)
project_ids = 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 = await projects_search_client.get_cordis_eu_projects_by_project_ids(
funding_project_page = projects_search_client.get_cordis_eu_projects_by_project_ids(
project_ids=project_ids
)
+32 -15
View File
@@ -8,8 +8,10 @@ from copy import deepcopy
from typing import Any
import httpx
from fastapi import HTTPException
from pydantic import ValidationError
from inse.exceptions import UpstreamAPIException, BadRequestException, ElasticsearchException
from starlette.status import HTTP_400_BAD_REQUEST
from starlette.status import HTTP_502_BAD_GATEWAY
from inse.models.openalex.autocomplete_response import AutocompleteResponse
from inse.models.openalex.autocomplete_response_meta import AutocompleteResponseMeta
@@ -36,7 +38,10 @@ async def list_topics(
client: OpenAlexTopicsClient | None = None,
) -> TopicsListResponse:
if sample is not None and (sort or page not in (None, 1)):
raise BadRequestException("sample cannot be combined with sort or page.")
raise HTTPException(
status_code=HTTP_400_BAD_REQUEST,
detail="sample cannot be combined with sort or page.",
)
openalex_client = client or OpenAlexTopicsClient()
@@ -61,12 +66,12 @@ async def list_topics(
except ValueError:
if exc.response.text:
detail = exc.response.text
raise UpstreamAPIException(message=detail, status_code=status_code) from exc
raise HTTPException(status_code=status_code, detail=detail) from exc
except httpx.HTTPError as exc:
logger.exception("OpenAlex topics request failed.")
raise UpstreamAPIException(
message="OpenAlex topics request failed.",
status_code=502,
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex topics request failed.",
) from exc
try:
@@ -74,9 +79,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 UpstreamAPIException(
message="OpenAlex topics response could not be parsed.",
status_code=502,
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex topics response could not be parsed.",
) from exc
@@ -277,7 +282,10 @@ async def vector_search_topics(
except Exception as exc:
logger.exception("Failed to load elasticsearch integration.")
raise ElasticsearchException(f"Failed to load elasticsearch integration: {exc}") from exc
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail=f"Failed to load elasticsearch integration: {exc}"
)
# 1. Vectorize query
try:
@@ -285,7 +293,10 @@ async def vector_search_topics(
query_vector = model.encode(query).tolist()
except Exception as exc:
logger.exception("Failed to encode query text.")
raise ElasticsearchException(f"Failed to encode query text: {exc}") from exc
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail=f"Failed to encode query text: {exc}"
)
# 2. Query Elasticsearch using standard Bool Should hybrid search
should_clauses = []
@@ -346,14 +357,17 @@ async def vector_search_topics(
}
try:
raw_results = await elasticsearch.search(
raw_results = elasticsearch.search(
index="topicvectors",
body=body,
cluster="nes"
)
except Exception as exc:
logger.exception("Elasticsearch vector search failed with unexpected error.")
raise ElasticsearchException(f"Unexpected vector search failure: {exc}") from exc
logger.exception("Elasticsearch vector search failed.")
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail=f"Elasticsearch vector search failed: {exc}"
)
# 3. Format result
hits = raw_results.get("hits", {}).get("hits", [])
@@ -375,5 +389,8 @@ 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 ElasticsearchException(f"Vector search response could not be parsed: {exc}") from exc
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="Vector search response could not be parsed.",
) from exc
+4 -2
View File
@@ -1,6 +1,6 @@
import httpx
import pytest
from inse.exceptions import BadRequestException
from fastapi import HTTPException
from inse.topics import logic
from inse.topics.search_client import OpenAlexTopicsClient
@@ -76,9 +76,11 @@ 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(BadRequestException) as exc_info:
with pytest.raises(HTTPException) 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 = await elasticsearch.search(
res = elasticsearch.search(
index="openalex-institutions",
query=query,
size=10,
+3 -2
View File
@@ -8,14 +8,15 @@ from typing import Optional
from typing import TypeVar
from inse.models.openalex import Author
from . import model
from inse.exceptions import NotFoundException
from fastapi import HTTPException
from starlette.status import HTTP_404_NOT_FOUND
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 NotFoundException("Not found.")
raise HTTPException(HTTP_404_NOT_FOUND)
else:
return value
+75 -47
View File
@@ -9,8 +9,11 @@ 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
@@ -21,7 +24,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 inse.exceptions import MissingApiKeyError, ElasticsearchException, UpstreamAPIException
from .search_client import MissingApiKeyError
from .search_client import OpenAlexWorksSearchClient
logger = logging.getLogger(__name__)
@@ -119,10 +122,10 @@ async def get_primary_topic_counts(
author_id: str,
client: OpenAlexWorksSearchClient | None = None,
) -> List[TopicCount]:
topic_counts = await _get_primary_topic_counts_from_es(author_id)
topic_counts = _get_primary_topic_counts_from_es(author_id)
topic_ids = [item["id"] for item in topic_counts if item["id"]]
details = await _get_topic_details(topic_ids)
details = _get_topic_details(topic_ids)
result = []
@@ -145,7 +148,7 @@ async def get_primary_topic_counts(
return result
async def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
indexed_author_id = f"https://openalex.org/{author_id.strip()}"
@@ -171,13 +174,16 @@ async def _get_primary_topic_counts_from_es(author_id: str) -> list[dict]:
}
try:
response = await elasticsearch.search(
response = elasticsearch.search(
index=config.settings.openalex_works_search_index,
body=body,
)
except ElasticsearchException as exc:
except httpx.HTTPError as exc:
logger.exception("OpenAlex primary topic aggregation request failed.")
raise
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex works search request failed.",
) from exc
aggregations = response.get("aggregations", {})
buckets = aggregations.get("primary_topics", {}).get("buckets", [])
@@ -206,18 +212,18 @@ async def get_work(
return elements[0]
async def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
if not topic_ids:
return {}
try:
response = await elasticsearch.search(
response = elasticsearch.search(
index="openalex-topics",
query={"terms": {"id": topic_ids}},
source=TOPIC_DETAIL_SOURCE_FIELDS,
size=len(topic_ids),
)
except Exception:
except httpx.HTTPError:
logger.exception("Could not load topic details from Elasticsearch.")
return {}
@@ -236,7 +242,7 @@ async def _get_topic_details(topic_ids: List[str]) -> dict[str, dict]:
"domain": _extract_topic_hierarchy_item(source, "domain"),
}
await _enrich_topic_hierarchy_descriptions(details)
_enrich_topic_hierarchy_descriptions(details)
return details
@@ -254,7 +260,7 @@ def _extract_topic_hierarchy_item(source: dict, key: str) -> dict[str, str | Non
}
async def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None:
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")
@@ -262,7 +268,7 @@ async def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None
if item.get(hierarchy_key, {}).get("id")
}
descriptions = await _get_topic_hierarchy_descriptions(index, list(hierarchy_ids))
descriptions = _get_topic_hierarchy_descriptions(index, list(hierarchy_ids))
for item in details.values():
hierarchy_item = item.get(hierarchy_key) or {}
@@ -272,7 +278,7 @@ async def _enrich_topic_hierarchy_descriptions(details: dict[str, dict]) -> None
hierarchy_item["description"] = descriptions[hierarchy_id]
async def _get_topic_hierarchy_descriptions(
def _get_topic_hierarchy_descriptions(
index: str,
hierarchy_ids: list[str],
) -> dict[str, str | None]:
@@ -280,13 +286,13 @@ async def _get_topic_hierarchy_descriptions(
return {}
try:
response = await elasticsearch.search(
response = elasticsearch.search(
index=index,
query={"terms": {"id": hierarchy_ids}},
source=TOPIC_HIERARCHY_DESCRIPTION_SOURCE_FIELDS,
size=len(hierarchy_ids),
)
except Exception:
except httpx.HTTPError:
logger.exception("Could not load topic hierarchy details from %s.", index)
return {}
@@ -427,7 +433,7 @@ async def get_topics_by_time_by_author(
client=client,
)
return await _get_topics_by_time_by_author_from_es(
return _get_topics_by_time_by_author_from_es(
author_id,
max_topics_per_year=max_topics_per_year,
target_publications=target_publications,
@@ -515,7 +521,7 @@ async def _get_topics_by_time_by_author_from_work_pages(
if topic["id"]:
topic_ids.add(topic["id"])
topic_details = await _get_topic_details(list(topic_ids))
topic_details = _get_topic_details(list(topic_ids))
elements = []
@@ -574,13 +580,13 @@ async def _get_topics_by_time_by_author_from_work_pages(
)
async def _get_topics_by_time_by_author_from_es(
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 = await _get_publication_year_counts_from_es(author_id)
year_buckets, total_publications = _get_publication_year_counts_from_es(author_id)
selected_years, is_limited = _select_complete_timeline_years(
year_buckets,
target_publications=target_publications,
@@ -596,13 +602,13 @@ async def _get_topics_by_time_by_author_from_es(
total_publications=total_publications,
)
year_topic_buckets = await _get_timeline_topic_counts_from_es(
year_topic_buckets = _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 = await _get_topic_details(list(topic_ids))
topic_details = _get_topic_details(list(topic_ids))
elements = _build_timeline_elements_from_aggregations(
year_topic_buckets,
@@ -619,7 +625,7 @@ async def _get_topics_by_time_by_author_from_es(
)
async def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], int]:
def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dict], int]:
body = {
"size": 0,
"track_total_hits": True,
@@ -636,18 +642,21 @@ async def _get_publication_year_counts_from_es(author_id: str) -> tuple[list[dic
}
try:
response = await elasticsearch.search(
response = elasticsearch.search(
index=config.settings.openalex_works_search_index,
body=body,
)
except ElasticsearchException as exc:
except httpx.HTTPError as exc:
logger.exception("OpenAlex publication year aggregation request failed.")
raise
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex works search request failed.",
) from exc
return _parse_year_count_buckets(response), _parse_total_hits(response)
async def _get_timeline_topic_counts_from_es(
def _get_timeline_topic_counts_from_es(
author_id: str,
years: list[int],
max_topics_per_year: int,
@@ -704,13 +713,16 @@ async def _get_timeline_topic_counts_from_es(
}
try:
response = await elasticsearch.search(
response = elasticsearch.search(
index=config.settings.openalex_works_search_index,
body=body,
)
except ElasticsearchException as exc:
except httpx.HTTPError as exc:
logger.exception("OpenAlex timeline topic aggregation request failed.")
raise
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex works search request failed.",
) from exc
return response.get("aggregations", {}).get("by_year", {}).get("buckets", [])
@@ -871,16 +883,29 @@ async def _search_author_works_data(
institution_id: list[str] | None = None,
topic_id: list[str] | None = None,
) -> dict:
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,
)
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
def _parse_full_work_search_response(data: dict) -> tuple[list[Work], int]:
@@ -921,15 +946,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 UpstreamAPIException(
message="OpenAlex works search response could not be parsed.",
status_code=502,
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="OpenAlex works search response could not be parsed.",
) from exc
return elements, total
async def get_publication_dois_of_author(
def get_publication_dois_of_author(
raw_oa_author_id: str,
) -> List[str]:
query = {
@@ -951,16 +976,19 @@ async def get_publication_dois_of_author(
}
try:
response = await elasticsearch.search(
response = elasticsearch.search(
index="openalex-works",
source=["doi"],
size=10000,
query=query,
cluster="nes",
)
except ElasticsearchException as exc:
except httpx.HTTPError as exc:
logger.exception("Request for publication DOIs of author failed.")
raise
raise HTTPException(
status_code=HTTP_502_BAD_GATEWAY,
detail="Request for publication DOIs of author failed.",
) from exc
dois = []
for hit in response.get("hits", {}).get("hits", []):
+47 -33
View File
@@ -11,7 +11,8 @@ import urllib
from .. import config
from inse.integrations import elasticsearch
from inse.model import ESCluster, ESIndex
from inse.exceptions import MissingApiKeyError
class MissingApiKeyError(Exception):
pass
logger = logging.getLogger(__name__)
@@ -140,49 +141,62 @@ class OpenAlexWorksSearchClient:
if not self.api_key:
raise MissingApiKeyError("OpenAlex works Elasticsearch API key is not configured.")
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 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()
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
}
}
}
}
response = await elasticsearch.search(index=f"{ESIndex.OPENALEX_WORKS}*",body=body,cluster=ESCluster.NES,size=1)
return response
}
print(body)
response = elasticsearch.search(index=f'{ESIndex.OPENALEX_WORKS}*',body=body,cluster=ESCluster.NES,size=1)
return response
async def search_for_work_by_title(
self,
@@ -206,6 +220,6 @@ class OpenAlexWorksSearchClient:
{"cited_by_count": {"order": "desc", "missing": "_last"}},
],
}
response = await elasticsearch.search(index=f'{ESIndex.OPENALEX_WORKS}*',body=body,cluster=ESCluster.NES,size=1)
response = 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.exceptions import MissingApiKeyError
from inse.works.search_client import MissingApiKeyError
from inse.works.search_client import OpenAlexWorksSearchClient
@@ -152,47 +152,37 @@ 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():
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"],
def handler(request: httpx.Request) -> httpx.Response:
body = json.loads(request.content)
assert body["query"]["bool"]["must"][1]["nested"]["path"] == (
"authorships.institutions"
)
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():
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")
def handler(request: httpx.Request) -> httpx.Response:
body = json.loads(request.content)
assert body["query"]["bool"]["filter"] == [
{
"bool": {
@@ -217,55 +207,61 @@ 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():
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")
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": []}})
result = await client.search_author_works("A5023888391", page=1, size=20)
client = OpenAlexWorksSearchClient(
base_url="https://project.nes.uni-due.de/elastic",
index="openalex-works",
api_key="test-key",
transport=httpx.MockTransport(handler),
)
assert result == {"hits": {"total": {"value": 0}, "hits": []}}
result = await client.search_author_works("A5023888391", page=1, size=20)
assert result == {"hits": {"total": {"value": 0}, "hits": []}}
@pytest.mark.anyio
async def test_search_work_filters_by_work_id():
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")
def handler(request: httpx.Request) -> httpx.Response:
body = json.loads(request.content)
assert body == {
"query": {
"bool": {
"should": [
{
"term": {
"_id": {
"value": "W2741809807",
"boost": 5
}
}
},
{
"term": {
"doi": {
"value": "https://doi.org/w2741809807",
"boost": 3
}
}
}
],
"minimum_should_match": 1
}
}
"size": 1,
"query": {"term": {"id": "https://openalex.org/W2741809807"}},
}
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
+62
View File
@@ -178,6 +178,36 @@ 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"
@@ -769,6 +799,18 @@ 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"
@@ -1085,6 +1127,7 @@ source = { virtual = "." }
dependencies = [
{ name = "cryptography" },
{ name = "dotenv" },
{ name = "elasticsearch" },
{ name = "fastapi" },
{ name = "httpx" },
{ name = "openai" },
@@ -1105,6 +1148,7 @@ 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" },
@@ -1138,6 +1182,15 @@ 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"
@@ -1368,6 +1421,15 @@ 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"
+3 -3
View File
@@ -12,11 +12,11 @@
"ngVersion": "21.2.14",
"providedInRoot": true,
"serviceSuffix": "Service",
"withInterfaces": true,
"withInterfaces": false,
"enumPropertyNaming": "original",
"fileNaming": "kebab-case"
"fileNaming": "camelCase"
}
}
}
}
}
}
+10
View File
@@ -19,6 +19,7 @@
"@angular/platform-browser-dynamic": "^21.2.14",
"@angular/router": "^21.2.14",
"echarts": "^6.1.0",
"echarts-wordcloud": "^2.1.0",
"ngx-echarts": "^21.0.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
@@ -6087,6 +6088,15 @@
"zrender": "6.1.0"
}
},
"node_modules/echarts-wordcloud": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/echarts-wordcloud/-/echarts-wordcloud-2.1.0.tgz",
"integrity": "sha512-Kt1JmbcROgb+3IMI48KZECK2AP5lG6bSsOEs+AsuwaWJxQom31RTNd6NFYI01E/YaI1PFZeueaupjlmzSQasjQ==",
"license": "ISC",
"peerDependencies": {
"echarts": "^5.0.1"
}
},
"node_modules/echarts/node_modules/tslib": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.0.tgz",
+1
View File
@@ -22,6 +22,7 @@
"@angular/platform-browser-dynamic": "^21.2.14",
"@angular/router": "^21.2.14",
"echarts": "^6.1.0",
"echarts-wordcloud": "^2.1.0",
"ngx-echarts": "^21.0.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
+419 -431
View File
@@ -1,431 +1,419 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import {
HttpClient,
HttpHeaders,
HttpParams,
HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore
import { AllPatentsResponse } from '../model/allPatentsResponse';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
import { PatentEntry } from '../model/patentEntry';
// @ts-ignore
import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
@Injectable({
providedIn: 'root',
})
export class PatentsService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
/**
* Get all patents with pagination and search.
* @endpoint get /api/inse-service/patents
* @param page
* @param size
* @param search
* @param source
* @param sortBy
* @param sortDirection
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getAllPatents(
page?: number,
size?: number,
search?: string,
source?: string,
sortBy?: string,
sortDirection?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<AllPatentsResponse>;
public getAllPatents(
page?: number,
size?: number,
search?: string,
source?: string,
sortBy?: string,
sortDirection?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<AllPatentsResponse>>;
public getAllPatents(
page?: number,
size?: number,
search?: string,
source?: string,
sortBy?: string,
sortDirection?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<AllPatentsResponse>>;
public getAllPatents(
page?: number,
size?: number,
search?: string,
source?: string,
sortBy?: string,
sortDirection?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>page,
'page',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>size,
'size',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>search,
'search',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>source,
'source',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>sortBy,
'sort_by',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>sortDirection,
'sort_direction',
);
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/patents`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<AllPatentsResponse>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Returns one publication by OpenAlex ID or DOI.
* @endpoint get /api/inse-service/patents/{identifier}
* @param identifier
* @param prefix Application Prefix (EP or US)
* @param title Do we want to fallback to title search if ID and DOI dont work?
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getPatentByIdOrTitle(
identifier: string,
prefix?: string,
title?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<PatentEntry>;
public getPatentByIdOrTitle(
identifier: string,
prefix?: string,
title?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<PatentEntry>>;
public getPatentByIdOrTitle(
identifier: string,
prefix?: string,
title?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<PatentEntry>>;
public getPatentByIdOrTitle(
identifier: string,
prefix?: string,
title?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (identifier === null || identifier === undefined) {
throw new Error(
'Required parameter identifier was null or undefined when calling getPatentByIdOrTitle.',
);
}
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>prefix,
'prefix',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>title,
'title',
);
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/patents/${this.configuration.encodeParam({ name: 'identifier', value: identifier, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<PatentEntry>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Get patents matched to an author by name.
* @endpoint get /api/inse-service/authors/{author_id}/patents
* @param authorId
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getPatentsByAuthor(
authorId: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<PatentsByAuthorResponse>;
public getPatentsByAuthor(
authorId: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<PatentsByAuthorResponse>>;
public getPatentsByAuthor(
authorId: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<PatentsByAuthorResponse>>;
public getPatentsByAuthor(
authorId: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error(
'Required parameter authorId was null or undefined when calling getPatentsByAuthor.',
);
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/patents`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<PatentsByAuthorResponse>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
}
import { Inject, Injectable, Optional } from '@angular/core';
import {
HttpClient,
HttpHeaders,
HttpParams,
HttpResponse,
HttpEvent,
HttpContext,
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { BASE_PATH } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
import { PatentEntry } from '../model/patentEntry';
import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse';
import { PatentsByInstitutionResponse } from '../model/patentsByInstitutionResponse';
import {
OrgPatentsResponse,
OrgPatentMatchTypeFilter,
} from '../model/orgPatentsResponse';
export interface AllPatentsResponse {
total: number;
page: number;
size: number;
patents: PatentEntry[];
}
type GetPatentsByAuthorOptions = {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
};
type GetPatentsByInstitutionOptions = {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
};
type GetOrgPatentsByInstitutionOptions = {
matchType?: OrgPatentMatchTypeFilter;
page?: number;
size?: number;
source?: 'EPO' | 'USPTO';
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
};
@Injectable({
providedIn: 'root',
})
export class PatentsService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
public getPatentsByAuthor(
authorId: string,
observe?: 'body',
reportProgress?: boolean,
options?: GetPatentsByAuthorOptions,
): Observable<PatentsByAuthorResponse>;
public getPatentsByAuthor(
authorId: string,
observe?: 'response',
reportProgress?: boolean,
options?: GetPatentsByAuthorOptions,
): Observable<HttpResponse<PatentsByAuthorResponse>>;
public getPatentsByAuthor(
authorId: string,
observe?: 'events',
reportProgress?: boolean,
options?: GetPatentsByAuthorOptions,
): Observable<HttpEvent<PatentsByAuthorResponse>>;
public getPatentsByAuthor(
authorId: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: GetPatentsByAuthorOptions,
): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error(
'Required parameter authorId was null or undefined when calling getPatentsByAuthor.',
);
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam(
{
name: 'authorId',
value: authorId,
in: 'path',
style: 'simple',
explode: false,
dataType: 'string',
dataFormat: undefined,
},
)}/patents`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<PatentsByAuthorResponse>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
public getPatentsByInstitution(
institutionId: string,
observe?: 'body',
reportProgress?: boolean,
options?: GetPatentsByInstitutionOptions,
): Observable<PatentsByInstitutionResponse>;
public getPatentsByInstitution(
institutionId: string,
observe?: 'response',
reportProgress?: boolean,
options?: GetPatentsByInstitutionOptions,
): Observable<HttpResponse<PatentsByInstitutionResponse>>;
public getPatentsByInstitution(
institutionId: string,
observe?: 'events',
reportProgress?: boolean,
options?: GetPatentsByInstitutionOptions,
): Observable<HttpEvent<PatentsByInstitutionResponse>>;
public getPatentsByInstitution(
institutionId: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: GetPatentsByInstitutionOptions,
): Observable<any> {
if (institutionId === null || institutionId === undefined) {
throw new Error(
'Required parameter institutionId was null or undefined when calling getPatentsByInstitution.',
);
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/institutions/${this.configuration.encodeParam(
{
name: 'institutionId',
value: institutionId,
in: 'path',
style: 'simple',
explode: false,
dataType: 'string',
dataFormat: undefined,
},
)}/patents`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<PatentsByInstitutionResponse>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
public getOrgPatentsByInstitution(
institutionId: string,
observe?: 'body',
reportProgress?: boolean,
options?: GetOrgPatentsByInstitutionOptions,
): Observable<OrgPatentsResponse>;
public getOrgPatentsByInstitution(
institutionId: string,
observe?: 'response',
reportProgress?: boolean,
options?: GetOrgPatentsByInstitutionOptions,
): Observable<HttpResponse<OrgPatentsResponse>>;
public getOrgPatentsByInstitution(
institutionId: string,
observe?: 'events',
reportProgress?: boolean,
options?: GetOrgPatentsByInstitutionOptions,
): Observable<HttpEvent<OrgPatentsResponse>>;
public getOrgPatentsByInstitution(
institutionId: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: GetOrgPatentsByInstitutionOptions,
): Observable<any> {
if (institutionId === null || institutionId === undefined) {
throw new Error(
'Required parameter institutionId was null or undefined when calling getOrgPatentsByInstitution.',
);
}
let localVarQueryParameters = new HttpParams();
if (options?.matchType) {
localVarQueryParameters = localVarQueryParameters.set(
'match_type',
options.matchType,
);
}
if (options?.page !== undefined) {
localVarQueryParameters = localVarQueryParameters.set(
'page',
String(options.page),
);
}
if (options?.size !== undefined) {
localVarQueryParameters = localVarQueryParameters.set(
'size',
String(options.size),
);
}
if (options?.source) {
localVarQueryParameters = localVarQueryParameters.set(
'source',
options.source,
);
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/institutions/${this.configuration.encodeParam(
{
name: 'institutionId',
value: institutionId,
in: 'path',
style: 'simple',
explode: false,
dataType: 'string',
dataFormat: undefined,
},
)}/org-patents`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<OrgPatentsResponse>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
public getAllPatents(
page: number = 0,
size: number = 10,
search?: string,
source?: string,
sortBy: string = 'date',
sortDirection: string = 'desc',
yearFrom?: number,
yearTo?: number,
): Observable<AllPatentsResponse> {
let params = new HttpParams()
.set('page', String(page))
.set('size', String(size))
.set('sort_by', sortBy)
.set('sort_direction', sortDirection);
if (search) params = params.set('search', search);
if (source) params = params.set('source', source);
if (yearFrom !== undefined)
params = params.set('year_from', String(yearFrom));
if (yearTo !== undefined) params = params.set('year_to', String(yearTo));
const localVarHeaders = this.defaultHeaders;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.get<AllPatentsResponse>(
`${basePath}/api/inse-service/patents`,
{
params,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
},
);
}
public getPatentById(
patentId: string,
title?: string,
prefix?: string,
fillingDate?: string,
): Observable<PatentEntry> {
const localVarHeaders = this.defaultHeaders;
const { basePath, withCredentials } = this.configuration;
let params = new HttpParams();
if (title) params = params.set('title', title);
if (prefix) params = params.set('prefix', prefix);
if (fillingDate) params = params.set('filling_date', fillingDate);
const localVarPath = `/api/inse-service/patents/${this.configuration.encodeParam(
{
name: 'patentId',
value: patentId,
in: 'path',
style: 'simple',
explode: false,
dataType: 'string',
dataFormat: undefined,
},
)}`;
return this.httpClient.get<PatentEntry>(`${basePath}${localVarPath}`, {
params,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
});
}
}
@@ -0,0 +1,4 @@
export interface MatchedAuthor {
openalex_author_id: string;
author_name: string;
}
+3
View File
@@ -103,6 +103,9 @@ export * from './newsArticle';
export * from './newsArticleDetail';
export * from './newsPage';
export * from './openAccess';
export * from './matchedAuthor';
export * from './orgPatentEntry';
export * from './orgPatentsResponse';
export * from './patentEntry';
export * from './patentsByAuthorResponse';
export * from './personBio';
@@ -0,0 +1,11 @@
import { PatentEntry } from './patentEntry';
import { MatchedAuthor } from './matchedAuthor';
export type OrgPatentMatchType = 'institution' | 'name' | 'both';
export interface OrgPatentEntry extends PatentEntry {
institution_id: string;
institution_name?: string | null;
match_type: OrgPatentMatchType;
matched_authors: MatchedAuthor[];
}
@@ -0,0 +1,12 @@
import { OrgPatentEntry } from './orgPatentEntry';
export type OrgPatentMatchTypeFilter = 'all' | 'institution' | 'name' | 'both';
export interface OrgPatentsResponse {
institution_id: string;
institution_name?: string | null;
patent_count: number;
page: number;
size: number;
patents: Array<OrgPatentEntry>;
}
@@ -0,0 +1,8 @@
import { PatentEntry } from './patentEntry';
export interface PatentsByInstitutionResponse {
institution_id: string;
institution_name?: string | null;
patent_count: number;
patents: Array<PatentEntry>;
}
+24 -46
View File
@@ -7,7 +7,6 @@ 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';
@@ -58,15 +57,8 @@ 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),
@@ -79,20 +71,6 @@ 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],
@@ -104,6 +82,14 @@ export const routes: Routes = [
publication: publicationResolver,
},
},
{
path: 'patent/:patentId',
canActivate: [userGuard],
loadComponent: () =>
import('./modules/patent-detail/patent-detail.component').then(
(mod) => mod.PatentDetailComponent,
),
},
{
path: 'projects/dfg/:id',
canActivate: [userGuard],
@@ -124,7 +110,7 @@ export const routes: Routes = [
),
resolve: { bundSingleProject: bundSingleProjectResolver },
},
{
{
path: 'projects/eu/:id',
canActivate: [userGuard],
pathMatch: 'full',
@@ -163,10 +149,7 @@ export const routes: Routes = [
import('./modules/person-projects/person-projects.component').then(
(mod) => mod.PersonProjectsComponent,
),
resolve: {
dfgProjectPage: dfgProjectsResolver,
personCordisEuProjectPage: personCordisEuProjectPageResolver,
},
resolve: { dfgProjectPage: dfgProjectsResolver },
runGuardsAndResolvers: (from, to) => {
const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search'];
return keys.some(
@@ -190,15 +173,9 @@ 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),
@@ -286,6 +263,13 @@ export const routes: Routes = [
);
},
},
{
path: 'patents',
loadComponent: () =>
import(
'./modules/institution-patents/institution-patents.component'
).then((mod) => mod.InstitutionPatentsComponent),
},
],
},
{
@@ -298,12 +282,7 @@ 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),
@@ -334,8 +313,7 @@ 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],
},
@@ -0,0 +1,193 @@
@if (loading) {
<p class="message">Lade Patente...</p>
} @else if (error) {
<p class="message">Fehler beim Laden der Patente.</p>
} @else if (patents.length === 0) {
<p class="message">Keine Patente in org_patents für diese Institution gefunden.</p>
<p class="message message-hint">
Der Index muss zuerst befüllt werden:
<code>python service/scripts/index_org_patents.py --institution-id {{ institutionId }}</code>
</p>
} @else {
<div class="patents-container">
<div class="patents-content">
<div class="patents-list">
<div class="patents-list-toolbar">
<label class="sort-control">
<span>Matching:</span>
<select [value]="activeMatchType" (change)="setMatchType($any($event.target).value)">
<option value="all">Alle</option>
<option value="institution">Institution</option>
<option value="name">Name</option>
<option value="both">Beides</option>
</select>
</label>
<label class="sort-control">
<span>Filter nach Quelle:</span>
<select [value]="activeFilter" (change)="setFilter($any($event.target).value)">
<option value="all">Alle</option>
<option value="EPO">EPO</option>
<option value="USPTO">USPTO</option>
</select>
</label>
<label class="sort-control">
<span>Sortieren nach:</span>
<select [value]="sortMode" (change)="setSortMode($any($event.target).value)">
<option value="date">Datum</option>
<option value="title">Titel</option>
</select>
</label>
</div>
<table>
<thead>
<tr>
<th>Patent</th>
<th>Quelle</th>
<th>Jahr</th>
<th>Erfinder</th>
<th>Applicant/Assignee</th>
<th>Match-Typ</th>
<th>Personen</th>
</tr>
</thead>
<tbody>
@for (patent of getPagedPatents(); track trackPatent($index, patent)) {
<tr
[class.selected]="selectedPatent === patent"
(click)="selectPatent(patent)">
<td class="patent-title">{{ patent.title ?? patent.patent_id }}</td>
<td>
<span class="source-badge source-badge--{{ patent.source.toLowerCase() }}">
{{ patent.source }}
</span>
</td>
<td>{{ patent.publication_year ?? '-' }}</td>
<td class="cell-preview">{{ getInventorsPreview(patent) }}</td>
<td class="cell-preview">{{ getAssigneesPreview(patent) }}</td>
<td>
<span class="match-badge match-badge--{{ patent.match_type }}">
{{ getMatchTypeLabel(patent) }}
</span>
</td>
<td class="cell-authors">
@if (patent.matched_authors.length) {
@for (author of patent.matched_authors.slice(0, 2); track author.openalex_author_id) {
<a
class="author-link"
[routerLink]="['/person', author.openalex_author_id]"
(click)="$event.stopPropagation()">
{{ author.author_name }}
</a>
}
} @else {
<span>-</span>
}
</td>
</tr>
}
</tbody>
</table>
@if (hasPagination()) {
<div class="pagination">
<button [disabled]="selectedPage === 1" (click)="setPage(selectedPage - 1)">Zurück</button>
<span>Seite {{ selectedPage }} von {{ getPageCount() }}</span>
<button [disabled]="selectedPage === getPageCount()" (click)="setPage(selectedPage + 1)">Weiter</button>
</div>
}
</div>
@if (selectedPatent) {
<div class="patent-detail">
<h3>{{ selectedPatent.title ?? selectedPatent.patent_id }}</h3>
<div class="detail-stats">
<div class="stat">
<span class="stat-label">Quelle</span>
<span class="stat-value">
<span class="source-badge source-badge--{{ selectedPatent.source.toLowerCase() }}">
{{ selectedPatent.source }}
</span>
</span>
</div>
<div class="stat">
<span class="stat-label">Patent-Nr.</span>
<span class="stat-value">{{ selectedPatent.patent_id }}</span>
</div>
<div class="stat">
<span class="stat-label">Datum</span>
<span class="stat-value">{{ formatDate(selectedPatent.publication_date) }}</span>
</div>
<div class="stat">
<span class="stat-label">Match-Typ</span>
<span class="stat-value">{{ getMatchTypeLabel(selectedPatent) }}</span>
</div>
@if (getPublicationStageLabel(selectedPatent); as stageLabel) {
<div class="stat">
<span class="stat-label">Publikationsstufe</span>
<span class="stat-value">{{ stageLabel }}</span>
</div>
}
</div>
@if (selectedPatent.matched_authors.length) {
<div class="detail-section">
<h4>Verknüpfte Personen</h4>
<ul class="tag-list tag-list--compact">
@for (author of selectedPatent.matched_authors; track author.openalex_author_id) {
<li>
<a class="tag author-link" [routerLink]="['/person', author.openalex_author_id]">
{{ author.author_name }}
</a>
</li>
}
</ul>
</div>
}
@if (getAbstractPreview(selectedPatent.abstract); as abstractPreview) {
<p class="patent-detail-preview">{{ abstractPreview }}</p>
}
<button type="button" class="patent-detail-action" (click)="openDetail()">
<span class="patent-detail-action__label">Patentdetails anzeigen</span>
<span class="material-icons" aria-hidden="true">chevron_right</span>
</button>
<p class="patent-detail-hint">
Abstract, Erfinder, Anmelder und IPC/CPC-Klassifikation
</p>
</div>
} @else {
<div class="patent-detail overview">
<p class="overview-title">Patentübersicht</p>
<p class="overview-subtitle">
@if (institutionName) {
Alle Patente von {{ institutionName }} im Überblick.
} @else {
Alle Patente dieser Institution im Überblick.
}
</p>
<div class="overview-stats">
<div class="overview-stat">
<span class="overview-value">{{ totalPatents }}</span>
<span class="overview-label">Patente</span>
</div>
<div class="overview-stat">
<span class="overview-value">{{ getInstitutionMatchCount() }}</span>
<span class="overview-label">Institution</span>
</div>
<div class="overview-stat">
<span class="overview-value">{{ getNameMatchCount() }}</span>
<span class="overview-label">Name</span>
</div>
<div class="overview-stat">
<span class="overview-value">{{ getBothMatchCount() }}</span>
<span class="overview-label">Beides</span>
</div>
</div>
<p class="overview-hint">Wähle links ein Patent aus, um Kurzinfos und Details zu sehen.</p>
</div>
}
</div>
</div>
}
@@ -0,0 +1,633 @@
.message {
padding: 16px;
color: #666;
&.message-hint {
padding-top: 0;
font-size: 13px;
color: #888;
code {
display: inline-block;
margin-top: 6px;
padding: 4px 8px;
border-radius: 6px;
background: #f5f5f5;
color: #333;
font-size: 12px;
}
}
}
.patents-container {
padding: 16px;
display: flex;
flex-direction: column;
gap: 16px;
}
.sort-control {
display: inline-flex;
align-items: center;
gap: 6px;
width: fit-content;
padding: 10px 14px;
border-radius: 20px;
background: #f2f2f2;
color: #333;
font-size: 14px;
span {
color: #555;
}
select {
border: 0;
background: transparent;
color: #111827;
font: inherit;
cursor: pointer;
outline: none;
}
}
.patents-content {
display: flex;
gap: 24px;
align-items: flex-start;
}
.patents-list {
flex: 1;
&.hidden {
display: none;
}
.patents-list-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
margin-bottom: 18px;
flex-wrap: wrap;
}
table {
width: 100%;
border-collapse: collapse;
th {
text-align: left;
padding: 10px 12px;
border-bottom: 2px solid #e0e0e0;
font-weight: 600;
color: #333;
}
tr {
cursor: pointer;
&:hover {
background: #f5f5f5;
}
&.selected {
background: #f0f0f0;
}
}
td {
padding: 10px 12px;
border-bottom: 1px solid #f0f0f0;
}
.patent-title {
color: #333;
font-weight: 500;
max-width: 280px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.cell-preview {
max-width: 160px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
color: #555;
font-size: 13px;
}
.cell-authors {
display: flex;
flex-direction: column;
gap: 4px;
min-width: 120px;
}
}
}
.match-badge {
display: inline-flex;
align-items: center;
padding: 3px 10px;
border-radius: 999px;
font-size: 0.72rem;
font-weight: 700;
&--institution {
background: #f5f3ff;
color: #6d28d9;
border: 1px solid #ddd6fe;
}
&--name {
background: #fff7ed;
color: #c2410c;
border: 1px solid #fed7aa;
}
&--both {
background: #ecfdf5;
color: #047857;
border: 1px solid #a7f3d0;
}
}
.author-link {
color: #2563eb;
text-decoration: none;
font-size: 0.82rem;
&:hover {
text-decoration: underline;
}
}
.source-badge {
display: inline-flex;
align-items: center;
padding: 3px 10px;
border-radius: 999px;
font-size: 0.75rem;
font-weight: 700;
&--epo {
background: #effaf3;
color: #24834f;
border: 1px solid #bdebcf;
}
&--uspto {
background: #f0f6ff;
color: #0b63ce;
border: 1px solid #bdd4ff;
}
}
.patent-detail {
width: 440px;
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 20px;
background: #fafafa;
&.empty {
display: flex;
align-items: center;
justify-content: center;
color: #999;
min-height: 200px;
}
&.overview {
display: flex;
flex-direction: column;
gap: 12px;
.overview-title {
font-size: 15px;
font-weight: 600;
color: #333;
margin: 0;
}
.overview-subtitle {
font-size: 13px;
color: #888;
margin: 0;
}
.overview-stats {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
margin-top: 4px;
}
.overview-stat {
background: white;
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 12px 8px;
text-align: center;
.overview-value {
display: block;
font-size: 22px;
font-weight: 700;
color: #333;
}
.overview-label {
display: block;
font-size: 12px;
color: #888;
margin-top: 4px;
}
}
.overview-hint {
font-size: 12px;
color: #aaa;
margin: 0;
}
}
h3 {
margin: 0 0 16px 0;
font-size: 16px;
color: #333;
line-height: 1.4;
}
}
.detail-stats {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
.stat {
background: white;
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 10px;
text-align: center;
.stat-label {
display: block;
font-size: 11px;
color: #666;
margin-bottom: 4px;
text-transform: uppercase;
letter-spacing: 0.03em;
}
.stat-value {
display: block;
font-size: 15px;
font-weight: bold;
color: #333;
}
}
}
.patent-detail-preview {
margin: 14px 0 0;
font-size: 13px;
line-height: 1.55;
color: #555;
}
.patent-detail-action {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
width: 100%;
margin-top: 16px;
padding: 12px 14px;
border: 1px solid #bdd4ff;
border-radius: 10px;
background: linear-gradient(180deg, #f8fbff 0%, #eef4ff 100%);
color: #0b63ce;
font-size: 14px;
font-weight: 600;
cursor: pointer;
transition: border-color 0.15s, background 0.15s, box-shadow 0.15s;
&:hover {
border-color: #0b63ce;
background: #f0f6ff;
box-shadow: 0 2px 8px rgba(11, 99, 206, 0.12);
}
.material-icons {
font-size: 20px;
}
}
.patent-detail-hint {
margin: 8px 0 0;
font-size: 12px;
line-height: 1.4;
color: #888;
text-align: center;
}
.patent-full-detail {
flex: 1;
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 20px;
background: #fafafa;
h3 {
margin: 0 0 4px 0;
font-size: 16px;
color: #333;
line-height: 1.4;
}
h4 {
margin: 16px 0 8px 0;
font-size: 14px;
color: #555;
font-weight: 600;
}
p {
font-size: 13px;
color: #444;
line-height: 1.6;
margin: 0;
}
}
.back-btn {
display: inline-flex;
align-items: center;
gap: 0.4rem;
width: auto;
margin-bottom: 1rem;
padding: 0.5rem 0.85rem;
border: 1px solid #d6e3f8;
border-radius: 999px;
background: #f8fbff;
color: #2563eb;
font-size: 0.9rem;
font-weight: 600;
cursor: pointer;
transition:
background-color 0.15s ease,
border-color 0.15s ease,
color 0.15s ease,
box-shadow 0.15s ease;
&:hover {
background: #eef5ff;
border-color: #bcd3f7;
color: #1d4ed8;
box-shadow: 0 1px 4px rgba(37, 99, 235, 0.12);
}
&:focus-visible {
outline: 2px solid #93c5fd;
outline-offset: 2px;
}
}
.detail-section {
margin-top: 12px;
padding-top: 12px;
border-top: 1px solid #eee;
}
.patent-meta {
&--inline {
margin: 12px 0 20px;
}
&__list {
margin: 0;
border: 1px solid #e2e8f4;
border-radius: 12px;
background: linear-gradient(180deg, #fff 0%, #f8faff 100%);
box-shadow: 0 1px 3px rgba(15, 23, 42, 0.04);
overflow: hidden;
}
&__row {
display: grid;
grid-template-columns: minmax(130px, 38%) 1fr;
gap: 12px 16px;
align-items: center;
padding: 11px 16px;
border-top: 1px solid #eef2f8;
&:first-child {
border-top: 0;
}
dt {
margin: 0;
font-size: 12px;
font-weight: 500;
color: #64748b;
line-height: 1.35;
}
dd {
margin: 0;
font-size: 14px;
font-weight: 600;
color: #1e293b;
line-height: 1.35;
word-break: break-word;
}
}
}
.tag-list {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin: 0;
padding: 0;
list-style: none;
&--compact .tag {
font-size: 0.75rem;
padding: 3px 8px;
}
}
.tag {
padding: 4px 10px;
border-radius: 999px;
background: #f0f6ff;
border: 1px solid #dbeafe;
color: #1e40af;
font-size: 0.8rem;
line-height: 1.3;
}
.classification-section {
&--ipc .classification-card {
background: #f0f6ff;
border-color: #bfdbfe;
}
&--ipc .classification-badge--system {
background: #dbeafe;
color: #1d4ed8;
}
&--cpc .classification-card {
background: #f0fdf4;
border-color: #bbf7d0;
}
&--cpc .classification-badge--system {
background: #dcfce7;
color: #15803d;
}
}
.classification-cards {
display: flex;
flex-direction: column;
gap: 10px;
}
.classification-card {
padding: 12px 14px;
border-radius: 10px;
border: 1px solid #dbeafe;
}
.classification-card__header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
}
.classification-card__codes {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.classification-card__badges {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.classification-code {
font-size: 0.9rem;
font-weight: 700;
color: #0f172a;
}
.classification-badge {
display: inline-flex;
align-items: center;
padding: 2px 8px;
border-radius: 999px;
font-size: 0.68rem;
font-weight: 700;
letter-spacing: 0.02em;
text-transform: uppercase;
}
.classification-badge--level {
background: #e2e8f0;
color: #475569;
}
.classification-summary {
margin: 10px 0 0;
font-size: 0.84rem;
line-height: 1.5;
color: #334155;
}
.classification-toggle {
margin-top: 6px;
padding: 0;
border: 0;
background: none;
color: #2563eb;
font-size: 0.78rem;
cursor: pointer;
&:hover {
text-decoration: underline;
}
}
.classification-hierarchy {
margin: 10px 0 0;
padding-top: 10px;
border-top: 1px solid rgba(15, 23, 42, 0.08);
}
.classification-hierarchy__row {
display: grid;
grid-template-columns: 88px 1fr;
gap: 8px;
margin-bottom: 6px;
dt {
margin: 0;
font-size: 0.72rem;
font-weight: 700;
color: #64748b;
text-transform: uppercase;
letter-spacing: 0.03em;
}
dd {
margin: 0;
font-size: 0.8rem;
line-height: 1.45;
color: #334155;
}
}
.pagination {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-top: 12px;
button {
padding: 4px 10px;
border: 1px solid #d0d0d0;
border-radius: 6px;
background: white;
cursor: pointer;
font-size: 12px;
&:disabled {
opacity: 0.5;
cursor: default;
}
}
span {
font-size: 12px;
color: #666;
}
}
@@ -0,0 +1,275 @@
import { Component, OnInit, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { PatentsService } from '../../api/api/patents.service';
import { OrgPatentEntry } from '../../api/model/orgPatentEntry';
import { OrgPatentMatchTypeFilter } from '../../api/model/orgPatentsResponse';
import {
formatPatentDate,
getPublicationStageLabel,
} from '../patent-detail/patent-detail.utils';
type SortMode = 'date' | 'title';
type SourceFilter = 'all' | 'EPO' | 'USPTO';
@Component({
selector: 'app-institution-patents',
imports: [CommonModule, RouterLink],
templateUrl: './institution-patents.component.html',
styleUrl: './institution-patents.component.scss',
})
export class InstitutionPatentsComponent implements OnInit {
private route = inject(ActivatedRoute);
private router = inject(Router);
private patentsApi = inject(PatentsService);
patents: OrgPatentEntry[] = [];
filteredPatents: OrgPatentEntry[] = [];
institutionName: string | null = null;
institutionId: string | null = null;
selectedPatent: OrgPatentEntry | null = null;
loading = true;
error = false;
activeFilter: SourceFilter = 'all';
activeMatchType: OrgPatentMatchTypeFilter = 'all';
sortMode: SortMode = 'date';
selectedPage = 1;
readonly pageSize = 20;
totalPatents = 0;
ngOnInit(): void {
this.route.parent?.paramMap.subscribe((params) => {
const institutionId = params.get('institutionId') ?? '';
const filterFromUrl = this.route.snapshot.queryParamMap.get('filter');
const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy');
const matchTypeFromUrl = this.route.snapshot.queryParamMap.get('matchType');
if (this.isValidFilter(filterFromUrl)) {
this.activeFilter = filterFromUrl;
}
if (this.isValidSortMode(sortFromUrl)) {
this.sortMode = sortFromUrl;
}
if (this.isValidMatchType(matchTypeFromUrl)) {
this.activeMatchType = matchTypeFromUrl;
}
if (institutionId) {
this.institutionId = institutionId;
this.loadPatents(institutionId);
}
});
}
setFilter(filter: SourceFilter): void {
this.activeFilter = filter;
this.selectedPage = 1;
this.selectedPatent = null;
this.reloadPatents();
}
setMatchType(matchType: OrgPatentMatchTypeFilter): void {
if (this.activeMatchType === matchType) return;
this.activeMatchType = matchType;
this.selectedPage = 1;
this.selectedPatent = null;
this.reloadPatents();
}
setSortMode(sortMode: SortMode): void {
this.sortMode = sortMode;
this.filteredPatents = this.sortPatents(this.patents);
this.updateQueryParams();
}
selectPatent(patent: OrgPatentEntry): void {
this.selectedPatent = patent;
this.updateQueryParams();
}
openDetail(): void {
if (!this.selectedPatent) return;
this.router.navigate(['/patent', this.selectedPatent.patent_id]);
}
setPage(page: number): void {
this.selectedPage = Math.min(Math.max(page, 1), this.getPageCount());
this.selectedPatent = null;
this.reloadPatents();
}
getPagedPatents(): OrgPatentEntry[] {
return this.filteredPatents;
}
getPageCount(): number {
return Math.max(1, Math.ceil(this.totalPatents / this.pageSize));
}
hasPagination(): boolean {
return this.totalPatents > this.pageSize;
}
private reloadPatents(): void {
const institutionId = this.institutionId ??
this.route.parent?.snapshot.paramMap.get('institutionId') ?? '';
if (institutionId) {
this.loadPatents(institutionId);
}
}
private loadPatents(institutionId: string): void {
this.loading = true;
this.error = false;
this.patentsApi
.getOrgPatentsByInstitution(institutionId, 'body', false, {
matchType: this.activeMatchType,
page: this.selectedPage - 1,
size: this.pageSize,
source: this.activeFilter !== 'all' ? this.activeFilter : undefined,
})
.subscribe({
next: (result) => {
this.patents = result.patents ?? [];
this.totalPatents = result.patent_count ?? 0;
this.institutionName = result.institution_name ?? null;
this.filteredPatents = this.sortPatents(this.patents);
this.loading = false;
this.updateQueryParams();
},
error: () => {
this.error = true;
this.loading = false;
},
});
}
private sortPatents(patents: OrgPatentEntry[]): OrgPatentEntry[] {
if (this.sortMode === 'title') {
return [...patents].sort((a, b) =>
(a.title ?? '').localeCompare(b.title ?? '', 'de', { sensitivity: 'base' }),
);
}
return [...patents];
}
private updateQueryParams(): void {
this.router.navigate([], {
relativeTo: this.route,
queryParams: {
filter: this.activeFilter,
sortBy: this.sortMode,
matchType: this.activeMatchType,
page: this.selectedPage,
},
queryParamsHandling: 'merge',
replaceUrl: true,
});
}
private isValidFilter(value: string | null): value is SourceFilter {
return value === 'all' || value === 'EPO' || value === 'USPTO';
}
private isValidSortMode(value: string | null): value is SortMode {
return value === 'date' || value === 'title';
}
private isValidMatchType(value: string | null): value is OrgPatentMatchTypeFilter {
return value === 'all' || value === 'institution' || value === 'name' || value === 'both';
}
formatDate(date: string | null): string {
return formatPatentDate(date);
}
getEpoCount(): number {
return this.patents.filter((p) => p.source === 'EPO').length;
}
getUsptoCount(): number {
return this.patents.filter((p) => p.source === 'USPTO').length;
}
getInstitutionMatchCount(): number {
return this.patents.filter(
(p) => p.match_type === 'institution' || p.match_type === 'both',
).length;
}
getNameMatchCount(): number {
return this.patents.filter(
(p) => p.match_type === 'name' || p.match_type === 'both',
).length;
}
getBothMatchCount(): number {
return this.patents.filter((p) => p.match_type === 'both').length;
}
trackPatent(_index: number, patent: OrgPatentEntry): string {
return [
patent.source,
patent.patent_id,
patent.publication_date ?? '',
patent.kind ?? patent.application_type ?? '',
].join('|');
}
getAbstractPreview(abstract: string | null | undefined): string | null {
if (!abstract?.trim()) {
return null;
}
const text = abstract.trim();
if (text.length <= 160) {
return text;
}
return `${text.slice(0, 160).trimEnd()}…`;
}
getPublicationStageLabel(patent: OrgPatentEntry): string | null {
return getPublicationStageLabel(patent);
}
getMatchTypeLabel(patent: OrgPatentEntry): string {
switch (patent.match_type) {
case 'institution':
return 'Institution';
case 'name':
return 'Name';
case 'both':
return 'Beides';
default:
return patent.match_type;
}
}
getInventorsPreview(patent: OrgPatentEntry): string {
if (!patent.inventors?.length) {
return '-';
}
return patent.inventors.slice(0, 2).join(', ');
}
getAssigneesPreview(patent: OrgPatentEntry): string {
if (!patent.assignees?.length) {
return '-';
}
return patent.assignees.slice(0, 2).join(', ');
}
getMatchedAuthorsPreview(patent: OrgPatentEntry): string {
if (!patent.matched_authors?.length) {
return '-';
}
return patent.matched_authors
.slice(0, 2)
.map((author) => author.author_name)
.join(', ');
}
}
@@ -40,6 +40,7 @@ export class InstitutionComponent implements OnInit {
sort_direction: 'asc',
},
},
{ label: 'Patente', path: 'patents', disabled: false },
];
constructor(private readonly activatedRoute: ActivatedRoute) {}
@@ -78,6 +78,13 @@
<mat-icon>work</mat-icon>
Projekte
</a>
<a
mat-button
[routerLink]="['/institution', institutionId, 'patents']"
(click)="$event.stopPropagation()">
<mat-icon>verified</mat-icon>
Patente
</a>
</mat-card-actions>
</mat-card-footer>
</mat-card>
@@ -107,21 +107,13 @@
<div class="sidebar-card">
<h3>
<mat-icon>label</mat-icon>
Schlüsselwörter
Relevante Themen
</h3>
<div class="chip-list">
@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>
@for (topic of relevantTopics; track topic; let i = $index) {
<span class="topic-chip" [ngClass]="chipColor(i)">{{
topic
}}</span>
}
</div>
</div>
@@ -180,9 +180,6 @@ main {
display: flex;
flex-direction: column;
gap: 8px;
max-height: 375px;
overflow-y: auto;
padding-right: 4px;
}
.person-item {
@@ -24,7 +24,6 @@ interface NewsArticleDetail {
full_content?: string | null;
relevant?: boolean;
authors?: MentionedPerson[];
keywords?: string[];
}
@Component({
@@ -50,6 +49,13 @@ 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 {
+102 -26
View File
@@ -4,31 +4,107 @@
<p>Aktuelle Nachrichten aus Campus-Aktuell.</p>
</div>
<ng-template #snippetTpl let-article>
@if (article.snippet) {
<span class="snippet" [innerHTML]="article.snippet"></span>
} @else {
<span class="snippet-empty">—</span>
}
</ng-template>
<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>
<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>
@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>
}
</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="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>
</div>
+169 -5
View File
@@ -17,14 +17,107 @@ 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.45;
line-height: 1.4;
}
::ng-deep .snippet em {
@@ -38,8 +131,79 @@ h6 {
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;
}
}
+49 -77
View File
@@ -1,23 +1,27 @@
import { Component, DestroyRef, OnInit, inject } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { PageEvent } from '@angular/material/paginator';
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 { 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 extends NewsArticleBase {
interface NewsArticle {
id: string;
date?: string | null;
maintitle?: string | null;
author?: string | null;
url?: string | null;
relevant?: boolean | null;
snippet?: string | null;
}
@@ -28,11 +32,22 @@ interface NewsPage {
results: NewsArticle[];
}
type SortOrder = 'desc' | 'asc';
const DEFAULT_SORT_ORDER: SortOrder = 'desc';
@Component({
selector: 'app-news',
imports: [ReactiveFormsModule, NewsListComponent],
imports: [
MatIconModule,
MatSelectModule,
MatFormFieldModule,
MatInputModule,
MatPaginatorModule,
MatProgressSpinnerModule,
MatTableModule,
ReactiveFormsModule,
RouterLink,
],
templateUrl: './news.component.html',
styleUrl: './news.component.scss',
})
@@ -46,12 +61,12 @@ export class NewsComponent implements OnInit {
readonly searchControl = new FormControl('', { nonNullable: true });
readonly displayedColumns: string[] = [
'maintitle',
'snippet',
'relevance',
'date',
];
get displayedColumns(): string[] {
if (this.isSearching) {
return ['maintitle', 'snippet', 'relevance', 'date'];
}
return ['maintitle', 'relevance', 'date'];
}
articles: NewsArticle[] = [];
total = 0;
@@ -60,12 +75,9 @@ export class NewsComponent implements OnInit {
currentPage = 1;
sortOrder: SortOrder = DEFAULT_SORT_ORDER;
relevanceValues: string[] = [];
yearFrom: number | null = null;
yearTo: number | null = null;
private readonly minYear = NEWS_MIN_YEAR;
private readonly maxYear = new Date().getFullYear();
get isSearching(): boolean {
return this.searchControl.value.trim().length > 0;
}
ngOnInit(): void {
this.route.queryParamMap
@@ -76,9 +88,6 @@ 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,
});
@@ -106,11 +115,10 @@ export class NewsComponent implements OnInit {
const basePath = this.worksService.configuration.basePath ?? '';
if (query) {
let params = new HttpParams()
const 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 })
@@ -127,11 +135,10 @@ export class NewsComponent implements OnInit {
},
});
} else {
let params = new HttpParams()
const 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 })
@@ -150,19 +157,6 @@ 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,
@@ -185,22 +179,19 @@ export class NewsComponent implements OnInit {
});
}
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;
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);
}
this.router.navigate([], {
relativeTo: this.route,
queryParams: {
relevance,
yearFrom,
yearTo,
page: 1,
},
queryParamsHandling: 'merge',
});
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`;
}
private parsePage(value: string | null): number {
@@ -225,23 +216,4 @@ 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;
}
}
@@ -0,0 +1,319 @@
<div class="detail-page">
<button
type="button"
class="back-link"
(click)="navigateBack()"
aria-label="Zurück zu den Patenten">
<mat-icon>arrow_back</mat-icon>
Alle Patente
</button>
@if (loading) {
<div class="state">
<mat-spinner diameter="42"></mat-spinner>
<p>Patent wird geladen...</p>
</div>
} @else if (notFound || !patent) {
<div class="state error-state">
<mat-icon>search_off</mat-icon>
<h2>Patent nicht gefunden</h2>
<p>Das Patent konnte nicht geladen werden.</p>
<a mat-stroked-button routerLink="/patents"> Zur Patentübersicht </a>
</div>
} @else {
<header class="hero">
<div class="hero-copy">
<div class="eyebrow">
<span class="source-badge source-badge--{{ patent.source.toLowerCase() }}">
{{ patent.source }}
</span>
@if (patent.publication_year) {
<span>{{ patent.publication_year }}</span>
}
@if (stageLabel(); as stage) {
<span>{{ stage }}</span>
}
</div>
<h1>{{ patent.title || patent.patent_id || 'Ohne Titel' }}</h1>
<p class="meta-line">
<span>{{ patent.patent_id }}</span>
@if (patent.publication_date) {
<span>· {{ formatDate(patent.publication_date) }}</span>
}
</p>
<div class="hero-actions">
@for (link of externalLinks(); track link.url; let first = $first) {
<a
[class.primary-action]="first"
[attr.mat-flat-button]="first ? '' : null"
[attr.mat-stroked-button]="first ? null : ''"
[href]="link.url"
target="_blank"
rel="noopener">
{{ link.label }}
<mat-icon>open_in_new</mat-icon>
</a>
}
</div>
</div>
<div class="metrics" aria-label="Patentkennzahlen">
<div>
<mat-icon>groups</mat-icon>
<strong>{{ patent.inventors.length }}</strong>
<span>Erfinder</span>
</div>
<div>
<mat-icon>business</mat-icon>
<strong>{{ patent.assignees.length }}</strong>
<span>Anmelder</span>
</div>
<div>
<mat-icon>category</mat-icon>
<strong>{{ patent.ipc.length + patent.cpc.length }}</strong>
<span>Klassifikationen</span>
</div>
</div>
</header>
<div class="content-grid">
<main>
@if (patent.abstract) {
<section class="card abstract-card">
<div class="section-title">
<mat-icon>subject</mat-icon>
<h2>Abstract</h2>
</div>
<p>{{ patent.abstract }}</p>
</section>
}
<section class="card">
<div class="section-title">
<mat-icon>engineering</mat-icon>
<h2>Erfinder</h2>
<span>{{ patent.inventors.length }}</span>
</div>
<div class="tags">
@for (inventor of patent.inventors; track inventor) {
<span>{{ inventor }}</span>
} @empty {
<p class="empty">Keine Angaben vorhanden.</p>
}
</div>
</section>
@if (patent.assignees.length > 0) {
<section class="card">
<div class="section-title">
<mat-icon>account_balance</mat-icon>
<h2>Anmelder</h2>
<span>{{ patent.assignees.length }}</span>
</div>
<div class="compact-list">
@for (assignee of patent.assignees; track assignee) {
<div>
<strong>{{ assignee }}</strong>
</div>
}
</div>
</section>
}
@if (patent.ipc_descriptions.length > 0) {
<section class="card classification-card-section classification-card-section--ipc">
<div class="section-title">
<mat-icon>label</mat-icon>
<h2>Klassifikation (IPC)</h2>
</div>
<div class="classification-cards">
@for (
card of classificationCards(patent.ipc_descriptions, 'IPC');
track card.key
) {
<article class="classification-card">
<header class="classification-card__header">
<div class="classification-card__codes">
@for (symbol of card.symbols; track symbol) {
<span class="classification-code">{{ symbol }}</span>
}
</div>
<div class="classification-card__badges">
<span class="classification-badge classification-badge--system">
{{ card.system }}
</span>
<span class="classification-badge classification-badge--level">
{{ card.levelLabel }}
</span>
</div>
</header>
@if (card.primaryDescription) {
<p class="classification-summary">
{{
isClassificationExpanded(card.key)
? card.primaryDescription
: getDescriptionPreview(card.primaryDescription)
}}
</p>
@if (isLongDescription(card.primaryDescription)) {
<button
type="button"
class="classification-toggle"
(click)="toggleClassificationExpanded(card.key)">
{{
isClassificationExpanded(card.key)
? 'Weniger anzeigen'
: 'Mehr anzeigen'
}}
</button>
}
}
@if (card.hierarchy.length > 0) {
<dl class="classification-hierarchy">
@for (row of card.hierarchy; track row.label) {
<div class="classification-hierarchy__row">
<dt>{{ row.label }}</dt>
<dd>{{ row.value }}</dd>
</div>
}
</dl>
}
</article>
}
</div>
</section>
} @else if (patent.ipc.length > 0) {
<section class="card">
<div class="section-title">
<mat-icon>label</mat-icon>
<h2>Klassifikation (IPC)</h2>
</div>
<div class="tags">
@for (ipc of patent.ipc; track ipc) {
<span>{{ ipc }}</span>
}
</div>
</section>
}
@if (patent.cpc_descriptions.length > 0) {
<section class="card classification-card-section classification-card-section--cpc">
<div class="section-title">
<mat-icon>label</mat-icon>
<h2>Klassifikation (CPC)</h2>
</div>
<div class="classification-cards">
@for (
card of classificationCards(patent.cpc_descriptions, 'CPC');
track card.key
) {
<article class="classification-card">
<header class="classification-card__header">
<div class="classification-card__codes">
@for (symbol of card.symbols; track symbol) {
<span class="classification-code">{{ symbol }}</span>
}
</div>
<div class="classification-card__badges">
<span class="classification-badge classification-badge--system">
{{ card.system }}
</span>
<span class="classification-badge classification-badge--level">
{{ card.levelLabel }}
</span>
</div>
</header>
@if (card.primaryDescription) {
<p class="classification-summary">
{{
isClassificationExpanded(card.key)
? card.primaryDescription
: getDescriptionPreview(card.primaryDescription)
}}
</p>
@if (isLongDescription(card.primaryDescription)) {
<button
type="button"
class="classification-toggle"
(click)="toggleClassificationExpanded(card.key)">
{{
isClassificationExpanded(card.key)
? 'Weniger anzeigen'
: 'Mehr anzeigen'
}}
</button>
}
}
@if (card.hierarchy.length > 0) {
<dl class="classification-hierarchy">
@for (row of card.hierarchy; track row.label) {
<div class="classification-hierarchy__row">
<dt>{{ row.label }}</dt>
<dd>{{ row.value }}</dd>
</div>
}
</dl>
}
</article>
}
</div>
</section>
} @else if (patent.cpc.length > 0) {
<section class="card">
<div class="section-title">
<mat-icon>label</mat-icon>
<h2>Klassifikation (CPC)</h2>
</div>
<div class="tags">
@for (cpc of patent.cpc; track cpc) {
<span>{{ cpc }}</span>
}
</div>
</section>
}
</main>
<aside>
<section class="card facts-card">
<div class="section-title">
<mat-icon>info</mat-icon>
<h2>Patentdaten</h2>
</div>
<dl>
@for (row of metadataRows(); track row.label) {
<div>
<dt>{{ row.label }}</dt>
<dd>
@if (row.variant === 'source') {
<span class="source-badge source-badge--{{ row.value.toLowerCase() }}">
{{ row.value }}
</span>
} @else {
{{ row.value }}
}
</dd>
</div>
}
</dl>
</section>
@if (externalLinks().length) {
<section class="card">
<div class="section-title">
<mat-icon>link</mat-icon>
<h2>Externe Links</h2>
</div>
<div class="link-list">
@for (link of externalLinks(); track link.url) {
<a [href]="link.url" target="_blank" rel="noopener">
<span>{{ link.label }}</span>
<mat-icon>north_east</mat-icon>
</a>
}
</div>
</section>
}
</aside>
</div>
}
</div>
@@ -0,0 +1,462 @@
:host {
display: block;
background: var(--sg-background);
}
.detail-page {
max-width: 1500px;
margin: 0 auto;
padding: 26px 32px 56px;
}
.back-link {
display: inline-flex;
align-items: center;
gap: 7px;
margin-bottom: 22px;
padding: 0;
border: 0;
background: transparent;
color: var(--sg-text-muted);
font-size: 13px;
font-weight: 600;
text-decoration: none;
cursor: pointer;
}
.back-link mat-icon {
width: 18px;
height: 18px;
font-size: 18px;
}
.hero {
display: grid;
grid-template-columns: minmax(0, 1fr) 420px;
gap: 42px;
padding: 38px 42px;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-lg);
background:
radial-gradient(
circle at 90% 10%,
rgba(200, 217, 255, 0.75),
transparent 35%
),
linear-gradient(140deg, #fff 0%, #f8faff 100%);
box-shadow: var(--sg-shadow-sm);
}
.eyebrow,
.tags,
.hero-actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.eyebrow span {
padding: 5px 10px;
border: 1px solid var(--sg-border);
border-radius: 999px;
background: rgba(255, 255, 255, 0.85);
color: var(--sg-text-muted);
font-size: 11px;
font-weight: 700;
text-transform: uppercase;
}
h1 {
max-width: 920px;
margin: 20px 0 13px;
font-size: clamp(27px, 3vw, 42px);
line-height: 1.13;
}
.meta-line {
max-width: 900px;
margin: 0;
color: var(--sg-text-muted);
font-size: 14px;
line-height: 1.7;
}
.hero-actions {
margin-top: 26px;
}
.hero-actions a {
display: inline-flex;
align-items: center;
gap: 8px;
min-height: 42px;
padding: 9px 16px;
border: 1px solid var(--sg-border-strong);
border-radius: var(--sg-radius-sm);
background: #fff;
color: var(--sg-text);
font-weight: 700;
text-decoration: none;
}
.hero-actions a.primary-action {
border-color: var(--sg-primary);
background: var(--sg-primary);
color: #fff;
}
.hero-actions mat-icon {
width: 17px;
height: 17px;
font-size: 17px;
}
.metrics {
display: grid;
grid-template-columns: repeat(3, 1fr);
align-self: center;
overflow: hidden;
border: 1px solid rgba(199, 211, 232, 0.8);
border-radius: var(--sg-radius-md);
background: rgba(255, 255, 255, 0.8);
}
.metrics div {
display: flex;
align-items: center;
flex-direction: column;
gap: 5px;
padding: 22px 10px;
text-align: center;
}
.metrics div + div {
border-left: 1px solid var(--sg-border);
}
.metrics mat-icon {
color: var(--sg-text-soft);
}
.metrics strong {
color: var(--sg-text);
font-family: 'Montserrat', 'Open Sans', sans-serif;
font-size: 22px;
}
.metrics span {
color: var(--sg-text-muted);
font-size: 11px;
}
.content-grid {
display: grid;
grid-template-columns: minmax(0, 1fr) 380px;
gap: 24px;
margin-top: 24px;
}
main,
aside {
display: flex;
flex-direction: column;
gap: 24px;
}
.card {
padding: 26px 28px;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-md);
background: var(--sg-surface);
box-shadow: var(--sg-shadow-sm);
}
.section-title {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 20px;
}
.section-title mat-icon {
color: var(--sg-text-muted);
}
.section-title h2 {
margin: 0;
font-size: 16px;
}
.section-title span {
margin-left: auto;
color: var(--sg-text-muted);
font-size: 12px;
}
.abstract-card p {
margin: 0;
color: var(--sg-text);
font-size: 14px;
line-height: 1.8;
}
.tags span {
padding: 7px 10px;
border: 1px solid var(--sg-border);
border-radius: 999px;
color: var(--sg-text-muted);
font-size: 11px;
}
.compact-list,
.link-list {
display: grid;
gap: 10px;
}
.compact-list div {
display: flex;
align-items: flex-start;
flex-direction: column;
gap: 3px;
padding: 13px 0;
border-bottom: 1px solid var(--sg-border);
}
.compact-list div:last-child {
border-bottom: 0;
}
.compact-list strong {
font-size: 12px;
}
dl {
margin: 0;
}
dl div {
display: grid;
grid-template-columns: 115px minmax(0, 1fr);
gap: 12px;
padding: 10px 0;
border-bottom: 1px solid var(--sg-border);
}
dl div:last-child {
border-bottom: 0;
}
dt {
color: var(--sg-text-muted);
font-size: 12px;
}
dd {
margin: 0;
overflow-wrap: anywhere;
color: var(--sg-text);
font-size: 12px;
font-weight: 600;
text-align: right;
}
.link-list a {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 0;
border-bottom: 1px solid var(--sg-border);
color: var(--sg-text);
font-size: 12px;
font-weight: 700;
text-decoration: none;
}
.link-list a:last-child {
border-bottom: 0;
}
.link-list mat-icon {
width: 16px;
height: 16px;
color: var(--sg-text-muted);
font-size: 16px;
}
.state {
display: grid;
place-items: center;
min-height: 380px;
color: var(--sg-text-muted);
text-align: center;
}
.error-state mat-icon {
width: 46px;
height: 46px;
font-size: 46px;
}
.empty {
color: var(--sg-text-muted);
}
.source-badge {
display: inline-flex;
align-items: center;
padding: 4px 10px;
border-radius: 999px;
font-size: 11px;
font-weight: 700;
text-transform: uppercase;
}
.source-badge--epo {
background: #e8f7ee;
color: #1f7a43;
}
.source-badge--uspto {
background: #eef3ff;
color: #1f4fbf;
}
.classification-cards {
display: grid;
gap: 12px;
}
.classification-card {
padding: 16px;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
background: var(--sg-surface-muted);
}
.classification-card-section--ipc .classification-card {
background: #f4f8ff;
}
.classification-card-section--cpc .classification-card {
background: #f3fbf5;
}
.classification-card__header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 10px;
}
.classification-card__codes {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.classification-code {
padding: 4px 8px;
border-radius: 6px;
background: #fff;
color: var(--sg-text);
font-size: 12px;
font-weight: 700;
}
.classification-card__badges {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.classification-badge {
padding: 3px 8px;
border-radius: 999px;
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
}
.classification-badge--system {
background: #e8eef8;
color: #35507a;
}
.classification-badge--level {
background: #fff;
color: var(--sg-text-muted);
}
.classification-summary {
margin: 0 0 8px;
color: var(--sg-text);
font-size: 13px;
line-height: 1.6;
}
.classification-toggle {
padding: 0;
border: 0;
background: transparent;
color: var(--sg-primary);
font-size: 12px;
font-weight: 700;
cursor: pointer;
}
.classification-hierarchy {
margin: 12px 0 0;
}
.classification-hierarchy__row {
display: grid;
grid-template-columns: 90px minmax(0, 1fr);
gap: 10px;
padding: 6px 0;
border-top: 1px solid rgba(0, 0, 0, 0.06);
}
.classification-hierarchy__row dt {
color: var(--sg-text-muted);
font-size: 11px;
}
.classification-hierarchy__row dd {
margin: 0;
color: var(--sg-text);
font-size: 12px;
text-align: left;
}
@media (max-width: 1150px) {
.hero,
.content-grid {
grid-template-columns: 1fr;
}
.metrics {
width: 100%;
}
}
@media (max-width: 700px) {
.detail-page {
padding: 18px 16px 40px;
}
.hero,
.card {
padding: 22px 20px;
}
.metrics {
grid-template-columns: 1fr;
}
.metrics div + div {
border-top: 1px solid var(--sg-border);
border-left: 0;
}
}
@@ -0,0 +1,139 @@
import { Location } from '@angular/common';
import { Component, DestroyRef, OnInit, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { finalize } from 'rxjs';
import { PatentsService } from '../../api/api/patents.service';
import { PatentEntry } from '../../api/model/patentEntry';
import {
ClassificationCard,
ClassificationSystem,
formatPatentDate,
getClassificationCards,
getDescriptionPreview,
getPatentMetadataRows,
getPublicationStageLabel,
isLongDescription,
patentExternalLinks,
} from './patent-detail.utils';
@Component({
selector: 'app-patent-detail',
imports: [
MatButtonModule,
MatIconModule,
MatProgressSpinnerModule,
RouterLink,
],
templateUrl: './patent-detail.component.html',
styleUrl: './patent-detail.component.scss',
})
export class PatentDetailComponent implements OnInit {
private readonly destroyRef = inject(DestroyRef);
private readonly route = inject(ActivatedRoute);
private readonly patentsService = inject(PatentsService);
private readonly location = inject(Location);
patent: PatentEntry | null = null;
loading = true;
notFound = false;
private expandedClassificationKeys = new Set<string>();
ngOnInit(): void {
this.route.paramMap
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((params) => {
const patentId = params.get('patentId');
if (!patentId) {
this.loading = false;
this.notFound = true;
return;
}
const title =
this.route.snapshot.queryParamMap.get('title') ?? undefined;
const prefix =
this.route.snapshot.queryParamMap.get('prefix') ?? undefined;
const fillingDate =
this.route.snapshot.queryParamMap.get('fillingDate') ?? undefined;
this.loadPatent(patentId, title, prefix, fillingDate);
});
}
navigateBack(): void {
this.location.back();
}
formatDate(date: string | null | undefined): string {
return formatPatentDate(date);
}
metadataRows() {
return this.patent ? getPatentMetadataRows(this.patent) : [];
}
stageLabel(): string | null {
return this.patent ? getPublicationStageLabel(this.patent) : null;
}
externalLinks() {
return this.patent ? patentExternalLinks(this.patent) : [];
}
classificationCards(
entries: PatentEntry['ipc_descriptions'],
system: ClassificationSystem,
): ClassificationCard[] {
return getClassificationCards(entries, system);
}
toggleClassificationExpanded(key: string): void {
if (this.expandedClassificationKeys.has(key)) {
this.expandedClassificationKeys.delete(key);
return;
}
this.expandedClassificationKeys.add(key);
}
isClassificationExpanded(key: string): boolean {
return this.expandedClassificationKeys.has(key);
}
isLongDescription(text: string | null): boolean {
return isLongDescription(text);
}
getDescriptionPreview(text: string | null): string {
return getDescriptionPreview(text);
}
private loadPatent(
patentId: string,
title?: string,
prefix?: string,
fillingDate?: string,
): void {
this.loading = true;
this.notFound = false;
this.patent = null;
this.expandedClassificationKeys.clear();
this.patentsService
.getPatentById(patentId, title, prefix, fillingDate)
.pipe(finalize(() => (this.loading = false)))
.subscribe({
next: (patent) => {
this.patent = patent;
},
error: () => {
this.notFound = true;
},
});
}
}
@@ -0,0 +1,205 @@
import { IpcClassification, PatentEntry } from '../../api/model/patentEntry';
export type ClassificationSystem = 'IPC' | 'CPC';
export interface ClassificationCard {
key: string;
symbols: string[];
system: ClassificationSystem;
levelLabel: string;
primaryDescription: string | null;
hierarchy: { label: string; value: string }[];
}
export interface PatentMetadataRow {
label: string;
value: string;
variant?: 'source';
}
const DESCRIPTION_PREVIEW_LENGTH = 140;
export function formatPatentDate(date: string | null | undefined): string {
if (!date) return '-';
const normalized = date.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
const parsed = new Date(normalized);
if (isNaN(parsed.getTime())) return date;
return new Intl.DateTimeFormat('de-DE').format(parsed);
}
export function formatMetadataLabel(value: string): string {
return value
.replace(/_/g, ' ')
.toLowerCase()
.replace(/\b\w/g, (char) => char.toUpperCase());
}
export function getPublicationStageLabel(patent: PatentEntry): string | null {
return patent.kind ?? patent.application_type ?? null;
}
export function getPatentMetadataRows(patent: PatentEntry): PatentMetadataRow[] {
const rows: PatentMetadataRow[] = [
{ label: 'Quelle', value: patent.source, variant: 'source' },
{ label: 'Patent-Nr.', value: patent.patent_id },
];
if (patent.publication_date) {
rows.push({
label: 'Veröffentlichungsdatum',
value: formatPatentDate(patent.publication_date),
});
}
if (patent.application_number) {
rows.push({ label: 'Anmeldungsnummer', value: patent.application_number });
}
if (patent.application_date) {
rows.push({
label: 'Anmeldedatum',
value: formatPatentDate(patent.application_date),
});
}
const stageLabel = getPublicationStageLabel(patent);
if (stageLabel) {
rows.push({
label: patent.kind ? 'Publikationsstufe' : 'Anmeldungstyp',
value: patent.kind ? stageLabel : formatMetadataLabel(stageLabel),
});
}
if (patent.number_of_claims != null) {
rows.push({ label: 'Ansprüche', value: String(patent.number_of_claims) });
}
if (patent.status) {
rows.push({ label: 'Status', value: formatMetadataLabel(patent.status) });
}
return rows;
}
export function getClassificationCards(
entries: IpcClassification[] | undefined,
system: ClassificationSystem,
): ClassificationCard[] {
if (!entries?.length) return [];
const merged = new Map<string, ClassificationCard>();
for (const entry of entries) {
const card = buildClassificationCard(entry, system);
const mergeKey =
card.primaryDescription?.toLocaleLowerCase('en') ??
card.symbols[0] ??
card.key;
const existing = merged.get(mergeKey);
if (existing) {
for (const symbol of card.symbols) {
if (!existing.symbols.includes(symbol)) {
existing.symbols.push(symbol);
}
}
continue;
}
merged.set(mergeKey, card);
}
return [...merged.values()];
}
export function isLongDescription(text: string | null): boolean {
return !!text && text.length > DESCRIPTION_PREVIEW_LENGTH;
}
export function getDescriptionPreview(text: string | null): string {
if (!text) return '';
if (text.length <= DESCRIPTION_PREVIEW_LENGTH) return text;
return `${text.slice(0, DESCRIPTION_PREVIEW_LENGTH).trimEnd()}…`;
}
export function patentExternalLinks(patent: PatentEntry): { label: string; url: string }[] {
const links: { label: string; url: string }[] = [];
const encodedId = encodeURIComponent(patent.patent_id);
if (patent.source === 'EPO') {
links.push({
label: 'Espacenet',
url: `https://worldwide.espacenet.com/patent/search?q=pn%3D${encodedId}`,
});
}
if (patent.source === 'USPTO') {
links.push({
label: 'Google Patents',
url: `https://patents.google.com/patent/${encodedId}`,
});
}
return links;
}
function buildClassificationCard(
entry: IpcClassification,
system: ClassificationSystem,
): ClassificationCard {
const level = getClassificationLevel(entry);
const primaryDescription = extractDescriptionText(entry[level.field]);
return {
key: `${system}-${entry.symbol}`,
symbols: [entry.symbol],
system,
levelLabel: level.label,
primaryDescription,
hierarchy: buildHierarchyRows(entry, primaryDescription),
};
}
function getClassificationLevel(entry: IpcClassification): {
label: string;
field: keyof IpcClassification;
} {
if (entry.subgroup) return { label: 'Untergruppe', field: 'subgroup' };
if (entry.main_group) return { label: 'Hauptgruppe', field: 'main_group' };
if (entry.subclass) return { label: 'Unterklasse', field: 'subclass' };
if (entry.section) return { label: 'Sektion', field: 'section' };
return { label: 'Code', field: 'symbol' };
}
function buildHierarchyRows(
entry: IpcClassification,
primaryDescription: string | null,
): { label: string; value: string }[] {
const rows: { label: string; value: string }[] = [];
const seen = new Set<string>();
const addRow = (label: string, raw: string | null) => {
const value = extractDescriptionText(raw);
if (!value) return;
const normalized = value.toLocaleLowerCase('en');
if (seen.has(normalized) || normalized === primaryDescription?.toLocaleLowerCase('en')) {
return;
}
seen.add(normalized);
rows.push({ label, value });
};
addRow('Sektion', entry.section);
addRow('Klasse', entry.class);
addRow('Unterklasse', entry.subclass);
return rows;
}
function extractDescriptionText(value: string | null | undefined): string | null {
if (!value?.trim()) return null;
const text = value.includes(' - ')
? value.split(' - ').slice(1).join(' - ').trim()
: value.trim();
if (!text) return null;
const firstSentence = text.split(/[;|]/)[0]?.trim() ?? text;
if (firstSentence !== firstSentence.toUpperCase()) return firstSentence;
return firstSentence.charAt(0) + firstSentence.slice(1).toLowerCase();
}
@@ -26,13 +26,52 @@
<mat-chip-option value="USPTO">USPTO</mat-chip-option>
</mat-chip-listbox>
<div class="sorting">
<select
(change)="setSortDirection($any($event.target).value)"
[value]="sortDirection">
<option value="desc">Absteigend</option>
<option value="asc">Aufsteigend</option>
</select>
<div class="year-filter">
<div class="year-filter-top">
<span class="year-filter-label">Zeitraum</span>
<button
type="button"
class="reset-range-button"
[disabled]="!canResetYearRange"
(click)="resetYearRange()">
Zurücksetzen
</button>
</div>
<div class="year-filter-values">
<span>{{ selectedStartYear }}</span>
<span>bis</span>
<span>{{ selectedEndYear }}</span>
</div>
<div
class="year-range-slider"
[style.--range-start]="rangeStartPercent"
[style.--range-end]="rangeEndPercent">
<div class="range-track"></div>
<input
class="range-input range-input-start"
type="range"
[min]="minYear"
[max]="maxYear"
[value]="selectedStartYear"
[style.z-index]="selectedStartYear >= selectedEndYear - 5 ? 4 : 2"
(input)="onStartYearInput($event)"
aria-label="Startjahr" />
<input
class="range-input range-input-end"
type="range"
[min]="minYear"
[max]="maxYear"
[value]="selectedEndYear"
(input)="onEndYearInput($event)"
aria-label="Endjahr" />
</div>
<div class="year-filter-bounds">
<span>{{ minYear }}</span>
<span>{{ maxYear }}</span>
</div>
</div>
</div>
</div>
@@ -46,172 +85,31 @@
</div>
} @else if (error) {
<p class="state-message error">Fehler beim Laden der Patente.</p>
} @else if (showDetail && selectedPatent) {
<div class="detail-view">
<button type="button" class="back-btn" (click)="closeDetail()">
← Zurück zu den Patenten
</button>
<h2>{{ selectedPatent.title ?? selectedPatent.patent_id }}</h2>
<div class="patent-meta__list">
@for (row of getPatentMetadataRows(selectedPatent); track row.label) {
<div class="patent-meta__row">
<dt>{{ row.label }}</dt>
<dd>
@if (row.variant === 'source') {
<span class="source-badge source-badge--{{ row.value.toLowerCase() }}">{{ row.value }}</span>
} @else {
{{ row.value }}
}
</dd>
</div>
}
</div>
@if (selectedPatent.abstract) {
<div class="detail-section">
<h4>Abstract</h4>
<p>{{ selectedPatent.abstract }}</p>
</div>
}
<div class="detail-section">
<h4>Erfinder</h4>
<ul class="tag-list">
@for (inv of selectedPatent.inventors; track inv) {
<li class="tag">{{ inv }}</li>
}
</ul>
</div>
@if (selectedPatent.assignees.length > 0) {
<div class="detail-section">
<h4>Anmelder</h4>
<ul class="tag-list">
@for (a of selectedPatent.assignees; track a) {
<li class="tag">{{ a }}</li>
}
</ul>
</div>
}
@if (selectedPatent.ipc_descriptions.length > 0) {
<div class="detail-section classification-section classification-section--ipc">
<h4>Klassifikation (IPC)</h4>
<div class="classification-cards">
@for (card of getClassificationCards(selectedPatent.ipc_descriptions, 'IPC'); track card.key) {
<article class="classification-card">
<header class="classification-card__header">
<div class="classification-card__codes">
@for (sym of card.symbols; track sym) {
<span class="classification-code">{{ sym }}</span>
}
</div>
<div class="classification-card__badges">
<span class="classification-badge classification-badge--system">{{ card.system }}</span>
<span class="classification-badge classification-badge--level">{{ card.levelLabel }}</span>
</div>
</header>
@if (card.primaryDescription) {
<p class="classification-summary">
{{ isClassificationExpanded(card.key) ? card.primaryDescription : getDescriptionPreview(card.primaryDescription) }}
</p>
@if (isLongDescription(card.primaryDescription)) {
<button type="button" class="classification-toggle" (click)="toggleClassificationExpanded(card.key)">
{{ isClassificationExpanded(card.key) ? 'Weniger anzeigen' : 'Mehr anzeigen' }}
</button>
}
}
@if (card.hierarchy.length > 0) {
<dl class="classification-hierarchy">
@for (row of card.hierarchy; track row.label) {
<div class="classification-hierarchy__row">
<dt>{{ row.label }}</dt>
<dd>{{ row.value }}</dd>
</div>
}
</dl>
}
</article>
}
</div>
</div>
} @else if (selectedPatent.ipc.length > 0) {
<div class="detail-section">
<h4>Klassifikation (IPC)</h4>
<ul class="tag-list tag-list--compact">
@for (ipc of selectedPatent.ipc; track ipc) {
<li class="tag">{{ ipc }}</li>
}
</ul>
</div>
}
@if (selectedPatent.cpc_descriptions.length > 0) {
<div class="detail-section classification-section classification-section--cpc">
<h4>Klassifikation (CPC)</h4>
<div class="classification-cards">
@for (card of getClassificationCards(selectedPatent.cpc_descriptions, 'CPC'); track card.key) {
<article class="classification-card">
<header class="classification-card__header">
<div class="classification-card__codes">
@for (sym of card.symbols; track sym) {
<span class="classification-code">{{ sym }}</span>
}
</div>
<div class="classification-card__badges">
<span class="classification-badge classification-badge--system">{{ card.system }}</span>
<span class="classification-badge classification-badge--level">{{ card.levelLabel }}</span>
</div>
</header>
@if (card.primaryDescription) {
<p class="classification-summary">
{{ isClassificationExpanded(card.key) ? card.primaryDescription : getDescriptionPreview(card.primaryDescription) }}
</p>
@if (isLongDescription(card.primaryDescription)) {
<button type="button" class="classification-toggle" (click)="toggleClassificationExpanded(card.key)">
{{ isClassificationExpanded(card.key) ? 'Weniger anzeigen' : 'Mehr anzeigen' }}
</button>
}
}
@if (card.hierarchy.length > 0) {
<dl class="classification-hierarchy">
@for (row of card.hierarchy; track row.label) {
<div class="classification-hierarchy__row">
<dt>{{ row.label }}</dt>
<dd>{{ row.value }}</dd>
</div>
}
</dl>
}
</article>
}
</div>
</div>
} @else if (selectedPatent.cpc.length > 0) {
<div class="detail-section">
<h4>Klassifikation (CPC)</h4>
<ul class="tag-list tag-list--compact">
@for (cpc of selectedPatent.cpc; track cpc) {
<li class="tag">{{ cpc }}</li>
}
</ul>
</div>
}
</div>
} @else if (patents.length === 0) {
<div class="no-results">
<p>Keine Patente gefunden.</p>
</div>
} @else {
<div class="cards">
@for (patent of patents; track patent.patent_id + (patent.publication_date ?? '')) {
<mat-card class="card" appearance="outlined" (click)="selectPatent(patent)">
@for (
patent of patents;
track patent.patent_id + (patent.publication_date ?? '')
) {
<mat-card
class="card"
appearance="outlined"
(click)="openPatent(patent)">
<mat-card-header>
<mat-card-title>{{ patent.title ?? patent.patent_id }}</mat-card-title>
<mat-card-title>{{
patent.title ?? patent.patent_id
}}</mat-card-title>
<mat-card-subtitle>
<span class="source-badge source-badge--{{ patent.source.toLowerCase() }}">{{ patent.source }}</span>
<span
class="source-badge source-badge--{{
patent.source.toLowerCase()
}}"
>{{ patent.source }}</span
>
</mat-card-subtitle>
</mat-card-header>
<mat-card-content class="card-content">
@@ -224,7 +122,9 @@
</mat-card-content>
<mat-card-footer>
<mat-card-actions>
<button mat-button (click)="selectPatent(patent); $event.stopPropagation()">
<button
mat-button
(click)="openPatent(patent); $event.stopPropagation()">
<mat-icon>info</mat-icon>
Übersicht
</button>
@@ -237,12 +137,10 @@
<mat-divider />
@if (!showDetail) {
<mat-paginator
<mat-paginator
[length]="total"
[pageSize]="pageSize"
[pageIndex]="page"
[pageSizeOptions]="[10, 25, 50]"
(page)="handlePageChange($event)" />
}
</div>
@@ -12,20 +12,6 @@ h1 {
padding: 1rem 0 0;
}
.sorting {
display: flex;
justify-content: flex-end;
gap: 0.5rem;
select {
padding: 0.75rem;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
font-size: 1rem;
cursor: pointer;
}
}
.search-and-filter {
padding: 0 1rem;
display: flex;
@@ -37,8 +23,140 @@ h1 {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 1rem;
}
.year-filter {
width: min(285px, 100%);
padding: 8px 10px;
border: 1px solid #dbe5f6;
border-radius: 10px;
background: #fbfdff;
box-sizing: border-box;
}
.year-filter-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 4px;
}
.year-filter-label {
color: #07163d;
font-size: 12px;
font-weight: 700;
}
.reset-range-button {
border: 0;
background: transparent;
color: #0057ff;
font-size: 11px;
cursor: pointer;
padding: 0;
font-family: inherit;
&:disabled {
color: #9aa5bc;
cursor: default;
}
}
.year-filter-values {
display: flex;
align-items: center;
justify-content: center;
gap: 7px;
margin-bottom: 5px;
color: #40506f;
font-size: 12px;
font-weight: 600;
}
.year-filter-bounds {
display: flex;
justify-content: space-between;
margin-top: 1px;
color: #7c88a3;
font-size: 10px;
}
.year-range-slider {
--range-start: 0%;
--range-end: 100%;
--accent: #0057ff;
position: relative;
height: 22px;
}
.range-track {
position: absolute;
top: 50%;
left: 0;
right: 0;
height: 5px;
transform: translateY(-50%);
border-radius: 999px;
background: linear-gradient(
to right,
#d8e2f4 0%,
#d8e2f4 var(--range-start),
var(--accent) var(--range-start),
var(--accent) var(--range-end),
#d8e2f4 var(--range-end),
#d8e2f4 100%
);
}
.range-input {
position: absolute;
inset: 0;
width: 100%;
height: 22px;
margin: 0;
appearance: none;
background: transparent;
pointer-events: none;
&::-webkit-slider-runnable-track,
&::-moz-range-track {
height: 5px;
background: transparent;
border: none;
}
&::-webkit-slider-thumb {
appearance: none;
width: 15px;
height: 15px;
margin-top: -5px;
border: 2px solid #ffffff;
border-radius: 50%;
background: #0057ff;
box-shadow: 0 0 0 1px #9ab7ff, 0 2px 6px rgba(0, 87, 255, 0.22);
cursor: pointer;
pointer-events: auto;
}
&::-moz-range-thumb {
width: 15px;
height: 15px;
border: 2px solid #ffffff;
border-radius: 50%;
background: #0057ff;
box-shadow: 0 0 0 1px #9ab7ff, 0 2px 6px rgba(0, 87, 255, 0.22);
cursor: pointer;
pointer-events: auto;
}
}
.range-input-start { z-index: 2; }
.range-input-end { z-index: 3; }
.state-message {
display: flex;
align-items: center;
@@ -58,15 +176,11 @@ h1 {
}
@media (max-width: 900px) {
.cards {
grid-template-columns: repeat(2, 1fr);
}
.cards { grid-template-columns: repeat(2, 1fr); }
}
@media (max-width: 600px) {
.cards {
grid-template-columns: 1fr;
}
.cards { grid-template-columns: 1fr; }
}
mat-paginator {
@@ -13,21 +13,11 @@ import { MatDividerModule } from '@angular/material/divider';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { debounceTime, distinctUntilChanged, Subject } from 'rxjs';
import { PatentsService } from '../../api/api/patents.service';
import { PatentEntry, IpcClassification } from '../../api/model/patentEntry';
import { PatentEntry } from '../../api/model/patentEntry';
type SourceFilter = 'all' | 'EPO' | 'USPTO';
type ClassificationSystem = 'IPC' | 'CPC';
interface ClassificationCard {
key: string;
symbols: string[];
system: ClassificationSystem;
levelLabel: string;
primaryDescription: string | null;
hierarchy: { label: string; value: string }[];
}
const DESCRIPTION_PREVIEW_LENGTH = 140;
const MIN_YEAR = 1978;
@Component({
selector: 'app-patents',
@@ -62,11 +52,13 @@ export class PatentsComponent implements OnInit {
searchTerm = '';
activeFilter: SourceFilter = 'all';
sortDirection: string = 'desc';
sortDirection: string = 'asc';
selectedPatent: PatentEntry | null = null;
showDetail = false;
private expandedClassificationKeys = new Set<string>();
// Jahr-Slider
readonly minYear = MIN_YEAR;
readonly maxYear = new Date().getFullYear();
selectedStartYear = MIN_YEAR;
selectedEndYear = new Date().getFullYear();
private searchSubject = new Subject<string>();
@@ -76,8 +68,6 @@ export class PatentsComponent implements OnInit {
.subscribe((term) => {
this.searchTerm = term;
this.page = 0;
this.selectedPatent = null;
this.showDetail = false;
this.loadPatents();
this.updateQueryParams();
});
@@ -92,17 +82,68 @@ export class PatentsComponent implements OnInit {
if (f === 'EPO' || f === 'USPTO') this.activeFilter = f;
const d = qp.get('sort_direction');
if (d === 'asc' || d === 'desc') this.sortDirection = d;
const sy = parseInt(qp.get('year_from') ?? '', 10);
const ey = parseInt(qp.get('year_to') ?? '', 10);
if (!isNaN(sy)) this.selectedStartYear = sy;
if (!isNaN(ey)) this.selectedEndYear = ey;
this.loadPatents();
}
get rangeStartPercent(): string {
const total = this.maxYear - this.minYear;
return `${((this.selectedStartYear - this.minYear) / total) * 100}%`;
}
get rangeEndPercent(): string {
const total = this.maxYear - this.minYear;
return `${((this.selectedEndYear - this.minYear) / total) * 100}%`;
}
get canResetYearRange(): boolean {
return this.selectedStartYear !== this.minYear || this.selectedEndYear !== this.maxYear;
}
onStartYearInput(event: Event): void {
const val = parseInt((event.target as HTMLInputElement).value, 10);
this.selectedStartYear = Math.min(val, this.selectedEndYear);
this.page = 0;
this.loadPatents();
this.updateQueryParams();
}
onEndYearInput(event: Event): void {
const val = parseInt((event.target as HTMLInputElement).value, 10);
this.selectedEndYear = Math.max(val, this.selectedStartYear);
this.page = 0;
this.loadPatents();
this.updateQueryParams();
}
resetYearRange(): void {
this.selectedStartYear = this.minYear;
this.selectedEndYear = this.maxYear;
this.page = 0;
this.loadPatents();
this.updateQueryParams();
}
private loadPatents(): void {
this.loading = true;
this.error = false;
const source = this.activeFilter === 'all' ? undefined : this.activeFilter;
this.patentsApi
.getAllPatents(this.page, this.pageSize, this.searchTerm || undefined, source, 'date', this.sortDirection)
.getAllPatents(
this.page,
this.pageSize,
this.searchTerm || undefined,
source,
'date',
this.sortDirection,
this.selectedStartYear,
this.selectedEndYear,
)
.subscribe({
next: (res) => {
this.patents = res.patents;
@@ -123,8 +164,6 @@ export class PatentsComponent implements OnInit {
clearSearch(): void {
this.searchTerm = '';
this.page = 0;
this.selectedPatent = null;
this.showDetail = false;
this.loadPatents();
this.updateQueryParams();
}
@@ -133,8 +172,6 @@ export class PatentsComponent implements OnInit {
const val = event.value;
this.activeFilter = val === 'EPO' || val === 'USPTO' ? val : 'all';
this.page = 0;
this.selectedPatent = null;
this.showDetail = false;
this.loadPatents();
this.updateQueryParams();
}
@@ -148,22 +185,12 @@ export class PatentsComponent implements OnInit {
handlePageChange(event: PageEvent): void {
this.page = event.pageIndex;
this.pageSize = event.pageSize;
this.selectedPatent = null;
this.showDetail = false;
this.loadPatents();
this.updateQueryParams();
}
selectPatent(patent: PatentEntry): void {
this.selectedPatent = patent;
this.showDetail = true;
this.expandedClassificationKeys.clear();
}
closeDetail(): void {
this.showDetail = false;
this.selectedPatent = null;
this.expandedClassificationKeys.clear();
openPatent(patent: PatentEntry): void {
this.router.navigate(['/patent', patent.patent_id]);
}
private updateQueryParams(): void {
@@ -175,6 +202,8 @@ export class PatentsComponent implements OnInit {
size: this.pageSize,
source: this.activeFilter === 'all' ? null : this.activeFilter,
sort_direction: this.sortDirection,
year_from: this.selectedStartYear !== this.minYear ? this.selectedStartYear : null,
year_to: this.selectedEndYear !== this.maxYear ? this.selectedEndYear : null,
},
queryParamsHandling: 'merge',
replaceUrl: true,
@@ -188,120 +217,4 @@ export class PatentsComponent implements OnInit {
if (isNaN(parsed.getTime())) return date;
return new Intl.DateTimeFormat('de-DE').format(parsed);
}
getPublicationStageLabel(patent: PatentEntry): string | null {
return patent.kind ?? patent.application_type ?? null;
}
getPatentMetadataRows(patent: PatentEntry) {
const rows: { label: string; value: string; variant?: 'source' }[] = [];
rows.push({ label: 'Quelle', value: patent.source, variant: 'source' });
rows.push({ label: 'Patent-Nr.', value: patent.patent_id });
if (patent.publication_date)
rows.push({ label: 'Veröffentlichungsdatum', value: this.formatDate(patent.publication_date) });
if (patent.application_number)
rows.push({ label: 'Anmeldungsnummer', value: patent.application_number });
if (patent.application_date)
rows.push({ label: 'Anmeldedatum', value: this.formatDate(patent.application_date) });
const stage = this.getPublicationStageLabel(patent);
if (stage)
rows.push({ label: patent.kind ? 'Publikationsstufe' : 'Anmeldungstyp', value: this.formatMetadataLabel(stage) });
if (patent.number_of_claims != null)
rows.push({ label: 'Ansprüche', value: String(patent.number_of_claims) });
if (patent.status)
rows.push({ label: 'Status', value: this.formatMetadataLabel(patent.status) });
return rows;
}
private formatMetadataLabel(value: string): string {
return value.replace(/_/g, ' ').toLowerCase().replace(/\b\w/g, (c) => c.toUpperCase());
}
getClassificationCards(
entries: IpcClassification[] | undefined,
system: ClassificationSystem,
): ClassificationCard[] {
if (!entries?.length) return [];
const merged = new Map<string, ClassificationCard>();
for (const entry of entries) {
const card = this.buildClassificationCard(entry, system);
const mergeKey = card.primaryDescription?.toLocaleLowerCase('en') ?? card.symbols[0] ?? card.key;
const existing = merged.get(mergeKey);
if (existing) {
for (const s of card.symbols) {
if (!existing.symbols.includes(s)) existing.symbols.push(s);
}
continue;
}
merged.set(mergeKey, card);
}
return [...merged.values()];
}
toggleClassificationExpanded(key: string): void {
this.expandedClassificationKeys.has(key)
? this.expandedClassificationKeys.delete(key)
: this.expandedClassificationKeys.add(key);
}
isClassificationExpanded(key: string): boolean {
return this.expandedClassificationKeys.has(key);
}
isLongDescription(text: string | null): boolean {
return !!text && text.length > DESCRIPTION_PREVIEW_LENGTH;
}
getDescriptionPreview(text: string | null): string {
if (!text) return '';
return text.length <= DESCRIPTION_PREVIEW_LENGTH
? text
: `${text.slice(0, DESCRIPTION_PREVIEW_LENGTH).trimEnd()}…`;
}
private buildClassificationCard(entry: IpcClassification, system: ClassificationSystem): ClassificationCard {
const level = this.getClassificationLevel(entry);
const primaryDescription = this.extractDescriptionText(entry[level.field]);
return {
key: `${system}-${entry.symbol}`,
symbols: [entry.symbol],
system,
levelLabel: level.label,
primaryDescription,
hierarchy: this.buildHierarchyRows(entry, primaryDescription),
};
}
private getClassificationLevel(entry: IpcClassification): { label: string; field: keyof IpcClassification } {
if (entry.subgroup) return { label: 'Untergruppe', field: 'subgroup' };
if (entry.main_group) return { label: 'Hauptgruppe', field: 'main_group' };
if (entry.subclass) return { label: 'Unterklasse', field: 'subclass' };
if (entry.section) return { label: 'Sektion', field: 'section' };
return { label: 'Code', field: 'symbol' };
}
private buildHierarchyRows(entry: IpcClassification, primaryDescription: string | null) {
const rows: { label: string; value: string }[] = [];
const seen = new Set<string>();
const addRow = (label: string, raw: string | null) => {
const value = this.extractDescriptionText(raw);
if (!value) return;
const norm = value.toLocaleLowerCase('en');
if (seen.has(norm) || norm === primaryDescription?.toLocaleLowerCase('en')) return;
seen.add(norm);
rows.push({ label, value });
};
addRow('Sektion', entry.section);
addRow('Klasse', entry.class);
addRow('Unterklasse', entry.subclass);
return rows;
}
private extractDescriptionText(value: string | null | undefined): string | null {
if (!value?.trim()) return null;
const text = value.includes(' - ') ? value.split(' - ').slice(1).join(' - ').trim() : value.trim();
if (!text) return null;
const first = text.split(/[;|]/)[0]?.trim() ?? text;
return first === first.toUpperCase() ? first.charAt(0) + first.slice(1).toLowerCase() : first;
}
}

Some files were not shown because too many files have changed in this diff Show More